book.tex 605 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251
  1. %\documentclass[]{TimesAPriori_MIT}%%6x9
  2. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  3. %\documentclass[8x10]{TimesAPriori_MIT}%%8x10
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  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. \def\racketEd{0}
  21. \def\pythonEd{1}
  22. \def\edition{1}
  23. % material that is specific to the Racket edition of the book
  24. \newcommand{\racket}[1]{{\if\edition\racketEd\color{olive}{#1}\fi}}
  25. % would like a command for: \if\edition\racketEd\color{olive}
  26. % and : \fi\color{black}
  27. % material that is specific to the Python edition of the book
  28. \newcommand{\python}[1]{{\if\edition\pythonEd\color{purple}{#1}\fi}}
  29. %% For multiple indices:
  30. \usepackage{multind}
  31. \makeindex{subject}
  32. \makeindex{authors}
  33. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  34. \if\edition\racketEd
  35. \lstset{%
  36. language=Lisp,
  37. basicstyle=\ttfamily\small,
  38. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  39. deletekeywords={read,mapping,vector},
  40. escapechar=|,
  41. columns=flexible,
  42. moredelim=[is][\color{red}]{~}{~},
  43. showstringspaces=false
  44. }
  45. \fi
  46. \if\edition\pythonEd
  47. \lstset{%
  48. language=Python,
  49. basicstyle=\ttfamily\small,
  50. morekeywords={match,case,bool,int},
  51. deletekeywords={},
  52. escapechar=|,
  53. columns=flexible,
  54. moredelim=[is][\color{red}]{~}{~},
  55. showstringspaces=false
  56. }
  57. \fi
  58. %%% Any shortcut own defined macros place here
  59. %% sample of author macro:
  60. \input{defs}
  61. \newtheorem{exercise}[theorem]{Exercise}
  62. % Adjusted settings
  63. \setlength{\columnsep}{4pt}
  64. %% \begingroup
  65. %% \setlength{\intextsep}{0pt}%
  66. %% \setlength{\columnsep}{0pt}%
  67. %% \begin{wrapfigure}{r}{0.5\textwidth}
  68. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  69. %% \caption{Basic layout}
  70. %% \end{wrapfigure}
  71. %% \lipsum[1]
  72. %% \endgroup
  73. \newbox\oiintbox
  74. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  75. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  76. \def\oiint{\copy\oiintbox}
  77. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  78. %\usepackage{showframe}
  79. \def\ShowFrameLinethickness{0.125pt}
  80. \addbibresource{book.bib}
  81. \begin{document}
  82. \frontmatter
  83. \HalfTitle{Essentials of Compilation}
  84. \halftitlepage
  85. %% \begin{seriespage}
  86. %% \seriestitle{Industrial Economics}
  87. %% \serieseditor{Miriam Smith and Simon Rattle, editors}
  88. %% \title{Engineering and Economics}
  89. %% \author{Samuel Endgrove}
  90. %% \title{Structural Economics: From Beginning to End}
  91. %% \author{Guang Xi}
  92. %% \end{seriespage}
  93. \Title{Essentials of Compilation}
  94. \Booksubtitle{The Incremental, Nano-Pass Approach}
  95. \edition{First Edition}
  96. \BookAuthor{Jeremy G. Siek}
  97. \imprint{The MIT Press\\
  98. Cambridge, Massachusetts\\
  99. London, England}
  100. \begin{copyrightpage}
  101. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  102. or personal downloading under the
  103. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  104. license.
  105. Copyright in this monograph has been licensed exclusively to The MIT
  106. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  107. version to the public in 2022. All inquiries regarding rights should
  108. be addressed to The MIT Press, Rights and Permissions Department.
  109. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  110. %% All rights reserved. No part of this book may be reproduced in any
  111. %% form by any electronic or mechanical means (including photocopying,
  112. %% recording, or information storage and retrieval) without permission in
  113. %% writing from the publisher.
  114. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  115. %% United States of America.
  116. %% Library of Congress Cataloging-in-Publication Data is available.
  117. %% ISBN:
  118. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  119. \end{copyrightpage}
  120. \dedication{This book is dedicated to the programming language wonks
  121. at Indiana University.}
  122. %% \begin{epigraphpage}
  123. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  124. %% \textit{Book Name if any}}
  125. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  126. %% \end{epigraphpage}
  127. \tableofcontents
  128. \listoffigures
  129. \listoftables
  130. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  131. \chapter*{Preface}
  132. \addcontentsline{toc}{fmbm}{Preface}
  133. There is a magical moment when a programmer presses the ``run'' button
  134. and the software begins to execute. Somehow a program written in a
  135. high-level language is running on a computer that is only capable of
  136. shuffling bits. Here we reveal the wizardry that makes that moment
  137. possible. Beginning with the groundbreaking work of Backus and
  138. colleagues in the 1950s, computer scientists discovered techniques for
  139. constructing programs, called \emph{compilers}, that automatically
  140. translate high-level programs into machine code.
  141. We take you on a journey by constructing your own compiler for a small
  142. but powerful language. Along the way we explain the essential
  143. concepts, algorithms, and data structures that underlie compilers. We
  144. develop your understanding of how programs are mapped onto computer
  145. hardware, which is helpful when reasoning about properties at the
  146. junction between hardware and software such as execution time,
  147. software errors, and security vulnerabilities. For those interested
  148. in pursuing compiler construction, our goal is to provide a
  149. stepping-stone to advanced topics such as just-in-time compilation,
  150. program analysis, and program optimization. For those interested in
  151. designing and implementing programming languages, we connect
  152. language design choices to their impact on the compiler and the generated
  153. code.
  154. A compiler is typically organized as a sequence of stages that
  155. progressively translates a program to code that runs on hardware. We
  156. take this approach to the extreme by partitioning our compiler into a
  157. large number of \emph{nanopasses}, each of which performs a single
  158. task. This allows us to test the output of each pass in isolation, and
  159. furthermore, allows us to focus our attention making the compiler far
  160. easier to understand.
  161. %% [TODO: easier to understand/debug for those maintaining the compiler,
  162. %% proving correctness]
  163. The most familiar approach to describing compilers is with one pass
  164. per chapter. The problem with that is it obfuscates how language
  165. features motivate design choices in a compiler. We take an
  166. \emph{incremental} approach in which we build a complete compiler in
  167. each chapter, starting with arithmetic and variables and add new
  168. features in subsequent chapters.
  169. Our choice of language features is designed to elicit the fundamental
  170. concepts and algorithms used in compilers.
  171. \begin{itemize}
  172. \item We begin with integer arithmetic and local variables in
  173. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  174. the fundamental tools of compiler construction: \emph{abstract
  175. syntax trees} and \emph{recursive functions}.
  176. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  177. \emph{graph coloring} to assign variables to machine registers.
  178. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  179. an elegant recursive algorithm for mapping expressions to
  180. \emph{control-flow graphs}.
  181. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  182. \emph{garbage collection}.
  183. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  184. but lack lexical scoping, similar to the C programming
  185. language~\citep{Kernighan:1988nx} except that we generate efficient
  186. tail calls. The reader learns about the procedure call stack,
  187. \emph{calling conventions}, and their interaction with register
  188. allocation and garbage collection.
  189. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  190. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  191. \emph{closure conversion}, in which lambdas are translated into a
  192. combination of functions and tuples.
  193. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  194. point the input languages are statically typed. The reader extends
  195. the statically typed language with an \code{Any} type which serves
  196. as a target for compiling the dynamically typed language.
  197. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  198. programming languages with the addition of loops and mutable
  199. variables. These additions elicit the need for \emph{dataflow
  200. analysis} in the register allocator.
  201. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  202. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  203. in which different regions of a program may be static or dynamically
  204. typed. The reader implements runtime support for \emph{proxies} that
  205. allow values to safely move between regions.
  206. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  207. leveraging the \code{Any} type and type casts developed in Chapters
  208. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  209. \end{itemize}
  210. There are many language features that we do not include. Our choices
  211. weigh the incidental complexity of a feature against the fundamental
  212. concepts that it exposes. For example, we include tuples and not
  213. records because they both elicit the study of heap allocation and
  214. garbage collection but records come with more incidental complexity.
  215. Since 2016 this book has served as the textbook for the compiler
  216. course at Indiana University, a 16-week course for upper-level
  217. undergraduates and first-year graduate students.
  218. %
  219. Prior to this course, students learn to program in both imperative and
  220. functional languages, study data structures and algorithms, and take
  221. discrete mathematics.
  222. %
  223. At the beginning of the course, students form groups of 2-4 people.
  224. The groups complete one chapter every two weeks, starting with
  225. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  226. chapters include a challenge problem that we assign to the graduate
  227. students. The last two weeks of the course involve a final project in
  228. which students design and implement a compiler extension of their
  229. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  230. \ref{ch:Rpoly} can be used in support of these projects or they can
  231. replace some of the earlier chapters. For example, a course with an
  232. emphasis on statically-typed imperative languages would skip
  233. Chapter~\ref{ch:Rdyn} in favor of
  234. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  235. the dependencies between chapters.
  236. This book has also been used in compiler courses at California
  237. Polytechnic State University, Portland State University, Rose–Hulman
  238. Institute of Technology, University of Massachusetts Lowell, and the
  239. University of Vermont.
  240. \begin{figure}[tp]
  241. \begin{tikzpicture}[baseline=(current bounding box.center)]
  242. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  243. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  244. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  245. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  246. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  247. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  248. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  249. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  250. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  251. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  252. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  253. \path[->] (C1) edge [above] node {} (C2);
  254. \path[->] (C2) edge [above] node {} (C3);
  255. \path[->] (C3) edge [above] node {} (C4);
  256. \path[->] (C4) edge [above] node {} (C5);
  257. \path[->] (C5) edge [above] node {} (C6);
  258. \path[->] (C6) edge [above] node {} (C7);
  259. \path[->] (C4) edge [above] node {} (C8);
  260. \path[->] (C4) edge [above] node {} (C9);
  261. \path[->] (C8) edge [above] node {} (C10);
  262. \path[->] (C10) edge [above] node {} (C11);
  263. \end{tikzpicture}
  264. \caption{Diagram of chapter dependencies.}
  265. \label{fig:chapter-dependences}
  266. \end{figure}
  267. \racket{
  268. We use the \href{https://racket-lang.org/}{Racket} language both for
  269. the implementation of the compiler and for the input language, so the
  270. reader should be proficient with Racket or Scheme. There are many
  271. excellent resources for learning Scheme and
  272. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  273. }
  274. \python{
  275. This edition of the book uses the \href{https://www.python.org/}{Python}
  276. both for the implementation of the compiler and for the input language, so the
  277. reader should be proficient with Python. There are many
  278. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  279. }
  280. The support code for this book is in the \code{github} repository at
  281. the following URL:
  282. \begin{center}\small
  283. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  284. \end{center}
  285. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  286. is helpful but not necessary for the reader to have taken a computer
  287. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  288. of x86-64 assembly language that are needed.
  289. %
  290. We follow the System V calling
  291. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  292. that we generate works with the runtime system (written in C) when it
  293. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  294. operating systems.
  295. %
  296. On the Windows operating system, \code{gcc} uses the Microsoft x64
  297. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  298. assembly code that we generate does \emph{not} work with the runtime
  299. system on Windows. One workaround is to use a virtual machine with
  300. Linux as the guest operating system.
  301. \section*{Acknowledgments}
  302. The tradition of compiler construction at Indiana University goes back
  303. to research and courses on programming languages by Daniel Friedman in
  304. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  305. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  306. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  307. the compiler course and continued the development of Chez Scheme.
  308. %
  309. The compiler course evolved to incorporate novel pedagogical ideas
  310. while also including elements of efficient real-world compilers. One
  311. of Friedman's ideas was to split the compiler into many small
  312. passes. Another idea, called ``the game'', was to test the code
  313. generated by each pass using interpreters.
  314. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  315. developed infrastructure to support this approach and evolved the
  316. course to use even smaller
  317. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  318. design decisions in this book are inspired by the assignment
  319. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  320. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  321. organization of the course made it difficult for students to
  322. understand the rationale for the compiler design. Ghuloum proposed the
  323. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  324. on.
  325. We thank the many students who served as teaching assistants for the
  326. compiler course at IU and made suggestions for improving the book
  327. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  328. thank Andre Kuhlenschmidt for his work on the garbage collector,
  329. Michael Vollmer for his work on efficient tail calls, and Michael
  330. Vitousek for his help running the first offering of the incremental
  331. compiler course at IU.
  332. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  333. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  334. for teaching courses based on drafts of this book and for their
  335. invaluable feedback.
  336. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  337. course in the early 2000's and especially for finding the bug that
  338. sent our garbage collector on a wild goose chase!
  339. \mbox{}\\
  340. \noindent Jeremy G. Siek \\
  341. Bloomington, Indiana
  342. \mainmatter
  343. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  344. \chapter{Preliminaries}
  345. \label{ch:trees-recur}
  346. In this chapter we review the basic tools that are needed to implement
  347. a compiler. Programs are typically input by a programmer as text,
  348. i.e., a sequence of characters. The program-as-text representation is
  349. called \emph{concrete syntax}. We use concrete syntax to concisely
  350. write down and talk about programs. Inside the compiler, we use
  351. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  352. that efficiently supports the operations that the compiler needs to
  353. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  354. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  355. from concrete syntax to abstract syntax is a process called
  356. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  357. implementation of parsing in this book.
  358. %
  359. \racket{A parser is provided in the support code for translating from
  360. concrete to abstract syntax.}
  361. %
  362. \python{We use Python's \code{ast} module to translate from concrete
  363. to abstract syntax.}
  364. ASTs can be represented in many different ways inside the compiler,
  365. depending on the programming language used to write the compiler.
  366. %
  367. \racket{We use Racket's
  368. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  369. feature to represent ASTs (Section~\ref{sec:ast}).}
  370. %
  371. \python{We use Python classes and objects to represent ASTs, especially the
  372. classes defined in the standard \code{ast} module for the Python
  373. source language.}
  374. %
  375. We use grammars to define the abstract syntax of programming languages
  376. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  377. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  378. recursive functions to construct and deconstruct ASTs
  379. (Section~\ref{sec:recursion}). This chapter provides an brief
  380. introduction to these ideas.
  381. \racket{\index{subject}{struct}}
  382. \python{\index{subject}{class}\index{subject}{object}}
  383. \section{Abstract Syntax Trees}
  384. \label{sec:ast}
  385. Compilers use abstract syntax trees to represent programs because they
  386. often need to ask questions like: for a given part of a program, what
  387. kind of language feature is it? What are its sub-parts? Consider the
  388. program on the left and its AST on the right. This program is an
  389. addition operation and it has two sub-parts, a read operation and a
  390. negation. The negation has another sub-part, the integer constant
  391. \code{8}. By using a tree to represent the program, we can easily
  392. follow the links to go from one part of a program to its sub-parts.
  393. \begin{center}
  394. \begin{minipage}{0.4\textwidth}
  395. \if\edition\racketEd
  396. \begin{lstlisting}
  397. (+ (read) (- 8))
  398. \end{lstlisting}
  399. \fi
  400. \if\edition\pythonEd
  401. \begin{lstlisting}
  402. input_int() + -8
  403. \end{lstlisting}
  404. \fi
  405. \end{minipage}
  406. \begin{minipage}{0.4\textwidth}
  407. \begin{equation}
  408. \begin{tikzpicture}
  409. \node[draw] (plus) at (0 , 0) {\key{+}};
  410. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  411. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  412. \node[draw] (8) at (1 , -3) {\key{8}};
  413. \draw[->] (plus) to (read);
  414. \draw[->] (plus) to (minus);
  415. \draw[->] (minus) to (8);
  416. \end{tikzpicture}
  417. \label{eq:arith-prog}
  418. \end{equation}
  419. \end{minipage}
  420. \end{center}
  421. We use the standard terminology for trees to describe ASTs: each
  422. rectangle above is called a \emph{node}. The arrows connect a node to its
  423. \emph{children} (which are also nodes). The top-most node is the
  424. \emph{root}. Every node except for the root has a \emph{parent} (the
  425. node it is the child of). If a node has no children, it is a
  426. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  427. \index{subject}{node}
  428. \index{subject}{children}
  429. \index{subject}{root}
  430. \index{subject}{parent}
  431. \index{subject}{leaf}
  432. \index{subject}{internal node}
  433. %% Recall that an \emph{symbolic expression} (S-expression) is either
  434. %% \begin{enumerate}
  435. %% \item an atom, or
  436. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  437. %% where $e_1$ and $e_2$ are each an S-expression.
  438. %% \end{enumerate}
  439. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  440. %% null value \code{'()}, etc. We can create an S-expression in Racket
  441. %% simply by writing a backquote (called a quasi-quote in Racket)
  442. %% followed by the textual representation of the S-expression. It is
  443. %% quite common to use S-expressions to represent a list, such as $a, b
  444. %% ,c$ in the following way:
  445. %% \begin{lstlisting}
  446. %% `(a . (b . (c . ())))
  447. %% \end{lstlisting}
  448. %% Each element of the list is in the first slot of a pair, and the
  449. %% second slot is either the rest of the list or the null value, to mark
  450. %% the end of the list. Such lists are so common that Racket provides
  451. %% special notation for them that removes the need for the periods
  452. %% and so many parenthesis:
  453. %% \begin{lstlisting}
  454. %% `(a b c)
  455. %% \end{lstlisting}
  456. %% The following expression creates an S-expression that represents AST
  457. %% \eqref{eq:arith-prog}.
  458. %% \begin{lstlisting}
  459. %% `(+ (read) (- 8))
  460. %% \end{lstlisting}
  461. %% When using S-expressions to represent ASTs, the convention is to
  462. %% represent each AST node as a list and to put the operation symbol at
  463. %% the front of the list. The rest of the list contains the children. So
  464. %% in the above case, the root AST node has operation \code{`+} and its
  465. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  466. %% diagram \eqref{eq:arith-prog}.
  467. %% To build larger S-expressions one often needs to splice together
  468. %% several smaller S-expressions. Racket provides the comma operator to
  469. %% splice an S-expression into a larger one. For example, instead of
  470. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  471. %% we could have first created an S-expression for AST
  472. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  473. %% S-expression.
  474. %% \begin{lstlisting}
  475. %% (define ast1.4 `(- 8))
  476. %% (define ast1_1 `(+ (read) ,ast1.4))
  477. %% \end{lstlisting}
  478. %% In general, the Racket expression that follows the comma (splice)
  479. %% can be any expression that produces an S-expression.
  480. {\if\edition\racketEd\color{olive}
  481. We define a Racket \code{struct} for each kind of node. For this
  482. chapter we require just two kinds of nodes: one for integer constants
  483. and one for primitive operations. The following is the \code{struct}
  484. definition for integer constants.
  485. \begin{lstlisting}
  486. (struct Int (value))
  487. \end{lstlisting}
  488. An integer node includes just one thing: the integer value.
  489. To create an AST node for the integer $8$, we write \INT{8}.
  490. \begin{lstlisting}
  491. (define eight (Int 8))
  492. \end{lstlisting}
  493. We say that the value created by \INT{8} is an
  494. \emph{instance} of the
  495. \code{Int} structure.
  496. The following is the \code{struct} definition for primitive operations.
  497. \begin{lstlisting}
  498. (struct Prim (op args))
  499. \end{lstlisting}
  500. A primitive operation node includes an operator symbol \code{op} and a
  501. list of child \code{args}. For example, to create an AST that negates
  502. the number $8$, we write \code{(Prim '- (list eight))}.
  503. \begin{lstlisting}
  504. (define neg-eight (Prim '- (list eight)))
  505. \end{lstlisting}
  506. Primitive operations may have zero or more children. The \code{read}
  507. operator has zero children:
  508. \begin{lstlisting}
  509. (define rd (Prim 'read '()))
  510. \end{lstlisting}
  511. whereas the addition operator has two children:
  512. \begin{lstlisting}
  513. (define ast1_1 (Prim '+ (list rd neg-eight)))
  514. \end{lstlisting}
  515. We have made a design choice regarding the \code{Prim} structure.
  516. Instead of using one structure for many different operations
  517. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  518. structure for each operation, as follows.
  519. \begin{lstlisting}
  520. (struct Read ())
  521. (struct Add (left right))
  522. (struct Neg (value))
  523. \end{lstlisting}
  524. The reason we choose to use just one structure is that in many parts
  525. of the compiler the code for the different primitive operators is the
  526. same, so we might as well just write that code once, which is enabled
  527. by using a single structure.
  528. \fi}
  529. {\if\edition\pythonEd\color{purple}
  530. We use a Python \code{class} for each kind of node.
  531. The following is the class definition for constants.
  532. \begin{lstlisting}
  533. class Constant:
  534. def __init__(self, value):
  535. self.value = value
  536. \end{lstlisting}
  537. An integer constant node includes just one thing: the integer value.
  538. To create an AST node for the integer $8$, we write \INT{8}.
  539. \begin{lstlisting}
  540. eight = Constant(8)
  541. \end{lstlisting}
  542. We say that the value created by \INT{8} is an
  543. \emph{instance} of the \code{Constant} class.
  544. The following is class definition for unary operators.
  545. \begin{lstlisting}
  546. class UnaryOp:
  547. def __init__(self, op, operand):
  548. self.op = op
  549. self.operand = operand
  550. \end{lstlisting}
  551. The specific operation is specified by the \code{op} parameter. For
  552. example, the class \code{USub} is for unary subtraction. (More unary
  553. operators are introduced in later chapters.) To create an AST that
  554. negates the number $8$, we write \NEG{\code{eight}}.
  555. \begin{lstlisting}
  556. neg_eight = UnaryOp(USub(), eight)
  557. \end{lstlisting}
  558. The call to the \code{input\_int} function is represented by the
  559. \code{Call} and \code{Name} classes.
  560. \begin{lstlisting}
  561. class Call:
  562. def __init__(self, func, args):
  563. self.func = func
  564. self.args = args
  565. class Name:
  566. def __init__(self, id):
  567. self.id = id
  568. \end{lstlisting}
  569. To create an AST node that calls \code{input\_int}, we write
  570. \begin{lstlisting}
  571. read = Call(Name('input_int'), [])
  572. \end{lstlisting}
  573. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  574. the \code{BinOp} class for binary operators.
  575. \begin{lstlisting}
  576. class BinOp:
  577. def __init__(self, left, op, right):
  578. self.op = op
  579. self.left = left
  580. self.right = right
  581. \end{lstlisting}
  582. Similar to \code{UnaryOp}, the specific operation is specified by the
  583. \code{op} parameter, which for now is just an instance of the
  584. \code{Add} class. So to create the AST node that adds negative eight
  585. to some user input, we write the following.
  586. \begin{lstlisting}
  587. ast1_1 = BinOp(read, Add(), neg_eight)
  588. \end{lstlisting}
  589. \fi}
  590. When compiling a program such as \eqref{eq:arith-prog}, we need to
  591. know that the operation associated with the root node is addition and
  592. we need to be able to access its two children. \racket{Racket}\python{Python}
  593. provides pattern matching to support these kinds of queries, as we see in
  594. Section~\ref{sec:pattern-matching}.
  595. In this book, we often write down the concrete syntax of a program
  596. even when we really have in mind the AST because the concrete syntax
  597. is more concise. We recommend that, in your mind, you always think of
  598. programs as abstract syntax trees.
  599. \section{Grammars}
  600. \label{sec:grammar}
  601. \index{subject}{integer}
  602. \index{subject}{literal}
  603. \index{subject}{constant}
  604. A programming language can be thought of as a \emph{set} of programs.
  605. The set is typically infinite (one can always create larger and larger
  606. programs), so one cannot simply describe a language by listing all of
  607. the programs in the language. Instead we write down a set of rules, a
  608. \emph{grammar}, for building programs. Grammars are often used to
  609. define the concrete syntax of a language, but they can also be used to
  610. describe the abstract syntax. We write our rules in a variant of
  611. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  612. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  613. As an example, we describe a small language, named \LangInt{}, that consists of
  614. integers and arithmetic operations.
  615. \index{subject}{grammar}
  616. The first grammar rule for the abstract syntax of \LangInt{} says that an
  617. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  618. \begin{equation}
  619. \Exp ::= \INT{\Int} \label{eq:arith-int}
  620. \end{equation}
  621. %
  622. Each rule has a left-hand-side and a right-hand-side.
  623. If you have an AST node that matches the
  624. right-hand-side, then you can categorize it according to the
  625. left-hand-side.
  626. %
  627. A name such as $\Exp$ that is defined by the grammar rules is a
  628. \emph{non-terminal}. \index{subject}{non-terminal}
  629. %
  630. The name $\Int$ is also a non-terminal, but instead of defining it
  631. with a grammar rule, we define it with the following explanation. An
  632. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  633. $-$ (for negative integers), such that the sequence of decimals
  634. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  635. the representation of integers using 63 bits, which simplifies several
  636. aspects of compilation. \racket{Thus, these integers corresponds to
  637. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  638. \python{In contrast, integers in Python have unlimited precision, but
  639. the techniques need to handle unlimited precision fall outside the
  640. scope of this book.}
  641. The second grammar rule is the \READOP{} operation that receives an
  642. input integer from the user of the program.
  643. \begin{equation}
  644. \Exp ::= \READ{} \label{eq:arith-read}
  645. \end{equation}
  646. The third rule says that, given an $\Exp$ node, the negation of that
  647. node is also an $\Exp$.
  648. \begin{equation}
  649. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  650. \end{equation}
  651. Symbols in typewriter font are \emph{terminal} symbols and must
  652. literally appear in the program for the rule to be applicable.
  653. \index{subject}{terminal}
  654. We can apply these rules to categorize the ASTs that are in the
  655. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  656. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  657. following AST is an $\Exp$.
  658. \begin{center}
  659. \begin{minipage}{0.5\textwidth}
  660. \NEG{\INT{\code{8}}}
  661. \end{minipage}
  662. \begin{minipage}{0.25\textwidth}
  663. \begin{equation}
  664. \begin{tikzpicture}
  665. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  666. \node[draw, circle] (8) at (0, -1.2) {$8$};
  667. \draw[->] (minus) to (8);
  668. \end{tikzpicture}
  669. \label{eq:arith-neg8}
  670. \end{equation}
  671. \end{minipage}
  672. \end{center}
  673. The next grammar rule is for addition expressions:
  674. \begin{equation}
  675. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  676. \end{equation}
  677. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  678. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  679. \eqref{eq:arith-read} and we have already categorized
  680. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  681. to show that
  682. \[
  683. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  684. \]
  685. is an $\Exp$ in the \LangInt{} language.
  686. If you have an AST for which the above rules do not apply, then the
  687. AST is not in \LangInt{}. For example, the program \racket{\code{(-
  688. (read) 8)}} \python{\code{input\_int() - 8}} is not in \LangInt{}
  689. because there are no rules for the \key{-} operator with two
  690. arguments. Whenever we define a language with a grammar, the language
  691. only includes those programs that are justified by the rules.
  692. {\if\edition\pythonEd\color{purple}
  693. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  694. There is a statement for printing the value of an expression
  695. \[
  696. \Stmt{} ::= \PRINT{\Exp}
  697. \]
  698. and a statement that evaluates an expression but ignores the result.
  699. \[
  700. \Stmt{} ::= \EXPR{\Exp}
  701. \]
  702. \fi}
  703. {\if\edition\racketEd\color{olive}
  704. The last grammar rule for \LangInt{} states that there is a
  705. \code{Program} node to mark the top of the whole program:
  706. \[
  707. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  708. \]
  709. The \code{Program} structure is defined as follows
  710. \begin{lstlisting}
  711. (struct Program (info body))
  712. \end{lstlisting}
  713. where \code{body} is an expression. In later chapters, the \code{info}
  714. part will be used to store auxiliary information but for now it is
  715. just the empty list.
  716. \fi}
  717. {\if\edition\pythonEd\color{purple}
  718. The last grammar rule for \LangInt{} states that there is a
  719. \code{Module} node to mark the top of the whole program:
  720. \[
  721. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  722. \]
  723. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  724. this case, a list of statements.
  725. %
  726. The \code{Module} class is defined as follows
  727. \begin{lstlisting}
  728. class Module:
  729. def __init__(self, body):
  730. self.body = body
  731. \end{lstlisting}
  732. where \code{body} is a list of statements.
  733. \fi}
  734. It is common to have many grammar rules with the same left-hand side
  735. but different right-hand sides, such as the rules for $\Exp$ in the
  736. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  737. combine several right-hand-sides into a single rule.
  738. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  739. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  740. defined in Figure~\ref{fig:r0-concrete-syntax}.
  741. \racket{The \code{read-program} function provided in
  742. \code{utilities.rkt} of the support code reads a program in from a
  743. file (the sequence of characters in the concrete syntax of Racket)
  744. and parses it into an abstract syntax tree. See the description of
  745. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  746. details.}
  747. \python{The \code{parse} function in Python's \code{ast} module
  748. converts the concrete syntax (represented as a string) into an
  749. abstract syntax tree.}
  750. \begin{figure}[tp]
  751. \fbox{
  752. \begin{minipage}{0.96\textwidth}
  753. {\if\edition\racketEd\color{olive}
  754. \[
  755. \begin{array}{rcl}
  756. \Exp &::=& \Int \MID \LP\key{read}\RP \MID \LP\key{-}\;\Exp\RP \MID \LP\key{+} \; \Exp\;\Exp\RP\\
  757. \LangInt{} &::=& \Exp
  758. \end{array}
  759. \]
  760. \fi}
  761. {\if\edition\pythonEd\color{purple}
  762. \[
  763. \begin{array}{rcl}
  764. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp\\
  765. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp\\
  766. \LangInt{} &::=& \Stmt^{*}
  767. \end{array}
  768. \]
  769. \fi}
  770. \end{minipage}
  771. }
  772. \caption{The concrete syntax of \LangInt{}.}
  773. \label{fig:r0-concrete-syntax}
  774. \end{figure}
  775. \begin{figure}[tp]
  776. \fbox{
  777. \begin{minipage}{0.96\textwidth}
  778. {\if\edition\racketEd\color{olive}
  779. \[
  780. \begin{array}{rcl}
  781. \Exp &::=& \INT{\Int} \MID \READ{} \MID \NEG{\Exp} \\
  782. &\MID& \ADD{\Exp}{\Exp} \\
  783. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  784. \end{array}
  785. \]
  786. \fi}
  787. {\if\edition\pythonEd\color{purple}
  788. \[
  789. \begin{array}{rcl}
  790. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  791. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  792. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  793. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  794. \end{array}
  795. \]
  796. \fi}
  797. \end{minipage}
  798. }
  799. \caption{The abstract syntax of \LangInt{}.}
  800. \label{fig:r0-syntax}
  801. \end{figure}
  802. \section{Pattern Matching}
  803. \label{sec:pattern-matching}
  804. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  805. the parts of an AST node. \racket{Racket}\python{Python} provides the
  806. \texttt{match} feature to access the parts of a value.
  807. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  808. \begin{center}
  809. \begin{minipage}{0.5\textwidth}
  810. {\if\edition\racketEd\color{olive}
  811. \begin{lstlisting}
  812. (match ast1_1
  813. [(Prim op (list child1 child2))
  814. (print op)])
  815. \end{lstlisting}
  816. \fi}
  817. {\if\edition\pythonEd\color{purple}
  818. \begin{lstlisting}
  819. match ast1_1:
  820. case BinOp(child1, op, child2):
  821. print(op)
  822. \end{lstlisting}
  823. \fi}
  824. \end{minipage}
  825. \end{center}
  826. {\if\edition\racketEd\color{olive}
  827. %
  828. In the above example, the \texttt{match} form checks whether the AST
  829. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  830. three pattern variables \texttt{op}, \texttt{child1}, and
  831. \texttt{child2}, and then prints out the operator. In general, a match
  832. clause consists of a \emph{pattern} and a
  833. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  834. to be either a pattern variable, a structure name followed by a
  835. pattern for each of the structure's arguments, or an S-expression
  836. (symbols, lists, etc.). (See Chapter 12 of The Racket
  837. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  838. and Chapter 9 of The Racket
  839. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  840. for a complete description of \code{match}.)
  841. %
  842. The body of a match clause may contain arbitrary Racket code. The
  843. pattern variables can be used in the scope of the body, such as
  844. \code{op} in \code{(print op)}.
  845. %
  846. \fi}
  847. %
  848. %
  849. {\if\edition\pythonEd\color{purple}
  850. %
  851. In the above example, the \texttt{match} form checks whether the AST
  852. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  853. three pattern variables \texttt{child1}, \texttt{op}, and
  854. \texttt{child2}, and then prints out the operator. In general, each
  855. \code{case} consists of a \emph{pattern} and a
  856. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  857. to be either a pattern variable, a class name followed by a pattern
  858. for each of its constructor's arguments, or other literals such as
  859. strings, lists, etc.
  860. %
  861. The body of each \code{case} may contain arbitrary Python code. The
  862. pattern variables can be used in the body, such as \code{op} in
  863. \code{print(op)}.
  864. %
  865. \fi}
  866. A \code{match} form may contain several clauses, as in the following
  867. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  868. the AST. The \code{match} proceeds through the clauses in order,
  869. checking whether the pattern can match the input AST. The body of the
  870. first clause that matches is executed. The output of \code{leaf} for
  871. several ASTs is shown on the right.
  872. \begin{center}
  873. \begin{minipage}{0.6\textwidth}
  874. {\if\edition\racketEd\color{olive}
  875. \begin{lstlisting}
  876. (define (leaf arith)
  877. (match arith
  878. [(Int n) #t]
  879. [(Prim 'read '()) #t]
  880. [(Prim '- (list e1)) #f]
  881. [(Prim '+ (list e1 e2)) #f]))
  882. (leaf (Prim 'read '()))
  883. (leaf (Prim '- (list (Int 8))))
  884. (leaf (Int 8))
  885. \end{lstlisting}
  886. \fi}
  887. {\if\edition\pythonEd\color{purple}
  888. \begin{lstlisting}
  889. def leaf(arith):
  890. match arith:
  891. case Constant(n):
  892. return True
  893. case Call(Name('input_int'), []):
  894. return True
  895. case UnaryOp(USub(), e1):
  896. return False
  897. case BinOp(e1, Add(), e2):
  898. return False
  899. case _:
  900. return False
  901. print(leaf(Call(Name('input_int'), [])))
  902. print(leaf(UnaryOp(USub(), eight)))
  903. print(leaf(Constant(8)))
  904. \end{lstlisting}
  905. \fi}
  906. \end{minipage}
  907. \vrule
  908. \begin{minipage}{0.25\textwidth}
  909. {\if\edition\racketEd\color{olive}
  910. \begin{lstlisting}
  911. #t
  912. #f
  913. #t
  914. \end{lstlisting}
  915. \fi}
  916. {\if\edition\pythonEd\color{purple}
  917. \begin{lstlisting}
  918. True
  919. False
  920. True
  921. \end{lstlisting}
  922. \fi}
  923. \end{minipage}
  924. \end{center}
  925. When writing a \code{match}, we refer to the grammar definition to
  926. identify which non-terminal we are expecting to match against, then we
  927. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  928. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  929. corresponding right-hand side of a grammar rule. For the \code{match}
  930. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  931. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  932. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  933. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  934. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  935. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  936. patterns, replace non-terminals such as $\Exp$ with pattern variables
  937. of your choice (e.g. \code{e1} and \code{e2}).
  938. \section{Recursive Functions}
  939. \label{sec:recursion}
  940. \index{subject}{recursive function}
  941. Programs are inherently recursive. For example, an \LangInt{}
  942. expression is often made of smaller expressions. Thus, the natural way
  943. to process an entire program is with a recursive function. As a first
  944. example of such a recursive function, we define the function
  945. \code{exp} in Figure~\ref{fig:exp-predicate}, which takes an
  946. arbitrary value and determines whether or not it is an \LangInt{}
  947. expression.
  948. %
  949. We say that a function is defined by \emph{structural recursion} when
  950. it is defined using a sequence of match \racket{clauses}\python{cases}
  951. that correspond to a grammar, and the body of each \racket{clause}\python{case}
  952. makes a recursive call on each
  953. child node.\footnote{This principle of structuring code according to
  954. the data definition is advocated in the book \emph{How to Design
  955. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  956. \python{We define a second function, named \code{stmt}, that recognizes
  957. whether a value is a \LangInt{} statement.}
  958. \python{Finally, }
  959. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{Rint}, which
  960. determines whether an AST is a program in \LangInt{}. In general we can
  961. expect to write one recursive function to handle each non-terminal in
  962. a grammar.\index{subject}{structural recursion}
  963. \begin{figure}[tp]
  964. {\if\edition\racketEd\color{olive}
  965. \begin{minipage}{0.7\textwidth}
  966. \begin{lstlisting}
  967. (define (exp ast)
  968. (match ast
  969. [(Int n) #t]
  970. [(Prim 'read '()) #t]
  971. [(Prim '- (list e)) (exp e)]
  972. [(Prim '+ (list e1 e2))
  973. (and (exp e1) (exp e2))]
  974. [else #f]))
  975. (define (Rint ast)
  976. (match ast
  977. [(Program '() e) (exp e)]
  978. [else #f]))
  979. (Rint (Program '() ast1_1)
  980. (Rint (Program '()
  981. (Prim '- (list (Prim 'read '())
  982. (Prim '+ (list (Num 8)))))))
  983. \end{lstlisting}
  984. \end{minipage}
  985. \vrule
  986. \begin{minipage}{0.25\textwidth}
  987. \begin{lstlisting}
  988. #t
  989. #f
  990. \end{lstlisting}
  991. \end{minipage}
  992. \fi}
  993. {\if\edition\pythonEd\color{purple}
  994. \begin{minipage}{0.7\textwidth}
  995. \begin{lstlisting}
  996. def exp(e):
  997. match e:
  998. case Constant(n):
  999. return True
  1000. case Call(Name('input_int'), []):
  1001. return True
  1002. case UnaryOp(USub(), e1):
  1003. return exp(e1)
  1004. case BinOp(e1, Add(), e2):
  1005. return exp(e1) and exp(e2)
  1006. case _:
  1007. return False
  1008. def stmt(s):
  1009. match s:
  1010. case Call(Name('print'), [e]):
  1011. return exp(e)
  1012. case Expr(e):
  1013. return exp(e)
  1014. case _:
  1015. return False
  1016. def Rint(p):
  1017. match p:
  1018. case Module(body):
  1019. return all([stmt(s) for s in body])
  1020. case _:
  1021. return False
  1022. print(Rint(Module([Expr(ast1_1)])))
  1023. print(Rint(Module([Expr(BinOp(read, Sub(),
  1024. UnaryOp(Add(), Constant(8))))])))
  1025. \end{lstlisting}
  1026. \end{minipage}
  1027. \vrule
  1028. \begin{minipage}{0.25\textwidth}
  1029. \begin{lstlisting}
  1030. True
  1031. False
  1032. \end{lstlisting}
  1033. \end{minipage}
  1034. \fi}
  1035. \caption{Example of recursive functions for \LangInt{}. These functions
  1036. recognize whether an AST is in \LangInt{}.}
  1037. \label{fig:exp-predicate}
  1038. \end{figure}
  1039. %% You may be tempted to merge the two functions into one, like this:
  1040. %% \begin{center}
  1041. %% \begin{minipage}{0.5\textwidth}
  1042. %% \begin{lstlisting}
  1043. %% (define (Rint ast)
  1044. %% (match ast
  1045. %% [(Int n) #t]
  1046. %% [(Prim 'read '()) #t]
  1047. %% [(Prim '- (list e)) (Rint e)]
  1048. %% [(Prim '+ (list e1 e2)) (and (Rint e1) (Rint e2))]
  1049. %% [(Program '() e) (Rint e)]
  1050. %% [else #f]))
  1051. %% \end{lstlisting}
  1052. %% \end{minipage}
  1053. %% \end{center}
  1054. %% %
  1055. %% Sometimes such a trick will save a few lines of code, especially when
  1056. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1057. %% \emph{not} recommended because it can get you into trouble.
  1058. %% %
  1059. %% For example, the above function is subtly wrong:
  1060. %% \lstinline{(Rint (Program '() (Program '() (Int 3))))}
  1061. %% returns true when it should return false.
  1062. \section{Interpreters}
  1063. \label{sec:interp_Rint}
  1064. \index{subject}{interpreter}
  1065. The behavior of a program is defined by the specification of the
  1066. programming language.
  1067. %
  1068. \racket{For example, the Scheme language is defined in the report by
  1069. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1070. reference manual~\citep{plt-tr}.}
  1071. %
  1072. \python{For example, the Python language is defined in the Python
  1073. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1074. %
  1075. In this book we use interpreters
  1076. to specify each language that we consider. An interpreter that is
  1077. designated as the definition of a language is called a
  1078. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1079. \index{subject}{definitional interpreter} We warm up by creating a
  1080. definitional interpreter for the \LangInt{} language, which serves as
  1081. a second example of structural recursion. The \texttt{interp\_Rint}
  1082. function is defined in Figure~\ref{fig:interp_Rint}. The body of the
  1083. function is a match on the input program followed by a call to the
  1084. \lstinline{interp_exp} helper function, which in turn has one match
  1085. clause per grammar rule for \LangInt{} expressions.
  1086. \begin{figure}[tp]
  1087. {\if\edition\racketEd\color{olive}
  1088. \begin{lstlisting}
  1089. (define (interp_exp e)
  1090. (match e
  1091. [(Int n) n]
  1092. [(Prim 'read '())
  1093. (define r (read))
  1094. (cond [(fixnum? r) r]
  1095. [else (error 'interp_exp "read expected an integer" r)])]
  1096. [(Prim '- (list e))
  1097. (define v (interp_exp e))
  1098. (fx- 0 v)]
  1099. [(Prim '+ (list e1 e2))
  1100. (define v1 (interp_exp e1))
  1101. (define v2 (interp_exp e2))
  1102. (fx+ v1 v2)]))
  1103. (define (interp_Rint p)
  1104. (match p
  1105. [(Program '() e) (interp_exp e)]))
  1106. \end{lstlisting}
  1107. \fi}
  1108. {\if\edition\pythonEd\color{purple}
  1109. \begin{lstlisting}
  1110. def interp_exp(e):
  1111. match e:
  1112. case BinOp(left, Add(), right):
  1113. l = interp_exp(left)
  1114. r = interp_exp(right)
  1115. return l + r
  1116. case UnaryOp(USub(), v):
  1117. return - interp_exp(v)
  1118. case Constant(value):
  1119. return value
  1120. case Call(Name('input_int'), []):
  1121. return int(input())
  1122. def interp_stmt(s):
  1123. match s:
  1124. case Expr(Call(Name('print'), [arg])):
  1125. print(interp_exp(arg))
  1126. case Expr(value):
  1127. interp_exp(value)
  1128. def interp_Pint(p):
  1129. match p:
  1130. case Module(body):
  1131. for s in body:
  1132. interp_stmt(s)
  1133. \end{lstlisting}
  1134. \fi}
  1135. \caption{Interpreter for the \LangInt{} language.}
  1136. \label{fig:interp_Rint}
  1137. \end{figure}
  1138. Let us consider the result of interpreting a few \LangInt{} programs. The
  1139. following program adds two integers.
  1140. {\if\edition\racketEd\color{olive}
  1141. \begin{lstlisting}
  1142. (+ 10 32)
  1143. \end{lstlisting}
  1144. \fi}
  1145. {\if\edition\pythonEd\color{purple}
  1146. \begin{lstlisting}
  1147. print(10 + 32)
  1148. \end{lstlisting}
  1149. \fi}
  1150. The result is \key{42}, the answer to life, the universe, and
  1151. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1152. Galaxy} by Douglas Adams.}.
  1153. %
  1154. We wrote the above program in concrete syntax whereas the parsed
  1155. abstract syntax is:
  1156. {\if\edition\racketEd\color{olive}
  1157. \begin{lstlisting}
  1158. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1159. \end{lstlisting}
  1160. \fi}
  1161. {\if\edition\pythonEd\color{purple}
  1162. \begin{lstlisting}
  1163. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1164. \end{lstlisting}
  1165. \fi}
  1166. The next example demonstrates that expressions may be nested within
  1167. each other, in this case nesting several additions and negations.
  1168. {\if\edition\racketEd\color{olive}
  1169. \begin{lstlisting}
  1170. (+ 10 (- (+ 12 20)))
  1171. \end{lstlisting}
  1172. \fi}
  1173. {\if\edition\pythonEd\color{purple}
  1174. \begin{lstlisting}
  1175. print(10 + -(12 + 20))
  1176. \end{lstlisting}
  1177. \fi}
  1178. What is the result of the above program?
  1179. {\if\edition\racketEd\color{olive}
  1180. As mentioned previously, the \LangInt{} language does not support
  1181. arbitrarily-large integers, but only $63$-bit integers, so we
  1182. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1183. in Racket.
  1184. Suppose
  1185. \[
  1186. n = 999999999999999999
  1187. \]
  1188. which indeed fits in $63$-bits. What happens when we run the
  1189. following program in our interpreter?
  1190. \begin{lstlisting}
  1191. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1192. \end{lstlisting}
  1193. It produces an error:
  1194. \begin{lstlisting}
  1195. fx+: result is not a fixnum
  1196. \end{lstlisting}
  1197. We establish the convention that if running the definitional
  1198. interpreter on a program produces an error then the meaning of that
  1199. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1200. error is a \code{trapped-error}. A compiler for the language is under
  1201. no obligations regarding programs with unspecified behavior; it does
  1202. not have to produce an executable, and if it does, that executable can
  1203. do anything. On the other hand, if the error is a
  1204. \code{trapped-error}, then the compiler must produce an executable and
  1205. it is required to report that an error occurred. To signal an error,
  1206. exit with a return code of \code{255}. The interpreters in chapters
  1207. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1208. \code{trapped-error}.
  1209. \fi}
  1210. % TODO: how to deal with too-large integers in the Python interpreter?
  1211. %% This convention applies to the languages defined in this
  1212. %% book, as a way to simplify the student's task of implementing them,
  1213. %% but this convention is not applicable to all programming languages.
  1214. %%
  1215. Moving on to the last feature of the \LangInt{} language, the
  1216. \READOP{} operation prompts the user of the program for an integer.
  1217. Recall that program \eqref{eq:arith-prog} requests an integer input
  1218. and then subtracts \code{8}. So if we run
  1219. {\if\edition\racketEd\color{olive}
  1220. \begin{lstlisting}
  1221. (interp_Rint (Program '() ast1_1))
  1222. \end{lstlisting}
  1223. \fi}
  1224. {\if\edition\pythonEd\color{purple}
  1225. \begin{lstlisting}
  1226. interp_Pint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1227. \end{lstlisting}
  1228. \fi}
  1229. \noindent and if the input is \code{50}, the result is \code{42}.
  1230. We include the \READOP{} operation in \LangInt{} so a clever student
  1231. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1232. during compilation to obtain the output and then generates the trivial
  1233. code to produce the output.\footnote{Yes, a clever student did this in the
  1234. first instance of this course!}
  1235. The job of a compiler is to translate a program in one language into a
  1236. program in another language so that the output program behaves the
  1237. same way as the input program does. This idea is depicted in the
  1238. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1239. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1240. Given a compiler that translates from language $\mathcal{L}_1$ to
  1241. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1242. compiler must translate it into some program $P_2$ such that
  1243. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1244. same input $i$ yields the same output $o$.
  1245. \begin{equation} \label{eq:compile-correct}
  1246. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1247. \node (p1) at (0, 0) {$P_1$};
  1248. \node (p2) at (3, 0) {$P_2$};
  1249. \node (o) at (3, -2.5) {$o$};
  1250. \path[->] (p1) edge [above] node {compile} (p2);
  1251. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1252. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1253. \end{tikzpicture}
  1254. \end{equation}
  1255. In the next section we see our first example of a compiler.
  1256. \section{Example Compiler: a Partial Evaluator}
  1257. \label{sec:partial-evaluation}
  1258. In this section we consider a compiler that translates \LangInt{} programs
  1259. into \LangInt{} programs that may be more efficient, that is, this compiler
  1260. is an optimizer. This optimizer eagerly computes the parts of the
  1261. program that do not depend on any inputs, a process known as
  1262. \emph{partial evaluation}~\citep{Jones:1993uq}.
  1263. \index{subject}{partial evaluation}
  1264. For example, given the following program
  1265. {\if\edition\racketEd\color{olive}
  1266. \begin{lstlisting}
  1267. (+ (read) (- (+ 5 3)))
  1268. \end{lstlisting}
  1269. \fi}
  1270. {\if\edition\pythonEd\color{purple}
  1271. \begin{lstlisting}
  1272. print input_int() + -(5 + 3)
  1273. \end{lstlisting}
  1274. \fi}
  1275. \noindent our compiler translates it into the program
  1276. {\if\edition\racketEd\color{olive}
  1277. \begin{lstlisting}
  1278. (+ (read) -8)
  1279. \end{lstlisting}
  1280. \fi}
  1281. {\if\edition\pythonEd\color{purple}
  1282. \begin{lstlisting}
  1283. print input_int() + -8
  1284. \end{lstlisting}
  1285. \fi}
  1286. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1287. evaluator for the \LangInt{} language. The output of the partial evaluator
  1288. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  1289. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1290. whereas the code for partially evaluating the negation and addition
  1291. operations is factored into two separate helper functions:
  1292. \code{pe\_neg} and \code{pe\_add}. The input to these helper
  1293. functions is the output of partially evaluating the children.
  1294. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1295. arguments are integers and if they are, perform the appropriate
  1296. arithmetic. Otherwise, they create an AST node for the arithmetic
  1297. operation.
  1298. \begin{figure}[tp]
  1299. {\if\edition\racketEd\color{olive}
  1300. \begin{lstlisting}
  1301. (define (pe_neg r)
  1302. (match r
  1303. [(Int n) (Int (fx- 0 n))]
  1304. [else (Prim '- (list r))]))
  1305. (define (pe_add r1 r2)
  1306. (match* (r1 r2)
  1307. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1308. [(_ _) (Prim '+ (list r1 r2))]))
  1309. (define (pe_exp e)
  1310. (match e
  1311. [(Int n) (Int n)]
  1312. [(Prim 'read '()) (Prim 'read '())]
  1313. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1314. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1315. (define (pe_Rint p)
  1316. (match p
  1317. [(Program '() e) (Program '() (pe_exp e))]))
  1318. \end{lstlisting}
  1319. \fi}
  1320. {\if\edition\pythonEd\color{purple}
  1321. \begin{lstlisting}
  1322. def pe_neg(r):
  1323. match r:
  1324. case Constant(n):
  1325. return Constant(-n)
  1326. case _:
  1327. return UnaryOp(USub(), r)
  1328. def pe_add(r1, r2):
  1329. match (r1, r2):
  1330. case (Constant(n1), Constant(n2)):
  1331. return Constant(n1 + n2)
  1332. case _:
  1333. return BinOp(r1, Add(), r2)
  1334. def pe_exp(e):
  1335. match e:
  1336. case BinOp(left, Add(), right):
  1337. return pe_add(pe_exp(left), pe_exp(right))
  1338. case UnaryOp(USub(), v):
  1339. return pe_neg(pe_exp(v))
  1340. case Constant(value):
  1341. return e
  1342. case Call(Name('input_int'), []):
  1343. return e
  1344. def pe_stmt(s):
  1345. match s:
  1346. case Expr(Call(Name('print'), [arg])):
  1347. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1348. case Expr(value):
  1349. return Expr(pe_exp(value))
  1350. def pe_Pint(p):
  1351. match p:
  1352. case Module(body):
  1353. new_body = [pe_stmt(s) for s in body]
  1354. return Module(new_body)
  1355. \end{lstlisting}
  1356. \fi}
  1357. \caption{A partial evaluator for \LangInt{}.}
  1358. \label{fig:pe-arith}
  1359. \end{figure}
  1360. To gain some confidence that the partial evaluator is correct, we can
  1361. test whether it produces programs that get the same result as the
  1362. input programs. That is, we can test whether it satisfies Diagram
  1363. \ref{eq:compile-correct}.
  1364. %
  1365. {\if\edition\racketEd\color{olive}
  1366. The following code runs the partial evaluator on several examples and
  1367. tests the output program. The \texttt{parse-program} and
  1368. \texttt{assert} functions are defined in
  1369. Appendix~\ref{appendix:utilities}.\\
  1370. \begin{minipage}{1.0\textwidth}
  1371. \begin{lstlisting}
  1372. (define (test_pe p)
  1373. (assert "testing pe_Rint"
  1374. (equal? (interp_Rint p) (interp_Rint (pe_Rint p)))))
  1375. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1376. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1377. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1378. \end{lstlisting}
  1379. \end{minipage}
  1380. \fi}
  1381. % TODO: python version of testing the PE
  1382. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1383. \chapter{Integers and Variables}
  1384. \label{ch:Rvar}
  1385. This chapter is about compiling a subset of \racket{Racket}\python{Python}
  1386. to x86-64 assembly
  1387. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1388. integer arithmetic and local variable binding. We often refer to
  1389. x86-64 simply as x86. The chapter begins with a description of the
  1390. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1391. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1392. is large so we discuss only the instructions needed for compiling
  1393. \LangVar{}. We introduce more x86 instructions in later chapters.
  1394. After introducing \LangVar{} and x86, we reflect on their differences
  1395. and come up with a plan to break down the translation from \LangVar{}
  1396. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1397. rest of the sections in this chapter give detailed hints regarding
  1398. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1399. We hope to give enough hints that the well-prepared reader, together
  1400. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1401. a couple weeks. To give the reader a feeling for the scale of this
  1402. first compiler, the instructor solution for the \LangVar{} compiler is
  1403. approximately \racket{500}\python{300} lines of code.
  1404. \section{The \LangVar{} Language}
  1405. \label{sec:s0}
  1406. \index{subject}{variable}
  1407. The \LangVar{} language extends the \LangInt{} language with
  1408. variables. The concrete syntax of the \LangVar{} language is defined
  1409. by the grammar in Figure~\ref{fig:Rvar-concrete-syntax} and the
  1410. abstract syntax is defined in Figure~\ref{fig:Rvar-syntax}. The
  1411. non-terminal \Var{} may be any Racket identifier. As in \LangInt{},
  1412. \key{read} is a nullary operator, \key{-} is a unary operator, and
  1413. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1414. syntax of \LangVar{} includes the \racket{\key{Program}
  1415. struct}\python{\key{Module} instance} to mark the top of the
  1416. program.
  1417. %% The $\itm{info}$
  1418. %% field of the \key{Program} structure contains an \emph{association
  1419. %% list} (a list of key-value pairs) that is used to communicate
  1420. %% auxiliary data from one compiler pass the next.
  1421. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1422. exhibit several compilation techniques.
  1423. \begin{figure}[tp]
  1424. \centering
  1425. \fbox{
  1426. \begin{minipage}{0.96\textwidth}
  1427. {\if\edition\racketEd\color{olive}
  1428. \[
  1429. \begin{array}{rcl}
  1430. \Exp &::=& \Int{} \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}\\
  1431. &\MID& \Var{} \MID \CLET{\Var}{\Exp}{\Exp} \\
  1432. \LangVarM{} &::=& \Exp
  1433. \end{array}
  1434. \]
  1435. \fi}
  1436. {\if\edition\pythonEd\color{purple}
  1437. \[
  1438. \begin{array}{rcl}
  1439. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Var{} \\
  1440. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \Var\mathop{\key{=}}\Exp\\
  1441. \LangVarM{} &::=& \Stmt^{*}
  1442. \end{array}
  1443. \]
  1444. \fi}
  1445. \end{minipage}
  1446. }
  1447. \caption{The concrete syntax of \LangVar{}.}
  1448. \label{fig:Rvar-concrete-syntax}
  1449. \end{figure}
  1450. \begin{figure}[tp]
  1451. \centering
  1452. \fbox{
  1453. \begin{minipage}{0.96\textwidth}
  1454. {\if\edition\racketEd\color{olive}
  1455. \[
  1456. \begin{array}{rcl}
  1457. \Exp &::=& \INT{\Int} \MID \READ{} \\
  1458. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  1459. &\MID& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  1460. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1461. \end{array}
  1462. \]
  1463. \fi}
  1464. {\if\edition\pythonEd\color{purple}
  1465. \[
  1466. \begin{array}{rcl}
  1467. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  1468. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \VAR{\Var{}} \\
  1469. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  1470. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  1471. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1472. \end{array}
  1473. \]
  1474. \fi}
  1475. \end{minipage}
  1476. }
  1477. \caption{The abstract syntax of \LangVar{}.}
  1478. \label{fig:Rvar-syntax}
  1479. \end{figure}
  1480. {\if\edition\racketEd\color{olive}
  1481. Let us dive further into the syntax and semantics of the \LangVar{}
  1482. language. The \key{let} feature defines a variable for use within its
  1483. body and initializes the variable with the value of an expression.
  1484. The abstract syntax for \key{let} is defined in
  1485. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for \key{let} is
  1486. \begin{lstlisting}
  1487. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1488. \end{lstlisting}
  1489. For example, the following program initializes \code{x} to $32$ and then
  1490. evaluates the body \code{(+ 10 x)}, producing $42$.
  1491. \begin{lstlisting}
  1492. (let ([x (+ 12 20)]) (+ 10 x))
  1493. \end{lstlisting}
  1494. \fi}
  1495. %
  1496. {\if\edition\pythonEd\color{purple}
  1497. The \LangVar{} language adds variables and the assignment statement
  1498. to \LangInt{}. The assignment statement defines a variable for use by
  1499. later statements and initializes the variable with the value of an expression.
  1500. The abstract syntax for assignment is defined in
  1501. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for assignment is
  1502. \begin{lstlisting}
  1503. |$\itm{var}$| = |$\itm{exp}$|
  1504. \end{lstlisting}
  1505. For example, the following program initializes \code{x} to $32$ and then
  1506. prints the result of \code{10 + x}, producing $42$.
  1507. \begin{lstlisting}
  1508. x = 12 + 20
  1509. print(10 + x)
  1510. \end{lstlisting}
  1511. \fi}
  1512. {\if\edition\racketEd\color{olive}
  1513. When there are multiple \key{let}'s for the same variable, the closest
  1514. enclosing \key{let} is used. That is, variable definitions overshadow
  1515. prior definitions. Consider the following program with two \key{let}'s
  1516. that define variables named \code{x}. Can you figure out the result?
  1517. \begin{lstlisting}
  1518. (let ([x 32]) (+ (let ([x 10]) x) x))
  1519. \end{lstlisting}
  1520. For the purposes of depicting which variable uses correspond to which
  1521. definitions, the following shows the \code{x}'s annotated with
  1522. subscripts to distinguish them. Double check that your answer for the
  1523. above is the same as your answer for this annotated version of the
  1524. program.
  1525. \begin{lstlisting}
  1526. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1527. \end{lstlisting}
  1528. The initializing expression is always evaluated before the body of the
  1529. \key{let}, so in the following, the \key{read} for \code{x} is
  1530. performed before the \key{read} for \code{y}. Given the input
  1531. $52$ then $10$, the following produces $42$ (not $-42$).
  1532. \begin{lstlisting}
  1533. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1534. \end{lstlisting}
  1535. \fi}
  1536. \subsection{Extensible Interpreters via Method Overriding}
  1537. \label{sec:extensible-interp}
  1538. To prepare for discussing the interpreter for \LangVar{}, we
  1539. explain why we to implement the interpreter using
  1540. object-oriented programming, that is, as a collection of methods
  1541. inside of a class. Throughout this book we define many interpreters,
  1542. one for each of the languages that we study. Because each language
  1543. builds on the prior one, there is a lot of commonality between these
  1544. interpreters. We want to write down the common parts just once
  1545. instead of many times. A naive approach would be to have, for example,
  1546. the interpreter for \LangIf{} handle all of the new features in that
  1547. language and then have a default case that dispatches to the
  1548. interpreter for \LangVar{}. The following code sketches this idea.
  1549. \begin{center}
  1550. {\if\edition\racketEd\color{olive}
  1551. \begin{minipage}{0.45\textwidth}
  1552. \begin{lstlisting}
  1553. (define (interp_Rvar_exp e)
  1554. (match e
  1555. [(Prim '- (list e1))
  1556. (fx- 0 (interp_Rvar_exp e1))]
  1557. ...))
  1558. \end{lstlisting}
  1559. \end{minipage}
  1560. \begin{minipage}{0.45\textwidth}
  1561. \begin{lstlisting}
  1562. (define (interp_Rif_exp e)
  1563. (match e
  1564. [(If cnd thn els)
  1565. (match (interp_Rif_exp cnd)
  1566. [#t (interp_Rif_exp thn)]
  1567. [#f (interp_Rif_exp els)])]
  1568. ...
  1569. [else (interp_Rvar_exp e)]))
  1570. \end{lstlisting}
  1571. \end{minipage}
  1572. \fi}
  1573. {\if\edition\pythonEd\color{purple}
  1574. \begin{minipage}{0.45\textwidth}
  1575. \begin{lstlisting}
  1576. def interp_Rvar_exp(e):
  1577. match e:
  1578. case UnaryOp(USub(), e1):
  1579. return - interp_Rvar_exp(e1)
  1580. ...
  1581. \end{lstlisting}
  1582. \end{minipage}
  1583. \begin{minipage}{0.45\textwidth}
  1584. \begin{lstlisting}
  1585. def interp_Rif_exp(e):
  1586. match e:
  1587. case IfExp(cnd, thn, els):
  1588. match interp_Rif_exp(cnd):
  1589. case True:
  1590. return interp_Rif_exp(thn)
  1591. case False:
  1592. return interp_Rif_exp(els)
  1593. ...
  1594. case _:
  1595. return interp_Rvar_exp(e)
  1596. \end{lstlisting}
  1597. \end{minipage}
  1598. \fi}
  1599. \end{center}
  1600. The problem with this approach is that it does not handle situations
  1601. in which an \LangIf{} feature, such as a conditional expression, is
  1602. nested inside an \LangVar{} feature, like the \code{-} operator, as in
  1603. the following program.
  1604. {\if\edition\racketEd\color{olive}
  1605. \begin{lstlisting}
  1606. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1607. \end{lstlisting}
  1608. \fi}
  1609. {\if\edition\pythonEd\color{purple}
  1610. \begin{lstlisting}
  1611. print(-(42 if True else 0))
  1612. \end{lstlisting}
  1613. \fi}
  1614. If we invoke \code{interp\_Rif\_exp} on this program, it dispatches to
  1615. \code{interp\_Rvar\_exp} to handle the \code{-} operator, but then it
  1616. recurisvely calls \code{interp\_Rvar\_exp} again on the argument of \code{-},
  1617. which is an \code{If}. But there is no case for \code{If} in
  1618. \code{interp\_Rvar\_exp}, so we get an error!
  1619. To make our interpreters extensible we need something called
  1620. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1621. recursive knot is delayed to when the functions are
  1622. composed. Object-oriented languages provide open recursion with the
  1623. late-binding of overridden methods\index{subject}{method overriding}. The
  1624. following code sketches this idea for interpreting \LangVar{} and
  1625. \LangIf{} using
  1626. \racket{the
  1627. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1628. \index{subject}{class} feature of Racket}
  1629. \python{a Python \code{class} definition}. We define one class for each
  1630. language and define a method for interpreting expressions inside each
  1631. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1632. and the method \code{interp\_exp} in \LangIf{} overrides the
  1633. \code{interp\_exp} in \LangVar{}. Note that the default case of
  1634. \code{interp\_exp} in \LangIf{} uses \code{super} to invoke
  1635. \code{interp\_exp}, and because \LangIf{} inherits from \LangVar{},
  1636. that dispatches to the \code{interp\_exp} in \LangVar{}.
  1637. \begin{center}
  1638. {\if\edition\racketEd\color{olive}
  1639. \begin{minipage}{0.45\textwidth}
  1640. \begin{lstlisting}
  1641. (define interp_Rvar_class
  1642. (class object%
  1643. (define/public (interp_exp e)
  1644. (match e
  1645. [(Prim '- (list e))
  1646. (fx- 0 (interp_exp e))]
  1647. ...))
  1648. ...))
  1649. \end{lstlisting}
  1650. \end{minipage}
  1651. \begin{minipage}{0.45\textwidth}
  1652. \begin{lstlisting}
  1653. (define interp_Rif_class
  1654. (class interp_Rvar_class
  1655. (define/override (interp_exp e)
  1656. (match e
  1657. [(If cnd thn els)
  1658. (match (interp_exp cnd)
  1659. [#t (interp_exp thn)]
  1660. [#f (interp_exp els)])]
  1661. ...
  1662. [else (super interp_exp e)]))
  1663. ...
  1664. ))
  1665. \end{lstlisting}
  1666. \end{minipage}
  1667. \fi}
  1668. {\if\edition\pythonEd\color{purple}
  1669. \begin{minipage}{0.45\textwidth}
  1670. \begin{lstlisting}
  1671. class InterpRvar:
  1672. def interp_exp(e):
  1673. match e:
  1674. case UnaryOp(USub(), e1):
  1675. return -self.interp_exp(e1)
  1676. ...
  1677. ...
  1678. \end{lstlisting}
  1679. \end{minipage}
  1680. \begin{minipage}{0.45\textwidth}
  1681. \begin{lstlisting}
  1682. def InterpRif(InterpRVar):
  1683. def interp_exp(e):
  1684. match e:
  1685. case IfExp(cnd, thn, els):
  1686. match self.interp_exp(cnd):
  1687. case True:
  1688. return self.interp_exp(thn)
  1689. case False:
  1690. return self.interp_exp(els)
  1691. ...
  1692. case _:
  1693. return super().interp_exp(e)
  1694. ...
  1695. \end{lstlisting}
  1696. \end{minipage}
  1697. \fi}
  1698. \end{center}
  1699. Getting back to the troublesome example, repeated here:
  1700. {\if\edition\racketEd\color{olive}
  1701. \begin{lstlisting}
  1702. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1703. \end{lstlisting}
  1704. \fi}
  1705. {\if\edition\pythonEd\color{purple}
  1706. \begin{lstlisting}
  1707. -(42 if True else 0)
  1708. \end{lstlisting}
  1709. \fi}
  1710. \noindent We can invoke the \code{interp\_exp} method for \LangIf{} on this
  1711. expression, call it \code{e0}, by creating an object of the \LangIf{} class
  1712. and calling the \code{interp\_exp} method.
  1713. {\if\edition\racketEd\color{olive}
  1714. \begin{lstlisting}
  1715. (send (new interp_Rif_class) interp_exp e0)
  1716. \end{lstlisting}
  1717. \fi}
  1718. {\if\edition\pythonEd\color{purple}
  1719. \begin{lstlisting}
  1720. InterpRif().interp_exp(e0)
  1721. \end{lstlisting}
  1722. \fi}
  1723. \noindent The default case of \code{interp\_exp} in \LangIf{} handles it by
  1724. dispatching to the \code{interp\_exp} method in \LangVar{}, which
  1725. handles the \code{-} operator. But then for the recursive method call,
  1726. it dispatches back to \code{interp\_exp} in \LangIf{}, where the
  1727. \code{If} is handled correctly. Thus, method overriding gives us the
  1728. open recursion that we need to implement our interpreters in an
  1729. extensible way.
  1730. \subsection{Definitional Interpreter for \LangVar{}}
  1731. {\if\edition\racketEd\color{olive}
  1732. \begin{figure}[tp]
  1733. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1734. \small
  1735. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1736. An \emph{association list} (alist) is a list of key-value pairs.
  1737. For example, we can map people to their ages with an alist.
  1738. \index{subject}{alist}\index{subject}{association list}
  1739. \begin{lstlisting}[basicstyle=\ttfamily]
  1740. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1741. \end{lstlisting}
  1742. The \emph{dictionary} interface is for mapping keys to values.
  1743. Every alist implements this interface. \index{subject}{dictionary} The package
  1744. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1745. provides many functions for working with dictionaries. Here
  1746. are a few of them:
  1747. \begin{description}
  1748. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1749. returns the value associated with the given $\itm{key}$.
  1750. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1751. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1752. but otherwise is the same as $\itm{dict}$.
  1753. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1754. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1755. of keys and values in $\itm{dict}$. For example, the following
  1756. creates a new alist in which the ages are incremented.
  1757. \end{description}
  1758. \vspace{-10pt}
  1759. \begin{lstlisting}[basicstyle=\ttfamily]
  1760. (for/list ([(k v) (in-dict ages)])
  1761. (cons k (add1 v)))
  1762. \end{lstlisting}
  1763. \end{tcolorbox}
  1764. %\end{wrapfigure}
  1765. \caption{Association lists implement the dictionary interface.}
  1766. \label{fig:alist}
  1767. \end{figure}
  1768. \fi}
  1769. Having justified the use of classes and methods to implement
  1770. interpreters, we turn to the definitional interpreter for \LangVar{}
  1771. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1772. \LangInt{} but adds two new \key{match} cases for variables and
  1773. \racket{\key{let}}\python{assignment}. For
  1774. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1775. value bound to a variable to all the uses of the variable. To
  1776. accomplish this, we maintain a mapping from variables to
  1777. values. Throughout the compiler we often need to map variables to
  1778. information about them. We refer to these mappings as
  1779. \emph{environments}\index{subject}{environment}.\footnote{Another
  1780. common term for environment in the compiler literature is \emph{symbol
  1781. table}\index{subject}{symbol table}.}
  1782. %
  1783. We use \racket{an association list
  1784. (alist)}\python{\href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}} to represent the
  1785. environment. \racket{Figure~\ref{fig:alist} gives a brief introduction
  1786. to alists and the \code{racket/dict} package.} The
  1787. \code{interp\_exp} function takes the current environment, \code{env},
  1788. as an extra parameter. When the interpreter encounters a variable, it
  1789. looks up the corresponding value in the dictionary.
  1790. %
  1791. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1792. initializing expression, extends the environment with the result
  1793. value bound to the variable, using \code{dict-set}, then evaluates
  1794. the body of the \key{Let}.}
  1795. %
  1796. \python{When the interpreter encounters an assignment, it evaluates
  1797. the initializing expression and then associates the resulting value
  1798. with the variable in the environment.}
  1799. \begin{figure}[tp]
  1800. {\if\edition\racketEd\color{olive}
  1801. \begin{lstlisting}
  1802. (define interp_Rvar_class
  1803. (class object%
  1804. (super-new)
  1805. (define/public ((interp_exp env) e)
  1806. (match e
  1807. [(Int n) n]
  1808. [(Prim 'read '())
  1809. (define r (read))
  1810. (cond [(fixnum? r) r]
  1811. [else (error 'interp_exp "expected an integer" r)])]
  1812. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1813. [(Prim '+ (list e1 e2))
  1814. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1815. [(Var x) (dict-ref env x)]
  1816. [(Let x e body)
  1817. (define new-env (dict-set env x ((interp_exp env) e)))
  1818. ((interp_exp new-env) body)]))
  1819. (define/public (interp_program p)
  1820. (match p
  1821. [(Program '() e) ((interp_exp '()) e)]))
  1822. ))
  1823. (define (interp_Rvar p)
  1824. (send (new interp_Rvar_class) interp_program p))
  1825. \end{lstlisting}
  1826. \fi}
  1827. {\if\edition\pythonEd\color{purple}
  1828. \begin{lstlisting}
  1829. class InterpPvar:
  1830. def interp_exp(self, e, env):
  1831. match e:
  1832. case BinOp(left, Add(), right):
  1833. l = self.interp_exp(left, env)
  1834. r = self.interp_exp(right, env)
  1835. return l + r
  1836. case UnaryOp(USub(), v):
  1837. return - self.interp_exp(v, env)
  1838. case Name(id):
  1839. return env[id]
  1840. case Constant(value):
  1841. return value
  1842. case Call(Name('input_int'), []):
  1843. return int(input())
  1844. def interp_stmts(self, ss, env):
  1845. if len(ss) == 0:
  1846. return
  1847. match ss[0]:
  1848. case Assign([lhs], value):
  1849. env[lhs.id] = self.interp_exp(value, env)
  1850. return self.interp_stmts(ss[1:], env)
  1851. case Expr(Call(Name('print'), [arg])):
  1852. print(self.interp_exp(arg, env), end='')
  1853. return self.interp_stmts(ss[1:], env)
  1854. case Expr(value):
  1855. self.interp_exp(value, env)
  1856. return self.interp_stmts(ss[1:], env)
  1857. def interp_P(self, p):
  1858. match p:
  1859. case Module(body):
  1860. self.interp_stmts(body, {})
  1861. \end{lstlisting}
  1862. \fi}
  1863. \caption{Interpreter for the \LangVar{} language.}
  1864. \label{fig:interp-Rvar}
  1865. \end{figure}
  1866. The goal for this chapter is to implement a compiler that translates
  1867. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1868. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1869. computer as the $P_1$ program interpreted by \code{interp\_Rvar}. That
  1870. is, they output the same integer $n$. We depict this correctness
  1871. criteria in the following diagram.
  1872. \[
  1873. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1874. \node (p1) at (0, 0) {$P_1$};
  1875. \node (p2) at (4, 0) {$P_2$};
  1876. \node (o) at (4, -2) {$n$};
  1877. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1878. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Rvar}} (o);
  1879. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  1880. \end{tikzpicture}
  1881. \]
  1882. In the next section we introduce the \LangXInt{} subset of x86 that
  1883. suffices for compiling \LangVar{}.
  1884. \section{The \LangXInt{} Assembly Language}
  1885. \label{sec:x86}
  1886. \index{subject}{x86}
  1887. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1888. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1889. assembler.
  1890. %
  1891. A program begins with a \code{main} label followed by a sequence of
  1892. instructions. The \key{globl} directive says that the \key{main}
  1893. procedure is externally visible, which is necessary so that the
  1894. operating system can call it. In the grammar, ellipses such as
  1895. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1896. \ldots$ is a sequence of instructions.\index{subject}{instruction}
  1897. %
  1898. An x86 program is stored in the computer's memory. For our purposes,
  1899. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1900. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1901. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1902. the address of the next instruction to be executed. For most
  1903. instructions, the program counter is incremented after the instruction
  1904. is executed, so it points to the next instruction in memory. Most x86
  1905. instructions take two operands, where each operand is either an
  1906. integer constant (called an \emph{immediate value}\index{subject}{immediate
  1907. value}), a \emph{register}\index{subject}{register}, or a memory location.
  1908. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  1909. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  1910. && \key{r8} \MID \key{r9} \MID \key{r10}
  1911. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  1912. \MID \key{r14} \MID \key{r15}}
  1913. \begin{figure}[tp]
  1914. \fbox{
  1915. \begin{minipage}{0.96\textwidth}
  1916. \[
  1917. \begin{array}{lcl}
  1918. \Reg &::=& \allregisters{} \\
  1919. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  1920. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  1921. \key{subq} \; \Arg\key{,} \Arg \MID
  1922. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  1923. && \key{callq} \; \mathit{label} \MID
  1924. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  1925. && \itm{label}\key{:}\; \Instr \\
  1926. \LangXIntM{} &::= & \key{.globl main}\\
  1927. & & \key{main:} \; \Instr\ldots
  1928. \end{array}
  1929. \]
  1930. \end{minipage}
  1931. }
  1932. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1933. \label{fig:x86-int-concrete}
  1934. \end{figure}
  1935. A register is a special kind of variable. Each one holds a 64-bit
  1936. value; there are 16 general-purpose registers in the computer and
  1937. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1938. is written with a \key{\%} followed by the register name, such as
  1939. \key{\%rax}.
  1940. An immediate value is written using the notation \key{\$}$n$ where $n$
  1941. is an integer.
  1942. %
  1943. %
  1944. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1945. which obtains the address stored in register $r$ and then adds $n$
  1946. bytes to the address. The resulting address is used to load or store
  1947. to memory depending on whether it occurs as a source or destination
  1948. argument of an instruction.
  1949. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1950. source $s$ and destination $d$, applies the arithmetic operation, then
  1951. writes the result back to the destination $d$.
  1952. %
  1953. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1954. stores the result in $d$.
  1955. %
  1956. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1957. specified by the label and $\key{retq}$ returns from a procedure to
  1958. its caller.
  1959. %
  1960. We discuss procedure calls in more detail later in this chapter and in
  1961. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1962. updates the program counter to the address of the instruction after
  1963. the specified label.
  1964. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1965. all of the x86 instructions used in this book.
  1966. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  1967. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  1968. \lstinline{movq $10, %rax}
  1969. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1970. adds $32$ to the $10$ in \key{rax} and
  1971. puts the result, $42$, back into \key{rax}.
  1972. %
  1973. The last instruction, \key{retq}, finishes the \key{main} function by
  1974. returning the integer in \key{rax} to the operating system. The
  1975. operating system interprets this integer as the program's exit
  1976. code. By convention, an exit code of 0 indicates that a program
  1977. completed successfully, and all other exit codes indicate various
  1978. errors. Nevertheless, in this book we return the result of the program
  1979. as the exit code.
  1980. \begin{figure}[tbp]
  1981. \begin{lstlisting}
  1982. .globl main
  1983. main:
  1984. movq $10, %rax
  1985. addq $32, %rax
  1986. retq
  1987. \end{lstlisting}
  1988. \caption{An x86 program that computes
  1989. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  1990. \label{fig:p0-x86}
  1991. \end{figure}
  1992. The x86 assembly language varies in a couple of ways depending on what
  1993. operating system it is assembled in. The code examples shown here are
  1994. correct on Linux and most Unix-like platforms, but when assembled on
  1995. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1996. as in \key{\_main}.
  1997. We exhibit the use of memory for storing intermediate results in the
  1998. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  1999. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2000. uses a region of memory called the \emph{procedure call stack} (or
  2001. \emph{stack} for
  2002. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2003. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2004. for each procedure call. The memory layout for an individual frame is
  2005. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2006. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  2007. item at the top of the stack. The stack grows downward in memory, so
  2008. we increase the size of the stack by subtracting from the stack
  2009. pointer. In the context of a procedure call, the \emph{return
  2010. address}\index{subject}{return address} is the instruction after the
  2011. call instruction on the caller side. The function call instruction,
  2012. \code{callq}, pushes the return address onto the stack prior to
  2013. jumping to the procedure. The register \key{rbp} is the \emph{base
  2014. pointer}\index{subject}{base pointer} and is used to access variables
  2015. that are stored in the frame of the current procedure call. The base
  2016. pointer of the caller is pushed onto the stack after the return
  2017. address and then the base pointer is set to the location of the old
  2018. base pointer. In Figure~\ref{fig:frame} we number the variables from
  2019. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  2020. variable $2$ at $-16\key{(\%rbp)}$, etc.
  2021. \begin{figure}[tbp]
  2022. \begin{lstlisting}
  2023. start:
  2024. movq $10, -8(%rbp)
  2025. negq -8(%rbp)
  2026. movq -8(%rbp), %rax
  2027. addq $52, %rax
  2028. jmp conclusion
  2029. .globl main
  2030. main:
  2031. pushq %rbp
  2032. movq %rsp, %rbp
  2033. subq $16, %rsp
  2034. jmp start
  2035. conclusion:
  2036. addq $16, %rsp
  2037. popq %rbp
  2038. retq
  2039. \end{lstlisting}
  2040. \caption{An x86 program that computes
  2041. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2042. \label{fig:p1-x86}
  2043. \end{figure}
  2044. \begin{figure}[tbp]
  2045. \centering
  2046. \begin{tabular}{|r|l|} \hline
  2047. Position & Contents \\ \hline
  2048. 8(\key{\%rbp}) & return address \\
  2049. 0(\key{\%rbp}) & old \key{rbp} \\
  2050. -8(\key{\%rbp}) & variable $1$ \\
  2051. -16(\key{\%rbp}) & variable $2$ \\
  2052. \ldots & \ldots \\
  2053. 0(\key{\%rsp}) & variable $n$\\ \hline
  2054. \end{tabular}
  2055. \caption{Memory layout of a frame.}
  2056. \label{fig:frame}
  2057. \end{figure}
  2058. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2059. control is transferred from the operating system to the \code{main}
  2060. function. The operating system issues a \code{callq main} instruction
  2061. which pushes its return address on the stack and then jumps to
  2062. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2063. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2064. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2065. alignment (because the \code{callq} pushed the return address). The
  2066. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2067. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2068. pointer for the caller onto the stack and subtracts $8$ from the stack
  2069. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  2070. base pointer so that it points the location of the old base
  2071. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2072. pointer down to make enough room for storing variables. This program
  2073. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2074. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2075. functions. The last instruction of the prelude is \code{jmp start},
  2076. which transfers control to the instructions that were generated from
  2077. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.
  2078. The first instruction under the \code{start} label is
  2079. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2080. %
  2081. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2082. %
  2083. The next instruction moves the $-10$ from variable $1$ into the
  2084. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2085. the value in \code{rax}, updating its contents to $42$.
  2086. The three instructions under the label \code{conclusion} are the
  2087. typical \emph{conclusion}\index{subject}{conclusion} of a procedure. The first
  2088. two instructions restore the \code{rsp} and \code{rbp} registers to
  2089. the state they were in at the beginning of the procedure. The
  2090. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  2091. point at the old base pointer. Then \key{popq \%rbp} returns the old
  2092. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  2093. instruction, \key{retq}, jumps back to the procedure that called this
  2094. one and adds $8$ to the stack pointer.
  2095. The compiler needs a convenient representation for manipulating x86
  2096. programs, so we define an abstract syntax for x86 in
  2097. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2098. \LangXInt{}.
  2099. %
  2100. {\if\edition\racketEd\color{olive}
  2101. The main difference compared to the concrete syntax of \LangXInt{}
  2102. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2103. front of every instruction. Instead instructions are grouped into
  2104. \emph{blocks}\index{subject}{block}\index{subject}{basic block} with a
  2105. label associated with every block, which is why the \key{X86Program}
  2106. struct includes an alist mapping labels to blocks. The reason for this
  2107. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  2108. introduce conditional branching. The \code{Block} structure includes
  2109. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2110. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  2111. $\itm{info}$ field should contain an empty list.
  2112. \fi}
  2113. %
  2114. {\if\edition\pythonEd\color{purple}
  2115. %
  2116. The main difference compared to the concrete syntax of \LangXInt{}
  2117. (Figure~\ref{fig:x86-int-concrete}) is that we do not yet include a
  2118. way to label instructions but instead recommend inserting the
  2119. \key{main}, \key{start}, and \key{conclusion} labels when printing the
  2120. final x86 program.
  2121. %
  2122. \fi}
  2123. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2124. node includes an integer for representing the arity of the function,
  2125. i.e., the number of arguments, which is helpful to know during
  2126. register allocation (Chapter~\ref{ch:register-allocation-Rvar}).
  2127. \begin{figure}[tp]
  2128. \fbox{
  2129. \begin{minipage}{0.98\textwidth}
  2130. \small
  2131. {\if\edition\racketEd\color{olive}
  2132. \[
  2133. \begin{array}{lcl}
  2134. \Reg &::=& \allregisters{} \\
  2135. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2136. \MID \DEREF{\Reg}{\Int} \\
  2137. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2138. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2139. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2140. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2141. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2142. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2143. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2144. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2145. \end{array}
  2146. \]
  2147. \fi}
  2148. {\if\edition\pythonEd\color{purple}
  2149. \[
  2150. \begin{array}{lcl}
  2151. \Reg &::=& \allregisters{} \\
  2152. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2153. \MID \DEREF{\Reg}{\Int} \\
  2154. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2155. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2156. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2157. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2158. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2159. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2160. \LangXIntM{} &::= & \XPROGRAM{\Instr^{*}}{}
  2161. \end{array}
  2162. \]
  2163. \fi}
  2164. \end{minipage}
  2165. }
  2166. \caption{The abstract syntax of \LangXInt{} assembly.}
  2167. \label{fig:x86-int-ast}
  2168. \end{figure}
  2169. \section{Planning the trip to x86}
  2170. \label{sec:plan-s0-x86}
  2171. To compile one language to another it helps to focus on the
  2172. differences between the two languages because the compiler will need
  2173. to bridge those differences. What are the differences between \LangVar{}
  2174. and x86 assembly? Here are some of the most important ones:
  2175. \begin{enumerate}
  2176. \item x86 arithmetic instructions typically have two arguments
  2177. and update the second argument in place. In contrast, \LangVar{}
  2178. arithmetic operations take two arguments and produce a new value.
  2179. An x86 instruction may have at most one memory-accessing argument.
  2180. Furthermore, some instructions place special restrictions on their
  2181. arguments.
  2182. \item An argument of an \LangVar{} operator can be a deeply-nested
  2183. expression, whereas x86 instructions restrict their arguments to be
  2184. integer constants, registers, and memory locations.
  2185. {\if\edition\racketEd\color{olive}
  2186. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  2187. sequence of instructions and jumps to labeled positions, whereas in
  2188. \LangVar{} the order of evaluation is a left-to-right depth-first
  2189. traversal of the abstract syntax tree.
  2190. \fi}
  2191. \item A program in \LangVar{} can have any number of variables
  2192. whereas x86 has 16 registers and the procedure calls stack.
  2193. {\if\edition\racketEd\color{olive}
  2194. \item Variables in \LangVar{} can shadow other variables with the
  2195. same name. In x86, registers have unique names and memory locations
  2196. have unique addresses.
  2197. \fi}
  2198. \end{enumerate}
  2199. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  2200. the problem into several steps, dealing with the above differences one
  2201. at a time. Each of these steps is called a \emph{pass} of the
  2202. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2203. %
  2204. This terminology comes from the way each step passes over the AST of
  2205. the program.
  2206. %
  2207. We begin by sketching how we might implement each pass, and give them
  2208. names. We then figure out an ordering of the passes and the
  2209. input/output language for each pass. The very first pass has
  2210. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2211. its output language. In between we can choose whichever language is
  2212. most convenient for expressing the output of each pass, whether that
  2213. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2214. our own design. Finally, to implement each pass we write one
  2215. recursive function per non-terminal in the grammar of the input
  2216. language of the pass. \index{subject}{intermediate language}
  2217. \begin{description}
  2218. {\if\edition\racketEd\color{olive}
  2219. \item[\key{uniquify}] deals with the shadowing of variables by
  2220. renaming every variable to a unique name.
  2221. \fi}
  2222. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2223. of a primitive operation or function call is a variable or integer,
  2224. that is, an \emph{atomic} expression. We refer to non-atomic
  2225. expressions as \emph{complex}. This pass introduces temporary
  2226. variables to hold the results of complex
  2227. subexpressions.\index{subject}{atomic
  2228. expression}\index{subject}{complex expression}%
  2229. {\if\edition\racketEd\color{olive}
  2230. \item[\key{explicate\_control}] makes the execution order of the
  2231. program explicit. It convert the abstract syntax tree representation
  2232. into a control-flow graph in which each node contains a sequence of
  2233. statements and the edges between nodes say which nodes contain jumps
  2234. to other nodes.
  2235. \fi}
  2236. \item[\key{select\_instructions}] handles the difference between
  2237. \LangVar{} operations and x86 instructions. This pass converts each
  2238. \LangVar{} operation to a short sequence of instructions that
  2239. accomplishes the same task.
  2240. \item[\key{assign\_homes}] replaces the variables in \LangVar{} with
  2241. registers or stack locations in x86.
  2242. \end{description}
  2243. The next question is: in what order should we apply these passes? This
  2244. question can be challenging because it is difficult to know ahead of
  2245. time which orderings will be better (easier to implement, produce more
  2246. efficient code, etc.) so oftentimes trial-and-error is
  2247. involved. Nevertheless, we can try to plan ahead and make educated
  2248. choices regarding the ordering.
  2249. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2250. \key{uniquify}? The \key{uniquify} pass should come first because
  2251. \key{explicate\_control} changes all the \key{let}-bound variables to
  2252. become local variables whose scope is the entire program, which would
  2253. confuse variables with the same name.}
  2254. %
  2255. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2256. because the later removes the \key{let} form, but it is convenient to
  2257. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2258. %
  2259. \racket{The ordering of \key{uniquify} with respect to
  2260. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2261. \key{uniquify} to come first.}
  2262. The \key{select\_instructions} and \key{assign\_homes}. passes are
  2263. intertwined. In Chapter~\ref{ch:Rfun} we learn that, in x86, registers
  2264. are used for passing arguments to functions and it is preferable to
  2265. assign parameters to their corresponding registers. On the other hand,
  2266. by selecting instructions first we may run into a dead end in
  2267. \key{assign\_homes}. Recall that only one argument of an x86
  2268. instruction may be a memory access but \key{assign\_homes} might fail
  2269. to assign even one of them to a register.
  2270. %
  2271. A sophisticated approach is to iteratively repeat the two passes until
  2272. a solution is found. However, to reduce implementation complexity we
  2273. recommend a simpler approach in which \key{select\_instructions} comes
  2274. first, followed by the \key{assign\_homes}, then a third pass named
  2275. \key{patch\_instructions} that uses a reserved register to fix
  2276. outstanding problems.
  2277. \begin{figure}[tbp]
  2278. {\if\edition\racketEd\color{olive}
  2279. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2280. \node (Rvar) at (0,2) {\large \LangVar{}};
  2281. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2282. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  2283. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2284. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2285. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2286. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2287. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2288. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2289. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  2290. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-3);
  2291. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2292. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2293. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2294. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2295. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print\_x86} (x86-5);
  2296. \end{tikzpicture}
  2297. \fi}
  2298. {\if\edition\pythonEd\color{purple}
  2299. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2300. \node (Rvar) at (0,2) {\large \LangVar{}};
  2301. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2302. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2303. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2304. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2305. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2306. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-2);
  2307. \path[->,bend right=15] (Rvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2308. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2309. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2310. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86} (x86-4);
  2311. \end{tikzpicture}
  2312. \fi}
  2313. \caption{Diagram of the passes for compiling \LangVar{}. }
  2314. \label{fig:Rvar-passes}
  2315. \end{figure}
  2316. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  2317. passes and identifies the input and output language of each pass. The
  2318. last pass, \key{print\_x86}, converts from the abstract syntax of
  2319. \LangXInt{} to the concrete syntax.
  2320. %
  2321. \racket{In the following two sections we discuss the \LangCVar{}
  2322. intermediate language and the \LangXVar{} dialect of x86.}
  2323. %
  2324. \python{In the following section we discuss the \LangXVar{} dialect of
  2325. x86.}
  2326. %
  2327. The remainder of this chapter gives hints regarding the implementation
  2328. of each of the compiler passes in Figure~\ref{fig:Rvar-passes}.
  2329. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2330. %% are programs that are still in the \LangVar{} language, though the
  2331. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2332. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  2333. %% %
  2334. %% The output of \code{explicate\_control} is in an intermediate language
  2335. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2336. %% syntax, which we introduce in the next section. The
  2337. %% \key{select-instruction} pass translates from \LangCVar{} to
  2338. %% \LangXVar{}. The \key{assign-homes} and
  2339. %% \key{patch-instructions}
  2340. %% passes input and output variants of x86 assembly.
  2341. {\if\edition\racketEd\color{olive}
  2342. \subsection{The \LangCVar{} Intermediate Language}
  2343. The output of \code{explicate\_control} is similar to the $C$
  2344. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2345. categories for expressions and statements, so we name it \LangCVar{}. The
  2346. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2347. (The concrete syntax for \LangCVar{} is in the Appendix,
  2348. Figure~\ref{fig:c0-concrete-syntax}.)
  2349. %
  2350. The \LangCVar{} language supports the same operators as \LangVar{} but
  2351. the arguments of operators are restricted to atomic
  2352. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2353. assignment statements which can be executed in sequence using the
  2354. \key{Seq} form. A sequence of statements always ends with
  2355. \key{Return}, a guarantee that is baked into the grammar rules for
  2356. \itm{tail}. The naming of this non-terminal comes from the term
  2357. \emph{tail position}\index{subject}{tail position}, which refers to an
  2358. expression that is the last one to execute within a function.
  2359. A \LangCVar{} program consists of a control-flow graph represented as
  2360. an alist mapping labels to tails. This is more general than necessary
  2361. for the present chapter, as we do not yet introduce \key{goto} for
  2362. jumping to labels, but it saves us from having to change the syntax in
  2363. Chapter~\ref{ch:Rif}. For now there will be just one label,
  2364. \key{start}, and the whole program is its tail.
  2365. %
  2366. The $\itm{info}$ field of the \key{CProgram} form, after the
  2367. \code{explicate\_control} pass, contains a mapping from the symbol
  2368. \key{locals} to a list of variables, that is, a list of all the
  2369. variables used in the program. At the start of the program, these
  2370. variables are uninitialized; they become initialized on their first
  2371. assignment.
  2372. \begin{figure}[tbp]
  2373. \fbox{
  2374. \begin{minipage}{0.96\textwidth}
  2375. \[
  2376. \begin{array}{lcl}
  2377. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2378. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2379. &\MID& \ADD{\Atm}{\Atm}\\
  2380. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2381. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} \\
  2382. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2383. \end{array}
  2384. \]
  2385. \end{minipage}
  2386. }
  2387. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2388. \label{fig:c0-syntax}
  2389. \end{figure}
  2390. The definitional interpreter for \LangCVar{} is in the support code,
  2391. in the file \code{interp-Cvar.rkt}.
  2392. \fi}
  2393. \section{The \LangXVar{} dialect}
  2394. The \LangXVar{} language is the output of the pass
  2395. \key{select\_instructions}. It extends \LangXInt{} with an unbounded
  2396. number of program-scope variables and removes the restrictions
  2397. regarding instruction arguments.
  2398. {\if\edition\racketEd\color{olive}
  2399. \section{Uniquify Variables}
  2400. \label{sec:uniquify-Rvar}
  2401. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2402. programs in which every \key{let} binds a unique variable name. For
  2403. example, the \code{uniquify} pass should translate the program on the
  2404. left into the program on the right.
  2405. \begin{transformation}
  2406. \begin{lstlisting}
  2407. (let ([x 32])
  2408. (+ (let ([x 10]) x) x))
  2409. \end{lstlisting}
  2410. \compilesto
  2411. \begin{lstlisting}
  2412. (let ([x.1 32])
  2413. (+ (let ([x.2 10]) x.2) x.1))
  2414. \end{lstlisting}
  2415. \end{transformation}
  2416. The following is another example translation, this time of a program
  2417. with a \key{let} nested inside the initializing expression of another
  2418. \key{let}.
  2419. \begin{transformation}
  2420. \begin{lstlisting}
  2421. (let ([x (let ([x 4])
  2422. (+ x 1))])
  2423. (+ x 2))
  2424. \end{lstlisting}
  2425. \compilesto
  2426. \begin{lstlisting}
  2427. (let ([x.2 (let ([x.1 4])
  2428. (+ x.1 1))])
  2429. (+ x.2 2))
  2430. \end{lstlisting}
  2431. \end{transformation}
  2432. We recommend implementing \code{uniquify} by creating a structurally
  2433. recursive function named \code{uniquify-exp} that mostly just copies
  2434. an expression. However, when encountering a \key{let}, it should
  2435. generate a unique name for the variable and associate the old name
  2436. with the new name in an alist.\footnote{The Racket function
  2437. \code{gensym} is handy for generating unique variable names.} The
  2438. \code{uniquify-exp} function needs to access this alist when it gets
  2439. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2440. for the alist.
  2441. The skeleton of the \code{uniquify-exp} function is shown in
  2442. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  2443. convenient to partially apply it to an alist and then apply it to
  2444. different expressions, as in the last case for primitive operations in
  2445. Figure~\ref{fig:uniquify-Rvar}. The
  2446. %
  2447. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2448. %
  2449. form of Racket is useful for transforming each element of a list to
  2450. produce a new list.\index{subject}{for/list}
  2451. \begin{figure}[tbp]
  2452. \begin{lstlisting}
  2453. (define (uniquify-exp env)
  2454. (lambda (e)
  2455. (match e
  2456. [(Var x) ___]
  2457. [(Int n) (Int n)]
  2458. [(Let x e body) ___]
  2459. [(Prim op es)
  2460. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2461. (define (uniquify p)
  2462. (match p
  2463. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2464. \end{lstlisting}
  2465. \caption{Skeleton for the \key{uniquify} pass.}
  2466. \label{fig:uniquify-Rvar}
  2467. \end{figure}
  2468. \begin{exercise}
  2469. \normalfont % I don't like the italics for exercises. -Jeremy
  2470. Complete the \code{uniquify} pass by filling in the blanks in
  2471. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  2472. variables and for the \key{let} form in the file \code{compiler.rkt}
  2473. in the support code.
  2474. \end{exercise}
  2475. \begin{exercise}
  2476. \normalfont % I don't like the italics for exercises. -Jeremy
  2477. \label{ex:Rvar}
  2478. Create five \LangVar{} programs that exercise the most interesting
  2479. parts of the \key{uniquify} pass, that is, the programs should include
  2480. \key{let} forms, variables, and variables that shadow each other.
  2481. The five programs should be placed in the subdirectory named
  2482. \key{tests} and the file names should start with \code{var\_test\_}
  2483. followed by a unique integer and end with the file extension
  2484. \key{.rkt}.
  2485. %
  2486. The \key{run-tests.rkt} script in the support code checks whether the
  2487. output programs produce the same result as the input programs. The
  2488. script uses the \key{interp-tests} function
  2489. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2490. your \key{uniquify} pass on the example programs. The \code{passes}
  2491. parameter of \key{interp-tests} is a list that should have one entry
  2492. for each pass in your compiler. For now, define \code{passes} to
  2493. contain just one entry for \code{uniquify} as shown below.
  2494. \begin{lstlisting}
  2495. (define passes
  2496. (list (list "uniquify" uniquify interp_Rvar type-check-Rvar)))
  2497. \end{lstlisting}
  2498. Run the \key{run-tests.rkt} script in the support code to check
  2499. whether the output programs produce the same result as the input
  2500. programs.
  2501. \end{exercise}
  2502. \fi}
  2503. \section{Remove Complex Operands}
  2504. \label{sec:remove-complex-opera-Rvar}
  2505. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2506. into a restricted form in which the arguments of operations are atomic
  2507. expressions. Put another way, this pass removes complex
  2508. operands\index{subject}{complex operand}, such as the expression
  2509. \racket{\code{(- 10)}}\python{\code{-10}}
  2510. in the program below. This is accomplished by introducing a new
  2511. temporary variable, assigning the complex operand to the new
  2512. variable, and then using the new variable in place of the complex
  2513. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2514. right.
  2515. {\if\edition\racketEd\color{olive}
  2516. \begin{transformation}
  2517. % var_test_19.rkt
  2518. \begin{lstlisting}
  2519. (let ([x (+ 42 (- 10))])
  2520. (+ x 10))
  2521. \end{lstlisting}
  2522. \compilesto
  2523. \begin{lstlisting}
  2524. (let ([x (let ([tmp.1 (- 10)])
  2525. (+ 42 tmp.1))])
  2526. (+ x 10))
  2527. \end{lstlisting}
  2528. \end{transformation}
  2529. \fi}
  2530. {\if\edition\pythonEd\color{purple}
  2531. \begin{transformation}
  2532. \begin{lstlisting}
  2533. x = 42 + -10
  2534. print(x + 10)
  2535. \end{lstlisting}
  2536. \compilesto
  2537. \begin{lstlisting}
  2538. tmp_0 = -10
  2539. x = 42 + tmp_0
  2540. tmp_1 = x + 10
  2541. print(tmp_1)
  2542. \end{lstlisting}
  2543. \end{transformation}
  2544. \fi}
  2545. \begin{figure}[tp]
  2546. \centering
  2547. \fbox{
  2548. \begin{minipage}{0.96\textwidth}
  2549. {\if\edition\racketEd\color{olive}
  2550. \[
  2551. \begin{array}{rcl}
  2552. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2553. \Exp &::=& \Atm \MID \READ{} \\
  2554. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2555. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2556. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2557. \end{array}
  2558. \]
  2559. \fi}
  2560. {\if\edition\pythonEd\color{purple}
  2561. \[
  2562. \begin{array}{rcl}
  2563. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2564. \Exp{} &::=& \Atm \MID \READ{} \\
  2565. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  2566. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2567. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2568. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2569. \end{array}
  2570. \]
  2571. \fi}
  2572. \end{minipage}
  2573. }
  2574. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2575. atomic expressions, like administrative normal form (ANF).}
  2576. \label{fig:Rvar-anf-syntax}
  2577. \end{figure}
  2578. Figure~\ref{fig:Rvar-anf-syntax} presents the grammar for the output of
  2579. this pass, the language \LangVarANF{}. The only difference is that
  2580. operator arguments are restricted to be atomic expressions that are
  2581. defined by the \Atm{} non-terminal. In particular, integer constants
  2582. and variables are atomic. In the literature, restricting arguments to
  2583. be atomic expressions is one of the ideas in \emph{administrative
  2584. normal form}, or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2585. \index{subject}{administrative normal form} \index{subject}{ANF}
  2586. {\if\edition\racketEd\color{olive}
  2587. We recommend implementing this pass with two mutually recursive
  2588. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2589. \code{rco\_atom} to subexpressions that need to become atomic and to
  2590. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2591. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2592. returns an expression. The \code{rco\_atom} function returns two
  2593. things: an atomic expression and an alist mapping temporary variables to
  2594. complex subexpressions. You can return multiple things from a function
  2595. using Racket's \key{values} form and you can receive multiple things
  2596. from a function call using the \key{define-values} form.
  2597. Also, the
  2598. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2599. form is useful for applying a function to each element of a list, in
  2600. the case where the function returns multiple values.
  2601. \index{subject}{for/lists}
  2602. \fi}
  2603. %
  2604. {\if\edition\pythonEd\color{purple}
  2605. %
  2606. We recommend implementing this pass with an auxiliary method named
  2607. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2608. Boolean that specifies whether the expression needs to become atomic
  2609. or not. The \code{rco\_exp} method should return a pair consisting of
  2610. the new expression and a list of pairs, associating new temporary
  2611. variables with their initializing expressions.
  2612. %
  2613. \fi}
  2614. {\if\edition\racketEd\color{olive}
  2615. Returning to the example program with the expression \code{(+ 42 (-
  2616. 10))}, the subexpression \code{(- 10)} should be processed using the
  2617. \code{rco\_atom} function because it is an argument of the \code{+} and
  2618. therefore needs to become atomic. The output of \code{rco\_atom}
  2619. applied to \code{(- 10)} is as follows.
  2620. \begin{transformation}
  2621. \begin{lstlisting}
  2622. (- 10)
  2623. \end{lstlisting}
  2624. \compilesto
  2625. \begin{lstlisting}
  2626. tmp.1
  2627. ((tmp.1 . (- 10)))
  2628. \end{lstlisting}
  2629. \end{transformation}
  2630. \fi}
  2631. %
  2632. {\if\edition\pythonEd\color{purple}
  2633. %
  2634. Returning to the example program with the expression \code{42 + -10},
  2635. the subexpression \code{-10} should be processed using the
  2636. \code{rco\_exp} function with \code{True} as the second argument
  2637. because \code{-10} is an argument of the \code{+} operator and
  2638. therefore needs to become atomic. The output of \code{rco\_exp}
  2639. applied to \code{-10} is as follows.
  2640. \begin{transformation}
  2641. \begin{lstlisting}
  2642. -10
  2643. \end{lstlisting}
  2644. \compilesto
  2645. \begin{lstlisting}
  2646. tmp_1
  2647. [(tmp_1, -10)]
  2648. \end{lstlisting}
  2649. \end{transformation}
  2650. %
  2651. \fi}
  2652. Take special care of programs such as the following that \racket{bind
  2653. a variable to an atomic expression}\python{assign an atomic
  2654. expression to a variable}. You should leave such \racket{variable
  2655. bindings}\python{assignments} unchanged, as shown in the program on
  2656. the right\\
  2657. %
  2658. {\if\edition\racketEd\color{olive}
  2659. \begin{transformation}
  2660. % var_test_20.rkt
  2661. \begin{lstlisting}
  2662. (let ([a 42])
  2663. (let ([b a])
  2664. b))
  2665. \end{lstlisting}
  2666. \compilesto
  2667. \begin{lstlisting}
  2668. (let ([a 42])
  2669. (let ([b a])
  2670. b))
  2671. \end{lstlisting}
  2672. \end{transformation}
  2673. \fi}
  2674. {\if\edition\pythonEd\color{purple}
  2675. \begin{transformation}
  2676. \begin{lstlisting}
  2677. a = 42
  2678. b = a
  2679. print(b)
  2680. \end{lstlisting}
  2681. \compilesto
  2682. \begin{lstlisting}
  2683. a = 42
  2684. b = a
  2685. print(b)
  2686. \end{lstlisting}
  2687. \end{transformation}
  2688. \fi}
  2689. A careless implementation might produce the following output with
  2690. unnecessary temporary variables.
  2691. \begin{center}
  2692. \begin{minipage}{0.4\textwidth}
  2693. {\if\edition\racketEd\color{olive}
  2694. \begin{lstlisting}
  2695. (let ([tmp.1 42])
  2696. (let ([a tmp.1])
  2697. (let ([tmp.2 a])
  2698. (let ([b tmp.2])
  2699. b))))
  2700. \end{lstlisting}
  2701. \fi}
  2702. {\if\edition\pythonEd\color{purple}
  2703. \begin{lstlisting}
  2704. tmp_1 = 42
  2705. a = tmp_1
  2706. tmp_2 = a
  2707. b = tmp_2
  2708. print(b)
  2709. \end{lstlisting}
  2710. \fi}
  2711. \end{minipage}
  2712. \end{center}
  2713. \begin{exercise}
  2714. \normalfont
  2715. {\if\edition\racketEd\color{olive}
  2716. Implement the \code{remove\_complex\_operands} function in
  2717. \code{compiler.rkt}.
  2718. %
  2719. Create three new \LangVar{} programs that exercise the interesting
  2720. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  2721. regarding file names described in Exercise~\ref{ex:Rvar}.
  2722. %
  2723. In the \code{run-tests.rkt} script, add the following entry to the
  2724. list of \code{passes} and then run the script to test your compiler.
  2725. \begin{lstlisting}
  2726. (list "remove-complex" remove-complex-opera* interp_Rvar type-check-Rvar)
  2727. \end{lstlisting}
  2728. While debugging your compiler, it is often useful to see the
  2729. intermediate programs that are output from each pass. To print the
  2730. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2731. \code{interp-tests} in \code{run-tests.rkt}.
  2732. \fi}
  2733. %
  2734. {\if\edition\pythonEd\color{purple}
  2735. Implement the \code{remove\_complex\_operands} function in
  2736. \code{compiler.py}, creating auxiliary functions for each
  2737. non-terminal in the grammar, i.e., \code{rco\_exp}
  2738. and \code{rco\_stmt}.
  2739. \fi}
  2740. \end{exercise}
  2741. {\if\edition\pythonEd\color{purple}
  2742. \begin{exercise}
  2743. \normalfont % I don't like the italics for exercises. -Jeremy
  2744. \label{ex:Rvar}
  2745. Create five \LangVar{} programs that exercise the most interesting
  2746. parts of the Remove Complex Operands pass. The five programs should
  2747. be placed in the subdirectory named \key{tests} and the file names
  2748. should start with \code{var\_test\_} followed by a unique integer and
  2749. end with the file extension \key{.py}.
  2750. % TODO: come up with passes infrastructure for Python -Jeremy
  2751. %% The \key{run-tests.rkt} script in the support code checks whether the
  2752. %% output programs produce the same result as the input programs. The
  2753. %% script uses the \key{interp-tests} function
  2754. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2755. %% your \key{uniquify} pass on the example programs. The \code{passes}
  2756. %% parameter of \key{interp-tests} is a list that should have one entry
  2757. %% for each pass in your compiler. For now, define \code{passes} to
  2758. %% contain just one entry for \code{uniquify} as shown below.
  2759. %% \begin{lstlisting}
  2760. %% (define passes
  2761. %% (list (list "uniquify" uniquify interp_Rvar type-check-Rvar)))
  2762. %% \end{lstlisting}
  2763. Run the \key{run-tests.py} script in the support code to check
  2764. whether the output programs produce the same result as the input
  2765. programs.
  2766. \end{exercise}
  2767. \fi}
  2768. {\if\edition\racketEd\color{olive}
  2769. \section{Explicate Control}
  2770. \label{sec:explicate-control-Rvar}
  2771. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  2772. programs that make the order of execution explicit in their
  2773. syntax. For now this amounts to flattening \key{let} constructs into a
  2774. sequence of assignment statements. For example, consider the following
  2775. \LangVar{} program.\\
  2776. % var_test_11.rkt
  2777. \begin{minipage}{0.96\textwidth}
  2778. \begin{lstlisting}
  2779. (let ([y (let ([x 20])
  2780. (+ x (let ([x 22]) x)))])
  2781. y)
  2782. \end{lstlisting}
  2783. \end{minipage}\\
  2784. %
  2785. The output of the previous pass and of \code{explicate\_control} is
  2786. shown below. Recall that the right-hand-side of a \key{let} executes
  2787. before its body, so the order of evaluation for this program is to
  2788. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2789. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2790. output of \code{explicate\_control} makes this ordering explicit.
  2791. \begin{transformation}
  2792. \begin{lstlisting}
  2793. (let ([y (let ([x.1 20])
  2794. (let ([x.2 22])
  2795. (+ x.1 x.2)))])
  2796. y)
  2797. \end{lstlisting}
  2798. \compilesto
  2799. \begin{lstlisting}[language=C]
  2800. start:
  2801. x.1 = 20;
  2802. x.2 = 22;
  2803. y = (+ x.1 x.2);
  2804. return y;
  2805. \end{lstlisting}
  2806. \end{transformation}
  2807. \begin{figure}[tbp]
  2808. \begin{lstlisting}
  2809. (define (explicate-tail e)
  2810. (match e
  2811. [(Var x) ___]
  2812. [(Int n) (Return (Int n))]
  2813. [(Let x rhs body) ___]
  2814. [(Prim op es) ___]
  2815. [else (error "explicate-tail unhandled case" e)]))
  2816. (define (explicate-assign e x cont)
  2817. (match e
  2818. [(Var x) ___]
  2819. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2820. [(Let y rhs body) ___]
  2821. [(Prim op es) ___]
  2822. [else (error "explicate-assign unhandled case" e)]))
  2823. (define (explicate-control p)
  2824. (match p
  2825. [(Program info body) ___]))
  2826. \end{lstlisting}
  2827. \caption{Skeleton for the \code{explicate\_control} pass.}
  2828. \label{fig:explicate-control-Rvar}
  2829. \end{figure}
  2830. The organization of this pass depends on the notion of tail position
  2831. that we have alluded to earlier.
  2832. \begin{definition}
  2833. The following rules define when an expression is in \textbf{\emph{tail
  2834. position}}\index{subject}{tail position} for the language \LangVar{}.
  2835. \begin{enumerate}
  2836. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2837. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2838. \end{enumerate}
  2839. \end{definition}
  2840. We recommend implementing \code{explicate\_control} using two mutually
  2841. recursive functions, \code{explicate-tail} and
  2842. \code{explicate-assign}, as suggested in the skeleton code in
  2843. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2844. function should be applied to expressions in tail position whereas the
  2845. \code{explicate-assign} should be applied to expressions that occur on
  2846. the right-hand-side of a \key{let}.
  2847. %
  2848. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2849. input and produces a \Tail{} in \LangCVar{} (see
  2850. Figure~\ref{fig:c0-syntax}).
  2851. %
  2852. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2853. the variable that it is to be assigned to, and a \Tail{} in
  2854. \LangCVar{} for the code that comes after the assignment. The
  2855. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2856. The \code{explicate-assign} function is in accumulator-passing style:
  2857. the \code{cont} parameter is used for accumulating the output. This
  2858. accumulator-passing style plays an important role in how we generate
  2859. high-quality code for conditional expressions in Chapter~\ref{ch:Rif}.
  2860. \begin{exercise}\normalfont
  2861. %
  2862. Implement the \code{explicate\_control} function in
  2863. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2864. exercise the code in \code{explicate\_control}.
  2865. %
  2866. In the \code{run-tests.rkt} script, add the following entry to the
  2867. list of \code{passes} and then run the script to test your compiler.
  2868. \begin{lstlisting}
  2869. (list "explicate control" explicate-control interp_Cvar type-check-Cvar)
  2870. \end{lstlisting}
  2871. \end{exercise}
  2872. \fi}
  2873. \section{Select Instructions}
  2874. \label{sec:select-Rvar}
  2875. \index{subject}{instruction selection}
  2876. In the \code{select\_instructions} pass we begin the work of
  2877. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  2878. language of this pass is a variant of x86 that still uses variables,
  2879. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  2880. non-terminal of the \LangXInt{} abstract syntax
  2881. (Figure~\ref{fig:x86-int-ast}).
  2882. \racket{We recommend implementing the
  2883. \code{select\_instructions} with three auxiliary functions, one for
  2884. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  2885. $\Tail$.}
  2886. \python{We recommend implementing an auxiliary function
  2887. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  2888. \racket{
  2889. The cases for $\Atm$ are straightforward; variables stay
  2890. the same and integer constants change to immediates:
  2891. $\INT{n}$ changes to $\IMM{n}$.}
  2892. We consider the cases for the $\Stmt$ non-terminal, starting with
  2893. arithmetic operations. For example, consider the addition
  2894. operation. We can use the \key{addq} instruction, but it performs an
  2895. in-place update. So we could move $\itm{arg}_1$ into the left-hand
  2896. side \itm{var} and then add $\itm{arg}_2$ to \itm{var}.
  2897. \begin{transformation}
  2898. {\if\edition\racketEd\color{olive}
  2899. \begin{lstlisting}
  2900. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2901. \end{lstlisting}
  2902. \fi}
  2903. {\if\edition\pythonEd\color{purple}
  2904. \begin{lstlisting}
  2905. |$\itm{var}$| = |$\itm{arg}_1$| + |$\itm{arg}_2$|
  2906. \end{lstlisting}
  2907. \fi}
  2908. \compilesto
  2909. \begin{lstlisting}
  2910. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2911. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2912. \end{lstlisting}
  2913. \end{transformation}
  2914. There are also cases that require special care to avoid generating
  2915. needlessly complicated code. For example, if one of the arguments of
  2916. the addition is the same variable as the left-hand side of the
  2917. assignment, then there is no need for the extra move instruction. The
  2918. assignment statement can be translated into a single \key{addq}
  2919. instruction as follows.
  2920. \begin{transformation}
  2921. {\if\edition\racketEd\color{olive}
  2922. \begin{lstlisting}
  2923. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2924. \end{lstlisting}
  2925. \fi}
  2926. {\if\edition\pythonEd\color{purple}
  2927. \begin{lstlisting}
  2928. |$\itm{var}$| = |$\itm{arg}_1$| + |$\itm{var}$|
  2929. \end{lstlisting}
  2930. \fi}
  2931. \compilesto
  2932. \begin{lstlisting}
  2933. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2934. \end{lstlisting}
  2935. \end{transformation}
  2936. The \key{read} operation does not have a direct counterpart in x86
  2937. assembly, so we provide this functionality with the function
  2938. \code{read\_int} in the file \code{runtime.c}, written in
  2939. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2940. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  2941. system}, or simply the \emph{runtime} for short. When compiling your
  2942. generated x86 assembly code, you need to compile \code{runtime.c} to
  2943. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2944. \code{-c}) and link it into the executable. For our purposes of code
  2945. generation, all you need to do is translate an assignment of
  2946. \key{read} into a call to the \code{read\_int} function followed by a
  2947. move from \code{rax} to the left-hand-side variable. (Recall that the
  2948. return value of a function goes into \code{rax}.)
  2949. \begin{transformation}
  2950. {\if\edition\racketEd\color{olive}
  2951. \begin{lstlisting}
  2952. |$\itm{var}$| = (read);
  2953. \end{lstlisting}
  2954. \fi}
  2955. {\if\edition\pythonEd\color{purple}
  2956. \begin{lstlisting}
  2957. |$\itm{var}$| = input_int();
  2958. \end{lstlisting}
  2959. \fi}
  2960. \compilesto
  2961. \begin{lstlisting}
  2962. callq read_int
  2963. movq %rax, |$\itm{var}$|
  2964. \end{lstlisting}
  2965. \end{transformation}
  2966. {\if\edition\racketEd\color{olive}
  2967. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2968. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2969. assignment to the \key{rax} register followed by a jump to the
  2970. conclusion of the program (so the conclusion needs to be labeled).
  2971. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2972. recursively and then append the resulting instructions.
  2973. \fi}
  2974. \begin{exercise}
  2975. \normalfont
  2976. {\if\edition\racketEd\color{olive}
  2977. Implement the \key{select-instructions} pass in
  2978. \code{compiler.rkt}. Create three new example programs that are
  2979. designed to exercise all of the interesting cases in this pass.
  2980. %
  2981. In the \code{run-tests.rkt} script, add the following entry to the
  2982. list of \code{passes} and then run the script to test your compiler.
  2983. \begin{lstlisting}
  2984. (list "instruction selection" select-instructions interp_pseudo-x86-0)
  2985. \end{lstlisting}
  2986. \fi}
  2987. {\if\edition\pythonEd\color{purple}
  2988. Implement the \key{select\_instructions} pass in
  2989. \code{compiler.py}. Create three new example programs that are
  2990. designed to exercise all of the interesting cases in this pass.
  2991. Run the \code{run-tests.py} script to to check
  2992. whether the output programs produce the same result as the input
  2993. programs.
  2994. \fi}
  2995. \end{exercise}
  2996. \section{Assign Homes}
  2997. \label{sec:assign-Rvar}
  2998. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  2999. \LangXVar{} programs that no longer use program variables.
  3000. Thus, the \key{assign-homes} pass is responsible for placing all of
  3001. the program variables in registers or on the stack. For runtime
  3002. efficiency, it is better to place variables in registers, but as there
  3003. are only 16 registers, some programs must necessarily resort to
  3004. placing some variables on the stack. In this chapter we focus on the
  3005. mechanics of placing variables on the stack. We study an algorithm for
  3006. placing variables in registers in
  3007. Chapter~\ref{ch:register-allocation-Rvar}.
  3008. Consider again the following \LangVar{} program from
  3009. Section~\ref{sec:remove-complex-opera-Rvar}.
  3010. % var_test_20.rkt
  3011. {\if\edition\racketEd\color{olive}
  3012. \begin{lstlisting}
  3013. (let ([a 42])
  3014. (let ([b a])
  3015. b))
  3016. \end{lstlisting}
  3017. \fi}
  3018. {\if\edition\pythonEd\color{purple}
  3019. \begin{lstlisting}
  3020. a = 42
  3021. b = a
  3022. print(b)
  3023. \end{lstlisting}
  3024. \fi}
  3025. The output of \code{select\_instructions} is shown on the left and the
  3026. output of \code{assign\_homes} on the right. In this example, we
  3027. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  3028. variable \code{b} to location \code{-16(\%rbp)}.
  3029. \begin{transformation}
  3030. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3031. start:
  3032. movq $42, a
  3033. movq a, b
  3034. movq b, %rax
  3035. jmp conclusion
  3036. \end{lstlisting}
  3037. \compilesto
  3038. %stack-space: 16
  3039. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3040. start:
  3041. movq $42, -8(%rbp)
  3042. movq -8(%rbp), -16(%rbp)
  3043. movq -16(%rbp), %rax
  3044. jmp conclusion
  3045. \end{lstlisting}
  3046. \end{transformation}
  3047. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3048. \code{X86Program} node is an alist mapping all the variables in the
  3049. program to their types (for now just \code{Integer}). The
  3050. \code{assign\_homes} pass should replace all uses of those variables
  3051. with stack locations. As an aside, the \code{locals-types} entry is
  3052. computed by \code{type-check-Cvar} in the support code, which installs
  3053. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  3054. be propagated to the \code{X86Program} node.}
  3055. %
  3056. \python{The \code{assign\_homes} pass should replace all uses of
  3057. variables with stack locations.}
  3058. %
  3059. In the process of assigning variables to stack locations, it is
  3060. convenient for you to compute and store the size of the frame (in
  3061. bytes) in%
  3062. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3063. %
  3064. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3065. which is needed later to generate the conclusion of the \code{main}
  3066. procedure. The x86-64 standard requires the frame size to be a
  3067. multiple of 16 bytes.\index{subject}{frame}
  3068. % TODO: store the number of variables instead? -Jeremy
  3069. \begin{exercise}\normalfont
  3070. Implement the \key{assign\_homes} pass in
  3071. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3072. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  3073. \Block{}. We recommend that the auxiliary functions take an extra
  3074. parameter that maps variable names to homes (stack locations for now).
  3075. %
  3076. {\if\edition\racketEd\color{olive}
  3077. In the \code{run-tests.rkt} script, add the following entry to the
  3078. list of \code{passes} and then run the script to test your compiler.
  3079. \begin{lstlisting}
  3080. (list "assign homes" assign-homes interp_x86-0)
  3081. \end{lstlisting}
  3082. \fi}
  3083. {\if\edition\pythonEd\color{purple}
  3084. Run the \code{run-tests.py} script to to check
  3085. whether the output programs produce the same result as the input
  3086. programs.
  3087. \fi}
  3088. \end{exercise}
  3089. \section{Patch Instructions}
  3090. \label{sec:patch-s0}
  3091. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3092. \LangXInt{} by making sure that each instruction adheres to the
  3093. restriction that at most one argument of an instruction may be a
  3094. memory reference.
  3095. We return to the following example.\\
  3096. \begin{minipage}{0.5\textwidth}
  3097. % var_test_20.rkt
  3098. {\if\edition\racketEd\color{olive}
  3099. \begin{lstlisting}
  3100. (let ([a 42])
  3101. (let ([b a])
  3102. b))
  3103. \end{lstlisting}
  3104. \fi}
  3105. {\if\edition\pythonEd\color{purple}
  3106. \begin{lstlisting}
  3107. a = 42
  3108. b = a
  3109. print(b)
  3110. \end{lstlisting}
  3111. \fi}
  3112. \end{minipage}\\
  3113. The \key{assign\_homes} pass produces the following translation. \\
  3114. \begin{minipage}{0.5\textwidth}
  3115. {\if\edition\racketEd\color{olive}
  3116. \begin{lstlisting}
  3117. movq $42, -8(%rbp)
  3118. movq -8(%rbp), -16(%rbp)
  3119. movq -16(%rbp), %rax
  3120. \end{lstlisting}
  3121. \fi}
  3122. {\if\edition\pythonEd\color{purple}
  3123. \begin{lstlisting}
  3124. movq 42, -8(%rbp)
  3125. movq -8(%rbp), -16(%rbp)
  3126. movq -16(%rbp), %rdi
  3127. callq print_int
  3128. \end{lstlisting}
  3129. \fi}
  3130. \end{minipage}\\
  3131. The second \key{movq} instruction is problematic because both
  3132. arguments are stack locations. We suggest fixing this problem by
  3133. moving from the source location to the register \key{rax} and then
  3134. from \key{rax} to the destination location, as follows.
  3135. \begin{lstlisting}
  3136. movq -8(%rbp), %rax
  3137. movq %rax, -16(%rbp)
  3138. \end{lstlisting}
  3139. \begin{exercise}
  3140. \normalfont Implement the \key{patch\_instructions} pass in
  3141. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3142. Create three new example programs that are
  3143. designed to exercise all of the interesting cases in this pass.
  3144. %
  3145. {\if\edition\racketEd\color{olive}
  3146. In the \code{run-tests.rkt} script, add the following entry to the
  3147. list of \code{passes} and then run the script to test your compiler.
  3148. \begin{lstlisting}
  3149. (list "patch instructions" patch-instructions interp_x86-0)
  3150. \end{lstlisting}
  3151. \fi}
  3152. {\if\edition\pythonEd\color{purple}
  3153. Run the \code{run-tests.py} script to to check
  3154. whether the output programs produce the same result as the input
  3155. programs.
  3156. \fi}
  3157. \end{exercise}
  3158. \section{Print x86}
  3159. \label{sec:print-x86}
  3160. The last step of the compiler from \LangVar{} to x86 is to convert the
  3161. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  3162. string representation (defined in
  3163. Figure~\ref{fig:x86-int-concrete}). \racket{The Racket \key{format} and
  3164. \key{string-append} functions are useful in this regard.} The main work
  3165. that this step needs to perform is to create the \key{main} function
  3166. and the standard instructions for its prelude and conclusion, as shown
  3167. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  3168. know the amount of space needed for the stack frame, which you can
  3169. obtain from the \racket{\code{stack-space} entry in the $\itm{info}$ field}
  3170. \python{\code{stack\_space} field}
  3171. of the \key{X86Program} node.
  3172. When running on Mac OS X, your compiler should prefix an underscore to
  3173. labels like \key{main}. \racket{The Racket call \code{(system-type 'os)} is
  3174. useful for determining which operating system the compiler is running
  3175. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3176. \python{The Python \code{platform} library includes a \code{system()} function
  3177. that returns \code{'Linux'}, \code{'Windows'}, or \code{'Darwin'} (for Mac).}
  3178. \begin{exercise}\normalfont
  3179. %
  3180. Implement the \key{print\_x86} pass in \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3181. %
  3182. {\if\edition\racketEd\color{olive}
  3183. In the \code{run-tests.rkt} script, add the following entry to the
  3184. list of \code{passes} and then run the script to test your compiler.
  3185. \begin{lstlisting}
  3186. (list "print x86" print-x86 #f)
  3187. \end{lstlisting}
  3188. %
  3189. Uncomment the call to the \key{compiler-tests} function
  3190. (Appendix~\ref{appendix:utilities}), which tests your complete
  3191. compiler by executing the generated x86 code. Compile the provided
  3192. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  3193. script to test your compiler.
  3194. \fi}
  3195. {\if\edition\pythonEd\color{purple}
  3196. Run the \code{run-tests.py} script to to check
  3197. whether the output programs produce the same result as the input
  3198. programs.
  3199. \fi}
  3200. \end{exercise}
  3201. \section{Challenge: Partial Evaluator for \LangVar{}}
  3202. \label{sec:pe-Rvar}
  3203. \index{subject}{partial evaluation}
  3204. This section describes optional challenge exercises that involve
  3205. adapting and improving the partial evaluator for \LangInt{} that was
  3206. introduced in Section~\ref{sec:partial-evaluation}.
  3207. \begin{exercise}\label{ex:pe-Rvar}
  3208. \normalfont
  3209. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3210. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3211. instead of \LangInt{} programs. Recall that \LangVar{} adds
  3212. \racket{\key{let} binding}\python{assignment}
  3213. and variables to the \LangInt{} language, so you will need to add cases for
  3214. them in the \code{pe\_exp} \racket{function}\python{and \code{pe\_stmt functions}}. Once complete, add the partial
  3215. evaluation pass to the front of your compiler and make sure that your
  3216. compiler still passes all of the tests.
  3217. \end{exercise}
  3218. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  3219. \begin{exercise}
  3220. \normalfont
  3221. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3222. \code{pe\_add} auxiliary functions with functions that know more about
  3223. arithmetic. For example, your partial evaluator should translate
  3224. {\if\edition\racketEd\color{olive}
  3225. \[
  3226. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3227. \code{(+ 2 (read))}
  3228. \]
  3229. \fi}
  3230. {\if\edition\pythonEd\color{purple}
  3231. \[
  3232. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3233. \code{2 + input\_int()}
  3234. \]
  3235. \fi}
  3236. To accomplish this, the \code{pe\_exp} function should produce output
  3237. in the form of the $\itm{residual}$ non-terminal of the following
  3238. grammar. The idea is that when processing an addition expression, we
  3239. can always produce either 1) an integer constant, 2) an addition
  3240. expression with an integer constant on the left-hand side but not the
  3241. right-hand side, or 3) or an addition expression in which neither
  3242. subexpression is a constant.
  3243. {\if\edition\racketEd\color{olive}
  3244. \[
  3245. \begin{array}{lcl}
  3246. \itm{inert} &::=& \Var
  3247. \MID \LP\key{read}\RP
  3248. \MID \LP\key{-} ~\Var\RP
  3249. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3250. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3251. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3252. \itm{residual} &::=& \Int
  3253. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3254. \MID \itm{inert}
  3255. \end{array}
  3256. \]
  3257. \fi}
  3258. {\if\edition\pythonEd\color{purple}
  3259. \[
  3260. \begin{array}{lcl}
  3261. \itm{inert} &::=& \Var
  3262. \MID \key{input\_int}\LP\RP
  3263. \MID \key{-} \Var
  3264. \MID \key{-} \key{input\_int}\LP\RP
  3265. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3266. \itm{residual} &::=& \Int
  3267. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3268. \MID \itm{inert}
  3269. \end{array}
  3270. \]
  3271. \fi}
  3272. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3273. inputs are $\itm{residual}$ expressions and they should return
  3274. $\itm{residual}$ expressions. Once the improvements are complete,
  3275. make sure that your compiler still passes all of the tests. After
  3276. all, fast code is useless if it produces incorrect results!
  3277. \end{exercise}
  3278. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3279. \chapter{Register Allocation}
  3280. \label{ch:register-allocation-Rvar}
  3281. \index{subject}{register allocation}
  3282. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  3283. stack. In this Chapter we learn how to improve the performance of the
  3284. generated code by placing some variables into registers. The CPU can
  3285. access a register in a single cycle, whereas accessing the stack can
  3286. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3287. serves as a running example. The source program is on the left and the
  3288. output of instruction selection is on the right. The program is almost
  3289. in the x86 assembly language but it still uses variables.
  3290. \begin{figure}
  3291. \begin{minipage}{0.45\textwidth}
  3292. Example \LangVar{} program:
  3293. % var_test_28.rkt
  3294. {\if\edition\racketEd\color{olive}
  3295. \begin{lstlisting}
  3296. (let ([v 1])
  3297. (let ([w 42])
  3298. (let ([x (+ v 7)])
  3299. (let ([y x])
  3300. (let ([z (+ x w)])
  3301. (+ z (- y)))))))
  3302. \end{lstlisting}
  3303. \fi}
  3304. {\if\edition\pythonEd\color{purple}
  3305. \begin{lstlisting}
  3306. v = 1
  3307. w = 42
  3308. x = v + 7
  3309. y = x
  3310. z = x + w
  3311. print(z + (- y))
  3312. \end{lstlisting}
  3313. \fi}
  3314. \end{minipage}
  3315. \begin{minipage}{0.45\textwidth}
  3316. After instruction selection:
  3317. {\if\edition\racketEd\color{olive}
  3318. \begin{lstlisting}
  3319. locals-types:
  3320. x : Integer, y : Integer,
  3321. z : Integer, t : Integer,
  3322. v : Integer, w : Integer
  3323. start:
  3324. movq $1, v
  3325. movq $42, w
  3326. movq v, x
  3327. addq $7, x
  3328. movq x, y
  3329. movq x, z
  3330. addq w, z
  3331. movq y, t
  3332. negq t
  3333. movq z, %rax
  3334. addq t, %rax
  3335. jmp conclusion
  3336. \end{lstlisting}
  3337. \fi}
  3338. {\if\edition\pythonEd\color{purple}
  3339. \begin{lstlisting}
  3340. movq $1, v
  3341. movq $42, w
  3342. movq v, x
  3343. addq $7, x
  3344. movq x, y
  3345. movq x, z
  3346. addq w, z
  3347. movq y, tmp_0
  3348. negq tmp_0
  3349. movq z, tmp_1
  3350. addq tmp_0, tmp_1
  3351. movq tmp_1, %rdi
  3352. callq print_int
  3353. \end{lstlisting}
  3354. \fi}
  3355. \end{minipage}
  3356. \caption{A running example for register allocation.}
  3357. \label{fig:reg-eg}
  3358. \end{figure}
  3359. The goal of register allocation is to fit as many variables into
  3360. registers as possible. Some programs have more variables than
  3361. registers so we cannot always map each variable to a different
  3362. register. Fortunately, it is common for different variables to be
  3363. needed during different periods of time during program execution, and
  3364. in such cases several variables can be mapped to the same register.
  3365. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3366. After the variable \code{x} is moved to \code{z} it is no longer
  3367. needed. Variable \code{z}, on the other hand, is used only after this
  3368. point, so \code{x} and \code{z} could share the same register. The
  3369. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  3370. where a variable is needed. Once we have that information, we compute
  3371. which variables are needed at the same time, i.e., which ones
  3372. \emph{interfere} with each other, and represent this relation as an
  3373. undirected graph whose vertices are variables and edges indicate when
  3374. two variables interfere (Section~\ref{sec:build-interference}). We
  3375. then model register allocation as a graph coloring problem
  3376. (Section~\ref{sec:graph-coloring}).
  3377. If we run out of registers despite these efforts, we place the
  3378. remaining variables on the stack, similar to what we did in
  3379. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  3380. for assigning a variable to a stack location. The decision to spill a
  3381. variable is handled as part of the graph coloring process
  3382. (Section~\ref{sec:graph-coloring}).
  3383. We make the simplifying assumption that each variable is assigned to
  3384. one location (a register or stack address). A more sophisticated
  3385. approach is to assign a variable to one or more locations in different
  3386. regions of the program. For example, if a variable is used many times
  3387. in short sequence and then only used again after many other
  3388. instructions, it could be more efficient to assign the variable to a
  3389. register during the initial sequence and then move it to the stack for
  3390. the rest of its lifetime. We refer the interested reader to
  3391. \citet{Cooper:2011aa} for more information about that approach.
  3392. % discuss prioritizing variables based on how much they are used.
  3393. \section{Registers and Calling Conventions}
  3394. \label{sec:calling-conventions}
  3395. \index{subject}{calling conventions}
  3396. As we perform register allocation, we need to be aware of the
  3397. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3398. functions calls are performed in x86.
  3399. %
  3400. Even though \LangVar{} does not include programmer-defined functions,
  3401. our generated code includes a \code{main} function that is called by
  3402. the operating system and our generated code contains calls to the
  3403. \code{read\_int} function.
  3404. Function calls require coordination between two pieces of code that
  3405. may be written by different programmers or generated by different
  3406. compilers. Here we follow the System V calling conventions that are
  3407. used by the GNU C compiler on Linux and
  3408. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3409. %
  3410. The calling conventions include rules about how functions share the
  3411. use of registers. In particular, the caller is responsible for freeing
  3412. up some registers prior to the function call for use by the callee.
  3413. These are called the \emph{caller-saved registers}
  3414. \index{subject}{caller-saved registers}
  3415. and they are
  3416. \begin{lstlisting}
  3417. rax rcx rdx rsi rdi r8 r9 r10 r11
  3418. \end{lstlisting}
  3419. On the other hand, the callee is responsible for preserving the values
  3420. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3421. which are
  3422. \begin{lstlisting}
  3423. rsp rbp rbx r12 r13 r14 r15
  3424. \end{lstlisting}
  3425. We can think about this caller/callee convention from two points of
  3426. view, the caller view and the callee view:
  3427. \begin{itemize}
  3428. \item The caller should assume that all the caller-saved registers get
  3429. overwritten with arbitrary values by the callee. On the other hand,
  3430. the caller can safely assume that all the callee-saved registers
  3431. contain the same values after the call that they did before the
  3432. call.
  3433. \item The callee can freely use any of the caller-saved registers.
  3434. However, if the callee wants to use a callee-saved register, the
  3435. callee must arrange to put the original value back in the register
  3436. prior to returning to the caller. This can be accomplished by saving
  3437. the value to the stack in the prelude of the function and restoring
  3438. the value in the conclusion of the function.
  3439. \end{itemize}
  3440. In x86, registers are also used for passing arguments to a function
  3441. and for the return value. In particular, the first six arguments to a
  3442. function are passed in the following six registers, in this order.
  3443. \begin{lstlisting}
  3444. rdi rsi rdx rcx r8 r9
  3445. \end{lstlisting}
  3446. If there are more than six arguments, then the convention is to use
  3447. space on the frame of the caller for the rest of the
  3448. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3449. need more than six arguments. For now, the only function we care about
  3450. is \code{read\_int} and it takes zero arguments.
  3451. %
  3452. The register \code{rax} is used for the return value of a function.
  3453. The next question is how these calling conventions impact register
  3454. allocation. Consider the \LangVar{} program in
  3455. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3456. example from the caller point of view and then from the callee point
  3457. of view.
  3458. The program makes two calls to the \code{read} function. Also, the
  3459. variable \code{x} is in use during the second call to \code{read}, so
  3460. we need to make sure that the value in \code{x} does not get
  3461. accidentally wiped out by the call to \code{read}. One obvious
  3462. approach is to save all the values in caller-saved registers to the
  3463. stack prior to each function call, and restore them after each
  3464. call. That way, if the register allocator chooses to assign \code{x}
  3465. to a caller-saved register, its value will be preserved across the
  3466. call to \code{read}. However, saving and restoring to the stack is
  3467. relatively slow. If \code{x} is not used many times, it may be better
  3468. to assign \code{x} to a stack location in the first place. Or better
  3469. yet, if we can arrange for \code{x} to be placed in a callee-saved
  3470. register, then it won't need to be saved and restored during function
  3471. calls.
  3472. The approach that we recommend for variables that are in use during a
  3473. function call is to either assign them to callee-saved registers or to
  3474. spill them to the stack. On the other hand, for variables that are not
  3475. in use during a function call, we try the following alternatives in
  3476. order 1) look for an available caller-saved register (to leave room
  3477. for other variables in the callee-saved register), 2) look for a
  3478. callee-saved register, and 3) spill the variable to the stack.
  3479. It is straightforward to implement this approach in a graph coloring
  3480. register allocator. First, we know which variables are in use during
  3481. every function call because we compute that information for every
  3482. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  3483. build the interference graph (Section~\ref{sec:build-interference}),
  3484. we can place an edge between each of these variables and the
  3485. caller-saved registers in the interference graph. This will prevent
  3486. the graph coloring algorithm from assigning those variables to
  3487. caller-saved registers.
  3488. Returning to the example in
  3489. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3490. generated x86 code on the right-hand side, focusing on the
  3491. \code{start} block. Notice that variable \code{x} is assigned to
  3492. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  3493. place during the second call to \code{read\_int}. Next, notice that
  3494. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  3495. because there are no function calls in the remainder of the block.
  3496. Next we analyze the example from the callee point of view, focusing on
  3497. the prelude and conclusion of the \code{main} function. As usual the
  3498. prelude begins with saving the \code{rbp} register to the stack and
  3499. setting the \code{rbp} to the current stack pointer. We now know why
  3500. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3501. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3502. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3503. (\code{x}). The other callee-saved registers are not saved in the
  3504. prelude because they are not used. The prelude subtracts 8 bytes from
  3505. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3506. conclusion, we see that \code{rbx} is restored from the stack with a
  3507. \code{popq} instruction.
  3508. \index{subject}{prelude}\index{subject}{conclusion}
  3509. \begin{figure}[tp]
  3510. \begin{minipage}{0.45\textwidth}
  3511. Example \LangVar{} program:
  3512. %var_test_14.rkt
  3513. {\if\edition\racketEd\color{olive}
  3514. \begin{lstlisting}
  3515. (let ([x (read)])
  3516. (let ([y (read)])
  3517. (+ (+ x y) 42)))
  3518. \end{lstlisting}
  3519. \fi}
  3520. {\if\edition\pythonEd\color{purple}
  3521. \begin{lstlisting}
  3522. x = input_int()
  3523. y = input_int()
  3524. print((x + y) + 42)
  3525. \end{lstlisting}
  3526. \fi}
  3527. \end{minipage}
  3528. \begin{minipage}{0.45\textwidth}
  3529. Generated x86 assembly:
  3530. {\if\edition\racketEd\color{olive}
  3531. \begin{lstlisting}
  3532. start:
  3533. callq read_int
  3534. movq %rax, %rbx
  3535. callq read_int
  3536. movq %rax, %rcx
  3537. addq %rcx, %rbx
  3538. movq %rbx, %rax
  3539. addq $42, %rax
  3540. jmp _conclusion
  3541. .globl main
  3542. main:
  3543. pushq %rbp
  3544. movq %rsp, %rbp
  3545. pushq %rbx
  3546. subq $8, %rsp
  3547. jmp start
  3548. conclusion:
  3549. addq $8, %rsp
  3550. popq %rbx
  3551. popq %rbp
  3552. retq
  3553. \end{lstlisting}
  3554. \fi}
  3555. {\if\edition\pythonEd\color{purple}
  3556. \begin{lstlisting}
  3557. .globl main
  3558. main:
  3559. pushq %rbp
  3560. movq %rsp, %rbp
  3561. pushq %rbx
  3562. subq $8, %rsp
  3563. callq read_int
  3564. movq %rax, %rbx
  3565. callq read_int
  3566. movq %rax, %rcx
  3567. movq %rbx, %rdx
  3568. addq %rcx, %rdx
  3569. movq %rdx, %rcx
  3570. addq $42, %rcx
  3571. movq %rcx, %rdi
  3572. callq print_int
  3573. addq $8, %rsp
  3574. popq %rbx
  3575. popq %rbp
  3576. retq
  3577. \end{lstlisting}
  3578. \fi}
  3579. \end{minipage}
  3580. \caption{An example with function calls.}
  3581. \label{fig:example-calling-conventions}
  3582. \end{figure}
  3583. %\clearpage
  3584. \section{Liveness Analysis}
  3585. \label{sec:liveness-analysis-Rvar}
  3586. \index{subject}{liveness analysis}
  3587. The \code{uncover\_live} \racket{pass}\python{function}
  3588. performs \emph{liveness analysis}, that
  3589. is, it discovers which variables are in-use in different regions of a
  3590. program.
  3591. %
  3592. A variable or register is \emph{live} at a program point if its
  3593. current value is used at some later point in the program. We
  3594. refer to variables and registers collectively as \emph{locations}.
  3595. %
  3596. Consider the following code fragment in which there are two writes to
  3597. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3598. \begin{center}
  3599. \begin{minipage}{0.96\textwidth}
  3600. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3601. movq $5, a
  3602. movq $30, b
  3603. movq a, c
  3604. movq $10, b
  3605. addq b, c
  3606. \end{lstlisting}
  3607. \end{minipage}
  3608. \end{center}
  3609. The answer is no because \code{a} is live from line 1 to 3 and
  3610. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3611. line 2 is never used because it is overwritten (line 4) before the
  3612. next read (line 5).
  3613. The live locations can be computed by traversing the instruction
  3614. sequence back to front (i.e., backwards in execution order). Let
  3615. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3616. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3617. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3618. locations before instruction $I_k$.
  3619. \racket{We recommend representing these
  3620. sets with the Racket \code{set} data structure described in
  3621. Figure~\ref{fig:set}.}
  3622. \python{We recommend representing these sets with the Python
  3623. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3624. data structure.}
  3625. {\if\edition\racketEd\color{olive}
  3626. \begin{figure}[tp]
  3627. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3628. \small
  3629. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3630. A \emph{set} is an unordered collection of elements without duplicates.
  3631. Here are some of the operations defined on sets.
  3632. \index{subject}{set}
  3633. \begin{description}
  3634. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3635. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3636. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3637. difference of the two sets.
  3638. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3639. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3640. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3641. \end{description}
  3642. \end{tcolorbox}
  3643. %\end{wrapfigure}
  3644. \caption{The \code{set} data structure.}
  3645. \label{fig:set}
  3646. \end{figure}
  3647. \fi}
  3648. The live locations after an instruction are always the same as the
  3649. live locations before the next instruction.
  3650. \index{subject}{live-after} \index{subject}{live-before}
  3651. \begin{equation} \label{eq:live-after-before-next}
  3652. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3653. \end{equation}
  3654. To start things off, there are no live locations after the last
  3655. instruction, so
  3656. \begin{equation}\label{eq:live-last-empty}
  3657. L_{\mathsf{after}}(n) = \emptyset
  3658. \end{equation}
  3659. We then apply the following rule repeatedly, traversing the
  3660. instruction sequence back to front.
  3661. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3662. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3663. \end{equation}
  3664. where $W(k)$ are the locations written to by instruction $I_k$ and
  3665. $R(k)$ are the locations read by instruction $I_k$.
  3666. {\if\edition\racketEd\color{olive}
  3667. There is a special case for \code{jmp} instructions. The locations
  3668. that are live before a \code{jmp} should be the locations in
  3669. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3670. maintaining an alist named \code{label->live} that maps each label to
  3671. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3672. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3673. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3674. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3675. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3676. \fi}
  3677. Let us walk through the above example, applying these formulas
  3678. starting with the instruction on line 5. We collect the answers in
  3679. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3680. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3681. instruction (formula~\ref{eq:live-last-empty}). The
  3682. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3683. because it reads from variables \code{b} and \code{c}
  3684. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3685. \[
  3686. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3687. \]
  3688. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3689. the live-before set from line 5 to be the live-after set for this
  3690. instruction (formula~\ref{eq:live-after-before-next}).
  3691. \[
  3692. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3693. \]
  3694. This move instruction writes to \code{b} and does not read from any
  3695. variables, so we have the following live-before set
  3696. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3697. \[
  3698. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3699. \]
  3700. The live-before for instruction \code{movq a, c}
  3701. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3702. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3703. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3704. variable that is not live and does not read from a variable.
  3705. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3706. because it writes to variable \code{a}.
  3707. \begin{figure}[tbp]
  3708. \begin{minipage}{0.45\textwidth}
  3709. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3710. movq $5, a
  3711. movq $30, b
  3712. movq a, c
  3713. movq $10, b
  3714. addq b, c
  3715. \end{lstlisting}
  3716. \end{minipage}
  3717. \vrule\hspace{10pt}
  3718. \begin{minipage}{0.45\textwidth}
  3719. \begin{align*}
  3720. L_{\mathsf{before}}(1)= \emptyset,
  3721. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3722. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3723. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3724. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3725. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3726. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3727. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3728. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3729. L_{\mathsf{after}}(5)= \emptyset
  3730. \end{align*}
  3731. \end{minipage}
  3732. \caption{Example output of liveness analysis on a short example.}
  3733. \label{fig:liveness-example-0}
  3734. \end{figure}
  3735. \begin{exercise}\normalfont
  3736. Perform liveness analysis on the running example in
  3737. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3738. sets for each instruction. Compare your answers to the solution
  3739. shown in Figure~\ref{fig:live-eg}.
  3740. \end{exercise}
  3741. \begin{figure}[tp]
  3742. \hspace{20pt}
  3743. \begin{minipage}{0.45\textwidth}
  3744. {\if\edition\racketEd\color{olive}
  3745. \begin{lstlisting}
  3746. |$\{\ttm{rsp}\}$|
  3747. movq $1, v
  3748. |$\{\ttm{v},\ttm{rsp}\}$|
  3749. movq $42, w
  3750. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3751. movq v, x
  3752. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3753. addq $7, x
  3754. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3755. movq x, y
  3756. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3757. movq x, z
  3758. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3759. addq w, z
  3760. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3761. movq y, t
  3762. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3763. negq t
  3764. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3765. movq z, %rax
  3766. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3767. addq t, %rax
  3768. |$\{\ttm{rax},\ttm{rsp}\}$|
  3769. jmp conclusion
  3770. \end{lstlisting}
  3771. \fi}
  3772. {\if\edition\pythonEd\color{purple}
  3773. \begin{lstlisting}
  3774. movq $1, v
  3775. |$\{\ttm{v}\}$|
  3776. movq $42, w
  3777. |$\{\ttm{w}, \ttm{v}\}$|
  3778. movq v, x
  3779. |$\{\ttm{w}, \ttm{x}\}$|
  3780. addq $7, x
  3781. |$\{\ttm{w}, \ttm{x}\}$|
  3782. movq x, y
  3783. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  3784. movq x, z
  3785. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  3786. addq w, z
  3787. |$\{\ttm{y}, \ttm{z}\}$|
  3788. movq y, tmp_0
  3789. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3790. negq tmp_0
  3791. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3792. movq z, tmp_1
  3793. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  3794. addq tmp_0, tmp_1
  3795. |$\{\ttm{tmp\_1}\}$|
  3796. movq tmp_1, %rdi
  3797. |$\{\ttm{rdi}\}$|
  3798. callq print_int
  3799. |$\{\}$|
  3800. \end{lstlisting}
  3801. \fi}
  3802. \end{minipage}
  3803. \caption{The running example annotated with live-after sets.}
  3804. \label{fig:live-eg}
  3805. \end{figure}
  3806. \begin{exercise}\normalfont
  3807. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  3808. %
  3809. \racket{Store the sequence of live-after sets in the $\itm{info}$
  3810. field of the \code{Block} structure.}
  3811. %
  3812. \python{Return a dictionary that maps each instruction to its
  3813. live-after set.}
  3814. %
  3815. \racket{We recommend creating an auxiliary function that takes a list
  3816. of instructions and an initial live-after set (typically empty) and
  3817. returns the list of live-after sets.}
  3818. %
  3819. We recommend creating auxiliary functions to 1) compute the set
  3820. of locations that appear in an \Arg{}, 2) compute the locations read
  3821. by an instruction (the $R$ function), and 3) the locations written by
  3822. an instruction (the $W$ function). The \code{callq} instruction should
  3823. include all of the caller-saved registers in its write-set $W$ because
  3824. the calling convention says that those registers may be written to
  3825. during the function call. Likewise, the \code{callq} instruction
  3826. should include the appropriate argument-passing registers in its
  3827. read-set $R$, depending on the arity of the function being
  3828. called. (This is why the abstract syntax for \code{callq} includes the
  3829. arity.)
  3830. \end{exercise}
  3831. %\clearpage
  3832. \section{Build the Interference Graph}
  3833. \label{sec:build-interference}
  3834. {\if\edition\racketEd\color{olive}
  3835. \begin{figure}[tp]
  3836. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  3837. \small
  3838. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  3839. A \emph{graph} is a collection of vertices and edges where each
  3840. edge connects two vertices. A graph is \emph{directed} if each
  3841. edge points from a source to a target. Otherwise the graph is
  3842. \emph{undirected}.
  3843. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  3844. \begin{description}
  3845. %% We currently don't use directed graphs. We instead use
  3846. %% directed multi-graphs. -Jeremy
  3847. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  3848. directed graph from a list of edges. Each edge is a list
  3849. containing the source and target vertex.
  3850. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  3851. undirected graph from a list of edges. Each edge is represented by
  3852. a list containing two vertices.
  3853. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  3854. inserts a vertex into the graph.
  3855. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  3856. inserts an edge between the two vertices.
  3857. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  3858. returns a sequence of vertices adjacent to the vertex.
  3859. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  3860. returns a sequence of all vertices in the graph.
  3861. \end{description}
  3862. \end{tcolorbox}
  3863. %\end{wrapfigure}
  3864. \caption{The Racket \code{graph} package.}
  3865. \label{fig:graph}
  3866. \end{figure}
  3867. \fi}
  3868. Based on the liveness analysis, we know where each location is live.
  3869. However, during register allocation, we need to answer questions of
  3870. the specific form: are locations $u$ and $v$ live at the same time?
  3871. (And therefore cannot be assigned to the same register.) To make this
  3872. question more efficient to answer, we create an explicit data
  3873. structure, an \emph{interference graph}\index{subject}{interference
  3874. graph}. An interference graph is an undirected graph that has an
  3875. edge between two locations if they are live at the same time, that is,
  3876. if they interfere with each other.
  3877. %
  3878. \racket{We recommend using the Racket \code{graph} package
  3879. (Figure~\ref{fig:graph}) to represent the interference graph.}
  3880. %
  3881. \python{We provide implementations of directed and undirected graph
  3882. data structures in the file \code{graph.py} of the support code.}
  3883. A straightforward way to compute the interference graph is to look at
  3884. the set of live locations between each instruction and the next and
  3885. add an edge to the graph for every pair of variables in the same set.
  3886. This approach is less than ideal for two reasons. First, it can be
  3887. expensive because it takes $O(n^2)$ time to consider at every pair in
  3888. a set of $n$ live locations. Second, in the special case where two
  3889. locations hold the same value (because one was assigned to the other),
  3890. they can be live at the same time without interfering with each other.
  3891. A better way to compute the interference graph is to focus on
  3892. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  3893. must not overwrite something in a live location. So for each
  3894. instruction, we create an edge between the locations being written to
  3895. and the live locations. (Except that one should not create self
  3896. edges.) Note that for the \key{callq} instruction, we consider all of
  3897. the caller-saved registers as being written to, so an edge is added
  3898. between every live variable and every caller-saved register. For
  3899. \key{movq}, we deal with the above-mentioned special case by not
  3900. adding an edge between a live variable $v$ and the destination if $v$
  3901. matches the source. So we have the following two rules.
  3902. \begin{enumerate}
  3903. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  3904. $d$, then add the edge $(d,v)$ for every $v \in
  3905. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  3906. \item For any other instruction $I_k$, for every $d \in W(k)$
  3907. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  3908. %% \item If instruction $I_k$ is an arithmetic instruction such as
  3909. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  3910. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  3911. %% \item If instruction $I_k$ is of the form \key{callq}
  3912. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  3913. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  3914. \end{enumerate}
  3915. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  3916. the above rules to each instruction. We highlight a few of the
  3917. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  3918. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  3919. so \code{v} interferes with \code{rsp}.}
  3920. %
  3921. \python{The first instruction is \lstinline{movq $1, v} and the
  3922. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  3923. no interference because $\ttm{v}$ is the destination of the move.}
  3924. %
  3925. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  3926. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  3927. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  3928. %
  3929. \python{The fourth instruction is \lstinline{addq $7, x} and the
  3930. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  3931. $\ttm{x}$ interferes with \ttm{w}.}
  3932. %
  3933. \racket{The next instruction is \lstinline{movq x, y} and the
  3934. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  3935. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  3936. \ttm{x} because \ttm{x} is the source of the move and therefore
  3937. \ttm{x} and \ttm{y} hold the same value.}
  3938. %
  3939. \python{The next instruction is \lstinline{movq x, y} and the
  3940. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  3941. applies, so \ttm{y} interferes with \ttm{w} but not
  3942. \ttm{x} because \ttm{x} is the source of the move and therefore
  3943. \ttm{x} and \ttm{y} hold the same value.}
  3944. %
  3945. Figure~\ref{fig:interference-results} lists the interference results
  3946. for all of the instructions and the resulting interference graph is
  3947. shown in Figure~\ref{fig:interfere}.
  3948. \begin{figure}[tbp]
  3949. \begin{quote}
  3950. {\if\edition\racketEd\color{olive}
  3951. \begin{tabular}{ll}
  3952. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  3953. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  3954. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3955. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3956. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  3957. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  3958. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  3959. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3960. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3961. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  3962. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  3963. \lstinline!jmp conclusion!& no interference.
  3964. \end{tabular}
  3965. \fi}
  3966. {\if\edition\pythonEd\color{purple}
  3967. \begin{tabular}{ll}
  3968. \lstinline!movq $1, v!& no interference\\
  3969. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  3970. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  3971. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  3972. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  3973. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  3974. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  3975. \lstinline!movq y, tmp_0!& \ttm{t} interferes with \ttm{z} \\
  3976. \lstinline!negq tmp_0!& \ttm{t} interferes with \ttm{z} \\
  3977. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  3978. \lstinline!addq tmp_0, tmp_1! & no interference\\
  3979. \lstinline!movq tmp_1, %rdi! & no interference \\
  3980. \lstinline!callq print_int!& no interference.
  3981. \end{tabular}
  3982. \fi}
  3983. \end{quote}
  3984. \caption{Interference results for the running example.}
  3985. \label{fig:interference-results}
  3986. \end{figure}
  3987. \begin{figure}[tbp]
  3988. \large
  3989. {\if\edition\racketEd\color{olive}
  3990. \[
  3991. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3992. \node (rax) at (0,0) {$\ttm{rax}$};
  3993. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3994. \node (t1) at (0,2) {$\ttm{t}$};
  3995. \node (z) at (3,2) {$\ttm{z}$};
  3996. \node (x) at (6,2) {$\ttm{x}$};
  3997. \node (y) at (3,0) {$\ttm{y}$};
  3998. \node (w) at (6,0) {$\ttm{w}$};
  3999. \node (v) at (9,0) {$\ttm{v}$};
  4000. \draw (t1) to (rax);
  4001. \draw (t1) to (z);
  4002. \draw (z) to (y);
  4003. \draw (z) to (w);
  4004. \draw (x) to (w);
  4005. \draw (y) to (w);
  4006. \draw (v) to (w);
  4007. \draw (v) to (rsp);
  4008. \draw (w) to (rsp);
  4009. \draw (x) to (rsp);
  4010. \draw (y) to (rsp);
  4011. \path[-.,bend left=15] (z) edge node {} (rsp);
  4012. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4013. \draw (rax) to (rsp);
  4014. \end{tikzpicture}
  4015. \]
  4016. \fi}
  4017. {\if\edition\pythonEd\color{purple}
  4018. \[
  4019. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4020. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4021. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4022. \node (z) at (3,2) {$\ttm{z}$};
  4023. \node (x) at (6,2) {$\ttm{x}$};
  4024. \node (y) at (3,0) {$\ttm{y}$};
  4025. \node (w) at (6,0) {$\ttm{w}$};
  4026. \node (v) at (9,0) {$\ttm{v}$};
  4027. \draw (t0) to (t1);
  4028. \draw (t0) to (z);
  4029. \draw (z) to (y);
  4030. \draw (z) to (w);
  4031. \draw (x) to (w);
  4032. \draw (y) to (w);
  4033. \draw (v) to (w);
  4034. \end{tikzpicture}
  4035. \]
  4036. \fi}
  4037. \caption{The interference graph of the example program.}
  4038. \label{fig:interfere}
  4039. \end{figure}
  4040. %% Our next concern is to choose a data structure for representing the
  4041. %% interference graph. There are many choices for how to represent a
  4042. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4043. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4044. %% data structure is to study the algorithm that uses the data structure,
  4045. %% determine what operations need to be performed, and then choose the
  4046. %% data structure that provide the most efficient implementations of
  4047. %% those operations. Often times the choice of data structure can have an
  4048. %% effect on the time complexity of the algorithm, as it does here. If
  4049. %% you skim the next section, you will see that the register allocation
  4050. %% algorithm needs to ask the graph for all of its vertices and, given a
  4051. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4052. %% correct choice of graph representation is that of an adjacency
  4053. %% list. There are helper functions in \code{utilities.rkt} for
  4054. %% representing graphs using the adjacency list representation:
  4055. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4056. %% (Appendix~\ref{appendix:utilities}).
  4057. %% %
  4058. %% \margincomment{\footnotesize To do: change to use the
  4059. %% Racket graph library. \\ --Jeremy}
  4060. %% %
  4061. %% In particular, those functions use a hash table to map each vertex to
  4062. %% the set of adjacent vertices, and the sets are represented using
  4063. %% Racket's \key{set}, which is also a hash table.
  4064. \begin{exercise}\normalfont
  4065. \racket{Implement the compiler pass named \code{build\_interference} according
  4066. to the algorithm suggested above. We recommend using the Racket
  4067. \code{graph} package to create and inspect the interference graph.
  4068. The output graph of this pass should be stored in the $\itm{info}$ field of
  4069. the program, under the key \code{conflicts}.}
  4070. %
  4071. \python{Implement a function named \code{build\_interference}
  4072. according to the algorithm suggested above that
  4073. returns the interference graph.}
  4074. \end{exercise}
  4075. \section{Graph Coloring via Sudoku}
  4076. \label{sec:graph-coloring}
  4077. \index{subject}{graph coloring}
  4078. \index{subject}{Sudoku}
  4079. \index{subject}{color}
  4080. We come to the main event, mapping variables to registers and stack
  4081. locations. Variables that interfere with each other must be mapped to
  4082. different locations. In terms of the interference graph, this means
  4083. that adjacent vertices must be mapped to different locations. If we
  4084. think of locations as colors, the register allocation problem becomes
  4085. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4086. The reader may be more familiar with the graph coloring problem than he
  4087. or she realizes; the popular game of Sudoku is an instance of the
  4088. graph coloring problem. The following describes how to build a graph
  4089. out of an initial Sudoku board.
  4090. \begin{itemize}
  4091. \item There is one vertex in the graph for each Sudoku square.
  4092. \item There is an edge between two vertices if the corresponding squares
  4093. are in the same row, in the same column, or if the squares are in
  4094. the same $3\times 3$ region.
  4095. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4096. \item Based on the initial assignment of numbers to squares in the
  4097. Sudoku board, assign the corresponding colors to the corresponding
  4098. vertices in the graph.
  4099. \end{itemize}
  4100. If you can color the remaining vertices in the graph with the nine
  4101. colors, then you have also solved the corresponding game of Sudoku.
  4102. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4103. the corresponding graph with colored vertices. We map the Sudoku
  4104. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4105. sampling of the vertices (the colored ones) because showing edges for
  4106. all of the vertices would make the graph unreadable.
  4107. \begin{figure}[tbp]
  4108. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4109. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4110. \caption{A Sudoku game board and the corresponding colored graph.}
  4111. \label{fig:sudoku-graph}
  4112. \end{figure}
  4113. Some techniques for playing Sudoku correspond to heuristics used in
  4114. graph coloring algorithms. For example, one of the basic techniques
  4115. for Sudoku is called Pencil Marks. The idea is to use a process of
  4116. elimination to determine what numbers are no longer available for a
  4117. square and write down those numbers in the square (writing very
  4118. small). For example, if the number $1$ is assigned to a square, then
  4119. write the pencil mark $1$ in all the squares in the same row, column,
  4120. and region to indicate that $1$ is no longer an option for those other
  4121. squares.
  4122. %
  4123. The Pencil Marks technique corresponds to the notion of
  4124. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4125. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4126. are no longer available. In graph terminology, we have the following
  4127. definition:
  4128. \begin{equation*}
  4129. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4130. \text{ and } \mathrm{color}(v) = c \}
  4131. \end{equation*}
  4132. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4133. edge with $u$.
  4134. Using the Pencil Marks technique leads to a simple strategy for
  4135. filling in numbers: if there is a square with only one possible number
  4136. left, then choose that number! But what if there are no squares with
  4137. only one possibility left? One brute-force approach is to try them
  4138. all: choose the first one and if that ultimately leads to a solution,
  4139. great. If not, backtrack and choose the next possibility. One good
  4140. thing about Pencil Marks is that it reduces the degree of branching in
  4141. the search tree. Nevertheless, backtracking can be terribly time
  4142. consuming. One way to reduce the amount of backtracking is to use the
  4143. most-constrained-first heuristic (aka. minimum remaining
  4144. values)~\citep{Russell2003}. That is, when choosing a square, always
  4145. choose one with the fewest possibilities left (the vertex with the
  4146. highest saturation). The idea is that choosing highly constrained
  4147. squares earlier rather than later is better because later on there may
  4148. not be any possibilities left in the highly saturated squares.
  4149. However, register allocation is easier than Sudoku because the
  4150. register allocator can map variables to stack locations when the
  4151. registers run out. Thus, it makes sense to replace backtracking with
  4152. greedy search: make the best choice at the time and keep going. We
  4153. still wish to minimize the number of colors needed, so we use the
  4154. most-constrained-first heuristic in the greedy search.
  4155. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4156. algorithm for register allocation based on saturation and the
  4157. most-constrained-first heuristic. It is roughly equivalent to the
  4158. DSATUR
  4159. algorithm~\citep{Brelaz:1979eu}.
  4160. %,Gebremedhin:1999fk,Omari:2006uq
  4161. Just as in Sudoku, the algorithm represents colors with integers. The
  4162. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4163. for register allocation. The integers $k$ and larger correspond to
  4164. stack locations. The registers that are not used for register
  4165. allocation, such as \code{rax}, are assigned to negative integers. In
  4166. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4167. %% One might wonder why we include registers at all in the liveness
  4168. %% analysis and interference graph. For example, we never allocate a
  4169. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4170. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  4171. %% to use register for passing arguments to functions, it will be
  4172. %% necessary for those registers to appear in the interference graph
  4173. %% because those registers will also be assigned to variables, and we
  4174. %% don't want those two uses to encroach on each other. Regarding
  4175. %% registers such as \code{rax} and \code{rsp} that are not used for
  4176. %% variables, we could omit them from the interference graph but that
  4177. %% would require adding special cases to our algorithm, which would
  4178. %% complicate the logic for little gain.
  4179. \begin{figure}[btp]
  4180. \centering
  4181. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4182. Algorithm: DSATUR
  4183. Input: a graph |$G$|
  4184. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4185. |$W \gets \mathrm{vertices}(G)$|
  4186. while |$W \neq \emptyset$| do
  4187. pick a vertex |$u$| from |$W$| with the highest saturation,
  4188. breaking ties randomly
  4189. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4190. |$\mathrm{color}[u] \gets c$|
  4191. |$W \gets W - \{u\}$|
  4192. \end{lstlisting}
  4193. \caption{The saturation-based greedy graph coloring algorithm.}
  4194. \label{fig:satur-algo}
  4195. \end{figure}
  4196. {\if\edition\racketEd\color{olive}
  4197. With the DSATUR algorithm in hand, let us return to the running
  4198. example and consider how to color the interference graph in
  4199. Figure~\ref{fig:interfere}.
  4200. %
  4201. We start by assigning the register nodes to their own color. For
  4202. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4203. assigned $-2$. The variables are not yet colored, so they are
  4204. annotated with a dash. We then update the saturation for vertices that
  4205. are adjacent to a register, obtaining the following annotated
  4206. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4207. it interferes with both \code{rax} and \code{rsp}.
  4208. \[
  4209. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4210. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4211. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4212. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4213. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4214. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4215. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4216. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4217. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4218. \draw (t1) to (rax);
  4219. \draw (t1) to (z);
  4220. \draw (z) to (y);
  4221. \draw (z) to (w);
  4222. \draw (x) to (w);
  4223. \draw (y) to (w);
  4224. \draw (v) to (w);
  4225. \draw (v) to (rsp);
  4226. \draw (w) to (rsp);
  4227. \draw (x) to (rsp);
  4228. \draw (y) to (rsp);
  4229. \path[-.,bend left=15] (z) edge node {} (rsp);
  4230. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4231. \draw (rax) to (rsp);
  4232. \end{tikzpicture}
  4233. \]
  4234. The algorithm says to select a maximally saturated vertex. So we pick
  4235. $\ttm{t}$ and color it with the first available integer, which is
  4236. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4237. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4238. \[
  4239. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4240. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4241. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4242. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4243. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4244. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4245. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4246. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4247. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4248. \draw (t1) to (rax);
  4249. \draw (t1) to (z);
  4250. \draw (z) to (y);
  4251. \draw (z) to (w);
  4252. \draw (x) to (w);
  4253. \draw (y) to (w);
  4254. \draw (v) to (w);
  4255. \draw (v) to (rsp);
  4256. \draw (w) to (rsp);
  4257. \draw (x) to (rsp);
  4258. \draw (y) to (rsp);
  4259. \path[-.,bend left=15] (z) edge node {} (rsp);
  4260. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4261. \draw (rax) to (rsp);
  4262. \end{tikzpicture}
  4263. \]
  4264. We repeat the process, selecting a maximally saturated vertex,
  4265. choosing is \code{z}, and color it with the first available number, which
  4266. is $1$. We add $1$ to the saturation for the neighboring vertices
  4267. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4268. \[
  4269. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4270. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4271. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4272. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4273. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4274. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4275. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4276. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4277. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4278. \draw (t1) to (rax);
  4279. \draw (t1) to (z);
  4280. \draw (z) to (y);
  4281. \draw (z) to (w);
  4282. \draw (x) to (w);
  4283. \draw (y) to (w);
  4284. \draw (v) to (w);
  4285. \draw (v) to (rsp);
  4286. \draw (w) to (rsp);
  4287. \draw (x) to (rsp);
  4288. \draw (y) to (rsp);
  4289. \path[-.,bend left=15] (z) edge node {} (rsp);
  4290. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4291. \draw (rax) to (rsp);
  4292. \end{tikzpicture}
  4293. \]
  4294. The most saturated vertices are now \code{w} and \code{y}. We color
  4295. \code{w} with the first available color, which is $0$.
  4296. \[
  4297. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4298. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4299. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4300. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4301. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4302. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4303. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4304. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4305. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4306. \draw (t1) to (rax);
  4307. \draw (t1) to (z);
  4308. \draw (z) to (y);
  4309. \draw (z) to (w);
  4310. \draw (x) to (w);
  4311. \draw (y) to (w);
  4312. \draw (v) to (w);
  4313. \draw (v) to (rsp);
  4314. \draw (w) to (rsp);
  4315. \draw (x) to (rsp);
  4316. \draw (y) to (rsp);
  4317. \path[-.,bend left=15] (z) edge node {} (rsp);
  4318. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4319. \draw (rax) to (rsp);
  4320. \end{tikzpicture}
  4321. \]
  4322. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4323. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4324. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4325. and \code{z}, whose colors are $0$ and $1$ respectively.
  4326. \[
  4327. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4328. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4329. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4330. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4331. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4332. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4333. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4334. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4335. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4336. \draw (t1) to (rax);
  4337. \draw (t1) to (z);
  4338. \draw (z) to (y);
  4339. \draw (z) to (w);
  4340. \draw (x) to (w);
  4341. \draw (y) to (w);
  4342. \draw (v) to (w);
  4343. \draw (v) to (rsp);
  4344. \draw (w) to (rsp);
  4345. \draw (x) to (rsp);
  4346. \draw (y) to (rsp);
  4347. \path[-.,bend left=15] (z) edge node {} (rsp);
  4348. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4349. \draw (rax) to (rsp);
  4350. \end{tikzpicture}
  4351. \]
  4352. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4353. \[
  4354. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4355. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4356. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4357. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4358. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4359. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4360. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4361. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4362. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4363. \draw (t1) to (rax);
  4364. \draw (t1) to (z);
  4365. \draw (z) to (y);
  4366. \draw (z) to (w);
  4367. \draw (x) to (w);
  4368. \draw (y) to (w);
  4369. \draw (v) to (w);
  4370. \draw (v) to (rsp);
  4371. \draw (w) to (rsp);
  4372. \draw (x) to (rsp);
  4373. \draw (y) to (rsp);
  4374. \path[-.,bend left=15] (z) edge node {} (rsp);
  4375. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4376. \draw (rax) to (rsp);
  4377. \end{tikzpicture}
  4378. \]
  4379. In the last step of the algorithm, we color \code{x} with $1$.
  4380. \[
  4381. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4382. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4383. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4384. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4385. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4386. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4387. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4388. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4389. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4390. \draw (t1) to (rax);
  4391. \draw (t1) to (z);
  4392. \draw (z) to (y);
  4393. \draw (z) to (w);
  4394. \draw (x) to (w);
  4395. \draw (y) to (w);
  4396. \draw (v) to (w);
  4397. \draw (v) to (rsp);
  4398. \draw (w) to (rsp);
  4399. \draw (x) to (rsp);
  4400. \draw (y) to (rsp);
  4401. \path[-.,bend left=15] (z) edge node {} (rsp);
  4402. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4403. \draw (rax) to (rsp);
  4404. \end{tikzpicture}
  4405. \]
  4406. So we obtain the following coloring:
  4407. \[
  4408. \{
  4409. \ttm{rax} \mapsto -1,
  4410. \ttm{rsp} \mapsto -2,
  4411. \ttm{t} \mapsto 0,
  4412. \ttm{z} \mapsto 1,
  4413. \ttm{x} \mapsto 1,
  4414. \ttm{y} \mapsto 2,
  4415. \ttm{w} \mapsto 0,
  4416. \ttm{v} \mapsto 1
  4417. \}
  4418. \]
  4419. \fi}
  4420. %
  4421. {\if\edition\pythonEd\color{purple}
  4422. %
  4423. With the DSATUR algorithm in hand, let us return to the running
  4424. example and consider how to color the interference graph in
  4425. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4426. to indicate that it has not yet been assigned a color. The saturation
  4427. sets are also shown for each node; all of them start as the empty set.
  4428. (We do not include the register nodes in the graph below because there
  4429. were no interference edges involving registers in this program, but in
  4430. general there can be.)
  4431. %
  4432. \[
  4433. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4434. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4435. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4436. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4437. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4438. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4439. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4440. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4441. \draw (t0) to (t1);
  4442. \draw (t0) to (z);
  4443. \draw (z) to (y);
  4444. \draw (z) to (w);
  4445. \draw (x) to (w);
  4446. \draw (y) to (w);
  4447. \draw (v) to (w);
  4448. \end{tikzpicture}
  4449. \]
  4450. The algorithm says to select a maximally saturated vertex. So we pick
  4451. $\ttm{tmp\_0}$ and color it with the first available integer, which is
  4452. $0$. We mark $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$
  4453. because they interfere with $\ttm{tmp\_0}$.
  4454. \[
  4455. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4456. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4457. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4458. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4459. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4460. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4461. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4462. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4463. \draw (t0) to (t1);
  4464. \draw (t0) to (z);
  4465. \draw (z) to (y);
  4466. \draw (z) to (w);
  4467. \draw (x) to (w);
  4468. \draw (y) to (w);
  4469. \draw (v) to (w);
  4470. \end{tikzpicture}
  4471. \]
  4472. We repeat the process, selecting a maximally saturated vertex,
  4473. choosing \code{z}, and color it with the first available number, which
  4474. is $1$. We add $1$ to the saturation for the neighboring vertices
  4475. \code{tmp\_0}, \code{y}, and \code{w}.
  4476. \[
  4477. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4478. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4479. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4480. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4481. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4482. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4483. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4484. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4485. \draw (t0) to (t1);
  4486. \draw (t0) to (z);
  4487. \draw (z) to (y);
  4488. \draw (z) to (w);
  4489. \draw (x) to (w);
  4490. \draw (y) to (w);
  4491. \draw (v) to (w);
  4492. \end{tikzpicture}
  4493. \]
  4494. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4495. \code{y}. We color \code{w} with the first available color, which
  4496. is $0$.
  4497. \[
  4498. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4499. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4500. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4501. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4502. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4503. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4504. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4505. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4506. \draw (t0) to (t1);
  4507. \draw (t0) to (z);
  4508. \draw (z) to (y);
  4509. \draw (z) to (w);
  4510. \draw (x) to (w);
  4511. \draw (y) to (w);
  4512. \draw (v) to (w);
  4513. \end{tikzpicture}
  4514. \]
  4515. Now \code{y} is the most saturated, so we color it with $2$.
  4516. \[
  4517. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4518. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4519. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4520. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4521. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4522. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4523. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4524. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4525. \draw (t0) to (t1);
  4526. \draw (t0) to (z);
  4527. \draw (z) to (y);
  4528. \draw (z) to (w);
  4529. \draw (x) to (w);
  4530. \draw (y) to (w);
  4531. \draw (v) to (w);
  4532. \end{tikzpicture}
  4533. \]
  4534. Now \code{tmp\_1}, \code{x}, and \code{v} are equally saturated.
  4535. We choose to color \code{v} with $1$.
  4536. \[
  4537. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4538. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4539. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4540. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4541. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4542. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4543. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4544. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4545. \draw (t0) to (t1);
  4546. \draw (t0) to (z);
  4547. \draw (z) to (y);
  4548. \draw (z) to (w);
  4549. \draw (x) to (w);
  4550. \draw (y) to (w);
  4551. \draw (v) to (w);
  4552. \end{tikzpicture}
  4553. \]
  4554. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4555. \[
  4556. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4557. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4558. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4559. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4560. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4561. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4562. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4563. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4564. \draw (t0) to (t1);
  4565. \draw (t0) to (z);
  4566. \draw (z) to (y);
  4567. \draw (z) to (w);
  4568. \draw (x) to (w);
  4569. \draw (y) to (w);
  4570. \draw (v) to (w);
  4571. \end{tikzpicture}
  4572. \]
  4573. So we obtain the following coloring:
  4574. \[
  4575. \{ \ttm{tmp\_0} \mapsto 0,
  4576. \ttm{tmp\_1} \mapsto 1,
  4577. \ttm{z} \mapsto 1,
  4578. \ttm{x} \mapsto 1,
  4579. \ttm{y} \mapsto 2,
  4580. \ttm{w} \mapsto 0,
  4581. \ttm{v} \mapsto 1 \}
  4582. \]
  4583. \fi}
  4584. We recommend creating an auxiliary function named \code{color\_graph}
  4585. that takes an interference graph and a list of all the variables in
  4586. the program. This function should return a mapping of variables to
  4587. their colors (represented as natural numbers). By creating this helper
  4588. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4589. when we add support for functions.
  4590. To prioritize the processing of highly saturated nodes inside the
  4591. \code{color\_graph} function, we recommend using the priority queue
  4592. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4593. addition, you will need to maintain a mapping from variables to their
  4594. ``handles'' in the priority queue so that you can notify the priority
  4595. queue when their saturation changes.}
  4596. {\if\edition\racketEd\color{olive}
  4597. \begin{figure}[tp]
  4598. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4599. \small
  4600. \begin{tcolorbox}[title=Priority Queue]
  4601. A \emph{priority queue} is a collection of items in which the
  4602. removal of items is governed by priority. In a ``min'' queue,
  4603. lower priority items are removed first. An implementation is in
  4604. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4605. queue} \index{subject}{minimum priority queue}
  4606. \begin{description}
  4607. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4608. priority queue that uses the $\itm{cmp}$ predicate to determine
  4609. whether its first argument has lower or equal priority to its
  4610. second argument.
  4611. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4612. items in the queue.
  4613. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4614. the item into the queue and returns a handle for the item in the
  4615. queue.
  4616. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4617. the lowest priority.
  4618. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4619. notifies the queue that the priority has decreased for the item
  4620. associated with the given handle.
  4621. \end{description}
  4622. \end{tcolorbox}
  4623. %\end{wrapfigure}
  4624. \caption{The priority queue data structure.}
  4625. \label{fig:priority-queue}
  4626. \end{figure}
  4627. \fi}
  4628. With the coloring complete, we finalize the assignment of variables to
  4629. registers and stack locations. We map the first $k$ colors to the $k$
  4630. registers and the rest of the colors to stack locations. Suppose for
  4631. the moment that we have just one register to use for register
  4632. allocation, \key{rcx}. Then we have the following map from colors to
  4633. locations.
  4634. \[
  4635. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4636. \]
  4637. Composing this mapping with the coloring, we arrive at the following
  4638. assignment of variables to locations.
  4639. {\if\edition\racketEd\color{olive}
  4640. \begin{gather*}
  4641. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4642. \ttm{w} \mapsto \key{\%rcx}, \,
  4643. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4644. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4645. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4646. \ttm{t} \mapsto \key{\%rcx} \}
  4647. \end{gather*}
  4648. \fi}
  4649. {\if\edition\pythonEd\color{purple}
  4650. \begin{gather*}
  4651. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4652. \ttm{w} \mapsto \key{\%rcx}, \,
  4653. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4654. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4655. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4656. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4657. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4658. \end{gather*}
  4659. \fi}
  4660. Adapt the code from the \code{assign\_homes} pass
  4661. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  4662. assigned location. Applying the above assignment to our running
  4663. example, on the left, yields the program on the right.
  4664. % why frame size of 32? -JGS
  4665. \begin{center}
  4666. {\if\edition\racketEd\color{olive}
  4667. \begin{minipage}{0.3\textwidth}
  4668. \begin{lstlisting}
  4669. movq $1, v
  4670. movq $42, w
  4671. movq v, x
  4672. addq $7, x
  4673. movq x, y
  4674. movq x, z
  4675. addq w, z
  4676. movq y, t
  4677. negq t
  4678. movq z, %rax
  4679. addq t, %rax
  4680. jmp conclusion
  4681. \end{lstlisting}
  4682. \end{minipage}
  4683. $\Rightarrow\qquad$
  4684. \begin{minipage}{0.45\textwidth}
  4685. \begin{lstlisting}
  4686. movq $1, -8(%rbp)
  4687. movq $42, %rcx
  4688. movq -8(%rbp), -8(%rbp)
  4689. addq $7, -8(%rbp)
  4690. movq -8(%rbp), -16(%rbp)
  4691. movq -8(%rbp), -8(%rbp)
  4692. addq %rcx, -8(%rbp)
  4693. movq -16(%rbp), %rcx
  4694. negq %rcx
  4695. movq -8(%rbp), %rax
  4696. addq %rcx, %rax
  4697. jmp conclusion
  4698. \end{lstlisting}
  4699. \end{minipage}
  4700. \fi}
  4701. {\if\edition\pythonEd\color{purple}
  4702. \begin{minipage}{0.3\textwidth}
  4703. \begin{lstlisting}
  4704. movq $1, v
  4705. movq $42, w
  4706. movq v, x
  4707. addq $7, x
  4708. movq x, y
  4709. movq x, z
  4710. addq w, z
  4711. movq y, tmp_0
  4712. negq tmp_0
  4713. movq z, tmp_1
  4714. addq tmp_0, tmp_1
  4715. movq tmp_1, %rdi
  4716. callq print_int
  4717. \end{lstlisting}
  4718. \end{minipage}
  4719. $\Rightarrow\qquad$
  4720. \begin{minipage}{0.45\textwidth}
  4721. \begin{lstlisting}
  4722. movq $1, -8(%rbp)
  4723. movq $42, %rcx
  4724. movq -8(%rbp), -8(%rbp)
  4725. addq $7, -8(%rbp)
  4726. movq -8(%rbp), -16(%rbp)
  4727. movq -8(%rbp), -8(%rbp)
  4728. addq %rcx, -8(%rbp)
  4729. movq -16(%rbp), %rcx
  4730. negq %rcx
  4731. movq -8(%rbp), -8(%rbp)
  4732. addq %rcx, -8(%rbp)
  4733. movq -8(%rbp), %rdi
  4734. callq print_int
  4735. \end{lstlisting}
  4736. \end{minipage}
  4737. \fi}
  4738. \end{center}
  4739. \begin{exercise}\normalfont
  4740. %
  4741. Implement the compiler pass \code{allocate\_registers}.
  4742. %
  4743. Create five programs that exercise all of the register allocation
  4744. algorithm, including spilling variables to the stack.
  4745. %
  4746. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  4747. \code{run-tests.rkt} script with the three new passes:
  4748. \code{uncover\_live}, \code{build\_interference}, and
  4749. \code{allocate\_registers}.
  4750. %
  4751. Temporarily remove the \code{print\_x86} pass from the list of passes
  4752. and the call to \code{compiler-tests}.
  4753. Run the script to test the register allocator.
  4754. }
  4755. %
  4756. \python{Run the \code{run-tests.py} script to to check whether the
  4757. output programs produce the same result as the input programs.}
  4758. \end{exercise}
  4759. \section{Patch Instructions}
  4760. \label{sec:patch-instructions}
  4761. The remaining step in the compilation to x86 is to ensure that the
  4762. instructions have at most one argument that is a memory access.
  4763. %
  4764. In the running example, the instruction \code{movq -8(\%rbp),
  4765. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  4766. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  4767. then move \code{rax} into \code{-16(\%rbp)}.
  4768. %
  4769. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  4770. problematic, but it can simply be deleted. In general, we recommend
  4771. deleting all the trivial moves whose source and destination are the
  4772. same location.
  4773. %
  4774. The following is the output of \code{patch\_instructions} on the
  4775. running example.
  4776. \begin{center}
  4777. {\if\edition\racketEd\color{olive}
  4778. \begin{minipage}{0.4\textwidth}
  4779. \begin{lstlisting}
  4780. movq $1, -8(%rbp)
  4781. movq $42, %rcx
  4782. movq -8(%rbp), -8(%rbp)
  4783. addq $7, -8(%rbp)
  4784. movq -8(%rbp), -16(%rbp)
  4785. movq -8(%rbp), -8(%rbp)
  4786. addq %rcx, -8(%rbp)
  4787. movq -16(%rbp), %rcx
  4788. negq %rcx
  4789. movq -8(%rbp), %rax
  4790. addq %rcx, %rax
  4791. jmp conclusion
  4792. \end{lstlisting}
  4793. \end{minipage}
  4794. $\Rightarrow\qquad$
  4795. \begin{minipage}{0.45\textwidth}
  4796. \begin{lstlisting}
  4797. movq $1, -8(%rbp)
  4798. movq $42, %rcx
  4799. addq $7, -8(%rbp)
  4800. movq -8(%rbp), %rax
  4801. movq %rax, -16(%rbp)
  4802. addq %rcx, -8(%rbp)
  4803. movq -16(%rbp), %rcx
  4804. negq %rcx
  4805. movq -8(%rbp), %rax
  4806. addq %rcx, %rax
  4807. jmp conclusion
  4808. \end{lstlisting}
  4809. \end{minipage}
  4810. \fi}
  4811. {\if\edition\pythonEd\color{purple}
  4812. \begin{minipage}{0.4\textwidth}
  4813. \begin{lstlisting}
  4814. movq $1, -8(%rbp)
  4815. movq $42, %rcx
  4816. movq -8(%rbp), -8(%rbp)
  4817. addq $7, -8(%rbp)
  4818. movq -8(%rbp), -16(%rbp)
  4819. movq -8(%rbp), -8(%rbp)
  4820. addq %rcx, -8(%rbp)
  4821. movq -16(%rbp), %rcx
  4822. negq %rcx
  4823. movq -8(%rbp), -8(%rbp)
  4824. addq %rcx, -8(%rbp)
  4825. movq -8(%rbp), %rdi
  4826. callq print_int
  4827. \end{lstlisting}
  4828. \end{minipage}
  4829. $\Rightarrow\qquad$
  4830. \begin{minipage}{0.45\textwidth}
  4831. \begin{lstlisting}
  4832. movq $1, -8(%rbp)
  4833. movq $42, %rcx
  4834. addq $7, -8(%rbp)
  4835. movq -8(%rbp), %rax
  4836. movq %rax, -16(%rbp)
  4837. addq %rcx, -8(%rbp)
  4838. movq -16(%rbp), %rcx
  4839. negq %rcx
  4840. addq %rcx, -8(%rbp)
  4841. movq -8(%rbp), %rdi
  4842. callq print_int
  4843. \end{lstlisting}
  4844. \end{minipage}
  4845. \fi}
  4846. \end{center}
  4847. \begin{exercise}\normalfont
  4848. %
  4849. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  4850. %
  4851. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  4852. %in the \code{run-tests.rkt} script.
  4853. %
  4854. Run the script to test the \code{patch\_instructions} pass.
  4855. \end{exercise}
  4856. \section{Print x86}
  4857. \label{sec:print-x86-reg-alloc}
  4858. \index{subject}{calling conventions}
  4859. \index{subject}{prelude}\index{subject}{conclusion}
  4860. Recall that the \code{print\_x86} pass generates the prelude and
  4861. conclusion instructions to satisfy the x86 calling conventions
  4862. (Section~\ref{sec:calling-conventions}). With the addition of the
  4863. register allocator, the callee-saved registers used by the register
  4864. allocator must be saved in the prelude and restored in the conclusion.
  4865. In the \code{allocate\_registers} pass,
  4866. %
  4867. \racket{add an entry to the \itm{info}
  4868. of \code{X86Program} named \code{used\_callee}}
  4869. %
  4870. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  4871. %
  4872. that stores the set of
  4873. callee-saved registers that were assigned to variables. The
  4874. \code{print\_x86} pass can then access this information to decide which
  4875. callee-saved registers need to be saved and restored.
  4876. %
  4877. When calculating the size of the frame to adjust the \code{rsp} in the
  4878. prelude, make sure to take into account the space used for saving the
  4879. callee-saved registers. Also, don't forget that the frame needs to be
  4880. a multiple of 16 bytes!
  4881. An overview of all of the passes involved in register allocation is
  4882. shown in Figure~\ref{fig:reg-alloc-passes}.
  4883. \begin{figure}[tbp]
  4884. {\if\edition\racketEd\color{olive}
  4885. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4886. \node (Rvar) at (0,2) {\large \LangVar{}};
  4887. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4888. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  4889. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  4890. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  4891. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  4892. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  4893. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  4894. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  4895. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  4896. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  4897. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-3);
  4898. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  4899. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  4900. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  4901. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  4902. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  4903. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  4904. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  4905. \end{tikzpicture}
  4906. \fi}
  4907. {\if\edition\pythonEd\color{purple}
  4908. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4909. \node (Rvar-1) at (0,2) {\large \LangVar{}};
  4910. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4911. \node (x86-1) at (3,0) {\large \LangXVar{}};
  4912. \node (x86-2) at (6,0) {\large \LangXVar{}};
  4913. \node (x86-3) at (9,0) {\large \LangXInt{}};
  4914. \node (x86-4) at (11,0) {\large \LangXInt{}};
  4915. \path[->,bend left=15] (Rvar-1) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-2);
  4916. \path[->,bend right=15] (Rvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  4917. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize allocate\_reg.} (x86-2);
  4918. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  4919. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86} (x86-4);
  4920. \end{tikzpicture}
  4921. \fi}
  4922. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  4923. \label{fig:reg-alloc-passes}
  4924. \end{figure}
  4925. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  4926. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  4927. use of registers and the stack, we have limited the register allocator
  4928. to use just two registers: \code{rbx} and \code{rcx}. In the
  4929. prelude\index{subject}{prelude} of the \code{main} function, we push
  4930. \code{rbx} onto the stack because it is a callee-saved register and it
  4931. was assigned to variable by the register allocator. We subtract
  4932. \code{8} from the \code{rsp} at the end of the prelude to reserve
  4933. space for the one spilled variable. After that subtraction, the
  4934. \code{rsp} is aligned to 16 bytes.
  4935. Moving on to the program proper, we see how the registers were
  4936. allocated.
  4937. %
  4938. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  4939. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  4940. %
  4941. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  4942. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  4943. were assigned to \code{rbx}.}
  4944. %
  4945. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  4946. location \code{-16(\%rbp)}. Recall that the prelude saved the
  4947. callee-save register \code{rbx} onto the stack. The spilled variables
  4948. must be placed lower on the stack than the saved callee-save
  4949. registers, so in this case \racket{\code{w}}\python{z} is placed at
  4950. \code{-16(\%rbp)}.
  4951. In the conclusion\index{subject}{conclusion}, we undo the work that was
  4952. done in the prelude. We move the stack pointer up by \code{8} bytes
  4953. (the room for spilled variables), then we pop the old values of
  4954. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  4955. \code{retq} to return control to the operating system.
  4956. \begin{figure}[tbp]
  4957. % var_test_28.rkt
  4958. % (use-minimal-set-of-registers! #t)
  4959. % and only rbx rcx
  4960. % tmp 0 rbx
  4961. % z 1 rcx
  4962. % y 0 rbx
  4963. % w 2 16(%rbp)
  4964. % v 0 rbx
  4965. % x 0 rbx
  4966. {\if\edition\racketEd\color{olive}
  4967. \begin{lstlisting}
  4968. start:
  4969. movq $1, %rbx
  4970. movq $42, -16(%rbp)
  4971. addq $7, %rbx
  4972. movq %rbx, %rcx
  4973. addq -16(%rbp), %rcx
  4974. negq %rbx
  4975. movq %rcx, %rax
  4976. addq %rbx, %rax
  4977. jmp conclusion
  4978. .globl main
  4979. main:
  4980. pushq %rbp
  4981. movq %rsp, %rbp
  4982. pushq %rbx
  4983. subq $8, %rsp
  4984. jmp start
  4985. conclusion:
  4986. addq $8, %rsp
  4987. popq %rbx
  4988. popq %rbp
  4989. retq
  4990. \end{lstlisting}
  4991. \fi}
  4992. {\if\edition\pythonEd\color{purple}
  4993. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  4994. \begin{lstlisting}
  4995. .globl main
  4996. main:
  4997. pushq %rbp
  4998. movq %rsp, %rbp
  4999. pushq %rbx
  5000. subq $8, %rsp
  5001. movq $1, %rcx
  5002. movq $42, %rbx
  5003. addq $7, %rcx
  5004. movq %rcx, -16(%rbp)
  5005. addq %rbx, -16(%rbp)
  5006. negq %rcx
  5007. movq -16(%rbp), %rbx
  5008. addq %rcx, %rbx
  5009. movq %rbx, %rdi
  5010. callq print_int
  5011. addq $8, %rsp
  5012. popq %rbx
  5013. popq %rbp
  5014. retq
  5015. \end{lstlisting}
  5016. \fi}
  5017. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  5018. \label{fig:running-example-x86}
  5019. \end{figure}
  5020. \begin{exercise}\normalfont
  5021. Update the \code{print\_x86} pass as described in this section.
  5022. %
  5023. \racket{
  5024. In the \code{run-tests.rkt} script, reinstate \code{print\_x86} in the
  5025. list of passes and the call to \code{compiler-tests}.}
  5026. %
  5027. Run the script to test the complete compiler for \LangVar{} that
  5028. performs register allocation.
  5029. \end{exercise}
  5030. \section{Challenge: Move Biasing}
  5031. \label{sec:move-biasing}
  5032. \index{subject}{move biasing}
  5033. This section describes an enhancement to the register allocator for
  5034. students looking for an extra challenge or who have a deeper interest
  5035. in register allocation.
  5036. {\if\edition\racketEd\color{olive}
  5037. To motivate the need for move biasing we return to the running example
  5038. but this time use all of the general purpose registers. So we have
  5039. the following mapping of color numbers to registers.
  5040. \[
  5041. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5042. \]
  5043. Using the same assignment of variables to color numbers that was
  5044. produced by the register allocator described in the last section, we
  5045. get the following program.
  5046. \begin{center}
  5047. \begin{minipage}{0.3\textwidth}
  5048. \begin{lstlisting}
  5049. movq $1, v
  5050. movq $42, w
  5051. movq v, x
  5052. addq $7, x
  5053. movq x, y
  5054. movq x, z
  5055. addq w, z
  5056. movq y, t
  5057. negq t
  5058. movq z, %rax
  5059. addq t, %rax
  5060. jmp conclusion
  5061. \end{lstlisting}
  5062. \end{minipage}
  5063. $\Rightarrow\qquad$
  5064. \begin{minipage}{0.45\textwidth}
  5065. \begin{lstlisting}
  5066. movq $1, %rdx
  5067. movq $42, %rcx
  5068. movq %rdx, %rdx
  5069. addq $7, %rdx
  5070. movq %rdx, %rsi
  5071. movq %rdx, %rdx
  5072. addq %rcx, %rdx
  5073. movq %rsi, %rcx
  5074. negq %rcx
  5075. movq %rdx, %rax
  5076. addq %rcx, %rax
  5077. jmp conclusion
  5078. \end{lstlisting}
  5079. \end{minipage}
  5080. \end{center}
  5081. In the above output code there are two \key{movq} instructions that
  5082. can be removed because their source and target are the same. However,
  5083. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5084. register, we could instead remove three \key{movq} instructions. We
  5085. can accomplish this by taking into account which variables appear in
  5086. \key{movq} instructions with which other variables.
  5087. \fi}
  5088. {\if\edition\pythonEd\color{purple}
  5089. %
  5090. To motivate the need for move biasing we return to the running example
  5091. and recall that Section~\ref{sec:patch-instructions} we were able to
  5092. remove three trivial move instructions from the running
  5093. example. However, we could remove another trivial move if we were able
  5094. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5095. We say that two variables $p$ and $q$ are \emph{move
  5096. related}\index{subject}{move related} if they participate together in a
  5097. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5098. \key{movq} $q$\key{,} $p$. When deciding which variable to
  5099. color next, when there are multiple variables with the same
  5100. saturation, prefer variables that can be assigned the same
  5101. color as a move related variable that has already been colored.
  5102. Furthermore, when the register allocator chooses a color
  5103. for a variable, it should prefer a color that has already been used
  5104. for a move-related variable (assuming that they do not interfere). Of
  5105. course, this preference should not override the preference for
  5106. registers over stack locations. This preference should be used as a
  5107. tie breaker when choosing between registers or when choosing between
  5108. stack locations.
  5109. We recommend representing the move relationships in a graph, similar
  5110. to how we represented interference. The following is the \emph{move
  5111. graph} for our running example.
  5112. {\if\edition\racketEd\color{olive}
  5113. \[
  5114. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5115. \node (rax) at (0,0) {$\ttm{rax}$};
  5116. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5117. \node (t) at (0,2) {$\ttm{t}$};
  5118. \node (z) at (3,2) {$\ttm{z}$};
  5119. \node (x) at (6,2) {$\ttm{x}$};
  5120. \node (y) at (3,0) {$\ttm{y}$};
  5121. \node (w) at (6,0) {$\ttm{w}$};
  5122. \node (v) at (9,0) {$\ttm{v}$};
  5123. \draw (v) to (x);
  5124. \draw (x) to (y);
  5125. \draw (x) to (z);
  5126. \draw (y) to (t);
  5127. \end{tikzpicture}
  5128. \]
  5129. \fi}
  5130. %
  5131. {\if\edition\pythonEd\color{purple}
  5132. \[
  5133. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5134. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5135. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5136. \node (z) at (3,2) {$\ttm{z}$};
  5137. \node (x) at (6,2) {$\ttm{x}$};
  5138. \node (y) at (3,0) {$\ttm{y}$};
  5139. \node (w) at (6,0) {$\ttm{w}$};
  5140. \node (v) at (9,0) {$\ttm{v}$};
  5141. \draw (y) to (t0);
  5142. \draw (z) to (x);
  5143. \draw (z) to (t1);
  5144. \draw (x) to (y);
  5145. \draw (x) to (v);
  5146. \end{tikzpicture}
  5147. \]
  5148. \fi}
  5149. {\if\edition\racketEd\color{olive}
  5150. Now we replay the graph coloring, pausing to see the coloring of
  5151. \code{y}. Recall the following configuration. The most saturated vertices
  5152. were \code{w} and \code{y}.
  5153. \[
  5154. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5155. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5156. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5157. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5158. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5159. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5160. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5161. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5162. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5163. \draw (t1) to (rax);
  5164. \draw (t1) to (z);
  5165. \draw (z) to (y);
  5166. \draw (z) to (w);
  5167. \draw (x) to (w);
  5168. \draw (y) to (w);
  5169. \draw (v) to (w);
  5170. \draw (v) to (rsp);
  5171. \draw (w) to (rsp);
  5172. \draw (x) to (rsp);
  5173. \draw (y) to (rsp);
  5174. \path[-.,bend left=15] (z) edge node {} (rsp);
  5175. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5176. \draw (rax) to (rsp);
  5177. \end{tikzpicture}
  5178. \]
  5179. %
  5180. Last time we chose to color \code{w} with $0$. But this time we see
  5181. that \code{w} is not move related to any vertex, but \code{y} is move
  5182. related to \code{t}. So we choose to color \code{y} the same color as
  5183. \code{t}, $0$.
  5184. \[
  5185. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5186. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5187. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5188. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5189. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5190. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5191. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5192. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5193. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5194. \draw (t1) to (rax);
  5195. \draw (t1) to (z);
  5196. \draw (z) to (y);
  5197. \draw (z) to (w);
  5198. \draw (x) to (w);
  5199. \draw (y) to (w);
  5200. \draw (v) to (w);
  5201. \draw (v) to (rsp);
  5202. \draw (w) to (rsp);
  5203. \draw (x) to (rsp);
  5204. \draw (y) to (rsp);
  5205. \path[-.,bend left=15] (z) edge node {} (rsp);
  5206. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5207. \draw (rax) to (rsp);
  5208. \end{tikzpicture}
  5209. \]
  5210. Now \code{w} is the most saturated, so we color it $2$.
  5211. \[
  5212. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5213. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5214. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5215. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5216. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5217. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5218. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5219. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5220. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5221. \draw (t1) to (rax);
  5222. \draw (t1) to (z);
  5223. \draw (z) to (y);
  5224. \draw (z) to (w);
  5225. \draw (x) to (w);
  5226. \draw (y) to (w);
  5227. \draw (v) to (w);
  5228. \draw (v) to (rsp);
  5229. \draw (w) to (rsp);
  5230. \draw (x) to (rsp);
  5231. \draw (y) to (rsp);
  5232. \path[-.,bend left=15] (z) edge node {} (rsp);
  5233. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5234. \draw (rax) to (rsp);
  5235. \end{tikzpicture}
  5236. \]
  5237. At this point, vertices \code{x} and \code{v} are most saturated, but
  5238. \code{x} is move related to \code{y} and \code{z}, so we color
  5239. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5240. \[
  5241. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5242. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5243. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5244. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5245. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5246. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5247. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5248. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5249. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5250. \draw (t1) to (rax);
  5251. \draw (t) to (z);
  5252. \draw (z) to (y);
  5253. \draw (z) to (w);
  5254. \draw (x) to (w);
  5255. \draw (y) to (w);
  5256. \draw (v) to (w);
  5257. \draw (v) to (rsp);
  5258. \draw (w) to (rsp);
  5259. \draw (x) to (rsp);
  5260. \draw (y) to (rsp);
  5261. \path[-.,bend left=15] (z) edge node {} (rsp);
  5262. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5263. \draw (rax) to (rsp);
  5264. \end{tikzpicture}
  5265. \]
  5266. \fi}
  5267. %
  5268. {\if\edition\pythonEd\color{purple}
  5269. Now we replay the graph coloring, pausing before the coloring of
  5270. \code{w}. Recall the following configuration. The most saturated vertices
  5271. were \code{tmp\_1}, \code{w}, and \code{y}.
  5272. \[
  5273. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5274. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5275. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5276. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5277. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5278. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5279. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5280. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5281. \draw (t0) to (t1);
  5282. \draw (t0) to (z);
  5283. \draw (z) to (y);
  5284. \draw (z) to (w);
  5285. \draw (x) to (w);
  5286. \draw (y) to (w);
  5287. \draw (v) to (w);
  5288. \end{tikzpicture}
  5289. \]
  5290. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5291. or \code{y}, but note that \code{w} is not move related to any
  5292. variables, wheras \code{y} and \code{tmp\_1} are move related to
  5293. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5294. \code{y} and color it $0$, we can delete another move instruction.
  5295. \[
  5296. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5297. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5298. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5299. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5300. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5301. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5302. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5303. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5304. \draw (t0) to (t1);
  5305. \draw (t0) to (z);
  5306. \draw (z) to (y);
  5307. \draw (z) to (w);
  5308. \draw (x) to (w);
  5309. \draw (y) to (w);
  5310. \draw (v) to (w);
  5311. \end{tikzpicture}
  5312. \]
  5313. Now \code{w} is the most saturated, so we color it $2$.
  5314. \[
  5315. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5316. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5317. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5318. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5319. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5320. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5321. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5322. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5323. \draw (t0) to (t1);
  5324. \draw (t0) to (z);
  5325. \draw (z) to (y);
  5326. \draw (z) to (w);
  5327. \draw (x) to (w);
  5328. \draw (y) to (w);
  5329. \draw (v) to (w);
  5330. \end{tikzpicture}
  5331. \]
  5332. To finish the coloring, \code{x} and \code{v} get $0$ and
  5333. \code{tmp\_1} gets $1$.
  5334. \[
  5335. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5336. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5337. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5338. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5339. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5340. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5341. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5342. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5343. \draw (t0) to (t1);
  5344. \draw (t0) to (z);
  5345. \draw (z) to (y);
  5346. \draw (z) to (w);
  5347. \draw (x) to (w);
  5348. \draw (y) to (w);
  5349. \draw (v) to (w);
  5350. \end{tikzpicture}
  5351. \]
  5352. \fi}
  5353. So we have the following assignment of variables to registers.
  5354. {\if\edition\racketEd\color{olive}
  5355. \begin{gather*}
  5356. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5357. \ttm{w} \mapsto \key{\%rsi}, \,
  5358. \ttm{x} \mapsto \key{\%rcx}, \,
  5359. \ttm{y} \mapsto \key{\%rcx}, \,
  5360. \ttm{z} \mapsto \key{\%rdx}, \,
  5361. \ttm{t} \mapsto \key{\%rcx} \}
  5362. \end{gather*}
  5363. \fi}
  5364. {\if\edition\pythonEd\color{purple}
  5365. \begin{gather*}
  5366. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5367. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5368. \ttm{x} \mapsto \key{\%rcx}, \,
  5369. \ttm{y} \mapsto \key{\%rcx}, \\
  5370. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5371. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5372. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5373. \end{gather*}
  5374. \fi}
  5375. We apply this register assignment to the running example, on the left,
  5376. to obtain the code in the middle. The \code{patch\_instructions} then
  5377. deletes the trivial moves to obtain the code on the right.
  5378. {\if\edition\racketEd\color{olive}
  5379. \begin{minipage}{0.25\textwidth}
  5380. \begin{lstlisting}
  5381. movq $1, v
  5382. movq $42, w
  5383. movq v, x
  5384. addq $7, x
  5385. movq x, y
  5386. movq x, z
  5387. addq w, z
  5388. movq y, t
  5389. negq t
  5390. movq z, %rax
  5391. addq t, %rax
  5392. jmp conclusion
  5393. \end{lstlisting}
  5394. \end{minipage}
  5395. $\Rightarrow\qquad$
  5396. \begin{minipage}{0.25\textwidth}
  5397. \begin{lstlisting}
  5398. movq $1, %rcx
  5399. movq $42, %rsi
  5400. movq %rcx, %rcx
  5401. addq $7, %rcx
  5402. movq %rcx, %rcx
  5403. movq %rcx, %rdx
  5404. addq %rsi, %rdx
  5405. movq %rcx, %rcx
  5406. negq %rcx
  5407. movq %rdx, %rax
  5408. addq %rcx, %rax
  5409. jmp conclusion
  5410. \end{lstlisting}
  5411. \end{minipage}
  5412. $\Rightarrow\qquad$
  5413. \begin{minipage}{0.25\textwidth}
  5414. \begin{lstlisting}
  5415. movq $1, %rcx
  5416. movq $42, %rsi
  5417. addq $7, %rcx
  5418. movq %rcx, %rdx
  5419. addq %rsi, %rdx
  5420. negq %rcx
  5421. movq %rdx, %rax
  5422. addq %rcx, %rax
  5423. jmp conclusion
  5424. \end{lstlisting}
  5425. \end{minipage}
  5426. \fi}
  5427. {\if\edition\pythonEd\color{purple}
  5428. \begin{minipage}{0.25\textwidth}
  5429. \begin{lstlisting}
  5430. movq $1, v
  5431. movq $42, w
  5432. movq v, x
  5433. addq $7, x
  5434. movq x, y
  5435. movq x, z
  5436. addq w, z
  5437. movq y, tmp_0
  5438. negq tmp_0
  5439. movq z, tmp_1
  5440. addq tmp_0, tmp_1
  5441. movq tmp_1, %rdi
  5442. callq _print_int\end{lstlisting}
  5443. \end{minipage}
  5444. $\Rightarrow\qquad$
  5445. \begin{minipage}{0.25\textwidth}
  5446. \begin{lstlisting}
  5447. movq $1, %rcx
  5448. movq $42, -16(%rbp)
  5449. movq %rcx, %rcx
  5450. addq $7, %rcx
  5451. movq %rcx, %rcx
  5452. movq %rcx, -8(%rbp)
  5453. addq -16(%rbp), -8(%rbp)
  5454. movq %rcx, %rcx
  5455. negq %rcx
  5456. movq -8(%rbp), -8(%rbp)
  5457. addq %rcx, -8(%rbp)
  5458. movq -8(%rbp), %rdi
  5459. callq _print_int
  5460. \end{lstlisting}
  5461. \end{minipage}
  5462. $\Rightarrow\qquad$
  5463. \begin{minipage}{0.25\textwidth}
  5464. \begin{lstlisting}
  5465. movq $1, %rcx
  5466. movq $42, -16(%rbp)
  5467. addq $7, %rcx
  5468. movq %rcx, -8(%rbp)
  5469. movq -16(%rbp), %rax
  5470. addq %rax, -8(%rbp)
  5471. negq %rcx
  5472. addq %rcx, -8(%rbp)
  5473. movq -8(%rbp), %rdi
  5474. callq print_int
  5475. \end{lstlisting}
  5476. \end{minipage}
  5477. \fi}
  5478. \begin{exercise}\normalfont
  5479. Change your implementation of \code{allocate\_registers} to take move
  5480. biasing into account. Create two new tests that include at least one
  5481. opportunity for move biasing and visually inspect the output x86
  5482. programs to make sure that your move biasing is working properly. Make
  5483. sure that your compiler still passes all of the tests.
  5484. \end{exercise}
  5485. %To do: another neat challenge would be to do
  5486. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5487. %% \subsection{Output of the Running Example}
  5488. %% \label{sec:reg-alloc-output}
  5489. % challenge: prioritize variables based on execution frequencies
  5490. % and the number of uses of a variable
  5491. % challenge: enhance the coloring algorithm using Chaitin's
  5492. % approach of prioritizing high-degree variables
  5493. % by removing low-degree variables (coloring them later)
  5494. % from the interference graph
  5495. \section{Further Reading}
  5496. \label{sec:register-allocation-further-reading}
  5497. Early register allocation algorithms were developed for Fortran
  5498. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5499. of graph coloring began in the late 1970s and early 1980s with the
  5500. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5501. algorithm is based on the following observation of
  5502. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  5503. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  5504. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  5505. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5506. different colors, but since there are less than $k$ of them, there
  5507. will be one or more colors left over to use for coloring $v$ in $G$.
  5508. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5509. less than $k$ from the graph and recursively colors the rest of the
  5510. graph. Upon returning from the recursion, it colors $v$ with one of
  5511. the available colors and returns. \citet{Chaitin:1982vn} augments
  5512. this algorithm to handle spilling as follows. If there are no vertices
  5513. of degree lower than $k$ then pick a vertex at random, spill it,
  5514. remove it from the graph, and proceed recursively to color the rest of
  5515. the graph.
  5516. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5517. move-related and that don't interfere with each other, a process
  5518. called \emph{coalescing}. While coalescing decreases the number of
  5519. moves, it can make the graph more difficult to
  5520. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5521. which two variables are merged only if they have fewer than $k$
  5522. neighbors of high degree. \citet{George:1996aa} observe that
  5523. conservative coalescing is sometimes too conservative and make it more
  5524. aggressive by iterating the coalescing with the removal of low-degree
  5525. vertices.
  5526. %
  5527. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5528. also propose \emph{biased coloring} in which a variable is assigned to
  5529. the same color as another move-related variable if possible, as
  5530. discussed in Section~\ref{sec:move-biasing}.
  5531. %
  5532. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5533. performs coalescing, graph coloring, and spill code insertion until
  5534. all variables have been assigned a location.
  5535. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5536. spills variables that don't have to be: a high-degree variable can be
  5537. colorable if many of its neighbors are assigned the same color.
  5538. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5539. high-degree vertex is not immediately spilled. Instead the decision is
  5540. deferred until after the recursive call, at which point it is apparent
  5541. whether there is actually an available color or not. We observe that
  5542. this algorithm is equivalent to the smallest-last ordering
  5543. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5544. be registers and the rest to be stack locations.
  5545. %% biased coloring
  5546. Earlier editions of the compiler course at Indiana University
  5547. \citep{Dybvig:2010aa} were based on the algorithm of
  5548. \citet{Briggs:1994kx}.
  5549. The smallest-last ordering algorithm is one of many \emph{greedy}
  5550. coloring algorithms. A greedy coloring algorithm visits all the
  5551. vertices in a particular order and assigns each one the first
  5552. available color. An \emph{offline} greedy algorithm chooses the
  5553. ordering up-front, prior to assigning colors. The algorithm of
  5554. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5555. ordering does not depend on the colors assigned, so the algorithm
  5556. could be split into two phases. Other orderings are possible. For
  5557. example, \citet{Chow:1984ys} order variables according to an estimate
  5558. of runtime cost.
  5559. An \emph{online} greedy coloring algorithm uses information about the
  5560. current assignment of colors to influence the order in which the
  5561. remaining vertices are colored. The saturation-based algorithm
  5562. described in this chapter is one such algorithm. We choose to use
  5563. saturation-based coloring is because it is fun to introduce graph
  5564. coloring via Sudoku.
  5565. A register allocator may choose to map each variable to just one
  5566. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5567. variable to one or more locations. The later can be achieved by
  5568. \emph{live range splitting}, where a variable is replaced by several
  5569. variables that each handle part of its live
  5570. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5571. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5572. %% replacement algorithm, bottom-up local
  5573. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5574. %% Cooper: top-down (priority bassed), bottom-up
  5575. %% top-down
  5576. %% order variables by priority (estimated cost)
  5577. %% caveat: split variables into two groups:
  5578. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5579. %% color the constrained ones first
  5580. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5581. %% cite J. Cocke for an algorithm that colors variables
  5582. %% in a high-degree first ordering
  5583. %Register Allocation via Usage Counts, Freiburghouse CACM
  5584. \citet{Palsberg:2007si} observe that many of the interference graphs
  5585. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5586. that is, every cycle with four or more edges has an edge which is not
  5587. part of the cycle but which connects two vertices on the cycle. Such
  5588. graphs can be optimally colored by the greedy algorithm with a vertex
  5589. ordering determined by maximum cardinality search.
  5590. In situations where compile time is of utmost importance, such as in
  5591. just-in-time compilers, graph coloring algorithms can be too expensive
  5592. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  5593. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5594. \chapter{Booleans and Control Flow}
  5595. \label{ch:Rif}
  5596. \index{subject}{Boolean}
  5597. \index{subject}{control flow}
  5598. \index{subject}{conditional expression}
  5599. The \LangInt{} and \LangVar{} languages only have a single kind of
  5600. value, integers. In this chapter we add a second kind of value, the
  5601. Booleans, to create the \LangIf{} language. The Boolean values
  5602. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5603. respectively in \racket{Racket}\python{Python}.
  5604. The \LangIf{} language includes several
  5605. operations that involve Booleans (\key{and}, \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if} expression \python{and statement}.
  5606. With the addition of \key{if}, programs can have non-trivial control flow which
  5607. \racket{impacts \code{explicate\_control} and liveness analysis}
  5608. \python{impacts liveness analysis and motivates a new pass named
  5609. \code{explicate\_control}}. Also, because
  5610. we now have two kinds of values, we need to handle programs that apply
  5611. an operation to the wrong kind of value, such as
  5612. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5613. There are two language design options for such situations. One option
  5614. is to signal an error and the other is to provide a wider
  5615. interpretation of the operation. \racket{The Racket
  5616. language}\python{Python} uses a mixture of these two options,
  5617. depending on the operation and the kind of value. For example, the
  5618. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5619. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5620. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5621. %
  5622. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5623. in Racket because \code{car} expects a pair.}
  5624. %
  5625. \python{On the other hand, \code{1[0]} results in a run-time error
  5626. in Python because an ``\code{int} object is not subscriptable''.}
  5627. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5628. design choices as \racket{Racket}\python{Python}, except much of the
  5629. error detection happens at compile time instead of run
  5630. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5631. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5632. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5633. Racket}\python{MyPy} reports a compile-time error
  5634. %
  5635. \racket{because Racket expects the type of the argument to be of the form
  5636. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5637. %
  5638. \python{stating that a ``value of type \code{int} is not indexable''.}
  5639. The \LangIf{} language performs type checking during compilation like
  5640. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5641. alternative choice, that is, a dynamically typed language like
  5642. \racket{Racket}\python{Python}.
  5643. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5644. for some operations we are more restrictive, for example, rejecting
  5645. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5646. This chapter is organized as follows. We begin by defining the syntax
  5647. and interpreter for the \LangIf{} language
  5648. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5649. checking and build a type checker for \LangIf{}
  5650. (Section~\ref{sec:type-check-Rif}).
  5651. %
  5652. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5653. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5654. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5655. %
  5656. The remaining sections of this chapter discuss how our compiler passes
  5657. change to accommodate Booleans and conditional control flow. There is
  5658. a new pass, named \code{shrink}, that translates some operators into
  5659. others, thereby reducing the number of operators that need to be
  5660. handled in later passes.
  5661. %
  5662. \racket{The largest changes occur in \code{explicate\_control}, to
  5663. translate \code{if} expressions into control-flow graphs
  5664. (Section~\ref{sec:explicate-control-Rif}).}
  5665. %
  5666. \python{The largest addition is a new pass named
  5667. \code{explicate\_control} that translates \code{if} expressions and
  5668. statements into conditional \code{goto}'s
  5669. (Section~\ref{sec:explicate-control-Rif}).}
  5670. %
  5671. Regarding register allocation, there is the interesting question of
  5672. how to handle conditional \code{goto}'s during liveness analysis.
  5673. \section{The \LangIf{} Language}
  5674. \label{sec:lang-if}
  5675. The concrete syntax of the \LangIf{} language is defined in
  5676. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  5677. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  5678. \LangVar{}\racket{(shown in gray)}, the Boolean literals \TRUE{} and
  5679. \FALSE{}, and the \code{if} expression \python{and statement}. We expand the
  5680. operators to include
  5681. \begin{enumerate}
  5682. \item subtraction on integers,
  5683. \item the logical operators \key{and}, \key{or} and \key{not},
  5684. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5685. for comparing two integers or two Booleans for equality, and
  5686. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5687. comparing integers.
  5688. \end{enumerate}
  5689. \racket{We reorganize the abstract syntax for the primitive
  5690. operations in Figure~\ref{fig:Rif-syntax}, using only one grammar
  5691. rule for all of them. This means that the grammar no longer checks
  5692. whether the arity of an operators matches the number of
  5693. arguments. That responsibility is moved to the type checker for
  5694. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Rif}.}
  5695. \begin{figure}[tp]
  5696. \centering
  5697. \fbox{
  5698. \begin{minipage}{0.96\textwidth}
  5699. {\if\edition\racketEd\color{olive}
  5700. \[
  5701. \begin{array}{lcl}
  5702. \itm{bool} &::=& \TRUE \MID \FALSE \\
  5703. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5704. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} } \MID \CSUB{\Exp}{\Exp} \\
  5705. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} } \\
  5706. &\MID& \itm{bool}
  5707. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5708. \MID (\key{not}\;\Exp) \\
  5709. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5710. \LangIfM{} &::=& \Exp
  5711. \end{array}
  5712. \]
  5713. \fi}
  5714. {\if\edition\pythonEd\color{purple}
  5715. \[
  5716. \begin{array}{rcl}
  5717. \itm{binop} &::= & \key{+} \MID \key{-} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5718. \itm{uniop} &::= & \key{-} \MID \key{not} \\
  5719. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \itm{uniop}\;\Exp \MID \Exp \; \itm{binop} \; \Exp \MID \Var{} \\
  5720. &\MID& \TRUE \MID \FALSE \MID \Exp\;\key{if}\;\Exp\;\key{else}\;\Exp\\
  5721. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \Var\mathop{\key{=}}\Exp
  5722. \MID \key{if}\; \Exp \;\key{:}\; \Stmt^{+} \;\key{else:}\; \Stmt^{+}\\
  5723. \LangVarM{} &::=& \Stmt^{*}
  5724. \end{array}
  5725. \]
  5726. \fi}
  5727. \end{minipage}
  5728. }
  5729. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  5730. (Figure~\ref{fig:Rvar-concrete-syntax}) with Booleans and conditionals.}
  5731. \label{fig:Rif-concrete-syntax}
  5732. \end{figure}
  5733. \begin{figure}[tp]
  5734. \centering
  5735. \fbox{
  5736. \begin{minipage}{0.96\textwidth}
  5737. {\if\edition\racketEd\color{olive}
  5738. \[
  5739. \begin{array}{lcl}
  5740. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  5741. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  5742. \itm{op} &::= & \itm{cmp} \MID \code{read} \MID \code{+} \MID \code{-}
  5743. \MID \code{and} \MID \code{or} \MID \code{not} \\
  5744. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  5745. &\MID& \PRIM{\itm{op}}{\Exp\ldots}\\
  5746. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5747. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  5748. \end{array}
  5749. \]
  5750. \fi}
  5751. {\if\edition\pythonEd\color{purple}
  5752. \[
  5753. \begin{array}{lcl}
  5754. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  5755. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  5756. \itm{bool} &::=& \code{True} \MID \code{False} \\
  5757. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  5758. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  5759. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  5760. &\MID& \BINOP{\Exp}{\itm{binop}}{\Exp}
  5761. \MID \UNIOP{\itm{uniop}}{\Exp}\\
  5762. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  5763. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  5764. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5765. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  5766. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  5767. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  5768. \end{array}
  5769. \]
  5770. \fi}
  5771. \end{minipage}
  5772. }
  5773. \caption{The abstract syntax of \LangIf{}.}
  5774. \label{fig:Rif-syntax}
  5775. \end{figure}
  5776. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  5777. which inherits from the interpreter for \LangVar{}
  5778. (Figure~\ref{fig:interp-Rvar}). The literals \TRUE{} and \FALSE{}
  5779. evaluate to the corresponding Boolean values. The conditional
  5780. expression $\CIF{\itm{cnd}}{\itm{thn}}{\itm{els}}$ evaluates \itm{cnd}
  5781. and then either evaluates \itm{thn} or \itm{els} depending on whether
  5782. \itm{cnd} produced \TRUE{} or \FALSE{}. The logical operations
  5783. \code{and}, \code{or}, and \code{not} behave as you might expect, but
  5784. note that the \code{and} an \code{or} operations are
  5785. short-circuiting.
  5786. %
  5787. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  5788. is not evaluated if $e_1$ evaluates to \FALSE{}.
  5789. %
  5790. Similarly, given the expression $\COR{e_1}{e_2}$, the expression $e_2$
  5791. is not evaluated if $e_1$ evaluates to \TRUE{}.
  5792. \racket{With the increase in the number of primitive operations, the
  5793. interpreter would become repetitive without some care. We refactor
  5794. the case for \code{Prim}, moving the code that differs with each
  5795. operation into the \code{interp\_op} method shown in in
  5796. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  5797. separately because of its short-circuiting behavior.}
  5798. \begin{figure}[tbp]
  5799. {\if\edition\racketEd\color{olive}
  5800. \begin{lstlisting}
  5801. (define interp_Rif_class
  5802. (class interp_Rvar_class
  5803. (super-new)
  5804. (define/public (interp_op op) ...)
  5805. (define/override ((interp_exp env) e)
  5806. (define recur (interp_exp env))
  5807. (match e
  5808. [(Bool b) b]
  5809. [(If cnd thn els)
  5810. (match (recur cnd)
  5811. [#t (recur thn)]
  5812. [#f (recur els)])]
  5813. [(Prim 'and (list e1 e2))
  5814. (match (recur e1)
  5815. [#t (match (recur e2) [#t #t] [#f #f])]
  5816. [#f #f])]
  5817. [(Prim op args)
  5818. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  5819. [else ((super interp_exp env) e)]))
  5820. ))
  5821. (define (interp_Rif p)
  5822. (send (new interp_Rif_class) interp_program p))
  5823. \end{lstlisting}
  5824. \fi}
  5825. {\if\edition\pythonEd\color{purple}
  5826. \begin{lstlisting}
  5827. class InterpPif(InterpPvar):
  5828. def interp_exp(self, e, env):
  5829. match e:
  5830. case IfExp(test, body, orelse):
  5831. match self.interp_exp(test, env):
  5832. case True:
  5833. return self.interp_exp(body, env)
  5834. case False:
  5835. return self.interp_exp(orelse, env)
  5836. case BinOp(left, Sub(), right):
  5837. l = self.interp_exp(left, env)
  5838. r = self.interp_exp(right, env)
  5839. return l - r
  5840. case UnaryOp(Not(), v):
  5841. return not self.interp_exp(v, env)
  5842. case BoolOp(And(), values):
  5843. left = values[0]; right = values[1]
  5844. match self.interp_exp(left, env):
  5845. case True:
  5846. return self.interp_exp(right, env)
  5847. case False:
  5848. return False
  5849. case BoolOp(Or(), values):
  5850. left = values[0]; right = values[1]
  5851. match self.interp_exp(left, env):
  5852. case True:
  5853. return True
  5854. case False:
  5855. return self.interp_exp(right, env)
  5856. case Compare(left, [cmp], [right]):
  5857. l = self.interp_exp(left, env)
  5858. r = self.interp_exp(right, env)
  5859. return self.interp_cmp(cmp)(l, r)
  5860. case _:
  5861. return super().interp_exp(e, env)
  5862. def interp_stmts(self, ss, env):
  5863. if len(ss) == 0:
  5864. return
  5865. match ss[0]:
  5866. case If(test, body, orelse):
  5867. match self.interp_exp(test, env):
  5868. case True:
  5869. return self.interp_stmts(body + ss[1:], env)
  5870. case False:
  5871. return self.interp_stmts(orelse + ss[1:], env)
  5872. case _:
  5873. return super().interp_stmts(ss, env)
  5874. ...
  5875. \end{lstlisting}
  5876. \fi}
  5877. \caption{Interpreter for the \LangIf{} language. \racket{(See
  5878. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  5879. \python{(See Figure~\ref{fig:interp-cmp-Rif} for \code{interp\_cmp}.)}}
  5880. \label{fig:interp-Rif}
  5881. \end{figure}
  5882. {\if\edition\racketEd\color{olive}
  5883. \begin{figure}[tbp]
  5884. \begin{lstlisting}
  5885. (define/public (interp_op op)
  5886. (match op
  5887. ['+ fx+]
  5888. ['- fx-]
  5889. ['read read-fixnum]
  5890. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  5891. ['or (lambda (v1 v2)
  5892. (cond [(and (boolean? v1) (boolean? v2))
  5893. (or v1 v2)]))]
  5894. ['eq? (lambda (v1 v2)
  5895. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5896. (and (boolean? v1) (boolean? v2))
  5897. (and (vector? v1) (vector? v2)))
  5898. (eq? v1 v2)]))]
  5899. ['< (lambda (v1 v2)
  5900. (cond [(and (fixnum? v1) (fixnum? v2))
  5901. (< v1 v2)]))]
  5902. ['<= (lambda (v1 v2)
  5903. (cond [(and (fixnum? v1) (fixnum? v2))
  5904. (<= v1 v2)]))]
  5905. ['> (lambda (v1 v2)
  5906. (cond [(and (fixnum? v1) (fixnum? v2))
  5907. (> v1 v2)]))]
  5908. ['>= (lambda (v1 v2)
  5909. (cond [(and (fixnum? v1) (fixnum? v2))
  5910. (>= v1 v2)]))]
  5911. [else (error 'interp_op "unknown operator")]))
  5912. \end{lstlisting}
  5913. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  5914. \label{fig:interp-op-Rif}
  5915. \end{figure}
  5916. \fi}
  5917. {\if\edition\pythonEd\color{purple}
  5918. \begin{figure}
  5919. \begin{lstlisting}
  5920. class InterpPif(InterpPvar):
  5921. ...
  5922. def interp_cmp(self, cmp):
  5923. match cmp:
  5924. case Lt():
  5925. return lambda x, y: x < y
  5926. case LtE():
  5927. return lambda x, y: x <= y
  5928. case Gt():
  5929. return lambda x, y: x > y
  5930. case GtE():
  5931. return lambda x, y: x >= y
  5932. case Eq():
  5933. return lambda x, y: x == y
  5934. case NotEq():
  5935. return lambda x, y: x != y
  5936. \end{lstlisting}
  5937. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  5938. \label{fig:interp-cmp-Rif}
  5939. \end{figure}
  5940. \fi}
  5941. \section{Type Checking \LangIf{} Programs}
  5942. \label{sec:type-check-Rif}
  5943. \index{subject}{type checking}
  5944. \index{subject}{semantic analysis}
  5945. It is helpful to think about type checking in two complementary
  5946. ways. A type checker predicts the type of value that will be produced
  5947. by each expression in the program. For \LangIf{}, we have just two types,
  5948. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  5949. {\if\edition\racketEd\color{olive}
  5950. \begin{lstlisting}
  5951. (+ 10 (- (+ 12 20)))
  5952. \end{lstlisting}
  5953. \fi}
  5954. {\if\edition\pythonEd\color{purple}
  5955. \begin{lstlisting}
  5956. 10 + -(12 + 20)
  5957. \end{lstlisting}
  5958. \fi}
  5959. \noindent produces a value of type \INTTY{} while
  5960. {\if\edition\racketEd\color{olive}
  5961. \begin{lstlisting}
  5962. (and (not #f) #t)
  5963. \end{lstlisting}
  5964. \fi}
  5965. {\if\edition\pythonEd\color{purple}
  5966. \begin{lstlisting}
  5967. (not False) and True
  5968. \end{lstlisting}
  5969. \fi}
  5970. \noindent produces a value of type \BOOLTY{}.
  5971. Another way to think about type checking is that it enforces a set of
  5972. rules about which operators can be applied to which kinds of
  5973. values. For example, our type checker for \LangIf{} signals an error
  5974. for the below expression
  5975. {\if\edition\racketEd\color{olive}
  5976. \begin{lstlisting}
  5977. (not (+ 10 (- (+ 12 20))))
  5978. \end{lstlisting}
  5979. \fi}
  5980. {\if\edition\pythonEd\color{purple}
  5981. \begin{lstlisting}
  5982. not (10 + -(12 + 20))
  5983. \end{lstlisting}
  5984. \fi}
  5985. The subexpression
  5986. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  5987. has type \INTTY{} but the type checker enforces the rule that the argument of
  5988. \code{not} must be an expression of type \BOOLTY{}.
  5989. We implement type checking using classes and methods because they
  5990. provide the open recursion needed to reuse code as we extend the type
  5991. checker in later chapters, analogous to the use of classes and methods
  5992. for the interpreters (Section~\ref{sec:extensible-interp}).
  5993. We separate the type checker for the \LangVar{} fragment into its own
  5994. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  5995. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  5996. from the type checker for \LangVar{}. These type checkers are in the
  5997. files
  5998. \racket{\code{type-check-Rvar.rkt}}\python{\code{type\_check\_Pvar.py}}
  5999. and
  6000. \racket{\code{type-check-Rif.rkt}}\python{\code{type\_check\_Pif.py}}
  6001. of the support code.
  6002. %
  6003. Each type checker is a structurally recursive function over the AST.
  6004. Given an input expression \code{e}, the type checker either signals an
  6005. error or returns an expression and its type (\INTTY{} or
  6006. \BOOLTY{}). It returns an expression because there are situations
  6007. in which we want to change or update the expression.
  6008. Next we discuss the \code{type\_check\_exp} function in
  6009. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  6010. \INTTY{}. To handle variables, the type checker uses the environment
  6011. \code{env} to map variables to types.
  6012. %
  6013. \racket{Consider the case for \key{let}. We type check the
  6014. initializing expression to obtain its type \key{T} and then
  6015. associate type \code{T} with the variable \code{x} in the
  6016. environment used to type check the body of the \key{let}. Thus,
  6017. when the type checker encounters a use of variable \code{x}, it can
  6018. find its type in the environment.}
  6019. %
  6020. \python{Consider the case for assignment. We type check the
  6021. initializing expression to obtain its type \key{t}. If the variable
  6022. \code{lhs.id} is already in the environment because there was a
  6023. prior assignment, we check that this initializer has the same type
  6024. as the prior one. If this is the first assignment to the variable,
  6025. we associate type \code{t} with the variable \code{lhs.id} in the
  6026. environment. Thus, when the type checker encounters a use of
  6027. variable \code{x}, it can find its type in the environment.}
  6028. %
  6029. \racket{Regarding primitive operators, we recursively analyze the
  6030. arguments and then invoke \code{type\_check\_op} to check whether
  6031. the argument types are allowed.}
  6032. %
  6033. \python{Regarding addition and negation, we recursively analyze the
  6034. arguments, check that they have type \INT{}, and return \INT{}.}
  6035. \racket{Several auxiliary methods are used in the type checker. The
  6036. method \code{operator-types} defines a dictionary that maps the
  6037. operator names to their parameter and return types. The
  6038. \code{type-equal?} method determines whether two types are equal,
  6039. which for now simply dispatches to \code{equal?} (deep
  6040. equality). The \code{check-type-equal?} method triggers an error if
  6041. the two types are not equal. The \code{type-check-op} method looks
  6042. up the operator in the \code{operator-types} dictionary and then
  6043. checks whether the argument types are equal to the parameter types.
  6044. The result is the return type of the operator.}
  6045. %
  6046. \python{The auxiliary method \code{check\_type\_equal} method triggers
  6047. an error if the two types are not equal.}
  6048. \begin{figure}[tbp]
  6049. {\if\edition\racketEd\color{olive}
  6050. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6051. (define type-check-Rvar_class
  6052. (class object%
  6053. (super-new)
  6054. (define/public (operator-types)
  6055. '((+ . ((Integer Integer) . Integer))
  6056. (- . ((Integer) . Integer))
  6057. (read . (() . Integer))))
  6058. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6059. (define/public (check-type-equal? t1 t2 e)
  6060. (unless (type-equal? t1 t2)
  6061. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6062. (define/public (type-check-op op arg-types e)
  6063. (match (dict-ref (operator-types) op)
  6064. [`(,param-types . ,return-type)
  6065. (for ([at arg-types] [pt param-types])
  6066. (check-type-equal? at pt e))
  6067. return-type]
  6068. [else (error 'type-check-op "unrecognized ~a" op)]))
  6069. (define/public (type-check-exp env)
  6070. (lambda (e)
  6071. (match e
  6072. [(Int n) (values (Int n) 'Integer)]
  6073. [(Var x) (values (Var x) (dict-ref env x))]
  6074. [(Let x e body)
  6075. (define-values (e^ Te) ((type-check-exp env) e))
  6076. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6077. (values (Let x e^ b) Tb)]
  6078. [(Prim op es)
  6079. (define-values (new-es ts)
  6080. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6081. (values (Prim op new-es) (type-check-op op ts e))]
  6082. [else (error 'type-check-exp "couldn't match" e)])))
  6083. (define/public (type-check-program e)
  6084. (match e
  6085. [(Program info body)
  6086. (define-values (body^ Tb) ((type-check-exp '()) body))
  6087. (check-type-equal? Tb 'Integer body)
  6088. (Program info body^)]
  6089. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  6090. ))
  6091. (define (type-check-Rvar p)
  6092. (send (new type-check-Rvar_class) type-check-program p))
  6093. \end{lstlisting}
  6094. \fi}
  6095. {\if\edition\pythonEd\color{purple}
  6096. \begin{lstlisting}
  6097. class TypeCheckPvar:
  6098. def check_type_equal(self, t1, t2, e):
  6099. if t1 != t2:
  6100. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6101. raise Exception(msg)
  6102. def type_check_exp(self, e, env):
  6103. match e:
  6104. case BinOp(left, Add(), right):
  6105. l = self.type_check_exp(left, env)
  6106. check_type_equal(l, int, left)
  6107. r = self.type_check_exp(right, env)
  6108. check_type_equal(r, int, right)
  6109. return int
  6110. case UnaryOp(USub(), v):
  6111. t = self.type_check_exp(v, env)
  6112. check_type_equal(t, int, v)
  6113. return int
  6114. case Name(id):
  6115. return env[id]
  6116. case Constant(value) if isinstance(value, int):
  6117. return int
  6118. case Call(Name('input_int'), []):
  6119. return int
  6120. def type_check_stmts(self, ss, env):
  6121. if len(ss) == 0:
  6122. return
  6123. match ss[0]:
  6124. case Assign([lhs], value):
  6125. t = self.type_check_exp(value, env)
  6126. if lhs.id in env:
  6127. check_type_equal(env[lhs.id], t, value)
  6128. else:
  6129. env[lhs.id] = t
  6130. return self.type_check_stmts(ss[1:], env)
  6131. case Expr(Call(Name('print'), [arg])):
  6132. t = self.type_check_exp(arg, env)
  6133. check_type_equal(t, int, arg)
  6134. return self.type_check_stmts(ss[1:], env)
  6135. case Expr(value):
  6136. self.type_check_exp(value, env)
  6137. return self.type_check_stmts(ss[1:], env)
  6138. def type_check_P(self, p):
  6139. match p:
  6140. case Module(body):
  6141. self.type_check_stmts(body, {})
  6142. \end{lstlisting}
  6143. \fi}
  6144. \caption{Type checker for the \LangVar{} language.}
  6145. \label{fig:type-check-Rvar}
  6146. \end{figure}
  6147. \begin{figure}[tbp]
  6148. {\if\edition\racketEd\color{olive}
  6149. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6150. (define type-check-Rif_class
  6151. (class type-check-Rvar_class
  6152. (super-new)
  6153. (inherit check-type-equal?)
  6154. (define/override (operator-types)
  6155. (append '((- . ((Integer Integer) . Integer))
  6156. (and . ((Boolean Boolean) . Boolean))
  6157. (or . ((Boolean Boolean) . Boolean))
  6158. (< . ((Integer Integer) . Boolean))
  6159. (<= . ((Integer Integer) . Boolean))
  6160. (> . ((Integer Integer) . Boolean))
  6161. (>= . ((Integer Integer) . Boolean))
  6162. (not . ((Boolean) . Boolean))
  6163. )
  6164. (super operator-types)))
  6165. (define/override (type-check-exp env)
  6166. (lambda (e)
  6167. (match e
  6168. [(Bool b) (values (Bool b) 'Boolean)]
  6169. [(Prim 'eq? (list e1 e2))
  6170. (define-values (e1^ T1) ((type-check-exp env) e1))
  6171. (define-values (e2^ T2) ((type-check-exp env) e2))
  6172. (check-type-equal? T1 T2 e)
  6173. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6174. [(If cnd thn els)
  6175. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6176. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6177. (define-values (els^ Te) ((type-check-exp env) els))
  6178. (check-type-equal? Tc 'Boolean e)
  6179. (check-type-equal? Tt Te e)
  6180. (values (If cnd^ thn^ els^) Te)]
  6181. [else ((super type-check-exp env) e)])))
  6182. ))
  6183. (define (type-check-Rif p)
  6184. (send (new type-check-Rif_class) type-check-program p))
  6185. \end{lstlisting}
  6186. \fi}
  6187. {\if\edition\pythonEd\color{purple}
  6188. \begin{lstlisting}
  6189. class TypeCheckPif(TypeCheckPvar):
  6190. def type_check_exp(self, e, env):
  6191. match e:
  6192. case Constant(value) if isinstance(value, bool):
  6193. return bool
  6194. case BinOp(left, Sub(), right):
  6195. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6196. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6197. return int
  6198. case UnaryOp(Not(), v):
  6199. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6200. return bool
  6201. case BoolOp(op, values):
  6202. left = values[0] ; right = values[1]
  6203. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6204. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6205. return bool
  6206. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6207. or isinstance(cmp, NotEq):
  6208. l = self.type_check_exp(left, env)
  6209. r = self.type_check_exp(right, env)
  6210. check_type_equal(l, r, e)
  6211. return bool
  6212. case Compare(left, [cmp], [right]):
  6213. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6214. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6215. return bool
  6216. case IfExp(test, body, orelse):
  6217. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6218. b = self.type_check_exp(body, env)
  6219. o = self.type_check_exp(orelse, env)
  6220. check_type_equal(b, o, e)
  6221. return b
  6222. case _:
  6223. return super().type_check_exp(e, env)
  6224. def type_check_stmts(self, ss, env):
  6225. if len(ss) == 0:
  6226. return
  6227. match ss[0]:
  6228. case If(test, body, orelse):
  6229. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6230. b = self.type_check_stmts(body, env)
  6231. o = self.type_check_stmts(orelse, env)
  6232. check_type_equal(b, o, ss[0])
  6233. return self.type_check_stmts(ss[1:], env)
  6234. case _:
  6235. return super().type_check_stmts(ss, env)
  6236. \end{lstlisting}
  6237. \fi}
  6238. \caption{Type checker for the \LangIf{} language.}
  6239. \label{fig:type-check-Rif}
  6240. \end{figure}
  6241. Next we discuss the type checker for \LangIf{} in
  6242. Figure~\ref{fig:type-check-Rif}.
  6243. %
  6244. The type of a Boolean constant is \code{Boolean}.
  6245. %
  6246. \racket{The \code{operator-types} function adds dictionary entries for
  6247. the other new operators.}
  6248. %
  6249. \python{Subtraction requires its arguments to be of type \INTTY{} and produces
  6250. an \INTTY{}. Negation requires its argument to be a \BOOLTY{} and
  6251. produces a \BOOLTY{}. Similarly for logical-and and logical-or. }
  6252. %
  6253. The equality operators requires the two arguments to have the same
  6254. type.
  6255. %
  6256. \python{The other comparisons (less-than, etc.) require their
  6257. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6258. %
  6259. The condition of an \code{if} must
  6260. be of \BOOLTY{} type and the two branches must have the same type.
  6261. \begin{exercise}\normalfont
  6262. Create 10 new test programs in \LangIf{}. Half of the programs should
  6263. have a type error. For those programs, create an empty file with the
  6264. same base name but with file extension \code{.tyerr}. For example, if
  6265. the test
  6266. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6267. is expected to error, then create
  6268. an empty file named \code{cond\_test\_14.tyerr}.
  6269. %
  6270. \racket{This indicates to \code{interp-tests} and
  6271. \code{compiler-tests} that a type error is expected. }
  6272. %
  6273. \racket{This indicates to the \code{run-tests.py} scripts that a type
  6274. error is expected.}
  6275. %
  6276. The other half of the test programs should not have type errors.
  6277. %
  6278. \racket{In the \code{run-tests.rkt} script, change the second argument
  6279. of \code{interp-tests} and \code{compiler-tests} to
  6280. \code{type-check-Rif}, which causes the type checker to run prior to
  6281. the compiler passes. Temporarily change the \code{passes} to an
  6282. empty list and run the script, thereby checking that the new test
  6283. programs either type check or not as intended.}
  6284. %
  6285. Run the test script to check that these test programs type check as
  6286. expected.
  6287. \end{exercise}
  6288. \section{The \LangCIf{} Intermediate Language}
  6289. \label{sec:Cif}
  6290. {\if\edition\pythonEd\color{purple}
  6291. The output of \key{explicate\_control} is a language similar to the
  6292. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6293. \code{goto} statements, so we name it \LangCIf{}. The abstract syntax
  6294. for \LangCIf{} is defined in Figure~\ref{fig:c1-syntax}. (The
  6295. concrete syntax for \LangCIf{} is in the Appendix,
  6296. Figure~\ref{fig:c1-concrete-syntax}.)
  6297. %
  6298. The \LangCIf{} language supports the same operators as \LangIf{} but
  6299. the arguments of operators are restricted to atomic
  6300. expressions. The \LangCIf{} language does not include
  6301. \code{if} expressions and the \code{if} statements are restricted:
  6302. the condition must be a comparison
  6303. and the two branches may only contain \code{goto} statements.
  6304. (These restrictions make them easy to translate to x86.)
  6305. %
  6306. Also, a \LangCIf{} program consists of a dictionary mapping labels to
  6307. lists of statements, instead of simply being a list of statements.
  6308. \fi}
  6309. \racket{
  6310. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  6311. \LangCIf{} intermediate language. (The concrete syntax is in the
  6312. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  6313. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  6314. operators to the \Exp{} non-terminal and the literals \TRUE{} and
  6315. \FALSE{} to the \Arg{} non-terminal.
  6316. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6317. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6318. statement is a comparison operation and the branches are \code{goto}
  6319. statements, making it straightforward to compile \code{if} statements
  6320. to x86.
  6321. }
  6322. \begin{figure}[tp]
  6323. \fbox{
  6324. \begin{minipage}{0.96\textwidth}
  6325. \small
  6326. {\if\edition\racketEd\color{olive}
  6327. \[
  6328. \begin{array}{lcl}
  6329. \Atm &::=& \gray{\INT{\Int} \MID \VAR{\Var}} \MID \BOOL{\itm{bool}} \\
  6330. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  6331. \Exp &::= & \gray{ \Atm \MID \READ{} }\\
  6332. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6333. &\MID& \UNIOP{\key{'not}}{\Atm}
  6334. \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6335. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  6336. \Tail &::= & \gray{\RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} }
  6337. \MID \GOTO{\itm{label}} \\
  6338. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  6339. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  6340. \end{array}
  6341. \]
  6342. \fi}
  6343. {\if\edition\pythonEd\color{purple}
  6344. \[
  6345. \begin{array}{lcl}
  6346. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6347. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  6348. \Exp &::= & \Atm \MID \READ{} \\
  6349. &\MID& \BINOP{\Atm}{\itm{binop}}{\Atm}
  6350. \MID \UNIOP{\itm{uniop}}{\Atm} \\
  6351. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm}
  6352. \MID \BOOLOP{\itm{boolop}}{\Atm}{\Atm} \\
  6353. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6354. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6355. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6356. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS} \\
  6357. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\,\key{:}\,\Stmt^{+}, \ldots \RC}
  6358. \end{array}
  6359. \]
  6360. \fi}
  6361. \end{minipage}
  6362. }
  6363. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6364. (Figure~\ref{fig:c0-syntax})}.}
  6365. \label{fig:c1-syntax}
  6366. \end{figure}
  6367. \section{The \LangXIf{} Language}
  6368. \label{sec:x86-if}
  6369. \index{subject}{x86} To implement the new logical operations, the comparison
  6370. operations, and the \key{if} expression, we need to delve further into
  6371. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6372. define the concrete and abstract syntax for the \LangXIf{} subset
  6373. of x86, which includes instructions for logical operations,
  6374. comparisons, and conditional jumps.
  6375. One challenge is that x86 does not provide an instruction that
  6376. directly implements logical negation (\code{not} in \LangIf{} and
  6377. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6378. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6379. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6380. bit of its arguments, and writes the results into its second argument.
  6381. Recall the truth table for exclusive-or:
  6382. \begin{center}
  6383. \begin{tabular}{l|cc}
  6384. & 0 & 1 \\ \hline
  6385. 0 & 0 & 1 \\
  6386. 1 & 1 & 0
  6387. \end{tabular}
  6388. \end{center}
  6389. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6390. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6391. for the bit $1$, the result is the opposite of the second bit. Thus,
  6392. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6393. the first argument:
  6394. \[
  6395. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Arg}}
  6396. \qquad\Rightarrow\qquad
  6397. \begin{array}{l}
  6398. \key{movq}~ \Arg\key{,} \Var\\
  6399. \key{xorq}~ \key{\$1,} \Var
  6400. \end{array}
  6401. \]
  6402. \begin{figure}[tp]
  6403. \fbox{
  6404. \begin{minipage}{0.96\textwidth}
  6405. \[
  6406. \begin{array}{lcl}
  6407. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6408. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6409. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6410. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6411. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6412. \key{subq} \; \Arg\key{,} \Arg \MID
  6413. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6414. && \gray{ \key{callq} \; \itm{label} \MID
  6415. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} } \\
  6416. && \gray{ \itm{label}\key{:}\; \Instr }
  6417. \MID \key{xorq}~\Arg\key{,}~\Arg
  6418. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6419. && \key{set}cc~\Arg
  6420. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6421. \MID \key{j}cc~\itm{label}
  6422. \\
  6423. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6424. & & \gray{ \key{main:} \; \Instr\ldots }
  6425. \end{array}
  6426. \]
  6427. \end{minipage}
  6428. }
  6429. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6430. \label{fig:x86-1-concrete}
  6431. \end{figure}
  6432. \begin{figure}[tp]
  6433. \fbox{
  6434. \begin{minipage}{0.98\textwidth}
  6435. \small
  6436. \[
  6437. \begin{array}{lcl}
  6438. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6439. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6440. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6441. \MID \BYTEREG{\itm{bytereg}} \\
  6442. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6443. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6444. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6445. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6446. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6447. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6448. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6449. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6450. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6451. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6452. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6453. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6454. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6455. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6456. \end{array}
  6457. \]
  6458. \end{minipage}
  6459. }
  6460. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6461. \label{fig:x86-1}
  6462. \end{figure}
  6463. Next we consider the x86 instructions that are relevant for compiling
  6464. the comparison operations. The \key{cmpq} instruction compares its two
  6465. arguments to determine whether one argument is less than, equal, or
  6466. greater than the other argument. The \key{cmpq} instruction is unusual
  6467. regarding the order of its arguments and where the result is
  6468. placed. The argument order is backwards: if you want to test whether
  6469. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6470. \key{cmpq} is placed in the special EFLAGS register. This register
  6471. cannot be accessed directly but it can be queried by a number of
  6472. instructions, including the \key{set} instruction. The instruction
  6473. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6474. depending on whether the comparison comes out according to the
  6475. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6476. for less-or-equal, \key{g} for greater, \key{ge} for
  6477. greater-or-equal). The \key{set} instruction has an annoying quirk in
  6478. that its destination argument must be single byte register, such as
  6479. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6480. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6481. instruction can be used to move from a single byte register to a
  6482. normal 64-bit register. The abstract syntax for the \code{set}
  6483. instruction differs from the concrete syntax in that it separates the
  6484. instruction name from the condition code.
  6485. The x86 instruction for conditional jump is relevant to the
  6486. compilation of \key{if} expressions. The instruction
  6487. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  6488. the instruction after \itm{label} depending on whether the result in
  6489. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  6490. jump instruction falls through to the next instruction. Like the
  6491. abstract syntax for \code{set}, the abstract syntax for conditional
  6492. jump separates the instruction name from the condition code. For
  6493. example, \JMPIF{\key{'le'}}{\key{foo}} corresponds to \code{jle foo}.
  6494. Because the conditional jump instruction relies on the EFLAGS
  6495. register, it is common for it to be immediately preceded by a
  6496. \key{cmpq} instruction to set the EFLAGS register.
  6497. \section{Shrink the \LangIf{} Language}
  6498. \label{sec:shrink-Rif}
  6499. The \LangIf{} language includes several features that are easily
  6500. expressible with other features. For example, \code{and} and \code{or}
  6501. are expressible using \code{if} as follows.
  6502. \begin{align*}
  6503. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6504. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6505. \end{align*}
  6506. By performing these translations in the front-end of the compiler, the
  6507. later passes of the compiler do not need to deal with these features,
  6508. making the passes shorter.
  6509. %% For example, subtraction is
  6510. %% expressible using addition and negation.
  6511. %% \[
  6512. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6513. %% \]
  6514. %% Several of the comparison operations are expressible using less-than
  6515. %% and logical negation.
  6516. %% \[
  6517. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6518. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6519. %% \]
  6520. %% The \key{let} is needed in the above translation to ensure that
  6521. %% expression $e_1$ is evaluated before $e_2$.
  6522. On the other hand, sometimes translations reduce the efficiency of the
  6523. generated code by increasing the number of instructions. For example,
  6524. expressing subtraction in terms of negation
  6525. \[
  6526. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6527. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6528. \]
  6529. produces code with two x86 instructions (\code{negq} and \code{addq})
  6530. instead of just one (\code{subq}).
  6531. %% However,
  6532. %% these differences typically do not affect the number of accesses to
  6533. %% memory, which is the primary factor that determines execution time on
  6534. %% modern computer architectures.
  6535. \begin{exercise}\normalfont
  6536. %
  6537. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  6538. the language by translating them to other constructs in \LangIf{}.
  6539. %
  6540. Create four test programs that involve these operators.
  6541. %
  6542. {\if\edition\racketEd\color{olive}
  6543. In the \code{run-tests.rkt} script, add the following entry for
  6544. \code{shrink} to the list of passes (it should be the only pass at
  6545. this point).
  6546. \begin{lstlisting}
  6547. (list "shrink" shrink interp_Rif type-check-Rif)
  6548. \end{lstlisting}
  6549. This instructs \code{interp-tests} to run the intepreter
  6550. \code{interp\_Rif} and the type checker \code{type-check-Rif} on the
  6551. output of \code{shrink}.
  6552. \fi}
  6553. %
  6554. Run the script to test your compiler on all the test programs.
  6555. \end{exercise}
  6556. {\if\edition\racketEd\color{olive}
  6557. \section{Uniquify Variables}
  6558. \label{sec:uniquify-Rif}
  6559. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6560. \code{if} expressions.
  6561. \begin{exercise}\normalfont
  6562. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  6563. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6564. \begin{lstlisting}
  6565. (list "uniquify" uniquify interp_Rif type_check_Rif)
  6566. \end{lstlisting}
  6567. Run the script to test your compiler.
  6568. \end{exercise}
  6569. \fi}
  6570. \section{Remove Complex Operands}
  6571. \label{sec:remove-complex-opera-Rif}
  6572. The output language for this pass is \LangIfANF{}
  6573. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  6574. \LangIf{}. A Boolean constant is an atomic expressions but the
  6575. \code{if} expression is not.
  6576. All three sub-expressions of an
  6577. \code{if} are allowed to be complex expressions but the operands of
  6578. \code{not} and the comparisons must be atomic.
  6579. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  6580. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  6581. according to whether the output needs to be \Exp{} or \Atm{} as
  6582. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  6583. particularly important to \textbf{not} replace its condition with a
  6584. temporary variable because that would interfere with the generation of
  6585. high-quality output in the \code{explicate\_control} pass.
  6586. \begin{figure}[tp]
  6587. \centering
  6588. \fbox{
  6589. \begin{minipage}{0.96\textwidth}
  6590. {\if\edition\racketEd\color{olive}
  6591. \[
  6592. \begin{array}{rcl}
  6593. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  6594. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  6595. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6596. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6597. &\MID& \UNIOP{\key{not}}{\Atm} \\
  6598. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6599. R^{\mathsf{ANF}}_{\mathsf{if}} &::=& \PROGRAM{\code{()}}{\Exp}
  6600. \end{array}
  6601. \]
  6602. \fi}
  6603. {\if\edition\pythonEd\color{purple}
  6604. \[
  6605. \begin{array}{rcl}
  6606. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  6607. \Exp &::=& \Atm \MID \READ{} \\
  6608. &\MID& \BINOP{\itm{binop}}{\Atm}{\Atm} \MID \UNIOP{\key{uniop}}{\Atm} \\
  6609. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6610. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6611. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  6612. P^{\mathsf{ANF}}_{\mathsf{if}} &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  6613. \end{array}
  6614. \]
  6615. \fi}
  6616. \end{minipage}
  6617. }
  6618. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  6619. \label{fig:Rif-anf-syntax}
  6620. \end{figure}
  6621. \begin{exercise}\normalfont
  6622. %
  6623. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  6624. and \code{rco\_exp} functions in \code{compiler.rkt}.
  6625. %
  6626. Create three new \LangInt{} programs that exercise the interesting
  6627. code in this pass.
  6628. %
  6629. In the \code{run-tests.rkt} script, add the following entry to the
  6630. list of \code{passes} and then run the script to test your compiler.
  6631. \begin{lstlisting}
  6632. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  6633. \end{lstlisting}
  6634. \end{exercise}
  6635. \section{Explicate Control}
  6636. \label{sec:explicate-control-Rif}
  6637. \racket{Recall that the purpose of \code{explicate\_control} is to
  6638. make the order of evaluation explicit in the syntax of the program.
  6639. With the addition of \key{if} this get more interesting.}
  6640. %
  6641. The main challenge is that the condition of an \key{if} can be an
  6642. arbitrary expression in \LangIf{} whereas in \LangCIf{} the condition
  6643. must be a comparison.
  6644. As a motivating example, consider the following program that has an
  6645. \key{if} expression nested in the condition of another \key{if}.
  6646. % cond_test_41.rkt, if_lt_eq.py
  6647. \begin{center}
  6648. \begin{minipage}{0.96\textwidth}
  6649. {\if\edition\racketEd\color{olive}
  6650. \begin{lstlisting}
  6651. (let ([x (read)])
  6652. (let ([y (read)])
  6653. (if (if (< x 1) (eq? x 0) (eq? x 2))
  6654. (+ y 2)
  6655. (+ y 10))))
  6656. \end{lstlisting}
  6657. \fi}
  6658. {\if\edition\pythonEd\color{purple}
  6659. \begin{lstlisting}
  6660. x = input_int()
  6661. y = input_int()
  6662. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  6663. \end{lstlisting}
  6664. \fi}
  6665. \end{minipage}
  6666. \end{center}
  6667. %
  6668. The naive way to compile \key{if} and the comparison operations would
  6669. be to handle each of them in isolation, regardless of their context.
  6670. Each comparison would be translated into a \key{cmpq} instruction
  6671. followed by a couple instructions to move the result from the EFLAGS
  6672. register into a general purpose register or stack location. Each
  6673. \key{if} would be translated into a \key{cmpq} instruction followed by
  6674. a conditional jump. The generated code for the inner \key{if} in the
  6675. above example would be as follows.
  6676. \begin{center}
  6677. \begin{minipage}{0.96\textwidth}
  6678. \begin{lstlisting}
  6679. cmpq $1, x
  6680. setl %al
  6681. movzbq %al, tmp
  6682. cmpq $1, tmp
  6683. je then_branch_1
  6684. jmp else_branch_1
  6685. \end{lstlisting}
  6686. \end{minipage}
  6687. \end{center}
  6688. However, if we take context into account we can do better and reduce
  6689. the use of \key{cmpq} instructions for accessing the EFLAG register.
  6690. Our goal will be to compile \key{if} expressions so that the relevant
  6691. comparison instruction appears directly before the conditional jump.
  6692. For example, we want to generate the following code for the inner
  6693. \code{if}.
  6694. \begin{center}
  6695. \begin{minipage}{0.96\textwidth}
  6696. \begin{lstlisting}
  6697. cmpq $1, x
  6698. je then_branch_1
  6699. jmp else_branch_1
  6700. \end{lstlisting}
  6701. \end{minipage}
  6702. \end{center}
  6703. One way to achieve this is to reorganize the code at the level of
  6704. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  6705. the following code.
  6706. \begin{center}
  6707. \begin{minipage}{0.96\textwidth}
  6708. {\if\edition\racketEd\color{olive}
  6709. \begin{lstlisting}
  6710. (let ([x (read)])
  6711. (let ([y (read)])
  6712. (if (< x 1)
  6713. (if (eq? x 0)
  6714. (+ y 2)
  6715. (+ y 10))
  6716. (if (eq? x 2)
  6717. (+ y 2)
  6718. (+ y 10)))))
  6719. \end{lstlisting}
  6720. \fi}
  6721. {\if\edition\pythonEd\color{purple}
  6722. \begin{lstlisting}
  6723. x = input_int()
  6724. y = intput_int()
  6725. print(((y + 2) if x == 0 else (y + 10)) \
  6726. if (x < 1) \
  6727. else ((y + 2) if (x == 2) else (y + 10)))
  6728. \end{lstlisting}
  6729. \fi}
  6730. \end{minipage}
  6731. \end{center}
  6732. Unfortunately, this approach duplicates the two branches from the
  6733. outer \code{if} and a compiler must never duplicate code!
  6734. We need a way to perform the above transformation but without
  6735. duplicating code. That is, we need a way for different parts of a
  6736. program to refer to the same piece of code.
  6737. %
  6738. Put another way, we need to move away from abstract syntax
  6739. \emph{trees} and instead use \emph{graphs}.
  6740. %
  6741. At the level of x86 assembly this is straightforward because we can
  6742. label the code for each branch and insert jumps in all the places that
  6743. need to execute the branch.
  6744. %
  6745. Likewise, our language \LangCIf{} provides the ability to label a
  6746. sequence of code and to jump to a label via \code{goto}.
  6747. %
  6748. %% In particular, we use a standard program representation called a
  6749. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  6750. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  6751. %% is a labeled sequence of code, called a \emph{basic block}, and each
  6752. %% edge represents a jump to another block.
  6753. %
  6754. In particular, the \key{CProgram} construct contains \racket{an
  6755. alist}\python{a dictionary} mapping labels to \emph{basic blocks}. Each
  6756. basic block is \racket{represented by the $\Tail$ non-terminal}
  6757. \python{a list of statements}.
  6758. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  6759. \code{remove\_complex\_operands} pass and then the
  6760. \code{explicate\_control} pass on the example program. We walk through
  6761. the output program and then discuss the algorithm.
  6762. %
  6763. Following the order of evaluation in the output of
  6764. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  6765. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  6766. in the predicate of the inner \key{if}. In the output of
  6767. \code{explicate\_control}, in the
  6768. block labeled \code{start}, is two assignment statements followed by a
  6769. \code{if} statement that branches to \code{block40} or
  6770. \code{block41}. The blocks associated with those labels contain the
  6771. translations of the code \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  6772. and \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  6773. respectively. In particular, we start \code{block40} with the
  6774. comparison \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  6775. and then branch to \code{block38} or
  6776. \code{block39}, the two branches of the outer \key{if}, i.e.,
  6777. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  6778. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  6779. The story for \code{block41} is similar.
  6780. \begin{figure}[tbp]
  6781. {\if\edition\racketEd\color{olive}
  6782. \begin{tabular}{lll}
  6783. \begin{minipage}{0.4\textwidth}
  6784. % cond_test_41.rkt
  6785. \begin{lstlisting}
  6786. (let ([x (read)])
  6787. (let ([y (read)])
  6788. (if (if (< x 1)
  6789. (eq? x 0)
  6790. (eq? x 2))
  6791. (+ y 2)
  6792. (+ y 10))))
  6793. \end{lstlisting}
  6794. \end{minipage}
  6795. &
  6796. $\Rightarrow$
  6797. &
  6798. \begin{minipage}{0.55\textwidth}
  6799. \begin{lstlisting}
  6800. start:
  6801. x = (read);
  6802. y = (read);
  6803. if (< x 1) goto block40;
  6804. else goto block41;
  6805. block40:
  6806. if (eq? x 0) goto block38;
  6807. else goto block39;
  6808. block41:
  6809. if (eq? x 2) goto block38;
  6810. else goto block39;
  6811. block38:
  6812. return (+ y 2);
  6813. block39:
  6814. return (+ y 10);
  6815. \end{lstlisting}
  6816. \end{minipage}
  6817. \end{tabular}
  6818. \fi}
  6819. {\if\edition\pythonEd\color{purple}
  6820. \begin{tabular}{lll}
  6821. \begin{minipage}{0.4\textwidth}
  6822. % cond_test_41.rkt
  6823. \begin{lstlisting}
  6824. x = input_int()
  6825. y = input_int()
  6826. print(y + 2 \
  6827. if (x == 0 \
  6828. if x < 1 \
  6829. else x == 2) \
  6830. else y + 10)
  6831. \end{lstlisting}
  6832. \end{minipage}
  6833. &
  6834. $\Rightarrow$
  6835. &
  6836. \begin{minipage}{0.55\textwidth}
  6837. \begin{lstlisting}
  6838. start:
  6839. x = input_int()
  6840. y = input_int()
  6841. if x < 1:
  6842. goto block_8
  6843. else:
  6844. goto block_9
  6845. block_8:
  6846. if x == 0:
  6847. goto block_2
  6848. else:
  6849. goto block_3
  6850. block_9:
  6851. if x == 2:
  6852. goto block_2
  6853. else:
  6854. goto block_3
  6855. block_2:
  6856. tmp_0 = y + 2
  6857. goto block_1
  6858. block_3:
  6859. tmp_0 = y + 10
  6860. goto block_1
  6861. block_1:
  6862. print(tmp_0)
  6863. return 0
  6864. \end{lstlisting}
  6865. \end{minipage}
  6866. \end{tabular}
  6867. \fi}
  6868. \caption{Translation from \LangIf{} to \LangCIf{}
  6869. via the \code{explicate\_control}.}
  6870. \label{fig:explicate-control-s1-38}
  6871. \end{figure}
  6872. %% The nice thing about the output of \code{explicate\_control} is that
  6873. %% there are no unnecessary comparisons and every comparison is part of a
  6874. %% conditional jump.
  6875. %% The down-side of this output is that it includes
  6876. %% trivial blocks, such as the blocks labeled \code{block92} through
  6877. %% \code{block95}, that only jump to another block. We discuss a solution
  6878. %% to this problem in Section~\ref{sec:opt-jumps}.
  6879. {\if\edition\racketEd\color{olive}
  6880. %
  6881. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  6882. \code{explicate\_control} for \LangVar{} using two mutually recursive
  6883. functions, \code{explicate-tail} and \code{explicate-assign}. The
  6884. former function translates expressions in tail position whereas the
  6885. later function translates expressions on the right-hand-side of a
  6886. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  6887. have a new kind of position to deal with: the predicate position of
  6888. the \key{if}. We need another function, \code{explicate-pred}, that
  6889. takes an \LangIf{} expression and two blocks for the then-branch and
  6890. else-branch. The output of \code{explicate-pred} is a block. In the
  6891. following paragraphs we discuss specific cases in the
  6892. \code{explicate\_pred} function as well as additions to the
  6893. \code{explicate\_tail} and \code{explicate\_assign} functions.
  6894. %
  6895. \fi}
  6896. %
  6897. {\if\edition\pythonEd\color{purple}
  6898. %
  6899. We recommend implementing \code{explicate\_control} using four
  6900. auxiliary functions which we discuss in the following paragraphs.
  6901. \begin{description}
  6902. \item[\code{explicate\_effect}] generates code for expressions as
  6903. statements, so their result is ignored and only their side-effects
  6904. matter.
  6905. \item[\code{explicate\_assign}] generates code for expressions
  6906. on the right-hand side of an assignment.
  6907. \item[\code{explicate\_pred}] generates code for an \code{if}
  6908. expression or statement by analyzing the condition expression.
  6909. \item[\code{explicate\_stmt}] generates code for statements.
  6910. \end{description}
  6911. These four functions should incrementally build up the dictionary of
  6912. basic blocks. The following auxiliary function can be used to create a
  6913. new basic block from a list of statements. It returns a \code{goto}
  6914. statement that jumps to the new basic block.
  6915. \begin{center}
  6916. \begin{minipage}{\textwidth}
  6917. \begin{lstlisting}
  6918. def create_block(stmts, basic_blocks):
  6919. label = label_name(generate_name('block'))
  6920. basic_blocks[label] = stmts
  6921. return Goto(label)
  6922. \end{lstlisting}
  6923. \end{minipage}
  6924. \end{center}
  6925. Figure~\ref{fig:explicate-control-Rif} provides a skeleton for the
  6926. \code{explicate\_control} pass.
  6927. The \code{explicate\_effect} function has three parameters: 1) the
  6928. expression to be compiled, 2) the already-compiled code for this
  6929. expression's \emph{continuation}, that is, the list of statements that
  6930. should execute after this expression, and 3) the dictionary of
  6931. generated basic blocks. The output of \code{explicate\_effect} is a
  6932. list of \LangCIf{} statements.
  6933. %
  6934. Let's consider a few of the cases for the expression to be compiled.
  6935. If the expression to be compiled is a constant, then it can be
  6936. discarded because it has no side effects. If it's a \CREAD{}, then
  6937. that's a side-effect and should be preserved. So it should be
  6938. translated into a statment using the \code{Expr} AST class. If the
  6939. expression to be compiled is an \code{if} expression, we translate the
  6940. two branches using \code{explicate\_effect} and then translate the
  6941. condition expression using \code{explicate\_pred}, which generates
  6942. code for the entire \code{if}.
  6943. The \code{explicate\_assign} function has four parameters: 1) the
  6944. right-hand-side of the assignment, 2) the left-hand-side of the
  6945. assignment (the variable), 3) the continuation, and 4) the dictionary
  6946. of basic blocks. The output of \code{explicate\_assign} is a list of
  6947. \LangCIf{} statements.
  6948. When the right-hand-side is an \code{if} expression, there is some
  6949. work to do. In particular, the two branches should be translated using
  6950. \code{explicate\_assign} and the condition expression should be
  6951. translated using \code{explicate\_pred}. Otherwise we can simply
  6952. generate an assignment statement with the given left and right-hand
  6953. sides.
  6954. \begin{figure}[tbp]
  6955. \begin{lstlisting}
  6956. def explicate_effect(e, cont, basic_blocks):
  6957. match e:
  6958. case IfExp(test, body, orelse):
  6959. ...
  6960. case Call(func, args):
  6961. ...
  6962. case _:
  6963. ...
  6964. def explicate_assign(rhs, lhs, cont, basic_blocks):
  6965. match rhs:
  6966. case IfExp(test, body, orelse):
  6967. ...
  6968. case _:
  6969. return [Assign([lhs], rhs)] + cont
  6970. def explicate_pred(cnd, thn, els, basic_blocks):
  6971. match cnd:
  6972. case Compare(left, [op], [right]):
  6973. goto_thn = create_block(thn, basic_blocks)
  6974. goto_els = create_block(els, basic_blocks)
  6975. return [If(cnd, [goto_thn], [goto_els])]
  6976. case Constant(True):
  6977. return thn;
  6978. case Constant(False):
  6979. return els;
  6980. case UnaryOp(Not(), operand):
  6981. ...
  6982. case IfExp(test, body, orelse):
  6983. ...
  6984. case _:
  6985. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  6986. [create_block(els, basic_blocks)],
  6987. [create_block(thn, basic_blocks)])]
  6988. def explicate_stmt(s, cont, basic_blocks):
  6989. match s:
  6990. case Assign([lhs], rhs):
  6991. return explicate_assign(rhs, lhs, cont, basic_blocks)
  6992. case Expr(value):
  6993. return explicate_effect(value, cont, basic_blocks)
  6994. case If(test, body, orelse):
  6995. ...
  6996. def explicate_control(p):
  6997. match p:
  6998. case Module(body):
  6999. new_body = [Return(Constant(0))]
  7000. basic_blocks = {}
  7001. for s in reversed(body):
  7002. new_body = explicate_stmt(s, new_body, basic_blocks)
  7003. basic_blocks[label_name('start')] = new_body
  7004. return CProgram(basic_blocks)
  7005. \end{lstlisting}
  7006. \caption{Skeleton for the \code{explicate\_control} pass.}
  7007. \label{fig:explicate-control-Rif}
  7008. \end{figure}
  7009. \fi}
  7010. {\if\edition\racketEd\color{olive}
  7011. \begin{figure}[tbp]
  7012. \begin{lstlisting}
  7013. (define (explicate-pred cnd thn els)
  7014. (match cnd
  7015. [(Var x) ___]
  7016. [(Let x rhs body) ___]
  7017. [(Prim 'not (list e)) ___]
  7018. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7019. (IfStmt (Prim op arg*) (force (block->goto thn))
  7020. (force (block->goto els)))]
  7021. [(Bool b) (if b thn els)]
  7022. [(If cnd^ thn^ els^) ___]
  7023. [else (error "explicate-pred unhandled case" cnd)]))
  7024. \end{lstlisting}
  7025. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  7026. \label{fig:explicate-pred}
  7027. \end{figure}
  7028. \fi}
  7029. \racket{The skeleton for the \code{explicate\_pred} function is given
  7030. in Figure~\ref{fig:explicate-pred}. It has a case for every
  7031. expression that can have type \code{Boolean}. We detail a few cases
  7032. here and leave the rest for the reader. The input to this function
  7033. is an expression and two blocks, \code{thn} and \code{els}, for the
  7034. two branches of the enclosing \key{if}.}
  7035. %
  7036. \python{The \code{explicate\_pred} function has four parameters: 1)
  7037. the condition expession, 2) the generated statements for the
  7038. ``then'' branch, 3) the generated statements for the ``else''
  7039. branch, and 4) the dictionary of basic blocks. The output of
  7040. \code{explicate\_pred} is a list of \LangCIf{} statements.}
  7041. %
  7042. Consider the case for comparison operators. We translate the
  7043. comparison to an \code{if} statement whose branches are \code{goto}
  7044. statements created by applying \code{create\_block} to the \code{thn}
  7045. and \code{els} branches.
  7046. %
  7047. Next consider the case for Boolean constants. We perform a kind of
  7048. partial evaluation\index{subject}{partial evaluation} and output
  7049. either the \code{thn} or \code{els} branch depending on whether the
  7050. constant is \TRUE{} or \FALSE{}. This case demonstrates that we
  7051. sometimes discard the \code{thn} or \code{els} blocks that are input
  7052. to \code{explicate\_pred}.
  7053. The case for \key{if} expressions in \code{explicate\_pred} is
  7054. particularly illuminating because it deals with the challenges we
  7055. discussed above regarding nested \key{if} expressions
  7056. (Figure~\ref{fig:explicate-control-s1-38}). The
  7057. \racket{\lstinline{thn^}}\python{\code{body}} and
  7058. \racket{\lstinline{els^}}\python{\code{orlese}} branches of the
  7059. \key{if} inherit their context from the current one, that is,
  7060. predicate context. So you should recursively apply
  7061. \code{explicate\_pred} to the
  7062. \racket{\lstinline{thn^}}\python{\code{body}} and
  7063. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7064. those recursive calls, pass \code{thn} and \code{els} as the extra
  7065. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7066. inside each recursive call. As discussed above, to avoid duplicating
  7067. code, we need to add them to the dictionary of basic blocks so that we
  7068. can instead refer to them by name and execute them with a \key{goto}.
  7069. {\if\edition\pythonEd\color{purple}
  7070. %
  7071. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7072. three parameters: 1) the statement to be compiled, 2) the code for its
  7073. continuation, and 3) the dictionary of basic blocks. The output is a
  7074. list of statements. The cases for assignment and an
  7075. expression-statement are given in full in the skeleton code: they
  7076. simply dispatch to \code{explicate\_assign} and
  7077. \code{explicate\_effect}, respectively. The case for \code{if}
  7078. statements is not given, and is similar to the case for \code{if}
  7079. expressions.
  7080. The \code{explicate\_control} function itself is given in
  7081. Figure~\ref{fig:explicate-control-Rif}. It applies
  7082. \code{explicate\_stmt} to each statement in the program, from back to
  7083. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7084. used as the continuation parameter in the next call to
  7085. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7086. \code{Return} statment. Once complete, we add the \code{new\_body} to
  7087. the dictionary of basic blocks, labeling it as the ``start'' block.
  7088. %
  7089. \fi}
  7090. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  7091. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  7092. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  7093. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7094. %% results from the two recursive calls. We complete the case for
  7095. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  7096. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7097. %% the result $B_5$.
  7098. %% \[
  7099. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7100. %% \quad\Rightarrow\quad
  7101. %% B_5
  7102. %% \]
  7103. \racket{The \code{explicate\_tail} and \code{explicate\_assign}
  7104. functions need additional cases for Boolean constants and \key{if}.
  7105. In the cases for \code{if}, the two branches inherit the current
  7106. context, so in \code{explicate\_tail} they are in tail position and
  7107. in \code{explicate\_assign} they are in assignment position. The
  7108. \code{cont} parameter of \code{explicate\_assign} is used in both
  7109. recursive calls, so make sure to use \code{block->goto} on it.}
  7110. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  7111. %% inherit the current context, so they are in tail position. Thus, the
  7112. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7113. %% \code{explicate-tail}.
  7114. %% %
  7115. %% We need to pass $B_0$ as the accumulator argument for both of these
  7116. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7117. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  7118. %% to the control-flow graph and obtain a promised goto $G_0$.
  7119. %% %
  7120. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  7121. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  7122. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7123. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  7124. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7125. %% \[
  7126. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7127. %% \]
  7128. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7129. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7130. %% should not be confused with the labels for the blocks that appear in
  7131. %% the generated code. We initially construct unlabeled blocks; we only
  7132. %% attach labels to blocks when we add them to the control-flow graph, as
  7133. %% we see in the next case.
  7134. %% Next consider the case for \key{if} in the \code{explicate-assign}
  7135. %% function. The context of the \key{if} is an assignment to some
  7136. %% variable $x$ and then the control continues to some promised block
  7137. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7138. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7139. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  7140. %% branches of the \key{if} inherit the current context, so they are in
  7141. %% assignment positions. Let $B_2$ be the result of applying
  7142. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  7143. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  7144. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7145. %% the result of applying \code{explicate-pred} to the predicate
  7146. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7147. %% translates to the promise $B_4$.
  7148. %% \[
  7149. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7150. %% \]
  7151. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7152. {\if\edition\racketEd\color{olive}
  7153. The way in which the \code{shrink} pass transforms logical operations
  7154. such as \code{and} and \code{or} can impact the quality of code
  7155. generated by \code{explicate\_control}. For example, consider the
  7156. following program.
  7157. % cond_test_21.rkt, and_eq_input.py
  7158. \begin{lstlisting}
  7159. (if (and (eq? (read) 0) (eq? (read) 1))
  7160. 0
  7161. 42)
  7162. \end{lstlisting}
  7163. The \code{and} operation should transform into something that the
  7164. \code{explicate-pred} function can still analyze and descend through to
  7165. reach the underlying \code{eq?} conditions. Ideally, your
  7166. \code{explicate\_control} pass should generate code similar to the
  7167. following for the above program.
  7168. \begin{center}
  7169. \begin{lstlisting}
  7170. start:
  7171. tmp1 = (read);
  7172. if (eq? tmp1 0) goto block40;
  7173. else goto block39;
  7174. block40:
  7175. tmp2 = (read);
  7176. if (eq? tmp2 1) goto block38;
  7177. else goto block39;
  7178. block38:
  7179. return 0;
  7180. block39:
  7181. return 42;
  7182. \end{lstlisting}
  7183. \end{center}
  7184. \fi}
  7185. \begin{exercise}\normalfont
  7186. \racket{
  7187. Implement the pass \code{explicate\_control} by adding the cases for
  7188. Boolean constants and \key{if} to the \code{explicate-tail} and
  7189. \code{explicate-assign}. Implement the auxiliary function
  7190. \code{explicate-pred} for predicate contexts.}
  7191. \python{Implement \code{explicate\_control} pass with its
  7192. four auxiliary functions.}
  7193. %
  7194. Create test cases that exercise all of the new cases in the code for
  7195. this pass.
  7196. %
  7197. {\if\edition\racketEd\color{olive}
  7198. Add the following entry to the list of \code{passes} in
  7199. \code{run-tests.rkt} and then run this script to test your compiler.
  7200. \begin{lstlisting}
  7201. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  7202. \end{lstlisting}
  7203. \fi}
  7204. \end{exercise}
  7205. \clearpage
  7206. \section{Select Instructions}
  7207. \label{sec:select-Rif}
  7208. \index{subject}{instruction selection}
  7209. The \code{select\_instructions} pass translates \LangCIf{} to
  7210. \LangXIfVar{}.
  7211. %
  7212. \racket{Recall that we implement this pass using three auxiliary
  7213. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7214. $\Tail$.}
  7215. %
  7216. \racket{For $\Atm$, we have new cases for the Booleans.}
  7217. %
  7218. \python{We begin with the Boolean constants.}
  7219. We take the usual approach of encoding them as integers.
  7220. \[
  7221. \TRUE{} \quad\Rightarrow\quad \key{1}
  7222. \qquad
  7223. \FALSE{} \quad\Rightarrow\quad \key{0}
  7224. \]
  7225. For translating statements, we discuss a couple cases. The \code{not}
  7226. operation can be implemented in terms of \code{xorq} as we discussed
  7227. at the beginning of this section. Given an assignment, if the
  7228. left-hand side variable is the same as the argument of \code{not},
  7229. then just the \code{xorq} instruction suffices.
  7230. \[
  7231. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7232. \quad\Rightarrow\quad
  7233. \key{xorq}~\key{\$}1\key{,}~\Var
  7234. \]
  7235. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7236. semantics of x86. In the following translation, let $\Arg$ be the
  7237. result of translating $\Atm$ to x86.
  7238. \[
  7239. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7240. \quad\Rightarrow\quad
  7241. \begin{array}{l}
  7242. \key{movq}~\Arg\key{,}~\Var\\
  7243. \key{xorq}~\key{\$}1\key{,}~\Var
  7244. \end{array}
  7245. \]
  7246. Next consider the cases for equality. Translating this operation to
  7247. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7248. instruction discussed above. We recommend translating an assignment
  7249. with an equality on the right-hand side into the following sequence of
  7250. three instructions. \\
  7251. \begin{tabular}{lll}
  7252. \begin{minipage}{0.4\textwidth}
  7253. \begin{lstlisting}
  7254. |$\CASSIGN{\Var}{ \CEQ{\Atm_1}{\Atm_2} }$|
  7255. \end{lstlisting}
  7256. \end{minipage}
  7257. &
  7258. $\Rightarrow$
  7259. &
  7260. \begin{minipage}{0.4\textwidth}
  7261. \begin{lstlisting}
  7262. cmpq |$\Arg_2$|, |$\Arg_1$|
  7263. sete %al
  7264. movzbq %al, |$\Var$|
  7265. \end{lstlisting}
  7266. \end{minipage}
  7267. \end{tabular} \\
  7268. The translations for the other comparison operators is similar to the
  7269. above but use different suffixes for the \code{set} instruction.
  7270. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7271. \key{goto} and \key{if} statements. Both are straightforward to
  7272. translate to x86.}
  7273. %
  7274. A \key{goto} statement becomes a jump instruction.
  7275. \[
  7276. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7277. \]
  7278. %
  7279. An \key{if} statement becomes a compare instruction followed by a
  7280. conditional jump (for the ``then'' branch) and the fall-through is to
  7281. a regular jump (for the ``else'' branch).\\
  7282. \begin{tabular}{lll}
  7283. \begin{minipage}{0.4\textwidth}
  7284. \begin{lstlisting}
  7285. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7286. goto |$\ell_1$||$\racket{\key{;}}$|
  7287. else|$\python{\key{:}}$|
  7288. goto |$\ell_2$||$\racket{\key{;}}$|
  7289. \end{lstlisting}
  7290. \end{minipage}
  7291. &
  7292. $\Rightarrow$
  7293. &
  7294. \begin{minipage}{0.4\textwidth}
  7295. \begin{lstlisting}
  7296. cmpq |$\Arg_2$|, |$\Arg_1$|
  7297. je |$\ell_1$|
  7298. jmp |$\ell_2$|
  7299. \end{lstlisting}
  7300. \end{minipage}
  7301. \end{tabular} \\
  7302. Again, the translations for the other comparison operators is similar to the
  7303. above but use different suffixes for the conditional jump instruction.
  7304. \begin{exercise}\normalfont
  7305. Expand your \code{select\_instructions} pass to handle the new
  7306. features of the \LangIf{} language.
  7307. %
  7308. {\if\edition\racketEd\color{olive}
  7309. Add the following entry to the list of \code{passes} in
  7310. \code{run-tests.rkt}
  7311. \begin{lstlisting}
  7312. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  7313. \end{lstlisting}
  7314. \fi}
  7315. %
  7316. Run the script to test your compiler on all the test programs.
  7317. \end{exercise}
  7318. \section{Register Allocation}
  7319. \label{sec:register-allocation-Rif}
  7320. \index{subject}{register allocation}
  7321. The changes required for \LangIf{} affect liveness analysis, building the
  7322. interference graph, and assigning homes, but the graph coloring
  7323. algorithm itself does not change.
  7324. \subsection{Liveness Analysis}
  7325. \label{sec:liveness-analysis-Rif}
  7326. \index{subject}{liveness analysis}
  7327. Recall that for \LangVar{} we implemented liveness analysis for a
  7328. single basic block (Section~\ref{sec:liveness-analysis-Rvar}). With
  7329. the addition of \key{if} expressions to \LangIf{},
  7330. \code{explicate\_control} produces many basic blocks.
  7331. %% We recommend that you create a new auxiliary function named
  7332. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  7333. %% control-flow graph.
  7334. The first question we is: what order should we process the basic
  7335. blocks? Recall that to perform liveness analysis on a basic block we
  7336. need to know the live-after set for the last instruction in the
  7337. block. If a basic block has no successors (i.e. contains no jumps to
  7338. other blocks), then it has an empty live-after set and we can
  7339. immediately apply liveness analysis to it. If a basic block has some
  7340. successors, then we need to complete liveness analysis on those blocks
  7341. first. These ordering contraints are the reverse of a
  7342. \emph{topological order}\index{subject}{topological order} on the
  7343. control-flow graph of the program~\citep{Allen:1970uq}. In a
  7344. \emph{control flow graph} (CFG), each node represents a \emph{basic
  7345. block} and each edge represents a jump from one block to another
  7346. \index{subject}{control-flow graph}. It is straightforward to
  7347. generate a CFG from the dictionary of basic blocks. One then needs to
  7348. transpose the CFG and apply the topological sort algorithm.
  7349. %
  7350. %
  7351. \racket{We recommend using the \code{tsort} and \code{transpose}
  7352. functions of the Racket \code{graph} package to accomplish this.}
  7353. %
  7354. \python{We provide implementations of \code{topological\_sort} and
  7355. \code{transpose} in the file \code{graph.py} of the support code.}
  7356. %
  7357. As an aside, a topological ordering is only guaranteed to exist if the
  7358. graph does not contain any cycles. That is indeed the case for the
  7359. control-flow graphs that we generate from \LangIf{} programs.
  7360. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  7361. learn how to handle cycles in the control-flow graph.
  7362. \racket{You'll need to construct a directed graph to represent the
  7363. control-flow graph. Do not use the \code{directed-graph} of the
  7364. \code{graph} package because that only allows at most one edge
  7365. between each pair of vertices, but a control-flow graph may have
  7366. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  7367. file in the support code implements a graph representation that
  7368. allows multiple edges between a pair of vertices.}
  7369. {\if\edition\racketEd\color{olive}
  7370. The next question is how to analyze jump instructions. Recall that in
  7371. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  7372. \code{label->live} that maps each label to the set of live locations
  7373. at the beginning of its block. We use \code{label->live} to determine
  7374. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  7375. that we have many basic blocks, \code{label->live} needs to be updated
  7376. as we process the blocks. In particular, after performing liveness
  7377. analysis on a block, we take the live-before set of its first
  7378. instruction and associate that with the block's label in the
  7379. \code{label->live}.
  7380. \fi}
  7381. %
  7382. {\if\edition\pythonEd\color{purple}
  7383. %
  7384. The next question is how to analyze jump instructions. The locations
  7385. that are live before a \code{jmp} should be the locations in
  7386. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  7387. maintaining dictionary named \code{live\_before\_block} that maps each
  7388. label to the $L_{\mathtt{before}}$ for the first instruction in its
  7389. block. After performing liveness analysis on each block, we take the
  7390. live-before set of its first instruction and associate that with the
  7391. block's label in the \code{live\_before\_block} dictionary.
  7392. %
  7393. \fi}
  7394. In \LangXIfVar{} we also have the conditional jump
  7395. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  7396. this instruction is particularly interesting because during
  7397. compilation we do not know which way a conditional jump will go. So
  7398. we do not know whether to use the live-before set for the following
  7399. instruction or the live-before set for the block associated with the
  7400. $\itm{label}$. However, there is no harm to the correctness of the
  7401. generated code if we classify more locations as live than the ones
  7402. that are truly live during one particular execution of the
  7403. instruction. Thus, we can take the union of the live-before sets from
  7404. the following instruction and from the mapping for $\itm{label}$ in
  7405. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  7406. The auxiliary functions for computing the variables in an
  7407. instruction's argument and for computing the variables read-from ($R$)
  7408. or written-to ($W$) by an instruction need to be updated to handle the
  7409. new kinds of arguments and instructions in \LangXIfVar{}.
  7410. \begin{exercise}\normalfont
  7411. {\if\edition\racketEd\color{olive}
  7412. %
  7413. Update the \code{uncover\_live} pass and implement the
  7414. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  7415. to the control-flow graph.
  7416. %
  7417. Add the following entry to the list of \code{passes} in the
  7418. \code{run-tests.rkt} script.
  7419. \begin{lstlisting}
  7420. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  7421. \end{lstlisting}
  7422. \fi}
  7423. {\if\edition\pythonEd\color{purple}
  7424. %
  7425. Update the \code{uncover\_live} function to perform liveness analysis,
  7426. in reverse topological order, on all of the basic blocks in the
  7427. program.
  7428. %
  7429. \fi}
  7430. \end{exercise}
  7431. \subsection{Build the Interference Graph}
  7432. \label{sec:build-interference-Rif}
  7433. UNDER CONSTRUCTION
  7434. Many of the new instructions in \LangXIfVar{} can be handled in the
  7435. same way as the instructions in \LangXVar{}. Thus, if your code was
  7436. already quite general, it will not need to be changed to handle the
  7437. new instructions. If you code is not general enough, we recommend that
  7438. you change your code to be more general. For example, you can factor
  7439. out the computing of the the read and write sets for each kind of
  7440. instruction into two auxiliary functions.
  7441. Note that the \key{movzbq} instruction requires some special care,
  7442. similar to the \key{movq} instruction. See rule number 1 in
  7443. Section~\ref{sec:build-interference}.
  7444. \begin{exercise}\normalfont
  7445. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  7446. following entries to the list of \code{passes} in the
  7447. \code{run-tests.rkt} script.
  7448. \begin{lstlisting}
  7449. (list "build-interference" build-interference interp-pseudo-x86-1)
  7450. (list "allocate-registers" allocate-registers interp-x86-1)
  7451. \end{lstlisting}
  7452. Run the script to test your compiler on all the \LangIf{} test
  7453. programs.
  7454. \end{exercise}
  7455. \section{Patch Instructions}
  7456. The second argument of the \key{cmpq} instruction must not be an
  7457. immediate value (such as an integer). So if you are comparing two
  7458. immediates, we recommend inserting a \key{movq} instruction to put the
  7459. second argument in \key{rax}. Also, recall that instructions may have
  7460. at most one memory reference.
  7461. %
  7462. The second argument of the \key{movzbq} must be a register.
  7463. %
  7464. There are no special restrictions on the jump instructions.
  7465. \begin{exercise}\normalfont
  7466. %
  7467. Update \code{patch-instructions} pass for \LangXIfVar{}.
  7468. %
  7469. Add the following entry to the list of \code{passes} in
  7470. \code{run-tests.rkt} and then run this script to test your compiler.
  7471. \begin{lstlisting}
  7472. (list "patch-instructions" patch-instructions interp-x86-1)
  7473. \end{lstlisting}
  7474. \end{exercise}
  7475. \begin{figure}[tbp]
  7476. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7477. \node (Rif) at (0,2) {\large \LangIf{}};
  7478. \node (Rif-2) at (3,2) {\large \LangIf{}};
  7479. \node (Rif-3) at (6,2) {\large \LangIf{}};
  7480. \node (Rif-4) at (9,2) {\large \LangIf{}};
  7481. \node (Rif-5) at (12,2) {\large \LangIf{}};
  7482. \node (C1-1) at (3,0) {\large \LangCIf{}};
  7483. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  7484. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  7485. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  7486. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  7487. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  7488. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  7489. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  7490. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  7491. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  7492. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  7493. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  7494. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  7495. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7496. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7497. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7498. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  7499. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  7500. \end{tikzpicture}
  7501. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  7502. \label{fig:Rif-passes}
  7503. \end{figure}
  7504. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  7505. compilation of \LangIf{}.
  7506. \section{An Example Translation}
  7507. Figure~\ref{fig:if-example-x86} shows a simple example program in
  7508. \LangIf{} translated to x86, showing the results of
  7509. \code{explicate\_control}, \code{select-instructions}, and the final
  7510. x86 assembly code.
  7511. \begin{figure}[tbp]
  7512. \begin{tabular}{lll}
  7513. \begin{minipage}{0.4\textwidth}
  7514. % cond_test_20.rkt, eq_input.py
  7515. \begin{lstlisting}
  7516. (if (eq? (read) 1) 42 0)
  7517. \end{lstlisting}
  7518. $\Downarrow$
  7519. \begin{lstlisting}
  7520. start:
  7521. tmp7951 = (read);
  7522. if (eq? tmp7951 1)
  7523. goto block7952;
  7524. else
  7525. goto block7953;
  7526. block7952:
  7527. return 42;
  7528. block7953:
  7529. return 0;
  7530. \end{lstlisting}
  7531. $\Downarrow$
  7532. \begin{lstlisting}
  7533. start:
  7534. callq read_int
  7535. movq %rax, tmp7951
  7536. cmpq $1, tmp7951
  7537. je block7952
  7538. jmp block7953
  7539. block7953:
  7540. movq $0, %rax
  7541. jmp conclusion
  7542. block7952:
  7543. movq $42, %rax
  7544. jmp conclusion
  7545. \end{lstlisting}
  7546. \end{minipage}
  7547. &
  7548. $\Rightarrow\qquad$
  7549. \begin{minipage}{0.4\textwidth}
  7550. \begin{lstlisting}
  7551. start:
  7552. callq read_int
  7553. movq %rax, %rcx
  7554. cmpq $1, %rcx
  7555. je block7952
  7556. jmp block7953
  7557. block7953:
  7558. movq $0, %rax
  7559. jmp conclusion
  7560. block7952:
  7561. movq $42, %rax
  7562. jmp conclusion
  7563. .globl main
  7564. main:
  7565. pushq %rbp
  7566. movq %rsp, %rbp
  7567. pushq %r13
  7568. pushq %r12
  7569. pushq %rbx
  7570. pushq %r14
  7571. subq $0, %rsp
  7572. jmp start
  7573. conclusion:
  7574. addq $0, %rsp
  7575. popq %r14
  7576. popq %rbx
  7577. popq %r12
  7578. popq %r13
  7579. popq %rbp
  7580. retq
  7581. \end{lstlisting}
  7582. \end{minipage}
  7583. \end{tabular}
  7584. \caption{Example compilation of an \key{if} expression to x86.}
  7585. \label{fig:if-example-x86}
  7586. \end{figure}
  7587. \section{Challenge: Optimize and Remove Jumps}
  7588. \label{sec:opt-jumps}
  7589. UNDER CONSTRUCTION
  7590. However, as we saw in the cases above for Boolean constants, the
  7591. blocks \code{thn} and \code{els} may not get used at all and we don't
  7592. want to prematurely add them to the control-flow graph if they end up
  7593. being discarded.
  7594. The solution to this conundrum is to use \emph{lazy
  7595. evaluation}\index{subject}{lazy evaluation}\citep{Friedman:1976aa} to delay
  7596. adding the blocks to the control-flow graph until the points where we
  7597. know they will be used. Racket provides support for lazy evaluation
  7598. with the
  7599. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  7600. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  7601. \index{subject}{delay} creates a \emph{promise}\index{subject}{promise} in which the
  7602. evaluation of the expressions is postponed. When \key{(force}
  7603. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the first
  7604. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  7605. $e_n$ is cached in the promise and returned. If \code{force} is
  7606. applied again to the same promise, then the cached result is returned.
  7607. If \code{force} is applied to an argument that is not a promise,
  7608. \code{force} simply returns the argument.
  7609. We use lazy evaluation for the input and output blocks of the
  7610. functions \code{explicate-pred} and \code{explicate-assign} and for
  7611. the output block of \code{explicate-tail}. So instead of taking and
  7612. returning blocks, they take and return promises. Furthermore, when we
  7613. come to a situation in which we a block might be used more than once,
  7614. as in the case for \code{if} in \code{explicate-pred}, we transform
  7615. the promise into a new promise that will add the block to the
  7616. control-flow graph and return a \code{goto}. The following auxiliary
  7617. function named \code{block->goto} accomplishes this task. It begins
  7618. with \code{delay} to create a promise. When forced, this promise will
  7619. force the original promise. If that returns a \code{goto} (because the
  7620. block was already added to the control-flow graph), then we return the
  7621. \code{goto}. Otherwise we add the block to the control-flow graph with
  7622. another auxiliary function named \code{add-node}. That function
  7623. returns the label for the new block, which we use to create a
  7624. \code{goto}.
  7625. \begin{lstlisting}
  7626. (define (block->goto block)
  7627. (delay
  7628. (define b (force block))
  7629. (match b
  7630. [(Goto label) (Goto label)]
  7631. [else (Goto (add-node b))])))
  7632. \end{lstlisting}
  7633. %% Recall that in the example output of \code{explicate\_control} in
  7634. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  7635. %% \code{block60} are trivial blocks, they do nothing but jump to another
  7636. %% block. The first goal of this challenge assignment is to remove those
  7637. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  7638. %% \code{explicate\_control} on the left and shows the result of bypassing
  7639. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  7640. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  7641. %% \code{block55}. The optimized code on the right of
  7642. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  7643. %% \code{then} branch jumping directly to \code{block55}. The story is
  7644. %% similar for the \code{else} branch, as well as for the two branches in
  7645. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  7646. %% have been optimized in this way, there are no longer any jumps to
  7647. %% blocks \code{block57} through \code{block60}, so they can be removed.
  7648. %% \begin{figure}[tbp]
  7649. %% \begin{tabular}{lll}
  7650. %% \begin{minipage}{0.4\textwidth}
  7651. %% \begin{lstlisting}
  7652. %% block62:
  7653. %% tmp54 = (read);
  7654. %% if (eq? tmp54 2) then
  7655. %% goto block59;
  7656. %% else
  7657. %% goto block60;
  7658. %% block61:
  7659. %% tmp53 = (read);
  7660. %% if (eq? tmp53 0) then
  7661. %% goto block57;
  7662. %% else
  7663. %% goto block58;
  7664. %% block60:
  7665. %% goto block56;
  7666. %% block59:
  7667. %% goto block55;
  7668. %% block58:
  7669. %% goto block56;
  7670. %% block57:
  7671. %% goto block55;
  7672. %% block56:
  7673. %% return (+ 700 77);
  7674. %% block55:
  7675. %% return (+ 10 32);
  7676. %% start:
  7677. %% tmp52 = (read);
  7678. %% if (eq? tmp52 1) then
  7679. %% goto block61;
  7680. %% else
  7681. %% goto block62;
  7682. %% \end{lstlisting}
  7683. %% \end{minipage}
  7684. %% &
  7685. %% $\Rightarrow$
  7686. %% &
  7687. %% \begin{minipage}{0.55\textwidth}
  7688. %% \begin{lstlisting}
  7689. %% block62:
  7690. %% tmp54 = (read);
  7691. %% if (eq? tmp54 2) then
  7692. %% goto block55;
  7693. %% else
  7694. %% goto block56;
  7695. %% block61:
  7696. %% tmp53 = (read);
  7697. %% if (eq? tmp53 0) then
  7698. %% goto block55;
  7699. %% else
  7700. %% goto block56;
  7701. %% block56:
  7702. %% return (+ 700 77);
  7703. %% block55:
  7704. %% return (+ 10 32);
  7705. %% start:
  7706. %% tmp52 = (read);
  7707. %% if (eq? tmp52 1) then
  7708. %% goto block61;
  7709. %% else
  7710. %% goto block62;
  7711. %% \end{lstlisting}
  7712. %% \end{minipage}
  7713. %% \end{tabular}
  7714. %% \caption{Optimize jumps by removing trivial blocks.}
  7715. %% \label{fig:optimize-jumps}
  7716. %% \end{figure}
  7717. %% The name of this pass is \code{optimize-jumps}. We recommend
  7718. %% implementing this pass in two phases. The first phrase builds a hash
  7719. %% table that maps labels to possibly improved labels. The second phase
  7720. %% changes the target of each \code{goto} to use the improved label. If
  7721. %% the label is for a trivial block, then the hash table should map the
  7722. %% label to the first non-trivial block that can be reached from this
  7723. %% label by jumping through trivial blocks. If the label is for a
  7724. %% non-trivial block, then the hash table should map the label to itself;
  7725. %% we do not want to change jumps to non-trivial blocks.
  7726. %% The first phase can be accomplished by constructing an empty hash
  7727. %% table, call it \code{short-cut}, and then iterating over the control
  7728. %% flow graph. Each time you encouter a block that is just a \code{goto},
  7729. %% then update the hash table, mapping the block's source to the target
  7730. %% of the \code{goto}. Also, the hash table may already have mapped some
  7731. %% labels to the block's source, to you must iterate through the hash
  7732. %% table and update all of those so that they instead map to the target
  7733. %% of the \code{goto}.
  7734. %% For the second phase, we recommend iterating through the $\Tail$ of
  7735. %% each block in the program, updating the target of every \code{goto}
  7736. %% according to the mapping in \code{short-cut}.
  7737. %% \begin{exercise}\normalfont
  7738. %% Implement the \code{optimize-jumps} pass as a transformation from
  7739. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate\_control} pass.
  7740. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  7741. %% example programs. Then check that your compiler still passes all of
  7742. %% your tests.
  7743. %% \end{exercise}
  7744. There is an opportunity for optimizing jumps that is apparent in the
  7745. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  7746. ends with a jump to \code{block7953} and there are no other jumps to
  7747. \code{block7953} in the rest of the program. In this situation we can
  7748. avoid the runtime overhead of this jump by merging \code{block7953}
  7749. into the preceding block, in this case the \code{start} block.
  7750. Figure~\ref{fig:remove-jumps} shows the output of
  7751. \code{select-instructions} on the left and the result of this
  7752. optimization on the right.
  7753. \begin{figure}[tbp]
  7754. \begin{tabular}{lll}
  7755. \begin{minipage}{0.5\textwidth}
  7756. % cond_test_20.rkt
  7757. \begin{lstlisting}
  7758. start:
  7759. callq read_int
  7760. movq %rax, tmp7951
  7761. cmpq $1, tmp7951
  7762. je block7952
  7763. jmp block7953
  7764. block7953:
  7765. movq $0, %rax
  7766. jmp conclusion
  7767. block7952:
  7768. movq $42, %rax
  7769. jmp conclusion
  7770. \end{lstlisting}
  7771. \end{minipage}
  7772. &
  7773. $\Rightarrow\qquad$
  7774. \begin{minipage}{0.4\textwidth}
  7775. \begin{lstlisting}
  7776. start:
  7777. callq read_int
  7778. movq %rax, tmp7951
  7779. cmpq $1, tmp7951
  7780. je block7952
  7781. movq $0, %rax
  7782. jmp conclusion
  7783. block7952:
  7784. movq $42, %rax
  7785. jmp conclusion
  7786. \end{lstlisting}
  7787. \end{minipage}
  7788. \end{tabular}
  7789. \caption{Merging basic blocks by removing unnecessary jumps.}
  7790. \label{fig:remove-jumps}
  7791. \end{figure}
  7792. \begin{exercise}\normalfont
  7793. %
  7794. Implement a pass named \code{remove-jumps} that merges basic blocks
  7795. into their preceding basic block, when there is only one preceding
  7796. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  7797. %
  7798. In the \code{run-tests.rkt} script, add the following entry to the
  7799. list of \code{passes} between \code{allocate-registers}
  7800. and \code{patch-instructions}.
  7801. \begin{lstlisting}
  7802. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  7803. \end{lstlisting}
  7804. Run this script to test your compiler.
  7805. %
  7806. Check that \code{remove-jumps} accomplishes the goal of merging basic
  7807. blocks on several test programs.
  7808. \end{exercise}
  7809. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7810. \chapter{Tuples and Garbage Collection}
  7811. \label{ch:Rvec}
  7812. \index{subject}{tuple}
  7813. \index{subject}{vector}
  7814. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  7815. %% all the IR grammars are spelled out! \\ --Jeremy}
  7816. %% \margincomment{\scriptsize Be more explicit about how to deal with
  7817. %% the root stack. \\ --Jeremy}
  7818. In this chapter we study the implementation of mutable tuples, called
  7819. vectors in Racket. This language feature is the first to use the
  7820. computer's \emph{heap}\index{subject}{heap} because the lifetime of a Racket
  7821. tuple is indefinite, that is, a tuple lives forever from the
  7822. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  7823. is important to reclaim the space associated with a tuple when it is
  7824. no longer needed, which is why we also study \emph{garbage collection}
  7825. \emph{garbage collection} techniques in this chapter.
  7826. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  7827. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  7828. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  7829. \code{void} value. The reason for including the later is that the
  7830. \code{vector-set!} operation returns a value of type
  7831. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  7832. called the \code{Unit} type in the programming languages
  7833. literature. Racket's \code{Void} type is inhabited by a single value
  7834. \code{void} which corresponds to \code{unit} or \code{()} in the
  7835. literature~\citep{Pierce:2002hj}.}.
  7836. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  7837. copying live objects back and forth between two halves of the
  7838. heap. The garbage collector requires coordination with the compiler so
  7839. that it can see all of the \emph{root} pointers, that is, pointers in
  7840. registers or on the procedure call stack.
  7841. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  7842. discuss all the necessary changes and additions to the compiler
  7843. passes, including a new compiler pass named \code{expose-allocation}.
  7844. \section{The \LangVec{} Language}
  7845. \label{sec:r3}
  7846. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  7847. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  7848. \LangVec{} language includes three new forms: \code{vector} for creating a
  7849. tuple, \code{vector-ref} for reading an element of a tuple, and
  7850. \code{vector-set!} for writing to an element of a tuple. The program
  7851. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  7852. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  7853. the 3-tuple, demonstrating that tuples are first-class values. The
  7854. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  7855. of the \key{if} is taken. The element at index $0$ of \code{t} is
  7856. \code{40}, to which we add \code{2}, the element at index $0$ of the
  7857. 1-tuple. So the result of the program is \code{42}.
  7858. \begin{figure}[tbp]
  7859. \centering
  7860. \fbox{
  7861. \begin{minipage}{0.96\textwidth}
  7862. \[
  7863. \begin{array}{lcl}
  7864. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}}
  7865. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}\\
  7866. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  7867. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  7868. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  7869. \MID \LP\key{and}\;\Exp\;\Exp\RP
  7870. \MID \LP\key{or}\;\Exp\;\Exp\RP
  7871. \MID \LP\key{not}\;\Exp\RP } \\
  7872. &\MID& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  7873. \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  7874. &\MID& \LP\key{vector}\;\Exp\ldots\RP
  7875. \MID \LP\key{vector-length}\;\Exp\RP \\
  7876. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  7877. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  7878. &\MID& \LP\key{void}\RP \MID \LP\key{has-type}~\Exp~\Type\RP\\
  7879. \LangVecM{} &::=& \Exp
  7880. \end{array}
  7881. \]
  7882. \end{minipage}
  7883. }
  7884. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  7885. (Figure~\ref{fig:Rif-concrete-syntax}).}
  7886. \label{fig:Rvec-concrete-syntax}
  7887. \end{figure}
  7888. \begin{figure}[tbp]
  7889. \begin{lstlisting}
  7890. (let ([t (vector 40 #t (vector 2))])
  7891. (if (vector-ref t 1)
  7892. (+ (vector-ref t 0)
  7893. (vector-ref (vector-ref t 2) 0))
  7894. 44))
  7895. \end{lstlisting}
  7896. \caption{Example program that creates tuples and reads from them.}
  7897. \label{fig:vector-eg}
  7898. \end{figure}
  7899. \begin{figure}[tp]
  7900. \centering
  7901. \fbox{
  7902. \begin{minipage}{0.96\textwidth}
  7903. \[
  7904. \begin{array}{lcl}
  7905. \itm{op} &::=& \ldots \MID \code{vector} \MID \code{vector-length} \\
  7906. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  7907. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  7908. \MID \BOOL{\itm{bool}}
  7909. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  7910. &\MID& \VECREF{\Exp}{\INT{\Int}}\\
  7911. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  7912. &\MID& \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP \\
  7913. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  7914. \end{array}
  7915. \]
  7916. \end{minipage}
  7917. }
  7918. \caption{The abstract syntax of \LangVec{}.}
  7919. \label{fig:Rvec-syntax}
  7920. \end{figure}
  7921. \index{subject}{allocate}
  7922. \index{subject}{heap allocate}
  7923. Tuples are our first encounter with heap-allocated data, which raises
  7924. several interesting issues. First, variable binding performs a
  7925. shallow-copy when dealing with tuples, which means that different
  7926. variables can refer to the same tuple, that is, different variables
  7927. can be \emph{aliases} for the same entity. Consider the following
  7928. example in which both \code{t1} and \code{t2} refer to the same tuple.
  7929. Thus, the mutation through \code{t2} is visible when referencing the
  7930. tuple from \code{t1}, so the result of this program is \code{42}.
  7931. \index{subject}{alias}\index{subject}{mutation}
  7932. \begin{center}
  7933. \begin{minipage}{0.96\textwidth}
  7934. \begin{lstlisting}
  7935. (let ([t1 (vector 3 7)])
  7936. (let ([t2 t1])
  7937. (let ([_ (vector-set! t2 0 42)])
  7938. (vector-ref t1 0))))
  7939. \end{lstlisting}
  7940. \end{minipage}
  7941. \end{center}
  7942. The next issue concerns the lifetime of tuples. Of course, they are
  7943. created by the \code{vector} form, but when does their lifetime end?
  7944. Notice that \LangVec{} does not include an operation for deleting
  7945. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  7946. of static scoping. For example, the following program returns
  7947. \code{42} even though the variable \code{w} goes out of scope prior to
  7948. the \code{vector-ref} that reads from the vector it was bound to.
  7949. \begin{center}
  7950. \begin{minipage}{0.96\textwidth}
  7951. \begin{lstlisting}
  7952. (let ([v (vector (vector 44))])
  7953. (let ([x (let ([w (vector 42)])
  7954. (let ([_ (vector-set! v 0 w)])
  7955. 0))])
  7956. (+ x (vector-ref (vector-ref v 0) 0))))
  7957. \end{lstlisting}
  7958. \end{minipage}
  7959. \end{center}
  7960. From the perspective of programmer-observable behavior, tuples live
  7961. forever. Of course, if they really lived forever, then many programs
  7962. would run out of memory.\footnote{The \LangVec{} language does not have
  7963. looping or recursive functions, so it is nigh impossible to write a
  7964. program in \LangVec{} that will run out of memory. However, we add
  7965. recursive functions in the next Chapter!} A Racket implementation
  7966. must therefore perform automatic garbage collection.
  7967. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  7968. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  7969. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  7970. terms of the corresponding operations in Racket. One subtle point is
  7971. that the \code{vector-set!} operation returns the \code{\#<void>}
  7972. value. The \code{\#<void>} value can be passed around just like other
  7973. values inside an \LangVec{} program and a \code{\#<void>} value can be
  7974. compared for equality with another \code{\#<void>} value. However,
  7975. there are no other operations specific to the the \code{\#<void>}
  7976. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  7977. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  7978. otherwise.
  7979. \begin{figure}[tbp]
  7980. \begin{lstlisting}
  7981. (define interp-Rvec_class
  7982. (class interp-Rif_class
  7983. (super-new)
  7984. (define/override (interp-op op)
  7985. (match op
  7986. ['eq? (lambda (v1 v2)
  7987. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7988. (and (boolean? v1) (boolean? v2))
  7989. (and (vector? v1) (vector? v2))
  7990. (and (void? v1) (void? v2)))
  7991. (eq? v1 v2)]))]
  7992. ['vector vector]
  7993. ['vector-length vector-length]
  7994. ['vector-ref vector-ref]
  7995. ['vector-set! vector-set!]
  7996. [else (super interp-op op)]
  7997. ))
  7998. (define/override ((interp-exp env) e)
  7999. (define recur (interp-exp env))
  8000. (match e
  8001. [(HasType e t) (recur e)]
  8002. [(Void) (void)]
  8003. [else ((super interp-exp env) e)]
  8004. ))
  8005. ))
  8006. (define (interp-Rvec p)
  8007. (send (new interp-Rvec_class) interp-program p))
  8008. \end{lstlisting}
  8009. \caption{Interpreter for the \LangVec{} language.}
  8010. \label{fig:interp-Rvec}
  8011. \end{figure}
  8012. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  8013. deserves some explanation. When allocating a vector, we need to know
  8014. which elements of the vector are pointers (i.e. are also vectors). We
  8015. can obtain this information during type checking. The type checker in
  8016. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  8017. expression, it also wraps every \key{vector} creation with the form
  8018. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  8019. %
  8020. To create the s-expression for the \code{Vector} type in
  8021. Figure~\ref{fig:type-check-Rvec}, we use the
  8022. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  8023. operator} \code{,@} to insert the list \code{t*} without its usual
  8024. start and end parentheses. \index{subject}{unquote-slicing}
  8025. \begin{figure}[tp]
  8026. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8027. (define type-check-Rvec_class
  8028. (class type-check-Rif_class
  8029. (super-new)
  8030. (inherit check-type-equal?)
  8031. (define/override (type-check-exp env)
  8032. (lambda (e)
  8033. (define recur (type-check-exp env))
  8034. (match e
  8035. [(Void) (values (Void) 'Void)]
  8036. [(Prim 'vector es)
  8037. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  8038. (define t `(Vector ,@t*))
  8039. (values (HasType (Prim 'vector e*) t) t)]
  8040. [(Prim 'vector-ref (list e1 (Int i)))
  8041. (define-values (e1^ t) (recur e1))
  8042. (match t
  8043. [`(Vector ,ts ...)
  8044. (unless (and (0 . <= . i) (i . < . (length ts)))
  8045. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  8046. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  8047. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  8048. [(Prim 'vector-set! (list e1 (Int i) arg) )
  8049. (define-values (e-vec t-vec) (recur e1))
  8050. (define-values (e-arg^ t-arg) (recur arg))
  8051. (match t-vec
  8052. [`(Vector ,ts ...)
  8053. (unless (and (0 . <= . i) (i . < . (length ts)))
  8054. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  8055. (check-type-equal? (list-ref ts i) t-arg e)
  8056. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  8057. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  8058. [(Prim 'vector-length (list e))
  8059. (define-values (e^ t) (recur e))
  8060. (match t
  8061. [`(Vector ,ts ...)
  8062. (values (Prim 'vector-length (list e^)) 'Integer)]
  8063. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  8064. [(Prim 'eq? (list arg1 arg2))
  8065. (define-values (e1 t1) (recur arg1))
  8066. (define-values (e2 t2) (recur arg2))
  8067. (match* (t1 t2)
  8068. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8069. [(other wise) (check-type-equal? t1 t2 e)])
  8070. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8071. [(HasType (Prim 'vector es) t)
  8072. ((type-check-exp env) (Prim 'vector es))]
  8073. [(HasType e1 t)
  8074. (define-values (e1^ t^) (recur e1))
  8075. (check-type-equal? t t^ e)
  8076. (values (HasType e1^ t) t)]
  8077. [else ((super type-check-exp env) e)]
  8078. )))
  8079. ))
  8080. (define (type-check-Rvec p)
  8081. (send (new type-check-Rvec_class) type-check-program p))
  8082. \end{lstlisting}
  8083. \caption{Type checker for the \LangVec{} language.}
  8084. \label{fig:type-check-Rvec}
  8085. \end{figure}
  8086. \section{Garbage Collection}
  8087. \label{sec:GC}
  8088. Here we study a relatively simple algorithm for garbage collection
  8089. that is the basis of state-of-the-art garbage
  8090. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  8091. particular, we describe a two-space copying
  8092. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  8093. perform the
  8094. copy~\citep{Cheney:1970aa}.
  8095. \index{subject}{copying collector}
  8096. \index{subject}{two-space copying collector}
  8097. Figure~\ref{fig:copying-collector} gives a
  8098. coarse-grained depiction of what happens in a two-space collector,
  8099. showing two time steps, prior to garbage collection (on the top) and
  8100. after garbage collection (on the bottom). In a two-space collector,
  8101. the heap is divided into two parts named the FromSpace and the
  8102. ToSpace. Initially, all allocations go to the FromSpace until there is
  8103. not enough room for the next allocation request. At that point, the
  8104. garbage collector goes to work to make more room.
  8105. \index{subject}{ToSpace}
  8106. \index{subject}{FromSpace}
  8107. The garbage collector must be careful not to reclaim tuples that will
  8108. be used by the program in the future. Of course, it is impossible in
  8109. general to predict what a program will do, but we can over approximate
  8110. the will-be-used tuples by preserving all tuples that could be
  8111. accessed by \emph{any} program given the current computer state. A
  8112. program could access any tuple whose address is in a register or on
  8113. the procedure call stack. These addresses are called the \emph{root
  8114. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  8115. transitively reachable from the root set. Thus, it is safe for the
  8116. garbage collector to reclaim the tuples that are not reachable in this
  8117. way.
  8118. So the goal of the garbage collector is twofold:
  8119. \begin{enumerate}
  8120. \item preserve all tuple that are reachable from the root set via a
  8121. path of pointers, that is, the \emph{live} tuples, and
  8122. \item reclaim the memory of everything else, that is, the
  8123. \emph{garbage}.
  8124. \end{enumerate}
  8125. A copying collector accomplishes this by copying all of the live
  8126. objects from the FromSpace into the ToSpace and then performs a sleight
  8127. of hand, treating the ToSpace as the new FromSpace and the old
  8128. FromSpace as the new ToSpace. In the example of
  8129. Figure~\ref{fig:copying-collector}, there are three pointers in the
  8130. root set, one in a register and two on the stack. All of the live
  8131. objects have been copied to the ToSpace (the right-hand side of
  8132. Figure~\ref{fig:copying-collector}) in a way that preserves the
  8133. pointer relationships. For example, the pointer in the register still
  8134. points to a 2-tuple whose first element is a 3-tuple and whose second
  8135. element is a 2-tuple. There are four tuples that are not reachable
  8136. from the root set and therefore do not get copied into the ToSpace.
  8137. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  8138. created by a well-typed program in \LangVec{} because it contains a
  8139. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  8140. We design the garbage collector to deal with cycles to begin with so
  8141. we will not need to revisit this issue.
  8142. \begin{figure}[tbp]
  8143. \centering
  8144. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  8145. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  8146. \caption{A copying collector in action.}
  8147. \label{fig:copying-collector}
  8148. \end{figure}
  8149. There are many alternatives to copying collectors (and their bigger
  8150. siblings, the generational collectors) when its comes to garbage
  8151. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  8152. reference counting~\citep{Collins:1960aa}. The strengths of copying
  8153. collectors are that allocation is fast (just a comparison and pointer
  8154. increment), there is no fragmentation, cyclic garbage is collected,
  8155. and the time complexity of collection only depends on the amount of
  8156. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  8157. main disadvantages of a two-space copying collector is that it uses a
  8158. lot of space and takes a long time to perform the copy, though these
  8159. problems are ameliorated in generational collectors. Racket and
  8160. Scheme programs tend to allocate many small objects and generate a lot
  8161. of garbage, so copying and generational collectors are a good fit.
  8162. Garbage collection is an active research topic, especially concurrent
  8163. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  8164. developing new techniques and revisiting old
  8165. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  8166. meet every year at the International Symposium on Memory Management to
  8167. present these findings.
  8168. \subsection{Graph Copying via Cheney's Algorithm}
  8169. \label{sec:cheney}
  8170. \index{subject}{Cheney's algorithm}
  8171. Let us take a closer look at the copying of the live objects. The
  8172. allocated objects and pointers can be viewed as a graph and we need to
  8173. copy the part of the graph that is reachable from the root set. To
  8174. make sure we copy all of the reachable vertices in the graph, we need
  8175. an exhaustive graph traversal algorithm, such as depth-first search or
  8176. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  8177. such algorithms take into account the possibility of cycles by marking
  8178. which vertices have already been visited, so as to ensure termination
  8179. of the algorithm. These search algorithms also use a data structure
  8180. such as a stack or queue as a to-do list to keep track of the vertices
  8181. that need to be visited. We use breadth-first search and a trick
  8182. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  8183. and copying tuples into the ToSpace.
  8184. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  8185. copy progresses. The queue is represented by a chunk of contiguous
  8186. memory at the beginning of the ToSpace, using two pointers to track
  8187. the front and the back of the queue. The algorithm starts by copying
  8188. all tuples that are immediately reachable from the root set into the
  8189. ToSpace to form the initial queue. When we copy a tuple, we mark the
  8190. old tuple to indicate that it has been visited. We discuss how this
  8191. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  8192. pointers inside the copied tuples in the queue still point back to the
  8193. FromSpace. Once the initial queue has been created, the algorithm
  8194. enters a loop in which it repeatedly processes the tuple at the front
  8195. of the queue and pops it off the queue. To process a tuple, the
  8196. algorithm copies all the tuple that are directly reachable from it to
  8197. the ToSpace, placing them at the back of the queue. The algorithm then
  8198. updates the pointers in the popped tuple so they point to the newly
  8199. copied tuples.
  8200. \begin{figure}[tbp]
  8201. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  8202. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  8203. \label{fig:cheney}
  8204. \end{figure}
  8205. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  8206. tuple whose second element is $42$ to the back of the queue. The other
  8207. pointer goes to a tuple that has already been copied, so we do not
  8208. need to copy it again, but we do need to update the pointer to the new
  8209. location. This can be accomplished by storing a \emph{forwarding
  8210. pointer} to the new location in the old tuple, back when we initially
  8211. copied the tuple into the ToSpace. This completes one step of the
  8212. algorithm. The algorithm continues in this way until the front of the
  8213. queue is empty, that is, until the front catches up with the back.
  8214. \subsection{Data Representation}
  8215. \label{sec:data-rep-gc}
  8216. The garbage collector places some requirements on the data
  8217. representations used by our compiler. First, the garbage collector
  8218. needs to distinguish between pointers and other kinds of data. There
  8219. are several ways to accomplish this.
  8220. \begin{enumerate}
  8221. \item Attached a tag to each object that identifies what type of
  8222. object it is~\citep{McCarthy:1960dz}.
  8223. \item Store different types of objects in different
  8224. regions~\citep{Steele:1977ab}.
  8225. \item Use type information from the program to either generate
  8226. type-specific code for collecting or to generate tables that can
  8227. guide the
  8228. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  8229. \end{enumerate}
  8230. Dynamically typed languages, such as Lisp, need to tag objects
  8231. anyways, so option 1 is a natural choice for those languages.
  8232. However, \LangVec{} is a statically typed language, so it would be
  8233. unfortunate to require tags on every object, especially small and
  8234. pervasive objects like integers and Booleans. Option 3 is the
  8235. best-performing choice for statically typed languages, but comes with
  8236. a relatively high implementation complexity. To keep this chapter
  8237. within a 2-week time budget, we recommend a combination of options 1
  8238. and 2, using separate strategies for the stack and the heap.
  8239. Regarding the stack, we recommend using a separate stack for pointers,
  8240. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  8241. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  8242. is, when a local variable needs to be spilled and is of type
  8243. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  8244. stack instead of the normal procedure call stack. Furthermore, we
  8245. always spill vector-typed variables if they are live during a call to
  8246. the collector, thereby ensuring that no pointers are in registers
  8247. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  8248. example from Figure~\ref{fig:copying-collector} and contrasts it with
  8249. the data layout using a root stack. The root stack contains the two
  8250. pointers from the regular stack and also the pointer in the second
  8251. register.
  8252. \begin{figure}[tbp]
  8253. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  8254. \caption{Maintaining a root stack to facilitate garbage collection.}
  8255. \label{fig:shadow-stack}
  8256. \end{figure}
  8257. The problem of distinguishing between pointers and other kinds of data
  8258. also arises inside of each tuple on the heap. We solve this problem by
  8259. attaching a tag, an extra 64-bits, to each
  8260. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  8261. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  8262. that we have drawn the bits in a big-endian way, from right-to-left,
  8263. with bit location 0 (the least significant bit) on the far right,
  8264. which corresponds to the direction of the x86 shifting instructions
  8265. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  8266. is dedicated to specifying which elements of the tuple are pointers,
  8267. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  8268. indicates there is a pointer and a 0 bit indicates some other kind of
  8269. data. The pointer mask starts at bit location 7. We have limited
  8270. tuples to a maximum size of 50 elements, so we just need 50 bits for
  8271. the pointer mask. The tag also contains two other pieces of
  8272. information. The length of the tuple (number of elements) is stored in
  8273. bits location 1 through 6. Finally, the bit at location 0 indicates
  8274. whether the tuple has yet to be copied to the ToSpace. If the bit has
  8275. value 1, then this tuple has not yet been copied. If the bit has
  8276. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  8277. of a pointer are always zero anyways because our tuples are 8-byte
  8278. aligned.)
  8279. \begin{figure}[tbp]
  8280. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  8281. \caption{Representation of tuples in the heap.}
  8282. \label{fig:tuple-rep}
  8283. \end{figure}
  8284. \subsection{Implementation of the Garbage Collector}
  8285. \label{sec:organize-gz}
  8286. \index{subject}{prelude}
  8287. An implementation of the copying collector is provided in the
  8288. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  8289. interface to the garbage collector that is used by the compiler. The
  8290. \code{initialize} function creates the FromSpace, ToSpace, and root
  8291. stack and should be called in the prelude of the \code{main}
  8292. function. The arguments of \code{initialize} are the root stack size
  8293. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  8294. good choice for both. The \code{initialize} function puts the address
  8295. of the beginning of the FromSpace into the global variable
  8296. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  8297. the address that is 1-past the last element of the FromSpace. (We use
  8298. half-open intervals to represent chunks of
  8299. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  8300. points to the first element of the root stack.
  8301. As long as there is room left in the FromSpace, your generated code
  8302. can allocate tuples simply by moving the \code{free\_ptr} forward.
  8303. %
  8304. The amount of room left in FromSpace is the difference between the
  8305. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  8306. function should be called when there is not enough room left in the
  8307. FromSpace for the next allocation. The \code{collect} function takes
  8308. a pointer to the current top of the root stack (one past the last item
  8309. that was pushed) and the number of bytes that need to be
  8310. allocated. The \code{collect} function performs the copying collection
  8311. and leaves the heap in a state such that the next allocation will
  8312. succeed.
  8313. \begin{figure}[tbp]
  8314. \begin{lstlisting}
  8315. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  8316. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  8317. int64_t* free_ptr;
  8318. int64_t* fromspace_begin;
  8319. int64_t* fromspace_end;
  8320. int64_t** rootstack_begin;
  8321. \end{lstlisting}
  8322. \caption{The compiler's interface to the garbage collector.}
  8323. \label{fig:gc-header}
  8324. \end{figure}
  8325. %% \begin{exercise}
  8326. %% In the file \code{runtime.c} you will find the implementation of
  8327. %% \code{initialize} and a partial implementation of \code{collect}.
  8328. %% The \code{collect} function calls another function, \code{cheney},
  8329. %% to perform the actual copy, and that function is left to the reader
  8330. %% to implement. The following is the prototype for \code{cheney}.
  8331. %% \begin{lstlisting}
  8332. %% static void cheney(int64_t** rootstack_ptr);
  8333. %% \end{lstlisting}
  8334. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  8335. %% rootstack (which is an array of pointers). The \code{cheney} function
  8336. %% also communicates with \code{collect} through the global
  8337. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  8338. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  8339. %% the ToSpace:
  8340. %% \begin{lstlisting}
  8341. %% static int64_t* tospace_begin;
  8342. %% static int64_t* tospace_end;
  8343. %% \end{lstlisting}
  8344. %% The job of the \code{cheney} function is to copy all the live
  8345. %% objects (reachable from the root stack) into the ToSpace, update
  8346. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  8347. %% update the root stack so that it points to the objects in the
  8348. %% ToSpace, and finally to swap the global pointers for the FromSpace
  8349. %% and ToSpace.
  8350. %% \end{exercise}
  8351. %% \section{Compiler Passes}
  8352. %% \label{sec:code-generation-gc}
  8353. The introduction of garbage collection has a non-trivial impact on our
  8354. compiler passes. We introduce a new compiler pass named
  8355. \code{expose-allocation}. We make
  8356. significant changes to \code{select-instructions},
  8357. \code{build-interference}, \code{allocate-registers}, and
  8358. \code{print\_x86} and make minor changes in several more passes. The
  8359. following program will serve as our running example. It creates two
  8360. tuples, one nested inside the other. Both tuples have length one. The
  8361. program accesses the element in the inner tuple tuple via two vector
  8362. references.
  8363. % tests/s2_17.rkt
  8364. \begin{lstlisting}
  8365. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  8366. \end{lstlisting}
  8367. \section{Shrink}
  8368. \label{sec:shrink-Rvec}
  8369. Recall that the \code{shrink} pass translates the primitives operators
  8370. into a smaller set of primitives. Because this pass comes after type
  8371. checking, but before the passes that require the type information in
  8372. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  8373. to wrap \code{HasType} around each AST node that it generates.
  8374. \section{Expose Allocation}
  8375. \label{sec:expose-allocation}
  8376. The pass \code{expose-allocation} lowers the \code{vector} creation
  8377. form into a conditional call to the collector followed by the
  8378. allocation. We choose to place the \code{expose-allocation} pass
  8379. before \code{remove\_complex\_operands} because the code generated by
  8380. \code{expose-allocation} contains complex operands. We also place
  8381. \code{expose-allocation} before \code{explicate\_control} because
  8382. \code{expose-allocation} introduces new variables using \code{let},
  8383. but \code{let} is gone after \code{explicate\_control}.
  8384. The output of \code{expose-allocation} is a language \LangAlloc{} that
  8385. extends \LangVec{} with the three new forms that we use in the translation
  8386. of the \code{vector} form.
  8387. \[
  8388. \begin{array}{lcl}
  8389. \Exp &::=& \cdots
  8390. \MID (\key{collect} \,\itm{int})
  8391. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  8392. \MID (\key{global-value} \,\itm{name})
  8393. \end{array}
  8394. \]
  8395. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  8396. $n$ bytes. It will become a call to the \code{collect} function in
  8397. \code{runtime.c} in \code{select-instructions}. The
  8398. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  8399. \index{subject}{allocate}
  8400. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  8401. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  8402. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  8403. a global variable, such as \code{free\_ptr}.
  8404. In the following, we show the transformation for the \code{vector}
  8405. form into 1) a sequence of let-bindings for the initializing
  8406. expressions, 2) a conditional call to \code{collect}, 3) a call to
  8407. \code{allocate}, and 4) the initialization of the vector. In the
  8408. following, \itm{len} refers to the length of the vector and
  8409. \itm{bytes} is how many total bytes need to be allocated for the
  8410. vector, which is 8 for the tag plus \itm{len} times 8.
  8411. \begin{lstlisting}
  8412. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  8413. |$\Longrightarrow$|
  8414. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  8415. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  8416. (global-value fromspace_end))
  8417. (void)
  8418. (collect |\itm{bytes}|))])
  8419. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  8420. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  8421. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  8422. |$v$|) ... )))) ...)
  8423. \end{lstlisting}
  8424. In the above, we suppressed all of the \code{has-type} forms in the
  8425. output for the sake of readability. The placement of the initializing
  8426. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  8427. sequence of \code{vector-set!} is important, as those expressions may
  8428. trigger garbage collection and we cannot have an allocated but
  8429. uninitialized tuple on the heap during a collection.
  8430. Figure~\ref{fig:expose-alloc-output} shows the output of the
  8431. \code{expose-allocation} pass on our running example.
  8432. \begin{figure}[tbp]
  8433. % tests/s2_17.rkt
  8434. \begin{lstlisting}
  8435. (vector-ref
  8436. (vector-ref
  8437. (let ([vecinit7976
  8438. (let ([vecinit7972 42])
  8439. (let ([collectret7974
  8440. (if (< (+ (global-value free_ptr) 16)
  8441. (global-value fromspace_end))
  8442. (void)
  8443. (collect 16)
  8444. )])
  8445. (let ([alloc7971 (allocate 1 (Vector Integer))])
  8446. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  8447. alloc7971)
  8448. )
  8449. )
  8450. )
  8451. ])
  8452. (let ([collectret7978
  8453. (if (< (+ (global-value free_ptr) 16)
  8454. (global-value fromspace_end))
  8455. (void)
  8456. (collect 16)
  8457. )])
  8458. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  8459. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  8460. alloc7975)
  8461. )
  8462. )
  8463. )
  8464. 0)
  8465. 0)
  8466. \end{lstlisting}
  8467. \caption{Output of the \code{expose-allocation} pass, minus
  8468. all of the \code{has-type} forms.}
  8469. \label{fig:expose-alloc-output}
  8470. \end{figure}
  8471. \section{Remove Complex Operands}
  8472. \label{sec:remove-complex-opera-Rvec}
  8473. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  8474. should all be treated as complex operands.
  8475. %% A new case for
  8476. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  8477. %% handled carefully to prevent the \code{Prim} node from being separated
  8478. %% from its enclosing \code{HasType}.
  8479. Figure~\ref{fig:Rvec-anf-syntax}
  8480. shows the grammar for the output language \LangVecANF{} of this
  8481. pass, which is \LangVec{} in administrative normal form.
  8482. \begin{figure}[tp]
  8483. \centering
  8484. \fbox{
  8485. \begin{minipage}{0.96\textwidth}
  8486. \small
  8487. \[
  8488. \begin{array}{rcl}
  8489. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }
  8490. \MID \VOID{} \\
  8491. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  8492. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  8493. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  8494. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  8495. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  8496. &\MID& \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  8497. \MID \LP\key{GlobalValue}~\Var\RP\\
  8498. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  8499. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  8500. \end{array}
  8501. \]
  8502. \end{minipage}
  8503. }
  8504. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  8505. \label{fig:Rvec-anf-syntax}
  8506. \end{figure}
  8507. \section{Explicate Control and the \LangCVec{} language}
  8508. \label{sec:explicate-control-r3}
  8509. \begin{figure}[tp]
  8510. \fbox{
  8511. \begin{minipage}{0.96\textwidth}
  8512. \small
  8513. \[
  8514. \begin{array}{lcl}
  8515. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  8516. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  8517. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  8518. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  8519. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  8520. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  8521. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  8522. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  8523. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  8524. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  8525. \MID \LP\key{Collect} \,\itm{int}\RP \\
  8526. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  8527. \MID \GOTO{\itm{label}} } \\
  8528. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8529. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  8530. \end{array}
  8531. \]
  8532. \end{minipage}
  8533. }
  8534. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  8535. (Figure~\ref{fig:c1-syntax}).}
  8536. \label{fig:c2-syntax}
  8537. \end{figure}
  8538. The output of \code{explicate\_control} is a program in the
  8539. intermediate language \LangCVec{}, whose abstract syntax is defined in
  8540. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  8541. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  8542. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  8543. \key{vector-set!}, and \key{global-value} expressions and the
  8544. \code{collect} statement. The \code{explicate\_control} pass can treat
  8545. these new forms much like the other expression forms that we've
  8546. already encoutered.
  8547. \section{Select Instructions and the \LangXGlobal{} Language}
  8548. \label{sec:select-instructions-gc}
  8549. \index{subject}{instruction selection}
  8550. %% void (rep as zero)
  8551. %% allocate
  8552. %% collect (callq collect)
  8553. %% vector-ref
  8554. %% vector-set!
  8555. %% global (postpone)
  8556. In this pass we generate x86 code for most of the new operations that
  8557. were needed to compile tuples, including \code{Allocate},
  8558. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  8559. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  8560. the later has a different concrete syntax (see
  8561. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  8562. \index{subject}{x86}
  8563. The \code{vector-ref} and \code{vector-set!} forms translate into
  8564. \code{movq} instructions. (The plus one in the offset is to get past
  8565. the tag at the beginning of the tuple representation.)
  8566. \begin{lstlisting}
  8567. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  8568. |$\Longrightarrow$|
  8569. movq |$\itm{vec}'$|, %r11
  8570. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  8571. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  8572. |$\Longrightarrow$|
  8573. movq |$\itm{vec}'$|, %r11
  8574. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  8575. movq $0, |$\itm{lhs'}$|
  8576. \end{lstlisting}
  8577. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  8578. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  8579. register \code{r11} ensures that offset expression
  8580. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  8581. removing \code{r11} from consideration by the register allocating.
  8582. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  8583. \code{rax}. Then the generated code for \code{vector-set!} would be
  8584. \begin{lstlisting}
  8585. movq |$\itm{vec}'$|, %rax
  8586. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  8587. movq $0, |$\itm{lhs}'$|
  8588. \end{lstlisting}
  8589. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  8590. \code{patch-instructions} would insert a move through \code{rax}
  8591. as follows.
  8592. \begin{lstlisting}
  8593. movq |$\itm{vec}'$|, %rax
  8594. movq |$\itm{arg}'$|, %rax
  8595. movq %rax, |$8(n+1)$|(%rax)
  8596. movq $0, |$\itm{lhs}'$|
  8597. \end{lstlisting}
  8598. But the above sequence of instructions does not work because we're
  8599. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  8600. $\itm{arg}'$) at the same time!
  8601. We compile the \code{allocate} form to operations on the
  8602. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  8603. is the next free address in the FromSpace, so we copy it into
  8604. \code{r11} and then move it forward by enough space for the tuple
  8605. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  8606. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  8607. initialize the \itm{tag} and finally copy the address in \code{r11} to
  8608. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  8609. tag is organized. We recommend using the Racket operations
  8610. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  8611. during compilation. The type annotation in the \code{vector} form is
  8612. used to determine the pointer mask region of the tag.
  8613. \begin{lstlisting}
  8614. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  8615. |$\Longrightarrow$|
  8616. movq free_ptr(%rip), %r11
  8617. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  8618. movq $|$\itm{tag}$|, 0(%r11)
  8619. movq %r11, |$\itm{lhs}'$|
  8620. \end{lstlisting}
  8621. The \code{collect} form is compiled to a call to the \code{collect}
  8622. function in the runtime. The arguments to \code{collect} are 1) the
  8623. top of the root stack and 2) the number of bytes that need to be
  8624. allocated. We use another dedicated register, \code{r15}, to
  8625. store the pointer to the top of the root stack. So \code{r15} is not
  8626. available for use by the register allocator.
  8627. \begin{lstlisting}
  8628. (collect |$\itm{bytes}$|)
  8629. |$\Longrightarrow$|
  8630. movq %r15, %rdi
  8631. movq $|\itm{bytes}|, %rsi
  8632. callq collect
  8633. \end{lstlisting}
  8634. \begin{figure}[tp]
  8635. \fbox{
  8636. \begin{minipage}{0.96\textwidth}
  8637. \[
  8638. \begin{array}{lcl}
  8639. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  8640. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  8641. & & \gray{ \key{main:} \; \Instr\ldots }
  8642. \end{array}
  8643. \]
  8644. \end{minipage}
  8645. }
  8646. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  8647. \label{fig:x86-2-concrete}
  8648. \end{figure}
  8649. \begin{figure}[tp]
  8650. \fbox{
  8651. \begin{minipage}{0.96\textwidth}
  8652. \small
  8653. \[
  8654. \begin{array}{lcl}
  8655. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  8656. \MID \BYTEREG{\Reg}} \\
  8657. &\MID& (\key{Global}~\Var) \\
  8658. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  8659. \end{array}
  8660. \]
  8661. \end{minipage}
  8662. }
  8663. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  8664. \label{fig:x86-2}
  8665. \end{figure}
  8666. The concrete and abstract syntax of the \LangXGlobal{} language is
  8667. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  8668. differs from \LangXIf{} just in the addition of the form for global
  8669. variables.
  8670. %
  8671. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  8672. \code{select-instructions} pass on the running example.
  8673. \begin{figure}[tbp]
  8674. \centering
  8675. % tests/s2_17.rkt
  8676. \begin{minipage}[t]{0.5\textwidth}
  8677. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8678. block35:
  8679. movq free_ptr(%rip), alloc9024
  8680. addq $16, free_ptr(%rip)
  8681. movq alloc9024, %r11
  8682. movq $131, 0(%r11)
  8683. movq alloc9024, %r11
  8684. movq vecinit9025, 8(%r11)
  8685. movq $0, initret9026
  8686. movq alloc9024, %r11
  8687. movq 8(%r11), tmp9034
  8688. movq tmp9034, %r11
  8689. movq 8(%r11), %rax
  8690. jmp conclusion
  8691. block36:
  8692. movq $0, collectret9027
  8693. jmp block35
  8694. block38:
  8695. movq free_ptr(%rip), alloc9020
  8696. addq $16, free_ptr(%rip)
  8697. movq alloc9020, %r11
  8698. movq $3, 0(%r11)
  8699. movq alloc9020, %r11
  8700. movq vecinit9021, 8(%r11)
  8701. movq $0, initret9022
  8702. movq alloc9020, vecinit9025
  8703. movq free_ptr(%rip), tmp9031
  8704. movq tmp9031, tmp9032
  8705. addq $16, tmp9032
  8706. movq fromspace_end(%rip), tmp9033
  8707. cmpq tmp9033, tmp9032
  8708. jl block36
  8709. jmp block37
  8710. block37:
  8711. movq %r15, %rdi
  8712. movq $16, %rsi
  8713. callq 'collect
  8714. jmp block35
  8715. block39:
  8716. movq $0, collectret9023
  8717. jmp block38
  8718. \end{lstlisting}
  8719. \end{minipage}
  8720. \begin{minipage}[t]{0.45\textwidth}
  8721. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8722. start:
  8723. movq $42, vecinit9021
  8724. movq free_ptr(%rip), tmp9028
  8725. movq tmp9028, tmp9029
  8726. addq $16, tmp9029
  8727. movq fromspace_end(%rip), tmp9030
  8728. cmpq tmp9030, tmp9029
  8729. jl block39
  8730. jmp block40
  8731. block40:
  8732. movq %r15, %rdi
  8733. movq $16, %rsi
  8734. callq 'collect
  8735. jmp block38
  8736. \end{lstlisting}
  8737. \end{minipage}
  8738. \caption{Output of the \code{select-instructions} pass.}
  8739. \label{fig:select-instr-output-gc}
  8740. \end{figure}
  8741. \clearpage
  8742. \section{Register Allocation}
  8743. \label{sec:reg-alloc-gc}
  8744. \index{subject}{register allocation}
  8745. As discussed earlier in this chapter, the garbage collector needs to
  8746. access all the pointers in the root set, that is, all variables that
  8747. are vectors. It will be the responsibility of the register allocator
  8748. to make sure that:
  8749. \begin{enumerate}
  8750. \item the root stack is used for spilling vector-typed variables, and
  8751. \item if a vector-typed variable is live during a call to the
  8752. collector, it must be spilled to ensure it is visible to the
  8753. collector.
  8754. \end{enumerate}
  8755. The later responsibility can be handled during construction of the
  8756. interference graph, by adding interference edges between the call-live
  8757. vector-typed variables and all the callee-saved registers. (They
  8758. already interfere with the caller-saved registers.) The type
  8759. information for variables is in the \code{Program} form, so we
  8760. recommend adding another parameter to the \code{build-interference}
  8761. function to communicate this alist.
  8762. The spilling of vector-typed variables to the root stack can be
  8763. handled after graph coloring, when choosing how to assign the colors
  8764. (integers) to registers and stack locations. The \code{Program} output
  8765. of this pass changes to also record the number of spills to the root
  8766. stack.
  8767. % build-interference
  8768. %
  8769. % callq
  8770. % extra parameter for var->type assoc. list
  8771. % update 'program' and 'if'
  8772. % allocate-registers
  8773. % allocate spilled vectors to the rootstack
  8774. % don't change color-graph
  8775. \section{Print x86}
  8776. \label{sec:print-x86-gc}
  8777. \index{subject}{prelude}\index{subject}{conclusion}
  8778. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  8779. \code{print\_x86} pass on the running example. In the prelude and
  8780. conclusion of the \code{main} function, we treat the root stack very
  8781. much like the regular stack in that we move the root stack pointer
  8782. (\code{r15}) to make room for the spills to the root stack, except
  8783. that the root stack grows up instead of down. For the running
  8784. example, there was just one spill so we increment \code{r15} by 8
  8785. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  8786. One issue that deserves special care is that there may be a call to
  8787. \code{collect} prior to the initializing assignments for all the
  8788. variables in the root stack. We do not want the garbage collector to
  8789. accidentally think that some uninitialized variable is a pointer that
  8790. needs to be followed. Thus, we zero-out all locations on the root
  8791. stack in the prelude of \code{main}. In
  8792. Figure~\ref{fig:print-x86-output-gc}, the instruction
  8793. %
  8794. \lstinline{movq $0, (%r15)}
  8795. %
  8796. accomplishes this task. The garbage collector tests each root to see
  8797. if it is null prior to dereferencing it.
  8798. \begin{figure}[htbp]
  8799. \begin{minipage}[t]{0.5\textwidth}
  8800. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8801. block35:
  8802. movq free_ptr(%rip), %rcx
  8803. addq $16, free_ptr(%rip)
  8804. movq %rcx, %r11
  8805. movq $131, 0(%r11)
  8806. movq %rcx, %r11
  8807. movq -8(%r15), %rax
  8808. movq %rax, 8(%r11)
  8809. movq $0, %rdx
  8810. movq %rcx, %r11
  8811. movq 8(%r11), %rcx
  8812. movq %rcx, %r11
  8813. movq 8(%r11), %rax
  8814. jmp conclusion
  8815. block36:
  8816. movq $0, %rcx
  8817. jmp block35
  8818. block38:
  8819. movq free_ptr(%rip), %rcx
  8820. addq $16, free_ptr(%rip)
  8821. movq %rcx, %r11
  8822. movq $3, 0(%r11)
  8823. movq %rcx, %r11
  8824. movq %rbx, 8(%r11)
  8825. movq $0, %rdx
  8826. movq %rcx, -8(%r15)
  8827. movq free_ptr(%rip), %rcx
  8828. addq $16, %rcx
  8829. movq fromspace_end(%rip), %rdx
  8830. cmpq %rdx, %rcx
  8831. jl block36
  8832. movq %r15, %rdi
  8833. movq $16, %rsi
  8834. callq collect
  8835. jmp block35
  8836. block39:
  8837. movq $0, %rcx
  8838. jmp block38
  8839. \end{lstlisting}
  8840. \end{minipage}
  8841. \begin{minipage}[t]{0.45\textwidth}
  8842. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8843. start:
  8844. movq $42, %rbx
  8845. movq free_ptr(%rip), %rdx
  8846. addq $16, %rdx
  8847. movq fromspace_end(%rip), %rcx
  8848. cmpq %rcx, %rdx
  8849. jl block39
  8850. movq %r15, %rdi
  8851. movq $16, %rsi
  8852. callq collect
  8853. jmp block38
  8854. .globl main
  8855. main:
  8856. pushq %rbp
  8857. movq %rsp, %rbp
  8858. pushq %r13
  8859. pushq %r12
  8860. pushq %rbx
  8861. pushq %r14
  8862. subq $0, %rsp
  8863. movq $16384, %rdi
  8864. movq $16384, %rsi
  8865. callq initialize
  8866. movq rootstack_begin(%rip), %r15
  8867. movq $0, (%r15)
  8868. addq $8, %r15
  8869. jmp start
  8870. conclusion:
  8871. subq $8, %r15
  8872. addq $0, %rsp
  8873. popq %r14
  8874. popq %rbx
  8875. popq %r12
  8876. popq %r13
  8877. popq %rbp
  8878. retq
  8879. \end{lstlisting}
  8880. \end{minipage}
  8881. \caption{Output of the \code{print\_x86} pass.}
  8882. \label{fig:print-x86-output-gc}
  8883. \end{figure}
  8884. \begin{figure}[p]
  8885. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8886. \node (Rvec) at (0,2) {\large \LangVec{}};
  8887. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  8888. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  8889. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  8890. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  8891. \node (C2-4) at (3,0) {\large \LangCVec{}};
  8892. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  8893. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  8894. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  8895. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  8896. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  8897. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  8898. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  8899. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  8900. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  8901. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  8902. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  8903. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  8904. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  8905. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8906. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8907. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8908. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  8909. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  8910. \end{tikzpicture}
  8911. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  8912. \label{fig:Rvec-passes}
  8913. \end{figure}
  8914. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  8915. for the compilation of \LangVec{}.
  8916. \section{Challenge: Simple Structures}
  8917. \label{sec:simple-structures}
  8918. \index{subject}{struct}
  8919. \index{subject}{structure}
  8920. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  8921. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  8922. Recall that a \code{struct} in Typed Racket is a user-defined data
  8923. type that contains named fields and that is heap allocated, similar to
  8924. a vector. The following is an example of a structure definition, in
  8925. this case the definition of a \code{point} type.
  8926. \begin{lstlisting}
  8927. (struct point ([x : Integer] [y : Integer]) #:mutable)
  8928. \end{lstlisting}
  8929. \begin{figure}[tbp]
  8930. \centering
  8931. \fbox{
  8932. \begin{minipage}{0.96\textwidth}
  8933. \[
  8934. \begin{array}{lcl}
  8935. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  8936. \MID (\key{Vector}\;\Type \ldots) \MID \key{Void} } \MID \Var \\
  8937. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  8938. \Exp &::=& \gray{ \Int \MID (\key{read}) \MID (\key{-}\;\Exp) \MID (\key{+} \; \Exp\;\Exp) \MID (\key{-}\;\Exp\;\Exp) } \\
  8939. &\MID& \gray{ \Var \MID (\key{let}~([\Var~\Exp])~\Exp) }\\
  8940. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  8941. \MID (\key{and}\;\Exp\;\Exp)
  8942. \MID (\key{or}\;\Exp\;\Exp)
  8943. \MID (\key{not}\;\Exp) } \\
  8944. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  8945. \MID (\key{if}~\Exp~\Exp~\Exp) } \\
  8946. &\MID& \gray{ (\key{vector}\;\Exp \ldots)
  8947. \MID (\key{vector-ref}\;\Exp\;\Int) } \\
  8948. &\MID& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  8949. &\MID& \gray{ (\key{void}) } \MID (\Var\;\Exp \ldots)\\
  8950. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  8951. \LangStruct{} &::=& \Def \ldots \; \Exp
  8952. \end{array}
  8953. \]
  8954. \end{minipage}
  8955. }
  8956. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  8957. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  8958. \label{fig:r3s-concrete-syntax}
  8959. \end{figure}
  8960. An instance of a structure is created using function call syntax, with
  8961. the name of the structure in the function position:
  8962. \begin{lstlisting}
  8963. (point 7 12)
  8964. \end{lstlisting}
  8965. Function-call syntax is also used to read the value in a field of a
  8966. structure. The function name is formed by the structure name, a dash,
  8967. and the field name. The following example uses \code{point-x} and
  8968. \code{point-y} to access the \code{x} and \code{y} fields of two point
  8969. instances.
  8970. \begin{center}
  8971. \begin{lstlisting}
  8972. (let ([pt1 (point 7 12)])
  8973. (let ([pt2 (point 4 3)])
  8974. (+ (- (point-x pt1) (point-x pt2))
  8975. (- (point-y pt1) (point-y pt2)))))
  8976. \end{lstlisting}
  8977. \end{center}
  8978. Similarly, to write to a field of a structure, use its set function,
  8979. whose name starts with \code{set-}, followed by the structure name,
  8980. then a dash, then the field name, and concluded with an exclamation
  8981. mark. The following example uses \code{set-point-x!} to change the
  8982. \code{x} field from \code{7} to \code{42}.
  8983. \begin{center}
  8984. \begin{lstlisting}
  8985. (let ([pt (point 7 12)])
  8986. (let ([_ (set-point-x! pt 42)])
  8987. (point-x pt)))
  8988. \end{lstlisting}
  8989. \end{center}
  8990. \begin{exercise}\normalfont
  8991. Extend your compiler with support for simple structures, compiling
  8992. \LangStruct{} to x86 assembly code. Create five new test cases that use
  8993. structures and test your compiler.
  8994. \end{exercise}
  8995. \section{Challenge: Generational Collection}
  8996. The copying collector described in Section~\ref{sec:GC} can incur
  8997. significant runtime overhead because the call to \code{collect} takes
  8998. time proportional to all of the live data. One way to reduce this
  8999. overhead is to reduce how much data is inspected in each call to
  9000. \code{collect}. In particular, researchers have observed that recently
  9001. allocated data is more likely to become garbage then data that has
  9002. survived one or more previous calls to \code{collect}. This insight
  9003. motivated the creation of \emph{generational garbage collectors}
  9004. \index{subject}{generational garbage collector} that
  9005. 1) segregates data according to its age into two or more generations,
  9006. 2) allocates less space for younger generations, so collecting them is
  9007. faster, and more space for the older generations, and 3) performs
  9008. collection on the younger generations more frequently then for older
  9009. generations~\citep{Wilson:1992fk}.
  9010. For this challenge assignment, the goal is to adapt the copying
  9011. collector implemented in \code{runtime.c} to use two generations, one
  9012. for young data and one for old data. Each generation consists of a
  9013. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  9014. \code{collect} function to use the two generations.
  9015. \begin{enumerate}
  9016. \item Copy the young generation's FromSpace to its ToSpace then switch
  9017. the role of the ToSpace and FromSpace
  9018. \item If there is enough space for the requested number of bytes in
  9019. the young FromSpace, then return from \code{collect}.
  9020. \item If there is not enough space in the young FromSpace for the
  9021. requested bytes, then move the data from the young generation to the
  9022. old one with the following steps:
  9023. \begin{enumerate}
  9024. \item If there is enough room in the old FromSpace, copy the young
  9025. FromSpace to the old FromSpace and then return.
  9026. \item If there is not enough room in the old FromSpace, then collect
  9027. the old generation by copying the old FromSpace to the old ToSpace
  9028. and swap the roles of the old FromSpace and ToSpace.
  9029. \item If there is enough room now, copy the young FromSpace to the
  9030. old FromSpace and return. Otherwise, allocate a larger FromSpace
  9031. and ToSpace for the old generation. Copy the young FromSpace and
  9032. the old FromSpace into the larger FromSpace for the old
  9033. generation and then return.
  9034. \end{enumerate}
  9035. \end{enumerate}
  9036. We recommend that you generalize the \code{cheney} function so that it
  9037. can be used for all the copies mentioned above: between the young
  9038. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  9039. between the young FromSpace and old FromSpace. This can be
  9040. accomplished by adding parameters to \code{cheney} that replace its
  9041. use of the global variables \code{fromspace\_begin},
  9042. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  9043. Note that the collection of the young generation does not traverse the
  9044. old generation. This introduces a potential problem: there may be
  9045. young data that is only reachable through pointers in the old
  9046. generation. If these pointers are not taken into account, the
  9047. collector could throw away young data that is live! One solution,
  9048. called \emph{pointer recording}, is to maintain a set of all the
  9049. pointers from the old generation into the new generation and consider
  9050. this set as part of the root set. To maintain this set, the compiler
  9051. must insert extra instructions around every \code{vector-set!}. If the
  9052. vector being modified is in the old generation, and if the value being
  9053. written is a pointer into the new generation, than that pointer must
  9054. be added to the set. Also, if the value being overwritten was a
  9055. pointer into the new generation, then that pointer should be removed
  9056. from the set.
  9057. \begin{exercise}\normalfont
  9058. Adapt the \code{collect} function in \code{runtime.c} to implement
  9059. generational garbage collection, as outlined in this section.
  9060. Update the code generation for \code{vector-set!} to implement
  9061. pointer recording. Make sure that your new compiler and runtime
  9062. passes your test suite.
  9063. \end{exercise}
  9064. % Further Reading
  9065. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9066. \chapter{Functions}
  9067. \label{ch:Rfun}
  9068. \index{subject}{function}
  9069. This chapter studies the compilation of functions similar to those
  9070. found in the C language. This corresponds to a subset of Typed Racket
  9071. in which only top-level function definitions are allowed. This kind of
  9072. function is an important stepping stone to implementing
  9073. lexically-scoped functions, that is, \key{lambda} abstractions, which
  9074. is the topic of Chapter~\ref{ch:Rlam}.
  9075. \section{The \LangFun{} Language}
  9076. The concrete and abstract syntax for function definitions and function
  9077. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  9078. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  9079. \LangFun{} begin with zero or more function definitions. The function
  9080. names from these definitions are in-scope for the entire program,
  9081. including all other function definitions (so the ordering of function
  9082. definitions does not matter). The concrete syntax for function
  9083. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  9084. where the first expression must
  9085. evaluate to a function and the rest are the arguments.
  9086. The abstract syntax for function application is
  9087. $\APPLY{\Exp}{\Exp\ldots}$.
  9088. %% The syntax for function application does not include an explicit
  9089. %% keyword, which is error prone when using \code{match}. To alleviate
  9090. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  9091. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  9092. Functions are first-class in the sense that a function pointer
  9093. \index{subject}{function pointer} is data and can be stored in memory or passed
  9094. as a parameter to another function. Thus, we introduce a function
  9095. type, written
  9096. \begin{lstlisting}
  9097. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  9098. \end{lstlisting}
  9099. for a function whose $n$ parameters have the types $\Type_1$ through
  9100. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  9101. these functions (with respect to Racket functions) is that they are
  9102. not lexically scoped. That is, the only external entities that can be
  9103. referenced from inside a function body are other globally-defined
  9104. functions. The syntax of \LangFun{} prevents functions from being nested
  9105. inside each other.
  9106. \begin{figure}[tp]
  9107. \centering
  9108. \fbox{
  9109. \begin{minipage}{0.96\textwidth}
  9110. \small
  9111. \[
  9112. \begin{array}{lcl}
  9113. \Type &::=& \gray{ \key{Integer} \MID \key{Boolean}
  9114. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void} } \MID (\Type \ldots \; \key{->}\; \Type) \\
  9115. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  9116. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  9117. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  9118. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  9119. \MID (\key{and}\;\Exp\;\Exp)
  9120. \MID (\key{or}\;\Exp\;\Exp)
  9121. \MID (\key{not}\;\Exp)} \\
  9122. &\MID& \gray{(\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  9123. &\MID& \gray{(\key{vector}\;\Exp\ldots) \MID
  9124. (\key{vector-ref}\;\Exp\;\Int)} \\
  9125. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  9126. \MID \LP\key{has-type}~\Exp~\Type\RP } \\
  9127. &\MID& \LP\Exp \; \Exp \ldots\RP \\
  9128. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  9129. \LangFunM{} &::=& \Def \ldots \; \Exp
  9130. \end{array}
  9131. \]
  9132. \end{minipage}
  9133. }
  9134. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  9135. \label{fig:Rfun-concrete-syntax}
  9136. \end{figure}
  9137. \begin{figure}[tp]
  9138. \centering
  9139. \fbox{
  9140. \begin{minipage}{0.96\textwidth}
  9141. \small
  9142. \[
  9143. \begin{array}{lcl}
  9144. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  9145. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9146. &\MID& \gray{ \BOOL{\itm{bool}}
  9147. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  9148. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP }
  9149. \MID \APPLY{\Exp}{\Exp\ldots}\\
  9150. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  9151. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  9152. \end{array}
  9153. \]
  9154. \end{minipage}
  9155. }
  9156. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  9157. \label{fig:Rfun-syntax}
  9158. \end{figure}
  9159. The program in Figure~\ref{fig:Rfun-function-example} is a
  9160. representative example of defining and using functions in \LangFun{}. We
  9161. define a function \code{map-vec} that applies some other function
  9162. \code{f} to both elements of a vector and returns a new
  9163. vector containing the results. We also define a function \code{add1}.
  9164. The program applies
  9165. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  9166. \code{(vector 1 42)}, from which we return the \code{42}.
  9167. \begin{figure}[tbp]
  9168. \begin{lstlisting}
  9169. (define (map-vec [f : (Integer -> Integer)]
  9170. [v : (Vector Integer Integer)])
  9171. : (Vector Integer Integer)
  9172. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  9173. (define (add1 [x : Integer]) : Integer
  9174. (+ x 1))
  9175. (vector-ref (map-vec add1 (vector 0 41)) 1)
  9176. \end{lstlisting}
  9177. \caption{Example of using functions in \LangFun{}.}
  9178. \label{fig:Rfun-function-example}
  9179. \end{figure}
  9180. The definitional interpreter for \LangFun{} is in
  9181. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  9182. responsible for setting up the mutual recursion between the top-level
  9183. function definitions. We use the classic back-patching \index{subject}{back-patching}
  9184. approach that uses mutable variables and makes two passes over the function
  9185. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  9186. top-level environment using a mutable cons cell for each function
  9187. definition. Note that the \code{lambda} value for each function is
  9188. incomplete; it does not yet include the environment. Once the
  9189. top-level environment is constructed, we then iterate over it and
  9190. update the \code{lambda} values to use the top-level environment.
  9191. \begin{figure}[tp]
  9192. \begin{lstlisting}
  9193. (define interp-Rfun_class
  9194. (class interp-Rvec_class
  9195. (super-new)
  9196. (define/override ((interp-exp env) e)
  9197. (define recur (interp-exp env))
  9198. (match e
  9199. [(Var x) (unbox (dict-ref env x))]
  9200. [(Let x e body)
  9201. (define new-env (dict-set env x (box (recur e))))
  9202. ((interp-exp new-env) body)]
  9203. [(Apply fun args)
  9204. (define fun-val (recur fun))
  9205. (define arg-vals (for/list ([e args]) (recur e)))
  9206. (match fun-val
  9207. [`(function (,xs ...) ,body ,fun-env)
  9208. (define params-args (for/list ([x xs] [arg arg-vals])
  9209. (cons x (box arg))))
  9210. (define new-env (append params-args fun-env))
  9211. ((interp-exp new-env) body)]
  9212. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  9213. [else ((super interp-exp env) e)]
  9214. ))
  9215. (define/public (interp-def d)
  9216. (match d
  9217. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  9218. (cons f (box `(function ,xs ,body ())))]))
  9219. (define/override (interp-program p)
  9220. (match p
  9221. [(ProgramDefsExp info ds body)
  9222. (let ([top-level (for/list ([d ds]) (interp-def d))])
  9223. (for/list ([f (in-dict-values top-level)])
  9224. (set-box! f (match (unbox f)
  9225. [`(function ,xs ,body ())
  9226. `(function ,xs ,body ,top-level)])))
  9227. ((interp-exp top-level) body))]))
  9228. ))
  9229. (define (interp-Rfun p)
  9230. (send (new interp-Rfun_class) interp-program p))
  9231. \end{lstlisting}
  9232. \caption{Interpreter for the \LangFun{} language.}
  9233. \label{fig:interp-Rfun}
  9234. \end{figure}
  9235. %\margincomment{TODO: explain type checker}
  9236. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  9237. \begin{figure}[tp]
  9238. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9239. (define type-check-Rfun_class
  9240. (class type-check-Rvec_class
  9241. (super-new)
  9242. (inherit check-type-equal?)
  9243. (define/public (type-check-apply env e es)
  9244. (define-values (e^ ty) ((type-check-exp env) e))
  9245. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  9246. ((type-check-exp env) e)))
  9247. (match ty
  9248. [`(,ty^* ... -> ,rt)
  9249. (for ([arg-ty ty*] [param-ty ty^*])
  9250. (check-type-equal? arg-ty param-ty (Apply e es)))
  9251. (values e^ e* rt)]))
  9252. (define/override (type-check-exp env)
  9253. (lambda (e)
  9254. (match e
  9255. [(FunRef f)
  9256. (values (FunRef f) (dict-ref env f))]
  9257. [(Apply e es)
  9258. (define-values (e^ es^ rt) (type-check-apply env e es))
  9259. (values (Apply e^ es^) rt)]
  9260. [(Call e es)
  9261. (define-values (e^ es^ rt) (type-check-apply env e es))
  9262. (values (Call e^ es^) rt)]
  9263. [else ((super type-check-exp env) e)])))
  9264. (define/public (type-check-def env)
  9265. (lambda (e)
  9266. (match e
  9267. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  9268. (define new-env (append (map cons xs ps) env))
  9269. (define-values (body^ ty^) ((type-check-exp new-env) body))
  9270. (check-type-equal? ty^ rt body)
  9271. (Def f p:t* rt info body^)])))
  9272. (define/public (fun-def-type d)
  9273. (match d
  9274. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  9275. (define/override (type-check-program e)
  9276. (match e
  9277. [(ProgramDefsExp info ds body)
  9278. (define new-env (for/list ([d ds])
  9279. (cons (Def-name d) (fun-def-type d))))
  9280. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  9281. (define-values (body^ ty) ((type-check-exp new-env) body))
  9282. (check-type-equal? ty 'Integer body)
  9283. (ProgramDefsExp info ds^ body^)]))))
  9284. (define (type-check-Rfun p)
  9285. (send (new type-check-Rfun_class) type-check-program p))
  9286. \end{lstlisting}
  9287. \caption{Type checker for the \LangFun{} language.}
  9288. \label{fig:type-check-Rfun}
  9289. \end{figure}
  9290. \section{Functions in x86}
  9291. \label{sec:fun-x86}
  9292. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  9293. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  9294. %% \margincomment{\tiny Talk about the return address on the
  9295. %% stack and what callq and retq does.\\ --Jeremy }
  9296. The x86 architecture provides a few features to support the
  9297. implementation of functions. We have already seen that x86 provides
  9298. labels so that one can refer to the location of an instruction, as is
  9299. needed for jump instructions. Labels can also be used to mark the
  9300. beginning of the instructions for a function. Going further, we can
  9301. obtain the address of a label by using the \key{leaq} instruction and
  9302. PC-relative addressing. For example, the following puts the
  9303. address of the \code{add1} label into the \code{rbx} register.
  9304. \begin{lstlisting}
  9305. leaq add1(%rip), %rbx
  9306. \end{lstlisting}
  9307. The instruction pointer register \key{rip} (aka. the program counter
  9308. \index{subject}{program counter}) always points to the next instruction to be
  9309. executed. When combined with an label, as in \code{add1(\%rip)}, the
  9310. linker computes the distance $d$ between the address of \code{add1}
  9311. and where the \code{rip} would be at that moment and then changes
  9312. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  9313. the address of \code{add1}.
  9314. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  9315. jump to a function whose location is given by a label. To support
  9316. function calls in this chapter we instead will be jumping to a
  9317. function whose location is given by an address in a register, that is,
  9318. we need to make an \emph{indirect function call}. The x86 syntax for
  9319. this is a \code{callq} instruction but with an asterisk before the
  9320. register name.\index{subject}{indirect function call}
  9321. \begin{lstlisting}
  9322. callq *%rbx
  9323. \end{lstlisting}
  9324. \subsection{Calling Conventions}
  9325. \index{subject}{calling conventions}
  9326. The \code{callq} instruction provides partial support for implementing
  9327. functions: it pushes the return address on the stack and it jumps to
  9328. the target. However, \code{callq} does not handle
  9329. \begin{enumerate}
  9330. \item parameter passing,
  9331. \item pushing frames on the procedure call stack and popping them off,
  9332. or
  9333. \item determining how registers are shared by different functions.
  9334. \end{enumerate}
  9335. Regarding (1) parameter passing, recall that the following six
  9336. registers are used to pass arguments to a function, in this order.
  9337. \begin{lstlisting}
  9338. rdi rsi rdx rcx r8 r9
  9339. \end{lstlisting}
  9340. If there are
  9341. more than six arguments, then the convention is to use space on the
  9342. frame of the caller for the rest of the arguments. However, to ease
  9343. the implementation of efficient tail calls
  9344. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  9345. arguments.
  9346. %
  9347. Also recall that the register \code{rax} is for the return value of
  9348. the function.
  9349. \index{subject}{prelude}\index{subject}{conclusion}
  9350. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  9351. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  9352. the stack grows down, with each function call using a chunk of space
  9353. called a frame. The caller sets the stack pointer, register
  9354. \code{rsp}, to the last data item in its frame. The callee must not
  9355. change anything in the caller's frame, that is, anything that is at or
  9356. above the stack pointer. The callee is free to use locations that are
  9357. below the stack pointer.
  9358. Recall that we are storing variables of vector type on the root stack.
  9359. So the prelude needs to move the root stack pointer \code{r15} up and
  9360. the conclusion needs to move the root stack pointer back down. Also,
  9361. the prelude must initialize to \code{0} this frame's slots in the root
  9362. stack to signal to the garbage collector that those slots do not yet
  9363. contain a pointer to a vector. Otherwise the garbage collector will
  9364. interpret the garbage bits in those slots as memory addresses and try
  9365. to traverse them, causing serious mayhem!
  9366. Regarding (3) the sharing of registers between different functions,
  9367. recall from Section~\ref{sec:calling-conventions} that the registers
  9368. are divided into two groups, the caller-saved registers and the
  9369. callee-saved registers. The caller should assume that all the
  9370. caller-saved registers get overwritten with arbitrary values by the
  9371. callee. That is why we recommend in
  9372. Section~\ref{sec:calling-conventions} that variables that are live
  9373. during a function call should not be assigned to caller-saved
  9374. registers.
  9375. On the flip side, if the callee wants to use a callee-saved register,
  9376. the callee must save the contents of those registers on their stack
  9377. frame and then put them back prior to returning to the caller. That
  9378. is why we recommended in Section~\ref{sec:calling-conventions} that if
  9379. the register allocator assigns a variable to a callee-saved register,
  9380. then the prelude of the \code{main} function must save that register
  9381. to the stack and the conclusion of \code{main} must restore it. This
  9382. recommendation now generalizes to all functions.
  9383. Also recall that the base pointer, register \code{rbp}, is used as a
  9384. point-of-reference within a frame, so that each local variable can be
  9385. accessed at a fixed offset from the base pointer
  9386. (Section~\ref{sec:x86}).
  9387. %
  9388. Figure~\ref{fig:call-frames} shows the general layout of the caller
  9389. and callee frames.
  9390. \begin{figure}[tbp]
  9391. \centering
  9392. \begin{tabular}{r|r|l|l} \hline
  9393. Caller View & Callee View & Contents & Frame \\ \hline
  9394. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  9395. 0(\key{\%rbp}) & & old \key{rbp} \\
  9396. -8(\key{\%rbp}) & & callee-saved $1$ \\
  9397. \ldots & & \ldots \\
  9398. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  9399. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  9400. \ldots & & \ldots \\
  9401. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  9402. %% & & \\
  9403. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  9404. %% & \ldots & \ldots \\
  9405. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  9406. \hline
  9407. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  9408. & 0(\key{\%rbp}) & old \key{rbp} \\
  9409. & -8(\key{\%rbp}) & callee-saved $1$ \\
  9410. & \ldots & \ldots \\
  9411. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  9412. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  9413. & \ldots & \ldots \\
  9414. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  9415. \end{tabular}
  9416. \caption{Memory layout of caller and callee frames.}
  9417. \label{fig:call-frames}
  9418. \end{figure}
  9419. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  9420. %% local variables and for storing the values of callee-saved registers
  9421. %% (we shall refer to all of these collectively as ``locals''), and that
  9422. %% at the beginning of a function we move the stack pointer \code{rsp}
  9423. %% down to make room for them.
  9424. %% We recommend storing the local variables
  9425. %% first and then the callee-saved registers, so that the local variables
  9426. %% can be accessed using \code{rbp} the same as before the addition of
  9427. %% functions.
  9428. %% To make additional room for passing arguments, we shall
  9429. %% move the stack pointer even further down. We count how many stack
  9430. %% arguments are needed for each function call that occurs inside the
  9431. %% body of the function and find their maximum. Adding this number to the
  9432. %% number of locals gives us how much the \code{rsp} should be moved at
  9433. %% the beginning of the function. In preparation for a function call, we
  9434. %% offset from \code{rsp} to set up the stack arguments. We put the first
  9435. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  9436. %% so on.
  9437. %% Upon calling the function, the stack arguments are retrieved by the
  9438. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  9439. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  9440. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  9441. %% the layout of the caller and callee frames. Notice how important it is
  9442. %% that we correctly compute the maximum number of arguments needed for
  9443. %% function calls; if that number is too small then the arguments and
  9444. %% local variables will smash into each other!
  9445. \subsection{Efficient Tail Calls}
  9446. \label{sec:tail-call}
  9447. In general, the amount of stack space used by a program is determined
  9448. by the longest chain of nested function calls. That is, if function
  9449. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  9450. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  9451. $n$ can grow quite large in the case of recursive or mutually
  9452. recursive functions. However, in some cases we can arrange to use only
  9453. constant space, i.e. $O(1)$, instead of $O(n)$.
  9454. If a function call is the last action in a function body, then that
  9455. call is said to be a \emph{tail call}\index{subject}{tail call}.
  9456. For example, in the following
  9457. program, the recursive call to \code{tail-sum} is a tail call.
  9458. \begin{center}
  9459. \begin{lstlisting}
  9460. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  9461. (if (eq? n 0)
  9462. r
  9463. (tail-sum (- n 1) (+ n r))))
  9464. (+ (tail-sum 5 0) 27)
  9465. \end{lstlisting}
  9466. \end{center}
  9467. At a tail call, the frame of the caller is no longer needed, so we
  9468. can pop the caller's frame before making the tail call. With this
  9469. approach, a recursive function that only makes tail calls will only
  9470. use $O(1)$ stack space. Functional languages like Racket typically
  9471. rely heavily on recursive functions, so they typically guarantee that
  9472. all tail calls will be optimized in this way.
  9473. \index{subject}{frame}
  9474. However, some care is needed with regards to argument passing in tail
  9475. calls. As mentioned above, for arguments beyond the sixth, the
  9476. convention is to use space in the caller's frame for passing
  9477. arguments. But for a tail call we pop the caller's frame and can no
  9478. longer use it. Another alternative is to use space in the callee's
  9479. frame for passing arguments. However, this option is also problematic
  9480. because the caller and callee's frame overlap in memory. As we begin
  9481. to copy the arguments from their sources in the caller's frame, the
  9482. target locations in the callee's frame might overlap with the sources
  9483. for later arguments! We solve this problem by using the heap instead
  9484. of the stack for passing more than six arguments, as we describe in
  9485. the Section~\ref{sec:limit-functions-r4}.
  9486. As mentioned above, for a tail call we pop the caller's frame prior to
  9487. making the tail call. The instructions for popping a frame are the
  9488. instructions that we usually place in the conclusion of a
  9489. function. Thus, we also need to place such code immediately before
  9490. each tail call. These instructions include restoring the callee-saved
  9491. registers, so it is good that the argument passing registers are all
  9492. caller-saved registers.
  9493. One last note regarding which instruction to use to make the tail
  9494. call. When the callee is finished, it should not return to the current
  9495. function, but it should return to the function that called the current
  9496. one. Thus, the return address that is already on the stack is the
  9497. right one, and we should not use \key{callq} to make the tail call, as
  9498. that would unnecessarily overwrite the return address. Instead we can
  9499. simply use the \key{jmp} instruction. Like the indirect function call,
  9500. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  9501. prefixed with an asterisk. We recommend using \code{rax} to hold the
  9502. jump target because the preceding conclusion overwrites just about
  9503. everything else.
  9504. \begin{lstlisting}
  9505. jmp *%rax
  9506. \end{lstlisting}
  9507. \section{Shrink \LangFun{}}
  9508. \label{sec:shrink-r4}
  9509. The \code{shrink} pass performs a minor modification to ease the
  9510. later passes. This pass introduces an explicit \code{main} function
  9511. and changes the top \code{ProgramDefsExp} form to
  9512. \code{ProgramDefs} as follows.
  9513. \begin{lstlisting}
  9514. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  9515. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  9516. \end{lstlisting}
  9517. where $\itm{mainDef}$ is
  9518. \begin{lstlisting}
  9519. (Def 'main '() 'Integer '() |$\Exp'$|)
  9520. \end{lstlisting}
  9521. \section{Reveal Functions and the \LangFunRef{} language}
  9522. \label{sec:reveal-functions-r4}
  9523. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  9524. respect: it conflates the use of function names and local
  9525. variables. This is a problem because we need to compile the use of a
  9526. function name differently than the use of a local variable; we need to
  9527. use \code{leaq} to convert the function name (a label in x86) to an
  9528. address in a register. Thus, it is a good idea to create a new pass
  9529. that changes function references from just a symbol $f$ to
  9530. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  9531. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  9532. The concrete syntax for a function reference is $\CFUNREF{f}$.
  9533. \begin{figure}[tp]
  9534. \centering
  9535. \fbox{
  9536. \begin{minipage}{0.96\textwidth}
  9537. \[
  9538. \begin{array}{lcl}
  9539. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  9540. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9541. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  9542. \end{array}
  9543. \]
  9544. \end{minipage}
  9545. }
  9546. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  9547. (Figure~\ref{fig:Rfun-syntax}).}
  9548. \label{fig:f1-syntax}
  9549. \end{figure}
  9550. %% Distinguishing between calls in tail position and non-tail position
  9551. %% requires the pass to have some notion of context. We recommend using
  9552. %% two mutually recursive functions, one for processing expressions in
  9553. %% tail position and another for the rest.
  9554. Placing this pass after \code{uniquify} will make sure that there are
  9555. no local variables and functions that share the same name. On the
  9556. other hand, \code{reveal-functions} needs to come before the
  9557. \code{explicate\_control} pass because that pass helps us compile
  9558. \code{FunRef} forms into assignment statements.
  9559. \section{Limit Functions}
  9560. \label{sec:limit-functions-r4}
  9561. Recall that we wish to limit the number of function parameters to six
  9562. so that we do not need to use the stack for argument passing, which
  9563. makes it easier to implement efficient tail calls. However, because
  9564. the input language \LangFun{} supports arbitrary numbers of function
  9565. arguments, we have some work to do!
  9566. This pass transforms functions and function calls that involve more
  9567. than six arguments to pass the first five arguments as usual, but it
  9568. packs the rest of the arguments into a vector and passes it as the
  9569. sixth argument.
  9570. Each function definition with too many parameters is transformed as
  9571. follows.
  9572. \begin{lstlisting}
  9573. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  9574. |$\Rightarrow$|
  9575. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  9576. \end{lstlisting}
  9577. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  9578. the occurrences of the later parameters with vector references.
  9579. \begin{lstlisting}
  9580. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  9581. \end{lstlisting}
  9582. For function calls with too many arguments, the \code{limit-functions}
  9583. pass transforms them in the following way.
  9584. \begin{tabular}{lll}
  9585. \begin{minipage}{0.2\textwidth}
  9586. \begin{lstlisting}
  9587. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  9588. \end{lstlisting}
  9589. \end{minipage}
  9590. &
  9591. $\Rightarrow$
  9592. &
  9593. \begin{minipage}{0.4\textwidth}
  9594. \begin{lstlisting}
  9595. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  9596. \end{lstlisting}
  9597. \end{minipage}
  9598. \end{tabular}
  9599. \section{Remove Complex Operands}
  9600. \label{sec:rco-r4}
  9601. The primary decisions to make for this pass is whether to classify
  9602. \code{FunRef} and \code{Apply} as either atomic or complex
  9603. expressions. Recall that a simple expression will eventually end up as
  9604. just an immediate argument of an x86 instruction. Function
  9605. application will be translated to a sequence of instructions, so
  9606. \code{Apply} must be classified as complex expression.
  9607. On the other hand, the arguments of \code{Apply} should be
  9608. atomic expressions.
  9609. %
  9610. Regarding \code{FunRef}, as discussed above, the function label needs
  9611. to be converted to an address using the \code{leaq} instruction. Thus,
  9612. even though \code{FunRef} seems rather simple, it needs to be
  9613. classified as a complex expression so that we generate an assignment
  9614. statement with a left-hand side that can serve as the target of the
  9615. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  9616. output language \LangFunANF{} of this pass.
  9617. \begin{figure}[tp]
  9618. \centering
  9619. \fbox{
  9620. \begin{minipage}{0.96\textwidth}
  9621. \small
  9622. \[
  9623. \begin{array}{rcl}
  9624. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  9625. \MID \VOID{} } \\
  9626. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  9627. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  9628. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9629. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  9630. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  9631. &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  9632. \MID \LP\key{GlobalValue}~\Var\RP }\\
  9633. &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  9634. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9635. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9636. \end{array}
  9637. \]
  9638. \end{minipage}
  9639. }
  9640. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  9641. \label{fig:Rfun-anf-syntax}
  9642. \end{figure}
  9643. \section{Explicate Control and the \LangCFun{} language}
  9644. \label{sec:explicate-control-r4}
  9645. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  9646. output of \code{explicate\_control}. (The concrete syntax is given in
  9647. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  9648. functions for assignment and tail contexts should be updated with
  9649. cases for \code{Apply} and \code{FunRef} and the function for
  9650. predicate context should be updated for \code{Apply} but not
  9651. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  9652. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  9653. tail position \code{Apply} becomes \code{TailCall}. We recommend
  9654. defining a new auxiliary function for processing function definitions.
  9655. This code is similar to the case for \code{Program} in \LangVec{}. The
  9656. top-level \code{explicate\_control} function that handles the
  9657. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  9658. all the function definitions.
  9659. \begin{figure}[tp]
  9660. \fbox{
  9661. \begin{minipage}{0.96\textwidth}
  9662. \small
  9663. \[
  9664. \begin{array}{lcl}
  9665. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  9666. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  9667. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  9668. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  9669. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  9670. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  9671. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  9672. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  9673. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  9674. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  9675. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9676. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  9677. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  9678. \MID \GOTO{\itm{label}} } \\
  9679. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9680. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  9681. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9682. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9683. \end{array}
  9684. \]
  9685. \end{minipage}
  9686. }
  9687. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  9688. \label{fig:c3-syntax}
  9689. \end{figure}
  9690. \section{Select Instructions and the \LangXIndCall{} Language}
  9691. \label{sec:select-r4}
  9692. \index{subject}{instruction selection}
  9693. The output of select instructions is a program in the \LangXIndCall{}
  9694. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  9695. \index{subject}{x86}
  9696. \begin{figure}[tp]
  9697. \fbox{
  9698. \begin{minipage}{0.96\textwidth}
  9699. \small
  9700. \[
  9701. \begin{array}{lcl}
  9702. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)}
  9703. \MID \LP\key{fun-ref}\; \itm{label}\RP\\
  9704. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  9705. \Instr &::=& \ldots
  9706. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  9707. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  9708. \Block &::= & \Instr\ldots \\
  9709. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  9710. \LangXIndCallM{} &::= & \Def\ldots
  9711. \end{array}
  9712. \]
  9713. \end{minipage}
  9714. }
  9715. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  9716. \label{fig:x86-3-concrete}
  9717. \end{figure}
  9718. \begin{figure}[tp]
  9719. \fbox{
  9720. \begin{minipage}{0.96\textwidth}
  9721. \small
  9722. \[
  9723. \begin{array}{lcl}
  9724. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  9725. \MID \BYTEREG{\Reg} } \\
  9726. &\MID& \gray{ (\key{Global}~\Var) } \MID \FUNREF{\itm{label}} \\
  9727. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  9728. \MID \TAILJMP{\Arg}{\itm{int}}\\
  9729. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  9730. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  9731. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  9732. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9733. \end{array}
  9734. \]
  9735. \end{minipage}
  9736. }
  9737. \caption{The abstract syntax of \LangXIndCall{} (extends
  9738. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  9739. \label{fig:x86-3}
  9740. \end{figure}
  9741. An assignment of a function reference to a variable becomes a
  9742. load-effective-address instruction as follows: \\
  9743. \begin{tabular}{lcl}
  9744. \begin{minipage}{0.35\textwidth}
  9745. \begin{lstlisting}
  9746. |$\itm{lhs}$| = (fun-ref |$f$|);
  9747. \end{lstlisting}
  9748. \end{minipage}
  9749. &
  9750. $\Rightarrow$\qquad\qquad
  9751. &
  9752. \begin{minipage}{0.3\textwidth}
  9753. \begin{lstlisting}
  9754. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  9755. \end{lstlisting}
  9756. \end{minipage}
  9757. \end{tabular} \\
  9758. Regarding function definitions, we need to remove the parameters and
  9759. instead perform parameter passing using the conventions discussed in
  9760. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  9761. registers. We recommend turning the parameters into local variables
  9762. and generating instructions at the beginning of the function to move
  9763. from the argument passing registers to these local variables.
  9764. \begin{lstlisting}
  9765. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  9766. |$\Rightarrow$|
  9767. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  9768. \end{lstlisting}
  9769. The $G'$ control-flow graph is the same as $G$ except that the
  9770. \code{start} block is modified to add the instructions for moving from
  9771. the argument registers to the parameter variables. So the \code{start}
  9772. block of $G$ shown on the left is changed to the code on the right.
  9773. \begin{center}
  9774. \begin{minipage}{0.3\textwidth}
  9775. \begin{lstlisting}
  9776. start:
  9777. |$\itm{instr}_1$|
  9778. |$\vdots$|
  9779. |$\itm{instr}_n$|
  9780. \end{lstlisting}
  9781. \end{minipage}
  9782. $\Rightarrow$
  9783. \begin{minipage}{0.3\textwidth}
  9784. \begin{lstlisting}
  9785. start:
  9786. movq %rdi, |$x_1$|
  9787. movq %rsi, |$x_2$|
  9788. |$\vdots$|
  9789. |$\itm{instr}_1$|
  9790. |$\vdots$|
  9791. |$\itm{instr}_n$|
  9792. \end{lstlisting}
  9793. \end{minipage}
  9794. \end{center}
  9795. By changing the parameters to local variables, we are giving the
  9796. register allocator control over which registers or stack locations to
  9797. use for them. If you implemented the move-biasing challenge
  9798. (Section~\ref{sec:move-biasing}), the register allocator will try to
  9799. assign the parameter variables to the corresponding argument register,
  9800. in which case the \code{patch-instructions} pass will remove the
  9801. \code{movq} instruction. This happens in the example translation in
  9802. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  9803. the \code{add} function.
  9804. %
  9805. Also, note that the register allocator will perform liveness analysis
  9806. on this sequence of move instructions and build the interference
  9807. graph. So, for example, $x_1$ will be marked as interfering with
  9808. \code{rsi} and that will prevent the assignment of $x_1$ to
  9809. \code{rsi}, which is good, because that would overwrite the argument
  9810. that needs to move into $x_2$.
  9811. Next, consider the compilation of function calls. In the mirror image
  9812. of handling the parameters of function definitions, the arguments need
  9813. to be moved to the argument passing registers. The function call
  9814. itself is performed with an indirect function call. The return value
  9815. from the function is stored in \code{rax}, so it needs to be moved
  9816. into the \itm{lhs}.
  9817. \begin{lstlisting}
  9818. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  9819. |$\Rightarrow$|
  9820. movq |$\itm{arg}_1$|, %rdi
  9821. movq |$\itm{arg}_2$|, %rsi
  9822. |$\vdots$|
  9823. callq *|\itm{fun}|
  9824. movq %rax, |\itm{lhs}|
  9825. \end{lstlisting}
  9826. The \code{IndirectCallq} AST node includes an integer for the arity of
  9827. the function, i.e., the number of parameters. That information is
  9828. useful in the \code{uncover-live} pass for determining which
  9829. argument-passing registers are potentially read during the call.
  9830. For tail calls, the parameter passing is the same as non-tail calls:
  9831. generate instructions to move the arguments into to the argument
  9832. passing registers. After that we need to pop the frame from the
  9833. procedure call stack. However, we do not yet know how big the frame
  9834. is; that gets determined during register allocation. So instead of
  9835. generating those instructions here, we invent a new instruction that
  9836. means ``pop the frame and then do an indirect jump'', which we name
  9837. \code{TailJmp}. The abstract syntax for this instruction includes an
  9838. argument that specifies where to jump and an integer that represents
  9839. the arity of the function being called.
  9840. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  9841. using the label \code{start} for the initial block of a program, and
  9842. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  9843. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  9844. can be compiled to an assignment to \code{rax} followed by a jump to
  9845. \code{conclusion}. With the addition of function definitions, we will
  9846. have a starting block and conclusion for each function, but their
  9847. labels need to be unique. We recommend prepending the function's name
  9848. to \code{start} and \code{conclusion}, respectively, to obtain unique
  9849. labels. (Alternatively, one could \code{gensym} labels for the start
  9850. and conclusion and store them in the $\itm{info}$ field of the
  9851. function definition.)
  9852. \section{Register Allocation}
  9853. \label{sec:register-allocation-r4}
  9854. \subsection{Liveness Analysis}
  9855. \label{sec:liveness-analysis-r4}
  9856. \index{subject}{liveness analysis}
  9857. %% The rest of the passes need only minor modifications to handle the new
  9858. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  9859. %% \code{leaq}.
  9860. The \code{IndirectCallq} instruction should be treated like
  9861. \code{Callq} regarding its written locations $W$, in that they should
  9862. include all the caller-saved registers. Recall that the reason for
  9863. that is to force call-live variables to be assigned to callee-saved
  9864. registers or to be spilled to the stack.
  9865. Regarding the set of read locations $R$ the arity field of
  9866. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  9867. argument-passing registers should be considered as read by those
  9868. instructions.
  9869. \subsection{Build Interference Graph}
  9870. \label{sec:build-interference-r4}
  9871. With the addition of function definitions, we compute an interference
  9872. graph for each function (not just one for the whole program).
  9873. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  9874. spill vector-typed variables that are live during a call to the
  9875. \code{collect}. With the addition of functions to our language, we
  9876. need to revisit this issue. Many functions perform allocation and
  9877. therefore have calls to the collector inside of them. Thus, we should
  9878. not only spill a vector-typed variable when it is live during a call
  9879. to \code{collect}, but we should spill the variable if it is live
  9880. during any function call. Thus, in the \code{build-interference} pass,
  9881. we recommend adding interference edges between call-live vector-typed
  9882. variables and the callee-saved registers (in addition to the usual
  9883. addition of edges between call-live variables and the caller-saved
  9884. registers).
  9885. \subsection{Allocate Registers}
  9886. The primary change to the \code{allocate-registers} pass is adding an
  9887. auxiliary function for handling definitions (the \Def{} non-terminal
  9888. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  9889. logic is the same as described in
  9890. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  9891. allocation is performed many times, once for each function definition,
  9892. instead of just once for the whole program.
  9893. \section{Patch Instructions}
  9894. In \code{patch-instructions}, you should deal with the x86
  9895. idiosyncrasy that the destination argument of \code{leaq} must be a
  9896. register. Additionally, you should ensure that the argument of
  9897. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  9898. code generation more convenient, because we trample many registers
  9899. before the tail call (as explained in the next section).
  9900. \section{Print x86}
  9901. For the \code{print\_x86} pass, the cases for \code{FunRef} and
  9902. \code{IndirectCallq} are straightforward: output their concrete
  9903. syntax.
  9904. \begin{lstlisting}
  9905. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  9906. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  9907. \end{lstlisting}
  9908. The \code{TailJmp} node requires a bit work. A straightforward
  9909. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  9910. before the jump we need to pop the current frame. This sequence of
  9911. instructions is the same as the code for the conclusion of a function,
  9912. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  9913. Regarding function definitions, you will need to generate a prelude
  9914. and conclusion for each one. This code is similar to the prelude and
  9915. conclusion that you generated for the \code{main} function in
  9916. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  9917. should carry out the following steps.
  9918. \begin{enumerate}
  9919. \item Start with \code{.global} and \code{.align} directives followed
  9920. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  9921. example.)
  9922. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  9923. pointer.
  9924. \item Push to the stack all of the callee-saved registers that were
  9925. used for register allocation.
  9926. \item Move the stack pointer \code{rsp} down by the size of the stack
  9927. frame for this function, which depends on the number of regular
  9928. spills. (Aligned to 16 bytes.)
  9929. \item Move the root stack pointer \code{r15} up by the size of the
  9930. root-stack frame for this function, which depends on the number of
  9931. spilled vectors. \label{root-stack-init}
  9932. \item Initialize to zero all of the entries in the root-stack frame.
  9933. \item Jump to the start block.
  9934. \end{enumerate}
  9935. The prelude of the \code{main} function has one additional task: call
  9936. the \code{initialize} function to set up the garbage collector and
  9937. move the value of the global \code{rootstack\_begin} in
  9938. \code{r15}. This should happen before step \ref{root-stack-init}
  9939. above, which depends on \code{r15}.
  9940. The conclusion of every function should do the following.
  9941. \begin{enumerate}
  9942. \item Move the stack pointer back up by the size of the stack frame
  9943. for this function.
  9944. \item Restore the callee-saved registers by popping them from the
  9945. stack.
  9946. \item Move the root stack pointer back down by the size of the
  9947. root-stack frame for this function.
  9948. \item Restore \code{rbp} by popping it from the stack.
  9949. \item Return to the caller with the \code{retq} instruction.
  9950. \end{enumerate}
  9951. \begin{exercise}\normalfont
  9952. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  9953. Create 5 new programs that use functions, including examples that pass
  9954. functions and return functions from other functions, recursive
  9955. functions, functions that create vectors, and functions that make tail
  9956. calls. Test your compiler on these new programs and all of your
  9957. previously created test programs.
  9958. \end{exercise}
  9959. \begin{figure}[tbp]
  9960. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9961. \node (Rfun) at (0,2) {\large \LangFun{}};
  9962. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  9963. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  9964. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  9965. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  9966. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  9967. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  9968. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  9969. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9970. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9971. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9972. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9973. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9974. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9975. \path[->,bend left=15] (Rfun) edge [above] node
  9976. {\ttfamily\footnotesize shrink} (Rfun-1);
  9977. \path[->,bend left=15] (Rfun-1) edge [above] node
  9978. {\ttfamily\footnotesize uniquify} (Rfun-2);
  9979. \path[->,bend left=15] (Rfun-2) edge [right] node
  9980. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  9981. \path[->,bend left=15] (F1-1) edge [below] node
  9982. {\ttfamily\footnotesize limit-functions} (F1-2);
  9983. \path[->,bend right=15] (F1-2) edge [above] node
  9984. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  9985. \path[->,bend right=15] (F1-3) edge [above] node
  9986. {\ttfamily\footnotesize remove-complex.} (F1-4);
  9987. \path[->,bend left=15] (F1-4) edge [right] node
  9988. {\ttfamily\footnotesize explicate-control} (C3-2);
  9989. \path[->,bend right=15] (C3-2) edge [left] node
  9990. {\ttfamily\footnotesize select-instr.} (x86-2);
  9991. \path[->,bend left=15] (x86-2) edge [left] node
  9992. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9993. \path[->,bend right=15] (x86-2-1) edge [below] node
  9994. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9995. \path[->,bend right=15] (x86-2-2) edge [left] node
  9996. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9997. \path[->,bend left=15] (x86-3) edge [above] node
  9998. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9999. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  10000. \end{tikzpicture}
  10001. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  10002. \label{fig:Rfun-passes}
  10003. \end{figure}
  10004. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  10005. compiling \LangFun{} to x86.
  10006. \section{An Example Translation}
  10007. \label{sec:functions-example}
  10008. Figure~\ref{fig:add-fun} shows an example translation of a simple
  10009. function in \LangFun{} to x86. The figure also includes the results of the
  10010. \code{explicate\_control} and \code{select-instructions} passes.
  10011. \begin{figure}[htbp]
  10012. \begin{tabular}{ll}
  10013. \begin{minipage}{0.5\textwidth}
  10014. % s3_2.rkt
  10015. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10016. (define (add [x : Integer] [y : Integer])
  10017. : Integer
  10018. (+ x y))
  10019. (add 40 2)
  10020. \end{lstlisting}
  10021. $\Downarrow$
  10022. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10023. (define (add86 [x87 : Integer]
  10024. [y88 : Integer]) : Integer
  10025. add86start:
  10026. return (+ x87 y88);
  10027. )
  10028. (define (main) : Integer ()
  10029. mainstart:
  10030. tmp89 = (fun-ref add86);
  10031. (tail-call tmp89 40 2)
  10032. )
  10033. \end{lstlisting}
  10034. \end{minipage}
  10035. &
  10036. $\Rightarrow$
  10037. \begin{minipage}{0.5\textwidth}
  10038. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10039. (define (add86) : Integer
  10040. add86start:
  10041. movq %rdi, x87
  10042. movq %rsi, y88
  10043. movq x87, %rax
  10044. addq y88, %rax
  10045. jmp add11389conclusion
  10046. )
  10047. (define (main) : Integer
  10048. mainstart:
  10049. leaq (fun-ref add86), tmp89
  10050. movq $40, %rdi
  10051. movq $2, %rsi
  10052. tail-jmp tmp89
  10053. )
  10054. \end{lstlisting}
  10055. $\Downarrow$
  10056. \end{minipage}
  10057. \end{tabular}
  10058. \begin{tabular}{ll}
  10059. \begin{minipage}{0.3\textwidth}
  10060. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10061. .globl add86
  10062. .align 16
  10063. add86:
  10064. pushq %rbp
  10065. movq %rsp, %rbp
  10066. jmp add86start
  10067. add86start:
  10068. movq %rdi, %rax
  10069. addq %rsi, %rax
  10070. jmp add86conclusion
  10071. add86conclusion:
  10072. popq %rbp
  10073. retq
  10074. \end{lstlisting}
  10075. \end{minipage}
  10076. &
  10077. \begin{minipage}{0.5\textwidth}
  10078. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10079. .globl main
  10080. .align 16
  10081. main:
  10082. pushq %rbp
  10083. movq %rsp, %rbp
  10084. movq $16384, %rdi
  10085. movq $16384, %rsi
  10086. callq initialize
  10087. movq rootstack_begin(%rip), %r15
  10088. jmp mainstart
  10089. mainstart:
  10090. leaq add86(%rip), %rcx
  10091. movq $40, %rdi
  10092. movq $2, %rsi
  10093. movq %rcx, %rax
  10094. popq %rbp
  10095. jmp *%rax
  10096. mainconclusion:
  10097. popq %rbp
  10098. retq
  10099. \end{lstlisting}
  10100. \end{minipage}
  10101. \end{tabular}
  10102. \caption{Example compilation of a simple function to x86.}
  10103. \label{fig:add-fun}
  10104. \end{figure}
  10105. % Challenge idea: inlining! (simple version)
  10106. % Further Reading
  10107. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10108. \chapter{Lexically Scoped Functions}
  10109. \label{ch:Rlam}
  10110. \index{subject}{lambda}
  10111. \index{subject}{lexical scoping}
  10112. This chapter studies lexically scoped functions as they appear in
  10113. functional languages such as Racket. By lexical scoping we mean that a
  10114. function's body may refer to variables whose binding site is outside
  10115. of the function, in an enclosing scope.
  10116. %
  10117. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  10118. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  10119. \key{lambda} form. The body of the \key{lambda}, refers to three
  10120. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  10121. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  10122. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  10123. parameter of function \code{f}. The \key{lambda} is returned from the
  10124. function \code{f}. The main expression of the program includes two
  10125. calls to \code{f} with different arguments for \code{x}, first
  10126. \code{5} then \code{3}. The functions returned from \code{f} are bound
  10127. to variables \code{g} and \code{h}. Even though these two functions
  10128. were created by the same \code{lambda}, they are really different
  10129. functions because they use different values for \code{x}. Applying
  10130. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  10131. \code{15} produces \code{22}. The result of this program is \code{42}.
  10132. \begin{figure}[btp]
  10133. % s4_6.rkt
  10134. \begin{lstlisting}
  10135. (define (f [x : Integer]) : (Integer -> Integer)
  10136. (let ([y 4])
  10137. (lambda: ([z : Integer]) : Integer
  10138. (+ x (+ y z)))))
  10139. (let ([g (f 5)])
  10140. (let ([h (f 3)])
  10141. (+ (g 11) (h 15))))
  10142. \end{lstlisting}
  10143. \caption{Example of a lexically scoped function.}
  10144. \label{fig:lexical-scoping}
  10145. \end{figure}
  10146. The approach that we take for implementing lexically scoped
  10147. functions is to compile them into top-level function definitions,
  10148. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  10149. provide special treatment for variable occurrences such as \code{x}
  10150. and \code{y} in the body of the \code{lambda} of
  10151. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  10152. refer to variables defined outside of it. To identify such variable
  10153. occurrences, we review the standard notion of free variable.
  10154. \begin{definition}
  10155. A variable is \emph{free in expression} $e$ if the variable occurs
  10156. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  10157. variable}
  10158. \end{definition}
  10159. For example, in the expression \code{(+ x (+ y z))} the variables
  10160. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  10161. only \code{x} and \code{y} are free in the following expression
  10162. because \code{z} is bound by the \code{lambda}.
  10163. \begin{lstlisting}
  10164. (lambda: ([z : Integer]) : Integer
  10165. (+ x (+ y z)))
  10166. \end{lstlisting}
  10167. So the free variables of a \code{lambda} are the ones that will need
  10168. special treatment. We need to arrange for some way to transport, at
  10169. runtime, the values of those variables from the point where the
  10170. \code{lambda} was created to the point where the \code{lambda} is
  10171. applied. An efficient solution to the problem, due to
  10172. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  10173. free variables together with the function pointer for the lambda's
  10174. code, an arrangement called a \emph{flat closure} (which we shorten to
  10175. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  10176. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  10177. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  10178. pointers. The function pointer resides at index $0$ and the
  10179. values for the free variables will fill in the rest of the vector.
  10180. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  10181. how closures work. It's a three-step dance. The program first calls
  10182. function \code{f}, which creates a closure for the \code{lambda}. The
  10183. closure is a vector whose first element is a pointer to the top-level
  10184. function that we will generate for the \code{lambda}, the second
  10185. element is the value of \code{x}, which is \code{5}, and the third
  10186. element is \code{4}, the value of \code{y}. The closure does not
  10187. contain an element for \code{z} because \code{z} is not a free
  10188. variable of the \code{lambda}. Creating the closure is step 1 of the
  10189. dance. The closure is returned from \code{f} and bound to \code{g}, as
  10190. shown in Figure~\ref{fig:closures}.
  10191. %
  10192. The second call to \code{f} creates another closure, this time with
  10193. \code{3} in the second slot (for \code{x}). This closure is also
  10194. returned from \code{f} but bound to \code{h}, which is also shown in
  10195. Figure~\ref{fig:closures}.
  10196. \begin{figure}[tbp]
  10197. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  10198. \caption{Example closure representation for the \key{lambda}'s
  10199. in Figure~\ref{fig:lexical-scoping}.}
  10200. \label{fig:closures}
  10201. \end{figure}
  10202. Continuing with the example, consider the application of \code{g} to
  10203. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  10204. obtain the function pointer in the first element of the closure and
  10205. call it, passing in the closure itself and then the regular arguments,
  10206. in this case \code{11}. This technique for applying a closure is step
  10207. 2 of the dance.
  10208. %
  10209. But doesn't this \code{lambda} only take 1 argument, for parameter
  10210. \code{z}? The third and final step of the dance is generating a
  10211. top-level function for a \code{lambda}. We add an additional
  10212. parameter for the closure and we insert a \code{let} at the beginning
  10213. of the function for each free variable, to bind those variables to the
  10214. appropriate elements from the closure parameter.
  10215. %
  10216. This three-step dance is known as \emph{closure conversion}. We
  10217. discuss the details of closure conversion in
  10218. Section~\ref{sec:closure-conversion} and the code generated from the
  10219. example in Section~\ref{sec:example-lambda}. But first we define the
  10220. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  10221. \section{The \LangLam{} Language}
  10222. \label{sec:r5}
  10223. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  10224. functions and lexical scoping, is defined in
  10225. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  10226. the \key{lambda} form to the grammar for \LangFun{}, which already has
  10227. syntax for function application.
  10228. \begin{figure}[tp]
  10229. \centering
  10230. \fbox{
  10231. \begin{minipage}{0.96\textwidth}
  10232. \small
  10233. \[
  10234. \begin{array}{lcl}
  10235. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  10236. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void}
  10237. \MID (\Type\ldots \; \key{->}\; \Type)} \\
  10238. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  10239. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  10240. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  10241. &\MID& \gray{\key{\#t} \MID \key{\#f}
  10242. \MID (\key{and}\;\Exp\;\Exp)
  10243. \MID (\key{or}\;\Exp\;\Exp)
  10244. \MID (\key{not}\;\Exp) } \\
  10245. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  10246. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  10247. (\key{vector-ref}\;\Exp\;\Int)} \\
  10248. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  10249. \MID (\Exp \; \Exp\ldots) } \\
  10250. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  10251. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  10252. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10253. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  10254. \end{array}
  10255. \]
  10256. \end{minipage}
  10257. }
  10258. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  10259. with \key{lambda}.}
  10260. \label{fig:Rlam-concrete-syntax}
  10261. \end{figure}
  10262. \begin{figure}[tp]
  10263. \centering
  10264. \fbox{
  10265. \begin{minipage}{0.96\textwidth}
  10266. \small
  10267. \[
  10268. \begin{array}{lcl}
  10269. \itm{op} &::=& \ldots \MID \code{procedure-arity} \\
  10270. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  10271. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10272. &\MID& \gray{ \BOOL{\itm{bool}}
  10273. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  10274. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  10275. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  10276. &\MID& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  10277. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  10278. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10279. \end{array}
  10280. \]
  10281. \end{minipage}
  10282. }
  10283. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  10284. \label{fig:Rlam-syntax}
  10285. \end{figure}
  10286. \index{subject}{interpreter}
  10287. \label{sec:interp-Rlambda}
  10288. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  10289. \LangLam{}. The case for \key{lambda} saves the current environment
  10290. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  10291. the environment from the \key{lambda}, the \code{lam-env}, when
  10292. interpreting the body of the \key{lambda}. The \code{lam-env}
  10293. environment is extended with the mapping of parameters to argument
  10294. values.
  10295. \begin{figure}[tbp]
  10296. \begin{lstlisting}
  10297. (define interp-Rlambda_class
  10298. (class interp-Rfun_class
  10299. (super-new)
  10300. (define/override (interp-op op)
  10301. (match op
  10302. ['procedure-arity
  10303. (lambda (v)
  10304. (match v
  10305. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  10306. [else (error 'interp-op "expected a function, not ~a" v)]))]
  10307. [else (super interp-op op)]))
  10308. (define/override ((interp-exp env) e)
  10309. (define recur (interp-exp env))
  10310. (match e
  10311. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  10312. `(function ,xs ,body ,env)]
  10313. [else ((super interp-exp env) e)]))
  10314. ))
  10315. (define (interp-Rlambda p)
  10316. (send (new interp-Rlambda_class) interp-program p))
  10317. \end{lstlisting}
  10318. \caption{Interpreter for \LangLam{}.}
  10319. \label{fig:interp-Rlambda}
  10320. \end{figure}
  10321. \label{sec:type-check-r5}
  10322. \index{subject}{type checking}
  10323. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  10324. \key{lambda} form. The body of the \key{lambda} is checked in an
  10325. environment that includes the current environment (because it is
  10326. lexically scoped) and also includes the \key{lambda}'s parameters. We
  10327. require the body's type to match the declared return type.
  10328. \begin{figure}[tbp]
  10329. \begin{lstlisting}
  10330. (define (type-check-Rlambda env)
  10331. (lambda (e)
  10332. (match e
  10333. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  10334. (define-values (new-body bodyT)
  10335. ((type-check-exp (append (map cons xs Ts) env)) body))
  10336. (define ty `(,@Ts -> ,rT))
  10337. (cond
  10338. [(equal? rT bodyT)
  10339. (values (HasType (Lambda params rT new-body) ty) ty)]
  10340. [else
  10341. (error "mismatch in return type" bodyT rT)])]
  10342. ...
  10343. )))
  10344. \end{lstlisting}
  10345. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  10346. \label{fig:type-check-Rlambda}
  10347. \end{figure}
  10348. \section{Reveal Functions and the $F_2$ language}
  10349. \label{sec:reveal-functions-r5}
  10350. To support the \code{procedure-arity} operator we need to communicate
  10351. the arity of a function to the point of closure creation. We can
  10352. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  10353. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  10354. output of this pass is the language $F_2$, whose syntax is defined in
  10355. Figure~\ref{fig:f2-syntax}.
  10356. \begin{figure}[tp]
  10357. \centering
  10358. \fbox{
  10359. \begin{minipage}{0.96\textwidth}
  10360. \[
  10361. \begin{array}{lcl}
  10362. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  10363. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10364. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  10365. \end{array}
  10366. \]
  10367. \end{minipage}
  10368. }
  10369. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  10370. (Figure~\ref{fig:Rlam-syntax}).}
  10371. \label{fig:f2-syntax}
  10372. \end{figure}
  10373. \section{Closure Conversion}
  10374. \label{sec:closure-conversion}
  10375. \index{subject}{closure conversion}
  10376. The compiling of lexically-scoped functions into top-level function
  10377. definitions is accomplished in the pass \code{convert-to-closures}
  10378. that comes after \code{reveal-functions} and before
  10379. \code{limit-functions}.
  10380. As usual, we implement the pass as a recursive function over the
  10381. AST. All of the action is in the cases for \key{Lambda} and
  10382. \key{Apply}. We transform a \key{Lambda} expression into an expression
  10383. that creates a closure, that is, a vector whose first element is a
  10384. function pointer and the rest of the elements are the free variables
  10385. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  10386. using \code{vector} so that we can distinguish closures from vectors
  10387. in Section~\ref{sec:optimize-closures} and to record the arity. In
  10388. the generated code below, the \itm{name} is a unique symbol generated
  10389. to identify the function and the \itm{arity} is the number of
  10390. parameters (the length of \itm{ps}).
  10391. \begin{lstlisting}
  10392. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  10393. |$\Rightarrow$|
  10394. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  10395. \end{lstlisting}
  10396. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  10397. create a top-level function definition for each \key{Lambda}, as
  10398. shown below.\\
  10399. \begin{minipage}{0.8\textwidth}
  10400. \begin{lstlisting}
  10401. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  10402. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  10403. ...
  10404. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  10405. |\itm{body'}|)...))
  10406. \end{lstlisting}
  10407. \end{minipage}\\
  10408. The \code{clos} parameter refers to the closure. Translate the type
  10409. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  10410. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  10411. $\itm{fvts}$ are the types of the free variables in the lambda and the
  10412. underscore \code{\_} is a dummy type that we use because it is rather
  10413. difficult to give a type to the function in the closure's
  10414. type.\footnote{To give an accurate type to a closure, we would need to
  10415. add existential types to the type checker~\citep{Minamide:1996ys}.}
  10416. The dummy type is considered to be equal to any other type during type
  10417. checking. The sequence of \key{Let} forms bind the free variables to
  10418. their values obtained from the closure.
  10419. Closure conversion turns functions into vectors, so the type
  10420. annotations in the program must also be translated. We recommend
  10421. defining a auxiliary recursive function for this purpose. Function
  10422. types should be translated as follows.
  10423. \begin{lstlisting}
  10424. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  10425. |$\Rightarrow$|
  10426. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  10427. \end{lstlisting}
  10428. The above type says that the first thing in the vector is a function
  10429. pointer. The first parameter of the function pointer is a vector (a
  10430. closure) and the rest of the parameters are the ones from the original
  10431. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  10432. the closure omits the types of the free variables because 1) those
  10433. types are not available in this context and 2) we do not need them in
  10434. the code that is generated for function application.
  10435. We transform function application into code that retrieves the
  10436. function pointer from the closure and then calls the function, passing
  10437. in the closure as the first argument. We bind $e'$ to a temporary
  10438. variable to avoid code duplication.
  10439. \begin{lstlisting}
  10440. (Apply |$e$| |\itm{es}|)
  10441. |$\Rightarrow$|
  10442. (Let |\itm{tmp}| |$e'$|
  10443. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  10444. \end{lstlisting}
  10445. There is also the question of what to do with references top-level
  10446. function definitions. To maintain a uniform translation of function
  10447. application, we turn function references into closures.
  10448. \begin{tabular}{lll}
  10449. \begin{minipage}{0.3\textwidth}
  10450. \begin{lstlisting}
  10451. (FunRefArity |$f$| |$n$|)
  10452. \end{lstlisting}
  10453. \end{minipage}
  10454. &
  10455. $\Rightarrow$
  10456. &
  10457. \begin{minipage}{0.5\textwidth}
  10458. \begin{lstlisting}
  10459. (Closure |$n$| (FunRef |$f$|) '())
  10460. \end{lstlisting}
  10461. \end{minipage}
  10462. \end{tabular} \\
  10463. %
  10464. The top-level function definitions need to be updated as well to take
  10465. an extra closure parameter.
  10466. \section{An Example Translation}
  10467. \label{sec:example-lambda}
  10468. Figure~\ref{fig:lexical-functions-example} shows the result of
  10469. \code{reveal-functions} and \code{convert-to-closures} for the example
  10470. program demonstrating lexical scoping that we discussed at the
  10471. beginning of this chapter.
  10472. \begin{figure}[tbp]
  10473. \begin{minipage}{0.8\textwidth}
  10474. % tests/lambda_test_6.rkt
  10475. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10476. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  10477. (let ([y8 4])
  10478. (lambda: ([z9 : Integer]) : Integer
  10479. (+ x7 (+ y8 z9)))))
  10480. (define (main) : Integer
  10481. (let ([g0 ((fun-ref-arity f6 1) 5)])
  10482. (let ([h1 ((fun-ref-arity f6 1) 3)])
  10483. (+ (g0 11) (h1 15)))))
  10484. \end{lstlisting}
  10485. $\Rightarrow$
  10486. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10487. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  10488. (let ([y8 4])
  10489. (closure 1 (list (fun-ref lambda2) x7 y8))))
  10490. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  10491. (let ([x7 (vector-ref fvs3 1)])
  10492. (let ([y8 (vector-ref fvs3 2)])
  10493. (+ x7 (+ y8 z9)))))
  10494. (define (main) : Integer
  10495. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  10496. ((vector-ref clos5 0) clos5 5))])
  10497. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  10498. ((vector-ref clos6 0) clos6 3))])
  10499. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  10500. \end{lstlisting}
  10501. \end{minipage}
  10502. \caption{Example of closure conversion.}
  10503. \label{fig:lexical-functions-example}
  10504. \end{figure}
  10505. \begin{exercise}\normalfont
  10506. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  10507. Create 5 new programs that use \key{lambda} functions and make use of
  10508. lexical scoping. Test your compiler on these new programs and all of
  10509. your previously created test programs.
  10510. \end{exercise}
  10511. \section{Expose Allocation}
  10512. \label{sec:expose-allocation-r5}
  10513. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  10514. that allocates and initializes a vector, similar to the translation of
  10515. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  10516. The only difference is replacing the use of
  10517. \ALLOC{\itm{len}}{\itm{type}} with
  10518. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  10519. \section{Explicate Control and \LangCLam{}}
  10520. \label{sec:explicate-r5}
  10521. The output language of \code{explicate\_control} is \LangCLam{} whose
  10522. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  10523. difference with respect to \LangCFun{} is the addition of the
  10524. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  10525. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  10526. similar to the handling of other expressions such as primitive
  10527. operators.
  10528. \begin{figure}[tp]
  10529. \fbox{
  10530. \begin{minipage}{0.96\textwidth}
  10531. \small
  10532. \[
  10533. \begin{array}{lcl}
  10534. \Exp &::= & \ldots
  10535. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  10536. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10537. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  10538. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  10539. \MID \GOTO{\itm{label}} } \\
  10540. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10541. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  10542. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  10543. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  10544. \end{array}
  10545. \]
  10546. \end{minipage}
  10547. }
  10548. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  10549. \label{fig:c4-syntax}
  10550. \end{figure}
  10551. \section{Select Instructions}
  10552. \label{sec:select-instructions-Rlambda}
  10553. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  10554. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  10555. (Section~\ref{sec:select-instructions-gc}). The only difference is
  10556. that you should place the \itm{arity} in the tag that is stored at
  10557. position $0$ of the vector. Recall that in
  10558. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  10559. was not used. We store the arity in the $5$ bits starting at position
  10560. $58$.
  10561. Compile the \code{procedure-arity} operator into a sequence of
  10562. instructions that access the tag from position $0$ of the vector and
  10563. extract the $5$-bits starting at position $58$ from the tag.
  10564. \begin{figure}[p]
  10565. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10566. \node (Rfun) at (0,2) {\large \LangFun{}};
  10567. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  10568. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  10569. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  10570. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  10571. \node (F1-3) at (6,0) {\large $F_1$};
  10572. \node (F1-4) at (3,0) {\large $F_1$};
  10573. \node (F1-5) at (0,0) {\large $F_1$};
  10574. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  10575. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10576. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10577. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10578. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10579. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10580. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10581. \path[->,bend left=15] (Rfun) edge [above] node
  10582. {\ttfamily\footnotesize shrink} (Rfun-2);
  10583. \path[->,bend left=15] (Rfun-2) edge [above] node
  10584. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10585. \path[->,bend left=15] (Rfun-3) edge [right] node
  10586. {\ttfamily\footnotesize reveal-functions} (F1-1);
  10587. \path[->,bend left=15] (F1-1) edge [below] node
  10588. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10589. \path[->,bend right=15] (F1-2) edge [above] node
  10590. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10591. \path[->,bend right=15] (F1-3) edge [above] node
  10592. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10593. \path[->,bend right=15] (F1-4) edge [above] node
  10594. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10595. \path[->,bend right=15] (F1-5) edge [right] node
  10596. {\ttfamily\footnotesize explicate-control} (C3-2);
  10597. \path[->,bend left=15] (C3-2) edge [left] node
  10598. {\ttfamily\footnotesize select-instr.} (x86-2);
  10599. \path[->,bend right=15] (x86-2) edge [left] node
  10600. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10601. \path[->,bend right=15] (x86-2-1) edge [below] node
  10602. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10603. \path[->,bend right=15] (x86-2-2) edge [left] node
  10604. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10605. \path[->,bend left=15] (x86-3) edge [above] node
  10606. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10607. \path[->,bend left=15] (x86-4) edge [right] node
  10608. {\ttfamily\footnotesize print-x86} (x86-5);
  10609. \end{tikzpicture}
  10610. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  10611. functions.}
  10612. \label{fig:Rlambda-passes}
  10613. \end{figure}
  10614. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  10615. for the compilation of \LangLam{}.
  10616. \clearpage
  10617. \section{Challenge: Optimize Closures}
  10618. \label{sec:optimize-closures}
  10619. In this chapter we compiled lexically-scoped functions into a
  10620. relatively efficient representation: flat closures. However, even this
  10621. representation comes with some overhead. For example, consider the
  10622. following program with a function \code{tail-sum} that does not have
  10623. any free variables and where all the uses of \code{tail-sum} are in
  10624. applications where we know that only \code{tail-sum} is being applied
  10625. (and not any other functions).
  10626. \begin{center}
  10627. \begin{minipage}{0.95\textwidth}
  10628. \begin{lstlisting}
  10629. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  10630. (if (eq? n 0)
  10631. r
  10632. (tail-sum (- n 1) (+ n r))))
  10633. (+ (tail-sum 5 0) 27)
  10634. \end{lstlisting}
  10635. \end{minipage}
  10636. \end{center}
  10637. As described in this chapter, we uniformly apply closure conversion to
  10638. all functions, obtaining the following output for this program.
  10639. \begin{center}
  10640. \begin{minipage}{0.95\textwidth}
  10641. \begin{lstlisting}
  10642. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  10643. (if (eq? n2 0)
  10644. r3
  10645. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  10646. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  10647. (define (main) : Integer
  10648. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  10649. ((vector-ref clos6 0) clos6 5 0)) 27))
  10650. \end{lstlisting}
  10651. \end{minipage}
  10652. \end{center}
  10653. In the previous Chapter, there would be no allocation in the program
  10654. and the calls to \code{tail-sum} would be direct calls. In contrast,
  10655. the above program allocates memory for each \code{closure} and the
  10656. calls to \code{tail-sum} are indirect. These two differences incur
  10657. considerable overhead in a program such as this one, where the
  10658. allocations and indirect calls occur inside a tight loop.
  10659. One might think that this problem is trivial to solve: can't we just
  10660. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  10661. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  10662. e'_n$)} instead of treating it like a call to a closure? We would
  10663. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  10664. %
  10665. However, this problem is not so trivial because a global function may
  10666. ``escape'' and become involved in applications that also involve
  10667. closures. Consider the following example in which the application
  10668. \code{(f 41)} needs to be compiled into a closure application, because
  10669. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  10670. function might also get bound to \code{f}.
  10671. \begin{lstlisting}
  10672. (define (add1 [x : Integer]) : Integer
  10673. (+ x 1))
  10674. (let ([y (read)])
  10675. (let ([f (if (eq? (read) 0)
  10676. add1
  10677. (lambda: ([x : Integer]) : Integer (- x y)))])
  10678. (f 41)))
  10679. \end{lstlisting}
  10680. If a global function name is used in any way other than as the
  10681. operator in a direct call, then we say that the function
  10682. \emph{escapes}. If a global function does not escape, then we do not
  10683. need to perform closure conversion on the function.
  10684. \begin{exercise}\normalfont
  10685. Implement an auxiliary function for detecting which global
  10686. functions escape. Using that function, implement an improved version
  10687. of closure conversion that does not apply closure conversion to
  10688. global functions that do not escape but instead compiles them as
  10689. regular functions. Create several new test cases that check whether
  10690. you properly detect whether global functions escape or not.
  10691. \end{exercise}
  10692. So far we have reduced the overhead of calling global functions, but
  10693. it would also be nice to reduce the overhead of calling a
  10694. \code{lambda} when we can determine at compile time which
  10695. \code{lambda} will be called. We refer to such calls as \emph{known
  10696. calls}. Consider the following example in which a \code{lambda} is
  10697. bound to \code{f} and then applied.
  10698. \begin{lstlisting}
  10699. (let ([y (read)])
  10700. (let ([f (lambda: ([x : Integer]) : Integer
  10701. (+ x y))])
  10702. (f 21)))
  10703. \end{lstlisting}
  10704. Closure conversion compiles \code{(f 21)} into an indirect call:
  10705. \begin{lstlisting}
  10706. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  10707. (let ([y2 (vector-ref fvs6 1)])
  10708. (+ x3 y2)))
  10709. (define (main) : Integer
  10710. (let ([y2 (read)])
  10711. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  10712. ((vector-ref f4 0) f4 21))))
  10713. \end{lstlisting}
  10714. but we can instead compile the application \code{(f 21)} into a direct call
  10715. to \code{lambda5}:
  10716. \begin{lstlisting}
  10717. (define (main) : Integer
  10718. (let ([y2 (read)])
  10719. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  10720. ((fun-ref lambda5) f4 21))))
  10721. \end{lstlisting}
  10722. The problem of determining which lambda will be called from a
  10723. particular application is quite challenging in general and the topic
  10724. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  10725. following exercise we recommend that you compile an application to a
  10726. direct call when the operator is a variable and the variable is
  10727. \code{let}-bound to a closure. This can be accomplished by maintaining
  10728. an environment mapping \code{let}-bound variables to function names.
  10729. Extend the environment whenever you encounter a closure on the
  10730. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  10731. to the name of the global function for the closure. This pass should
  10732. come after closure conversion.
  10733. \begin{exercise}\normalfont
  10734. Implement a compiler pass, named \code{optimize-known-calls}, that
  10735. compiles known calls into direct calls. Verify that your compiler is
  10736. successful in this regard on several example programs.
  10737. \end{exercise}
  10738. These exercises only scratches the surface of optimizing of
  10739. closures. A good next step for the interested reader is to look at the
  10740. work of \citet{Keep:2012ab}.
  10741. \section{Further Reading}
  10742. The notion of lexically scoped anonymous functions predates modern
  10743. computers by about a decade. They were invented by
  10744. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  10745. foundation for logic. Anonymous functions were included in the
  10746. LISP~\citep{McCarthy:1960dz} programming language but were initially
  10747. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  10748. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  10749. compile Scheme programs. However, environments were represented as
  10750. linked lists, so variable lookup was linear in the size of the
  10751. environment. In this chapter we represent environments using flat
  10752. closures, which were invented by
  10753. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  10754. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  10755. closures, variable lookup is constant time but the time to create a
  10756. closure is proportional to the number of its free variables. Flat
  10757. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  10758. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  10759. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10760. \chapter{Dynamic Typing}
  10761. \label{ch:Rdyn}
  10762. \index{subject}{dynamic typing}
  10763. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  10764. typed language that is a subset of Racket. This is in contrast to the
  10765. previous chapters, which have studied the compilation of Typed
  10766. Racket. In dynamically typed languages such as \LangDyn{}, a given
  10767. expression may produce a value of a different type each time it is
  10768. executed. Consider the following example with a conditional \code{if}
  10769. expression that may return a Boolean or an integer depending on the
  10770. input to the program.
  10771. % part of dynamic_test_25.rkt
  10772. \begin{lstlisting}
  10773. (not (if (eq? (read) 1) #f 0))
  10774. \end{lstlisting}
  10775. Languages that allow expressions to produce different kinds of values
  10776. are called \emph{polymorphic}, a word composed of the Greek roots
  10777. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  10778. are several kinds of polymorphism in programming languages, such as
  10779. subtype polymorphism and parametric
  10780. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  10781. study in this chapter does not have a special name but it is the kind
  10782. that arises in dynamically typed languages.
  10783. Another characteristic of dynamically typed languages is that
  10784. primitive operations, such as \code{not}, are often defined to operate
  10785. on many different types of values. In fact, in Racket, the \code{not}
  10786. operator produces a result for any kind of value: given \code{\#f} it
  10787. returns \code{\#t} and given anything else it returns \code{\#f}.
  10788. Furthermore, even when primitive operations restrict their inputs to
  10789. values of a certain type, this restriction is enforced at runtime
  10790. instead of during compilation. For example, the following vector
  10791. reference results in a run-time contract violation because the index
  10792. must be in integer, not a Boolean such as \code{\#t}.
  10793. \begin{lstlisting}
  10794. (vector-ref (vector 42) #t)
  10795. \end{lstlisting}
  10796. \begin{figure}[tp]
  10797. \centering
  10798. \fbox{
  10799. \begin{minipage}{0.97\textwidth}
  10800. \[
  10801. \begin{array}{rcl}
  10802. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  10803. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  10804. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  10805. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  10806. &\MID& \key{\#t} \MID \key{\#f}
  10807. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  10808. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  10809. \MID \CUNIOP{\key{not}}{\Exp} \\
  10810. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  10811. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  10812. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  10813. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  10814. &\MID& \LP\Exp \; \Exp\ldots\RP
  10815. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  10816. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  10817. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  10818. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  10819. \LangDynM{} &::=& \Def\ldots\; \Exp
  10820. \end{array}
  10821. \]
  10822. \end{minipage}
  10823. }
  10824. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  10825. \label{fig:r7-concrete-syntax}
  10826. \end{figure}
  10827. \begin{figure}[tp]
  10828. \centering
  10829. \fbox{
  10830. \begin{minipage}{0.96\textwidth}
  10831. \small
  10832. \[
  10833. \begin{array}{lcl}
  10834. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  10835. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  10836. &\MID& \BOOL{\itm{bool}}
  10837. \MID \IF{\Exp}{\Exp}{\Exp} \\
  10838. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  10839. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  10840. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  10841. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  10842. \end{array}
  10843. \]
  10844. \end{minipage}
  10845. }
  10846. \caption{The abstract syntax of \LangDyn{}.}
  10847. \label{fig:r7-syntax}
  10848. \end{figure}
  10849. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  10850. defined in Figures~\ref{fig:r7-concrete-syntax} and
  10851. \ref{fig:r7-syntax}.
  10852. %
  10853. There is no type checker for \LangDyn{} because it is not a statically
  10854. typed language (it's dynamically typed!).
  10855. The definitional interpreter for \LangDyn{} is presented in
  10856. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  10857. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  10858. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  10859. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  10860. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  10861. value} that combines an underlying value with a tag that identifies
  10862. what kind of value it is. We define the following struct
  10863. to represented tagged values.
  10864. \begin{lstlisting}
  10865. (struct Tagged (value tag) #:transparent)
  10866. \end{lstlisting}
  10867. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  10868. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  10869. but don't always capture all the information that a type does. For
  10870. example, a vector of type \code{(Vector Any Any)} is tagged with
  10871. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  10872. is tagged with \code{Procedure}.
  10873. Next consider the match case for \code{vector-ref}. The
  10874. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  10875. is used to ensure that the first argument is a vector and the second
  10876. is an integer. If they are not, a \code{trapped-error} is raised.
  10877. Recall from Section~\ref{sec:interp_Rint} that when a definition
  10878. interpreter raises a \code{trapped-error} error, the compiled code
  10879. must also signal an error by exiting with return code \code{255}. A
  10880. \code{trapped-error} is also raised if the index is not less than
  10881. length of the vector.
  10882. \begin{figure}[tbp]
  10883. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10884. (define ((interp-Rdyn-exp env) ast)
  10885. (define recur (interp-Rdyn-exp env))
  10886. (match ast
  10887. [(Var x) (lookup x env)]
  10888. [(Int n) (Tagged n 'Integer)]
  10889. [(Bool b) (Tagged b 'Boolean)]
  10890. [(Lambda xs rt body)
  10891. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  10892. [(Prim 'vector es)
  10893. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  10894. [(Prim 'vector-ref (list e1 e2))
  10895. (define vec (recur e1)) (define i (recur e2))
  10896. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  10897. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  10898. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  10899. (vector-ref (Tagged-value vec) (Tagged-value i))]
  10900. [(Prim 'vector-set! (list e1 e2 e3))
  10901. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  10902. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  10903. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  10904. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  10905. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  10906. (Tagged (void) 'Void)]
  10907. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  10908. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  10909. [(Prim 'or (list e1 e2))
  10910. (define v1 (recur e1))
  10911. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  10912. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  10913. [(Prim op (list e1))
  10914. #:when (set-member? type-predicates op)
  10915. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  10916. [(Prim op es)
  10917. (define args (map recur es))
  10918. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  10919. (unless (for/or ([expected-tags (op-tags op)])
  10920. (equal? expected-tags tags))
  10921. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  10922. (tag-value
  10923. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  10924. [(If q t f)
  10925. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  10926. [(Apply f es)
  10927. (define new-f (recur f)) (define args (map recur es))
  10928. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  10929. (match f-val
  10930. [`(function ,xs ,body ,lam-env)
  10931. (unless (eq? (length xs) (length args))
  10932. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  10933. (define new-env (append (map cons xs args) lam-env))
  10934. ((interp-Rdyn-exp new-env) body)]
  10935. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  10936. \end{lstlisting}
  10937. \caption{Interpreter for the \LangDyn{} language.}
  10938. \label{fig:interp-Rdyn}
  10939. \end{figure}
  10940. \begin{figure}[tbp]
  10941. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10942. (define (interp-op op)
  10943. (match op
  10944. ['+ fx+]
  10945. ['- fx-]
  10946. ['read read-fixnum]
  10947. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  10948. ['< (lambda (v1 v2)
  10949. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  10950. ['<= (lambda (v1 v2)
  10951. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  10952. ['> (lambda (v1 v2)
  10953. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  10954. ['>= (lambda (v1 v2)
  10955. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  10956. ['boolean? boolean?]
  10957. ['integer? fixnum?]
  10958. ['void? void?]
  10959. ['vector? vector?]
  10960. ['vector-length vector-length]
  10961. ['procedure? (match-lambda
  10962. [`(functions ,xs ,body ,env) #t] [else #f])]
  10963. [else (error 'interp-op "unknown operator" op)]))
  10964. (define (op-tags op)
  10965. (match op
  10966. ['+ '((Integer Integer))]
  10967. ['- '((Integer Integer) (Integer))]
  10968. ['read '(())]
  10969. ['not '((Boolean))]
  10970. ['< '((Integer Integer))]
  10971. ['<= '((Integer Integer))]
  10972. ['> '((Integer Integer))]
  10973. ['>= '((Integer Integer))]
  10974. ['vector-length '((Vector))]))
  10975. (define type-predicates
  10976. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  10977. (define (tag-value v)
  10978. (cond [(boolean? v) (Tagged v 'Boolean)]
  10979. [(fixnum? v) (Tagged v 'Integer)]
  10980. [(procedure? v) (Tagged v 'Procedure)]
  10981. [(vector? v) (Tagged v 'Vector)]
  10982. [(void? v) (Tagged v 'Void)]
  10983. [else (error 'tag-value "unidentified value ~a" v)]))
  10984. (define (check-tag val expected ast)
  10985. (define tag (Tagged-tag val))
  10986. (unless (eq? tag expected)
  10987. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  10988. \end{lstlisting}
  10989. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  10990. \label{fig:interp-Rdyn-aux}
  10991. \end{figure}
  10992. \clearpage
  10993. \section{Representation of Tagged Values}
  10994. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  10995. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  10996. values at the bit level. Because almost every operation in \LangDyn{}
  10997. involves manipulating tagged values, the representation must be
  10998. efficient. Recall that all of our values are 64 bits. We shall steal
  10999. the 3 right-most bits to encode the tag. We use $001$ to identify
  11000. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  11001. and $101$ for the void value. We define the following auxiliary
  11002. function for mapping types to tag codes.
  11003. \begin{align*}
  11004. \itm{tagof}(\key{Integer}) &= 001 \\
  11005. \itm{tagof}(\key{Boolean}) &= 100 \\
  11006. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  11007. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  11008. \itm{tagof}(\key{Void}) &= 101
  11009. \end{align*}
  11010. This stealing of 3 bits comes at some price: our integers are reduced
  11011. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  11012. affect vectors and procedures because those values are addresses, and
  11013. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  11014. they are always $000$. Thus, we do not lose information by overwriting
  11015. the rightmost 3 bits with the tag and we can simply zero-out the tag
  11016. to recover the original address.
  11017. To make tagged values into first-class entities, we can give them a
  11018. type, called \code{Any}, and define operations such as \code{Inject}
  11019. and \code{Project} for creating and using them, yielding the \LangAny{}
  11020. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  11021. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  11022. in greater detail.
  11023. \section{The \LangAny{} Language}
  11024. \label{sec:Rany-lang}
  11025. \begin{figure}[tp]
  11026. \centering
  11027. \fbox{
  11028. \begin{minipage}{0.96\textwidth}
  11029. \small
  11030. \[
  11031. \begin{array}{lcl}
  11032. \Type &::= & \ldots \MID \key{Any} \\
  11033. \itm{op} &::= & \ldots \MID \code{any-vector-length}
  11034. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  11035. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  11036. \MID \code{procedure?} \MID \code{void?} \\
  11037. \Exp &::=& \ldots
  11038. \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  11039. &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  11040. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  11041. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11042. \end{array}
  11043. \]
  11044. \end{minipage}
  11045. }
  11046. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  11047. \label{fig:Rany-syntax}
  11048. \end{figure}
  11049. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  11050. (The concrete syntax of \LangAny{} is in the Appendix,
  11051. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  11052. converts the value produced by expression $e$ of type $T$ into a
  11053. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  11054. produced by expression $e$ into a value of type $T$ or else halts the
  11055. program if the type tag is not equivalent to $T$.
  11056. %
  11057. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  11058. restricted to a flat type $\FType$, which simplifies the
  11059. implementation and corresponds with what is needed for compiling \LangDyn{}.
  11060. The \code{any-vector} operators adapt the vector operations so that
  11061. they can be applied to a value of type \code{Any}. They also
  11062. generalize the vector operations in that the index is not restricted
  11063. to be a literal integer in the grammar but is allowed to be any
  11064. expression.
  11065. The type predicates such as \key{boolean?} expect their argument to
  11066. produce a tagged value; they return \key{\#t} if the tag corresponds
  11067. to the predicate and they return \key{\#f} otherwise.
  11068. The type checker for \LangAny{} is shown in
  11069. Figures~\ref{fig:type-check-Rany-part-1} and
  11070. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  11071. Figure~\ref{fig:type-check-Rany-aux}.
  11072. %
  11073. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  11074. auxiliary functions \code{apply-inject} and \code{apply-project} are
  11075. in Figure~\ref{fig:apply-project}.
  11076. \begin{figure}[btp]
  11077. \begin{lstlisting}[basicstyle=\ttfamily\small]
  11078. (define type-check-Rany_class
  11079. (class type-check-Rlambda_class
  11080. (super-new)
  11081. (inherit check-type-equal?)
  11082. (define/override (type-check-exp env)
  11083. (lambda (e)
  11084. (define recur (type-check-exp env))
  11085. (match e
  11086. [(Inject e1 ty)
  11087. (unless (flat-ty? ty)
  11088. (error 'type-check "may only inject from flat type, not ~a" ty))
  11089. (define-values (new-e1 e-ty) (recur e1))
  11090. (check-type-equal? e-ty ty e)
  11091. (values (Inject new-e1 ty) 'Any)]
  11092. [(Project e1 ty)
  11093. (unless (flat-ty? ty)
  11094. (error 'type-check "may only project to flat type, not ~a" ty))
  11095. (define-values (new-e1 e-ty) (recur e1))
  11096. (check-type-equal? e-ty 'Any e)
  11097. (values (Project new-e1 ty) ty)]
  11098. [(Prim 'any-vector-length (list e1))
  11099. (define-values (e1^ t1) (recur e1))
  11100. (check-type-equal? t1 'Any e)
  11101. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  11102. [(Prim 'any-vector-ref (list e1 e2))
  11103. (define-values (e1^ t1) (recur e1))
  11104. (define-values (e2^ t2) (recur e2))
  11105. (check-type-equal? t1 'Any e)
  11106. (check-type-equal? t2 'Integer e)
  11107. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  11108. [(Prim 'any-vector-set! (list e1 e2 e3))
  11109. (define-values (e1^ t1) (recur e1))
  11110. (define-values (e2^ t2) (recur e2))
  11111. (define-values (e3^ t3) (recur e3))
  11112. (check-type-equal? t1 'Any e)
  11113. (check-type-equal? t2 'Integer e)
  11114. (check-type-equal? t3 'Any e)
  11115. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  11116. \end{lstlisting}
  11117. \caption{Type checker for the \LangAny{} language, part 1.}
  11118. \label{fig:type-check-Rany-part-1}
  11119. \end{figure}
  11120. \begin{figure}[btp]
  11121. \begin{lstlisting}[basicstyle=\ttfamily\small]
  11122. [(ValueOf e ty)
  11123. (define-values (new-e e-ty) (recur e))
  11124. (values (ValueOf new-e ty) ty)]
  11125. [(Prim pred (list e1))
  11126. #:when (set-member? (type-predicates) pred)
  11127. (define-values (new-e1 e-ty) (recur e1))
  11128. (check-type-equal? e-ty 'Any e)
  11129. (values (Prim pred (list new-e1)) 'Boolean)]
  11130. [(If cnd thn els)
  11131. (define-values (cnd^ Tc) (recur cnd))
  11132. (define-values (thn^ Tt) (recur thn))
  11133. (define-values (els^ Te) (recur els))
  11134. (check-type-equal? Tc 'Boolean cnd)
  11135. (check-type-equal? Tt Te e)
  11136. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  11137. [(Exit) (values (Exit) '_)]
  11138. [(Prim 'eq? (list arg1 arg2))
  11139. (define-values (e1 t1) (recur arg1))
  11140. (define-values (e2 t2) (recur arg2))
  11141. (match* (t1 t2)
  11142. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11143. [(other wise) (check-type-equal? t1 t2 e)])
  11144. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11145. [else ((super type-check-exp env) e)])))
  11146. ))
  11147. \end{lstlisting}
  11148. \caption{Type checker for the \LangAny{} language, part 2.}
  11149. \label{fig:type-check-Rany-part-2}
  11150. \end{figure}
  11151. \begin{figure}[tbp]
  11152. \begin{lstlisting}
  11153. (define/override (operator-types)
  11154. (append
  11155. '((integer? . ((Any) . Boolean))
  11156. (vector? . ((Any) . Boolean))
  11157. (procedure? . ((Any) . Boolean))
  11158. (void? . ((Any) . Boolean))
  11159. (tag-of-any . ((Any) . Integer))
  11160. (make-any . ((_ Integer) . Any))
  11161. )
  11162. (super operator-types)))
  11163. (define/public (type-predicates)
  11164. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  11165. (define/public (combine-types t1 t2)
  11166. (match (list t1 t2)
  11167. [(list '_ t2) t2]
  11168. [(list t1 '_) t1]
  11169. [(list `(Vector ,ts1 ...)
  11170. `(Vector ,ts2 ...))
  11171. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  11172. (combine-types t1 t2)))]
  11173. [(list `(,ts1 ... -> ,rt1)
  11174. `(,ts2 ... -> ,rt2))
  11175. `(,@(for/list ([t1 ts1] [t2 ts2])
  11176. (combine-types t1 t2))
  11177. -> ,(combine-types rt1 rt2))]
  11178. [else t1]))
  11179. (define/public (flat-ty? ty)
  11180. (match ty
  11181. [(or `Integer `Boolean '_ `Void) #t]
  11182. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  11183. [`(,ts ... -> ,rt)
  11184. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  11185. [else #f]))
  11186. \end{lstlisting}
  11187. \caption{Auxiliary methods for type checking \LangAny{}.}
  11188. \label{fig:type-check-Rany-aux}
  11189. \end{figure}
  11190. \begin{figure}[btp]
  11191. \begin{lstlisting}
  11192. (define interp-Rany_class
  11193. (class interp-Rlambda_class
  11194. (super-new)
  11195. (define/override (interp-op op)
  11196. (match op
  11197. ['boolean? (match-lambda
  11198. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  11199. [else #f])]
  11200. ['integer? (match-lambda
  11201. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  11202. [else #f])]
  11203. ['vector? (match-lambda
  11204. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  11205. [else #f])]
  11206. ['procedure? (match-lambda
  11207. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  11208. [else #f])]
  11209. ['eq? (match-lambda*
  11210. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  11211. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  11212. [ls (apply (super interp-op op) ls)])]
  11213. ['any-vector-ref (lambda (v i)
  11214. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  11215. ['any-vector-set! (lambda (v i a)
  11216. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  11217. ['any-vector-length (lambda (v)
  11218. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  11219. [else (super interp-op op)]))
  11220. (define/override ((interp-exp env) e)
  11221. (define recur (interp-exp env))
  11222. (match e
  11223. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  11224. [(Project e ty2) (apply-project (recur e) ty2)]
  11225. [else ((super interp-exp env) e)]))
  11226. ))
  11227. (define (interp-Rany p)
  11228. (send (new interp-Rany_class) interp-program p))
  11229. \end{lstlisting}
  11230. \caption{Interpreter for \LangAny{}.}
  11231. \label{fig:interp-Rany}
  11232. \end{figure}
  11233. \begin{figure}[tbp]
  11234. \begin{lstlisting}
  11235. (define/public (apply-inject v tg) (Tagged v tg))
  11236. (define/public (apply-project v ty2)
  11237. (define tag2 (any-tag ty2))
  11238. (match v
  11239. [(Tagged v1 tag1)
  11240. (cond
  11241. [(eq? tag1 tag2)
  11242. (match ty2
  11243. [`(Vector ,ts ...)
  11244. (define l1 ((interp-op 'vector-length) v1))
  11245. (cond
  11246. [(eq? l1 (length ts)) v1]
  11247. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  11248. l1 (length ts))])]
  11249. [`(,ts ... -> ,rt)
  11250. (match v1
  11251. [`(function ,xs ,body ,env)
  11252. (cond [(eq? (length xs) (length ts)) v1]
  11253. [else
  11254. (error 'apply-project "arity mismatch ~a != ~a"
  11255. (length xs) (length ts))])]
  11256. [else (error 'apply-project "expected function not ~a" v1)])]
  11257. [else v1])]
  11258. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  11259. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  11260. \end{lstlisting}
  11261. \caption{Auxiliary functions for injection and projection.}
  11262. \label{fig:apply-project}
  11263. \end{figure}
  11264. \clearpage
  11265. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  11266. \label{sec:compile-r7}
  11267. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  11268. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  11269. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  11270. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  11271. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  11272. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  11273. the Boolean \code{\#t}, which must be injected to produce an
  11274. expression of type \key{Any}.
  11275. %
  11276. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  11277. addition, is representative of compilation for many primitive
  11278. operations: the arguments have type \key{Any} and must be projected to
  11279. \key{Integer} before the addition can be performed.
  11280. The compilation of \key{lambda} (third row of
  11281. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  11282. produce type annotations: we simply use \key{Any}.
  11283. %
  11284. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  11285. has to account for some differences in behavior between \LangDyn{} and
  11286. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  11287. kind of values can be used in various places. For example, the
  11288. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  11289. the arguments need not be of the same type (in that case the
  11290. result is \code{\#f}).
  11291. \begin{figure}[btp]
  11292. \centering
  11293. \begin{tabular}{|lll|} \hline
  11294. \begin{minipage}{0.27\textwidth}
  11295. \begin{lstlisting}
  11296. #t
  11297. \end{lstlisting}
  11298. \end{minipage}
  11299. &
  11300. $\Rightarrow$
  11301. &
  11302. \begin{minipage}{0.65\textwidth}
  11303. \begin{lstlisting}
  11304. (inject #t Boolean)
  11305. \end{lstlisting}
  11306. \end{minipage}
  11307. \\[2ex]\hline
  11308. \begin{minipage}{0.27\textwidth}
  11309. \begin{lstlisting}
  11310. (+ |$e_1$| |$e_2$|)
  11311. \end{lstlisting}
  11312. \end{minipage}
  11313. &
  11314. $\Rightarrow$
  11315. &
  11316. \begin{minipage}{0.65\textwidth}
  11317. \begin{lstlisting}
  11318. (inject
  11319. (+ (project |$e'_1$| Integer)
  11320. (project |$e'_2$| Integer))
  11321. Integer)
  11322. \end{lstlisting}
  11323. \end{minipage}
  11324. \\[2ex]\hline
  11325. \begin{minipage}{0.27\textwidth}
  11326. \begin{lstlisting}
  11327. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  11328. \end{lstlisting}
  11329. \end{minipage}
  11330. &
  11331. $\Rightarrow$
  11332. &
  11333. \begin{minipage}{0.65\textwidth}
  11334. \begin{lstlisting}
  11335. (inject
  11336. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  11337. (Any|$\ldots$|Any -> Any))
  11338. \end{lstlisting}
  11339. \end{minipage}
  11340. \\[2ex]\hline
  11341. \begin{minipage}{0.27\textwidth}
  11342. \begin{lstlisting}
  11343. (|$e_0$| |$e_1 \ldots e_n$|)
  11344. \end{lstlisting}
  11345. \end{minipage}
  11346. &
  11347. $\Rightarrow$
  11348. &
  11349. \begin{minipage}{0.65\textwidth}
  11350. \begin{lstlisting}
  11351. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  11352. \end{lstlisting}
  11353. \end{minipage}
  11354. \\[2ex]\hline
  11355. \begin{minipage}{0.27\textwidth}
  11356. \begin{lstlisting}
  11357. (vector-ref |$e_1$| |$e_2$|)
  11358. \end{lstlisting}
  11359. \end{minipage}
  11360. &
  11361. $\Rightarrow$
  11362. &
  11363. \begin{minipage}{0.65\textwidth}
  11364. \begin{lstlisting}
  11365. (any-vector-ref |$e_1'$| |$e_2'$|)
  11366. \end{lstlisting}
  11367. \end{minipage}
  11368. \\[2ex]\hline
  11369. \begin{minipage}{0.27\textwidth}
  11370. \begin{lstlisting}
  11371. (if |$e_1$| |$e_2$| |$e_3$|)
  11372. \end{lstlisting}
  11373. \end{minipage}
  11374. &
  11375. $\Rightarrow$
  11376. &
  11377. \begin{minipage}{0.65\textwidth}
  11378. \begin{lstlisting}
  11379. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  11380. \end{lstlisting}
  11381. \end{minipage}
  11382. \\[2ex]\hline
  11383. \begin{minipage}{0.27\textwidth}
  11384. \begin{lstlisting}
  11385. (eq? |$e_1$| |$e_2$|)
  11386. \end{lstlisting}
  11387. \end{minipage}
  11388. &
  11389. $\Rightarrow$
  11390. &
  11391. \begin{minipage}{0.65\textwidth}
  11392. \begin{lstlisting}
  11393. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  11394. \end{lstlisting}
  11395. \end{minipage}
  11396. \\[2ex]\hline
  11397. \begin{minipage}{0.27\textwidth}
  11398. \begin{lstlisting}
  11399. (not |$e_1$|)
  11400. \end{lstlisting}
  11401. \end{minipage}
  11402. &
  11403. $\Rightarrow$
  11404. &
  11405. \begin{minipage}{0.65\textwidth}
  11406. \begin{lstlisting}
  11407. (if (eq? |$e'_1$| (inject #f Boolean))
  11408. (inject #t Boolean) (inject #f Boolean))
  11409. \end{lstlisting}
  11410. \end{minipage}
  11411. \\[2ex]\hline
  11412. \end{tabular}
  11413. \caption{Cast Insertion}
  11414. \label{fig:compile-r7-Rany}
  11415. \end{figure}
  11416. \section{Reveal Casts}
  11417. \label{sec:reveal-casts-Rany}
  11418. % TODO: define R'_6
  11419. In the \code{reveal-casts} pass we recommend compiling \code{project}
  11420. into an \code{if} expression that checks whether the value's tag
  11421. matches the target type; if it does, the value is converted to a value
  11422. of the target type by removing the tag; if it does not, the program
  11423. exits. To perform these actions we need a new primitive operation,
  11424. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  11425. The \code{tag-of-any} operation retrieves the type tag from a tagged
  11426. value of type \code{Any}. The \code{ValueOf} form retrieves the
  11427. underlying value from a tagged value. The \code{ValueOf} form
  11428. includes the type for the underlying value which is used by the type
  11429. checker. Finally, the \code{Exit} form ends the execution of the
  11430. program.
  11431. If the target type of the projection is \code{Boolean} or
  11432. \code{Integer}, then \code{Project} can be translated as follows.
  11433. \begin{center}
  11434. \begin{minipage}{1.0\textwidth}
  11435. \begin{lstlisting}
  11436. (Project |$e$| |$\FType$|)
  11437. |$\Rightarrow$|
  11438. (Let |$\itm{tmp}$| |$e'$|
  11439. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  11440. (Int |$\itm{tagof}(\FType)$|)))
  11441. (ValueOf |$\itm{tmp}$| |$\FType$|)
  11442. (Exit)))
  11443. \end{lstlisting}
  11444. \end{minipage}
  11445. \end{center}
  11446. If the target type of the projection is a vector or function type,
  11447. then there is a bit more work to do. For vectors, check that the
  11448. length of the vector type matches the length of the vector (using the
  11449. \code{vector-length} primitive). For functions, check that the number
  11450. of parameters in the function type matches the function's arity (using
  11451. \code{procedure-arity}).
  11452. Regarding \code{inject}, we recommend compiling it to a slightly
  11453. lower-level primitive operation named \code{make-any}. This operation
  11454. takes a tag instead of a type.
  11455. \begin{center}
  11456. \begin{minipage}{1.0\textwidth}
  11457. \begin{lstlisting}
  11458. (Inject |$e$| |$\FType$|)
  11459. |$\Rightarrow$|
  11460. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  11461. \end{lstlisting}
  11462. \end{minipage}
  11463. \end{center}
  11464. The type predicates (\code{boolean?}, etc.) can be translated into
  11465. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  11466. translation of \code{Project}.
  11467. The \code{any-vector-ref} and \code{any-vector-set!} operations
  11468. combine the projection action with the vector operation. Also, the
  11469. read and write operations allow arbitrary expressions for the index so
  11470. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  11471. cannot guarantee that the index is within bounds. Thus, we insert code
  11472. to perform bounds checking at runtime. The translation for
  11473. \code{any-vector-ref} is as follows and the other two operations are
  11474. translated in a similar way.
  11475. \begin{lstlisting}
  11476. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  11477. |$\Rightarrow$|
  11478. (Let |$v$| |$e'_1$|
  11479. (Let |$i$| |$e'_2$|
  11480. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  11481. (If (Prim '< (list (Var |$i$|)
  11482. (Prim 'any-vector-length (list (Var |$v$|)))))
  11483. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  11484. (Exit))))
  11485. \end{lstlisting}
  11486. \section{Remove Complex Operands}
  11487. \label{sec:rco-Rany}
  11488. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  11489. The subexpression of \code{ValueOf} must be atomic.
  11490. \section{Explicate Control and \LangCAny{}}
  11491. \label{sec:explicate-Rany}
  11492. The output of \code{explicate\_control} is the \LangCAny{} language whose
  11493. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  11494. form that we added to \LangAny{} remains an expression and the \code{Exit}
  11495. expression becomes a $\Tail$. Also, note that the index argument of
  11496. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  11497. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  11498. \begin{figure}[tp]
  11499. \fbox{
  11500. \begin{minipage}{0.96\textwidth}
  11501. \small
  11502. \[
  11503. \begin{array}{lcl}
  11504. \Exp &::= & \ldots
  11505. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  11506. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  11507. &\MID& \VALUEOF{\Exp}{\FType} \\
  11508. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  11509. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  11510. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  11511. \MID \GOTO{\itm{label}} } \\
  11512. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  11513. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  11514. \MID \LP\key{Exit}\RP \\
  11515. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  11516. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  11517. \end{array}
  11518. \]
  11519. \end{minipage}
  11520. }
  11521. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  11522. \label{fig:c5-syntax}
  11523. \end{figure}
  11524. \section{Select Instructions}
  11525. \label{sec:select-Rany}
  11526. In the \code{select-instructions} pass we translate the primitive
  11527. operations on the \code{Any} type to x86 instructions that involve
  11528. manipulating the 3 tag bits of the tagged value.
  11529. \paragraph{Make-any}
  11530. We recommend compiling the \key{make-any} primitive as follows if the
  11531. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  11532. shifts the destination to the left by the number of bits specified its
  11533. source argument (in this case $3$, the length of the tag) and it
  11534. preserves the sign of the integer. We use the \key{orq} instruction to
  11535. combine the tag and the value to form the tagged value. \\
  11536. \begin{lstlisting}
  11537. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  11538. |$\Rightarrow$|
  11539. movq |$e'$|, |\itm{lhs'}|
  11540. salq $3, |\itm{lhs'}|
  11541. orq $|$\itm{tag}$|, |\itm{lhs'}|
  11542. \end{lstlisting}
  11543. The instruction selection for vectors and procedures is different
  11544. because their is no need to shift them to the left. The rightmost 3
  11545. bits are already zeros as described at the beginning of this
  11546. chapter. So we just combine the value and the tag using \key{orq}. \\
  11547. \begin{lstlisting}
  11548. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  11549. |$\Rightarrow$|
  11550. movq |$e'$|, |\itm{lhs'}|
  11551. orq $|$\itm{tag}$|, |\itm{lhs'}|
  11552. \end{lstlisting}
  11553. \paragraph{Tag-of-any}
  11554. Recall that the \code{tag-of-any} operation extracts the type tag from
  11555. a value of type \code{Any}. The type tag is the bottom three bits, so
  11556. we obtain the tag by taking the bitwise-and of the value with $111$
  11557. ($7$ in decimal).
  11558. \begin{lstlisting}
  11559. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  11560. |$\Rightarrow$|
  11561. movq |$e'$|, |\itm{lhs'}|
  11562. andq $7, |\itm{lhs'}|
  11563. \end{lstlisting}
  11564. \paragraph{ValueOf}
  11565. Like \key{make-any}, the instructions for \key{ValueOf} are different
  11566. depending on whether the type $T$ is a pointer (vector or procedure)
  11567. or not (Integer or Boolean). The following shows the instruction
  11568. selection for Integer and Boolean. We produce an untagged value by
  11569. shifting it to the right by 3 bits.
  11570. \begin{lstlisting}
  11571. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  11572. |$\Rightarrow$|
  11573. movq |$e'$|, |\itm{lhs'}|
  11574. sarq $3, |\itm{lhs'}|
  11575. \end{lstlisting}
  11576. %
  11577. In the case for vectors and procedures, there is no need to
  11578. shift. Instead we just need to zero-out the rightmost 3 bits. We
  11579. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  11580. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  11581. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  11582. then apply \code{andq} with the tagged value to get the desired
  11583. result. \\
  11584. \begin{lstlisting}
  11585. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  11586. |$\Rightarrow$|
  11587. movq $|$-8$|, |\itm{lhs'}|
  11588. andq |$e'$|, |\itm{lhs'}|
  11589. \end{lstlisting}
  11590. %% \paragraph{Type Predicates} We leave it to the reader to
  11591. %% devise a sequence of instructions to implement the type predicates
  11592. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  11593. \paragraph{Any-vector-length}
  11594. \begin{lstlisting}
  11595. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  11596. |$\Longrightarrow$|
  11597. movq |$\neg 111$|, %r11
  11598. andq |$a_1'$|, %r11
  11599. movq 0(%r11), %r11
  11600. andq $126, %r11
  11601. sarq $1, %r11
  11602. movq %r11, |$\itm{lhs'}$|
  11603. \end{lstlisting}
  11604. \paragraph{Any-vector-ref}
  11605. The index may be an arbitrary atom so instead of computing the offset
  11606. at compile time, instructions need to be generated to compute the
  11607. offset at runtime as follows. Note the use of the new instruction
  11608. \code{imulq}.
  11609. \begin{center}
  11610. \begin{minipage}{0.96\textwidth}
  11611. \begin{lstlisting}
  11612. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  11613. |$\Longrightarrow$|
  11614. movq |$\neg 111$|, %r11
  11615. andq |$a_1'$|, %r11
  11616. movq |$a_2'$|, %rax
  11617. addq $1, %rax
  11618. imulq $8, %rax
  11619. addq %rax, %r11
  11620. movq 0(%r11) |$\itm{lhs'}$|
  11621. \end{lstlisting}
  11622. \end{minipage}
  11623. \end{center}
  11624. \paragraph{Any-vector-set!}
  11625. The code generation for \code{any-vector-set!} is similar to the other
  11626. \code{any-vector} operations.
  11627. \section{Register Allocation for \LangAny{}}
  11628. \label{sec:register-allocation-Rany}
  11629. \index{subject}{register allocation}
  11630. There is an interesting interaction between tagged values and garbage
  11631. collection that has an impact on register allocation. A variable of
  11632. type \code{Any} might refer to a vector and therefore it might be a
  11633. root that needs to be inspected and copied during garbage
  11634. collection. Thus, we need to treat variables of type \code{Any} in a
  11635. similar way to variables of type \code{Vector} for purposes of
  11636. register allocation. In particular,
  11637. \begin{itemize}
  11638. \item If a variable of type \code{Any} is live during a function call,
  11639. then it must be spilled. This can be accomplished by changing
  11640. \code{build-interference} to mark all variables of type \code{Any}
  11641. that are live after a \code{callq} as interfering with all the
  11642. registers.
  11643. \item If a variable of type \code{Any} is spilled, it must be spilled
  11644. to the root stack instead of the normal procedure call stack.
  11645. \end{itemize}
  11646. Another concern regarding the root stack is that the garbage collector
  11647. needs to differentiate between (1) plain old pointers to tuples, (2) a
  11648. tagged value that points to a tuple, and (3) a tagged value that is
  11649. not a tuple. We enable this differentiation by choosing not to use the
  11650. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  11651. reserved for identifying plain old pointers to tuples. That way, if
  11652. one of the first three bits is set, then we have a tagged value and
  11653. inspecting the tag can differentiation between vectors ($010$) and the
  11654. other kinds of values.
  11655. \begin{exercise}\normalfont
  11656. Expand your compiler to handle \LangAny{} as discussed in the last few
  11657. sections. Create 5 new programs that use the \code{Any} type and the
  11658. new operations (\code{inject}, \code{project}, \code{boolean?},
  11659. etc.). Test your compiler on these new programs and all of your
  11660. previously created test programs.
  11661. \end{exercise}
  11662. \begin{exercise}\normalfont
  11663. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  11664. Create tests for \LangDyn{} by adapting ten of your previous test programs
  11665. by removing type annotations. Add 5 more tests programs that
  11666. specifically rely on the language being dynamically typed. That is,
  11667. they should not be legal programs in a statically typed language, but
  11668. nevertheless, they should be valid \LangDyn{} programs that run to
  11669. completion without error.
  11670. \end{exercise}
  11671. \begin{figure}[p]
  11672. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11673. \node (Rfun) at (0,4) {\large \LangDyn{}};
  11674. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  11675. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  11676. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  11677. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  11678. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  11679. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  11680. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  11681. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  11682. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  11683. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  11684. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  11685. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11686. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11687. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11688. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11689. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11690. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11691. \path[->,bend left=15] (Rfun) edge [above] node
  11692. {\ttfamily\footnotesize shrink} (Rfun-2);
  11693. \path[->,bend left=15] (Rfun-2) edge [above] node
  11694. {\ttfamily\footnotesize uniquify} (Rfun-3);
  11695. \path[->,bend left=15] (Rfun-3) edge [above] node
  11696. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  11697. \path[->,bend right=15] (Rfun-4) edge [left] node
  11698. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  11699. \path[->,bend left=15] (Rfun-5) edge [above] node
  11700. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  11701. \path[->,bend left=15] (Rfun-6) edge [left] node
  11702. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  11703. \path[->,bend left=15] (Rfun-7) edge [below] node
  11704. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11705. \path[->,bend right=15] (F1-2) edge [above] node
  11706. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11707. \path[->,bend right=15] (F1-3) edge [above] node
  11708. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11709. \path[->,bend right=15] (F1-4) edge [above] node
  11710. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11711. \path[->,bend right=15] (F1-5) edge [right] node
  11712. {\ttfamily\footnotesize explicate-control} (C3-2);
  11713. \path[->,bend left=15] (C3-2) edge [left] node
  11714. {\ttfamily\footnotesize select-instr.} (x86-2);
  11715. \path[->,bend right=15] (x86-2) edge [left] node
  11716. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11717. \path[->,bend right=15] (x86-2-1) edge [below] node
  11718. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11719. \path[->,bend right=15] (x86-2-2) edge [left] node
  11720. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11721. \path[->,bend left=15] (x86-3) edge [above] node
  11722. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11723. \path[->,bend left=15] (x86-4) edge [right] node
  11724. {\ttfamily\footnotesize print-x86} (x86-5);
  11725. \end{tikzpicture}
  11726. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  11727. \label{fig:Rdyn-passes}
  11728. \end{figure}
  11729. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  11730. for the compilation of \LangDyn{}.
  11731. % Further Reading
  11732. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11733. \chapter{Loops and Assignment}
  11734. \label{ch:Rwhile}
  11735. % TODO: define R'_8
  11736. % TODO: multi-graph
  11737. In this chapter we study two features that are the hallmarks of
  11738. imperative programming languages: loops and assignments to local
  11739. variables. The following example demonstrates these new features by
  11740. computing the sum of the first five positive integers.
  11741. % similar to loop_test_1.rkt
  11742. \begin{lstlisting}
  11743. (let ([sum 0])
  11744. (let ([i 5])
  11745. (begin
  11746. (while (> i 0)
  11747. (begin
  11748. (set! sum (+ sum i))
  11749. (set! i (- i 1))))
  11750. sum)))
  11751. \end{lstlisting}
  11752. The \code{while} loop consists of a condition and a body.
  11753. %
  11754. The \code{set!} consists of a variable and a right-hand-side expression.
  11755. %
  11756. The primary purpose of both the \code{while} loop and \code{set!} is
  11757. to cause side effects, so it is convenient to also include in a
  11758. language feature for sequencing side effects: the \code{begin}
  11759. expression. It consists of one or more subexpressions that are
  11760. evaluated left-to-right.
  11761. \section{The \LangLoop{} Language}
  11762. \begin{figure}[tp]
  11763. \centering
  11764. \fbox{
  11765. \begin{minipage}{0.96\textwidth}
  11766. \small
  11767. \[
  11768. \begin{array}{lcl}
  11769. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11770. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  11771. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11772. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11773. \MID (\key{and}\;\Exp\;\Exp)
  11774. \MID (\key{or}\;\Exp\;\Exp)
  11775. \MID (\key{not}\;\Exp) } \\
  11776. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11777. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  11778. (\key{vector-ref}\;\Exp\;\Int)} \\
  11779. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  11780. \MID (\Exp \; \Exp\ldots) } \\
  11781. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11782. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11783. &\MID& \CSETBANG{\Var}{\Exp}
  11784. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11785. \MID \CWHILE{\Exp}{\Exp} \\
  11786. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11787. \LangLoopM{} &::=& \gray{\Def\ldots \; \Exp}
  11788. \end{array}
  11789. \]
  11790. \end{minipage}
  11791. }
  11792. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  11793. \label{fig:Rwhile-concrete-syntax}
  11794. \end{figure}
  11795. \begin{figure}[tp]
  11796. \centering
  11797. \fbox{
  11798. \begin{minipage}{0.96\textwidth}
  11799. \small
  11800. \[
  11801. \begin{array}{lcl}
  11802. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  11803. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11804. &\MID& \gray{ \BOOL{\itm{bool}}
  11805. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  11806. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  11807. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  11808. &\MID& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  11809. &\MID& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  11810. \MID \WHILE{\Exp}{\Exp} \\
  11811. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  11812. \LangLoopM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11813. \end{array}
  11814. \]
  11815. \end{minipage}
  11816. }
  11817. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  11818. \label{fig:Rwhile-syntax}
  11819. \end{figure}
  11820. The concrete syntax of \LangLoop{} is defined in
  11821. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  11822. in Figure~\ref{fig:Rwhile-syntax}.
  11823. %
  11824. The definitional interpreter for \LangLoop{} is shown in
  11825. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  11826. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  11827. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  11828. support assignment to variables and to make their lifetimes indefinite
  11829. (see the second example in Section~\ref{sec:assignment-scoping}), we
  11830. box the value that is bound to each variable (in \code{Let}) and
  11831. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  11832. the value.
  11833. %
  11834. Now to discuss the new cases. For \code{SetBang}, we lookup the
  11835. variable in the environment to obtain a boxed value and then we change
  11836. it using \code{set-box!} to the result of evaluating the right-hand
  11837. side. The result value of a \code{SetBang} is \code{void}.
  11838. %
  11839. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  11840. if the result is true, 2) evaluate the body.
  11841. The result value of a \code{while} loop is also \code{void}.
  11842. %
  11843. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  11844. subexpressions \itm{es} for their effects and then evaluates
  11845. and returns the result from \itm{body}.
  11846. \begin{figure}[tbp]
  11847. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11848. (define interp-Rwhile_class
  11849. (class interp-Rany_class
  11850. (super-new)
  11851. (define/override ((interp-exp env) e)
  11852. (define recur (interp-exp env))
  11853. (match e
  11854. [(SetBang x rhs)
  11855. (set-box! (lookup x env) (recur rhs))]
  11856. [(WhileLoop cnd body)
  11857. (define (loop)
  11858. (cond [(recur cnd) (recur body) (loop)]
  11859. [else (void)]))
  11860. (loop)]
  11861. [(Begin es body)
  11862. (for ([e es]) (recur e))
  11863. (recur body)]
  11864. [else ((super interp-exp env) e)]))
  11865. ))
  11866. (define (interp-Rwhile p)
  11867. (send (new interp-Rwhile_class) interp-program p))
  11868. \end{lstlisting}
  11869. \caption{Interpreter for \LangLoop{}.}
  11870. \label{fig:interp-Rwhile}
  11871. \end{figure}
  11872. The type checker for \LangLoop{} is define in
  11873. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  11874. variable and the right-hand-side must agree. The result type is
  11875. \code{Void}. For the \code{WhileLoop}, the condition must be a
  11876. \code{Boolean}. The result type is also \code{Void}. For
  11877. \code{Begin}, the result type is the type of its last subexpression.
  11878. \begin{figure}[tbp]
  11879. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11880. (define type-check-Rwhile_class
  11881. (class type-check-Rany_class
  11882. (super-new)
  11883. (inherit check-type-equal?)
  11884. (define/override (type-check-exp env)
  11885. (lambda (e)
  11886. (define recur (type-check-exp env))
  11887. (match e
  11888. [(SetBang x rhs)
  11889. (define-values (rhs^ rhsT) (recur rhs))
  11890. (define varT (dict-ref env x))
  11891. (check-type-equal? rhsT varT e)
  11892. (values (SetBang x rhs^) 'Void)]
  11893. [(WhileLoop cnd body)
  11894. (define-values (cnd^ Tc) (recur cnd))
  11895. (check-type-equal? Tc 'Boolean e)
  11896. (define-values (body^ Tbody) ((type-check-exp env) body))
  11897. (values (WhileLoop cnd^ body^) 'Void)]
  11898. [(Begin es body)
  11899. (define-values (es^ ts)
  11900. (for/lists (l1 l2) ([e es]) (recur e)))
  11901. (define-values (body^ Tbody) (recur body))
  11902. (values (Begin es^ body^) Tbody)]
  11903. [else ((super type-check-exp env) e)])))
  11904. ))
  11905. (define (type-check-Rwhile p)
  11906. (send (new type-check-Rwhile_class) type-check-program p))
  11907. \end{lstlisting}
  11908. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  11909. and \code{Begin} in \LangLoop{}.}
  11910. \label{fig:type-check-Rwhile}
  11911. \end{figure}
  11912. At first glance, the translation of these language features to x86
  11913. seems straightforward because the \LangCFun{} intermediate language already
  11914. supports all of the ingredients that we need: assignment, \code{goto},
  11915. conditional branching, and sequencing. However, there are two
  11916. complications that arise which we discuss in the next two
  11917. sections. After that we introduce one new compiler pass and the
  11918. changes necessary to the existing passes.
  11919. \section{Assignment and Lexically Scoped Functions}
  11920. \label{sec:assignment-scoping}
  11921. The addition of assignment raises a problem with our approach to
  11922. implementing lexically-scoped functions. Consider the following
  11923. example in which function \code{f} has a free variable \code{x} that
  11924. is changed after \code{f} is created but before the call to \code{f}.
  11925. % loop_test_11.rkt
  11926. \begin{lstlisting}
  11927. (let ([x 0])
  11928. (let ([y 0])
  11929. (let ([z 20])
  11930. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  11931. (begin
  11932. (set! x 10)
  11933. (set! y 12)
  11934. (f y))))))
  11935. \end{lstlisting}
  11936. The correct output for this example is \code{42} because the call to
  11937. \code{f} is required to use the current value of \code{x} (which is
  11938. \code{10}). Unfortunately, the closure conversion pass
  11939. (Section~\ref{sec:closure-conversion}) generates code for the
  11940. \code{lambda} that copies the old value of \code{x} into a
  11941. closure. Thus, if we naively add support for assignment to our current
  11942. compiler, the output of this program would be \code{32}.
  11943. A first attempt at solving this problem would be to save a pointer to
  11944. \code{x} in the closure and change the occurrences of \code{x} inside
  11945. the lambda to dereference the pointer. Of course, this would require
  11946. assigning \code{x} to the stack and not to a register. However, the
  11947. problem goes a bit deeper. Consider the following example in which we
  11948. create a counter abstraction by creating a pair of functions that
  11949. share the free variable \code{x}.
  11950. % similar to loop_test_10.rkt
  11951. \begin{lstlisting}
  11952. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  11953. (vector
  11954. (lambda: () : Integer x)
  11955. (lambda: () : Void (set! x (+ 1 x)))))
  11956. (let ([counter (f 0)])
  11957. (let ([get (vector-ref counter 0)])
  11958. (let ([inc (vector-ref counter 1)])
  11959. (begin
  11960. (inc)
  11961. (get)))))
  11962. \end{lstlisting}
  11963. In this example, the lifetime of \code{x} extends beyond the lifetime
  11964. of the call to \code{f}. Thus, if we were to store \code{x} on the
  11965. stack frame for the call to \code{f}, it would be gone by the time we
  11966. call \code{inc} and \code{get}, leaving us with dangling pointers for
  11967. \code{x}. This example demonstrates that when a variable occurs free
  11968. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  11969. value of the variable needs to live on the heap. The verb ``box'' is
  11970. often used for allocating a single value on the heap, producing a
  11971. pointer, and ``unbox'' for dereferencing the pointer.
  11972. We recommend solving these problems by ``boxing'' the local variables
  11973. that are in the intersection of 1) variables that appear on the
  11974. left-hand-side of a \code{set!} and 2) variables that occur free
  11975. inside a \code{lambda}. We shall introduce a new pass named
  11976. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  11977. perform this translation. But before diving into the compiler passes,
  11978. we one more problem to discuss.
  11979. \section{Cyclic Control Flow and Dataflow Analysis}
  11980. \label{sec:dataflow-analysis}
  11981. Up until this point the control-flow graphs generated in
  11982. \code{explicate\_control} were guaranteed to be acyclic. However, each
  11983. \code{while} loop introduces a cycle in the control-flow graph.
  11984. But does that matter?
  11985. %
  11986. Indeed it does. Recall that for register allocation, the compiler
  11987. performs liveness analysis to determine which variables can share the
  11988. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  11989. the control-flow graph in reverse topological order, but topological
  11990. order is only well-defined for acyclic graphs.
  11991. Let us return to the example of computing the sum of the first five
  11992. positive integers. Here is the program after instruction selection but
  11993. before register allocation.
  11994. \begin{center}
  11995. \begin{minipage}{0.45\textwidth}
  11996. \begin{lstlisting}
  11997. (define (main) : Integer
  11998. mainstart:
  11999. movq $0, sum1
  12000. movq $5, i2
  12001. jmp block5
  12002. block5:
  12003. movq i2, tmp3
  12004. cmpq tmp3, $0
  12005. jl block7
  12006. jmp block8
  12007. \end{lstlisting}
  12008. \end{minipage}
  12009. \begin{minipage}{0.45\textwidth}
  12010. \begin{lstlisting}
  12011. block7:
  12012. addq i2, sum1
  12013. movq $1, tmp4
  12014. negq tmp4
  12015. addq tmp4, i2
  12016. jmp block5
  12017. block8:
  12018. movq $27, %rax
  12019. addq sum1, %rax
  12020. jmp mainconclusion
  12021. )
  12022. \end{lstlisting}
  12023. \end{minipage}
  12024. \end{center}
  12025. Recall that liveness analysis works backwards, starting at the end
  12026. of each function. For this example we could start with \code{block8}
  12027. because we know what is live at the beginning of the conclusion,
  12028. just \code{rax} and \code{rsp}. So the live-before set
  12029. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  12030. %
  12031. Next we might try to analyze \code{block5} or \code{block7}, but
  12032. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  12033. we are stuck.
  12034. The way out of this impasse comes from the realization that one can
  12035. perform liveness analysis starting with an empty live-after set to
  12036. compute an under-approximation of the live-before set. By
  12037. \emph{under-approximation}, we mean that the set only contains
  12038. variables that are really live, but it may be missing some. Next, the
  12039. under-approximations for each block can be improved by 1) updating the
  12040. live-after set for each block using the approximate live-before sets
  12041. from the other blocks and 2) perform liveness analysis again on each
  12042. block. In fact, by iterating this process, the under-approximations
  12043. eventually become the correct solutions!
  12044. %
  12045. This approach of iteratively analyzing a control-flow graph is
  12046. applicable to many static analysis problems and goes by the name
  12047. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  12048. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  12049. Washington.
  12050. Let us apply this approach to the above example. We use the empty set
  12051. for the initial live-before set for each block. Let $m_0$ be the
  12052. following mapping from label names to sets of locations (variables and
  12053. registers).
  12054. \begin{center}
  12055. \begin{lstlisting}
  12056. mainstart: {}
  12057. block5: {}
  12058. block7: {}
  12059. block8: {}
  12060. \end{lstlisting}
  12061. \end{center}
  12062. Using the above live-before approximations, we determine the
  12063. live-after for each block and then apply liveness analysis to each
  12064. block. This produces our next approximation $m_1$ of the live-before
  12065. sets.
  12066. \begin{center}
  12067. \begin{lstlisting}
  12068. mainstart: {}
  12069. block5: {i2}
  12070. block7: {i2, sum1}
  12071. block8: {rsp, sum1}
  12072. \end{lstlisting}
  12073. \end{center}
  12074. For the second round, the live-after for \code{mainstart} is the
  12075. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  12076. liveness analysis for \code{mainstart} computes the empty set. The
  12077. live-after for \code{block5} is the union of the live-before sets for
  12078. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  12079. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  12080. sum1\}}. The live-after for \code{block7} is the live-before for
  12081. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  12082. So the liveness analysis for \code{block7} remains \code{\{i2,
  12083. sum1\}}. Together these yield the following approximation $m_2$ of
  12084. the live-before sets.
  12085. \begin{center}
  12086. \begin{lstlisting}
  12087. mainstart: {}
  12088. block5: {i2, rsp, sum1}
  12089. block7: {i2, sum1}
  12090. block8: {rsp, sum1}
  12091. \end{lstlisting}
  12092. \end{center}
  12093. In the preceding iteration, only \code{block5} changed, so we can
  12094. limit our attention to \code{mainstart} and \code{block7}, the two
  12095. blocks that jump to \code{block5}. As a result, the live-before sets
  12096. for \code{mainstart} and \code{block7} are updated to include
  12097. \code{rsp}, yielding the following approximation $m_3$.
  12098. \begin{center}
  12099. \begin{lstlisting}
  12100. mainstart: {rsp}
  12101. block5: {i2, rsp, sum1}
  12102. block7: {i2, rsp, sum1}
  12103. block8: {rsp, sum1}
  12104. \end{lstlisting}
  12105. \end{center}
  12106. Because \code{block7} changed, we analyze \code{block5} once more, but
  12107. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  12108. our approximations have converged, so $m_3$ is the solution.
  12109. This iteration process is guaranteed to converge to a solution by the
  12110. Kleene Fixed-Point Theorem, a general theorem about functions on
  12111. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  12112. any collection that comes with a partial ordering $\sqsubseteq$ on its
  12113. elements, a least element $\bot$ (pronounced bottom), and a join
  12114. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  12115. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  12116. working with join semi-lattices.} When two elements are ordered $m_i
  12117. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  12118. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  12119. approximation than $m_i$. The bottom element $\bot$ represents the
  12120. complete lack of information, i.e., the worst approximation. The join
  12121. operator takes two lattice elements and combines their information,
  12122. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  12123. bound}
  12124. A dataflow analysis typically involves two lattices: one lattice to
  12125. represent abstract states and another lattice that aggregates the
  12126. abstract states of all the blocks in the control-flow graph. For
  12127. liveness analysis, an abstract state is a set of locations. We form
  12128. the lattice $L$ by taking its elements to be sets of locations, the
  12129. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  12130. set, and the join operator to be set union.
  12131. %
  12132. We form a second lattice $M$ by taking its elements to be mappings
  12133. from the block labels to sets of locations (elements of $L$). We
  12134. order the mappings point-wise, using the ordering of $L$. So given any
  12135. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  12136. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  12137. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  12138. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  12139. We can think of one iteration of liveness analysis as being a function
  12140. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  12141. mapping.
  12142. \[
  12143. f(m_i) = m_{i+1}
  12144. \]
  12145. Next let us think for a moment about what a final solution $m_s$
  12146. should look like. If we perform liveness analysis using the solution
  12147. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  12148. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  12149. \[
  12150. f(m_s) = m_s
  12151. \]
  12152. Furthermore, the solution should only include locations that are
  12153. forced to be there by performing liveness analysis on the program, so
  12154. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  12155. The Kleene Fixed-Point Theorem states that if a function $f$ is
  12156. monotone (better inputs produce better outputs), then the least fixed
  12157. point of $f$ is the least upper bound of the \emph{ascending Kleene
  12158. chain} obtained by starting at $\bot$ and iterating $f$ as
  12159. follows.\index{subject}{Kleene Fixed-Point Theorem}
  12160. \[
  12161. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  12162. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  12163. \]
  12164. When a lattice contains only finitely-long ascending chains, then
  12165. every Kleene chain tops out at some fixed point after a number of
  12166. iterations of $f$. So that fixed point is also a least upper
  12167. bound of the chain.
  12168. \[
  12169. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  12170. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  12171. \]
  12172. The liveness analysis is indeed a monotone function and the lattice
  12173. $M$ only has finitely-long ascending chains because there are only a
  12174. finite number of variables and blocks in the program. Thus we are
  12175. guaranteed that iteratively applying liveness analysis to all blocks
  12176. in the program will eventually produce the least fixed point solution.
  12177. Next let us consider dataflow analysis in general and discuss the
  12178. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  12179. %
  12180. The algorithm has four parameters: the control-flow graph \code{G}, a
  12181. function \code{transfer} that applies the analysis to one block, the
  12182. \code{bottom} and \code{join} operator for the lattice of abstract
  12183. states. The algorithm begins by creating the bottom mapping,
  12184. represented by a hash table. It then pushes all of the nodes in the
  12185. control-flow graph onto the work list (a queue). The algorithm repeats
  12186. the \code{while} loop as long as there are items in the work list. In
  12187. each iteration, a node is popped from the work list and processed. The
  12188. \code{input} for the node is computed by taking the join of the
  12189. abstract states of all the predecessor nodes. The \code{transfer}
  12190. function is then applied to obtain the \code{output} abstract
  12191. state. If the output differs from the previous state for this block,
  12192. the mapping for this block is updated and its successor nodes are
  12193. pushed onto the work list.
  12194. \begin{figure}[tb]
  12195. \begin{lstlisting}
  12196. (define (analyze-dataflow G transfer bottom join)
  12197. (define mapping (make-hash))
  12198. (for ([v (in-vertices G)])
  12199. (dict-set! mapping v bottom))
  12200. (define worklist (make-queue))
  12201. (for ([v (in-vertices G)])
  12202. (enqueue! worklist v))
  12203. (define trans-G (transpose G))
  12204. (while (not (queue-empty? worklist))
  12205. (define node (dequeue! worklist))
  12206. (define input (for/fold ([state bottom])
  12207. ([pred (in-neighbors trans-G node)])
  12208. (join state (dict-ref mapping pred))))
  12209. (define output (transfer node input))
  12210. (cond [(not (equal? output (dict-ref mapping node)))
  12211. (dict-set! mapping node output)
  12212. (for ([v (in-neighbors G node)])
  12213. (enqueue! worklist v))]))
  12214. mapping)
  12215. \end{lstlisting}
  12216. \caption{Generic work list algorithm for dataflow analysis}
  12217. \label{fig:generic-dataflow}
  12218. \end{figure}
  12219. Having discussed the two complications that arise from adding support
  12220. for assignment and loops, we turn to discussing the one new compiler
  12221. pass and the significant changes to existing passes.
  12222. \section{Convert Assignments}
  12223. \label{sec:convert-assignments}
  12224. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  12225. the combination of assignments and lexically-scoped functions requires
  12226. that we box those variables that are both assigned-to and that appear
  12227. free inside a \code{lambda}. The purpose of the
  12228. \code{convert-assignments} pass is to carry out that transformation.
  12229. We recommend placing this pass after \code{uniquify} but before
  12230. \code{reveal-functions}.
  12231. Consider again the first example from
  12232. Section~\ref{sec:assignment-scoping}:
  12233. \begin{lstlisting}
  12234. (let ([x 0])
  12235. (let ([y 0])
  12236. (let ([z 20])
  12237. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  12238. (begin
  12239. (set! x 10)
  12240. (set! y 12)
  12241. (f y))))))
  12242. \end{lstlisting}
  12243. The variables \code{x} and \code{y} are assigned-to. The variables
  12244. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  12245. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  12246. The boxing of \code{x} consists of three transformations: initialize
  12247. \code{x} with a vector, replace reads from \code{x} with
  12248. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  12249. \code{vector-set!}. The output of \code{convert-assignments} for this
  12250. example is as follows.
  12251. \begin{lstlisting}
  12252. (define (main) : Integer
  12253. (let ([x0 (vector 0)])
  12254. (let ([y1 0])
  12255. (let ([z2 20])
  12256. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  12257. (+ a3 (+ (vector-ref x0 0) z2)))])
  12258. (begin
  12259. (vector-set! x0 0 10)
  12260. (set! y1 12)
  12261. (f4 y1)))))))
  12262. \end{lstlisting}
  12263. \paragraph{Assigned \& Free}
  12264. We recommend defining an auxiliary function named
  12265. \code{assigned\&free} that takes an expression and simultaneously
  12266. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  12267. that occur free within lambda's, and 3) a new version of the
  12268. expression that records which bound variables occurred in the
  12269. intersection of $A$ and $F$. You can use the struct
  12270. \code{AssignedFree} to do this. Consider the case for
  12271. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  12272. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  12273. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  12274. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  12275. \begin{lstlisting}
  12276. (Let |$x$| |$rhs$| |$body$|)
  12277. |$\Rightarrow$|
  12278. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  12279. \end{lstlisting}
  12280. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  12281. The set of assigned variables for this \code{Let} is
  12282. $A_r \cup (A_b - \{x\})$
  12283. and the set of variables free in lambda's is
  12284. $F_r \cup (F_b - \{x\})$.
  12285. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  12286. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  12287. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  12288. and $F_r$.
  12289. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  12290. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  12291. recursively processing \itm{body}. Wrap each of parameter that occurs
  12292. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  12293. Let $P$ be the set of parameter names in \itm{params}. The result is
  12294. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  12295. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  12296. variables of an expression (see Chapter~\ref{ch:Rlam}).
  12297. \paragraph{Convert Assignments}
  12298. Next we discuss the \code{convert-assignment} pass with its auxiliary
  12299. functions for expressions and definitions. The function for
  12300. expressions, \code{cnvt-assign-exp}, should take an expression and a
  12301. set of assigned-and-free variables (obtained from the result of
  12302. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  12303. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  12304. \code{vector-ref}.
  12305. \begin{lstlisting}
  12306. (Var |$x$|)
  12307. |$\Rightarrow$|
  12308. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  12309. \end{lstlisting}
  12310. %
  12311. In the case for $\LET{\LP\code{AssignedFree}\,
  12312. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  12313. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  12314. \itm{body'} but with $x$ added to the set of assigned-and-free
  12315. variables. Translate the let-expression as follows to bind $x$ to a
  12316. boxed value.
  12317. \begin{lstlisting}
  12318. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  12319. |$\Rightarrow$|
  12320. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  12321. \end{lstlisting}
  12322. %
  12323. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  12324. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  12325. variables, translate the \code{set!} into a \code{vector-set!}
  12326. as follows.
  12327. \begin{lstlisting}
  12328. (SetBang |$x$| |$\itm{rhs}$|)
  12329. |$\Rightarrow$|
  12330. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  12331. \end{lstlisting}
  12332. %
  12333. The case for \code{Lambda} is non-trivial, but it is similar to the
  12334. case for function definitions, which we discuss next.
  12335. The auxiliary function for definitions, \code{cnvt-assign-def},
  12336. applies assignment conversion to function definitions.
  12337. We translate a function definition as follows.
  12338. \begin{lstlisting}
  12339. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  12340. |$\Rightarrow$|
  12341. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  12342. \end{lstlisting}
  12343. So it remains to explain \itm{params'} and $\itm{body}_4$.
  12344. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  12345. \code{assigned\&free} on $\itm{body_1}$.
  12346. Let $P$ be the parameter names in \itm{params}.
  12347. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  12348. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  12349. as the set of assigned-and-free variables.
  12350. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  12351. in a sequence of let-expressions that box the parameters
  12352. that are in $A_b \cap F_b$.
  12353. %
  12354. Regarding \itm{params'}, change the names of the parameters that are
  12355. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  12356. variables can retain the original names). Recall the second example in
  12357. Section~\ref{sec:assignment-scoping} involving a counter
  12358. abstraction. The following is the output of assignment version for
  12359. function \code{f}.
  12360. \begin{lstlisting}
  12361. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  12362. (vector
  12363. (lambda: () : Integer x1)
  12364. (lambda: () : Void (set! x1 (+ 1 x1)))))
  12365. |$\Rightarrow$|
  12366. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  12367. (let ([x1 (vector param_x1)])
  12368. (vector (lambda: () : Integer (vector-ref x1 0))
  12369. (lambda: () : Void
  12370. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  12371. \end{lstlisting}
  12372. \section{Remove Complex Operands}
  12373. \label{sec:rco-loop}
  12374. The three new language forms, \code{while}, \code{set!}, and
  12375. \code{begin} are all complex expressions and their subexpressions are
  12376. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  12377. output language \LangFunANF{} of this pass.
  12378. \begin{figure}[tp]
  12379. \centering
  12380. \fbox{
  12381. \begin{minipage}{0.96\textwidth}
  12382. \small
  12383. \[
  12384. \begin{array}{rcl}
  12385. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12386. \MID \VOID{} } \\
  12387. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12388. &\MID& \WHILE{\Exp}{\Exp} \MID \SETBANG{\Var}{\Exp}
  12389. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  12390. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12391. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12392. \end{array}
  12393. \]
  12394. \end{minipage}
  12395. }
  12396. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  12397. \label{fig:Rwhile-anf-syntax}
  12398. \end{figure}
  12399. As usual, when a complex expression appears in a grammar position that
  12400. needs to be atomic, such as the argument of a primitive operator, we
  12401. must introduce a temporary variable and bind it to the complex
  12402. expression. This approach applies, unchanged, to handle the new
  12403. language forms. For example, in the following code there are two
  12404. \code{begin} expressions appearing as arguments to \code{+}. The
  12405. output of \code{rco-exp} is shown below, in which the \code{begin}
  12406. expressions have been bound to temporary variables. Recall that
  12407. \code{let} expressions in \LangLoopANF{} are allowed to have
  12408. arbitrary expressions in their right-hand-side expression, so it is
  12409. fine to place \code{begin} there.
  12410. \begin{lstlisting}
  12411. (let ([x0 10])
  12412. (let ([y1 0])
  12413. (+ (+ (begin (set! y1 (read)) x0)
  12414. (begin (set! x0 (read)) y1))
  12415. x0)))
  12416. |$\Rightarrow$|
  12417. (let ([x0 10])
  12418. (let ([y1 0])
  12419. (let ([tmp2 (begin (set! y1 (read)) x0)])
  12420. (let ([tmp3 (begin (set! x0 (read)) y1)])
  12421. (let ([tmp4 (+ tmp2 tmp3)])
  12422. (+ tmp4 x0))))))
  12423. \end{lstlisting}
  12424. \section{Explicate Control and \LangCLoop{}}
  12425. \label{sec:explicate-loop}
  12426. Recall that in the \code{explicate\_control} pass we define one helper
  12427. function for each kind of position in the program. For the \LangVar{}
  12428. language of integers and variables we needed kinds of positions:
  12429. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  12430. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  12431. yet another kind of position: effect position. Except for the last
  12432. subexpression, the subexpressions inside a \code{begin} are evaluated
  12433. only for their effect. Their result values are discarded. We can
  12434. generate better code by taking this fact into account.
  12435. The output language of \code{explicate\_control} is \LangCLoop{}
  12436. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  12437. \LangCLam{}. The only syntactic difference is that \code{Call},
  12438. \code{vector-set!}, and \code{read} may also appear as statements.
  12439. The most significant difference between \LangCLam{} and \LangCLoop{}
  12440. is that the control-flow graphs of the later may contain cycles.
  12441. \begin{figure}[tp]
  12442. \fbox{
  12443. \begin{minipage}{0.96\textwidth}
  12444. \small
  12445. \[
  12446. \begin{array}{lcl}
  12447. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  12448. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  12449. &\MID& \CALL{\Atm}{\LP\Atm\ldots\RP} \MID \READ{}\\
  12450. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  12451. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  12452. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12453. \end{array}
  12454. \]
  12455. \end{minipage}
  12456. }
  12457. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  12458. \label{fig:c7-syntax}
  12459. \end{figure}
  12460. The new auxiliary function \code{explicate-effect} takes an expression
  12461. (in an effect position) and a promise of a continuation block. The
  12462. function returns a promise for a $\Tail$ that includes the generated
  12463. code for the input expression followed by the continuation block. If
  12464. the expression is obviously pure, that is, never causes side effects,
  12465. then the expression can be removed, so the result is just the
  12466. continuation block.
  12467. %
  12468. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  12469. case. First, you will need a fresh label $\itm{loop}$ for the top of
  12470. the loop. Recursively process the \itm{body} (in effect position)
  12471. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  12472. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  12473. \itm{body'} as the then-branch and the continuation block as the
  12474. else-branch. The result should be added to the control-flow graph with
  12475. the label \itm{loop}. The result for the whole \code{while} loop is a
  12476. \code{goto} to the \itm{loop} label. Note that the loop should only be
  12477. added to the control-flow graph if the loop is indeed used, which can
  12478. be accomplished using \code{delay}.
  12479. The auxiliary functions for tail, assignment, and predicate positions
  12480. need to be updated. The three new language forms, \code{while},
  12481. \code{set!}, and \code{begin}, can appear in assignment and tail
  12482. positions. Only \code{begin} may appear in predicate positions; the
  12483. other two have result type \code{Void}.
  12484. \section{Select Instructions}
  12485. \label{sec:select-instructions-loop}
  12486. Only three small additions are needed in the
  12487. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  12488. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  12489. stand-alone statements instead of only appearing on the right-hand
  12490. side of an assignment statement. The code generation is nearly
  12491. identical; just leave off the instruction for moving the result into
  12492. the left-hand side.
  12493. \section{Register Allocation}
  12494. \label{sec:register-allocation-loop}
  12495. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  12496. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  12497. which complicates the liveness analysis needed for register
  12498. allocation.
  12499. \subsection{Liveness Analysis}
  12500. \label{sec:liveness-analysis-r8}
  12501. We recommend using the generic \code{analyze-dataflow} function that
  12502. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  12503. perform liveness analysis, replacing the code in
  12504. \code{uncover-live-CFG} that processed the basic blocks in topological
  12505. order (Section~\ref{sec:liveness-analysis-Rif}).
  12506. The \code{analyze-dataflow} function has four parameters.
  12507. \begin{enumerate}
  12508. \item The first parameter \code{G} should be a directed graph from the
  12509. \code{racket/graph} package (see the sidebar in
  12510. Section~\ref{sec:build-interference}) that represents the
  12511. control-flow graph.
  12512. \item The second parameter \code{transfer} is a function that applies
  12513. liveness analysis to a basic block. It takes two parameters: the
  12514. label for the block to analyze and the live-after set for that
  12515. block. The transfer function should return the live-before set for
  12516. the block. Also, as a side-effect, it should update the block's
  12517. $\itm{info}$ with the liveness information for each instruction. To
  12518. implement the \code{transfer} function, you should be able to reuse
  12519. the code you already have for analyzing basic blocks.
  12520. \item The third and fourth parameters of \code{analyze-dataflow} are
  12521. \code{bottom} and \code{join} for the lattice of abstract states,
  12522. i.e. sets of locations. The bottom of the lattice is the empty set
  12523. \code{(set)} and the join operator is \code{set-union}.
  12524. \end{enumerate}
  12525. \begin{figure}[p]
  12526. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12527. \node (Rfun) at (0,2) {\large \LangLoop{}};
  12528. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  12529. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  12530. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  12531. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  12532. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  12533. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  12534. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  12535. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  12536. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  12537. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12538. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12539. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12540. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12541. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12542. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12543. %% \path[->,bend left=15] (Rfun) edge [above] node
  12544. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  12545. \path[->,bend left=15] (Rfun) edge [above] node
  12546. {\ttfamily\footnotesize shrink} (Rfun-2);
  12547. \path[->,bend left=15] (Rfun-2) edge [above] node
  12548. {\ttfamily\footnotesize uniquify} (Rfun-3);
  12549. \path[->,bend left=15] (Rfun-3) edge [above] node
  12550. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  12551. \path[->,bend left=15] (Rfun-4) edge [right] node
  12552. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12553. \path[->,bend left=15] (F1-1) edge [below] node
  12554. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12555. \path[->,bend right=15] (F1-2) edge [above] node
  12556. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12557. \path[->,bend right=15] (F1-3) edge [above] node
  12558. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12559. \path[->,bend right=15] (F1-4) edge [above] node
  12560. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12561. \path[->,bend right=15] (F1-5) edge [right] node
  12562. {\ttfamily\footnotesize explicate-control} (C3-2);
  12563. \path[->,bend left=15] (C3-2) edge [left] node
  12564. {\ttfamily\footnotesize select-instr.} (x86-2);
  12565. \path[->,bend right=15] (x86-2) edge [left] node
  12566. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12567. \path[->,bend right=15] (x86-2-1) edge [below] node
  12568. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12569. \path[->,bend right=15] (x86-2-2) edge [left] node
  12570. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12571. \path[->,bend left=15] (x86-3) edge [above] node
  12572. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12573. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12574. \end{tikzpicture}
  12575. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  12576. \label{fig:Rwhile-passes}
  12577. \end{figure}
  12578. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  12579. for the compilation of \LangLoop{}.
  12580. \section{Challenge: Arrays}
  12581. \label{sec:arrays}
  12582. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  12583. elements whose length is determined at compile-time and where each
  12584. element of a tuple may have a different type (they are
  12585. heterogeous). This challenge is also about sequences, but this time
  12586. the length is determined at run-time and all the elements have the same
  12587. type (they are homogeneous). We use the term ``array'' for this later
  12588. kind of sequence.
  12589. The Racket language does not distinguish between tuples and arrays,
  12590. they are both represented by vectors. However, Typed Racket
  12591. distinguishes between tuples and arrays: the \code{Vector} type is for
  12592. tuples and the \code{Vectorof} type is for arrays.
  12593. %
  12594. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  12595. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  12596. and the \code{make-vector} primitive operator for creating an array,
  12597. whose arguments are the length of the array and an initial value for
  12598. all the elements in the array. The \code{vector-length},
  12599. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  12600. for tuples become overloaded for use with arrays.
  12601. %
  12602. We also include integer multiplication in \LangArray{}, as it is
  12603. useful in many examples involving arrays such as computing the
  12604. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  12605. \begin{figure}[tp]
  12606. \centering
  12607. \fbox{
  12608. \begin{minipage}{0.96\textwidth}
  12609. \small
  12610. \[
  12611. \begin{array}{lcl}
  12612. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  12613. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12614. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  12615. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  12616. &\MID& \gray{\key{\#t} \MID \key{\#f}
  12617. \MID \LP\key{and}\;\Exp\;\Exp\RP
  12618. \MID \LP\key{or}\;\Exp\;\Exp\RP
  12619. \MID \LP\key{not}\;\Exp\RP } \\
  12620. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  12621. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  12622. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  12623. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  12624. \MID \LP\Exp \; \Exp\ldots\RP } \\
  12625. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  12626. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  12627. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  12628. \MID \CBEGIN{\Exp\ldots}{\Exp}
  12629. \MID \CWHILE{\Exp}{\Exp} } \\
  12630. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  12631. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12632. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  12633. \end{array}
  12634. \]
  12635. \end{minipage}
  12636. }
  12637. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  12638. \label{fig:Rvecof-concrete-syntax}
  12639. \end{figure}
  12640. \begin{figure}[tp]
  12641. \begin{lstlisting}
  12642. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  12643. [n : Integer]) : Integer
  12644. (let ([i 0])
  12645. (let ([prod 0])
  12646. (begin
  12647. (while (< i n)
  12648. (begin
  12649. (set! prod (+ prod (* (vector-ref A i)
  12650. (vector-ref B i))))
  12651. (set! i (+ i 1))
  12652. ))
  12653. prod))))
  12654. (let ([A (make-vector 2 2)])
  12655. (let ([B (make-vector 2 3)])
  12656. (+ (inner-product A B 2)
  12657. 30)))
  12658. \end{lstlisting}
  12659. \caption{Example program that computes the inner-product.}
  12660. \label{fig:inner-product}
  12661. \end{figure}
  12662. The type checker for \LangArray{} is define in
  12663. Figure~\ref{fig:type-check-Rvecof}. The result type of
  12664. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  12665. of the intializing expression. The length expression is required to
  12666. have type \code{Integer}. The type checking of the operators
  12667. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12668. updated to handle the situation where the vector has type
  12669. \code{Vectorof}. In these cases we translate the operators to their
  12670. \code{vectorof} form so that later passes can easily distinguish
  12671. between operations on tuples versus arrays. We override the
  12672. \code{operator-types} method to provide the type signature for
  12673. multiplication: it takes two integers and returns an integer. To
  12674. support injection and projection of arrays to the \code{Any} type
  12675. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  12676. predicate.
  12677. \begin{figure}[tbp]
  12678. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12679. (define type-check-Rvecof_class
  12680. (class type-check-Rwhile_class
  12681. (super-new)
  12682. (inherit check-type-equal?)
  12683. (define/override (flat-ty? ty)
  12684. (match ty
  12685. ['(Vectorof Any) #t]
  12686. [else (super flat-ty? ty)]))
  12687. (define/override (operator-types)
  12688. (append '((* . ((Integer Integer) . Integer)))
  12689. (super operator-types)))
  12690. (define/override (type-check-exp env)
  12691. (lambda (e)
  12692. (define recur (type-check-exp env))
  12693. (match e
  12694. [(Prim 'make-vector (list e1 e2))
  12695. (define-values (e1^ t1) (recur e1))
  12696. (define-values (e2^ elt-type) (recur e2))
  12697. (define vec-type `(Vectorof ,elt-type))
  12698. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  12699. vec-type)]
  12700. [(Prim 'vector-ref (list e1 e2))
  12701. (define-values (e1^ t1) (recur e1))
  12702. (define-values (e2^ t2) (recur e2))
  12703. (match* (t1 t2)
  12704. [(`(Vectorof ,elt-type) 'Integer)
  12705. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12706. [(other wise) ((super type-check-exp env) e)])]
  12707. [(Prim 'vector-set! (list e1 e2 e3) )
  12708. (define-values (e-vec t-vec) (recur e1))
  12709. (define-values (e2^ t2) (recur e2))
  12710. (define-values (e-arg^ t-arg) (recur e3))
  12711. (match t-vec
  12712. [`(Vectorof ,elt-type)
  12713. (check-type-equal? elt-type t-arg e)
  12714. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12715. [else ((super type-check-exp env) e)])]
  12716. [(Prim 'vector-length (list e1))
  12717. (define-values (e1^ t1) (recur e1))
  12718. (match t1
  12719. [`(Vectorof ,t)
  12720. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12721. [else ((super type-check-exp env) e)])]
  12722. [else ((super type-check-exp env) e)])))
  12723. ))
  12724. (define (type-check-Rvecof p)
  12725. (send (new type-check-Rvecof_class) type-check-program p))
  12726. \end{lstlisting}
  12727. \caption{Type checker for the \LangArray{} language.}
  12728. \label{fig:type-check-Rvecof}
  12729. \end{figure}
  12730. The interpreter for \LangArray{} is defined in
  12731. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  12732. implemented with Racket's \code{make-vector} function and
  12733. multiplication is \code{fx*}, multiplication for \code{fixnum}
  12734. integers.
  12735. \begin{figure}[tbp]
  12736. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12737. (define interp-Rvecof_class
  12738. (class interp-Rwhile_class
  12739. (super-new)
  12740. (define/override (interp-op op)
  12741. (verbose "Rvecof/interp-op" op)
  12742. (match op
  12743. ['make-vector make-vector]
  12744. ['* fx*]
  12745. [else (super interp-op op)]))
  12746. ))
  12747. (define (interp-Rvecof p)
  12748. (send (new interp-Rvecof_class) interp-program p))
  12749. \end{lstlisting}
  12750. \caption{Interpreter for \LangArray{}.}
  12751. \label{fig:interp-Rvecof}
  12752. \end{figure}
  12753. \subsection{Data Representation}
  12754. \label{sec:array-rep}
  12755. Just like tuples, we store arrays on the heap which means that the
  12756. garbage collector will need to inspect arrays. An immediate thought is
  12757. to use the same representation for arrays that we use for tuples.
  12758. However, we limit tuples to a length of $50$ so that their length and
  12759. pointer mask can fit into the 64-bit tag at the beginning of each
  12760. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12761. millions of elements, so we need more bits to store the length.
  12762. However, because arrays are homogeneous, we only need $1$ bit for the
  12763. pointer mask instead of one bit per array elements. Finally, the
  12764. garbage collector will need to be able to distinguish between tuples
  12765. and arrays, so we need to reserve $1$ bit for that purpose. So we
  12766. arrive at the following layout for the 64-bit tag at the beginning of
  12767. an array:
  12768. \begin{itemize}
  12769. \item The right-most bit is the forwarding bit, just like in a tuple.
  12770. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  12771. it is not.
  12772. \item The next bit to the left is the pointer mask. A $0$ indicates
  12773. that none of the elements are pointers to the heap and a $1$
  12774. indicates that all of the elements are pointers.
  12775. \item The next $61$ bits store the length of the array.
  12776. \item The left-most bit distinguishes between a tuple ($0$) versus an
  12777. array ($1$).
  12778. \end{itemize}
  12779. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  12780. differentiate the kinds of values that have been injected into the
  12781. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12782. to indicate that the value is an array.
  12783. In the following subsections we provide hints regarding how to update
  12784. the passes to handle arrays.
  12785. \subsection{Reveal Casts}
  12786. The array-access operators \code{vectorof-ref} and
  12787. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12788. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  12789. that the type checker cannot tell whether the index will be in bounds,
  12790. so the bounds check must be performed at run time. Recall that the
  12791. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  12792. an \code{If} arround a vector reference for update to check whether
  12793. the index is less than the length. You should do the same for
  12794. \code{vectorof-ref} and \code{vectorof-set!} .
  12795. In addition, the handling of the \code{any-vector} operators in
  12796. \code{reveal-casts} needs to be updated to account for arrays that are
  12797. injected to \code{Any}. For the \code{any-vector-length} operator, the
  12798. generated code should test whether the tag is for tuples (\code{010})
  12799. or arrays (\code{110}) and then dispatch to either
  12800. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12801. we add a case in \code{select-instructions} to generate the
  12802. appropriate instructions for accessing the array length from the
  12803. header of an array.
  12804. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12805. the generated code needs to check that the index is less than the
  12806. vector length, so like the code for \code{any-vector-length}, check
  12807. the tag to determine whether to use \code{any-vector-length} or
  12808. \code{any-vectorof-length} for this purpose. Once the bounds checking
  12809. is complete, the generated code can use \code{any-vector-ref} and
  12810. \code{any-vector-set!} for both tuples and arrays because the
  12811. instructions used for those operators do not look at the tag at the
  12812. front of the tuple or array.
  12813. \subsection{Expose Allocation}
  12814. This pass should translate the \code{make-vector} operator into
  12815. lower-level operations. In particular, the new AST node
  12816. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  12817. length specified by the $\Exp$, but does not initialize the elements
  12818. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  12819. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  12820. element type for the array. Regarding the initialization of the array,
  12821. we recommend generated a \code{while} loop that uses
  12822. \code{vector-set!} to put the initializing value into every element of
  12823. the array.
  12824. \subsection{Remove Complex Operands}
  12825. Add cases in the \code{rco-atom} and \code{rco-exp} for
  12826. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12827. complex and its subexpression must be atomic.
  12828. \subsection{Explicate Control}
  12829. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  12830. \code{explicate-assign}.
  12831. \subsection{Select Instructions}
  12832. Generate instructions for \code{AllocateArray} similar to those for
  12833. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  12834. that the tag at the front of the array should instead use the
  12835. representation discussed in Section~\ref{sec:array-rep}.
  12836. Regarding \code{vectorof-length}, extract the length from the tag
  12837. according to the representation discussed in
  12838. Section~\ref{sec:array-rep}.
  12839. The instructions generated for \code{vectorof-ref} differ from those
  12840. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  12841. that the index is not a constant so the offset must be computed at
  12842. runtime, similar to the instructions generated for
  12843. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  12844. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  12845. appear in an assignment and as a stand-alone statement, so make sure
  12846. to handle both situations in this pass.
  12847. Finally, the instructions for \code{any-vectorof-length} should be
  12848. similar to those for \code{vectorof-length}, except that one must
  12849. first project the array by writing zeroes into the $3$-bit tag
  12850. \begin{exercise}\normalfont
  12851. Implement a compiler for the \LangArray{} language by extending your
  12852. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12853. programs, including the one in Figure~\ref{fig:inner-product} and also
  12854. a program that multiplies two matrices. Note that matrices are
  12855. 2-dimensional arrays, but those can be encoded into 1-dimensional
  12856. arrays by laying out each row in the array, one after the next.
  12857. \end{exercise}
  12858. % Further Reading: dataflow analysis
  12859. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12860. \chapter{Gradual Typing}
  12861. \label{ch:Rgrad}
  12862. \index{subject}{gradual typing}
  12863. This chapter studies a language, \LangGrad{}, in which the programmer
  12864. can choose between static and dynamic type checking in different parts
  12865. of a program, thereby mixing the statically typed \LangLoop{} language
  12866. with the dynamically typed \LangDyn{}. There are several approaches to
  12867. mixing static and dynamic typing, including multi-language
  12868. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  12869. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  12870. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  12871. programmer controls the amount of static versus dynamic checking by
  12872. adding or removing type annotations on parameters and
  12873. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  12874. %
  12875. The concrete syntax of \LangGrad{} is defined in
  12876. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  12877. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  12878. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  12879. non-terminals that make type annotations optional. The return types
  12880. are not optional in the abstract syntax; the parser fills in
  12881. \code{Any} when the return type is not specified in the concrete
  12882. syntax.
  12883. \begin{figure}[tp]
  12884. \centering
  12885. \fbox{
  12886. \begin{minipage}{0.96\textwidth}
  12887. \small
  12888. \[
  12889. \begin{array}{lcl}
  12890. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  12891. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  12892. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12893. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  12894. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  12895. &\MID& \gray{\key{\#t} \MID \key{\#f}
  12896. \MID (\key{and}\;\Exp\;\Exp)
  12897. \MID (\key{or}\;\Exp\;\Exp)
  12898. \MID (\key{not}\;\Exp) } \\
  12899. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  12900. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  12901. (\key{vector-ref}\;\Exp\;\Int)} \\
  12902. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  12903. \MID (\Exp \; \Exp\ldots) } \\
  12904. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  12905. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  12906. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  12907. \MID \CBEGIN{\Exp\ldots}{\Exp}
  12908. \MID \CWHILE{\Exp}{\Exp} } \\
  12909. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  12910. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  12911. \end{array}
  12912. \]
  12913. \end{minipage}
  12914. }
  12915. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  12916. \label{fig:Rgrad-concrete-syntax}
  12917. \end{figure}
  12918. \begin{figure}[tp]
  12919. \centering
  12920. \fbox{
  12921. \begin{minipage}{0.96\textwidth}
  12922. \small
  12923. \[
  12924. \begin{array}{lcl}
  12925. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  12926. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  12927. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  12928. &\MID& \gray{ \BOOL{\itm{bool}}
  12929. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  12930. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  12931. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  12932. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  12933. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  12934. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  12935. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  12936. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12937. \end{array}
  12938. \]
  12939. \end{minipage}
  12940. }
  12941. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  12942. \label{fig:Rgrad-syntax}
  12943. \end{figure}
  12944. Both the type checker and the interpreter for \LangGrad{} require some
  12945. interesting changes to enable gradual typing, which we discuss in the
  12946. next two sections in the context of the \code{map-vec} example from
  12947. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  12948. revised the \code{map-vec} example, omitting the type annotations from
  12949. the \code{add1} function.
  12950. \begin{figure}[btp]
  12951. % gradual_test_9.rkt
  12952. \begin{lstlisting}
  12953. (define (map-vec [f : (Integer -> Integer)]
  12954. [v : (Vector Integer Integer)])
  12955. : (Vector Integer Integer)
  12956. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12957. (define (add1 x) (+ x 1))
  12958. (vector-ref (map-vec add1 (vector 0 41)) 1)
  12959. \end{lstlisting}
  12960. \caption{A partially-typed version of the \code{map-vec} example.}
  12961. \label{fig:gradual-map-vec}
  12962. \end{figure}
  12963. \section{Type Checking \LangGrad{} and \LangCast{}}
  12964. \label{sec:gradual-type-check}
  12965. The type checker for \LangGrad{} uses the \code{Any} type for missing
  12966. parameter and return types. For example, the \code{x} parameter of
  12967. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  12968. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  12969. consider the \code{+} operator inside \code{add1}. It expects both
  12970. arguments to have type \code{Integer}, but its first argument \code{x}
  12971. has type \code{Any}. In a gradually typed language, such differences
  12972. are allowed so long as the types are \emph{consistent}, that is, they
  12973. are equal except in places where there is an \code{Any} type. The type
  12974. \code{Any} is consistent with every other type.
  12975. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  12976. \begin{figure}[tbp]
  12977. \begin{lstlisting}
  12978. (define/public (consistent? t1 t2)
  12979. (match* (t1 t2)
  12980. [('Integer 'Integer) #t]
  12981. [('Boolean 'Boolean) #t]
  12982. [('Void 'Void) #t]
  12983. [('Any t2) #t]
  12984. [(t1 'Any) #t]
  12985. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  12986. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  12987. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  12988. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  12989. (consistent? rt1 rt2))]
  12990. [(other wise) #f]))
  12991. \end{lstlisting}
  12992. \caption{The consistency predicate on types.}
  12993. \label{fig:consistent}
  12994. \end{figure}
  12995. Returning to the \code{map-vec} example of
  12996. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  12997. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  12998. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  12999. because the two types are consistent. In particular, \code{->} is
  13000. equal to \code{->} and because \code{Any} is consistent with
  13001. \code{Integer}.
  13002. Next consider a program with an error, such as applying the
  13003. \code{map-vec} to a function that sometimes returns a Boolean, as
  13004. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  13005. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  13006. consistent with the type of parameter \code{f} of \code{map-vec}, that
  13007. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  13008. Integer)}. One might say that a gradual type checker is optimistic
  13009. in that it accepts programs that might execute without a runtime type
  13010. error.
  13011. %
  13012. Unfortunately, running this program with input \code{1} triggers an
  13013. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  13014. performs checking at runtime to ensure the integrity of the static
  13015. types, such as the \code{(Integer -> Integer)} annotation on parameter
  13016. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  13017. new \code{Cast} form that is inserted by the type checker. Thus, the
  13018. output of the type checker is a program in the \LangCast{} language, which
  13019. adds \code{Cast} to \LangLoop{}, as shown in
  13020. Figure~\ref{fig:Rgrad-prime-syntax}.
  13021. \begin{figure}[tp]
  13022. \centering
  13023. \fbox{
  13024. \begin{minipage}{0.96\textwidth}
  13025. \small
  13026. \[
  13027. \begin{array}{lcl}
  13028. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  13029. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13030. \end{array}
  13031. \]
  13032. \end{minipage}
  13033. }
  13034. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  13035. \label{fig:Rgrad-prime-syntax}
  13036. \end{figure}
  13037. \begin{figure}[tbp]
  13038. \begin{lstlisting}
  13039. (define (map-vec [f : (Integer -> Integer)]
  13040. [v : (Vector Integer Integer)])
  13041. : (Vector Integer Integer)
  13042. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13043. (define (add1 x) (+ x 1))
  13044. (define (true) #t)
  13045. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  13046. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  13047. \end{lstlisting}
  13048. \caption{A variant of the \code{map-vec} example with an error.}
  13049. \label{fig:map-vec-maybe-add1}
  13050. \end{figure}
  13051. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  13052. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  13053. inserted every time the type checker sees two types that are
  13054. consistent but not equal. In the \code{add1} function, \code{x} is
  13055. cast to \code{Integer} and the result of the \code{+} is cast to
  13056. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  13057. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  13058. \begin{figure}[btp]
  13059. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13060. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13061. : (Vector Integer Integer)
  13062. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13063. (define (add1 [x : Any]) : Any
  13064. (cast (+ (cast x Any Integer) 1) Integer Any))
  13065. (define (true) : Any (cast #t Boolean Any))
  13066. (define (maybe-add1 [x : Any]) : Any
  13067. (if (eq? 0 (read)) (add1 x) (true)))
  13068. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  13069. (vector 0 41)) 0)
  13070. \end{lstlisting}
  13071. \caption{Output of type checking \code{map-vec}
  13072. and \code{maybe-add1}.}
  13073. \label{fig:map-vec-cast}
  13074. \end{figure}
  13075. The type checker for \LangGrad{} is defined in
  13076. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  13077. and \ref{fig:type-check-Rgradual-3}.
  13078. \begin{figure}[tbp]
  13079. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13080. (define type-check-gradual_class
  13081. (class type-check-Rwhile_class
  13082. (super-new)
  13083. (inherit operator-types type-predicates)
  13084. (define/override (type-check-exp env)
  13085. (lambda (e)
  13086. (define recur (type-check-exp env))
  13087. (match e
  13088. [(Prim 'vector-length (list e1))
  13089. (define-values (e1^ t) (recur e1))
  13090. (match t
  13091. [`(Vector ,ts ...)
  13092. (values (Prim 'vector-length (list e1^)) 'Integer)]
  13093. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  13094. [(Prim 'vector-ref (list e1 e2))
  13095. (define-values (e1^ t1) (recur e1))
  13096. (define-values (e2^ t2) (recur e2))
  13097. (check-consistent? t2 'Integer e)
  13098. (match t1
  13099. [`(Vector ,ts ...)
  13100. (match e2^
  13101. [(Int i)
  13102. (unless (and (0 . <= . i) (i . < . (length ts)))
  13103. (error 'type-check "invalid index ~a in ~a" i e))
  13104. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  13105. [else (define e1^^ (make-cast e1^ t1 'Any))
  13106. (define e2^^ (make-cast e2^ t2 'Integer))
  13107. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  13108. ['Any
  13109. (define e2^^ (make-cast e2^ t2 'Integer))
  13110. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  13111. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  13112. [(Prim 'vector-set! (list e1 e2 e3) )
  13113. (define-values (e1^ t1) (recur e1))
  13114. (define-values (e2^ t2) (recur e2))
  13115. (define-values (e3^ t3) (recur e3))
  13116. (check-consistent? t2 'Integer e)
  13117. (match t1
  13118. [`(Vector ,ts ...)
  13119. (match e2^
  13120. [(Int i)
  13121. (unless (and (0 . <= . i) (i . < . (length ts)))
  13122. (error 'type-check "invalid index ~a in ~a" i e))
  13123. (check-consistent? (list-ref ts i) t3 e)
  13124. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  13125. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  13126. [else
  13127. (define e1^^ (make-cast e1^ t1 'Any))
  13128. (define e2^^ (make-cast e2^ t2 'Integer))
  13129. (define e3^^ (make-cast e3^ t3 'Any))
  13130. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  13131. ['Any
  13132. (define e2^^ (make-cast e2^ t2 'Integer))
  13133. (define e3^^ (make-cast e3^ t3 'Any))
  13134. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  13135. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  13136. \end{lstlisting}
  13137. \caption{Type checker for the \LangGrad{} language, part 1.}
  13138. \label{fig:type-check-Rgradual-1}
  13139. \end{figure}
  13140. \begin{figure}[tbp]
  13141. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13142. [(Prim 'eq? (list e1 e2))
  13143. (define-values (e1^ t1) (recur e1))
  13144. (define-values (e2^ t2) (recur e2))
  13145. (check-consistent? t1 t2 e)
  13146. (define T (meet t1 t2))
  13147. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  13148. 'Boolean)]
  13149. [(Prim 'not (list e1))
  13150. (define-values (e1^ t1) (recur e1))
  13151. (match t1
  13152. ['Any
  13153. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  13154. (Bool #t) (Bool #f)))]
  13155. [else
  13156. (define-values (t-ret new-es^)
  13157. (type-check-op 'not (list t1) (list e1^) e))
  13158. (values (Prim 'not new-es^) t-ret)])]
  13159. [(Prim 'and (list e1 e2))
  13160. (recur (If e1 e2 (Bool #f)))]
  13161. [(Prim 'or (list e1 e2))
  13162. (define tmp (gensym 'tmp))
  13163. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  13164. [(Prim op es)
  13165. #:when (not (set-member? explicit-prim-ops op))
  13166. (define-values (new-es ts)
  13167. (for/lists (exprs types) ([e es])
  13168. (recur e)))
  13169. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  13170. (values (Prim op new-es^) t-ret)]
  13171. [(If e1 e2 e3)
  13172. (define-values (e1^ T1) (recur e1))
  13173. (define-values (e2^ T2) (recur e2))
  13174. (define-values (e3^ T3) (recur e3))
  13175. (check-consistent? T2 T3 e)
  13176. (match T1
  13177. ['Boolean
  13178. (define Tif (join T2 T3))
  13179. (values (If e1^ (make-cast e2^ T2 Tif)
  13180. (make-cast e3^ T3 Tif)) Tif)]
  13181. ['Any
  13182. (define Tif (meet T2 T3))
  13183. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  13184. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  13185. Tif)]
  13186. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  13187. [(HasType e1 T)
  13188. (define-values (e1^ T1) (recur e1))
  13189. (check-consistent? T1 T)
  13190. (values (make-cast e1^ T1 T) T)]
  13191. [(SetBang x e1)
  13192. (define-values (e1^ T1) (recur e1))
  13193. (define varT (dict-ref env x))
  13194. (check-consistent? T1 varT e)
  13195. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  13196. [(WhileLoop e1 e2)
  13197. (define-values (e1^ T1) (recur e1))
  13198. (check-consistent? T1 'Boolean e)
  13199. (define-values (e2^ T2) ((type-check-exp env) e2))
  13200. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  13201. \end{lstlisting}
  13202. \caption{Type checker for the \LangGrad{} language, part 2.}
  13203. \label{fig:type-check-Rgradual-2}
  13204. \end{figure}
  13205. \begin{figure}[tbp]
  13206. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13207. [(Apply e1 e2s)
  13208. (define-values (e1^ T1) (recur e1))
  13209. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  13210. (match T1
  13211. [`(,T1ps ... -> ,T1rt)
  13212. (for ([T2 T2s] [Tp T1ps])
  13213. (check-consistent? T2 Tp e))
  13214. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  13215. (make-cast e2 src tgt)))
  13216. (values (Apply e1^ e2s^^) T1rt)]
  13217. [`Any
  13218. (define e1^^ (make-cast e1^ 'Any
  13219. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  13220. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  13221. (make-cast e2 src 'Any)))
  13222. (values (Apply e1^^ e2s^^) 'Any)]
  13223. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  13224. [(Lambda params Tr e1)
  13225. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  13226. (match p
  13227. [`[,x : ,T] (values x T)]
  13228. [(? symbol? x) (values x 'Any)])))
  13229. (define-values (e1^ T1)
  13230. ((type-check-exp (append (map cons xs Ts) env)) e1))
  13231. (check-consistent? Tr T1 e)
  13232. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  13233. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  13234. [else ((super type-check-exp env) e)]
  13235. )))
  13236. \end{lstlisting}
  13237. \caption{Type checker for the \LangGrad{} language, part 3.}
  13238. \label{fig:type-check-Rgradual-3}
  13239. \end{figure}
  13240. \begin{figure}[tbp]
  13241. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13242. (define/public (join t1 t2)
  13243. (match* (t1 t2)
  13244. [('Integer 'Integer) 'Integer]
  13245. [('Boolean 'Boolean) 'Boolean]
  13246. [('Void 'Void) 'Void]
  13247. [('Any t2) t2]
  13248. [(t1 'Any) t1]
  13249. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  13250. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  13251. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  13252. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  13253. -> ,(join rt1 rt2))]))
  13254. (define/public (meet t1 t2)
  13255. (match* (t1 t2)
  13256. [('Integer 'Integer) 'Integer]
  13257. [('Boolean 'Boolean) 'Boolean]
  13258. [('Void 'Void) 'Void]
  13259. [('Any t2) 'Any]
  13260. [(t1 'Any) 'Any]
  13261. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  13262. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  13263. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  13264. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  13265. -> ,(meet rt1 rt2))]))
  13266. (define/public (make-cast e src tgt)
  13267. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  13268. (define/public (check-consistent? t1 t2 e)
  13269. (unless (consistent? t1 t2)
  13270. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  13271. (define/override (type-check-op op arg-types args e)
  13272. (match (dict-ref (operator-types) op)
  13273. [`(,param-types . ,return-type)
  13274. (for ([at arg-types] [pt param-types])
  13275. (check-consistent? at pt e))
  13276. (values return-type
  13277. (for/list ([e args] [s arg-types] [t param-types])
  13278. (make-cast e s t)))]
  13279. [else (error 'type-check-op "unrecognized ~a" op)]))
  13280. (define explicit-prim-ops
  13281. (set-union
  13282. (type-predicates)
  13283. (set 'procedure-arity 'eq?
  13284. 'vector 'vector-length 'vector-ref 'vector-set!
  13285. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  13286. (define/override (fun-def-type d)
  13287. (match d
  13288. [(Def f params rt info body)
  13289. (define ps
  13290. (for/list ([p params])
  13291. (match p
  13292. [`[,x : ,T] T]
  13293. [(? symbol?) 'Any]
  13294. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  13295. `(,@ps -> ,rt)]
  13296. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  13297. \end{lstlisting}
  13298. \caption{Auxiliary functions for type checking \LangGrad{}.}
  13299. \label{fig:type-check-Rgradual-aux}
  13300. \end{figure}
  13301. \clearpage
  13302. \section{Interpreting \LangCast{}}
  13303. \label{sec:interp-casts}
  13304. The runtime behavior of first-order casts is straightforward, that is,
  13305. casts involving simple types such as \code{Integer} and
  13306. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  13307. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  13308. puts the integer into a tagged value
  13309. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  13310. \code{Integer} is accomplished with the \code{Project} operator, that
  13311. is, by checking the value's tag and either retrieving the underlying
  13312. integer or signaling an error if it the tag is not the one for
  13313. integers (Figure~\ref{fig:apply-project}).
  13314. %
  13315. Things get more interesting for higher-order casts, that is, casts
  13316. involving function or vector types.
  13317. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  13318. Any)} to \code{(Integer -> Integer)}. When a function flows through
  13319. this cast at runtime, we can't know in general whether the function
  13320. will always return an integer.\footnote{Predicting the return value of
  13321. a function is equivalent to the halting problem, which is
  13322. undecidable.} The \LangCast{} interpreter therefore delays the checking
  13323. of the cast until the function is applied. This is accomplished by
  13324. wrapping \code{maybe-add1} in a new function that casts its parameter
  13325. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  13326. casts the return value from \code{Any} to \code{Integer}.
  13327. Turning our attention to casts involving vector types, we consider the
  13328. example in Figure~\ref{fig:map-vec-bang} that defines a
  13329. partially-typed version of \code{map-vec} whose parameter \code{v} has
  13330. type \code{(Vector Any Any)} and that updates \code{v} in place
  13331. instead of returning a new vector. So we name this function
  13332. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  13333. the type checker inserts a cast from \code{(Vector Integer Integer)}
  13334. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  13335. cast between vector types would be a build a new vector whose elements
  13336. are the result of casting each of the original elements to the
  13337. appropriate target type. However, this approach is only valid for
  13338. immutable vectors; and our vectors are mutable. In the example of
  13339. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  13340. the updates inside of \code{map-vec!} would happen to the new vector
  13341. and not the original one.
  13342. \begin{figure}[tbp]
  13343. % gradual_test_11.rkt
  13344. \begin{lstlisting}
  13345. (define (map-vec! [f : (Any -> Any)]
  13346. [v : (Vector Any Any)]) : Void
  13347. (begin
  13348. (vector-set! v 0 (f (vector-ref v 0)))
  13349. (vector-set! v 1 (f (vector-ref v 1)))))
  13350. (define (add1 x) (+ x 1))
  13351. (let ([v (vector 0 41)])
  13352. (begin (map-vec! add1 v) (vector-ref v 1)))
  13353. \end{lstlisting}
  13354. \caption{An example involving casts on vectors.}
  13355. \label{fig:map-vec-bang}
  13356. \end{figure}
  13357. Instead the interpreter needs to create a new kind of value, a
  13358. \emph{vector proxy}, that intercepts every vector operation. On a
  13359. read, the proxy reads from the underlying vector and then applies a
  13360. cast to the resulting value. On a write, the proxy casts the argument
  13361. value and then performs the write to the underlying vector. For the
  13362. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  13363. \code{0} from \code{Integer} to \code{Any}. For the first
  13364. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  13365. to \code{Integer}.
  13366. The final category of cast that we need to consider are casts between
  13367. the \code{Any} type and either a function or a vector
  13368. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  13369. in which parameter \code{v} does not have a type annotation, so it is
  13370. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  13371. type \code{(Vector Integer Integer)} so the type checker inserts a
  13372. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  13373. thought is to use \code{Inject}, but that doesn't work because
  13374. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  13375. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  13376. to \code{Any}.
  13377. \begin{figure}[tbp]
  13378. \begin{lstlisting}
  13379. (define (map-vec! [f : (Any -> Any)] v) : Void
  13380. (begin
  13381. (vector-set! v 0 (f (vector-ref v 0)))
  13382. (vector-set! v 1 (f (vector-ref v 1)))))
  13383. (define (add1 x) (+ x 1))
  13384. (let ([v (vector 0 41)])
  13385. (begin (map-vec! add1 v) (vector-ref v 1)))
  13386. \end{lstlisting}
  13387. \caption{Casting a vector to \code{Any}.}
  13388. \label{fig:map-vec-any}
  13389. \end{figure}
  13390. The \LangCast{} interpreter uses an auxiliary function named
  13391. \code{apply-cast} to cast a value from a source type to a target type,
  13392. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  13393. of the kinds of casts that we've discussed in this section.
  13394. \begin{figure}[tbp]
  13395. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13396. (define/public (apply-cast v s t)
  13397. (match* (s t)
  13398. [(t1 t2) #:when (equal? t1 t2) v]
  13399. [('Any t2)
  13400. (match t2
  13401. [`(,ts ... -> ,rt)
  13402. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  13403. (define v^ (apply-project v any->any))
  13404. (apply-cast v^ any->any `(,@ts -> ,rt))]
  13405. [`(Vector ,ts ...)
  13406. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  13407. (define v^ (apply-project v vec-any))
  13408. (apply-cast v^ vec-any `(Vector ,@ts))]
  13409. [else (apply-project v t2)])]
  13410. [(t1 'Any)
  13411. (match t1
  13412. [`(,ts ... -> ,rt)
  13413. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  13414. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  13415. (apply-inject v^ (any-tag any->any))]
  13416. [`(Vector ,ts ...)
  13417. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  13418. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  13419. (apply-inject v^ (any-tag vec-any))]
  13420. [else (apply-inject v (any-tag t1))])]
  13421. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  13422. (define x (gensym 'x))
  13423. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  13424. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  13425. (define cast-writes
  13426. (for/list ([t1 ts1] [t2 ts2])
  13427. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  13428. `(vector-proxy ,(vector v (apply vector cast-reads)
  13429. (apply vector cast-writes)))]
  13430. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  13431. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  13432. `(function ,xs ,(Cast
  13433. (Apply (Value v)
  13434. (for/list ([x xs][t1 ts1][t2 ts2])
  13435. (Cast (Var x) t2 t1)))
  13436. rt1 rt2) ())]
  13437. ))
  13438. \end{lstlisting}
  13439. \caption{The \code{apply-cast} auxiliary method.}
  13440. \label{fig:apply-cast}
  13441. \end{figure}
  13442. The interpreter for \LangCast{} is defined in
  13443. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  13444. dispatching to \code{apply-cast}. To handle the addition of vector
  13445. proxies, we update the vector primitives in \code{interp-op} using the
  13446. functions in Figure~\ref{fig:guarded-vector}.
  13447. \begin{figure}[tbp]
  13448. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13449. (define interp-Rcast_class
  13450. (class interp-Rwhile_class
  13451. (super-new)
  13452. (inherit apply-fun apply-inject apply-project)
  13453. (define/override (interp-op op)
  13454. (match op
  13455. ['vector-length guarded-vector-length]
  13456. ['vector-ref guarded-vector-ref]
  13457. ['vector-set! guarded-vector-set!]
  13458. ['any-vector-ref (lambda (v i)
  13459. (match v [`(tagged ,v^ ,tg)
  13460. (guarded-vector-ref v^ i)]))]
  13461. ['any-vector-set! (lambda (v i a)
  13462. (match v [`(tagged ,v^ ,tg)
  13463. (guarded-vector-set! v^ i a)]))]
  13464. ['any-vector-length (lambda (v)
  13465. (match v [`(tagged ,v^ ,tg)
  13466. (guarded-vector-length v^)]))]
  13467. [else (super interp-op op)]
  13468. ))
  13469. (define/override ((interp-exp env) e)
  13470. (define (recur e) ((interp-exp env) e))
  13471. (match e
  13472. [(Value v) v]
  13473. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  13474. [else ((super interp-exp env) e)]))
  13475. ))
  13476. (define (interp-Rcast p)
  13477. (send (new interp-Rcast_class) interp-program p))
  13478. \end{lstlisting}
  13479. \caption{The interpreter for \LangCast{}.}
  13480. \label{fig:interp-Rcast}
  13481. \end{figure}
  13482. \begin{figure}[tbp]
  13483. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13484. (define (guarded-vector-ref vec i)
  13485. (match vec
  13486. [`(vector-proxy ,proxy)
  13487. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  13488. (define rd (vector-ref (vector-ref proxy 1) i))
  13489. (apply-fun rd (list val) 'guarded-vector-ref)]
  13490. [else (vector-ref vec i)]))
  13491. (define (guarded-vector-set! vec i arg)
  13492. (match vec
  13493. [`(vector-proxy ,proxy)
  13494. (define wr (vector-ref (vector-ref proxy 2) i))
  13495. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  13496. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  13497. [else (vector-set! vec i arg)]))
  13498. (define (guarded-vector-length vec)
  13499. (match vec
  13500. [`(vector-proxy ,proxy)
  13501. (guarded-vector-length (vector-ref proxy 0))]
  13502. [else (vector-length vec)]))
  13503. \end{lstlisting}
  13504. \caption{The guarded-vector auxiliary functions.}
  13505. \label{fig:guarded-vector}
  13506. \end{figure}
  13507. \section{Lower Casts}
  13508. \label{sec:lower-casts}
  13509. The next step in the journey towards x86 is the \code{lower-casts}
  13510. pass that translates the casts in \LangCast{} to the lower-level
  13511. \code{Inject} and \code{Project} operators and a new operator for
  13512. creating vector proxies, extending the \LangLoop{} language to create
  13513. \LangProxy{}. We recommend creating an auxiliary function named
  13514. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  13515. and a target type, and translates it to expression in \LangProxy{} that has
  13516. the same behavior as casting the expression from the source to the
  13517. target type in the interpreter.
  13518. The \code{lower-cast} function can follow a code structure similar to
  13519. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  13520. the interpreter for \LangCast{} because it must handle the same cases as
  13521. \code{apply-cast} and it needs to mimic the behavior of
  13522. \code{apply-cast}. The most interesting cases are those concerning the
  13523. casts between two vector types and between two function types.
  13524. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  13525. type to another vector type is accomplished by creating a proxy that
  13526. intercepts the operations on the underlying vector. Here we make the
  13527. creation of the proxy explicit with the \code{vector-proxy} primitive
  13528. operation. It takes three arguments, the first is an expression for
  13529. the vector, the second is a vector of functions for casting an element
  13530. that is being read from the vector, and the third is a vector of
  13531. functions for casting an element that is being written to the vector.
  13532. You can create the functions using \code{Lambda}. Also, as we shall
  13533. see in the next section, we need to differentiate these vectors from
  13534. the user-created ones, so we recommend using a new primitive operator
  13535. named \code{raw-vector} instead of \code{vector} to create these
  13536. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  13537. the output of \code{lower-casts} on the example in
  13538. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  13539. integers to a vector of \code{Any}.
  13540. \begin{figure}[tbp]
  13541. \begin{lstlisting}
  13542. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  13543. (begin
  13544. (vector-set! v 0 (f (vector-ref v 0)))
  13545. (vector-set! v 1 (f (vector-ref v 1)))))
  13546. (define (add1 [x : Any]) : Any
  13547. (inject (+ (project x Integer) 1) Integer))
  13548. (let ([v (vector 0 41)])
  13549. (begin
  13550. (map-vec! add1 (vector-proxy v
  13551. (raw-vector (lambda: ([x9 : Integer]) : Any
  13552. (inject x9 Integer))
  13553. (lambda: ([x9 : Integer]) : Any
  13554. (inject x9 Integer)))
  13555. (raw-vector (lambda: ([x9 : Any]) : Integer
  13556. (project x9 Integer))
  13557. (lambda: ([x9 : Any]) : Integer
  13558. (project x9 Integer)))))
  13559. (vector-ref v 1)))
  13560. \end{lstlisting}
  13561. \caption{Output of \code{lower-casts} on the example in
  13562. Figure~\ref{fig:map-vec-bang}.}
  13563. \label{fig:map-vec-bang-lower-cast}
  13564. \end{figure}
  13565. A cast from one function type to another function type is accomplished
  13566. by generating a \code{Lambda} whose parameter and return types match
  13567. the target function type. The body of the \code{Lambda} should cast
  13568. the parameters from the target type to the source type (yes,
  13569. backwards! functions are contravariant\index{subject}{contravariant} in the
  13570. parameters), then call the underlying function, and finally cast the
  13571. result from the source return type to the target return type.
  13572. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  13573. \code{lower-casts} pass on the \code{map-vec} example in
  13574. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  13575. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  13576. \begin{figure}[tbp]
  13577. \begin{lstlisting}
  13578. (define (map-vec [f : (Integer -> Integer)]
  13579. [v : (Vector Integer Integer)])
  13580. : (Vector Integer Integer)
  13581. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13582. (define (add1 [x : Any]) : Any
  13583. (inject (+ (project x Integer) 1) Integer))
  13584. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  13585. (project (add1 (inject x9 Integer)) Integer))
  13586. (vector 0 41)) 1)
  13587. \end{lstlisting}
  13588. \caption{Output of \code{lower-casts} on the example in
  13589. Figure~\ref{fig:gradual-map-vec}.}
  13590. \label{fig:map-vec-lower-cast}
  13591. \end{figure}
  13592. \section{Differentiate Proxies}
  13593. \label{sec:differentiate-proxies}
  13594. So far the job of differentiating vectors and vector proxies has been
  13595. the job of the interpreter. For example, the interpreter for \LangCast{}
  13596. implements \code{vector-ref} using the \code{guarded-vector-ref}
  13597. function in Figure~\ref{fig:guarded-vector}. In the
  13598. \code{differentiate-proxies} pass we shift this responsibility to the
  13599. generated code.
  13600. We begin by designing the output language $R^p_8$. In
  13601. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  13602. proxies. In $R^p_8$ we return the \code{Vector} type to
  13603. its original meaning, as the type of real vectors, and we introduce a
  13604. new type, \code{PVector}, whose values can be either real vectors or
  13605. vector proxies. This new type comes with a suite of new primitive
  13606. operations for creating and using values of type \code{PVector}. We
  13607. don't need to introduce a new type to represent vector proxies. A
  13608. proxy is represented by a vector containing three things: 1) the
  13609. underlying vector, 2) a vector of functions for casting elements that
  13610. are read from the vector, and 3) a vector of functions for casting
  13611. values to be written to the vector. So we define the following
  13612. abbreviation for the type of a vector proxy:
  13613. \[
  13614. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  13615. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  13616. \to (\key{PVector}~ T' \ldots)
  13617. \]
  13618. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  13619. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  13620. %
  13621. Next we describe each of the new primitive operations.
  13622. \begin{description}
  13623. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  13624. (\key{PVector} $T \ldots$)]\ \\
  13625. %
  13626. This operation brands a vector as a value of the \code{PVector} type.
  13627. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  13628. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  13629. %
  13630. This operation brands a vector proxy as value of the \code{PVector} type.
  13631. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  13632. \code{Boolean}] \ \\
  13633. %
  13634. returns true if the value is a vector proxy and false if it is a
  13635. real vector.
  13636. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  13637. (\key{Vector} $T \ldots$)]\ \\
  13638. %
  13639. Assuming that the input is a vector (and not a proxy), this
  13640. operation returns the vector.
  13641. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  13642. $\to$ \code{Boolean}]\ \\
  13643. %
  13644. Given a vector proxy, this operation returns the length of the
  13645. underlying vector.
  13646. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  13647. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  13648. %
  13649. Given a vector proxy, this operation returns the $i$th element of
  13650. the underlying vector.
  13651. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  13652. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  13653. proxy, this operation writes a value to the $i$th element of the
  13654. underlying vector.
  13655. \end{description}
  13656. Now to discuss the translation that differentiates vectors from
  13657. proxies. First, every type annotation in the program must be
  13658. translated (recursively) to replace \code{Vector} with \code{PVector}.
  13659. Next, we must insert uses of \code{PVector} operations in the
  13660. appropriate places. For example, we wrap every vector creation with an
  13661. \code{inject-vector}.
  13662. \begin{lstlisting}
  13663. (vector |$e_1 \ldots e_n$|)
  13664. |$\Rightarrow$|
  13665. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  13666. \end{lstlisting}
  13667. The \code{raw-vector} operator that we introduced in the previous
  13668. section does not get injected.
  13669. \begin{lstlisting}
  13670. (raw-vector |$e_1 \ldots e_n$|)
  13671. |$\Rightarrow$|
  13672. (vector |$e'_1 \ldots e'_n$|)
  13673. \end{lstlisting}
  13674. The \code{vector-proxy} primitive translates as follows.
  13675. \begin{lstlisting}
  13676. (vector-proxy |$e_1~e_2~e_3$|)
  13677. |$\Rightarrow$|
  13678. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  13679. \end{lstlisting}
  13680. We translate the vector operations into conditional expressions that
  13681. check whether the value is a proxy and then dispatch to either the
  13682. appropriate proxy vector operation or the regular vector operation.
  13683. For example, the following is the translation for \code{vector-ref}.
  13684. \begin{lstlisting}
  13685. (vector-ref |$e_1$| |$i$|)
  13686. |$\Rightarrow$|
  13687. (let ([|$v~e_1$|])
  13688. (if (proxy? |$v$|)
  13689. (proxy-vector-ref |$v$| |$i$|)
  13690. (vector-ref (project-vector |$v$|) |$i$|)
  13691. \end{lstlisting}
  13692. Note in the case of a real vector, we must apply \code{project-vector}
  13693. before the \code{vector-ref}.
  13694. \section{Reveal Casts}
  13695. \label{sec:reveal-casts-gradual}
  13696. Recall that the \code{reveal-casts} pass
  13697. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  13698. \code{Inject} and \code{Project} into lower-level operations. In
  13699. particular, \code{Project} turns into a conditional expression that
  13700. inspects the tag and retrieves the underlying value. Here we need to
  13701. augment the translation of \code{Project} to handle the situation when
  13702. the target type is \code{PVector}. Instead of using
  13703. \code{vector-length} we need to use \code{proxy-vector-length}.
  13704. \begin{lstlisting}
  13705. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  13706. |$\Rightarrow$|
  13707. (let |$\itm{tmp}$| |$e'$|
  13708. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  13709. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  13710. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  13711. (exit)))
  13712. \end{lstlisting}
  13713. \section{Closure Conversion}
  13714. \label{sec:closure-conversion-gradual}
  13715. The closure conversion pass only requires one minor adjustment. The
  13716. auxiliary function that translates type annotations needs to be
  13717. updated to handle the \code{PVector} type.
  13718. \section{Explicate Control}
  13719. \label{sec:explicate-control-gradual}
  13720. Update the \code{explicate\_control} pass to handle the new primitive
  13721. operations on the \code{PVector} type.
  13722. \section{Select Instructions}
  13723. \label{sec:select-instructions-gradual}
  13724. Recall that the \code{select-instructions} pass is responsible for
  13725. lowering the primitive operations into x86 instructions. So we need
  13726. to translate the new \code{PVector} operations to x86. To do so, the
  13727. first question we need to answer is how will we differentiate the two
  13728. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  13729. We need just one bit to accomplish this, and use the bit in position
  13730. $57$ of the 64-bit tag at the front of every vector (see
  13731. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  13732. for \code{inject-vector} we leave it that way.
  13733. \begin{lstlisting}
  13734. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  13735. |$\Rightarrow$|
  13736. movq |$e'_1$|, |$\itm{lhs'}$|
  13737. \end{lstlisting}
  13738. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  13739. \begin{lstlisting}
  13740. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  13741. |$\Rightarrow$|
  13742. movq |$e'_1$|, %r11
  13743. movq |$(1 << 57)$|, %rax
  13744. orq 0(%r11), %rax
  13745. movq %rax, 0(%r11)
  13746. movq %r11, |$\itm{lhs'}$|
  13747. \end{lstlisting}
  13748. The \code{proxy?} operation consumes the information so carefully
  13749. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  13750. isolates the $57$th bit to tell whether the value is a real vector or
  13751. a proxy.
  13752. \begin{lstlisting}
  13753. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  13754. |$\Rightarrow$|
  13755. movq |$e_1'$|, %r11
  13756. movq 0(%r11), %rax
  13757. sarq $57, %rax
  13758. andq $1, %rax
  13759. movq %rax, |$\itm{lhs'}$|
  13760. \end{lstlisting}
  13761. The \code{project-vector} operation is straightforward to translate,
  13762. so we leave it up to the reader.
  13763. Regarding the \code{proxy-vector} operations, the runtime provides
  13764. procedures that implement them (they are recursive functions!) so
  13765. here we simply need to translate these vector operations into the
  13766. appropriate function call. For example, here is the translation for
  13767. \code{proxy-vector-ref}.
  13768. \begin{lstlisting}
  13769. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  13770. |$\Rightarrow$|
  13771. movq |$e_1'$|, %rdi
  13772. movq |$e_2'$|, %rsi
  13773. callq proxy_vector_ref
  13774. movq %rax, |$\itm{lhs'}$|
  13775. \end{lstlisting}
  13776. We have another batch of vector operations to deal with, those for the
  13777. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  13778. \code{any-vector-ref} when there is a \code{vector-ref} on something
  13779. of type \code{Any}, and similarly for \code{any-vector-set!} and
  13780. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  13781. Section~\ref{sec:select-Rany} we selected instructions for these
  13782. operations based on the idea that the underlying value was a real
  13783. vector. But in the current setting, the underlying value is of type
  13784. \code{PVector}. So \code{any-vector-ref} can be translates to
  13785. pseudo-x86 as follows. We begin by projecting the underlying value out
  13786. of the tagged value and then call the \code{proxy\_vector\_ref}
  13787. procedure in the runtime.
  13788. \begin{lstlisting}
  13789. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  13790. movq |$\neg 111$|, %rdi
  13791. andq |$e_1'$|, %rdi
  13792. movq |$e_2'$|, %rsi
  13793. callq proxy_vector_ref
  13794. movq %rax, |$\itm{lhs'}$|
  13795. \end{lstlisting}
  13796. The \code{any-vector-set!} and \code{any-vector-length} operators can
  13797. be translated in a similar way.
  13798. \begin{exercise}\normalfont
  13799. Implement a compiler for the gradually-typed \LangGrad{} language by
  13800. extending and adapting your compiler for \LangLoop{}. Create 10 new
  13801. partially-typed test programs. In addition to testing with these
  13802. new programs, also test your compiler on all the tests for \LangLoop{}
  13803. and tests for \LangDyn{}. Sometimes you may get a type checking error
  13804. on the \LangDyn{} programs but you can adapt them by inserting
  13805. a cast to the \code{Any} type around each subexpression
  13806. causing a type error. While \LangDyn{} doesn't have explicit casts,
  13807. you can induce one by wrapping the subexpression \code{e}
  13808. with a call to an un-annotated identity function, like this:
  13809. \code{((lambda (x) x) e)}.
  13810. \end{exercise}
  13811. \begin{figure}[p]
  13812. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13813. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  13814. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  13815. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  13816. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  13817. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  13818. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  13819. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  13820. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  13821. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  13822. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  13823. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  13824. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  13825. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  13826. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  13827. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13828. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13829. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13830. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13831. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13832. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13833. \path[->,bend right=15] (Rgradual) edge [above] node
  13834. {\ttfamily\footnotesize type-check} (Rgradualp);
  13835. \path[->,bend right=15] (Rgradualp) edge [above] node
  13836. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  13837. \path[->,bend right=15] (Rwhilepp) edge [right] node
  13838. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  13839. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  13840. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  13841. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  13842. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  13843. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  13844. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  13845. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  13846. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  13847. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  13848. {\ttfamily\footnotesize convert-assignments} (F1-1);
  13849. \path[->,bend left=15] (F1-1) edge [below] node
  13850. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  13851. \path[->,bend right=15] (F1-2) edge [above] node
  13852. {\ttfamily\footnotesize limit-fun.} (F1-3);
  13853. \path[->,bend right=15] (F1-3) edge [above] node
  13854. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  13855. \path[->,bend right=15] (F1-4) edge [above] node
  13856. {\ttfamily\footnotesize remove-complex.} (F1-5);
  13857. \path[->,bend right=15] (F1-5) edge [right] node
  13858. {\ttfamily\footnotesize explicate-control} (C3-2);
  13859. \path[->,bend left=15] (C3-2) edge [left] node
  13860. {\ttfamily\footnotesize select-instr.} (x86-2);
  13861. \path[->,bend right=15] (x86-2) edge [left] node
  13862. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  13863. \path[->,bend right=15] (x86-2-1) edge [below] node
  13864. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  13865. \path[->,bend right=15] (x86-2-2) edge [left] node
  13866. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  13867. \path[->,bend left=15] (x86-3) edge [above] node
  13868. {\ttfamily\footnotesize patch-instr.} (x86-4);
  13869. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  13870. \end{tikzpicture}
  13871. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  13872. \label{fig:Rgradual-passes}
  13873. \end{figure}
  13874. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  13875. for the compilation of \LangGrad{}.
  13876. \section{Further Reading}
  13877. This chapter just scratches the surface of gradual typing. The basic
  13878. approach described here is missing two key ingredients that one would
  13879. want in a implementation of gradual typing: blame
  13880. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  13881. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  13882. problem addressed by blame tracking is that when a cast on a
  13883. higher-order value fails, it often does so at a point in the program
  13884. that is far removed from the original cast. Blame tracking is a
  13885. technique for propagating extra information through casts and proxies
  13886. so that when a cast fails, the error message can point back to the
  13887. original location of the cast in the source program.
  13888. The problem addressed by space-efficient casts also relates to
  13889. higher-order casts. It turns out that in partially typed programs, a
  13890. function or vector can flow through very-many casts at runtime. With
  13891. the approach described in this chapter, each cast adds another
  13892. \code{lambda} wrapper or a vector proxy. Not only does this take up
  13893. considerable space, but it also makes the function calls and vector
  13894. operations slow. For example, a partially-typed version of quicksort
  13895. could, in the worst case, build a chain of proxies of length $O(n)$
  13896. around the vector, changing the overall time complexity of the
  13897. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  13898. solution to this problem by representing casts using the coercion
  13899. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  13900. long chains of proxies by compressing them into a concise normal
  13901. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  13902. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  13903. the Grift compiler.
  13904. \begin{center}
  13905. \url{https://github.com/Gradual-Typing/Grift}
  13906. \end{center}
  13907. There are also interesting interactions between gradual typing and
  13908. other language features, such as parametetric polymorphism,
  13909. information-flow types, and type inference, to name a few. We
  13910. recommend the reader to the online gradual typing bibliography:
  13911. \begin{center}
  13912. \url{http://samth.github.io/gradual-typing-bib/}
  13913. \end{center}
  13914. % TODO: challenge problem:
  13915. % type analysis and type specialization?
  13916. % coercions?
  13917. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13918. \chapter{Parametric Polymorphism}
  13919. \label{ch:Rpoly}
  13920. \index{subject}{parametric polymorphism}
  13921. \index{subject}{generics}
  13922. This chapter studies the compilation of parametric
  13923. polymorphism\index{subject}{parametric polymorphism}
  13924. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  13925. Racket. Parametric polymorphism enables improved code reuse by
  13926. parameterizing functions and data structures with respect to the types
  13927. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  13928. revisits the \code{map-vec} example but this time gives it a more
  13929. fitting type. This \code{map-vec} function is parameterized with
  13930. respect to the element type of the vector. The type of \code{map-vec}
  13931. is the following polymorphic type as specified by the \code{All} and
  13932. the type parameter \code{a}.
  13933. \begin{lstlisting}
  13934. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  13935. \end{lstlisting}
  13936. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  13937. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  13938. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  13939. \code{a}, but we could have just as well applied \code{map-vec} to a
  13940. vector of Booleans (and a function on Booleans).
  13941. \begin{figure}[tbp]
  13942. % poly_test_2.rkt
  13943. \begin{lstlisting}
  13944. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  13945. (define (map-vec f v)
  13946. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13947. (define (add1 [x : Integer]) : Integer (+ x 1))
  13948. (vector-ref (map-vec add1 (vector 0 41)) 1)
  13949. \end{lstlisting}
  13950. \caption{The \code{map-vec} example using parametric polymorphism.}
  13951. \label{fig:map-vec-poly}
  13952. \end{figure}
  13953. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  13954. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  13955. syntax. We add a second form for function definitions in which a type
  13956. declaration comes before the \code{define}. In the abstract syntax,
  13957. the return type in the \code{Def} is \code{Any}, but that should be
  13958. ignored in favor of the return type in the type declaration. (The
  13959. \code{Any} comes from using the same parser as in
  13960. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  13961. enables the use of an \code{All} type for a function, thereby making
  13962. it polymorphic. The grammar for types is extended to include
  13963. polymorphic types and type variables.
  13964. \begin{figure}[tp]
  13965. \centering
  13966. \fbox{
  13967. \begin{minipage}{0.96\textwidth}
  13968. \small
  13969. \[
  13970. \begin{array}{lcl}
  13971. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  13972. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  13973. &\MID& \LP\key{:}~\Var~\Type\RP \\
  13974. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  13975. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  13976. \end{array}
  13977. \]
  13978. \end{minipage}
  13979. }
  13980. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  13981. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  13982. \label{fig:Rpoly-concrete-syntax}
  13983. \end{figure}
  13984. \begin{figure}[tp]
  13985. \centering
  13986. \fbox{
  13987. \begin{minipage}{0.96\textwidth}
  13988. \small
  13989. \[
  13990. \begin{array}{lcl}
  13991. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  13992. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  13993. &\MID& \DECL{\Var}{\Type} \\
  13994. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  13995. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13996. \end{array}
  13997. \]
  13998. \end{minipage}
  13999. }
  14000. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  14001. (Figure~\ref{fig:Rwhile-syntax}).}
  14002. \label{fig:Rpoly-syntax}
  14003. \end{figure}
  14004. By including polymorphic types in the $\Type$ non-terminal we choose
  14005. to make them first-class which has interesting repercussions on the
  14006. compiler. Many languages with polymorphism, such as
  14007. C++~\citep{stroustrup88:_param_types} and Standard
  14008. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  14009. it is useful to see an example of first-class polymorphism. In
  14010. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  14011. whose parameter is a polymorphic function. The occurrence of a
  14012. polymorphic type underneath a function type is enabled by the normal
  14013. recursive structure of the grammar for $\Type$ and the categorization
  14014. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  14015. applies the polymorphic function to a Boolean and to an integer.
  14016. \begin{figure}[tbp]
  14017. \begin{lstlisting}
  14018. (: apply-twice ((All (b) (b -> b)) -> Integer))
  14019. (define (apply-twice f)
  14020. (if (f #t) (f 42) (f 777)))
  14021. (: id (All (a) (a -> a)))
  14022. (define (id x) x)
  14023. (apply-twice id)
  14024. \end{lstlisting}
  14025. \caption{An example illustrating first-class polymorphism.}
  14026. \label{fig:apply-twice}
  14027. \end{figure}
  14028. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  14029. three new responsibilities (compared to \LangLoop{}). The type checking of
  14030. function application is extended to handle the case where the operator
  14031. expression is a polymorphic function. In that case the type arguments
  14032. are deduced by matching the type of the parameters with the types of
  14033. the arguments.
  14034. %
  14035. The \code{match-types} auxiliary function carries out this deduction
  14036. by recursively descending through a parameter type \code{pt} and the
  14037. corresponding argument type \code{at}, making sure that they are equal
  14038. except when there is a type parameter on the left (in the parameter
  14039. type). If it's the first time that the type parameter has been
  14040. encountered, then the algorithm deduces an association of the type
  14041. parameter to the corresponding type on the right (in the argument
  14042. type). If it's not the first time that the type parameter has been
  14043. encountered, the algorithm looks up its deduced type and makes sure
  14044. that it is equal to the type on the right.
  14045. %
  14046. Once the type arguments are deduced, the operator expression is
  14047. wrapped in an \code{Inst} AST node (for instantiate) that records the
  14048. type of the operator, but more importantly, records the deduced type
  14049. arguments. The return type of the application is the return type of
  14050. the polymorphic function, but with the type parameters replaced by the
  14051. deduced type arguments, using the \code{subst-type} function.
  14052. The second responsibility of the type checker is extending the
  14053. function \code{type-equal?} to handle the \code{All} type. This is
  14054. not quite a simple as equal on other types, such as function and
  14055. vector types, because two polymorphic types can be syntactically
  14056. different even though they are equivalent types. For example,
  14057. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  14058. Two polymorphic types should be considered equal if they differ only
  14059. in the choice of the names of the type parameters. The
  14060. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  14061. renames the type parameters of the first type to match the type
  14062. parameters of the second type.
  14063. The third responsibility of the type checker is making sure that only
  14064. defined type variables appear in type annotations. The
  14065. \code{check-well-formed} function defined in
  14066. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  14067. sure that each type variable has been defined.
  14068. The output language of the type checker is \LangInst{}, defined in
  14069. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  14070. declaration and polymorphic function into a single definition, using
  14071. the \code{Poly} form, to make polymorphic functions more convenient to
  14072. process in next pass of the compiler.
  14073. \begin{figure}[tp]
  14074. \centering
  14075. \fbox{
  14076. \begin{minipage}{0.96\textwidth}
  14077. \small
  14078. \[
  14079. \begin{array}{lcl}
  14080. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  14081. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  14082. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  14083. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  14084. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14085. \end{array}
  14086. \]
  14087. \end{minipage}
  14088. }
  14089. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  14090. (Figure~\ref{fig:Rwhile-syntax}).}
  14091. \label{fig:Rpoly-prime-syntax}
  14092. \end{figure}
  14093. The output of the type checker on the polymorphic \code{map-vec}
  14094. example is listed in Figure~\ref{fig:map-vec-type-check}.
  14095. \begin{figure}[tbp]
  14096. % poly_test_2.rkt
  14097. \begin{lstlisting}
  14098. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  14099. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  14100. (define (add1 [x : Integer]) : Integer (+ x 1))
  14101. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  14102. (Integer))
  14103. add1 (vector 0 41)) 1)
  14104. \end{lstlisting}
  14105. \caption{Output of the type checker on the \code{map-vec} example.}
  14106. \label{fig:map-vec-type-check}
  14107. \end{figure}
  14108. \begin{figure}[tbp]
  14109. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14110. (define type-check-poly-class
  14111. (class type-check-Rwhile-class
  14112. (super-new)
  14113. (inherit check-type-equal?)
  14114. (define/override (type-check-apply env e1 es)
  14115. (define-values (e^ ty) ((type-check-exp env) e1))
  14116. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  14117. ((type-check-exp env) e)))
  14118. (match ty
  14119. [`(,ty^* ... -> ,rt)
  14120. (for ([arg-ty ty*] [param-ty ty^*])
  14121. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  14122. (values e^ es^ rt)]
  14123. [`(All ,xs (,tys ... -> ,rt))
  14124. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  14125. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  14126. (match-types env^^ param-ty arg-ty)))
  14127. (define targs
  14128. (for/list ([x xs])
  14129. (match (dict-ref env^^ x (lambda () #f))
  14130. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  14131. x (Apply e1 es))]
  14132. [ty ty])))
  14133. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  14134. [else (error 'type-check "expected a function, not ~a" ty)]))
  14135. (define/override ((type-check-exp env) e)
  14136. (match e
  14137. [(Lambda `([,xs : ,Ts] ...) rT body)
  14138. (for ([T Ts]) ((check-well-formed env) T))
  14139. ((check-well-formed env) rT)
  14140. ((super type-check-exp env) e)]
  14141. [(HasType e1 ty)
  14142. ((check-well-formed env) ty)
  14143. ((super type-check-exp env) e)]
  14144. [else ((super type-check-exp env) e)]))
  14145. (define/override ((type-check-def env) d)
  14146. (verbose 'type-check "poly/def" d)
  14147. (match d
  14148. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  14149. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  14150. (for ([p ps]) ((check-well-formed ts-env) p))
  14151. ((check-well-formed ts-env) rt)
  14152. (define new-env (append ts-env (map cons xs ps) env))
  14153. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14154. (check-type-equal? ty^ rt body)
  14155. (Generic ts (Def f p:t* rt info body^))]
  14156. [else ((super type-check-def env) d)]))
  14157. (define/override (type-check-program p)
  14158. (match p
  14159. [(Program info body)
  14160. (type-check-program (ProgramDefsExp info '() body))]
  14161. [(ProgramDefsExp info ds body)
  14162. (define ds^ (combine-decls-defs ds))
  14163. (define new-env (for/list ([d ds^])
  14164. (cons (def-name d) (fun-def-type d))))
  14165. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  14166. (define-values (body^ ty) ((type-check-exp new-env) body))
  14167. (check-type-equal? ty 'Integer body)
  14168. (ProgramDefsExp info ds^^ body^)]))
  14169. ))
  14170. \end{lstlisting}
  14171. \caption{Type checker for the \LangPoly{} language.}
  14172. \label{fig:type-check-Rvar0}
  14173. \end{figure}
  14174. \begin{figure}[tbp]
  14175. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14176. (define/override (type-equal? t1 t2)
  14177. (match* (t1 t2)
  14178. [(`(All ,xs ,T1) `(All ,ys ,T2))
  14179. (define env (map cons xs ys))
  14180. (type-equal? (subst-type env T1) T2)]
  14181. [(other wise)
  14182. (super type-equal? t1 t2)]))
  14183. (define/public (match-types env pt at)
  14184. (match* (pt at)
  14185. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  14186. [('Void 'Void) env] [('Any 'Any) env]
  14187. [(`(Vector ,pts ...) `(Vector ,ats ...))
  14188. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  14189. (match-types env^ pt1 at1))]
  14190. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  14191. (define env^ (match-types env prt art))
  14192. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  14193. (match-types env^^ pt1 at1))]
  14194. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  14195. (define env^ (append (map cons pxs axs) env))
  14196. (match-types env^ pt1 at1)]
  14197. [((? symbol? x) at)
  14198. (match (dict-ref env x (lambda () #f))
  14199. [#f (error 'type-check "undefined type variable ~a" x)]
  14200. ['Type (cons (cons x at) env)]
  14201. [t^ (check-type-equal? at t^ 'matching) env])]
  14202. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  14203. (define/public (subst-type env pt)
  14204. (match pt
  14205. ['Integer 'Integer] ['Boolean 'Boolean]
  14206. ['Void 'Void] ['Any 'Any]
  14207. [`(Vector ,ts ...)
  14208. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  14209. [`(,ts ... -> ,rt)
  14210. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  14211. [`(All ,xs ,t)
  14212. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  14213. [(? symbol? x) (dict-ref env x)]
  14214. [else (error 'type-check "expected a type not ~a" pt)]))
  14215. (define/public (combine-decls-defs ds)
  14216. (match ds
  14217. ['() '()]
  14218. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  14219. (unless (equal? name f)
  14220. (error 'type-check "name mismatch, ~a != ~a" name f))
  14221. (match type
  14222. [`(All ,xs (,ps ... -> ,rt))
  14223. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  14224. (cons (Generic xs (Def name params^ rt info body))
  14225. (combine-decls-defs ds^))]
  14226. [`(,ps ... -> ,rt)
  14227. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  14228. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  14229. [else (error 'type-check "expected a function type, not ~a" type) ])]
  14230. [`(,(Def f params rt info body) . ,ds^)
  14231. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  14232. \end{lstlisting}
  14233. \caption{Auxiliary functions for type checking \LangPoly{}.}
  14234. \label{fig:type-check-Rvar0-aux}
  14235. \end{figure}
  14236. \begin{figure}[tbp]
  14237. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  14238. (define/public ((check-well-formed env) ty)
  14239. (match ty
  14240. ['Integer (void)]
  14241. ['Boolean (void)]
  14242. ['Void (void)]
  14243. [(? symbol? a)
  14244. (match (dict-ref env a (lambda () #f))
  14245. ['Type (void)]
  14246. [else (error 'type-check "undefined type variable ~a" a)])]
  14247. [`(Vector ,ts ...)
  14248. (for ([t ts]) ((check-well-formed env) t))]
  14249. [`(,ts ... -> ,t)
  14250. (for ([t ts]) ((check-well-formed env) t))
  14251. ((check-well-formed env) t)]
  14252. [`(All ,xs ,t)
  14253. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  14254. ((check-well-formed env^) t)]
  14255. [else (error 'type-check "unrecognized type ~a" ty)]))
  14256. \end{lstlisting}
  14257. \caption{Well-formed types.}
  14258. \label{fig:well-formed-types}
  14259. \end{figure}
  14260. % TODO: interpreter for R'_10
  14261. \section{Compiling Polymorphism}
  14262. \label{sec:compiling-poly}
  14263. Broadly speaking, there are four approaches to compiling parametric
  14264. polymorphism, which we describe below.
  14265. \begin{description}
  14266. \item[Monomorphization] generates a different version of a polymorphic
  14267. function for each set of type arguments that it is used with,
  14268. producing type-specialized code. This approach results in the most
  14269. efficient code but requires whole-program compilation (no separate
  14270. compilation) and increases code size. For our current purposes
  14271. monomorphization is a non-starter because, with first-class
  14272. polymorphism, it is sometimes not possible to determine which
  14273. generic functions are used with which type arguments during
  14274. compilation. (It can be done at runtime, with just-in-time
  14275. compilation.) This approach is used to compile C++
  14276. templates~\citep{stroustrup88:_param_types} and polymorphic
  14277. functions in NESL~\citep{Blelloch:1993aa} and
  14278. ML~\citep{Weeks:2006aa}.
  14279. \item[Uniform representation] generates one version of each
  14280. polymorphic function but requires all values have a common ``boxed''
  14281. format, such as the tagged values of type \code{Any} in
  14282. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  14283. similarly to code in a dynamically typed language (like \LangDyn{}),
  14284. in which primitive operators require their arguments to be projected
  14285. from \code{Any} and their results are injected into \code{Any}. (In
  14286. object-oriented languages, the projection is accomplished via
  14287. virtual method dispatch.) The uniform representation approach is
  14288. compatible with separate compilation and with first-class
  14289. polymorphism. However, it produces the least-efficient code because
  14290. it introduces overhead in the entire program, including
  14291. non-polymorphic code. This approach is used in implementations of
  14292. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  14293. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  14294. Java~\citep{Bracha:1998fk}.
  14295. \item[Mixed representation] generates one version of each polymorphic
  14296. function, using a boxed representation for type
  14297. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  14298. and conversions are performed at the boundaries between monomorphic
  14299. and polymorphic (e.g. when a polymorphic function is instantiated
  14300. and called). This approach is compatible with separate compilation
  14301. and first-class polymorphism and maintains the efficiency of
  14302. monomorphic code. The tradeoff is increased overhead at the boundary
  14303. between monomorphic and polymorphic code. This approach is used in
  14304. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  14305. Java 5 with the addition of autoboxing.
  14306. \item[Type passing] uses the unboxed representation in both
  14307. monomorphic and polymorphic code. Each polymorphic function is
  14308. compiled to a single function with extra parameters that describe
  14309. the type arguments. The type information is used by the generated
  14310. code to know how to access the unboxed values at runtime. This
  14311. approach is used in implementation of the Napier88
  14312. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  14313. passing is compatible with separate compilation and first-class
  14314. polymorphism and maintains the efficiency for monomorphic
  14315. code. There is runtime overhead in polymorphic code from dispatching
  14316. on type information.
  14317. \end{description}
  14318. In this chapter we use the mixed representation approach, partly
  14319. because of its favorable attributes, and partly because it is
  14320. straightforward to implement using the tools that we have already
  14321. built to support gradual typing. To compile polymorphic functions, we
  14322. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  14323. \LangCast{}.
  14324. \section{Erase Types}
  14325. \label{sec:erase-types}
  14326. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  14327. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  14328. shows the output of the \code{erase-types} pass on the polymorphic
  14329. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  14330. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  14331. \code{All} types are removed from the type of \code{map-vec}.
  14332. \begin{figure}[tbp]
  14333. \begin{lstlisting}
  14334. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  14335. : (Vector Any Any)
  14336. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14337. (define (add1 [x : Integer]) : Integer (+ x 1))
  14338. (vector-ref ((cast map-vec
  14339. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  14340. ((Integer -> Integer) (Vector Integer Integer)
  14341. -> (Vector Integer Integer)))
  14342. add1 (vector 0 41)) 1)
  14343. \end{lstlisting}
  14344. \caption{The polymorphic \code{map-vec} example after type erasure.}
  14345. \label{fig:map-vec-erase}
  14346. \end{figure}
  14347. This process of type erasure creates a challenge at points of
  14348. instantiation. For example, consider the instantiation of
  14349. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  14350. The type of \code{map-vec} is
  14351. \begin{lstlisting}
  14352. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  14353. \end{lstlisting}
  14354. and it is instantiated to
  14355. \begin{lstlisting}
  14356. ((Integer -> Integer) (Vector Integer Integer)
  14357. -> (Vector Integer Integer))
  14358. \end{lstlisting}
  14359. After erasure, the type of \code{map-vec} is
  14360. \begin{lstlisting}
  14361. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  14362. \end{lstlisting}
  14363. but we need to convert it to the instantiated type. This is easy to
  14364. do in the target language \LangCast{} with a single \code{cast}. In
  14365. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  14366. has been compiled to a \code{cast} from the type of \code{map-vec} to
  14367. the instantiated type. The source and target type of a cast must be
  14368. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  14369. because both the source and target are obtained from the same
  14370. polymorphic type of \code{map-vec}, replacing the type parameters with
  14371. \code{Any} in the former and with the deduced type arguments in the
  14372. later. (Recall that the \code{Any} type is consistent with any type.)
  14373. To implement the \code{erase-types} pass, we recommend defining a
  14374. recursive auxiliary function named \code{erase-type} that applies the
  14375. following two transformations. It replaces type variables with
  14376. \code{Any}
  14377. \begin{lstlisting}
  14378. |$x$|
  14379. |$\Rightarrow$|
  14380. Any
  14381. \end{lstlisting}
  14382. and it removes the polymorphic \code{All} types.
  14383. \begin{lstlisting}
  14384. (All |$xs$| |$T_1$|)
  14385. |$\Rightarrow$|
  14386. |$T'_1$|
  14387. \end{lstlisting}
  14388. Apply the \code{erase-type} function to all of the type annotations in
  14389. the program.
  14390. Regarding the translation of expressions, the case for \code{Inst} is
  14391. the interesting one. We translate it into a \code{Cast}, as shown
  14392. below. The type of the subexpression $e$ is the polymorphic type
  14393. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  14394. $T$, the type $T'$. The target type $T''$ is the result of
  14395. substituting the arguments types $ts$ for the type parameters $xs$ in
  14396. $T$ followed by doing type erasure.
  14397. \begin{lstlisting}
  14398. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  14399. |$\Rightarrow$|
  14400. (Cast |$e'$| |$T'$| |$T''$|)
  14401. \end{lstlisting}
  14402. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  14403. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  14404. Finally, each polymorphic function is translated to a regular
  14405. functions in which type erasure has been applied to all the type
  14406. annotations and the body.
  14407. \begin{lstlisting}
  14408. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  14409. |$\Rightarrow$|
  14410. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  14411. \end{lstlisting}
  14412. \begin{exercise}\normalfont
  14413. Implement a compiler for the polymorphic language \LangPoly{} by
  14414. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  14415. programs that use polymorphic functions. Some of them should make
  14416. use of first-class polymorphism.
  14417. \end{exercise}
  14418. \begin{figure}[p]
  14419. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14420. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  14421. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  14422. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  14423. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  14424. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  14425. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  14426. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  14427. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  14428. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  14429. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  14430. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  14431. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  14432. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  14433. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  14434. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  14435. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14436. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14437. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14438. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14439. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14440. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14441. \path[->,bend right=15] (Rpoly) edge [above] node
  14442. {\ttfamily\footnotesize type-check} (Rpolyp);
  14443. \path[->,bend right=15] (Rpolyp) edge [above] node
  14444. {\ttfamily\footnotesize erase-types} (Rgradualp);
  14445. \path[->,bend right=15] (Rgradualp) edge [above] node
  14446. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  14447. \path[->,bend right=15] (Rwhilepp) edge [right] node
  14448. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  14449. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  14450. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  14451. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  14452. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  14453. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  14454. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  14455. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  14456. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  14457. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  14458. {\ttfamily\footnotesize convert-assignments} (F1-1);
  14459. \path[->,bend left=15] (F1-1) edge [below] node
  14460. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  14461. \path[->,bend right=15] (F1-2) edge [above] node
  14462. {\ttfamily\footnotesize limit-fun.} (F1-3);
  14463. \path[->,bend right=15] (F1-3) edge [above] node
  14464. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  14465. \path[->,bend right=15] (F1-4) edge [above] node
  14466. {\ttfamily\footnotesize remove-complex.} (F1-5);
  14467. \path[->,bend right=15] (F1-5) edge [right] node
  14468. {\ttfamily\footnotesize explicate-control} (C3-2);
  14469. \path[->,bend left=15] (C3-2) edge [left] node
  14470. {\ttfamily\footnotesize select-instr.} (x86-2);
  14471. \path[->,bend right=15] (x86-2) edge [left] node
  14472. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  14473. \path[->,bend right=15] (x86-2-1) edge [below] node
  14474. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  14475. \path[->,bend right=15] (x86-2-2) edge [left] node
  14476. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  14477. \path[->,bend left=15] (x86-3) edge [above] node
  14478. {\ttfamily\footnotesize patch-instr.} (x86-4);
  14479. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  14480. \end{tikzpicture}
  14481. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  14482. \label{fig:Rpoly-passes}
  14483. \end{figure}
  14484. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  14485. for the compilation of \LangPoly{}.
  14486. % TODO: challenge problem: specialization of instantiations
  14487. % Further Reading
  14488. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14489. \clearpage
  14490. \appendix
  14491. \chapter{Appendix}
  14492. \section{Interpreters}
  14493. \label{appendix:interp}
  14494. \index{subject}{interpreter}
  14495. We provide interpreters for each of the source languages \LangInt{},
  14496. \LangVar{}, $\ldots$ in the files \code{interp\_Rint.rkt},
  14497. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  14498. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  14499. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  14500. and x86 are in the \key{interp.rkt} file.
  14501. \section{Utility Functions}
  14502. \label{appendix:utilities}
  14503. The utility functions described in this section are in the
  14504. \key{utilities.rkt} file of the support code.
  14505. \paragraph{\code{interp-tests}}
  14506. The \key{interp-tests} function runs the compiler passes and the
  14507. interpreters on each of the specified tests to check whether each pass
  14508. is correct. The \key{interp-tests} function has the following
  14509. parameters:
  14510. \begin{description}
  14511. \item[name (a string)] a name to identify the compiler,
  14512. \item[typechecker] a function of exactly one argument that either
  14513. raises an error using the \code{error} function when it encounters a
  14514. type error, or returns \code{\#f} when it encounters a type
  14515. error. If there is no type error, the type checker returns the
  14516. program.
  14517. \item[passes] a list with one entry per pass. An entry is a list with
  14518. four things:
  14519. \begin{enumerate}
  14520. \item a string giving the name of the pass,
  14521. \item the function that implements the pass (a translator from AST
  14522. to AST),
  14523. \item a function that implements the interpreter (a function from
  14524. AST to result value) for the output language,
  14525. \item and a type checker for the output language. Type checkers for
  14526. the $R$ and $C$ languages are provided in the support code. For
  14527. example, the type checkers for \LangVar{} and \LangCVar{} are in
  14528. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  14529. type checker entry is optional. The support code does not provide
  14530. type checkers for the x86 languages.
  14531. \end{enumerate}
  14532. \item[source-interp] an interpreter for the source language. The
  14533. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  14534. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  14535. \item[tests] a list of test numbers that specifies which tests to
  14536. run. (see below)
  14537. \end{description}
  14538. %
  14539. The \key{interp-tests} function assumes that the subdirectory
  14540. \key{tests} has a collection of Racket programs whose names all start
  14541. with the family name, followed by an underscore and then the test
  14542. number, ending with the file extension \key{.rkt}. Also, for each test
  14543. program that calls \code{read} one or more times, there is a file with
  14544. the same name except that the file extension is \key{.in} that
  14545. provides the input for the Racket program. If the test program is
  14546. expected to fail type checking, then there should be an empty file of
  14547. the same name but with extension \key{.tyerr}.
  14548. \paragraph{\code{compiler-tests}}
  14549. runs the compiler passes to generate x86 (a \key{.s} file) and then
  14550. runs the GNU C compiler (gcc) to generate machine code. It runs the
  14551. machine code and checks that the output is $42$. The parameters to the
  14552. \code{compiler-tests} function are similar to those of the
  14553. \code{interp-tests} function, and consist of
  14554. \begin{itemize}
  14555. \item a compiler name (a string),
  14556. \item a type checker,
  14557. \item description of the passes,
  14558. \item name of a test-family, and
  14559. \item a list of test numbers.
  14560. \end{itemize}
  14561. \paragraph{\code{compile-file}}
  14562. takes a description of the compiler passes (see the comment for
  14563. \key{interp-tests}) and returns a function that, given a program file
  14564. name (a string ending in \key{.rkt}), applies all of the passes and
  14565. writes the output to a file whose name is the same as the program file
  14566. name but with \key{.rkt} replaced with \key{.s}.
  14567. \paragraph{\code{read-program}}
  14568. takes a file path and parses that file (it must be a Racket program)
  14569. into an abstract syntax tree.
  14570. \paragraph{\code{parse-program}}
  14571. takes an S-expression representation of an abstract syntax tree and converts it into
  14572. the struct-based representation.
  14573. \paragraph{\code{assert}}
  14574. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  14575. and displays the message \key{msg} if the Boolean \key{bool} is false.
  14576. \paragraph{\code{lookup}}
  14577. % remove discussion of lookup? -Jeremy
  14578. takes a key and an alist, and returns the first value that is
  14579. associated with the given key, if there is one. If not, an error is
  14580. triggered. The alist may contain both immutable pairs (built with
  14581. \key{cons}) and mutable pairs (built with \key{mcons}).
  14582. %The \key{map2} function ...
  14583. \section{x86 Instruction Set Quick-Reference}
  14584. \label{sec:x86-quick-reference}
  14585. \index{subject}{x86}
  14586. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  14587. do. We write $A \to B$ to mean that the value of $A$ is written into
  14588. location $B$. Address offsets are given in bytes. The instruction
  14589. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  14590. registers (such as \code{\%rax}), or memory references (such as
  14591. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  14592. reference per instruction. Other operands must be immediates or
  14593. registers.
  14594. \begin{table}[tbp]
  14595. \centering
  14596. \begin{tabular}{l|l}
  14597. \textbf{Instruction} & \textbf{Operation} \\ \hline
  14598. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  14599. \texttt{negq} $A$ & $- A \to A$ \\
  14600. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  14601. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  14602. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  14603. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  14604. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  14605. \texttt{retq} & Pops the return address and jumps to it \\
  14606. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  14607. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  14608. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  14609. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  14610. be an immediate) \\
  14611. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  14612. matches the condition code of the instruction, otherwise go to the
  14613. next instructions. The condition codes are \key{e} for ``equal'',
  14614. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  14615. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  14616. \texttt{jl} $L$ & \\
  14617. \texttt{jle} $L$ & \\
  14618. \texttt{jg} $L$ & \\
  14619. \texttt{jge} $L$ & \\
  14620. \texttt{jmp} $L$ & Jump to label $L$ \\
  14621. \texttt{movq} $A$, $B$ & $A \to B$ \\
  14622. \texttt{movzbq} $A$, $B$ &
  14623. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  14624. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  14625. and the extra bytes of $B$ are set to zero.} \\
  14626. & \\
  14627. & \\
  14628. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  14629. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  14630. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  14631. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  14632. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  14633. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  14634. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  14635. description of the condition codes. $A$ must be a single byte register
  14636. (e.g., \texttt{al} or \texttt{cl}).} \\
  14637. \texttt{setl} $A$ & \\
  14638. \texttt{setle} $A$ & \\
  14639. \texttt{setg} $A$ & \\
  14640. \texttt{setge} $A$ &
  14641. \end{tabular}
  14642. \vspace{5pt}
  14643. \caption{Quick-reference for the x86 instructions used in this book.}
  14644. \label{tab:x86-instr}
  14645. \end{table}
  14646. \cleardoublepage
  14647. \section{Concrete Syntax for Intermediate Languages}
  14648. The concrete syntax of \LangAny{} is defined in
  14649. Figure~\ref{fig:Rany-concrete-syntax}.
  14650. \begin{figure}[tp]
  14651. \centering
  14652. \fbox{
  14653. \begin{minipage}{0.97\textwidth}\small
  14654. \[
  14655. \begin{array}{lcl}
  14656. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  14657. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  14658. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  14659. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  14660. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  14661. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  14662. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  14663. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  14664. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  14665. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  14666. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  14667. \MID \LP\key{void?}\;\Exp\RP \\
  14668. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  14669. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  14670. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  14671. \end{array}
  14672. \]
  14673. \end{minipage}
  14674. }
  14675. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  14676. (Figure~\ref{fig:Rlam-syntax}).}
  14677. \label{fig:Rany-concrete-syntax}
  14678. \end{figure}
  14679. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  14680. defined in Figures~\ref{fig:c0-concrete-syntax},
  14681. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  14682. and \ref{fig:c3-concrete-syntax}, respectively.
  14683. \begin{figure}[tbp]
  14684. \fbox{
  14685. \begin{minipage}{0.96\textwidth}
  14686. \[
  14687. \begin{array}{lcl}
  14688. \Atm &::=& \Int \MID \Var \\
  14689. \Exp &::=& \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)}\\
  14690. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  14691. \Tail &::= & \key{return}~\Exp\key{;} \MID \Stmt~\Tail \\
  14692. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  14693. \end{array}
  14694. \]
  14695. \end{minipage}
  14696. }
  14697. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  14698. \label{fig:c0-concrete-syntax}
  14699. \end{figure}
  14700. \begin{figure}[tbp]
  14701. \fbox{
  14702. \begin{minipage}{0.96\textwidth}
  14703. \small
  14704. \[
  14705. \begin{array}{lcl}
  14706. \Atm &::=& \gray{ \Int \MID \Var } \MID \itm{bool} \\
  14707. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  14708. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  14709. &\MID& \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  14710. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  14711. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  14712. \MID \key{goto}~\itm{label}\key{;}\\
  14713. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  14714. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  14715. \end{array}
  14716. \]
  14717. \end{minipage}
  14718. }
  14719. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  14720. \label{fig:c1-concrete-syntax}
  14721. \end{figure}
  14722. \begin{figure}[tbp]
  14723. \fbox{
  14724. \begin{minipage}{0.96\textwidth}
  14725. \small
  14726. \[
  14727. \begin{array}{lcl}
  14728. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  14729. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  14730. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  14731. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  14732. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  14733. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  14734. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  14735. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  14736. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  14737. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  14738. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  14739. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  14740. \end{array}
  14741. \]
  14742. \end{minipage}
  14743. }
  14744. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  14745. \label{fig:c2-concrete-syntax}
  14746. \end{figure}
  14747. \begin{figure}[tp]
  14748. \fbox{
  14749. \begin{minipage}{0.96\textwidth}
  14750. \small
  14751. \[
  14752. \begin{array}{lcl}
  14753. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  14754. \\
  14755. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  14756. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  14757. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  14758. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  14759. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  14760. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  14761. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  14762. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  14763. \MID \LP\key{collect} \,\itm{int}\RP }\\
  14764. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  14765. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  14766. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  14767. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  14768. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  14769. \LangCFunM{} & ::= & \Def\ldots
  14770. \end{array}
  14771. \]
  14772. \end{minipage}
  14773. }
  14774. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  14775. \label{fig:c3-concrete-syntax}
  14776. \end{figure}
  14777. \backmatter
  14778. \addtocontents{toc}{\vspace{11pt}}
  14779. %% \addtocontents{toc}{\vspace{11pt}}
  14780. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  14781. \nocite{*}\let\bibname\refname
  14782. \addcontentsline{toc}{fmbm}{\refname}
  14783. \printbibliography
  14784. \printindex{authors}{Author Index}
  14785. \printindex{subject}{Subject Index}
  14786. \end{document}