book.tex 683 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498
  1. \documentclass[7x10,nocrop]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  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. \usepackage{upquote}
  17. \definecolor{lightgray}{gray}{1}
  18. \newcommand{\black}[1]{{\color{black} #1}}
  19. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  20. \newcommand{\gray}[1]{{\color{gray} #1}}
  21. \def\racketEd{0}
  22. \def\pythonEd{1}
  23. \def\edition{1}
  24. % material that is specific to the Racket edition of the book
  25. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  26. % would like a command for: \if\edition\racketEd\color{olive}
  27. % and : \fi\color{black}
  28. % material that is specific to the Python edition of the book
  29. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  30. %% For multiple indices:
  31. \usepackage{multind}
  32. \makeindex{subject}
  33. \makeindex{authors}
  34. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  35. \if\edition\racketEd
  36. \lstset{%
  37. language=Lisp,
  38. basicstyle=\ttfamily\small,
  39. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  40. deletekeywords={read,mapping,vector},
  41. escapechar=|,
  42. columns=flexible,
  43. moredelim=[is][\color{red}]{~}{~},
  44. showstringspaces=false
  45. }
  46. \fi
  47. \if\edition\pythonEd
  48. \lstset{%
  49. language=Python,
  50. basicstyle=\ttfamily\small,
  51. morekeywords={match,case,bool,int,let},
  52. deletekeywords={},
  53. escapechar=|,
  54. columns=flexible,
  55. moredelim=[is][\color{red}]{~}{~},
  56. showstringspaces=false
  57. }
  58. \fi
  59. %%% Any shortcut own defined macros place here
  60. %% sample of author macro:
  61. \input{defs}
  62. \newtheorem{exercise}[theorem]{Exercise}
  63. % Adjusted settings
  64. \setlength{\columnsep}{4pt}
  65. %% \begingroup
  66. %% \setlength{\intextsep}{0pt}%
  67. %% \setlength{\columnsep}{0pt}%
  68. %% \begin{wrapfigure}{r}{0.5\textwidth}
  69. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  70. %% \caption{Basic layout}
  71. %% \end{wrapfigure}
  72. %% \lipsum[1]
  73. %% \endgroup
  74. \newbox\oiintbox
  75. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  76. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  77. \def\oiint{\copy\oiintbox}
  78. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  79. %\usepackage{showframe}
  80. \def\ShowFrameLinethickness{0.125pt}
  81. \addbibresource{book.bib}
  82. \begin{document}
  83. \frontmatter
  84. \HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  85. \halftitlepage
  86. \Title{Essentials of Compilation}
  87. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  88. %\edition{First Edition}
  89. \BookAuthor{Jeremy G. Siek}
  90. \imprint{The MIT Press\\
  91. Cambridge, Massachusetts\\
  92. London, England}
  93. \begin{copyrightpage}
  94. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  95. or personal downloading under the
  96. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  97. license.
  98. Copyright in this monograph has been licensed exclusively to The MIT
  99. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  100. version to the public in 2022. All inquiries regarding rights should
  101. be addressed to The MIT Press, Rights and Permissions Department.
  102. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  103. %% All rights reserved. No part of this book may be reproduced in any
  104. %% form by any electronic or mechanical means (including photocopying,
  105. %% recording, or information storage and retrieval) without permission in
  106. %% writing from the publisher.
  107. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  108. %% United States of America.
  109. %% Library of Congress Cataloging-in-Publication Data is available.
  110. %% ISBN:
  111. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  112. \end{copyrightpage}
  113. \dedication{This book is dedicated to the programming language wonks
  114. at Indiana University.}
  115. %% \begin{epigraphpage}
  116. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  117. %% \textit{Book Name if any}}
  118. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  119. %% \end{epigraphpage}
  120. \tableofcontents
  121. %\listoffigures
  122. %\listoftables
  123. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  124. \chapter*{Preface}
  125. \addcontentsline{toc}{fmbm}{Preface}
  126. There is a magical moment when a programmer presses the ``run'' button
  127. and the software begins to execute. Somehow a program written in a
  128. high-level language is running on a computer that is only capable of
  129. shuffling bits. Here we reveal the wizardry that makes that moment
  130. possible. Beginning with the groundbreaking work of Backus and
  131. colleagues in the 1950s, computer scientists discovered techniques for
  132. constructing programs, called \emph{compilers}, that automatically
  133. translate high-level programs into machine code.
  134. We take you on a journey by constructing your own compiler for a small
  135. but powerful language. Along the way we explain the essential
  136. concepts, algorithms, and data structures that underlie compilers. We
  137. develop your understanding of how programs are mapped onto computer
  138. hardware, which is helpful when reasoning about properties at the
  139. junction between hardware and software such as execution time,
  140. software errors, and security vulnerabilities. For those interested
  141. in pursuing compiler construction as a career, our goal is to provide a
  142. stepping-stone to advanced topics such as just-in-time compilation,
  143. program analysis, and program optimization. For those interested in
  144. designing and implementing programming languages, we connect
  145. language design choices to their impact on the compiler and the generated
  146. code.
  147. A compiler is typically organized as a sequence of stages that
  148. progressively translate a program to the code that runs on
  149. hardware. We take this approach to the extreme by partitioning our
  150. compiler into a large number of \emph{nanopasses}, each of which
  151. performs a single task. This allows us to test the output of each pass
  152. in isolation, and furthermore, allows us to focus our attention which
  153. makes the compiler far easier to understand.
  154. The most familiar approach to describing compilers is with one pass
  155. per chapter. The problem with that approach is it obfuscates how
  156. language features motivate design choices in a compiler. We instead
  157. take an \emph{incremental} approach in which we build a complete
  158. compiler in each chapter, starting with a small input language that
  159. includes only arithmetic and variables and we add new language
  160. features in subsequent chapters.
  161. Our choice of language features is designed to elicit fundamental
  162. concepts and algorithms used in compilers.
  163. \begin{itemize}
  164. \item We begin with integer arithmetic and local variables in
  165. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  166. the fundamental tools of compiler construction: \emph{abstract
  167. syntax trees} and \emph{recursive functions}.
  168. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  169. \emph{graph coloring} to assign variables to machine registers.
  170. \item Chapter~\ref{ch:Lif} adds \code{if} expressions, which motivates
  171. an elegant recursive algorithm for translating them into conditional
  172. \code{goto}'s.
  173. \item Chapter~\ref{ch:Lwhile} fleshes out support for imperative
  174. programming languages with the addition of loops\racket{ and mutable
  175. variables}. This elicits the need for \emph{dataflow
  176. analysis} in the register allocator.
  177. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  178. \emph{garbage collection}.
  179. \item Chapter~\ref{ch:Lfun} adds functions that are first-class values
  180. but lack lexical scoping, similar to the C programming
  181. language~\citep{Kernighan:1988nx} except that we generate efficient
  182. tail calls. The reader learns about the procedure call stack,
  183. \emph{calling conventions}, and their interaction with register
  184. allocation and garbage collection.
  185. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  186. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  187. \emph{closure conversion}, in which lambdas are translated into a
  188. combination of functions and tuples.
  189. % Chapter about classes and objects?
  190. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  191. point the input languages are statically typed. The reader extends
  192. the statically typed language with an \code{Any} type which serves
  193. as a target for compiling the dynamically typed language.
  194. {\if\edition\pythonEd
  195. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  196. \emph{classes}.
  197. \fi}
  198. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type of
  199. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  200. in which different regions of a program may be static or dynamically
  201. typed. The reader implements runtime support for \emph{proxies} that
  202. allow values to safely move between regions.
  203. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  204. leveraging the \code{Any} type and type casts developed in Chapters
  205. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  206. \end{itemize}
  207. There are many language features that we do not include. Our choices
  208. balance the incidental complexity of a feature versus the fundamental
  209. concepts that it exposes. For example, we include tuples and not
  210. records because they both elicit the study of heap allocation and
  211. garbage collection but records come with more incidental complexity.
  212. Since 2009 drafts of this book have served as the textbook for 16-week
  213. compiler courses for upper-level undergraduates and first-year
  214. graduate students at the University of Colorado and Indiana
  215. University.
  216. %
  217. Students come into the course having learned the basics of
  218. programming, data structures and algorithms, and discrete
  219. mathematics.
  220. %
  221. At the beginning of the course, students form groups of 2-4 people.
  222. The groups complete one chapter every two weeks, starting with
  223. Chapter~\ref{ch:Lvar} and finishing with
  224. Chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  225. that we assign to the graduate students. The last two weeks of the
  226. course involve a final project in which students design and implement
  227. a compiler extension of their choosing. The later chapters can be
  228. used in support of these projects. For compiler courses at
  229. universities on the quarter system that are about 10 weeks in length,
  230. we recommend completing up through Chapter~\ref{ch:Lvec} or
  231. Chapter~\ref{ch:Lfun} and providing some scafolding code to the
  232. students for each compiler pass.
  233. %
  234. The course can be adapted to emphasize functional languages by
  235. skipping Chapter~\ref{ch:Lwhile} (loops) and including
  236. Chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  237. dynamically typed languages by including Chapter~\ref{ch:Ldyn}.
  238. %
  239. \python{A course that emphasizes object-oriented languages would
  240. include Chapter~\ref{ch:Lobject}.}
  241. %
  242. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  243. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  244. Chapter~\ref{ch:Lvec} (tuples) in the implementation of efficient
  245. tail calls.
  246. This book has been used in compiler courses at California Polytechnic
  247. State University, Portland State University, Rose–Hulman Institute of
  248. Technology, University of Freiburg, University of Massachusetts
  249. Lowell, and the University of Vermont.
  250. \begin{figure}[tp]
  251. {\if\edition\racketEd
  252. \begin{tikzpicture}[baseline=(current bounding box.center)]
  253. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  254. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  255. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  256. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  257. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  258. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  259. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  260. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  261. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  262. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  263. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  264. \path[->] (C1) edge [above] node {} (C2);
  265. \path[->] (C2) edge [above] node {} (C3);
  266. \path[->] (C3) edge [above] node {} (C4);
  267. \path[->] (C4) edge [above] node {} (C5);
  268. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  269. \path[->] (C5) edge [above] node {} (C7);
  270. \path[->] (C6) edge [above] node {} (C7);
  271. \path[->] (C4) edge [above] node {} (C8);
  272. \path[->] (C4) edge [above] node {} (C9);
  273. \path[->] (C7) edge [above] node {} (C10);
  274. \path[->] (C8) edge [above] node {} (C10);
  275. \path[->] (C10) edge [above] node {} (C11);
  276. \end{tikzpicture}
  277. \fi}
  278. {\if\edition\pythonEd
  279. \begin{tikzpicture}[baseline=(current bounding box.center)]
  280. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  281. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  282. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  283. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  284. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  285. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  286. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  287. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  288. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  289. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  290. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  291. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  292. \path[->] (C1) edge [above] node {} (C2);
  293. \path[->] (C2) edge [above] node {} (C3);
  294. \path[->] (C3) edge [above] node {} (C4);
  295. \path[->] (C4) edge [above] node {} (C5);
  296. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  297. \path[->] (C5) edge [above] node {} (C7);
  298. \path[->] (C6) edge [above] node {} (C7);
  299. \path[->] (C4) edge [above] node {} (C8);
  300. \path[->] (C4) edge [above] node {} (C9);
  301. \path[->] (C7) edge [above] node {} (C10);
  302. \path[->] (C8) edge [above] node {} (C10);
  303. \path[->] (C8) edge [above] node {} (CO);
  304. \path[->] (C10) edge [above] node {} (C11);
  305. \end{tikzpicture}
  306. \fi}
  307. \caption{Diagram of chapter dependencies.}
  308. \label{fig:chapter-dependences}
  309. \end{figure}
  310. \racket{
  311. We use the \href{https://racket-lang.org/}{Racket} language both for
  312. the implementation of the compiler and for the input language, so the
  313. reader should be proficient with Racket or Scheme. There are many
  314. excellent resources for learning Scheme and
  315. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  316. }
  317. \python{
  318. This edition of the book uses \href{https://www.python.org/}{Python}
  319. both for the implementation of the compiler and for the input language, so the
  320. reader should be proficient with Python. There are many
  321. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  322. }
  323. The support code for this book is in the github repository at
  324. the following location:
  325. \if\edition\racketEd
  326. \begin{center}\small
  327. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  328. \end{center}
  329. \fi
  330. \if\edition\pythonEd
  331. \begin{center}\small
  332. \url{https://github.com/IUCompilerCourse/}
  333. \end{center}
  334. \fi
  335. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  336. is helpful but not necessary for the reader to have taken a computer
  337. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  338. of x86-64 assembly language that are needed.
  339. %
  340. We follow the System V calling
  341. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  342. that we generate works with the runtime system (written in C) when it
  343. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  344. operating systems on Intel hardware.
  345. %
  346. On the Windows operating system, \code{gcc} uses the Microsoft x64
  347. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  348. assembly code that we generate does \emph{not} work with the runtime
  349. system on Windows. One workaround is to use a virtual machine with
  350. Linux as the guest operating system.
  351. \section*{Acknowledgments}
  352. The tradition of compiler construction at Indiana University goes back
  353. to research and courses on programming languages by Daniel Friedman in
  354. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  355. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  356. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  357. the compiler course and continued the development of Chez Scheme.
  358. %
  359. The compiler course evolved to incorporate novel pedagogical ideas
  360. while also including elements of real-world compilers. One of
  361. Friedman's ideas was to split the compiler into many small
  362. passes. Another idea, called ``the game'', was to test the code
  363. generated by each pass using interpreters.
  364. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  365. developed infrastructure to support this approach and evolved the
  366. course to use even smaller
  367. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  368. design decisions in this book are inspired by the assignment
  369. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  370. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  371. organization of the course made it difficult for students to
  372. understand the rationale for the compiler design. Ghuloum proposed the
  373. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  374. on.
  375. We thank the many students who served as teaching assistants for the
  376. compiler course at IU and made suggestions for improving the book
  377. including Carl Factora, Ryan Scott, Cameron Swords, and Chris
  378. Wailes. We thank Andre Kuhlenschmidt for work on the garbage collector
  379. and x86 interpreter, Michael Vollmer for work on efficient tail calls,
  380. and Michael Vitousek for help running the first offering of the
  381. incremental compiler course at IU.
  382. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  383. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  384. Michael Wollowski for teaching courses based on drafts of this book
  385. and for their feedback.
  386. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  387. course in the early 2000's and especially for finding the bug that
  388. sent our garbage collector on a wild goose chase!
  389. \mbox{}\\
  390. \noindent Jeremy G. Siek \\
  391. Bloomington, Indiana
  392. \mainmatter
  393. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  394. \chapter{Preliminaries}
  395. \label{ch:trees-recur}
  396. In this chapter we review the basic tools that are needed to implement
  397. a compiler. Programs are typically input by a programmer as text,
  398. i.e., a sequence of characters. The program-as-text representation is
  399. called \emph{concrete syntax}. We use concrete syntax to concisely
  400. write down and talk about programs. Inside the compiler, we use
  401. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  402. that efficiently supports the operations that the compiler needs to
  403. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  404. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  405. from concrete syntax to abstract syntax is a process called
  406. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  407. implementation of parsing in this book.
  408. %
  409. \racket{A parser is provided in the support code for translating from
  410. concrete to abstract syntax.}
  411. %
  412. \python{We use Python's \code{ast} module to translate from concrete
  413. to abstract syntax.}
  414. ASTs can be represented in many different ways inside the compiler,
  415. depending on the programming language used to write the compiler.
  416. %
  417. \racket{We use Racket's
  418. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  419. feature to represent ASTs (Section~\ref{sec:ast}).}
  420. %
  421. \python{We use Python classes and objects to represent ASTs, especially the
  422. classes defined in the standard \code{ast} module for the Python
  423. source language.}
  424. %
  425. We use grammars to define the abstract syntax of programming languages
  426. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  427. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  428. recursive functions to construct and deconstruct ASTs
  429. (Section~\ref{sec:recursion}). This chapter provides an brief
  430. introduction to these ideas.
  431. \racket{\index{subject}{struct}}
  432. \python{\index{subject}{class}\index{subject}{object}}
  433. \section{Abstract Syntax Trees}
  434. \label{sec:ast}
  435. Compilers use abstract syntax trees to represent programs because they
  436. often need to ask questions like: for a given part of a program, what
  437. kind of language feature is it? What are its sub-parts? Consider the
  438. program on the left and its AST on the right. This program is an
  439. addition operation and it has two sub-parts, a
  440. \racket{read}\python{input} operation and a negation. The negation has
  441. another sub-part, the integer constant \code{8}. By using a tree to
  442. represent the program, we can easily follow the links to go from one
  443. part of a program to its sub-parts.
  444. \begin{center}
  445. \begin{minipage}{0.4\textwidth}
  446. \if\edition\racketEd
  447. \begin{lstlisting}
  448. (+ (read) (- 8))
  449. \end{lstlisting}
  450. \fi
  451. \if\edition\pythonEd
  452. \begin{lstlisting}
  453. input_int() + -8
  454. \end{lstlisting}
  455. \fi
  456. \end{minipage}
  457. \begin{minipage}{0.4\textwidth}
  458. \begin{equation}
  459. \begin{tikzpicture}
  460. \node[draw] (plus) at (0 , 0) {\key{+}};
  461. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  462. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  463. \node[draw] (8) at (1 , -3) {\key{8}};
  464. \draw[->] (plus) to (read);
  465. \draw[->] (plus) to (minus);
  466. \draw[->] (minus) to (8);
  467. \end{tikzpicture}
  468. \label{eq:arith-prog}
  469. \end{equation}
  470. \end{minipage}
  471. \end{center}
  472. We use the standard terminology for trees to describe ASTs: each
  473. rectangle above is called a \emph{node}. The arrows connect a node to its
  474. \emph{children} (which are also nodes). The top-most node is the
  475. \emph{root}. Every node except for the root has a \emph{parent} (the
  476. node it is the child of). If a node has no children, it is a
  477. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  478. \index{subject}{node}
  479. \index{subject}{children}
  480. \index{subject}{root}
  481. \index{subject}{parent}
  482. \index{subject}{leaf}
  483. \index{subject}{internal node}
  484. %% Recall that an \emph{symbolic expression} (S-expression) is either
  485. %% \begin{enumerate}
  486. %% \item an atom, or
  487. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  488. %% where $e_1$ and $e_2$ are each an S-expression.
  489. %% \end{enumerate}
  490. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  491. %% null value \code{'()}, etc. We can create an S-expression in Racket
  492. %% simply by writing a backquote (called a quasi-quote in Racket)
  493. %% followed by the textual representation of the S-expression. It is
  494. %% quite common to use S-expressions to represent a list, such as $a, b
  495. %% ,c$ in the following way:
  496. %% \begin{lstlisting}
  497. %% `(a . (b . (c . ())))
  498. %% \end{lstlisting}
  499. %% Each element of the list is in the first slot of a pair, and the
  500. %% second slot is either the rest of the list or the null value, to mark
  501. %% the end of the list. Such lists are so common that Racket provides
  502. %% special notation for them that removes the need for the periods
  503. %% and so many parenthesis:
  504. %% \begin{lstlisting}
  505. %% `(a b c)
  506. %% \end{lstlisting}
  507. %% The following expression creates an S-expression that represents AST
  508. %% \eqref{eq:arith-prog}.
  509. %% \begin{lstlisting}
  510. %% `(+ (read) (- 8))
  511. %% \end{lstlisting}
  512. %% When using S-expressions to represent ASTs, the convention is to
  513. %% represent each AST node as a list and to put the operation symbol at
  514. %% the front of the list. The rest of the list contains the children. So
  515. %% in the above case, the root AST node has operation \code{`+} and its
  516. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  517. %% diagram \eqref{eq:arith-prog}.
  518. %% To build larger S-expressions one often needs to splice together
  519. %% several smaller S-expressions. Racket provides the comma operator to
  520. %% splice an S-expression into a larger one. For example, instead of
  521. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  522. %% we could have first created an S-expression for AST
  523. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  524. %% S-expression.
  525. %% \begin{lstlisting}
  526. %% (define ast1.4 `(- 8))
  527. %% (define ast1_1 `(+ (read) ,ast1.4))
  528. %% \end{lstlisting}
  529. %% In general, the Racket expression that follows the comma (splice)
  530. %% can be any expression that produces an S-expression.
  531. {\if\edition\racketEd
  532. We define a Racket \code{struct} for each kind of node. For this
  533. chapter we require just two kinds of nodes: one for integer constants
  534. and one for primitive operations. The following is the \code{struct}
  535. definition for integer constants.
  536. \begin{lstlisting}
  537. (struct Int (value))
  538. \end{lstlisting}
  539. An integer node includes just one thing: the integer value.
  540. To create an AST node for the integer $8$, we write \INT{8}.
  541. \begin{lstlisting}
  542. (define eight (Int 8))
  543. \end{lstlisting}
  544. We say that the value created by \INT{8} is an
  545. \emph{instance} of the
  546. \code{Int} structure.
  547. The following is the \code{struct} definition for primitive operations.
  548. \begin{lstlisting}
  549. (struct Prim (op args))
  550. \end{lstlisting}
  551. A primitive operation node includes an operator symbol \code{op} and a
  552. list of child \code{args}. For example, to create an AST that negates
  553. the number $8$, we write \code{(Prim '- (list eight))}.
  554. \begin{lstlisting}
  555. (define neg-eight (Prim '- (list eight)))
  556. \end{lstlisting}
  557. Primitive operations may have zero or more children. The \code{read}
  558. operator has zero children:
  559. \begin{lstlisting}
  560. (define rd (Prim 'read '()))
  561. \end{lstlisting}
  562. whereas the addition operator has two children:
  563. \begin{lstlisting}
  564. (define ast1_1 (Prim '+ (list rd neg-eight)))
  565. \end{lstlisting}
  566. We have made a design choice regarding the \code{Prim} structure.
  567. Instead of using one structure for many different operations
  568. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  569. structure for each operation, as follows.
  570. \begin{lstlisting}
  571. (struct Read ())
  572. (struct Add (left right))
  573. (struct Neg (value))
  574. \end{lstlisting}
  575. The reason we choose to use just one structure is that in many parts
  576. of the compiler the code for the different primitive operators is the
  577. same, so we might as well just write that code once, which is enabled
  578. by using a single structure.
  579. \fi}
  580. {\if\edition\pythonEd
  581. We use a Python \code{class} for each kind of node.
  582. The following is the class definition for constants.
  583. \begin{lstlisting}
  584. class Constant:
  585. def __init__(self, value):
  586. self.value = value
  587. \end{lstlisting}
  588. An integer constant node includes just one thing: the integer value.
  589. To create an AST node for the integer $8$, we write \INT{8}.
  590. \begin{lstlisting}
  591. eight = Constant(8)
  592. \end{lstlisting}
  593. We say that the value created by \INT{8} is an
  594. \emph{instance} of the \code{Constant} class.
  595. The following is the class definition for unary operators.
  596. \begin{lstlisting}
  597. class UnaryOp:
  598. def __init__(self, op, operand):
  599. self.op = op
  600. self.operand = operand
  601. \end{lstlisting}
  602. The specific operation is specified by the \code{op} parameter. For
  603. example, the class \code{USub} is for unary subtraction. (More unary
  604. operators are introduced in later chapters.) To create an AST that
  605. negates the number $8$, we write the following.
  606. \begin{lstlisting}
  607. neg_eight = UnaryOp(USub(), eight)
  608. \end{lstlisting}
  609. The call to the \code{input\_int} function is represented by the
  610. \code{Call} and \code{Name} classes.
  611. \begin{lstlisting}
  612. class Call:
  613. def __init__(self, func, args):
  614. self.func = func
  615. self.args = args
  616. class Name:
  617. def __init__(self, id):
  618. self.id = id
  619. \end{lstlisting}
  620. To create an AST node that calls \code{input\_int}, we write
  621. \begin{lstlisting}
  622. read = Call(Name('input_int'), [])
  623. \end{lstlisting}
  624. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  625. the \code{BinOp} class for binary operators.
  626. \begin{lstlisting}
  627. class BinOp:
  628. def __init__(self, left, op, right):
  629. self.op = op
  630. self.left = left
  631. self.right = right
  632. \end{lstlisting}
  633. Similar to \code{UnaryOp}, the specific operation is specified by the
  634. \code{op} parameter, which for now is just an instance of the
  635. \code{Add} class. So to create the AST node that adds negative eight
  636. to some user input, we write the following.
  637. \begin{lstlisting}
  638. ast1_1 = BinOp(read, Add(), neg_eight)
  639. \end{lstlisting}
  640. \fi}
  641. When compiling a program such as \eqref{eq:arith-prog}, we need to
  642. know that the operation associated with the root node is addition and
  643. we need to be able to access its two children. \racket{Racket}\python{Python}
  644. provides pattern matching to support these kinds of queries, as we see in
  645. Section~\ref{sec:pattern-matching}.
  646. In this book, we often write down the concrete syntax of a program
  647. even when we really have in mind the AST because the concrete syntax
  648. is more concise. We recommend that, in your mind, you always think of
  649. programs as abstract syntax trees.
  650. \section{Grammars}
  651. \label{sec:grammar}
  652. \index{subject}{integer}
  653. \index{subject}{literal}
  654. \index{subject}{constant}
  655. A programming language can be thought of as a \emph{set} of programs.
  656. The set is typically infinite (one can always create larger and larger
  657. programs), so one cannot simply describe a language by listing all of
  658. the programs in the language. Instead we write down a set of rules, a
  659. \emph{grammar}, for building programs. Grammars are often used to
  660. define the concrete syntax of a language, but they can also be used to
  661. describe the abstract syntax. We write our rules in a variant of
  662. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  663. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  664. As an example, we describe a small language, named \LangInt{}, that consists of
  665. integers and arithmetic operations.
  666. \index{subject}{grammar}
  667. The first grammar rule for the abstract syntax of \LangInt{} says that an
  668. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  669. \begin{equation}
  670. \Exp ::= \INT{\Int} \label{eq:arith-int}
  671. \end{equation}
  672. %
  673. Each rule has a left-hand-side and a right-hand-side.
  674. If you have an AST node that matches the
  675. right-hand-side, then you can categorize it according to the
  676. left-hand-side.
  677. %
  678. Symbols in typewriter font are \emph{terminal} symbols and must
  679. literally appear in the program for the rule to be applicable.
  680. \index{subject}{terminal}
  681. %
  682. Our grammars do not mention \emph{white-space}, that is, separating characters
  683. like spaces, tabulators, and newlines. White-space may be inserted
  684. between symbols for disambiguation and to improve readability.
  685. \index{subject}{white-space}
  686. %
  687. A name such as $\Exp$ that is defined by the grammar rules is a
  688. \emph{non-terminal}. \index{subject}{non-terminal}
  689. %
  690. The name $\Int$ is also a non-terminal, but instead of defining it
  691. with a grammar rule, we define it with the following explanation. An
  692. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  693. $-$ (for negative integers), such that the sequence of decimals
  694. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  695. the representation of integers using 63 bits, which simplifies several
  696. aspects of compilation. \racket{Thus, these integers corresponds to
  697. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  698. \python{In contrast, integers in Python have unlimited precision, but
  699. the techniques needed to handle unlimited precision fall outside the
  700. scope of this book.}
  701. The second grammar rule is the \READOP{} operation that receives an
  702. input integer from the user of the program.
  703. \begin{equation}
  704. \Exp ::= \READ{} \label{eq:arith-read}
  705. \end{equation}
  706. The third rule says that, given an $\Exp$ node, the negation of that
  707. node is also an $\Exp$.
  708. \begin{equation}
  709. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  710. \end{equation}
  711. We can apply these rules to categorize the ASTs that are in the
  712. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  713. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  714. following AST is an $\Exp$.
  715. \begin{center}
  716. \begin{minipage}{0.5\textwidth}
  717. \NEG{\INT{\code{8}}}
  718. \end{minipage}
  719. \begin{minipage}{0.25\textwidth}
  720. \begin{equation}
  721. \begin{tikzpicture}
  722. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  723. \node[draw, circle] (8) at (0, -1.2) {$8$};
  724. \draw[->] (minus) to (8);
  725. \end{tikzpicture}
  726. \label{eq:arith-neg8}
  727. \end{equation}
  728. \end{minipage}
  729. \end{center}
  730. The next grammar rules are for addition and subtraction expressions:
  731. \begin{align}
  732. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  733. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  734. \end{align}
  735. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  736. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  737. \eqref{eq:arith-read} and we have already categorized
  738. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  739. to show that
  740. \[
  741. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  742. \]
  743. is an $\Exp$ in the \LangInt{} language.
  744. If you have an AST for which the above rules do not apply, then the
  745. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  746. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  747. because there are no rules for the \key{*} operator. Whenever we
  748. define a language with a grammar, the language only includes those
  749. programs that are justified by the grammar rules.
  750. {\if\edition\pythonEd
  751. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  752. There is a statement for printing the value of an expression
  753. \[
  754. \Stmt{} ::= \PRINT{\Exp}
  755. \]
  756. and a statement that evaluates an expression but ignores the result.
  757. \[
  758. \Stmt{} ::= \EXPR{\Exp}
  759. \]
  760. \fi}
  761. {\if\edition\racketEd
  762. The last grammar rule for \LangInt{} states that there is a
  763. \code{Program} node to mark the top of the whole program:
  764. \[
  765. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  766. \]
  767. The \code{Program} structure is defined as follows
  768. \begin{lstlisting}
  769. (struct Program (info body))
  770. \end{lstlisting}
  771. where \code{body} is an expression. In later chapters, the \code{info}
  772. part will be used to store auxiliary information but for now it is
  773. just the empty list.
  774. \fi}
  775. {\if\edition\pythonEd
  776. The last grammar rule for \LangInt{} states that there is a
  777. \code{Module} node to mark the top of the whole program:
  778. \[
  779. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  780. \]
  781. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  782. this case, a list of statements.
  783. %
  784. The \code{Module} class is defined as follows
  785. \begin{lstlisting}
  786. class Module:
  787. def __init__(self, body):
  788. self.body = body
  789. \end{lstlisting}
  790. where \code{body} is a list of statements.
  791. \fi}
  792. It is common to have many grammar rules with the same left-hand side
  793. but different right-hand sides, such as the rules for $\Exp$ in the
  794. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  795. combine several right-hand-sides into a single rule.
  796. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  797. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  798. defined in Figure~\ref{fig:r0-concrete-syntax}.
  799. \racket{The \code{read-program} function provided in
  800. \code{utilities.rkt} of the support code reads a program in from a
  801. file (the sequence of characters in the concrete syntax of Racket)
  802. and parses it into an abstract syntax tree. See the description of
  803. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  804. details.}
  805. \python{The \code{parse} function in Python's \code{ast} module
  806. converts the concrete syntax (represented as a string) into an
  807. abstract syntax tree.}
  808. \newcommand{\LintGrammarRacket}{
  809. \begin{array}{rcl}
  810. \Type &::=& \key{Integer} \\
  811. \Exp{} &::=& \Int{} \MID \CREAD \RP \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  812. \end{array}
  813. }
  814. \newcommand{\LintASTRacket}{
  815. \begin{array}{rcl}
  816. \Type &::=& \key{Integer} \\
  817. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  818. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp}
  819. \end{array}
  820. }
  821. \newcommand{\LintGrammarPython}{
  822. \begin{array}{rcl}
  823. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  824. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  825. \end{array}
  826. }
  827. \newcommand{\LintASTPython}{
  828. \begin{array}{rcl}
  829. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  830. \itm{unaryop} &::= & \code{USub()} \\
  831. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  832. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  833. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  834. \end{array}
  835. }
  836. \begin{figure}[tp]
  837. \fbox{
  838. \begin{minipage}{0.96\textwidth}
  839. {\if\edition\racketEd
  840. \[
  841. \begin{array}{l}
  842. \LintGrammarRacket \\
  843. \begin{array}{rcl}
  844. \LangInt{} &::=& \Exp
  845. \end{array}
  846. \end{array}
  847. \]
  848. \fi}
  849. {\if\edition\pythonEd
  850. \[
  851. \begin{array}{l}
  852. \LintGrammarPython \\
  853. \begin{array}{rcl}
  854. \LangInt{} &::=& \Stmt^{*}
  855. \end{array}
  856. \end{array}
  857. \]
  858. \fi}
  859. \end{minipage}
  860. }
  861. \caption{The concrete syntax of \LangInt{}.}
  862. \label{fig:r0-concrete-syntax}
  863. \end{figure}
  864. \begin{figure}[tp]
  865. \fbox{
  866. \begin{minipage}{0.96\textwidth}
  867. {\if\edition\racketEd
  868. \[
  869. \begin{array}{l}
  870. \LintASTRacket{} \\
  871. \begin{array}{rcl}
  872. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  873. \end{array}
  874. \end{array}
  875. \]
  876. \fi}
  877. {\if\edition\pythonEd
  878. \[
  879. \begin{array}{l}
  880. \LintASTPython\\
  881. \begin{array}{rcl}
  882. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  883. \end{array}
  884. \end{array}
  885. \]
  886. \fi}
  887. \end{minipage}
  888. }
  889. \caption{The abstract syntax of \LangInt{}.}
  890. \label{fig:r0-syntax}
  891. \end{figure}
  892. \section{Pattern Matching}
  893. \label{sec:pattern-matching}
  894. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  895. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  896. \texttt{match} feature to access the parts of a value.
  897. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  898. \begin{center}
  899. \begin{minipage}{0.5\textwidth}
  900. {\if\edition\racketEd
  901. \begin{lstlisting}
  902. (match ast1_1
  903. [(Prim op (list child1 child2))
  904. (print op)])
  905. \end{lstlisting}
  906. \fi}
  907. {\if\edition\pythonEd
  908. \begin{lstlisting}
  909. match ast1_1:
  910. case BinOp(child1, op, child2):
  911. print(op)
  912. \end{lstlisting}
  913. \fi}
  914. \end{minipage}
  915. \end{center}
  916. {\if\edition\racketEd
  917. %
  918. In the above example, the \texttt{match} form checks whether the AST
  919. \eqref{eq:arith-prog} is a binary operator, binds its parts to the
  920. three pattern variables \texttt{op}, \texttt{child1}, and
  921. \texttt{child2}, and then prints out the operator. In general, a match
  922. clause consists of a \emph{pattern} and a
  923. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  924. to be either a pattern variable, a structure name followed by a
  925. pattern for each of the structure's arguments, or an S-expression
  926. (symbols, lists, etc.). (See Chapter 12 of The Racket
  927. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  928. and Chapter 9 of The Racket
  929. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  930. for a complete description of \code{match}.)
  931. %
  932. The body of a match clause may contain arbitrary Racket code. The
  933. pattern variables can be used in the scope of the body, such as
  934. \code{op} in \code{(print op)}.
  935. %
  936. \fi}
  937. %
  938. %
  939. {\if\edition\pythonEd
  940. %
  941. In the above example, the \texttt{match} form checks whether the AST
  942. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  943. three pattern variables \texttt{child1}, \texttt{op}, and
  944. \texttt{child2}, and then prints out the operator. In general, each
  945. \code{case} consists of a \emph{pattern} and a
  946. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  947. to be either a pattern variable, a class name followed by a pattern
  948. for each of its constructor's arguments, or other literals such as
  949. strings, lists, etc.
  950. %
  951. The body of each \code{case} may contain arbitrary Python code. The
  952. pattern variables can be used in the body, such as \code{op} in
  953. \code{print(op)}.
  954. %
  955. \fi}
  956. A \code{match} form may contain several clauses, as in the following
  957. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  958. the AST. The \code{match} proceeds through the clauses in order,
  959. checking whether the pattern can match the input AST. The body of the
  960. first clause that matches is executed. The output of \code{leaf} for
  961. several ASTs is shown on the right.
  962. \begin{center}
  963. \begin{minipage}{0.6\textwidth}
  964. {\if\edition\racketEd
  965. \begin{lstlisting}
  966. (define (leaf arith)
  967. (match arith
  968. [(Int n) #t]
  969. [(Prim 'read '()) #t]
  970. [(Prim '- (list e1)) #f]
  971. [(Prim '+ (list e1 e2)) #f]))
  972. (leaf (Prim 'read '()))
  973. (leaf (Prim '- (list (Int 8))))
  974. (leaf (Int 8))
  975. \end{lstlisting}
  976. \fi}
  977. {\if\edition\pythonEd
  978. \begin{lstlisting}
  979. def leaf(arith):
  980. match arith:
  981. case Constant(n):
  982. return True
  983. case Call(Name('input_int'), []):
  984. return True
  985. case UnaryOp(USub(), e1):
  986. return False
  987. case BinOp(e1, Add(), e2):
  988. return False
  989. print(leaf(Call(Name('input_int'), [])))
  990. print(leaf(UnaryOp(USub(), eight)))
  991. print(leaf(Constant(8)))
  992. \end{lstlisting}
  993. \fi}
  994. \end{minipage}
  995. \vrule
  996. \begin{minipage}{0.25\textwidth}
  997. {\if\edition\racketEd
  998. \begin{lstlisting}
  999. #t
  1000. #f
  1001. #t
  1002. \end{lstlisting}
  1003. \fi}
  1004. {\if\edition\pythonEd
  1005. \begin{lstlisting}
  1006. True
  1007. False
  1008. True
  1009. \end{lstlisting}
  1010. \fi}
  1011. \end{minipage}
  1012. \end{center}
  1013. When writing a \code{match}, we refer to the grammar definition to
  1014. identify which non-terminal we are expecting to match against, then we
  1015. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  1016. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  1017. corresponding right-hand side of a grammar rule. For the \code{match}
  1018. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  1019. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  1020. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  1021. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  1022. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  1023. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  1024. patterns, replace non-terminals such as $\Exp$ with pattern variables
  1025. of your choice (e.g. \code{e1} and \code{e2}).
  1026. \section{Recursive Functions}
  1027. \label{sec:recursion}
  1028. \index{subject}{recursive function}
  1029. Programs are inherently recursive. For example, an expression is often
  1030. made of smaller expressions. Thus, the natural way to process an
  1031. entire program is with a recursive function. As a first example of
  1032. such a recursive function, we define the function \code{exp} in
  1033. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1034. determines whether or not it is an expression in \LangInt{}.
  1035. %
  1036. We say that a function is defined by \emph{structural recursion} when
  1037. it is defined using a sequence of match \racket{clauses}\python{cases}
  1038. that correspond to a grammar, and the body of each
  1039. \racket{clause}\python{case} makes a recursive call on each child
  1040. node.\footnote{This principle of structuring code according to the
  1041. data definition is advocated in the book \emph{How to Design
  1042. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}
  1043. \python{We define a second function, named \code{stmt}, that
  1044. recognizes whether a value is a \LangInt{} statement.}
  1045. \python{Finally, } Figure~\ref{fig:exp-predicate} \racket{also}
  1046. defines \code{Lint}, which determines whether an AST is a program in
  1047. \LangInt{}. In general we can expect to write one recursive function
  1048. to handle each non-terminal in a grammar.\index{subject}{structural
  1049. recursion} Of the two examples at the bottom of the figure, the
  1050. first is in \code{Lint} and the second is not.
  1051. \begin{figure}[tp]
  1052. {\if\edition\racketEd
  1053. \begin{lstlisting}
  1054. (define (exp ast)
  1055. (match ast
  1056. [(Int n) #t]
  1057. [(Prim 'read '()) #t]
  1058. [(Prim '- (list e)) (exp e)]
  1059. [(Prim '+ (list e1 e2))
  1060. (and (exp e1) (exp e2))]
  1061. [else #f]))
  1062. (define (Lint ast)
  1063. (match ast
  1064. [(Program '() e) (exp e)]
  1065. [else #f]))
  1066. (Lint (Program '() ast1_1)
  1067. (Lint (Program '()
  1068. (Prim '- (list (Prim 'read '())
  1069. (Prim '+ (list (Int 8)))))))
  1070. \end{lstlisting}
  1071. \fi}
  1072. {\if\edition\pythonEd
  1073. \begin{lstlisting}
  1074. def exp(e):
  1075. match e:
  1076. case Constant(n):
  1077. return True
  1078. case Call(Name('input_int'), []):
  1079. return True
  1080. case UnaryOp(USub(), e1):
  1081. return exp(e1)
  1082. case BinOp(e1, Add(), e2):
  1083. return exp(e1) and exp(e2)
  1084. case BinOp(e1, Sub(), e2):
  1085. return exp(e1) and exp(e2)
  1086. case _:
  1087. return False
  1088. def stmt(s):
  1089. match s:
  1090. case Expr(Call(Name('print'), [e])):
  1091. return exp(e)
  1092. case Expr(e):
  1093. return exp(e)
  1094. case _:
  1095. return False
  1096. def Lint(p):
  1097. match p:
  1098. case Module(body):
  1099. return all([stmt(s) for s in body])
  1100. case _:
  1101. return False
  1102. print(Lint(Module([Expr(ast1_1)])))
  1103. print(Lint(Module([Expr(BinOp(read, Sub(),
  1104. UnaryOp(Add(), Constant(8))))])))
  1105. \end{lstlisting}
  1106. \fi}
  1107. \caption{Example of recursive functions for \LangInt{}. These functions
  1108. recognize whether an AST is in \LangInt{}.}
  1109. \label{fig:exp-predicate}
  1110. \end{figure}
  1111. %% You may be tempted to merge the two functions into one, like this:
  1112. %% \begin{center}
  1113. %% \begin{minipage}{0.5\textwidth}
  1114. %% \begin{lstlisting}
  1115. %% (define (Lint ast)
  1116. %% (match ast
  1117. %% [(Int n) #t]
  1118. %% [(Prim 'read '()) #t]
  1119. %% [(Prim '- (list e)) (Lint e)]
  1120. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1121. %% [(Program '() e) (Lint e)]
  1122. %% [else #f]))
  1123. %% \end{lstlisting}
  1124. %% \end{minipage}
  1125. %% \end{center}
  1126. %% %
  1127. %% Sometimes such a trick will save a few lines of code, especially when
  1128. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1129. %% \emph{not} recommended because it can get you into trouble.
  1130. %% %
  1131. %% For example, the above function is subtly wrong:
  1132. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1133. %% returns true when it should return false.
  1134. \section{Interpreters}
  1135. \label{sec:interp_Lint}
  1136. \index{subject}{interpreter}
  1137. The behavior of a program is defined by the specification of the
  1138. programming language.
  1139. %
  1140. \racket{For example, the Scheme language is defined in the report by
  1141. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1142. reference manual~\citep{plt-tr}.}
  1143. %
  1144. \python{For example, the Python language is defined in the Python
  1145. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1146. %
  1147. In this book we use interpreters
  1148. to specify each language that we consider. An interpreter that is
  1149. designated as the definition of a language is called a
  1150. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1151. \index{subject}{definitional interpreter} We warm up by creating a
  1152. definitional interpreter for the \LangInt{} language, which serves as
  1153. a second example of structural recursion. The \code{interp\_Lint}
  1154. function is defined in Figure~\ref{fig:interp_Lint}.
  1155. %
  1156. \racket{The body of the function is a match on the input program
  1157. followed by a call to the \lstinline{interp_exp} helper function,
  1158. which in turn has one match clause per grammar rule for \LangInt{}
  1159. expressions.}
  1160. %
  1161. \python{The body of the function matches on the \code{Module} AST node
  1162. and then invokes \code{interp\_stmt} on each statement in the
  1163. module. The \code{interp\_stmt} function includes a case for each
  1164. grammar rule of the \Stmt{} non-terminal and it calls
  1165. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1166. function includes a case for each grammar rule of the \Exp{}
  1167. non-terminal.}
  1168. \begin{figure}[tp]
  1169. {\if\edition\racketEd
  1170. \begin{lstlisting}
  1171. (define (interp_exp e)
  1172. (match e
  1173. [(Int n) n]
  1174. [(Prim 'read '())
  1175. (define r (read))
  1176. (cond [(fixnum? r) r]
  1177. [else (error 'interp_exp "read expected an integer" r)])]
  1178. [(Prim '- (list e))
  1179. (define v (interp_exp e))
  1180. (fx- 0 v)]
  1181. [(Prim '+ (list e1 e2))
  1182. (define v1 (interp_exp e1))
  1183. (define v2 (interp_exp e2))
  1184. (fx+ v1 v2)]))
  1185. (define (interp_Lint p)
  1186. (match p
  1187. [(Program '() e) (interp_exp e)]))
  1188. \end{lstlisting}
  1189. \fi}
  1190. {\if\edition\pythonEd
  1191. \begin{lstlisting}
  1192. def interp_exp(e):
  1193. match e:
  1194. case BinOp(left, Add(), right):
  1195. l = interp_exp(left); r = interp_exp(right)
  1196. return l + r
  1197. case BinOp(left, Sub(), right):
  1198. l = interp_exp(left); r = interp_exp(right)
  1199. return l - r
  1200. case UnaryOp(USub(), v):
  1201. return - interp_exp(v)
  1202. case Constant(value):
  1203. return value
  1204. case Call(Name('input_int'), []):
  1205. return int(input())
  1206. def interp_stmt(s):
  1207. match s:
  1208. case Expr(Call(Name('print'), [arg])):
  1209. print(interp_exp(arg))
  1210. case Expr(value):
  1211. interp_exp(value)
  1212. def interp_Lint(p):
  1213. match p:
  1214. case Module(body):
  1215. for s in body:
  1216. interp_stmt(s)
  1217. \end{lstlisting}
  1218. \fi}
  1219. \caption{Interpreter for the \LangInt{} language.}
  1220. \label{fig:interp_Lint}
  1221. \end{figure}
  1222. Let us consider the result of interpreting a few \LangInt{} programs. The
  1223. following program adds two integers.
  1224. {\if\edition\racketEd
  1225. \begin{lstlisting}
  1226. (+ 10 32)
  1227. \end{lstlisting}
  1228. \fi}
  1229. {\if\edition\pythonEd
  1230. \begin{lstlisting}
  1231. print(10 + 32)
  1232. \end{lstlisting}
  1233. \fi}
  1234. The result is \key{42}, the answer to life, the universe, and
  1235. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1236. Galaxy} by Douglas Adams.}
  1237. %
  1238. We wrote the above program in concrete syntax whereas the parsed
  1239. abstract syntax is:
  1240. {\if\edition\racketEd
  1241. \begin{lstlisting}
  1242. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1243. \end{lstlisting}
  1244. \fi}
  1245. {\if\edition\pythonEd
  1246. \begin{lstlisting}
  1247. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1248. \end{lstlisting}
  1249. \fi}
  1250. The next example demonstrates that expressions may be nested within
  1251. each other, in this case nesting several additions and negations.
  1252. {\if\edition\racketEd
  1253. \begin{lstlisting}
  1254. (+ 10 (- (+ 12 20)))
  1255. \end{lstlisting}
  1256. \fi}
  1257. {\if\edition\pythonEd
  1258. \begin{lstlisting}
  1259. print(10 + -(12 + 20))
  1260. \end{lstlisting}
  1261. \fi}
  1262. %
  1263. \noindent What is the result of the above program?
  1264. {\if\edition\racketEd
  1265. As mentioned previously, the \LangInt{} language does not support
  1266. arbitrarily-large integers, but only $63$-bit integers, so we
  1267. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1268. in Racket.
  1269. Suppose
  1270. \[
  1271. n = 999999999999999999
  1272. \]
  1273. which indeed fits in $63$-bits. What happens when we run the
  1274. following program in our interpreter?
  1275. \begin{lstlisting}
  1276. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1277. \end{lstlisting}
  1278. It produces an error:
  1279. \begin{lstlisting}
  1280. fx+: result is not a fixnum
  1281. \end{lstlisting}
  1282. We establish the convention that if running the definitional
  1283. interpreter on a program produces an error then the meaning of that
  1284. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1285. error is a \code{trapped-error}. A compiler for the language is under
  1286. no obligations regarding programs with unspecified behavior; it does
  1287. not have to produce an executable, and if it does, that executable can
  1288. do anything. On the other hand, if the error is a
  1289. \code{trapped-error}, then the compiler must produce an executable and
  1290. it is required to report that an error occurred. To signal an error,
  1291. exit with a return code of \code{255}. The interpreters in chapters
  1292. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1293. \code{trapped-error}.
  1294. \fi}
  1295. % TODO: how to deal with too-large integers in the Python interpreter?
  1296. %% This convention applies to the languages defined in this
  1297. %% book, as a way to simplify the student's task of implementing them,
  1298. %% but this convention is not applicable to all programming languages.
  1299. %%
  1300. Moving on to the last feature of the \LangInt{} language, the
  1301. \READOP{} operation prompts the user of the program for an integer.
  1302. Recall that program \eqref{eq:arith-prog} requests an integer input
  1303. and then subtracts \code{8}. So if we run
  1304. {\if\edition\racketEd
  1305. \begin{lstlisting}
  1306. (interp_Lint (Program '() ast1_1))
  1307. \end{lstlisting}
  1308. \fi}
  1309. {\if\edition\pythonEd
  1310. \begin{lstlisting}
  1311. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1312. \end{lstlisting}
  1313. \fi}
  1314. \noindent and if the input is \code{50}, the result is \code{42}.
  1315. We include the \READOP{} operation in \LangInt{} so a clever student
  1316. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1317. during compilation to obtain the output and then generates the trivial
  1318. code to produce the output.\footnote{Yes, a clever student did this in the
  1319. first instance of this course!}
  1320. The job of a compiler is to translate a program in one language into a
  1321. program in another language so that the output program behaves the
  1322. same way as the input program. This idea is depicted in the
  1323. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1324. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1325. Given a compiler that translates from language $\mathcal{L}_1$ to
  1326. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1327. compiler must translate it into some program $P_2$ such that
  1328. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1329. same input $i$ yields the same output $o$.
  1330. \begin{equation} \label{eq:compile-correct}
  1331. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1332. \node (p1) at (0, 0) {$P_1$};
  1333. \node (p2) at (3, 0) {$P_2$};
  1334. \node (o) at (3, -2.5) {$o$};
  1335. \path[->] (p1) edge [above] node {compile} (p2);
  1336. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1337. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1338. \end{tikzpicture}
  1339. \end{equation}
  1340. In the next section we see our first example of a compiler.
  1341. \section{Example Compiler: a Partial Evaluator}
  1342. \label{sec:partial-evaluation}
  1343. In this section we consider a compiler that translates \LangInt{}
  1344. programs into \LangInt{} programs that may be more efficient. The
  1345. compiler eagerly computes the parts of the program that do not depend
  1346. on any inputs, a process known as \emph{partial
  1347. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1348. For example, given the following program
  1349. {\if\edition\racketEd
  1350. \begin{lstlisting}
  1351. (+ (read) (- (+ 5 3)))
  1352. \end{lstlisting}
  1353. \fi}
  1354. {\if\edition\pythonEd
  1355. \begin{lstlisting}
  1356. print(input_int() + -(5 + 3) )
  1357. \end{lstlisting}
  1358. \fi}
  1359. \noindent our compiler translates it into the program
  1360. {\if\edition\racketEd
  1361. \begin{lstlisting}
  1362. (+ (read) -8)
  1363. \end{lstlisting}
  1364. \fi}
  1365. {\if\edition\pythonEd
  1366. \begin{lstlisting}
  1367. print(input_int() + -8)
  1368. \end{lstlisting}
  1369. \fi}
  1370. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1371. evaluator for the \LangInt{} language. The output of the partial evaluator
  1372. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1373. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1374. whereas the code for partially evaluating the negation and addition
  1375. operations is factored into two auxiliary functions:
  1376. \code{pe\_neg} and \code{pe\_add}. The input to these
  1377. functions is the output of partially evaluating the children.
  1378. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1379. arguments are integers and if they are, perform the appropriate
  1380. arithmetic. Otherwise, they create an AST node for the arithmetic
  1381. operation.
  1382. \begin{figure}[tp]
  1383. {\if\edition\racketEd
  1384. \begin{lstlisting}
  1385. (define (pe_neg r)
  1386. (match r
  1387. [(Int n) (Int (fx- 0 n))]
  1388. [else (Prim '- (list r))]))
  1389. (define (pe_add r1 r2)
  1390. (match* (r1 r2)
  1391. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1392. [(_ _) (Prim '+ (list r1 r2))]))
  1393. (define (pe_exp e)
  1394. (match e
  1395. [(Int n) (Int n)]
  1396. [(Prim 'read '()) (Prim 'read '())]
  1397. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1398. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1399. (define (pe_Lint p)
  1400. (match p
  1401. [(Program '() e) (Program '() (pe_exp e))]))
  1402. \end{lstlisting}
  1403. \fi}
  1404. {\if\edition\pythonEd
  1405. \begin{lstlisting}
  1406. def pe_neg(r):
  1407. match r:
  1408. case Constant(n):
  1409. return Constant(-n)
  1410. case _:
  1411. return UnaryOp(USub(), r)
  1412. def pe_add(r1, r2):
  1413. match (r1, r2):
  1414. case (Constant(n1), Constant(n2)):
  1415. return Constant(n1 + n2)
  1416. case _:
  1417. return BinOp(r1, Add(), r2)
  1418. def pe_sub(r1, r2):
  1419. match (r1, r2):
  1420. case (Constant(n1), Constant(n2)):
  1421. return Constant(n1 - n2)
  1422. case _:
  1423. return BinOp(r1, Sub(), r2)
  1424. def pe_exp(e):
  1425. match e:
  1426. case BinOp(left, Add(), right):
  1427. return pe_add(pe_exp(left), pe_exp(right))
  1428. case BinOp(left, Sub(), right):
  1429. return pe_sub(pe_exp(left), pe_exp(right))
  1430. case UnaryOp(USub(), v):
  1431. return pe_neg(pe_exp(v))
  1432. case Constant(value):
  1433. return e
  1434. case Call(Name('input_int'), []):
  1435. return e
  1436. def pe_stmt(s):
  1437. match s:
  1438. case Expr(Call(Name('print'), [arg])):
  1439. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1440. case Expr(value):
  1441. return Expr(pe_exp(value))
  1442. def pe_P_int(p):
  1443. match p:
  1444. case Module(body):
  1445. new_body = [pe_stmt(s) for s in body]
  1446. return Module(new_body)
  1447. \end{lstlisting}
  1448. \fi}
  1449. \caption{A partial evaluator for \LangInt{}.}
  1450. \label{fig:pe-arith}
  1451. \end{figure}
  1452. To gain some confidence that the partial evaluator is correct, we can
  1453. test whether it produces programs that get the same result as the
  1454. input programs. That is, we can test whether it satisfies Diagram
  1455. \ref{eq:compile-correct}.
  1456. %
  1457. {\if\edition\racketEd
  1458. The following code runs the partial evaluator on several examples and
  1459. tests the output program. The \texttt{parse-program} and
  1460. \texttt{assert} functions are defined in
  1461. Appendix~\ref{appendix:utilities}.\\
  1462. \begin{minipage}{1.0\textwidth}
  1463. \begin{lstlisting}
  1464. (define (test_pe p)
  1465. (assert "testing pe_Lint"
  1466. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1467. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1468. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1469. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1470. \end{lstlisting}
  1471. \end{minipage}
  1472. \fi}
  1473. % TODO: python version of testing the PE
  1474. \begin{exercise}\normalfont
  1475. Create three programs in the \LangInt{} language and test whether
  1476. partially evaluating them with \code{pe\_Lint} and then
  1477. interpreting them with \code{interp\_Lint} gives the same result
  1478. as directly interpreting them with \code{interp\_Lint}.
  1479. \end{exercise}
  1480. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1481. \chapter{Integers and Variables}
  1482. \label{ch:Lvar}
  1483. This chapter is about compiling a subset of
  1484. \racket{Racket}\python{Python} to x86-64 assembly
  1485. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1486. integer arithmetic and local variables. We often refer to x86-64
  1487. simply as x86. The chapter begins with a description of the
  1488. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1489. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1490. large so we discuss only the instructions needed for compiling
  1491. \LangVar{}. We introduce more x86 instructions in later chapters.
  1492. After introducing \LangVar{} and x86, we reflect on their differences
  1493. and come up with a plan to break down the translation from \LangVar{}
  1494. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1495. rest of the sections in this chapter give detailed hints regarding
  1496. each step. We hope to give enough hints that the well-prepared
  1497. reader, together with a few friends, can implement a compiler from
  1498. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1499. the scale of this first compiler, the instructor solution for the
  1500. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1501. code.
  1502. \section{The \LangVar{} Language}
  1503. \label{sec:s0}
  1504. \index{subject}{variable}
  1505. The \LangVar{} language extends the \LangInt{} language with
  1506. variables. The concrete syntax of the \LangVar{} language is defined
  1507. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1508. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1509. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1510. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1511. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1512. syntax of \LangVar{} includes the \racket{\key{Program}
  1513. struct}\python{\key{Module} instance} to mark the top of the
  1514. program.
  1515. %% The $\itm{info}$
  1516. %% field of the \key{Program} structure contains an \emph{association
  1517. %% list} (a list of key-value pairs) that is used to communicate
  1518. %% auxiliary data from one compiler pass the next.
  1519. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1520. exhibit several compilation techniques.
  1521. \newcommand{\LvarGrammarRacket}{
  1522. \begin{array}{rcl}
  1523. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1524. \end{array}
  1525. }
  1526. \newcommand{\LvarASTRacket}{
  1527. \begin{array}{rcl}
  1528. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1529. \end{array}
  1530. }
  1531. \newcommand{\LvarGrammarPython}{
  1532. \begin{array}{rcl}
  1533. \Exp &::=& \Var{} \\
  1534. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1535. \end{array}
  1536. }
  1537. \newcommand{\LvarASTPython}{
  1538. \begin{array}{rcl}
  1539. \Exp{} &::=& \VAR{\Var{}} \\
  1540. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1541. \end{array}
  1542. }
  1543. \begin{figure}[tp]
  1544. \centering
  1545. \fbox{
  1546. \begin{minipage}{0.96\textwidth}
  1547. {\if\edition\racketEd
  1548. \[
  1549. \begin{array}{l}
  1550. \gray{\LintGrammarRacket{}} \\ \hline
  1551. \LvarGrammarRacket{} \\
  1552. \begin{array}{rcl}
  1553. \LangVarM{} &::=& \Exp
  1554. \end{array}
  1555. \end{array}
  1556. \]
  1557. \fi}
  1558. {\if\edition\pythonEd
  1559. \[
  1560. \begin{array}{l}
  1561. \gray{\LintGrammarPython} \\ \hline
  1562. \LvarGrammarPython \\
  1563. \begin{array}{rcl}
  1564. \LangVarM{} &::=& \Stmt^{*}
  1565. \end{array}
  1566. \end{array}
  1567. \]
  1568. \fi}
  1569. \end{minipage}
  1570. }
  1571. \caption{The concrete syntax of \LangVar{}.}
  1572. \label{fig:Lvar-concrete-syntax}
  1573. \end{figure}
  1574. \begin{figure}[tp]
  1575. \centering
  1576. \fbox{
  1577. \begin{minipage}{0.96\textwidth}
  1578. {\if\edition\racketEd
  1579. \[
  1580. \begin{array}{l}
  1581. \gray{\LintASTRacket{}} \\ \hline
  1582. \LvarASTRacket \\
  1583. \begin{array}{rcl}
  1584. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1585. \end{array}
  1586. \end{array}
  1587. \]
  1588. \fi}
  1589. {\if\edition\pythonEd
  1590. \[
  1591. \begin{array}{l}
  1592. \gray{\LintASTPython}\\ \hline
  1593. \LvarASTPython \\
  1594. \begin{array}{rcl}
  1595. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1596. \end{array}
  1597. \end{array}
  1598. \]
  1599. \fi}
  1600. \end{minipage}
  1601. }
  1602. \caption{The abstract syntax of \LangVar{}.}
  1603. \label{fig:Lvar-syntax}
  1604. \end{figure}
  1605. {\if\edition\racketEd
  1606. Let us dive further into the syntax and semantics of the \LangVar{}
  1607. language. The \key{let} feature defines a variable for use within its
  1608. body and initializes the variable with the value of an expression.
  1609. The abstract syntax for \key{let} is defined in
  1610. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1611. \begin{lstlisting}
  1612. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1613. \end{lstlisting}
  1614. For example, the following program initializes \code{x} to $32$ and then
  1615. evaluates the body \code{(+ 10 x)}, producing $42$.
  1616. \begin{lstlisting}
  1617. (let ([x (+ 12 20)]) (+ 10 x))
  1618. \end{lstlisting}
  1619. \fi}
  1620. %
  1621. {\if\edition\pythonEd
  1622. %
  1623. The \LangVar{} language includes assignment statements, which define a
  1624. variable for use in later statements and initializes the variable with
  1625. the value of an expression. The abstract syntax for assignment is
  1626. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1627. assignment is
  1628. \begin{lstlisting}
  1629. |$\itm{var}$| = |$\itm{exp}$|
  1630. \end{lstlisting}
  1631. For example, the following program initializes the variable \code{x}
  1632. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1633. \begin{lstlisting}
  1634. x = 12 + 20
  1635. print(10 + x)
  1636. \end{lstlisting}
  1637. \fi}
  1638. {\if\edition\racketEd
  1639. %
  1640. When there are multiple \key{let}'s for the same variable, the closest
  1641. enclosing \key{let} is used. That is, variable definitions overshadow
  1642. prior definitions. Consider the following program with two \key{let}'s
  1643. that define variables named \code{x}. Can you figure out the result?
  1644. \begin{lstlisting}
  1645. (let ([x 32]) (+ (let ([x 10]) x) x))
  1646. \end{lstlisting}
  1647. For the purposes of depicting which variable uses correspond to which
  1648. definitions, the following shows the \code{x}'s annotated with
  1649. subscripts to distinguish them. Double check that your answer for the
  1650. above is the same as your answer for this annotated version of the
  1651. program.
  1652. \begin{lstlisting}
  1653. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1654. \end{lstlisting}
  1655. The initializing expression is always evaluated before the body of the
  1656. \key{let}, so in the following, the \key{read} for \code{x} is
  1657. performed before the \key{read} for \code{y}. Given the input
  1658. $52$ then $10$, the following produces $42$ (not $-42$).
  1659. \begin{lstlisting}
  1660. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1661. \end{lstlisting}
  1662. \fi}
  1663. \subsection{Extensible Interpreters via Method Overriding}
  1664. \label{sec:extensible-interp}
  1665. To prepare for discussing the interpreter of \LangVar{}, we explain
  1666. why we implement it in an object-oriented style. Throughout this book
  1667. we define many interpreters, one for each of language that we
  1668. study. Because each language builds on the prior one, there is a lot
  1669. of commonality between these interpreters. We want to write down the
  1670. common parts just once instead of many times. A naive approach would
  1671. be for the interpreter of \LangVar{} to handle the
  1672. \racket{cases for variables and \code{let}}
  1673. \python{case for variables}
  1674. but dispatch to \LangInt{}
  1675. for the rest of the cases. The following code sketches this idea. (We
  1676. explain the \code{env} parameter soon, in
  1677. Section~\ref{sec:interp-Lvar}.)
  1678. \begin{center}
  1679. {\if\edition\racketEd
  1680. \begin{minipage}{0.45\textwidth}
  1681. \begin{lstlisting}
  1682. (define ((interp_Lint env) e)
  1683. (match e
  1684. [(Prim '- (list e1))
  1685. (fx- 0 ((interp_Lint env) e1))]
  1686. ...))
  1687. \end{lstlisting}
  1688. \end{minipage}
  1689. \begin{minipage}{0.45\textwidth}
  1690. \begin{lstlisting}
  1691. (define ((interp_Lvar env) e)
  1692. (match e
  1693. [(Var x)
  1694. (dict-ref env x)]
  1695. [(Let x e body)
  1696. (define v ((interp_exp env) e))
  1697. (define env^ (dict-set env x v))
  1698. ((interp_exp env^) body)]
  1699. [else ((interp_Lint env) e)]))
  1700. \end{lstlisting}
  1701. \end{minipage}
  1702. \fi}
  1703. {\if\edition\pythonEd
  1704. \begin{minipage}{0.45\textwidth}
  1705. \begin{lstlisting}
  1706. def interp_Lint(e, env):
  1707. match e:
  1708. case UnaryOp(USub(), e1):
  1709. return - interp_Lint(e1, env)
  1710. ...
  1711. \end{lstlisting}
  1712. \end{minipage}
  1713. \begin{minipage}{0.45\textwidth}
  1714. \begin{lstlisting}
  1715. def interp_Lvar(e, env):
  1716. match e:
  1717. case Name(id):
  1718. return env[id]
  1719. case _:
  1720. return interp_Lint(e, env)
  1721. \end{lstlisting}
  1722. \end{minipage}
  1723. \fi}
  1724. \end{center}
  1725. The problem with this approach is that it does not handle situations
  1726. in which an \LangVar{} feature, such as a variable, is nested inside
  1727. an \LangInt{} feature, like the \code{-} operator, as in the following
  1728. program.
  1729. %
  1730. {\if\edition\racketEd
  1731. \begin{lstlisting}
  1732. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1733. \end{lstlisting}
  1734. \fi}
  1735. {\if\edition\pythonEd
  1736. \begin{lstlisting}
  1737. y = 10
  1738. print(-y)
  1739. \end{lstlisting}
  1740. \fi}
  1741. %
  1742. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1743. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1744. then it recursively calls \code{interp\_Lint} again on its argument.
  1745. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1746. an error!
  1747. To make our interpreters extensible we need something called
  1748. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1749. recursive knot is delayed to when the functions are
  1750. composed. Object-oriented languages provide open recursion via
  1751. method overriding\index{subject}{method overriding}. The
  1752. following code uses method overriding to interpret \LangInt{} and
  1753. \LangVar{} using
  1754. %
  1755. \racket{the
  1756. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1757. \index{subject}{class} feature of Racket}
  1758. %
  1759. \python{a Python \code{class} definition}.
  1760. %
  1761. We define one class for each language and define a method for
  1762. interpreting expressions inside each class. The class for \LangVar{}
  1763. inherits from the class for \LangInt{} and the method
  1764. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1765. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1766. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1767. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1768. \code{interp\_exp} in \LangInt{}.
  1769. \begin{center}
  1770. \hspace{-20pt}
  1771. {\if\edition\racketEd
  1772. \begin{minipage}{0.45\textwidth}
  1773. \begin{lstlisting}
  1774. (define interp_Lint_class
  1775. (class object%
  1776. (define/public ((interp_exp env) e)
  1777. (match e
  1778. [(Prim '- (list e))
  1779. (fx- 0 ((interp_exp env) e))]
  1780. ...))
  1781. ...))
  1782. \end{lstlisting}
  1783. \end{minipage}
  1784. \begin{minipage}{0.45\textwidth}
  1785. \begin{lstlisting}
  1786. (define interp_Lvar_class
  1787. (class interp_Lint_class
  1788. (define/override ((interp_exp env) e)
  1789. (match e
  1790. [(Var x)
  1791. (dict-ref env x)]
  1792. [(Let x e body)
  1793. (define v ((interp_exp env) e))
  1794. (define env^ (dict-set env x v))
  1795. ((interp_exp env^) body)]
  1796. [else
  1797. (super (interp_exp env) e)]))
  1798. ...
  1799. ))
  1800. \end{lstlisting}
  1801. \end{minipage}
  1802. \fi}
  1803. {\if\edition\pythonEd
  1804. \begin{minipage}{0.45\textwidth}
  1805. \begin{lstlisting}
  1806. class InterpLint:
  1807. def interp_exp(e):
  1808. match e:
  1809. case UnaryOp(USub(), e1):
  1810. return -self.interp_exp(e1)
  1811. ...
  1812. ...
  1813. \end{lstlisting}
  1814. \end{minipage}
  1815. \begin{minipage}{0.45\textwidth}
  1816. \begin{lstlisting}
  1817. def InterpLvar(InterpLint):
  1818. def interp_exp(e):
  1819. match e:
  1820. case Name(id):
  1821. return env[id]
  1822. case _:
  1823. return super().interp_exp(e)
  1824. ...
  1825. \end{lstlisting}
  1826. \end{minipage}
  1827. \fi}
  1828. \end{center}
  1829. Getting back to the troublesome example, repeated here:
  1830. {\if\edition\racketEd
  1831. \begin{lstlisting}
  1832. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1833. \end{lstlisting}
  1834. \fi}
  1835. {\if\edition\pythonEd
  1836. \begin{lstlisting}
  1837. y = 10
  1838. print(-y)
  1839. \end{lstlisting}
  1840. \fi}
  1841. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1842. \racket{on this expression,}
  1843. \python{on the \code{-y} expression,}
  1844. %
  1845. call it \code{e0}, by creating an object of the \LangVar{} class
  1846. and calling the \code{interp\_exp} method.
  1847. {\if\edition\racketEd
  1848. \begin{lstlisting}
  1849. (send (new interp_Lvar_class) interp_exp e0)
  1850. \end{lstlisting}
  1851. \fi}
  1852. {\if\edition\pythonEd
  1853. \begin{lstlisting}
  1854. InterpLvar().interp_exp(e0)
  1855. \end{lstlisting}
  1856. \fi}
  1857. \noindent To process the \code{-} operator, the default case of
  1858. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1859. method in \LangInt{}. But then for the recursive method call, it
  1860. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1861. \code{Var} node is handled correctly. Thus, method overriding gives us
  1862. the open recursion that we need to implement our interpreters in an
  1863. extensible way.
  1864. \subsection{Definitional Interpreter for \LangVar{}}
  1865. \label{sec:interp-Lvar}
  1866. {\if\edition\racketEd
  1867. \begin{figure}[tp]
  1868. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1869. \small
  1870. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1871. An \emph{association list} (alist) is a list of key-value pairs.
  1872. For example, we can map people to their ages with an alist.
  1873. \index{subject}{alist}\index{subject}{association list}
  1874. \begin{lstlisting}[basicstyle=\ttfamily]
  1875. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1876. \end{lstlisting}
  1877. The \emph{dictionary} interface is for mapping keys to values.
  1878. Every alist implements this interface. \index{subject}{dictionary} The package
  1879. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1880. provides many functions for working with dictionaries. Here
  1881. are a few of them:
  1882. \begin{description}
  1883. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1884. returns the value associated with the given $\itm{key}$.
  1885. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1886. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1887. but otherwise is the same as $\itm{dict}$.
  1888. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1889. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1890. of keys and values in $\itm{dict}$. For example, the following
  1891. creates a new alist in which the ages are incremented.
  1892. \end{description}
  1893. \vspace{-10pt}
  1894. \begin{lstlisting}[basicstyle=\ttfamily]
  1895. (for/list ([(k v) (in-dict ages)])
  1896. (cons k (add1 v)))
  1897. \end{lstlisting}
  1898. \end{tcolorbox}
  1899. %\end{wrapfigure}
  1900. \caption{Association lists implement the dictionary interface.}
  1901. \label{fig:alist}
  1902. \end{figure}
  1903. \fi}
  1904. Having justified the use of classes and methods to implement
  1905. interpreters, we revisit the definitional interpreter for \LangInt{}
  1906. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1907. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1908. interpreter for \LangVar{} adds two new \key{match} cases for
  1909. variables and \racket{\key{let}}\python{assignment}. For
  1910. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1911. value bound to a variable to all the uses of the variable. To
  1912. accomplish this, we maintain a mapping from variables to values
  1913. called an \emph{environment}\index{subject}{environment}.
  1914. %
  1915. We use%
  1916. %
  1917. \racket{an association list (alist)}
  1918. %
  1919. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}}
  1920. %
  1921. to represent the environment.
  1922. %
  1923. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1924. and the \code{racket/dict} package.}
  1925. %
  1926. The \code{interp\_exp} function takes the current environment,
  1927. \code{env}, as an extra parameter. When the interpreter encounters a
  1928. variable, it looks up the corresponding value in the dictionary.
  1929. %
  1930. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1931. initializing expression, extends the environment with the result
  1932. value bound to the variable, using \code{dict-set}, then evaluates
  1933. the body of the \key{Let}.}
  1934. %
  1935. \python{When the interpreter encounters an assignment, it evaluates
  1936. the initializing expression and then associates the resulting value
  1937. with the variable in the environment.}
  1938. \begin{figure}[tp]
  1939. {\if\edition\racketEd
  1940. \begin{lstlisting}
  1941. (define interp_Lint_class
  1942. (class object%
  1943. (super-new)
  1944. (define/public ((interp_exp env) e)
  1945. (match e
  1946. [(Int n) n]
  1947. [(Prim 'read '())
  1948. (define r (read))
  1949. (cond [(fixnum? r) r]
  1950. [else (error 'interp_exp "expected an integer" r)])]
  1951. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1952. [(Prim '+ (list e1 e2))
  1953. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]))
  1954. (define/public (interp_program p)
  1955. (match p
  1956. [(Program '() e) ((interp_exp '()) e)]))
  1957. ))
  1958. \end{lstlisting}
  1959. \fi}
  1960. {\if\edition\pythonEd
  1961. \begin{lstlisting}
  1962. class InterpLint:
  1963. def interp_exp(self, e, env):
  1964. match e:
  1965. case BinOp(left, Add(), right):
  1966. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1967. case UnaryOp(USub(), v):
  1968. return - self.interp_exp(v, env)
  1969. case Constant(value):
  1970. return value
  1971. case Call(Name('input_int'), []):
  1972. return int(input())
  1973. def interp_stmts(self, ss, env):
  1974. if len(ss) == 0:
  1975. return
  1976. match ss[0]:
  1977. case Expr(Call(Name('print'), [arg])):
  1978. print(self.interp_exp(arg, env), end='')
  1979. return self.interp_stmts(ss[1:], env)
  1980. case Expr(value):
  1981. self.interp_exp(value, env)
  1982. return self.interp_stmts(ss[1:], env)
  1983. def interp(self, p):
  1984. match p:
  1985. case Module(body):
  1986. self.interp_stmts(body, {})
  1987. def interp_Lint(p):
  1988. return InterpLint().interp(p)
  1989. \end{lstlisting}
  1990. \fi}
  1991. \caption{Interpreter for \LangInt{} as a class.}
  1992. \label{fig:interp-Lint-class}
  1993. \end{figure}
  1994. \begin{figure}[tp]
  1995. {\if\edition\racketEd
  1996. \begin{lstlisting}
  1997. (define interp_Lvar_class
  1998. (class interp_Lint_class
  1999. (super-new)
  2000. (define/override ((interp_exp env) e)
  2001. (match e
  2002. [(Var x) (dict-ref env x)]
  2003. [(Let x e body)
  2004. (define new-env (dict-set env x ((interp_exp env) e)))
  2005. ((interp_exp new-env) body)]
  2006. [else ((super interp-exp env) e)]))
  2007. ))
  2008. (define (interp_Lvar p)
  2009. (send (new interp_Lvar_class) interp_program p))
  2010. \end{lstlisting}
  2011. \fi}
  2012. {\if\edition\pythonEd
  2013. \begin{lstlisting}
  2014. class InterpLvar(InterpLint):
  2015. def interp_exp(self, e, env):
  2016. match e:
  2017. case Name(id):
  2018. return env[id]
  2019. case _:
  2020. return super().interp_exp(e, env)
  2021. def interp_stmts(self, ss, env):
  2022. if len(ss) == 0:
  2023. return
  2024. match ss[0]:
  2025. case Assign([lhs], value):
  2026. env[lhs.id] = self.interp_exp(value, env)
  2027. return self.interp_stmts(ss[1:], env)
  2028. case _:
  2029. return super().interp_stmts(ss, env)
  2030. def interp_Lvar(p):
  2031. return InterpLvar().interp(p)
  2032. \end{lstlisting}
  2033. \fi}
  2034. \caption{Interpreter for the \LangVar{} language.}
  2035. \label{fig:interp-Lvar}
  2036. \end{figure}
  2037. The goal for this chapter is to implement a compiler that translates
  2038. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2039. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2040. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2041. That is, they output the same integer $n$. We depict this correctness
  2042. criteria in the following diagram.
  2043. \[
  2044. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2045. \node (p1) at (0, 0) {$P_1$};
  2046. \node (p2) at (4, 0) {$P_2$};
  2047. \node (o) at (4, -2) {$n$};
  2048. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2049. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2050. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2051. \end{tikzpicture}
  2052. \]
  2053. In the next section we introduce the \LangXInt{} subset of x86 that
  2054. suffices for compiling \LangVar{}.
  2055. \section{The \LangXInt{} Assembly Language}
  2056. \label{sec:x86}
  2057. \index{subject}{x86}
  2058. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2059. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2060. assembler.
  2061. %
  2062. A program begins with a \code{main} label followed by a sequence of
  2063. instructions. The \key{globl} directive says that the \key{main}
  2064. procedure is externally visible, which is necessary so that the
  2065. operating system can call it.
  2066. %
  2067. An x86 program is stored in the computer's memory. For our purposes,
  2068. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2069. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2070. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2071. the address of the next instruction to be executed. For most
  2072. instructions, the program counter is incremented after the instruction
  2073. is executed, so it points to the next instruction in memory. Most x86
  2074. instructions take two operands, where each operand is either an
  2075. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2076. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2077. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2078. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2079. && \key{r8} \MID \key{r9} \MID \key{r10}
  2080. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2081. \MID \key{r14} \MID \key{r15}}
  2082. \begin{figure}[tp]
  2083. \fbox{
  2084. \begin{minipage}{0.96\textwidth}
  2085. {\if\edition\racketEd
  2086. \[
  2087. \begin{array}{lcl}
  2088. \Reg &::=& \allregisters{} \\
  2089. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2090. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2091. \key{subq} \; \Arg\key{,} \Arg \MID
  2092. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2093. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2094. \key{callq} \; \mathit{label} \MID
  2095. \key{retq} \MID
  2096. \key{jmp}\,\itm{label} \MID \\
  2097. && \itm{label}\key{:}\; \Instr \\
  2098. \LangXIntM{} &::= & \key{.globl main}\\
  2099. & & \key{main:} \; \Instr\ldots
  2100. \end{array}
  2101. \]
  2102. \fi}
  2103. {\if\edition\pythonEd
  2104. \[
  2105. \begin{array}{lcl}
  2106. \Reg &::=& \allregisters{} \\
  2107. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2108. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2109. \key{subq} \; \Arg\key{,} \Arg \MID
  2110. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2111. && \key{callq} \; \mathit{label} \MID
  2112. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2113. \LangXIntM{} &::= & \key{.globl main}\\
  2114. & & \key{main:} \; \Instr^{*}
  2115. \end{array}
  2116. \]
  2117. \fi}
  2118. \end{minipage}
  2119. }
  2120. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2121. \label{fig:x86-int-concrete}
  2122. \end{figure}
  2123. A register is a special kind of variable that holds a 64-bit
  2124. value. There are 16 general-purpose registers in the computer and
  2125. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2126. is written with a \key{\%} followed by the register name, such as
  2127. \key{\%rax}.
  2128. An immediate value is written using the notation \key{\$}$n$ where $n$
  2129. is an integer.
  2130. %
  2131. %
  2132. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2133. which obtains the address stored in register $r$ and then adds $n$
  2134. bytes to the address. The resulting address is used to load or store
  2135. to memory depending on whether it occurs as a source or destination
  2136. argument of an instruction.
  2137. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2138. source $s$ and destination $d$, applies the arithmetic operation, then
  2139. writes the result back to the destination $d$. \index{subject}{instruction}
  2140. %
  2141. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2142. stores the result in $d$.
  2143. %
  2144. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2145. specified by the label and $\key{retq}$ returns from a procedure to
  2146. its caller.
  2147. %
  2148. We discuss procedure calls in more detail later in this chapter and in
  2149. Chapter~\ref{ch:Lfun}.
  2150. %
  2151. The last letter \key{q} indicates that these instructions operate on
  2152. quadwords, i.e., 64-bit values.
  2153. %
  2154. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2155. counter to the address of the instruction after the specified
  2156. label.}
  2157. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2158. all of the x86 instructions used in this book.
  2159. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2160. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2161. \lstinline{movq $10, %rax}
  2162. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2163. adds $32$ to the $10$ in \key{rax} and
  2164. puts the result, $42$, back into \key{rax}.
  2165. %
  2166. The last instruction, \key{retq}, finishes the \key{main} function by
  2167. returning the integer in \key{rax} to the operating system. The
  2168. operating system interprets this integer as the program's exit
  2169. code. By convention, an exit code of 0 indicates that a program
  2170. completed successfully, and all other exit codes indicate various
  2171. errors.
  2172. %
  2173. \racket{Nevertheless, in this book we return the result of the program
  2174. as the exit code.}
  2175. \begin{figure}[tbp]
  2176. \begin{lstlisting}
  2177. .globl main
  2178. main:
  2179. movq $10, %rax
  2180. addq $32, %rax
  2181. retq
  2182. \end{lstlisting}
  2183. \caption{An x86 program that computes
  2184. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2185. \label{fig:p0-x86}
  2186. \end{figure}
  2187. We exhibit the use of memory for storing intermediate results in the
  2188. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2189. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2190. uses a region of memory called the \emph{procedure call stack} (or
  2191. \emph{stack} for
  2192. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2193. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2194. for each procedure call. The memory layout for an individual frame is
  2195. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2196. \emph{stack pointer}\index{subject}{stack pointer} and it contains the
  2197. address of the item at the top of the stack. In general, we use the
  2198. term \emph{pointer}\index{subject}{pointer} for something that
  2199. contains an address. The stack grows downward in memory, so we
  2200. increase the size of the stack by subtracting from the stack pointer.
  2201. In the context of a procedure call, the \emph{return
  2202. address}\index{subject}{return address} is the instruction after the
  2203. call instruction on the caller side. The function call instruction,
  2204. \code{callq}, pushes the return address onto the stack prior to
  2205. jumping to the procedure. The register \key{rbp} is the \emph{base
  2206. pointer}\index{subject}{base pointer} and is used to access variables
  2207. that are stored in the frame of the current procedure call. The base
  2208. pointer of the caller is store after the return address. In
  2209. Figure~\ref{fig:frame} we number the variables from $1$ to
  2210. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2211. at $-16\key{(\%rbp)}$, etc.
  2212. \begin{figure}[tbp]
  2213. {\if\edition\racketEd
  2214. \begin{lstlisting}
  2215. start:
  2216. movq $10, -8(%rbp)
  2217. negq -8(%rbp)
  2218. movq -8(%rbp), %rax
  2219. addq $52, %rax
  2220. jmp conclusion
  2221. .globl main
  2222. main:
  2223. pushq %rbp
  2224. movq %rsp, %rbp
  2225. subq $16, %rsp
  2226. jmp start
  2227. conclusion:
  2228. addq $16, %rsp
  2229. popq %rbp
  2230. retq
  2231. \end{lstlisting}
  2232. \fi}
  2233. {\if\edition\pythonEd
  2234. \begin{lstlisting}
  2235. .globl main
  2236. main:
  2237. pushq %rbp
  2238. movq %rsp, %rbp
  2239. subq $16, %rsp
  2240. movq $10, -8(%rbp)
  2241. negq -8(%rbp)
  2242. movq -8(%rbp), %rax
  2243. addq $52, %rax
  2244. addq $16, %rsp
  2245. popq %rbp
  2246. retq
  2247. \end{lstlisting}
  2248. \fi}
  2249. \caption{An x86 program that computes
  2250. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2251. \label{fig:p1-x86}
  2252. \end{figure}
  2253. \begin{figure}[tbp]
  2254. \centering
  2255. \begin{tabular}{|r|l|} \hline
  2256. Position & Contents \\ \hline
  2257. 8(\key{\%rbp}) & return address \\
  2258. 0(\key{\%rbp}) & old \key{rbp} \\
  2259. -8(\key{\%rbp}) & variable $1$ \\
  2260. -16(\key{\%rbp}) & variable $2$ \\
  2261. \ldots & \ldots \\
  2262. 0(\key{\%rsp}) & variable $n$\\ \hline
  2263. \end{tabular}
  2264. \caption{Memory layout of a frame.}
  2265. \label{fig:frame}
  2266. \end{figure}
  2267. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2268. control is transferred from the operating system to the \code{main}
  2269. function. The operating system issues a \code{callq main} instruction
  2270. which pushes its return address on the stack and then jumps to
  2271. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2272. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2273. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2274. alignment (because the \code{callq} pushed the return address). The
  2275. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2276. for a procedure. The instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2277. pointer and then saves the base pointer of the caller at address
  2278. \code{rsp} on the stack. The next instruction \code{movq \%rsp, \%rbp} sets the
  2279. base pointer to the current stack pointer, which is pointing at the location
  2280. of the old base pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2281. pointer down to make enough room for storing variables. This program
  2282. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2283. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2284. functions.
  2285. \racket{The last instruction of the prelude is \code{jmp start},
  2286. which transfers control to the instructions that were generated from
  2287. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2288. \racket{The first instruction under the \code{start} label is}
  2289. %
  2290. \python{The first instruction after the prelude is}
  2291. %
  2292. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2293. %
  2294. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2295. %
  2296. The next instruction moves the $-10$ from variable $1$ into the
  2297. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2298. the value in \code{rax}, updating its contents to $42$.
  2299. \racket{The three instructions under the label \code{conclusion} are the
  2300. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2301. %
  2302. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2303. \code{main} function consists of the last three instructions.}
  2304. %
  2305. The first two restore the \code{rsp} and \code{rbp} registers to the
  2306. state they were in at the beginning of the procedure. In particular,
  2307. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2308. old base pointer. Then \key{popq \%rbp} returns the old base pointer
  2309. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2310. \key{retq}, jumps back to the procedure that called this one and adds
  2311. $8$ to the stack pointer.
  2312. Our compiler needs a convenient representation for manipulating x86
  2313. programs, so we define an abstract syntax for x86 in
  2314. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2315. \LangXInt{}.
  2316. %
  2317. {\if\edition\pythonEd%
  2318. The main difference compared to the concrete syntax of \LangXInt{}
  2319. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2320. names, and register names are explicitly represented by strings.
  2321. \fi} %
  2322. {\if\edition\racketEd
  2323. The main difference compared to the concrete syntax of \LangXInt{}
  2324. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2325. front of every instruction. Instead instructions are grouped into
  2326. \emph{blocks}\index{subject}{block} with a
  2327. label associated with every block, which is why the \key{X86Program}
  2328. struct includes an alist mapping labels to blocks. The reason for this
  2329. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2330. introduce conditional branching. The \code{Block} structure includes
  2331. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2332. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2333. $\itm{info}$ field should contain an empty list.
  2334. \fi}
  2335. %
  2336. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2337. node includes an integer for representing the arity of the function,
  2338. i.e., the number of arguments, which is helpful to know during
  2339. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2340. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2341. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2342. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2343. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2344. \MID \skey{r14} \MID \skey{r15}}
  2345. \begin{figure}[tp]
  2346. \fbox{
  2347. \begin{minipage}{0.98\textwidth}
  2348. \small
  2349. {\if\edition\racketEd
  2350. \[
  2351. \begin{array}{lcl}
  2352. \Reg &::=& \allregisters{} \\
  2353. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2354. \MID \DEREF{\Reg}{\Int} \\
  2355. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2356. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2357. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2358. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2359. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2360. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2361. \MID \RETQ{}
  2362. \MID \JMP{\itm{label}} \\
  2363. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2364. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2365. \end{array}
  2366. \]
  2367. \fi}
  2368. {\if\edition\pythonEd
  2369. \[
  2370. \begin{array}{lcl}
  2371. \Reg &::=& \allastregisters{} \\
  2372. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2373. \MID \DEREF{\Reg}{\Int} \\
  2374. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2375. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2376. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2377. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2378. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2379. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2380. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2381. \end{array}
  2382. \]
  2383. \fi}
  2384. \end{minipage}
  2385. }
  2386. \caption{The abstract syntax of \LangXInt{} assembly.}
  2387. \label{fig:x86-int-ast}
  2388. \end{figure}
  2389. \section{Planning the trip to x86}
  2390. \label{sec:plan-s0-x86}
  2391. To compile one language to another it helps to focus on the
  2392. differences between the two languages because the compiler will need
  2393. to bridge those differences. What are the differences between \LangVar{}
  2394. and x86 assembly? Here are some of the most important ones:
  2395. \begin{enumerate}
  2396. \item x86 arithmetic instructions typically have two arguments and
  2397. update the second argument in place. In contrast, \LangVar{}
  2398. arithmetic operations take two arguments and produce a new value.
  2399. An x86 instruction may have at most one memory-accessing argument.
  2400. Furthermore, some x86 instructions place special restrictions on
  2401. their arguments.
  2402. \item An argument of an \LangVar{} operator can be a deeply-nested
  2403. expression, whereas x86 instructions restrict their arguments to be
  2404. integer constants, registers, and memory locations.
  2405. {\if\edition\racketEd
  2406. \item The order of execution in x86 is explicit in the syntax: a
  2407. sequence of instructions and jumps to labeled positions, whereas in
  2408. \LangVar{} the order of evaluation is a left-to-right depth-first
  2409. traversal of the abstract syntax tree.
  2410. \fi}
  2411. \item A program in \LangVar{} can have any number of variables
  2412. whereas x86 has 16 registers and the procedure call stack.
  2413. {\if\edition\racketEd
  2414. \item Variables in \LangVar{} can shadow other variables with the
  2415. same name. In x86, registers have unique names and memory locations
  2416. have unique addresses.
  2417. \fi}
  2418. \end{enumerate}
  2419. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2420. down the problem into several steps, dealing with the above
  2421. differences one at a time. Each of these steps is called a \emph{pass}
  2422. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2423. %
  2424. This terminology comes from the way each step passes over, that is,
  2425. traverses the AST of the program.
  2426. %
  2427. Furthermore, we follow the nanopass approach, which means we strive
  2428. for each pass to accomplish one clear objective (not two or three at
  2429. the same time).
  2430. %
  2431. We begin by sketching how we might implement each pass, and give them
  2432. names. We then figure out an ordering of the passes and the
  2433. input/output language for each pass. The very first pass has
  2434. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2435. its output language. In between we can choose whichever language is
  2436. most convenient for expressing the output of each pass, whether that
  2437. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2438. our own design. Finally, to implement each pass we write one
  2439. recursive function per non-terminal in the grammar of the input
  2440. language of the pass. \index{subject}{intermediate language}
  2441. Our compiler for \LangVar{} consists of the following passes.
  2442. %
  2443. \begin{description}
  2444. {\if\edition\racketEd
  2445. \item[\key{uniquify}] deals with the shadowing of variables by
  2446. renaming every variable to a unique name.
  2447. \fi}
  2448. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2449. of a primitive operation or function call is a variable or integer,
  2450. that is, an \emph{atomic} expression. We refer to non-atomic
  2451. expressions as \emph{complex}. This pass introduces temporary
  2452. variables to hold the results of complex
  2453. subexpressions.\index{subject}{atomic
  2454. expression}\index{subject}{complex expression}%
  2455. {\if\edition\racketEd
  2456. \item[\key{explicate\_control}] makes the execution order of the
  2457. program explicit. It converts the abstract syntax tree representation
  2458. into a control-flow graph in which each node contains a sequence of
  2459. statements and the edges between nodes say which nodes contain jumps
  2460. to other nodes.
  2461. \fi}
  2462. \item[\key{select\_instructions}] handles the difference between
  2463. \LangVar{} operations and x86 instructions. This pass converts each
  2464. \LangVar{} operation to a short sequence of instructions that
  2465. accomplishes the same task.
  2466. \item[\key{assign\_homes}] replaces variables with registers or stack
  2467. locations.
  2468. \end{description}
  2469. %
  2470. {\if\edition\racketEd
  2471. %
  2472. Our treatment of \code{remove\_complex\_operands} and
  2473. \code{explicate\_control} as separate passes is an example of the
  2474. nanopass approach\footnote{For analogous decompositions of the
  2475. translation into continuation passing style, see the work of
  2476. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2477. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2478. %
  2479. \fi}
  2480. The next question is: in what order should we apply these passes? This
  2481. question can be challenging because it is difficult to know ahead of
  2482. time which orderings will be better (easier to implement, produce more
  2483. efficient code, etc.) so oftentimes trial-and-error is
  2484. involved. Nevertheless, we can try to plan ahead and make educated
  2485. choices regarding the ordering.
  2486. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2487. \key{uniquify}? The \key{uniquify} pass should come first because
  2488. \key{explicate\_control} changes all the \key{let}-bound variables to
  2489. become local variables whose scope is the entire program, which would
  2490. confuse variables with the same name.}
  2491. %
  2492. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2493. because the later removes the \key{let} form, but it is convenient to
  2494. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2495. %
  2496. \racket{The ordering of \key{uniquify} with respect to
  2497. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2498. \key{uniquify} to come first.}
  2499. The \key{select\_instructions} and \key{assign\_homes} passes are
  2500. intertwined.
  2501. %
  2502. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2503. passing arguments to functions and it is preferable to assign
  2504. parameters to their corresponding registers. This suggests that it
  2505. would be better to start with the \key{select\_instructions} pass,
  2506. which generates the instructions for argument passing, before
  2507. performing register allocation.
  2508. %
  2509. On the other hand, by selecting instructions first we may run into a
  2510. dead end in \key{assign\_homes}. Recall that only one argument of an
  2511. x86 instruction may be a memory access but \key{assign\_homes} might
  2512. be forced to assign both arguments to memory locations.
  2513. %
  2514. A sophisticated approach is to iteratively repeat the two passes until
  2515. a solution is found. However, to reduce implementation complexity we
  2516. recommend placing \key{select\_instructions} first, followed by the
  2517. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2518. that uses a reserved register to fix outstanding problems.
  2519. \begin{figure}[tbp]
  2520. {\if\edition\racketEd
  2521. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2522. \node (Lvar) at (0,2) {\large \LangVar{}};
  2523. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2524. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2525. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2526. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2527. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2528. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2529. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2530. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2531. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2532. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2533. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2534. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2535. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2536. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2537. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2538. \end{tikzpicture}
  2539. \fi}
  2540. {\if\edition\pythonEd
  2541. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2542. \node (Lvar) at (0,2) {\large \LangVar{}};
  2543. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2544. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2545. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2546. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2547. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2548. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2549. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2550. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2551. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2552. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2553. \end{tikzpicture}
  2554. \fi}
  2555. \caption{Diagram of the passes for compiling \LangVar{}. }
  2556. \label{fig:Lvar-passes}
  2557. \end{figure}
  2558. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2559. passes and identifies the input and output language of each pass.
  2560. %
  2561. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2562. language, which extends \LangXInt{} with an unbounded number of
  2563. program-scope variables and removes the restrictions regarding
  2564. instruction arguments.
  2565. %
  2566. The last pass, \key{prelude\_and\_conclusion}, places the program
  2567. instructions inside a \code{main} function with instructions for the
  2568. prelude and conclusion.
  2569. %
  2570. \racket{In the following section we discuss the \LangCVar{}
  2571. intermediate language.}
  2572. %
  2573. The remainder of this chapter provides guidance on the implementation
  2574. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2575. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2576. %% are programs that are still in the \LangVar{} language, though the
  2577. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2578. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2579. %% %
  2580. %% The output of \code{explicate\_control} is in an intermediate language
  2581. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2582. %% syntax, which we introduce in the next section. The
  2583. %% \key{select-instruction} pass translates from \LangCVar{} to
  2584. %% \LangXVar{}. The \key{assign-homes} and
  2585. %% \key{patch-instructions}
  2586. %% passes input and output variants of x86 assembly.
  2587. \newcommand{\CvarGrammarRacket}{
  2588. \begin{array}{lcl}
  2589. \Atm &::=& \Int \MID \Var \\
  2590. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2591. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2592. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2593. \end{array}
  2594. }
  2595. \newcommand{\CvarASTRacket}{
  2596. \begin{array}{lcl}
  2597. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2598. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2599. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2600. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2601. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2602. \end{array}
  2603. }
  2604. {\if\edition\racketEd
  2605. \subsection{The \LangCVar{} Intermediate Language}
  2606. The output of \code{explicate\_control} is similar to the $C$
  2607. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2608. categories for expressions and statements, so we name it \LangCVar{}.
  2609. This style of intermediate language is also known as
  2610. \emph{three-address code}, to emphasize that the typical form of a
  2611. statement is \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2612. addresses~\citep{Aho:2006wb}.
  2613. The concrete syntax for \LangCVar{} is defined in
  2614. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2615. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2616. %
  2617. The \LangCVar{} language supports the same operators as \LangVar{} but
  2618. the arguments of operators are restricted to atomic
  2619. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2620. assignment statements which can be executed in sequence using the
  2621. \key{Seq} form. A sequence of statements always ends with
  2622. \key{Return}, a guarantee that is baked into the grammar rules for
  2623. \itm{tail}. The naming of this non-terminal comes from the term
  2624. \emph{tail position}\index{subject}{tail position}, which refers to an
  2625. expression that is the last one to execute within a function.
  2626. A \LangCVar{} program consists of an alist mapping labels to
  2627. tails. This is more general than necessary for the present chapter, as
  2628. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2629. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2630. there will be just one label, \key{start}, and the whole program is
  2631. its tail.
  2632. %
  2633. The $\itm{info}$ field of the \key{CProgram} form, after the
  2634. \code{explicate\_control} pass, contains a mapping from the symbol
  2635. \key{locals} to a list of variables, that is, a list of all the
  2636. variables used in the program. At the start of the program, these
  2637. variables are uninitialized; they become initialized on their first
  2638. assignment.
  2639. \begin{figure}[tbp]
  2640. \fbox{
  2641. \begin{minipage}{0.96\textwidth}
  2642. \[
  2643. \begin{array}{l}
  2644. \CvarGrammarRacket \\
  2645. \begin{array}{lcl}
  2646. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2647. \end{array}
  2648. \end{array}
  2649. \]
  2650. \end{minipage}
  2651. }
  2652. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2653. \label{fig:c0-concrete-syntax}
  2654. \end{figure}
  2655. \begin{figure}[tbp]
  2656. \fbox{
  2657. \begin{minipage}{0.96\textwidth}
  2658. \[
  2659. \begin{array}{l}
  2660. \CvarASTRacket \\
  2661. \begin{array}{lcl}
  2662. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2663. \end{array}
  2664. \end{array}
  2665. \]
  2666. \end{minipage}
  2667. }
  2668. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2669. \label{fig:c0-syntax}
  2670. \end{figure}
  2671. The definitional interpreter for \LangCVar{} is in the support code,
  2672. in the file \code{interp-Cvar.rkt}.
  2673. \fi}
  2674. {\if\edition\racketEd
  2675. \section{Uniquify Variables}
  2676. \label{sec:uniquify-Lvar}
  2677. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2678. programs in which every \key{let} binds a unique variable name. For
  2679. example, the \code{uniquify} pass should translate the program on the
  2680. left into the program on the right.
  2681. \begin{transformation}
  2682. \begin{lstlisting}
  2683. (let ([x 32])
  2684. (+ (let ([x 10]) x) x))
  2685. \end{lstlisting}
  2686. \compilesto
  2687. \begin{lstlisting}
  2688. (let ([x.1 32])
  2689. (+ (let ([x.2 10]) x.2) x.1))
  2690. \end{lstlisting}
  2691. \end{transformation}
  2692. The following is another example translation, this time of a program
  2693. with a \key{let} nested inside the initializing expression of another
  2694. \key{let}.
  2695. \begin{transformation}
  2696. \begin{lstlisting}
  2697. (let ([x (let ([x 4])
  2698. (+ x 1))])
  2699. (+ x 2))
  2700. \end{lstlisting}
  2701. \compilesto
  2702. \begin{lstlisting}
  2703. (let ([x.2 (let ([x.1 4])
  2704. (+ x.1 1))])
  2705. (+ x.2 2))
  2706. \end{lstlisting}
  2707. \end{transformation}
  2708. We recommend implementing \code{uniquify} by creating a structurally
  2709. recursive function named \code{uniquify-exp} that mostly just copies
  2710. an expression. However, when encountering a \key{let}, it should
  2711. generate a unique name for the variable and associate the old name
  2712. with the new name in an alist.\footnote{The Racket function
  2713. \code{gensym} is handy for generating unique variable names.} The
  2714. \code{uniquify-exp} function needs to access this alist when it gets
  2715. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2716. for the alist.
  2717. The skeleton of the \code{uniquify-exp} function is shown in
  2718. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2719. convenient to partially apply it to an alist and then apply it to
  2720. different expressions, as in the last case for primitive operations in
  2721. Figure~\ref{fig:uniquify-Lvar}. The
  2722. %
  2723. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2724. %
  2725. form of Racket is useful for transforming each element of a list to
  2726. produce a new list.\index{subject}{for/list}
  2727. \begin{figure}[tbp]
  2728. \begin{lstlisting}
  2729. (define (uniquify-exp env)
  2730. (lambda (e)
  2731. (match e
  2732. [(Var x) ___]
  2733. [(Int n) (Int n)]
  2734. [(Let x e body) ___]
  2735. [(Prim op es)
  2736. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2737. (define (uniquify p)
  2738. (match p
  2739. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2740. \end{lstlisting}
  2741. \caption{Skeleton for the \key{uniquify} pass.}
  2742. \label{fig:uniquify-Lvar}
  2743. \end{figure}
  2744. \begin{exercise}
  2745. \normalfont % I don't like the italics for exercises. -Jeremy
  2746. Complete the \code{uniquify} pass by filling in the blanks in
  2747. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2748. variables and for the \key{let} form in the file \code{compiler.rkt}
  2749. in the support code.
  2750. \end{exercise}
  2751. \begin{exercise}
  2752. \normalfont % I don't like the italics for exercises. -Jeremy
  2753. \label{ex:Lvar}
  2754. Create five \LangVar{} programs that exercise the most interesting
  2755. parts of the \key{uniquify} pass, that is, the programs should include
  2756. \key{let} forms, variables, and variables that shadow each other.
  2757. The five programs should be placed in the subdirectory named
  2758. \key{tests} and the file names should start with \code{var\_test\_}
  2759. followed by a unique integer and end with the file extension
  2760. \key{.rkt}.
  2761. %
  2762. The \key{run-tests.rkt} script in the support code checks whether the
  2763. output programs produce the same result as the input programs. The
  2764. script uses the \key{interp-tests} function
  2765. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2766. your \key{uniquify} pass on the example programs. The \code{passes}
  2767. parameter of \key{interp-tests} is a list that should have one entry
  2768. for each pass in your compiler. For now, define \code{passes} to
  2769. contain just one entry for \code{uniquify} as shown below.
  2770. \begin{lstlisting}
  2771. (define passes
  2772. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2773. \end{lstlisting}
  2774. Run the \key{run-tests.rkt} script in the support code to check
  2775. whether the output programs produce the same result as the input
  2776. programs.
  2777. \end{exercise}
  2778. \fi}
  2779. \section{Remove Complex Operands}
  2780. \label{sec:remove-complex-opera-Lvar}
  2781. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2782. into a restricted form in which the arguments of operations are atomic
  2783. expressions. Put another way, this pass removes complex
  2784. operands\index{subject}{complex operand}, such as the expression
  2785. \racket{\code{(- 10)}}\python{\code{-10}}
  2786. in the program below. This is accomplished by introducing a new
  2787. temporary variable, assigning the complex operand to the new
  2788. variable, and then using the new variable in place of the complex
  2789. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2790. right.
  2791. {\if\edition\racketEd
  2792. \begin{transformation}
  2793. % var_test_19.rkt
  2794. \begin{lstlisting}
  2795. (let ([x (+ 42 (- 10))])
  2796. (+ x 10))
  2797. \end{lstlisting}
  2798. \compilesto
  2799. \begin{lstlisting}
  2800. (let ([x (let ([tmp.1 (- 10)])
  2801. (+ 42 tmp.1))])
  2802. (+ x 10))
  2803. \end{lstlisting}
  2804. \end{transformation}
  2805. \fi}
  2806. {\if\edition\pythonEd
  2807. \begin{transformation}
  2808. \begin{lstlisting}
  2809. x = 42 + -10
  2810. print(x + 10)
  2811. \end{lstlisting}
  2812. \compilesto
  2813. \begin{lstlisting}
  2814. tmp_0 = -10
  2815. x = 42 + tmp_0
  2816. tmp_1 = x + 10
  2817. print(tmp_1)
  2818. \end{lstlisting}
  2819. \end{transformation}
  2820. \fi}
  2821. \newcommand{\LvarMonadASTPython}{
  2822. \begin{array}{rcl}
  2823. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2824. \Exp{} &::=& \Atm \MID \READ{} \\
  2825. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2826. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2827. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2828. \end{array}
  2829. }
  2830. \begin{figure}[tp]
  2831. \centering
  2832. \fbox{
  2833. \begin{minipage}{0.96\textwidth}
  2834. {\if\edition\racketEd
  2835. \[
  2836. \begin{array}{rcl}
  2837. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2838. \Exp &::=& \Atm \MID \READ{} \\
  2839. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2840. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2841. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2842. \end{array}
  2843. \]
  2844. \fi}
  2845. {\if\edition\pythonEd
  2846. \[
  2847. \begin{array}{l}
  2848. \LvarMonadASTPython \\
  2849. \begin{array}{rcl}
  2850. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2851. \end{array}
  2852. \end{array}
  2853. \]
  2854. \fi}
  2855. \end{minipage}
  2856. }
  2857. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2858. atomic expressions.}
  2859. \label{fig:Lvar-anf-syntax}
  2860. \end{figure}
  2861. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2862. of this pass, the language \LangVarANF{}. The only difference is that
  2863. operator arguments are restricted to be atomic expressions that are
  2864. defined by the \Atm{} non-terminal. In particular, integer constants
  2865. and variables are atomic.
  2866. The atomic expressions are pure (they do not cause side-effects or
  2867. depend on them) whereas complex expressions may have side effects,
  2868. such as \READ{}. A language with this separation between pure versus
  2869. side-effecting expressions is said to be in monadic normal
  2870. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2871. in \LangVarANF{}. An important invariant of the
  2872. \code{remove\_complex\_operands} pass is that the relative ordering
  2873. among complex expressions is not changed, but the relative ordering
  2874. between atomic expressions and complex expressions can change and
  2875. often does. The reason that these changes are behaviour preserving is
  2876. that the atomic expressions are pure.
  2877. Another well-known form for intermediate languages is the
  2878. \emph{administrative normal form}
  2879. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2880. \index{subject}{administrative normal form} \index{subject}{ANF}
  2881. %
  2882. The \LangVarANF{} language is not quite in ANF because we allow the
  2883. right-hand side of a \code{let} to be a complex expression.
  2884. {\if\edition\racketEd
  2885. We recommend implementing this pass with two mutually recursive
  2886. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2887. \code{rco\_atom} to subexpressions that need to become atomic and to
  2888. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2889. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2890. returns an expression. The \code{rco\_atom} function returns two
  2891. things: an atomic expression and an alist mapping temporary variables to
  2892. complex subexpressions. You can return multiple things from a function
  2893. using Racket's \key{values} form and you can receive multiple things
  2894. from a function call using the \key{define-values} form.
  2895. Also, the
  2896. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2897. form is useful for applying a function to each element of a list, in
  2898. the case where the function returns multiple values.
  2899. \index{subject}{for/lists}
  2900. \fi}
  2901. %
  2902. {\if\edition\pythonEd
  2903. %
  2904. We recommend implementing this pass with an auxiliary method named
  2905. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2906. Boolean that specifies whether the expression needs to become atomic
  2907. or not. The \code{rco\_exp} method should return a pair consisting of
  2908. the new expression and a list of pairs, associating new temporary
  2909. variables with their initializing expressions.
  2910. %
  2911. \fi}
  2912. {\if\edition\racketEd
  2913. Returning to the example program with the expression \code{(+ 42 (-
  2914. 10))}, the subexpression \code{(- 10)} should be processed using the
  2915. \code{rco\_atom} function because it is an argument of the \code{+} and
  2916. therefore needs to become atomic. The output of \code{rco\_atom}
  2917. applied to \code{(- 10)} is as follows.
  2918. \begin{transformation}
  2919. \begin{lstlisting}
  2920. (- 10)
  2921. \end{lstlisting}
  2922. \compilesto
  2923. \begin{lstlisting}
  2924. tmp.1
  2925. ((tmp.1 . (- 10)))
  2926. \end{lstlisting}
  2927. \end{transformation}
  2928. \fi}
  2929. %
  2930. {\if\edition\pythonEd
  2931. %
  2932. Returning to the example program with the expression \code{42 + -10},
  2933. the subexpression \code{-10} should be processed using the
  2934. \code{rco\_exp} function with \code{True} as the second argument
  2935. because \code{-10} is an argument of the \code{+} operator and
  2936. therefore needs to become atomic. The output of \code{rco\_exp}
  2937. applied to \code{-10} is as follows.
  2938. \begin{transformation}
  2939. \begin{lstlisting}
  2940. -10
  2941. \end{lstlisting}
  2942. \compilesto
  2943. \begin{lstlisting}
  2944. tmp_1
  2945. [(tmp_1, -10)]
  2946. \end{lstlisting}
  2947. \end{transformation}
  2948. %
  2949. \fi}
  2950. Take special care of programs such as the following that
  2951. %
  2952. \racket{bind a variable to an atomic expression}
  2953. %
  2954. \python{assign an atomic expression to a variable}.
  2955. %
  2956. You should leave such \racket{variable bindings}\python{assignments}
  2957. unchanged, as shown in the program on the right\\
  2958. %
  2959. {\if\edition\racketEd
  2960. \begin{transformation}
  2961. % var_test_20.rkt
  2962. \begin{lstlisting}
  2963. (let ([a 42])
  2964. (let ([b a])
  2965. b))
  2966. \end{lstlisting}
  2967. \compilesto
  2968. \begin{lstlisting}
  2969. (let ([a 42])
  2970. (let ([b a])
  2971. b))
  2972. \end{lstlisting}
  2973. \end{transformation}
  2974. \fi}
  2975. {\if\edition\pythonEd
  2976. \begin{transformation}
  2977. \begin{lstlisting}
  2978. a = 42
  2979. b = a
  2980. print(b)
  2981. \end{lstlisting}
  2982. \compilesto
  2983. \begin{lstlisting}
  2984. a = 42
  2985. b = a
  2986. print(b)
  2987. \end{lstlisting}
  2988. \end{transformation}
  2989. \fi}
  2990. %
  2991. \noindent A careless implementation might produce the following output with
  2992. unnecessary temporary variables.
  2993. \begin{center}
  2994. \begin{minipage}{0.4\textwidth}
  2995. {\if\edition\racketEd
  2996. \begin{lstlisting}
  2997. (let ([tmp.1 42])
  2998. (let ([a tmp.1])
  2999. (let ([tmp.2 a])
  3000. (let ([b tmp.2])
  3001. b))))
  3002. \end{lstlisting}
  3003. \fi}
  3004. {\if\edition\pythonEd
  3005. \begin{lstlisting}
  3006. tmp_1 = 42
  3007. a = tmp_1
  3008. tmp_2 = a
  3009. b = tmp_2
  3010. print(b)
  3011. \end{lstlisting}
  3012. \fi}
  3013. \end{minipage}
  3014. \end{center}
  3015. \begin{exercise}
  3016. \normalfont
  3017. {\if\edition\racketEd
  3018. Implement the \code{remove\_complex\_operands} function in
  3019. \code{compiler.rkt}.
  3020. %
  3021. Create three new \LangVar{} programs that exercise the interesting
  3022. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3023. regarding file names described in Exercise~\ref{ex:Lvar}.
  3024. %
  3025. In the \code{run-tests.rkt} script, add the following entry to the
  3026. list of \code{passes} and then run the script to test your compiler.
  3027. \begin{lstlisting}
  3028. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  3029. \end{lstlisting}
  3030. While debugging your compiler, it is often useful to see the
  3031. intermediate programs that are output from each pass. To print the
  3032. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3033. \code{interp-tests} in \code{run-tests.rkt}.
  3034. \fi}
  3035. %
  3036. {\if\edition\pythonEd
  3037. Implement the \code{remove\_complex\_operands} pass in
  3038. \code{compiler.py}, creating auxiliary functions for each
  3039. non-terminal in the grammar, i.e., \code{rco\_exp}
  3040. and \code{rco\_stmt}. We recommend you use the function
  3041. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3042. \fi}
  3043. \end{exercise}
  3044. {\if\edition\pythonEd
  3045. \begin{exercise}
  3046. \normalfont % I don't like the italics for exercises. -Jeremy
  3047. \label{ex:Lvar}
  3048. Create five \LangVar{} programs that exercise the most interesting
  3049. parts of the \code{remove\_complex\_operands} pass. The five programs
  3050. should be placed in the subdirectory named \key{tests} and the file
  3051. names should start with \code{var\_test\_} followed by a unique
  3052. integer and end with the file extension \key{.py}.
  3053. %% The \key{run-tests.rkt} script in the support code checks whether the
  3054. %% output programs produce the same result as the input programs. The
  3055. %% script uses the \key{interp-tests} function
  3056. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3057. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3058. %% parameter of \key{interp-tests} is a list that should have one entry
  3059. %% for each pass in your compiler. For now, define \code{passes} to
  3060. %% contain just one entry for \code{uniquify} as shown below.
  3061. %% \begin{lstlisting}
  3062. %% (define passes
  3063. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3064. %% \end{lstlisting}
  3065. Run the \key{run-tests.py} script in the support code to check
  3066. whether the output programs produce the same result as the input
  3067. programs.
  3068. \end{exercise}
  3069. \fi}
  3070. {\if\edition\racketEd
  3071. \section{Explicate Control}
  3072. \label{sec:explicate-control-Lvar}
  3073. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3074. programs that make the order of execution explicit in their
  3075. syntax. For now this amounts to flattening \key{let} constructs into a
  3076. sequence of assignment statements. For example, consider the following
  3077. \LangVar{} program.\\
  3078. % var_test_11.rkt
  3079. \begin{minipage}{0.96\textwidth}
  3080. \begin{lstlisting}
  3081. (let ([y (let ([x 20])
  3082. (+ x (let ([x 22]) x)))])
  3083. y)
  3084. \end{lstlisting}
  3085. \end{minipage}\\
  3086. %
  3087. The output of the previous pass and of \code{explicate\_control} is
  3088. shown below. Recall that the right-hand-side of a \key{let} executes
  3089. before its body, so the order of evaluation for this program is to
  3090. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  3091. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  3092. output of \code{explicate\_control} makes this ordering explicit.
  3093. \begin{transformation}
  3094. \begin{lstlisting}
  3095. (let ([y (let ([x.1 20])
  3096. (let ([x.2 22])
  3097. (+ x.1 x.2)))])
  3098. y)
  3099. \end{lstlisting}
  3100. \compilesto
  3101. \begin{lstlisting}[language=C]
  3102. start:
  3103. x.1 = 20;
  3104. x.2 = 22;
  3105. y = (+ x.1 x.2);
  3106. return y;
  3107. \end{lstlisting}
  3108. \end{transformation}
  3109. \begin{figure}[tbp]
  3110. \begin{lstlisting}
  3111. (define (explicate_tail e)
  3112. (match e
  3113. [(Var x) ___]
  3114. [(Int n) (Return (Int n))]
  3115. [(Let x rhs body) ___]
  3116. [(Prim op es) ___]
  3117. [else (error "explicate_tail unhandled case" e)]))
  3118. (define (explicate_assign e x cont)
  3119. (match e
  3120. [(Var x) ___]
  3121. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3122. [(Let y rhs body) ___]
  3123. [(Prim op es) ___]
  3124. [else (error "explicate_assign unhandled case" e)]))
  3125. (define (explicate_control p)
  3126. (match p
  3127. [(Program info body) ___]))
  3128. \end{lstlisting}
  3129. \caption{Skeleton for the \code{explicate\_control} pass.}
  3130. \label{fig:explicate-control-Lvar}
  3131. \end{figure}
  3132. The organization of this pass depends on the notion of tail position
  3133. that we have alluded to earlier.
  3134. \begin{definition}
  3135. The following rules define when an expression is in \textbf{\emph{tail
  3136. position}}\index{subject}{tail position} for the language \LangVar{}.
  3137. \begin{enumerate}
  3138. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3139. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3140. \end{enumerate}
  3141. \end{definition}
  3142. We recommend implementing \code{explicate\_control} using two mutually
  3143. recursive functions, \code{explicate\_tail} and
  3144. \code{explicate\_assign}, as suggested in the skeleton code in
  3145. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3146. function should be applied to expressions in tail position whereas the
  3147. \code{explicate\_assign} should be applied to expressions that occur on
  3148. the right-hand-side of a \key{let}.
  3149. %
  3150. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3151. input and produces a \Tail{} in \LangCVar{} (see
  3152. Figure~\ref{fig:c0-syntax}).
  3153. %
  3154. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3155. the variable that it is to be assigned to, and a \Tail{} in
  3156. \LangCVar{} for the code that comes after the assignment. The
  3157. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3158. The \code{explicate\_assign} function is in accumulator-passing style:
  3159. the \code{cont} parameter is used for accumulating the output. This
  3160. accumulator-passing style plays an important role in how we generate
  3161. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3162. \begin{exercise}\normalfont
  3163. %
  3164. Implement the \code{explicate\_control} function in
  3165. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3166. exercise the code in \code{explicate\_control}.
  3167. %
  3168. In the \code{run-tests.rkt} script, add the following entry to the
  3169. list of \code{passes} and then run the script to test your compiler.
  3170. \begin{lstlisting}
  3171. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3172. \end{lstlisting}
  3173. \end{exercise}
  3174. \fi}
  3175. \section{Select Instructions}
  3176. \label{sec:select-Lvar}
  3177. \index{subject}{instruction selection}
  3178. In the \code{select\_instructions} pass we begin the work of
  3179. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3180. language of this pass is a variant of x86 that still uses variables,
  3181. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3182. non-terminal of the \LangXInt{} abstract syntax
  3183. (Figure~\ref{fig:x86-int-ast}).
  3184. \racket{We recommend implementing the
  3185. \code{select\_instructions} with three auxiliary functions, one for
  3186. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3187. $\Tail$.}
  3188. \python{We recommend implementing an auxiliary function
  3189. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3190. \racket{
  3191. The cases for $\Atm$ are straightforward; variables stay
  3192. the same and integer constants change to immediates:
  3193. $\INT{n}$ changes to $\IMM{n}$.}
  3194. We consider the cases for the $\Stmt$ non-terminal, starting with
  3195. arithmetic operations. For example, consider the addition operation
  3196. below, on the left side. There is an \key{addq} instruction in x86,
  3197. but it performs an in-place update. So we could move $\Arg_1$
  3198. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3199. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3200. $\Atm_1$ and $\Atm_2$ respectively.
  3201. \begin{transformation}
  3202. {\if\edition\racketEd
  3203. \begin{lstlisting}
  3204. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3205. \end{lstlisting}
  3206. \fi}
  3207. {\if\edition\pythonEd
  3208. \begin{lstlisting}
  3209. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3210. \end{lstlisting}
  3211. \fi}
  3212. \compilesto
  3213. \begin{lstlisting}
  3214. movq |$\Arg_1$|, |$\itm{var}$|
  3215. addq |$\Arg_2$|, |$\itm{var}$|
  3216. \end{lstlisting}
  3217. \end{transformation}
  3218. There are also cases that require special care to avoid generating
  3219. needlessly complicated code. For example, if one of the arguments of
  3220. the addition is the same variable as the left-hand side of the
  3221. assignment, as shown below, then there is no need for the extra move
  3222. instruction. The assignment statement can be translated into a single
  3223. \key{addq} instruction as follows.
  3224. \begin{transformation}
  3225. {\if\edition\racketEd
  3226. \begin{lstlisting}
  3227. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3228. \end{lstlisting}
  3229. \fi}
  3230. {\if\edition\pythonEd
  3231. \begin{lstlisting}
  3232. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3233. \end{lstlisting}
  3234. \fi}
  3235. \compilesto
  3236. \begin{lstlisting}
  3237. addq |$\Arg_1$|, |$\itm{var}$|
  3238. \end{lstlisting}
  3239. \end{transformation}
  3240. The \READOP{} operation does not have a direct counterpart in x86
  3241. assembly, so we provide this functionality with the function
  3242. \code{read\_int} in the file \code{runtime.c}, written in
  3243. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3244. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3245. system}, or simply the \emph{runtime} for short. When compiling your
  3246. generated x86 assembly code, you need to compile \code{runtime.c} to
  3247. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3248. \code{-c}) and link it into the executable. For our purposes of code
  3249. generation, all you need to do is translate an assignment of
  3250. \READOP{} into a call to the \code{read\_int} function followed by a
  3251. move from \code{rax} to the left-hand-side variable. (Recall that the
  3252. return value of a function goes into \code{rax}.)
  3253. \begin{transformation}
  3254. {\if\edition\racketEd
  3255. \begin{lstlisting}
  3256. |$\itm{var}$| = (read);
  3257. \end{lstlisting}
  3258. \fi}
  3259. {\if\edition\pythonEd
  3260. \begin{lstlisting}
  3261. |$\itm{var}$| = input_int();
  3262. \end{lstlisting}
  3263. \fi}
  3264. \compilesto
  3265. \begin{lstlisting}
  3266. callq read_int
  3267. movq %rax, |$\itm{var}$|
  3268. \end{lstlisting}
  3269. \end{transformation}
  3270. {\if\edition\pythonEd
  3271. %
  3272. Similarly, we translate the \code{print} operation, shown below, into
  3273. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3274. In x86, the first six arguments to functions are passed in registers,
  3275. with the first argument passed in register \code{rdi}. So we move the
  3276. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3277. \code{callq} instruction.
  3278. \begin{transformation}
  3279. \begin{lstlisting}
  3280. print(|$\Atm$|)
  3281. \end{lstlisting}
  3282. \compilesto
  3283. \begin{lstlisting}
  3284. movq |$\Arg$|, %rdi
  3285. callq print_int
  3286. \end{lstlisting}
  3287. \end{transformation}
  3288. %
  3289. \fi}
  3290. {\if\edition\racketEd
  3291. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3292. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3293. assignment to the \key{rax} register followed by a jump to the
  3294. conclusion of the program (so the conclusion needs to be labeled).
  3295. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3296. recursively and then append the resulting instructions.
  3297. \fi}
  3298. {\if\edition\pythonEd
  3299. We recommend that you use the function \code{utils.label\_name()} to
  3300. transform a string into an label argument suitably suitable for, e.g.,
  3301. the target of the \code{callq} instruction. This practice makes your
  3302. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3303. all labels.
  3304. \fi}
  3305. \begin{exercise}
  3306. \normalfont
  3307. {\if\edition\racketEd
  3308. Implement the \code{select\_instructions} pass in
  3309. \code{compiler.rkt}. Create three new example programs that are
  3310. designed to exercise all of the interesting cases in this pass.
  3311. %
  3312. In the \code{run-tests.rkt} script, add the following entry to the
  3313. list of \code{passes} and then run the script to test your compiler.
  3314. \begin{lstlisting}
  3315. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3316. \end{lstlisting}
  3317. \fi}
  3318. {\if\edition\pythonEd
  3319. Implement the \key{select\_instructions} pass in
  3320. \code{compiler.py}. Create three new example programs that are
  3321. designed to exercise all of the interesting cases in this pass.
  3322. Run the \code{run-tests.py} script to to check
  3323. whether the output programs produce the same result as the input
  3324. programs.
  3325. \fi}
  3326. \end{exercise}
  3327. \section{Assign Homes}
  3328. \label{sec:assign-Lvar}
  3329. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3330. \LangXVar{} programs that no longer use program variables.
  3331. Thus, the \key{assign-homes} pass is responsible for placing all of
  3332. the program variables in registers or on the stack. For runtime
  3333. efficiency, it is better to place variables in registers, but as there
  3334. are only 16 registers, some programs must necessarily resort to
  3335. placing some variables on the stack. In this chapter we focus on the
  3336. mechanics of placing variables on the stack. We study an algorithm for
  3337. placing variables in registers in
  3338. Chapter~\ref{ch:register-allocation-Lvar}.
  3339. Consider again the following \LangVar{} program from
  3340. Section~\ref{sec:remove-complex-opera-Lvar}.
  3341. % var_test_20.rkt
  3342. {\if\edition\racketEd
  3343. \begin{lstlisting}
  3344. (let ([a 42])
  3345. (let ([b a])
  3346. b))
  3347. \end{lstlisting}
  3348. \fi}
  3349. {\if\edition\pythonEd
  3350. \begin{lstlisting}
  3351. a = 42
  3352. b = a
  3353. print(b)
  3354. \end{lstlisting}
  3355. \fi}
  3356. %
  3357. The output of \code{select\_instructions} is shown below, on the left,
  3358. and the output of \code{assign\_homes} is on the right. In this
  3359. example, we assign variable \code{a} to stack location
  3360. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3361. \begin{transformation}
  3362. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3363. movq $42, a
  3364. movq a, b
  3365. movq b, %rax
  3366. \end{lstlisting}
  3367. \compilesto
  3368. %stack-space: 16
  3369. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3370. movq $42, -8(%rbp)
  3371. movq -8(%rbp), -16(%rbp)
  3372. movq -16(%rbp), %rax
  3373. \end{lstlisting}
  3374. \end{transformation}
  3375. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3376. \code{X86Program} node is an alist mapping all the variables in the
  3377. program to their types (for now just \code{Integer}). The
  3378. \code{assign\_homes} pass should replace all uses of those variables
  3379. with stack locations. As an aside, the \code{locals-types} entry is
  3380. computed by \code{type-check-Cvar} in the support code, which
  3381. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3382. which should be propagated to the \code{X86Program} node.}
  3383. %
  3384. \python{The \code{assign\_homes} pass should replace all uses of
  3385. variables with stack locations.}
  3386. %
  3387. In the process of assigning variables to stack locations, it is
  3388. convenient for you to compute and store the size of the frame (in
  3389. bytes) in%
  3390. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3391. %
  3392. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3393. which is needed later to generate the conclusion of the \code{main}
  3394. procedure. The x86-64 standard requires the frame size to be a
  3395. multiple of 16 bytes.\index{subject}{frame}
  3396. % TODO: store the number of variables instead? -Jeremy
  3397. \begin{exercise}\normalfont
  3398. Implement the \key{assign\_homes} pass in
  3399. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3400. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3401. grammar. We recommend that the auxiliary functions take an extra
  3402. parameter that maps variable names to homes (stack locations for now).
  3403. %
  3404. {\if\edition\racketEd
  3405. In the \code{run-tests.rkt} script, add the following entry to the
  3406. list of \code{passes} and then run the script to test your compiler.
  3407. \begin{lstlisting}
  3408. (list "assign homes" assign-homes interp_x86-0)
  3409. \end{lstlisting}
  3410. \fi}
  3411. {\if\edition\pythonEd
  3412. Run the \code{run-tests.py} script to to check
  3413. whether the output programs produce the same result as the input
  3414. programs.
  3415. \fi}
  3416. \end{exercise}
  3417. \section{Patch Instructions}
  3418. \label{sec:patch-s0}
  3419. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3420. \LangXInt{} by making sure that each instruction adheres to the
  3421. restriction that at most one argument of an instruction may be a
  3422. memory reference.
  3423. We return to the following example.\\
  3424. \begin{minipage}{0.5\textwidth}
  3425. % var_test_20.rkt
  3426. {\if\edition\racketEd
  3427. \begin{lstlisting}
  3428. (let ([a 42])
  3429. (let ([b a])
  3430. b))
  3431. \end{lstlisting}
  3432. \fi}
  3433. {\if\edition\pythonEd
  3434. \begin{lstlisting}
  3435. a = 42
  3436. b = a
  3437. print(b)
  3438. \end{lstlisting}
  3439. \fi}
  3440. \end{minipage}\\
  3441. The \key{assign\_homes} pass produces the following translation. \\
  3442. \begin{minipage}{0.5\textwidth}
  3443. {\if\edition\racketEd
  3444. \begin{lstlisting}
  3445. movq $42, -8(%rbp)
  3446. movq -8(%rbp), -16(%rbp)
  3447. movq -16(%rbp), %rax
  3448. \end{lstlisting}
  3449. \fi}
  3450. {\if\edition\pythonEd
  3451. \begin{lstlisting}
  3452. movq 42, -8(%rbp)
  3453. movq -8(%rbp), -16(%rbp)
  3454. movq -16(%rbp), %rdi
  3455. callq print_int
  3456. \end{lstlisting}
  3457. \fi}
  3458. \end{minipage}\\
  3459. The second \key{movq} instruction is problematic because both
  3460. arguments are stack locations. We suggest fixing this problem by
  3461. moving from the source location to the register \key{rax} and then
  3462. from \key{rax} to the destination location, as follows.
  3463. \begin{lstlisting}
  3464. movq -8(%rbp), %rax
  3465. movq %rax, -16(%rbp)
  3466. \end{lstlisting}
  3467. \begin{exercise}
  3468. \normalfont Implement the \key{patch\_instructions} pass in
  3469. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3470. Create three new example programs that are
  3471. designed to exercise all of the interesting cases in this pass.
  3472. %
  3473. {\if\edition\racketEd
  3474. In the \code{run-tests.rkt} script, add the following entry to the
  3475. list of \code{passes} and then run the script to test your compiler.
  3476. \begin{lstlisting}
  3477. (list "patch instructions" patch_instructions interp_x86-0)
  3478. \end{lstlisting}
  3479. \fi}
  3480. {\if\edition\pythonEd
  3481. Run the \code{run-tests.py} script to to check
  3482. whether the output programs produce the same result as the input
  3483. programs.
  3484. \fi}
  3485. \end{exercise}
  3486. \section{Generate Prelude and Conclusion}
  3487. \label{sec:print-x86}
  3488. \index{subject}{prelude}\index{subject}{conclusion}
  3489. The last step of the compiler from \LangVar{} to x86 is to generate
  3490. the \code{main} function with a prelude and conclusion wrapped around
  3491. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3492. discussed in Section~\ref{sec:x86}.
  3493. When running on Mac OS X, your compiler should prefix an underscore to
  3494. all labels, e.g., changing \key{main} to \key{\_main}.
  3495. %
  3496. \racket{The Racket call \code{(system-type 'os)} is useful for
  3497. determining which operating system the compiler is running on. It
  3498. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3499. %
  3500. \python{The Python \code{platform} library includes a \code{system()}
  3501. function that returns \code{'Linux'}, \code{'Windows'}, or
  3502. \code{'Darwin'} (for Mac).}
  3503. \begin{exercise}\normalfont
  3504. %
  3505. Implement the \key{prelude\_and\_conclusion} pass in
  3506. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3507. %
  3508. {\if\edition\racketEd
  3509. In the \code{run-tests.rkt} script, add the following entry to the
  3510. list of \code{passes} and then run the script to test your compiler.
  3511. \begin{lstlisting}
  3512. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3513. \end{lstlisting}
  3514. %
  3515. Uncomment the call to the \key{compiler-tests} function
  3516. (Appendix~\ref{appendix:utilities}), which tests your complete
  3517. compiler by executing the generated x86 code. It translates the x86
  3518. AST that you produce into a string by invoking the \code{print-x86}
  3519. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3520. the provided \key{runtime.c} file to \key{runtime.o} using
  3521. \key{gcc}. Run the script to test your compiler.
  3522. %
  3523. \fi}
  3524. {\if\edition\pythonEd
  3525. %
  3526. Run the \code{run-tests.py} script to to check whether the output
  3527. programs produce the same result as the input programs. That script
  3528. translates the x86 AST that you produce into a string by invoking the
  3529. \code{repr} method that is implemented by the x86 AST classes in
  3530. \code{x86\_ast.py}.
  3531. %
  3532. \fi}
  3533. \end{exercise}
  3534. \section{Challenge: Partial Evaluator for \LangVar{}}
  3535. \label{sec:pe-Lvar}
  3536. \index{subject}{partial evaluation}
  3537. This section describes two optional challenge exercises that involve
  3538. adapting and improving the partial evaluator for \LangInt{} that was
  3539. introduced in Section~\ref{sec:partial-evaluation}.
  3540. \begin{exercise}\label{ex:pe-Lvar}
  3541. \normalfont
  3542. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3543. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3544. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3545. %
  3546. \racket{\key{let} binding}\python{assignment}
  3547. %
  3548. to the \LangInt{} language, so you will need to add cases for them in
  3549. the \code{pe\_exp}
  3550. %
  3551. \racket{function}
  3552. %
  3553. \python{and \code{pe\_stmt} functions}.
  3554. %
  3555. Once complete, add the partial evaluation pass to the front of your
  3556. compiler and make sure that your compiler still passes all of the
  3557. tests.
  3558. \end{exercise}
  3559. \begin{exercise}
  3560. \normalfont
  3561. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3562. \code{pe\_add} auxiliary functions with functions that know more about
  3563. arithmetic. For example, your partial evaluator should translate
  3564. {\if\edition\racketEd
  3565. \[
  3566. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3567. \code{(+ 2 (read))}
  3568. \]
  3569. \fi}
  3570. {\if\edition\pythonEd
  3571. \[
  3572. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3573. \code{2 + input\_int()}
  3574. \]
  3575. \fi}
  3576. To accomplish this, the \code{pe\_exp} function should produce output
  3577. in the form of the $\itm{residual}$ non-terminal of the following
  3578. grammar. The idea is that when processing an addition expression, we
  3579. can always produce either 1) an integer constant, 2) an addition
  3580. expression with an integer constant on the left-hand side but not the
  3581. right-hand side, or 3) or an addition expression in which neither
  3582. subexpression is a constant.
  3583. {\if\edition\racketEd
  3584. \[
  3585. \begin{array}{lcl}
  3586. \itm{inert} &::=& \Var
  3587. \MID \LP\key{read}\RP
  3588. \MID \LP\key{-} ~\Var\RP
  3589. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3590. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3591. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3592. \itm{residual} &::=& \Int
  3593. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3594. \MID \itm{inert}
  3595. \end{array}
  3596. \]
  3597. \fi}
  3598. {\if\edition\pythonEd
  3599. \[
  3600. \begin{array}{lcl}
  3601. \itm{inert} &::=& \Var
  3602. \MID \key{input\_int}\LP\RP
  3603. \MID \key{-} \Var
  3604. \MID \key{-} \key{input\_int}\LP\RP
  3605. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3606. \itm{residual} &::=& \Int
  3607. \MID \Int ~ \key{+} ~ \itm{inert}
  3608. \MID \itm{inert}
  3609. \end{array}
  3610. \]
  3611. \fi}
  3612. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3613. inputs are $\itm{residual}$ expressions and they should return
  3614. $\itm{residual}$ expressions. Once the improvements are complete,
  3615. make sure that your compiler still passes all of the tests. After
  3616. all, fast code is useless if it produces incorrect results!
  3617. \end{exercise}
  3618. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3619. \chapter{Register Allocation}
  3620. \label{ch:register-allocation-Lvar}
  3621. \index{subject}{register allocation}
  3622. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3623. stack. In this chapter we learn how to improve the performance of the
  3624. generated code by assigning some variables to registers. The CPU can
  3625. access a register in a single cycle, whereas accessing the stack can
  3626. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3627. serves as a running example. The source program is on the left and the
  3628. output of instruction selection is on the right. The program is almost
  3629. in the x86 assembly language but it still uses variables.
  3630. \begin{figure}
  3631. \begin{minipage}{0.45\textwidth}
  3632. Example \LangVar{} program:
  3633. % var_test_28.rkt
  3634. {\if\edition\racketEd
  3635. \begin{lstlisting}
  3636. (let ([v 1])
  3637. (let ([w 42])
  3638. (let ([x (+ v 7)])
  3639. (let ([y x])
  3640. (let ([z (+ x w)])
  3641. (+ z (- y)))))))
  3642. \end{lstlisting}
  3643. \fi}
  3644. {\if\edition\pythonEd
  3645. \begin{lstlisting}
  3646. v = 1
  3647. w = 42
  3648. x = v + 7
  3649. y = x
  3650. z = x + w
  3651. print(z + (- y))
  3652. \end{lstlisting}
  3653. \fi}
  3654. \end{minipage}
  3655. \begin{minipage}{0.45\textwidth}
  3656. After instruction selection:
  3657. {\if\edition\racketEd
  3658. \begin{lstlisting}
  3659. locals-types:
  3660. x : Integer, y : Integer,
  3661. z : Integer, t : Integer,
  3662. v : Integer, w : Integer
  3663. start:
  3664. movq $1, v
  3665. movq $42, w
  3666. movq v, x
  3667. addq $7, x
  3668. movq x, y
  3669. movq x, z
  3670. addq w, z
  3671. movq y, t
  3672. negq t
  3673. movq z, %rax
  3674. addq t, %rax
  3675. jmp conclusion
  3676. \end{lstlisting}
  3677. \fi}
  3678. {\if\edition\pythonEd
  3679. \begin{lstlisting}
  3680. movq $1, v
  3681. movq $42, w
  3682. movq v, x
  3683. addq $7, x
  3684. movq x, y
  3685. movq x, z
  3686. addq w, z
  3687. movq y, tmp_0
  3688. negq tmp_0
  3689. movq z, tmp_1
  3690. addq tmp_0, tmp_1
  3691. movq tmp_1, %rdi
  3692. callq print_int
  3693. \end{lstlisting}
  3694. \fi}
  3695. \end{minipage}
  3696. \caption{A running example for register allocation.}
  3697. \label{fig:reg-eg}
  3698. \end{figure}
  3699. The goal of register allocation is to fit as many variables into
  3700. registers as possible. Some programs have more variables than
  3701. registers so we cannot always map each variable to a different
  3702. register. Fortunately, it is common for different variables to be
  3703. needed during different periods of time during program execution, and
  3704. in such cases several variables can be mapped to the same register.
  3705. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3706. After the variable \code{x} is moved to \code{z} it is no longer
  3707. needed. Variable \code{z}, on the other hand, is used only after this
  3708. point, so \code{x} and \code{z} could share the same register. The
  3709. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3710. where a variable is needed. Once we have that information, we compute
  3711. which variables are needed at the same time, i.e., which ones
  3712. \emph{interfere} with each other, and represent this relation as an
  3713. undirected graph whose vertices are variables and edges indicate when
  3714. two variables interfere (Section~\ref{sec:build-interference}). We
  3715. then model register allocation as a graph coloring problem
  3716. (Section~\ref{sec:graph-coloring}).
  3717. If we run out of registers despite these efforts, we place the
  3718. remaining variables on the stack, similar to what we did in
  3719. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3720. assigning a variable to a stack location. The decision to spill a
  3721. variable is handled as part of the graph coloring process.
  3722. We make the simplifying assumption that each variable is assigned to
  3723. one location (a register or stack address). A more sophisticated
  3724. approach is to assign a variable to one or more locations in different
  3725. regions of the program. For example, if a variable is used many times
  3726. in short sequence and then only used again after many other
  3727. instructions, it could be more efficient to assign the variable to a
  3728. register during the initial sequence and then move it to the stack for
  3729. the rest of its lifetime. We refer the interested reader to
  3730. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3731. approach.
  3732. % discuss prioritizing variables based on how much they are used.
  3733. \section{Registers and Calling Conventions}
  3734. \label{sec:calling-conventions}
  3735. \index{subject}{calling conventions}
  3736. As we perform register allocation, we need to be aware of the
  3737. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3738. functions calls are performed in x86.
  3739. %
  3740. Even though \LangVar{} does not include programmer-defined functions,
  3741. our generated code includes a \code{main} function that is called by
  3742. the operating system and our generated code contains calls to the
  3743. \code{read\_int} function.
  3744. Function calls require coordination between two pieces of code that
  3745. may be written by different programmers or generated by different
  3746. compilers. Here we follow the System V calling conventions that are
  3747. used by the GNU C compiler on Linux and
  3748. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3749. %
  3750. The calling conventions include rules about how functions share the
  3751. use of registers. In particular, the caller is responsible for freeing
  3752. up some registers prior to the function call for use by the callee.
  3753. These are called the \emph{caller-saved registers}
  3754. \index{subject}{caller-saved registers}
  3755. and they are
  3756. \begin{lstlisting}
  3757. rax rcx rdx rsi rdi r8 r9 r10 r11
  3758. \end{lstlisting}
  3759. On the other hand, the callee is responsible for preserving the values
  3760. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3761. which are
  3762. \begin{lstlisting}
  3763. rsp rbp rbx r12 r13 r14 r15
  3764. \end{lstlisting}
  3765. We can think about this caller/callee convention from two points of
  3766. view, the caller view and the callee view:
  3767. \begin{itemize}
  3768. \item The caller should assume that all the caller-saved registers get
  3769. overwritten with arbitrary values by the callee. On the other hand,
  3770. the caller can safely assume that all the callee-saved registers
  3771. contain the same values after the call that they did before the
  3772. call.
  3773. \item The callee can freely use any of the caller-saved registers.
  3774. However, if the callee wants to use a callee-saved register, the
  3775. callee must arrange to put the original value back in the register
  3776. prior to returning to the caller. This can be accomplished by saving
  3777. the value to the stack in the prelude of the function and restoring
  3778. the value in the conclusion of the function.
  3779. \end{itemize}
  3780. In x86, registers are also used for passing arguments to a function
  3781. and for the return value. In particular, the first six arguments to a
  3782. function are passed in the following six registers, in this order.
  3783. \begin{lstlisting}
  3784. rdi rsi rdx rcx r8 r9
  3785. \end{lstlisting}
  3786. If there are more than six arguments, then the convention is to use
  3787. space on the frame of the caller for the rest of the
  3788. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3789. need more than six arguments.
  3790. %
  3791. \racket{For now, the only function we care about is \code{read\_int}
  3792. and it takes zero arguments.}
  3793. %
  3794. \python{For now, the only functions we care about are \code{read\_int}
  3795. and \code{print\_int}, which take zero and one argument, respectively.}
  3796. %
  3797. The register \code{rax} is used for the return value of a function.
  3798. The next question is how these calling conventions impact register
  3799. allocation. Consider the \LangVar{} program in
  3800. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3801. example from the caller point of view and then from the callee point
  3802. of view.
  3803. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3804. is in use during the second call to \READOP{}, so we need to make sure
  3805. that the value in \code{x} does not get accidentally wiped out by the
  3806. call to \READOP{}. One obvious approach is to save all the values in
  3807. caller-saved registers to the stack prior to each function call, and
  3808. restore them after each call. That way, if the register allocator
  3809. chooses to assign \code{x} to a caller-saved register, its value will
  3810. be preserved across the call to \READOP{}. However, saving and
  3811. restoring to the stack is relatively slow. If \code{x} is not used
  3812. many times, it may be better to assign \code{x} to a stack location in
  3813. the first place. Or better yet, if we can arrange for \code{x} to be
  3814. placed in a callee-saved register, then it won't need to be saved and
  3815. restored during function calls.
  3816. The approach that we recommend for variables that are in use during a
  3817. function call is to either assign them to callee-saved registers or to
  3818. spill them to the stack. On the other hand, for variables that are not
  3819. in use during a function call, we try the following alternatives in
  3820. order 1) look for an available caller-saved register (to leave room
  3821. for other variables in the callee-saved register), 2) look for a
  3822. callee-saved register, and 3) spill the variable to the stack.
  3823. It is straightforward to implement this approach in a graph coloring
  3824. register allocator. First, we know which variables are in use during
  3825. every function call because we compute that information for every
  3826. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3827. we build the interference graph
  3828. (Section~\ref{sec:build-interference}), we can place an edge between
  3829. each of these call-live variables and the caller-saved registers in
  3830. the interference graph. This will prevent the graph coloring algorithm
  3831. from assigning them to caller-saved registers.
  3832. Returning to the example in
  3833. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3834. generated x86 code on the right-hand side. Notice that variable
  3835. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3836. is already in a safe place during the second call to
  3837. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3838. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3839. live-after set of a \code{callq} instruction.
  3840. Next we analyze the example from the callee point of view, focusing on
  3841. the prelude and conclusion of the \code{main} function. As usual the
  3842. prelude begins with saving the \code{rbp} register to the stack and
  3843. setting the \code{rbp} to the current stack pointer. We now know why
  3844. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3845. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3846. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3847. (\code{x}). The other callee-saved registers are not saved in the
  3848. prelude because they are not used. The prelude subtracts 8 bytes from
  3849. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3850. conclusion, we see that \code{rbx} is restored from the stack with a
  3851. \code{popq} instruction.
  3852. \index{subject}{prelude}\index{subject}{conclusion}
  3853. \begin{figure}[tp]
  3854. \begin{minipage}{0.45\textwidth}
  3855. Example \LangVar{} program:
  3856. %var_test_14.rkt
  3857. {\if\edition\racketEd
  3858. \begin{lstlisting}
  3859. (let ([x (read)])
  3860. (let ([y (read)])
  3861. (+ (+ x y) 42)))
  3862. \end{lstlisting}
  3863. \fi}
  3864. {\if\edition\pythonEd
  3865. \begin{lstlisting}
  3866. x = input_int()
  3867. y = input_int()
  3868. print((x + y) + 42)
  3869. \end{lstlisting}
  3870. \fi}
  3871. \end{minipage}
  3872. \begin{minipage}{0.45\textwidth}
  3873. Generated x86 assembly:
  3874. {\if\edition\racketEd
  3875. \begin{lstlisting}
  3876. start:
  3877. callq read_int
  3878. movq %rax, %rbx
  3879. callq read_int
  3880. movq %rax, %rcx
  3881. addq %rcx, %rbx
  3882. movq %rbx, %rax
  3883. addq $42, %rax
  3884. jmp _conclusion
  3885. .globl main
  3886. main:
  3887. pushq %rbp
  3888. movq %rsp, %rbp
  3889. pushq %rbx
  3890. subq $8, %rsp
  3891. jmp start
  3892. conclusion:
  3893. addq $8, %rsp
  3894. popq %rbx
  3895. popq %rbp
  3896. retq
  3897. \end{lstlisting}
  3898. \fi}
  3899. {\if\edition\pythonEd
  3900. \begin{lstlisting}
  3901. .globl main
  3902. main:
  3903. pushq %rbp
  3904. movq %rsp, %rbp
  3905. pushq %rbx
  3906. subq $8, %rsp
  3907. callq read_int
  3908. movq %rax, %rbx
  3909. callq read_int
  3910. movq %rax, %rcx
  3911. movq %rbx, %rdx
  3912. addq %rcx, %rdx
  3913. movq %rdx, %rcx
  3914. addq $42, %rcx
  3915. movq %rcx, %rdi
  3916. callq print_int
  3917. addq $8, %rsp
  3918. popq %rbx
  3919. popq %rbp
  3920. retq
  3921. \end{lstlisting}
  3922. \fi}
  3923. \end{minipage}
  3924. \caption{An example with function calls.}
  3925. \label{fig:example-calling-conventions}
  3926. \end{figure}
  3927. %\clearpage
  3928. \section{Liveness Analysis}
  3929. \label{sec:liveness-analysis-Lvar}
  3930. \index{subject}{liveness analysis}
  3931. The \code{uncover\_live} \racket{pass}\python{function}
  3932. performs \emph{liveness analysis}, that
  3933. is, it discovers which variables are in-use in different regions of a
  3934. program.
  3935. %
  3936. A variable or register is \emph{live} at a program point if its
  3937. current value is used at some later point in the program. We refer to
  3938. variables, stack locations, and registers collectively as
  3939. \emph{locations}.
  3940. %
  3941. Consider the following code fragment in which there are two writes to
  3942. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3943. \begin{center}
  3944. \begin{minipage}{0.96\textwidth}
  3945. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3946. movq $5, a
  3947. movq $30, b
  3948. movq a, c
  3949. movq $10, b
  3950. addq b, c
  3951. \end{lstlisting}
  3952. \end{minipage}
  3953. \end{center}
  3954. The answer is no because \code{a} is live from line 1 to 3 and
  3955. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3956. line 2 is never used because it is overwritten (line 4) before the
  3957. next read (line 5).
  3958. The live locations can be computed by traversing the instruction
  3959. sequence back to front (i.e., backwards in execution order). Let
  3960. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3961. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3962. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3963. locations before instruction $I_k$.
  3964. \racket{We recommend representing these
  3965. sets with the Racket \code{set} data structure described in
  3966. Figure~\ref{fig:set}.}
  3967. \python{We recommend representing these sets with the Python
  3968. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3969. data structure.}
  3970. {\if\edition\racketEd
  3971. \begin{figure}[tp]
  3972. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3973. \small
  3974. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3975. A \emph{set} is an unordered collection of elements without duplicates.
  3976. Here are some of the operations defined on sets.
  3977. \index{subject}{set}
  3978. \begin{description}
  3979. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3980. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3981. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3982. difference of the two sets.
  3983. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3984. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3985. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3986. \end{description}
  3987. \end{tcolorbox}
  3988. %\end{wrapfigure}
  3989. \caption{The \code{set} data structure.}
  3990. \label{fig:set}
  3991. \end{figure}
  3992. \fi}
  3993. The live locations after an instruction are always the same as the
  3994. live locations before the next instruction.
  3995. \index{subject}{live-after} \index{subject}{live-before}
  3996. \begin{equation} \label{eq:live-after-before-next}
  3997. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3998. \end{equation}
  3999. To start things off, there are no live locations after the last
  4000. instruction, so
  4001. \begin{equation}\label{eq:live-last-empty}
  4002. L_{\mathsf{after}}(n) = \emptyset
  4003. \end{equation}
  4004. We then apply the following rule repeatedly, traversing the
  4005. instruction sequence back to front.
  4006. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4007. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4008. \end{equation}
  4009. where $W(k)$ are the locations written to by instruction $I_k$ and
  4010. $R(k)$ are the locations read by instruction $I_k$.
  4011. {\if\edition\racketEd
  4012. There is a special case for \code{jmp} instructions. The locations
  4013. that are live before a \code{jmp} should be the locations in
  4014. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  4015. maintaining an alist named \code{label->live} that maps each label to
  4016. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  4017. now the only \code{jmp} in a \LangXVar{} program is the one at the
  4018. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  4019. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  4020. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4021. \fi}
  4022. Let us walk through the above example, applying these formulas
  4023. starting with the instruction on line 5. We collect the answers in
  4024. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  4025. \code{addq b, c} instruction is $\emptyset$ because it is the last
  4026. instruction (formula~\ref{eq:live-last-empty}). The
  4027. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4028. because it reads from variables \code{b} and \code{c}
  4029. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4030. \[
  4031. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4032. \]
  4033. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4034. the live-before set from line 5 to be the live-after set for this
  4035. instruction (formula~\ref{eq:live-after-before-next}).
  4036. \[
  4037. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4038. \]
  4039. This move instruction writes to \code{b} and does not read from any
  4040. variables, so we have the following live-before set
  4041. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4042. \[
  4043. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4044. \]
  4045. The live-before for instruction \code{movq a, c}
  4046. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4047. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4048. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4049. variable that is not live and does not read from a variable.
  4050. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4051. because it writes to variable \code{a}.
  4052. \begin{figure}[tbp]
  4053. \begin{minipage}{0.45\textwidth}
  4054. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4055. movq $5, a
  4056. movq $30, b
  4057. movq a, c
  4058. movq $10, b
  4059. addq b, c
  4060. \end{lstlisting}
  4061. \end{minipage}
  4062. \vrule\hspace{10pt}
  4063. \begin{minipage}{0.45\textwidth}
  4064. \begin{align*}
  4065. L_{\mathsf{before}}(1)= \emptyset,
  4066. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4067. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4068. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4069. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4070. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4071. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4072. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4073. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4074. L_{\mathsf{after}}(5)= \emptyset
  4075. \end{align*}
  4076. \end{minipage}
  4077. \caption{Example output of liveness analysis on a short example.}
  4078. \label{fig:liveness-example-0}
  4079. \end{figure}
  4080. \begin{exercise}\normalfont
  4081. Perform liveness analysis on the running example in
  4082. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4083. sets for each instruction. Compare your answers to the solution
  4084. shown in Figure~\ref{fig:live-eg}.
  4085. \end{exercise}
  4086. \begin{figure}[tp]
  4087. \hspace{20pt}
  4088. \begin{minipage}{0.45\textwidth}
  4089. {\if\edition\racketEd
  4090. \begin{lstlisting}
  4091. |$\{\ttm{rsp}\}$|
  4092. movq $1, v
  4093. |$\{\ttm{v},\ttm{rsp}\}$|
  4094. movq $42, w
  4095. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4096. movq v, x
  4097. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4098. addq $7, x
  4099. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4100. movq x, y
  4101. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4102. movq x, z
  4103. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4104. addq w, z
  4105. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4106. movq y, t
  4107. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4108. negq t
  4109. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4110. movq z, %rax
  4111. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4112. addq t, %rax
  4113. |$\{\ttm{rax},\ttm{rsp}\}$|
  4114. jmp conclusion
  4115. \end{lstlisting}
  4116. \fi}
  4117. {\if\edition\pythonEd
  4118. \begin{lstlisting}
  4119. movq $1, v
  4120. |$\{\ttm{v}\}$|
  4121. movq $42, w
  4122. |$\{\ttm{w}, \ttm{v}\}$|
  4123. movq v, x
  4124. |$\{\ttm{w}, \ttm{x}\}$|
  4125. addq $7, x
  4126. |$\{\ttm{w}, \ttm{x}\}$|
  4127. movq x, y
  4128. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4129. movq x, z
  4130. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4131. addq w, z
  4132. |$\{\ttm{y}, \ttm{z}\}$|
  4133. movq y, tmp_0
  4134. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4135. negq tmp_0
  4136. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4137. movq z, tmp_1
  4138. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4139. addq tmp_0, tmp_1
  4140. |$\{\ttm{tmp\_1}\}$|
  4141. movq tmp_1, %rdi
  4142. |$\{\ttm{rdi}\}$|
  4143. callq print_int
  4144. |$\{\}$|
  4145. \end{lstlisting}
  4146. \fi}
  4147. \end{minipage}
  4148. \caption{The running example annotated with live-after sets.}
  4149. \label{fig:live-eg}
  4150. \end{figure}
  4151. \begin{exercise}\normalfont
  4152. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4153. %
  4154. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4155. field of the \code{Block} structure.}
  4156. %
  4157. \python{Return a dictionary that maps each instruction to its
  4158. live-after set.}
  4159. %
  4160. \racket{We recommend creating an auxiliary function that takes a list
  4161. of instructions and an initial live-after set (typically empty) and
  4162. returns the list of live-after sets.}
  4163. %
  4164. We recommend creating auxiliary functions to 1) compute the set
  4165. of locations that appear in an \Arg{}, 2) compute the locations read
  4166. by an instruction (the $R$ function), and 3) the locations written by
  4167. an instruction (the $W$ function). The \code{callq} instruction should
  4168. include all of the caller-saved registers in its write-set $W$ because
  4169. the calling convention says that those registers may be written to
  4170. during the function call. Likewise, the \code{callq} instruction
  4171. should include the appropriate argument-passing registers in its
  4172. read-set $R$, depending on the arity of the function being
  4173. called. (This is why the abstract syntax for \code{callq} includes the
  4174. arity.)
  4175. \end{exercise}
  4176. %\clearpage
  4177. \section{Build the Interference Graph}
  4178. \label{sec:build-interference}
  4179. {\if\edition\racketEd
  4180. \begin{figure}[tp]
  4181. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4182. \small
  4183. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4184. A \emph{graph} is a collection of vertices and edges where each
  4185. edge connects two vertices. A graph is \emph{directed} if each
  4186. edge points from a source to a target. Otherwise the graph is
  4187. \emph{undirected}.
  4188. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4189. \begin{description}
  4190. %% We currently don't use directed graphs. We instead use
  4191. %% directed multi-graphs. -Jeremy
  4192. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4193. directed graph from a list of edges. Each edge is a list
  4194. containing the source and target vertex.
  4195. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4196. undirected graph from a list of edges. Each edge is represented by
  4197. a list containing two vertices.
  4198. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4199. inserts a vertex into the graph.
  4200. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4201. inserts an edge between the two vertices.
  4202. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4203. returns a sequence of vertices adjacent to the vertex.
  4204. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4205. returns a sequence of all vertices in the graph.
  4206. \end{description}
  4207. \end{tcolorbox}
  4208. %\end{wrapfigure}
  4209. \caption{The Racket \code{graph} package.}
  4210. \label{fig:graph}
  4211. \end{figure}
  4212. \fi}
  4213. Based on the liveness analysis, we know where each location is live.
  4214. However, during register allocation, we need to answer questions of
  4215. the specific form: are locations $u$ and $v$ live at the same time?
  4216. (And therefore cannot be assigned to the same register.) To make this
  4217. question more efficient to answer, we create an explicit data
  4218. structure, an \emph{interference graph}\index{subject}{interference
  4219. graph}. An interference graph is an undirected graph that has an
  4220. edge between two locations if they are live at the same time, that is,
  4221. if they interfere with each other.
  4222. %
  4223. \racket{We recommend using the Racket \code{graph} package
  4224. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4225. %
  4226. \python{We provide implementations of directed and undirected graph
  4227. data structures in the file \code{graph.py} of the support code.}
  4228. A straightforward way to compute the interference graph is to look at
  4229. the set of live locations between each instruction and add an edge to
  4230. the graph for every pair of variables in the same set. This approach
  4231. is less than ideal for two reasons. First, it can be expensive because
  4232. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4233. locations. Second, in the special case where two locations hold the
  4234. same value (because one was assigned to the other), they can be live
  4235. at the same time without interfering with each other.
  4236. A better way to compute the interference graph is to focus on
  4237. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4238. must not overwrite something in a live location. So for each
  4239. instruction, we create an edge between the locations being written to
  4240. and the live locations. (Except that one should not create self
  4241. edges.) Note that for the \key{callq} instruction, we consider all of
  4242. the caller-saved registers as being written to, so an edge is added
  4243. between every live variable and every caller-saved register. Also, for
  4244. \key{movq} there is the above-mentioned special case to deal with. If
  4245. a live variable $v$ is the same as the source of the \key{movq}, then
  4246. there is no need to add an edge between $v$ and the destination,
  4247. because they both hold the same value.
  4248. %
  4249. So we have the following two rules.
  4250. \begin{enumerate}
  4251. \item If instruction $I_k$ is a move instruction of the form
  4252. \key{movq} $s$\key{,} $d$, then for every $v \in
  4253. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4254. $(d,v)$.
  4255. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4256. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4257. $(d,v)$.
  4258. \end{enumerate}
  4259. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4260. the above rules to each instruction. We highlight a few of the
  4261. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4262. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4263. so \code{v} interferes with \code{rsp}.}
  4264. %
  4265. \python{The first instruction is \lstinline{movq $1, v} and the
  4266. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4267. no interference because $\ttm{v}$ is the destination of the move.}
  4268. %
  4269. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4270. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4271. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4272. %
  4273. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4274. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4275. $\ttm{x}$ interferes with \ttm{w}.}
  4276. %
  4277. \racket{The next instruction is \lstinline{movq x, y} and the
  4278. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4279. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4280. \ttm{x} because \ttm{x} is the source of the move and therefore
  4281. \ttm{x} and \ttm{y} hold the same value.}
  4282. %
  4283. \python{The next instruction is \lstinline{movq x, y} and the
  4284. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4285. applies, so \ttm{y} interferes with \ttm{w} but not
  4286. \ttm{x} because \ttm{x} is the source of the move and therefore
  4287. \ttm{x} and \ttm{y} hold the same value.}
  4288. %
  4289. Figure~\ref{fig:interference-results} lists the interference results
  4290. for all of the instructions and the resulting interference graph is
  4291. shown in Figure~\ref{fig:interfere}.
  4292. \begin{figure}[tbp]
  4293. \begin{quote}
  4294. {\if\edition\racketEd
  4295. \begin{tabular}{ll}
  4296. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4297. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4298. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4299. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4300. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4301. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4302. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4303. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4304. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4305. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4306. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4307. \lstinline!jmp conclusion!& no interference.
  4308. \end{tabular}
  4309. \fi}
  4310. {\if\edition\pythonEd
  4311. \begin{tabular}{ll}
  4312. \lstinline!movq $1, v!& no interference\\
  4313. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4314. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4315. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4316. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4317. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4318. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4319. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4320. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4321. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4322. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4323. \lstinline!movq tmp_1, %rdi! & no interference \\
  4324. \lstinline!callq print_int!& no interference.
  4325. \end{tabular}
  4326. \fi}
  4327. \end{quote}
  4328. \caption{Interference results for the running example.}
  4329. \label{fig:interference-results}
  4330. \end{figure}
  4331. \begin{figure}[tbp]
  4332. \large
  4333. {\if\edition\racketEd
  4334. \[
  4335. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4336. \node (rax) at (0,0) {$\ttm{rax}$};
  4337. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4338. \node (t1) at (0,2) {$\ttm{t}$};
  4339. \node (z) at (3,2) {$\ttm{z}$};
  4340. \node (x) at (6,2) {$\ttm{x}$};
  4341. \node (y) at (3,0) {$\ttm{y}$};
  4342. \node (w) at (6,0) {$\ttm{w}$};
  4343. \node (v) at (9,0) {$\ttm{v}$};
  4344. \draw (t1) to (rax);
  4345. \draw (t1) to (z);
  4346. \draw (z) to (y);
  4347. \draw (z) to (w);
  4348. \draw (x) to (w);
  4349. \draw (y) to (w);
  4350. \draw (v) to (w);
  4351. \draw (v) to (rsp);
  4352. \draw (w) to (rsp);
  4353. \draw (x) to (rsp);
  4354. \draw (y) to (rsp);
  4355. \path[-.,bend left=15] (z) edge node {} (rsp);
  4356. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4357. \draw (rax) to (rsp);
  4358. \end{tikzpicture}
  4359. \]
  4360. \fi}
  4361. {\if\edition\pythonEd
  4362. \[
  4363. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4364. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4365. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4366. \node (z) at (3,2) {$\ttm{z}$};
  4367. \node (x) at (6,2) {$\ttm{x}$};
  4368. \node (y) at (3,0) {$\ttm{y}$};
  4369. \node (w) at (6,0) {$\ttm{w}$};
  4370. \node (v) at (9,0) {$\ttm{v}$};
  4371. \draw (t0) to (t1);
  4372. \draw (t0) to (z);
  4373. \draw (z) to (y);
  4374. \draw (z) to (w);
  4375. \draw (x) to (w);
  4376. \draw (y) to (w);
  4377. \draw (v) to (w);
  4378. \end{tikzpicture}
  4379. \]
  4380. \fi}
  4381. \caption{The interference graph of the example program.}
  4382. \label{fig:interfere}
  4383. \end{figure}
  4384. %% Our next concern is to choose a data structure for representing the
  4385. %% interference graph. There are many choices for how to represent a
  4386. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4387. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4388. %% data structure is to study the algorithm that uses the data structure,
  4389. %% determine what operations need to be performed, and then choose the
  4390. %% data structure that provide the most efficient implementations of
  4391. %% those operations. Often times the choice of data structure can have an
  4392. %% effect on the time complexity of the algorithm, as it does here. If
  4393. %% you skim the next section, you will see that the register allocation
  4394. %% algorithm needs to ask the graph for all of its vertices and, given a
  4395. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4396. %% correct choice of graph representation is that of an adjacency
  4397. %% list. There are helper functions in \code{utilities.rkt} for
  4398. %% representing graphs using the adjacency list representation:
  4399. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4400. %% (Appendix~\ref{appendix:utilities}).
  4401. %% %
  4402. %% \margincomment{\footnotesize To do: change to use the
  4403. %% Racket graph library. \\ --Jeremy}
  4404. %% %
  4405. %% In particular, those functions use a hash table to map each vertex to
  4406. %% the set of adjacent vertices, and the sets are represented using
  4407. %% Racket's \key{set}, which is also a hash table.
  4408. \begin{exercise}\normalfont
  4409. \racket{Implement the compiler pass named \code{build\_interference} according
  4410. to the algorithm suggested above. We recommend using the Racket
  4411. \code{graph} package to create and inspect the interference graph.
  4412. The output graph of this pass should be stored in the $\itm{info}$ field of
  4413. the program, under the key \code{conflicts}.}
  4414. %
  4415. \python{Implement a function named \code{build\_interference}
  4416. according to the algorithm suggested above that
  4417. returns the interference graph.}
  4418. \end{exercise}
  4419. \section{Graph Coloring via Sudoku}
  4420. \label{sec:graph-coloring}
  4421. \index{subject}{graph coloring}
  4422. \index{subject}{Sudoku}
  4423. \index{subject}{color}
  4424. We come to the main event, mapping variables to registers and stack
  4425. locations. Variables that interfere with each other must be mapped to
  4426. different locations. In terms of the interference graph, this means
  4427. that adjacent vertices must be mapped to different locations. If we
  4428. think of locations as colors, the register allocation problem becomes
  4429. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4430. The reader may be more familiar with the graph coloring problem than he
  4431. or she realizes; the popular game of Sudoku is an instance of the
  4432. graph coloring problem. The following describes how to build a graph
  4433. out of an initial Sudoku board.
  4434. \begin{itemize}
  4435. \item There is one vertex in the graph for each Sudoku square.
  4436. \item There is an edge between two vertices if the corresponding squares
  4437. are in the same row, in the same column, or if the squares are in
  4438. the same $3\times 3$ region.
  4439. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4440. \item Based on the initial assignment of numbers to squares in the
  4441. Sudoku board, assign the corresponding colors to the corresponding
  4442. vertices in the graph.
  4443. \end{itemize}
  4444. If you can color the remaining vertices in the graph with the nine
  4445. colors, then you have also solved the corresponding game of Sudoku.
  4446. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4447. the corresponding graph with colored vertices. We map the Sudoku
  4448. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4449. sampling of the vertices (the colored ones) because showing edges for
  4450. all of the vertices would make the graph unreadable.
  4451. \begin{figure}[tbp]
  4452. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4453. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4454. \caption{A Sudoku game board and the corresponding colored graph.}
  4455. \label{fig:sudoku-graph}
  4456. \end{figure}
  4457. Some techniques for playing Sudoku correspond to heuristics used in
  4458. graph coloring algorithms. For example, one of the basic techniques
  4459. for Sudoku is called Pencil Marks. The idea is to use a process of
  4460. elimination to determine what numbers are no longer available for a
  4461. square and write down those numbers in the square (writing very
  4462. small). For example, if the number $1$ is assigned to a square, then
  4463. write the pencil mark $1$ in all the squares in the same row, column,
  4464. and region to indicate that $1$ is no longer an option for those other
  4465. squares.
  4466. %
  4467. The Pencil Marks technique corresponds to the notion of
  4468. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4469. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4470. are no longer available. In graph terminology, we have the following
  4471. definition:
  4472. \begin{equation*}
  4473. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4474. \text{ and } \mathrm{color}(v) = c \}
  4475. \end{equation*}
  4476. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4477. edge with $u$.
  4478. The Pencil Marks technique leads to a simple strategy for filling in
  4479. numbers: if there is a square with only one possible number left, then
  4480. choose that number! But what if there are no squares with only one
  4481. possibility left? One brute-force approach is to try them all: choose
  4482. the first one and if that ultimately leads to a solution, great. If
  4483. not, backtrack and choose the next possibility. One good thing about
  4484. Pencil Marks is that it reduces the degree of branching in the search
  4485. tree. Nevertheless, backtracking can be terribly time consuming. One
  4486. way to reduce the amount of backtracking is to use the
  4487. most-constrained-first heuristic (aka. minimum remaining
  4488. values)~\citep{Russell2003}. That is, when choosing a square, always
  4489. choose one with the fewest possibilities left (the vertex with the
  4490. highest saturation). The idea is that choosing highly constrained
  4491. squares earlier rather than later is better because later on there may
  4492. not be any possibilities left in the highly saturated squares.
  4493. However, register allocation is easier than Sudoku because the
  4494. register allocator can fall back to assigning variables to stack
  4495. locations when the registers run out. Thus, it makes sense to replace
  4496. backtracking with greedy search: make the best choice at the time and
  4497. keep going. We still wish to minimize the number of colors needed, so
  4498. we use the most-constrained-first heuristic in the greedy search.
  4499. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4500. algorithm for register allocation based on saturation and the
  4501. most-constrained-first heuristic. It is roughly equivalent to the
  4502. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4503. %,Gebremedhin:1999fk,Omari:2006uq
  4504. Just as in Sudoku, the algorithm represents colors with integers. The
  4505. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4506. for register allocation. The integers $k$ and larger correspond to
  4507. stack locations. The registers that are not used for register
  4508. allocation, such as \code{rax}, are assigned to negative integers. In
  4509. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4510. %% One might wonder why we include registers at all in the liveness
  4511. %% analysis and interference graph. For example, we never allocate a
  4512. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4513. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4514. %% to use register for passing arguments to functions, it will be
  4515. %% necessary for those registers to appear in the interference graph
  4516. %% because those registers will also be assigned to variables, and we
  4517. %% don't want those two uses to encroach on each other. Regarding
  4518. %% registers such as \code{rax} and \code{rsp} that are not used for
  4519. %% variables, we could omit them from the interference graph but that
  4520. %% would require adding special cases to our algorithm, which would
  4521. %% complicate the logic for little gain.
  4522. \begin{figure}[btp]
  4523. \centering
  4524. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4525. Algorithm: DSATUR
  4526. Input: a graph |$G$|
  4527. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4528. |$W \gets \mathrm{vertices}(G)$|
  4529. while |$W \neq \emptyset$| do
  4530. pick a vertex |$u$| from |$W$| with the highest saturation,
  4531. breaking ties randomly
  4532. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4533. |$\mathrm{color}[u] \gets c$|
  4534. |$W \gets W - \{u\}$|
  4535. \end{lstlisting}
  4536. \caption{The saturation-based greedy graph coloring algorithm.}
  4537. \label{fig:satur-algo}
  4538. \end{figure}
  4539. {\if\edition\racketEd
  4540. With the DSATUR algorithm in hand, let us return to the running
  4541. example and consider how to color the interference graph in
  4542. Figure~\ref{fig:interfere}.
  4543. %
  4544. We start by assigning the register nodes to their own color. For
  4545. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4546. assigned $-2$. The variables are not yet colored, so they are
  4547. annotated with a dash. We then update the saturation for vertices that
  4548. are adjacent to a register, obtaining the following annotated
  4549. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4550. it interferes with both \code{rax} and \code{rsp}.
  4551. \[
  4552. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4553. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4554. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4555. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4556. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4557. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4558. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4559. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4560. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4561. \draw (t1) to (rax);
  4562. \draw (t1) to (z);
  4563. \draw (z) to (y);
  4564. \draw (z) to (w);
  4565. \draw (x) to (w);
  4566. \draw (y) to (w);
  4567. \draw (v) to (w);
  4568. \draw (v) to (rsp);
  4569. \draw (w) to (rsp);
  4570. \draw (x) to (rsp);
  4571. \draw (y) to (rsp);
  4572. \path[-.,bend left=15] (z) edge node {} (rsp);
  4573. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4574. \draw (rax) to (rsp);
  4575. \end{tikzpicture}
  4576. \]
  4577. The algorithm says to select a maximally saturated vertex. So we pick
  4578. $\ttm{t}$ and color it with the first available integer, which is
  4579. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4580. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4581. \[
  4582. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4583. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4584. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4585. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4586. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4587. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4588. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4589. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4590. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4591. \draw (t1) to (rax);
  4592. \draw (t1) to (z);
  4593. \draw (z) to (y);
  4594. \draw (z) to (w);
  4595. \draw (x) to (w);
  4596. \draw (y) to (w);
  4597. \draw (v) to (w);
  4598. \draw (v) to (rsp);
  4599. \draw (w) to (rsp);
  4600. \draw (x) to (rsp);
  4601. \draw (y) to (rsp);
  4602. \path[-.,bend left=15] (z) edge node {} (rsp);
  4603. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4604. \draw (rax) to (rsp);
  4605. \end{tikzpicture}
  4606. \]
  4607. We repeat the process, selecting a maximally saturated vertex,
  4608. choosing is \code{z}, and color it with the first available number, which
  4609. is $1$. We add $1$ to the saturation for the neighboring vertices
  4610. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4611. \[
  4612. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4613. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4614. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4615. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4616. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4617. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4618. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4619. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4620. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4621. \draw (t1) to (rax);
  4622. \draw (t1) to (z);
  4623. \draw (z) to (y);
  4624. \draw (z) to (w);
  4625. \draw (x) to (w);
  4626. \draw (y) to (w);
  4627. \draw (v) to (w);
  4628. \draw (v) to (rsp);
  4629. \draw (w) to (rsp);
  4630. \draw (x) to (rsp);
  4631. \draw (y) to (rsp);
  4632. \path[-.,bend left=15] (z) edge node {} (rsp);
  4633. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4634. \draw (rax) to (rsp);
  4635. \end{tikzpicture}
  4636. \]
  4637. The most saturated vertices are now \code{w} and \code{y}. We color
  4638. \code{w} with the first available color, which is $0$.
  4639. \[
  4640. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4641. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4642. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4643. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4644. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4645. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4646. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4647. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4648. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4649. \draw (t1) to (rax);
  4650. \draw (t1) to (z);
  4651. \draw (z) to (y);
  4652. \draw (z) to (w);
  4653. \draw (x) to (w);
  4654. \draw (y) to (w);
  4655. \draw (v) to (w);
  4656. \draw (v) to (rsp);
  4657. \draw (w) to (rsp);
  4658. \draw (x) to (rsp);
  4659. \draw (y) to (rsp);
  4660. \path[-.,bend left=15] (z) edge node {} (rsp);
  4661. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4662. \draw (rax) to (rsp);
  4663. \end{tikzpicture}
  4664. \]
  4665. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4666. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4667. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4668. and \code{z}, whose colors are $0$ and $1$ respectively.
  4669. \[
  4670. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4671. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4672. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4673. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4674. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4675. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4676. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4677. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4678. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4679. \draw (t1) to (rax);
  4680. \draw (t1) to (z);
  4681. \draw (z) to (y);
  4682. \draw (z) to (w);
  4683. \draw (x) to (w);
  4684. \draw (y) to (w);
  4685. \draw (v) to (w);
  4686. \draw (v) to (rsp);
  4687. \draw (w) to (rsp);
  4688. \draw (x) to (rsp);
  4689. \draw (y) to (rsp);
  4690. \path[-.,bend left=15] (z) edge node {} (rsp);
  4691. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4692. \draw (rax) to (rsp);
  4693. \end{tikzpicture}
  4694. \]
  4695. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4696. \[
  4697. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4698. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4699. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4700. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4701. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4702. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4703. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4704. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4705. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4706. \draw (t1) to (rax);
  4707. \draw (t1) to (z);
  4708. \draw (z) to (y);
  4709. \draw (z) to (w);
  4710. \draw (x) to (w);
  4711. \draw (y) to (w);
  4712. \draw (v) to (w);
  4713. \draw (v) to (rsp);
  4714. \draw (w) to (rsp);
  4715. \draw (x) to (rsp);
  4716. \draw (y) to (rsp);
  4717. \path[-.,bend left=15] (z) edge node {} (rsp);
  4718. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4719. \draw (rax) to (rsp);
  4720. \end{tikzpicture}
  4721. \]
  4722. In the last step of the algorithm, we color \code{x} with $1$.
  4723. \[
  4724. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4725. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4726. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4727. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4728. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4729. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4730. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4731. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4732. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4733. \draw (t1) to (rax);
  4734. \draw (t1) to (z);
  4735. \draw (z) to (y);
  4736. \draw (z) to (w);
  4737. \draw (x) to (w);
  4738. \draw (y) to (w);
  4739. \draw (v) to (w);
  4740. \draw (v) to (rsp);
  4741. \draw (w) to (rsp);
  4742. \draw (x) to (rsp);
  4743. \draw (y) to (rsp);
  4744. \path[-.,bend left=15] (z) edge node {} (rsp);
  4745. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4746. \draw (rax) to (rsp);
  4747. \end{tikzpicture}
  4748. \]
  4749. So we obtain the following coloring:
  4750. \[
  4751. \{
  4752. \ttm{rax} \mapsto -1,
  4753. \ttm{rsp} \mapsto -2,
  4754. \ttm{t} \mapsto 0,
  4755. \ttm{z} \mapsto 1,
  4756. \ttm{x} \mapsto 1,
  4757. \ttm{y} \mapsto 2,
  4758. \ttm{w} \mapsto 0,
  4759. \ttm{v} \mapsto 1
  4760. \}
  4761. \]
  4762. \fi}
  4763. %
  4764. {\if\edition\pythonEd
  4765. %
  4766. With the DSATUR algorithm in hand, let us return to the running
  4767. example and consider how to color the interference graph in
  4768. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4769. to indicate that it has not yet been assigned a color. The saturation
  4770. sets are also shown for each node; all of them start as the empty set.
  4771. (We do not include the register nodes in the graph below because there
  4772. were no interference edges involving registers in this program, but in
  4773. general there can be.)
  4774. %
  4775. \[
  4776. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4777. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4778. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4779. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4780. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4781. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4782. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4783. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4784. \draw (t0) to (t1);
  4785. \draw (t0) to (z);
  4786. \draw (z) to (y);
  4787. \draw (z) to (w);
  4788. \draw (x) to (w);
  4789. \draw (y) to (w);
  4790. \draw (v) to (w);
  4791. \end{tikzpicture}
  4792. \]
  4793. The algorithm says to select a maximally saturated vertex, but they
  4794. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4795. then color it with the first available integer, which is $0$. We mark
  4796. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4797. they interfere with $\ttm{tmp\_0}$.
  4798. \[
  4799. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4800. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4801. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4802. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4803. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4804. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4805. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4806. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4807. \draw (t0) to (t1);
  4808. \draw (t0) to (z);
  4809. \draw (z) to (y);
  4810. \draw (z) to (w);
  4811. \draw (x) to (w);
  4812. \draw (y) to (w);
  4813. \draw (v) to (w);
  4814. \end{tikzpicture}
  4815. \]
  4816. We repeat the process. The most saturated vertices are \code{z} and
  4817. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4818. available number, which is $1$. We add $1$ to the saturation for the
  4819. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4820. \[
  4821. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4822. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4823. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4824. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4825. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4826. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4827. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4828. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4829. \draw (t0) to (t1);
  4830. \draw (t0) to (z);
  4831. \draw (z) to (y);
  4832. \draw (z) to (w);
  4833. \draw (x) to (w);
  4834. \draw (y) to (w);
  4835. \draw (v) to (w);
  4836. \end{tikzpicture}
  4837. \]
  4838. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4839. \code{y}. We color \code{w} with the first available color, which
  4840. is $0$.
  4841. \[
  4842. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4843. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4844. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4845. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4846. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4847. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4848. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4849. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4850. \draw (t0) to (t1);
  4851. \draw (t0) to (z);
  4852. \draw (z) to (y);
  4853. \draw (z) to (w);
  4854. \draw (x) to (w);
  4855. \draw (y) to (w);
  4856. \draw (v) to (w);
  4857. \end{tikzpicture}
  4858. \]
  4859. Now \code{y} is the most saturated, so we color it with $2$.
  4860. \[
  4861. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4862. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4863. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4864. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4865. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4866. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4867. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4868. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4869. \draw (t0) to (t1);
  4870. \draw (t0) to (z);
  4871. \draw (z) to (y);
  4872. \draw (z) to (w);
  4873. \draw (x) to (w);
  4874. \draw (y) to (w);
  4875. \draw (v) to (w);
  4876. \end{tikzpicture}
  4877. \]
  4878. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4879. We choose to color \code{v} with $1$.
  4880. \[
  4881. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4882. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4883. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4884. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4885. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4886. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4887. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4888. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4889. \draw (t0) to (t1);
  4890. \draw (t0) to (z);
  4891. \draw (z) to (y);
  4892. \draw (z) to (w);
  4893. \draw (x) to (w);
  4894. \draw (y) to (w);
  4895. \draw (v) to (w);
  4896. \end{tikzpicture}
  4897. \]
  4898. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4899. \[
  4900. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4901. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4902. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4903. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4904. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4905. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4906. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4907. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4908. \draw (t0) to (t1);
  4909. \draw (t0) to (z);
  4910. \draw (z) to (y);
  4911. \draw (z) to (w);
  4912. \draw (x) to (w);
  4913. \draw (y) to (w);
  4914. \draw (v) to (w);
  4915. \end{tikzpicture}
  4916. \]
  4917. So we obtain the following coloring:
  4918. \[
  4919. \{ \ttm{tmp\_0} \mapsto 0,
  4920. \ttm{tmp\_1} \mapsto 1,
  4921. \ttm{z} \mapsto 1,
  4922. \ttm{x} \mapsto 1,
  4923. \ttm{y} \mapsto 2,
  4924. \ttm{w} \mapsto 0,
  4925. \ttm{v} \mapsto 1 \}
  4926. \]
  4927. \fi}
  4928. We recommend creating an auxiliary function named \code{color\_graph}
  4929. that takes an interference graph and a list of all the variables in
  4930. the program. This function should return a mapping of variables to
  4931. their colors (represented as natural numbers). By creating this helper
  4932. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  4933. when we add support for functions.
  4934. To prioritize the processing of highly saturated nodes inside the
  4935. \code{color\_graph} function, we recommend using the priority queue
  4936. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4937. addition, you will need to maintain a mapping from variables to their
  4938. ``handles'' in the priority queue so that you can notify the priority
  4939. queue when their saturation changes.}
  4940. {\if\edition\racketEd
  4941. \begin{figure}[tp]
  4942. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4943. \small
  4944. \begin{tcolorbox}[title=Priority Queue]
  4945. A \emph{priority queue} is a collection of items in which the
  4946. removal of items is governed by priority. In a ``min'' queue,
  4947. lower priority items are removed first. An implementation is in
  4948. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4949. queue} \index{subject}{minimum priority queue}
  4950. \begin{description}
  4951. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4952. priority queue that uses the $\itm{cmp}$ predicate to determine
  4953. whether its first argument has lower or equal priority to its
  4954. second argument.
  4955. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4956. items in the queue.
  4957. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4958. the item into the queue and returns a handle for the item in the
  4959. queue.
  4960. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4961. the lowest priority.
  4962. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4963. notifies the queue that the priority has decreased for the item
  4964. associated with the given handle.
  4965. \end{description}
  4966. \end{tcolorbox}
  4967. %\end{wrapfigure}
  4968. \caption{The priority queue data structure.}
  4969. \label{fig:priority-queue}
  4970. \end{figure}
  4971. \fi}
  4972. With the coloring complete, we finalize the assignment of variables to
  4973. registers and stack locations. We map the first $k$ colors to the $k$
  4974. registers and the rest of the colors to stack locations. Suppose for
  4975. the moment that we have just one register to use for register
  4976. allocation, \key{rcx}. Then we have the following map from colors to
  4977. locations.
  4978. \[
  4979. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4980. \]
  4981. Composing this mapping with the coloring, we arrive at the following
  4982. assignment of variables to locations.
  4983. {\if\edition\racketEd
  4984. \begin{gather*}
  4985. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4986. \ttm{w} \mapsto \key{\%rcx}, \,
  4987. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4988. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4989. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4990. \ttm{t} \mapsto \key{\%rcx} \}
  4991. \end{gather*}
  4992. \fi}
  4993. {\if\edition\pythonEd
  4994. \begin{gather*}
  4995. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4996. \ttm{w} \mapsto \key{\%rcx}, \,
  4997. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4998. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4999. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5000. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5001. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5002. \end{gather*}
  5003. \fi}
  5004. Adapt the code from the \code{assign\_homes} pass
  5005. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  5006. assigned location. Applying the above assignment to our running
  5007. example, on the left, yields the program on the right.
  5008. % why frame size of 32? -JGS
  5009. \begin{center}
  5010. {\if\edition\racketEd
  5011. \begin{minipage}{0.3\textwidth}
  5012. \begin{lstlisting}
  5013. movq $1, v
  5014. movq $42, w
  5015. movq v, x
  5016. addq $7, x
  5017. movq x, y
  5018. movq x, z
  5019. addq w, z
  5020. movq y, t
  5021. negq t
  5022. movq z, %rax
  5023. addq t, %rax
  5024. jmp conclusion
  5025. \end{lstlisting}
  5026. \end{minipage}
  5027. $\Rightarrow\qquad$
  5028. \begin{minipage}{0.45\textwidth}
  5029. \begin{lstlisting}
  5030. movq $1, -8(%rbp)
  5031. movq $42, %rcx
  5032. movq -8(%rbp), -8(%rbp)
  5033. addq $7, -8(%rbp)
  5034. movq -8(%rbp), -16(%rbp)
  5035. movq -8(%rbp), -8(%rbp)
  5036. addq %rcx, -8(%rbp)
  5037. movq -16(%rbp), %rcx
  5038. negq %rcx
  5039. movq -8(%rbp), %rax
  5040. addq %rcx, %rax
  5041. jmp conclusion
  5042. \end{lstlisting}
  5043. \end{minipage}
  5044. \fi}
  5045. {\if\edition\pythonEd
  5046. \begin{minipage}{0.3\textwidth}
  5047. \begin{lstlisting}
  5048. movq $1, v
  5049. movq $42, w
  5050. movq v, x
  5051. addq $7, x
  5052. movq x, y
  5053. movq x, z
  5054. addq w, z
  5055. movq y, tmp_0
  5056. negq tmp_0
  5057. movq z, tmp_1
  5058. addq tmp_0, tmp_1
  5059. movq tmp_1, %rdi
  5060. callq print_int
  5061. \end{lstlisting}
  5062. \end{minipage}
  5063. $\Rightarrow\qquad$
  5064. \begin{minipage}{0.45\textwidth}
  5065. \begin{lstlisting}
  5066. movq $1, -8(%rbp)
  5067. movq $42, %rcx
  5068. movq -8(%rbp), -8(%rbp)
  5069. addq $7, -8(%rbp)
  5070. movq -8(%rbp), -16(%rbp)
  5071. movq -8(%rbp), -8(%rbp)
  5072. addq %rcx, -8(%rbp)
  5073. movq -16(%rbp), %rcx
  5074. negq %rcx
  5075. movq -8(%rbp), -8(%rbp)
  5076. addq %rcx, -8(%rbp)
  5077. movq -8(%rbp), %rdi
  5078. callq print_int
  5079. \end{lstlisting}
  5080. \end{minipage}
  5081. \fi}
  5082. \end{center}
  5083. \begin{exercise}\normalfont
  5084. %
  5085. Implement the compiler pass \code{allocate\_registers}.
  5086. %
  5087. Create five programs that exercise all aspects of the register
  5088. allocation algorithm, including spilling variables to the stack.
  5089. %
  5090. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  5091. \code{run-tests.rkt} script with the three new passes:
  5092. \code{uncover\_live}, \code{build\_interference}, and
  5093. \code{allocate\_registers}.
  5094. %
  5095. Temporarily remove the \code{print\_x86} pass from the list of passes
  5096. and the call to \code{compiler-tests}.
  5097. Run the script to test the register allocator.
  5098. }
  5099. %
  5100. \python{Run the \code{run-tests.py} script to to check whether the
  5101. output programs produce the same result as the input programs.}
  5102. \end{exercise}
  5103. \section{Patch Instructions}
  5104. \label{sec:patch-instructions}
  5105. The remaining step in the compilation to x86 is to ensure that the
  5106. instructions have at most one argument that is a memory access.
  5107. %
  5108. In the running example, the instruction \code{movq -8(\%rbp),
  5109. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5110. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5111. then move \code{rax} into \code{-16(\%rbp)}.
  5112. %
  5113. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5114. problematic, but they can simply be deleted. In general, we recommend
  5115. deleting all the trivial moves whose source and destination are the
  5116. same location.
  5117. %
  5118. The following is the output of \code{patch\_instructions} on the
  5119. running example.
  5120. \begin{center}
  5121. {\if\edition\racketEd
  5122. \begin{minipage}{0.4\textwidth}
  5123. \begin{lstlisting}
  5124. movq $1, -8(%rbp)
  5125. movq $42, %rcx
  5126. movq -8(%rbp), -8(%rbp)
  5127. addq $7, -8(%rbp)
  5128. movq -8(%rbp), -16(%rbp)
  5129. movq -8(%rbp), -8(%rbp)
  5130. addq %rcx, -8(%rbp)
  5131. movq -16(%rbp), %rcx
  5132. negq %rcx
  5133. movq -8(%rbp), %rax
  5134. addq %rcx, %rax
  5135. jmp conclusion
  5136. \end{lstlisting}
  5137. \end{minipage}
  5138. $\Rightarrow\qquad$
  5139. \begin{minipage}{0.45\textwidth}
  5140. \begin{lstlisting}
  5141. movq $1, -8(%rbp)
  5142. movq $42, %rcx
  5143. addq $7, -8(%rbp)
  5144. movq -8(%rbp), %rax
  5145. movq %rax, -16(%rbp)
  5146. addq %rcx, -8(%rbp)
  5147. movq -16(%rbp), %rcx
  5148. negq %rcx
  5149. movq -8(%rbp), %rax
  5150. addq %rcx, %rax
  5151. jmp conclusion
  5152. \end{lstlisting}
  5153. \end{minipage}
  5154. \fi}
  5155. {\if\edition\pythonEd
  5156. \begin{minipage}{0.4\textwidth}
  5157. \begin{lstlisting}
  5158. movq $1, -8(%rbp)
  5159. movq $42, %rcx
  5160. movq -8(%rbp), -8(%rbp)
  5161. addq $7, -8(%rbp)
  5162. movq -8(%rbp), -16(%rbp)
  5163. movq -8(%rbp), -8(%rbp)
  5164. addq %rcx, -8(%rbp)
  5165. movq -16(%rbp), %rcx
  5166. negq %rcx
  5167. movq -8(%rbp), -8(%rbp)
  5168. addq %rcx, -8(%rbp)
  5169. movq -8(%rbp), %rdi
  5170. callq print_int
  5171. \end{lstlisting}
  5172. \end{minipage}
  5173. $\Rightarrow\qquad$
  5174. \begin{minipage}{0.45\textwidth}
  5175. \begin{lstlisting}
  5176. movq $1, -8(%rbp)
  5177. movq $42, %rcx
  5178. addq $7, -8(%rbp)
  5179. movq -8(%rbp), %rax
  5180. movq %rax, -16(%rbp)
  5181. addq %rcx, -8(%rbp)
  5182. movq -16(%rbp), %rcx
  5183. negq %rcx
  5184. addq %rcx, -8(%rbp)
  5185. movq -8(%rbp), %rdi
  5186. callq print_int
  5187. \end{lstlisting}
  5188. \end{minipage}
  5189. \fi}
  5190. \end{center}
  5191. \begin{exercise}\normalfont
  5192. %
  5193. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5194. %
  5195. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5196. %in the \code{run-tests.rkt} script.
  5197. %
  5198. Run the script to test the \code{patch\_instructions} pass.
  5199. \end{exercise}
  5200. \section{Prelude and Conclusion}
  5201. \label{sec:print-x86-reg-alloc}
  5202. \index{subject}{calling conventions}
  5203. \index{subject}{prelude}\index{subject}{conclusion}
  5204. Recall that this pass generates the prelude and conclusion
  5205. instructions to satisfy the x86 calling conventions
  5206. (Section~\ref{sec:calling-conventions}). With the addition of the
  5207. register allocator, the callee-saved registers used by the register
  5208. allocator must be saved in the prelude and restored in the conclusion.
  5209. In the \code{allocate\_registers} pass,
  5210. %
  5211. \racket{add an entry to the \itm{info}
  5212. of \code{X86Program} named \code{used\_callee}}
  5213. %
  5214. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5215. %
  5216. that stores the set of callee-saved registers that were assigned to
  5217. variables. The \code{prelude\_and\_conclusion} pass can then access
  5218. this information to decide which callee-saved registers need to be
  5219. saved and restored.
  5220. %
  5221. When calculating the size of the frame to adjust the \code{rsp} in the
  5222. prelude, make sure to take into account the space used for saving the
  5223. callee-saved registers. Also, don't forget that the frame needs to be
  5224. a multiple of 16 bytes!
  5225. \racket{An overview of all of the passes involved in register
  5226. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5227. {\if\edition\racketEd
  5228. \begin{figure}[tbp]
  5229. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5230. \node (Lvar) at (0,2) {\large \LangVar{}};
  5231. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5232. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5233. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5234. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5235. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5236. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5237. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5238. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5239. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5240. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5241. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5242. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5243. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5244. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5245. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5246. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5247. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5248. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5249. \end{tikzpicture}
  5250. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5251. \label{fig:reg-alloc-passes}
  5252. \end{figure}
  5253. \fi}
  5254. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5255. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5256. use of registers and the stack, we limit the register allocator for
  5257. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5258. the prelude\index{subject}{prelude} of the \code{main} function, we
  5259. push \code{rbx} onto the stack because it is a callee-saved register
  5260. and it was assigned to variable by the register allocator. We
  5261. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5262. reserve space for the one spilled variable. After that subtraction,
  5263. the \code{rsp} is aligned to 16 bytes.
  5264. Moving on to the program proper, we see how the registers were
  5265. allocated.
  5266. %
  5267. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5268. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5269. %
  5270. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5271. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5272. were assigned to \code{rbx}.}
  5273. %
  5274. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5275. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5276. callee-save register \code{rbx} onto the stack. The spilled variables
  5277. must be placed lower on the stack than the saved callee-save
  5278. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5279. \code{-16(\%rbp)}.
  5280. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5281. done in the prelude. We move the stack pointer up by \code{8} bytes
  5282. (the room for spilled variables), then we pop the old values of
  5283. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5284. \code{retq} to return control to the operating system.
  5285. \begin{figure}[tbp]
  5286. % var_test_28.rkt
  5287. % (use-minimal-set-of-registers! #t)
  5288. % and only rbx rcx
  5289. % tmp 0 rbx
  5290. % z 1 rcx
  5291. % y 0 rbx
  5292. % w 2 16(%rbp)
  5293. % v 0 rbx
  5294. % x 0 rbx
  5295. {\if\edition\racketEd
  5296. \begin{lstlisting}
  5297. start:
  5298. movq $1, %rbx
  5299. movq $42, -16(%rbp)
  5300. addq $7, %rbx
  5301. movq %rbx, %rcx
  5302. addq -16(%rbp), %rcx
  5303. negq %rbx
  5304. movq %rcx, %rax
  5305. addq %rbx, %rax
  5306. jmp conclusion
  5307. .globl main
  5308. main:
  5309. pushq %rbp
  5310. movq %rsp, %rbp
  5311. pushq %rbx
  5312. subq $8, %rsp
  5313. jmp start
  5314. conclusion:
  5315. addq $8, %rsp
  5316. popq %rbx
  5317. popq %rbp
  5318. retq
  5319. \end{lstlisting}
  5320. \fi}
  5321. {\if\edition\pythonEd
  5322. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5323. \begin{lstlisting}
  5324. .globl main
  5325. main:
  5326. pushq %rbp
  5327. movq %rsp, %rbp
  5328. pushq %rbx
  5329. subq $8, %rsp
  5330. movq $1, %rcx
  5331. movq $42, %rbx
  5332. addq $7, %rcx
  5333. movq %rcx, -16(%rbp)
  5334. addq %rbx, -16(%rbp)
  5335. negq %rcx
  5336. movq -16(%rbp), %rbx
  5337. addq %rcx, %rbx
  5338. movq %rbx, %rdi
  5339. callq print_int
  5340. addq $8, %rsp
  5341. popq %rbx
  5342. popq %rbp
  5343. retq
  5344. \end{lstlisting}
  5345. \fi}
  5346. \caption{The x86 output from the running example
  5347. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5348. and \code{rcx}.}
  5349. \label{fig:running-example-x86}
  5350. \end{figure}
  5351. \begin{exercise}\normalfont
  5352. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5353. %
  5354. \racket{
  5355. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5356. list of passes and the call to \code{compiler-tests}.}
  5357. %
  5358. Run the script to test the complete compiler for \LangVar{} that
  5359. performs register allocation.
  5360. \end{exercise}
  5361. \section{Challenge: Move Biasing}
  5362. \label{sec:move-biasing}
  5363. \index{subject}{move biasing}
  5364. This section describes an enhancement to the register allocator,
  5365. called move biasing, for students who are looking for an extra
  5366. challenge.
  5367. {\if\edition\racketEd
  5368. To motivate the need for move biasing we return to the running example
  5369. but this time use all of the general purpose registers. So we have
  5370. the following mapping of color numbers to registers.
  5371. \[
  5372. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5373. \]
  5374. Using the same assignment of variables to color numbers that was
  5375. produced by the register allocator described in the last section, we
  5376. get the following program.
  5377. \begin{center}
  5378. \begin{minipage}{0.3\textwidth}
  5379. \begin{lstlisting}
  5380. movq $1, v
  5381. movq $42, w
  5382. movq v, x
  5383. addq $7, x
  5384. movq x, y
  5385. movq x, z
  5386. addq w, z
  5387. movq y, t
  5388. negq t
  5389. movq z, %rax
  5390. addq t, %rax
  5391. jmp conclusion
  5392. \end{lstlisting}
  5393. \end{minipage}
  5394. $\Rightarrow\qquad$
  5395. \begin{minipage}{0.45\textwidth}
  5396. \begin{lstlisting}
  5397. movq $1, %rdx
  5398. movq $42, %rcx
  5399. movq %rdx, %rdx
  5400. addq $7, %rdx
  5401. movq %rdx, %rsi
  5402. movq %rdx, %rdx
  5403. addq %rcx, %rdx
  5404. movq %rsi, %rcx
  5405. negq %rcx
  5406. movq %rdx, %rax
  5407. addq %rcx, %rax
  5408. jmp conclusion
  5409. \end{lstlisting}
  5410. \end{minipage}
  5411. \end{center}
  5412. In the above output code there are two \key{movq} instructions that
  5413. can be removed because their source and target are the same. However,
  5414. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5415. register, we could instead remove three \key{movq} instructions. We
  5416. can accomplish this by taking into account which variables appear in
  5417. \key{movq} instructions with which other variables.
  5418. \fi}
  5419. {\if\edition\pythonEd
  5420. %
  5421. To motivate the need for move biasing we return to the running example
  5422. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5423. remove three trivial move instructions from the running
  5424. example. However, we could remove another trivial move if we were able
  5425. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5426. We say that two variables $p$ and $q$ are \emph{move
  5427. related}\index{subject}{move related} if they participate together in
  5428. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5429. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5430. when there are multiple variables with the same saturation, prefer
  5431. variables that can be assigned to a color that is the same as the
  5432. color of a move related variable. Furthermore, when the register
  5433. allocator chooses a color for a variable, it should prefer a color
  5434. that has already been used for a move-related variable (assuming that
  5435. they do not interfere). Of course, this preference should not override
  5436. the preference for registers over stack locations. So this preference
  5437. should be used as a tie breaker when choosing between registers or
  5438. when choosing between stack locations.
  5439. We recommend representing the move relationships in a graph, similar
  5440. to how we represented interference. The following is the \emph{move
  5441. graph} for our running example.
  5442. {\if\edition\racketEd
  5443. \[
  5444. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5445. \node (rax) at (0,0) {$\ttm{rax}$};
  5446. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5447. \node (t) at (0,2) {$\ttm{t}$};
  5448. \node (z) at (3,2) {$\ttm{z}$};
  5449. \node (x) at (6,2) {$\ttm{x}$};
  5450. \node (y) at (3,0) {$\ttm{y}$};
  5451. \node (w) at (6,0) {$\ttm{w}$};
  5452. \node (v) at (9,0) {$\ttm{v}$};
  5453. \draw (v) to (x);
  5454. \draw (x) to (y);
  5455. \draw (x) to (z);
  5456. \draw (y) to (t);
  5457. \end{tikzpicture}
  5458. \]
  5459. \fi}
  5460. %
  5461. {\if\edition\pythonEd
  5462. \[
  5463. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5464. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5465. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5466. \node (z) at (3,2) {$\ttm{z}$};
  5467. \node (x) at (6,2) {$\ttm{x}$};
  5468. \node (y) at (3,0) {$\ttm{y}$};
  5469. \node (w) at (6,0) {$\ttm{w}$};
  5470. \node (v) at (9,0) {$\ttm{v}$};
  5471. \draw (y) to (t0);
  5472. \draw (z) to (x);
  5473. \draw (z) to (t1);
  5474. \draw (x) to (y);
  5475. \draw (x) to (v);
  5476. \end{tikzpicture}
  5477. \]
  5478. \fi}
  5479. {\if\edition\racketEd
  5480. Now we replay the graph coloring, pausing to see the coloring of
  5481. \code{y}. Recall the following configuration. The most saturated vertices
  5482. were \code{w} and \code{y}.
  5483. \[
  5484. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5485. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5486. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5487. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5488. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5489. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5490. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5491. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5492. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5493. \draw (t1) to (rax);
  5494. \draw (t1) to (z);
  5495. \draw (z) to (y);
  5496. \draw (z) to (w);
  5497. \draw (x) to (w);
  5498. \draw (y) to (w);
  5499. \draw (v) to (w);
  5500. \draw (v) to (rsp);
  5501. \draw (w) to (rsp);
  5502. \draw (x) to (rsp);
  5503. \draw (y) to (rsp);
  5504. \path[-.,bend left=15] (z) edge node {} (rsp);
  5505. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5506. \draw (rax) to (rsp);
  5507. \end{tikzpicture}
  5508. \]
  5509. %
  5510. Last time we chose to color \code{w} with $0$. But this time we see
  5511. that \code{w} is not move related to any vertex, but \code{y} is move
  5512. related to \code{t}. So we choose to color \code{y} the same color as
  5513. \code{t}, $0$.
  5514. \[
  5515. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5516. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5517. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5518. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5519. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5520. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5521. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5522. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5523. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5524. \draw (t1) to (rax);
  5525. \draw (t1) to (z);
  5526. \draw (z) to (y);
  5527. \draw (z) to (w);
  5528. \draw (x) to (w);
  5529. \draw (y) to (w);
  5530. \draw (v) to (w);
  5531. \draw (v) to (rsp);
  5532. \draw (w) to (rsp);
  5533. \draw (x) to (rsp);
  5534. \draw (y) to (rsp);
  5535. \path[-.,bend left=15] (z) edge node {} (rsp);
  5536. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5537. \draw (rax) to (rsp);
  5538. \end{tikzpicture}
  5539. \]
  5540. Now \code{w} is the most saturated, so we color it $2$.
  5541. \[
  5542. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5543. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5544. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5545. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5546. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5547. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5548. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5549. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5550. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5551. \draw (t1) to (rax);
  5552. \draw (t1) to (z);
  5553. \draw (z) to (y);
  5554. \draw (z) to (w);
  5555. \draw (x) to (w);
  5556. \draw (y) to (w);
  5557. \draw (v) to (w);
  5558. \draw (v) to (rsp);
  5559. \draw (w) to (rsp);
  5560. \draw (x) to (rsp);
  5561. \draw (y) to (rsp);
  5562. \path[-.,bend left=15] (z) edge node {} (rsp);
  5563. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5564. \draw (rax) to (rsp);
  5565. \end{tikzpicture}
  5566. \]
  5567. At this point, vertices \code{x} and \code{v} are most saturated, but
  5568. \code{x} is move related to \code{y} and \code{z}, so we color
  5569. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5570. \[
  5571. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5572. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5573. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5574. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5575. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5576. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5577. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5578. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5579. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5580. \draw (t1) to (rax);
  5581. \draw (t) to (z);
  5582. \draw (z) to (y);
  5583. \draw (z) to (w);
  5584. \draw (x) to (w);
  5585. \draw (y) to (w);
  5586. \draw (v) to (w);
  5587. \draw (v) to (rsp);
  5588. \draw (w) to (rsp);
  5589. \draw (x) to (rsp);
  5590. \draw (y) to (rsp);
  5591. \path[-.,bend left=15] (z) edge node {} (rsp);
  5592. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5593. \draw (rax) to (rsp);
  5594. \end{tikzpicture}
  5595. \]
  5596. \fi}
  5597. %
  5598. {\if\edition\pythonEd
  5599. Now we replay the graph coloring, pausing before the coloring of
  5600. \code{w}. Recall the following configuration. The most saturated vertices
  5601. were \code{tmp\_1}, \code{w}, and \code{y}.
  5602. \[
  5603. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5604. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5605. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5606. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5607. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5608. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5609. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5610. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5611. \draw (t0) to (t1);
  5612. \draw (t0) to (z);
  5613. \draw (z) to (y);
  5614. \draw (z) to (w);
  5615. \draw (x) to (w);
  5616. \draw (y) to (w);
  5617. \draw (v) to (w);
  5618. \end{tikzpicture}
  5619. \]
  5620. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5621. or \code{y}, but note that \code{w} is not move related to any
  5622. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5623. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5624. \code{y} and color it $0$, we can delete another move instruction.
  5625. \[
  5626. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5627. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5628. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5629. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5630. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5631. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5632. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5633. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5634. \draw (t0) to (t1);
  5635. \draw (t0) to (z);
  5636. \draw (z) to (y);
  5637. \draw (z) to (w);
  5638. \draw (x) to (w);
  5639. \draw (y) to (w);
  5640. \draw (v) to (w);
  5641. \end{tikzpicture}
  5642. \]
  5643. Now \code{w} is the most saturated, so we color it $2$.
  5644. \[
  5645. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5646. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5647. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5648. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5649. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5650. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5651. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5652. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5653. \draw (t0) to (t1);
  5654. \draw (t0) to (z);
  5655. \draw (z) to (y);
  5656. \draw (z) to (w);
  5657. \draw (x) to (w);
  5658. \draw (y) to (w);
  5659. \draw (v) to (w);
  5660. \end{tikzpicture}
  5661. \]
  5662. To finish the coloring, \code{x} and \code{v} get $0$ and
  5663. \code{tmp\_1} gets $1$.
  5664. \[
  5665. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5666. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5667. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5668. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5669. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5670. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5671. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5672. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5673. \draw (t0) to (t1);
  5674. \draw (t0) to (z);
  5675. \draw (z) to (y);
  5676. \draw (z) to (w);
  5677. \draw (x) to (w);
  5678. \draw (y) to (w);
  5679. \draw (v) to (w);
  5680. \end{tikzpicture}
  5681. \]
  5682. \fi}
  5683. So we have the following assignment of variables to registers.
  5684. {\if\edition\racketEd
  5685. \begin{gather*}
  5686. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5687. \ttm{w} \mapsto \key{\%rsi}, \,
  5688. \ttm{x} \mapsto \key{\%rcx}, \,
  5689. \ttm{y} \mapsto \key{\%rcx}, \,
  5690. \ttm{z} \mapsto \key{\%rdx}, \,
  5691. \ttm{t} \mapsto \key{\%rcx} \}
  5692. \end{gather*}
  5693. \fi}
  5694. {\if\edition\pythonEd
  5695. \begin{gather*}
  5696. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5697. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5698. \ttm{x} \mapsto \key{\%rcx}, \,
  5699. \ttm{y} \mapsto \key{\%rcx}, \\
  5700. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5701. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5702. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5703. \end{gather*}
  5704. \fi}
  5705. We apply this register assignment to the running example, on the left,
  5706. to obtain the code in the middle. The \code{patch\_instructions} then
  5707. deletes the trivial moves to obtain the code on the right.
  5708. {\if\edition\racketEd
  5709. \begin{minipage}{0.25\textwidth}
  5710. \begin{lstlisting}
  5711. movq $1, v
  5712. movq $42, w
  5713. movq v, x
  5714. addq $7, x
  5715. movq x, y
  5716. movq x, z
  5717. addq w, z
  5718. movq y, t
  5719. negq t
  5720. movq z, %rax
  5721. addq t, %rax
  5722. jmp conclusion
  5723. \end{lstlisting}
  5724. \end{minipage}
  5725. $\Rightarrow\qquad$
  5726. \begin{minipage}{0.25\textwidth}
  5727. \begin{lstlisting}
  5728. movq $1, %rcx
  5729. movq $42, %rsi
  5730. movq %rcx, %rcx
  5731. addq $7, %rcx
  5732. movq %rcx, %rcx
  5733. movq %rcx, %rdx
  5734. addq %rsi, %rdx
  5735. movq %rcx, %rcx
  5736. negq %rcx
  5737. movq %rdx, %rax
  5738. addq %rcx, %rax
  5739. jmp conclusion
  5740. \end{lstlisting}
  5741. \end{minipage}
  5742. $\Rightarrow\qquad$
  5743. \begin{minipage}{0.25\textwidth}
  5744. \begin{lstlisting}
  5745. movq $1, %rcx
  5746. movq $42, %rsi
  5747. addq $7, %rcx
  5748. movq %rcx, %rdx
  5749. addq %rsi, %rdx
  5750. negq %rcx
  5751. movq %rdx, %rax
  5752. addq %rcx, %rax
  5753. jmp conclusion
  5754. \end{lstlisting}
  5755. \end{minipage}
  5756. \fi}
  5757. {\if\edition\pythonEd
  5758. \begin{minipage}{0.20\textwidth}
  5759. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5760. movq $1, v
  5761. movq $42, w
  5762. movq v, x
  5763. addq $7, x
  5764. movq x, y
  5765. movq x, z
  5766. addq w, z
  5767. movq y, tmp_0
  5768. negq tmp_0
  5769. movq z, tmp_1
  5770. addq tmp_0, tmp_1
  5771. movq tmp_1, %rdi
  5772. callq _print_int
  5773. \end{lstlisting}
  5774. \end{minipage}
  5775. ${\Rightarrow\qquad}$
  5776. \begin{minipage}{0.30\textwidth}
  5777. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5778. movq $1, %rcx
  5779. movq $42, -16(%rbp)
  5780. movq %rcx, %rcx
  5781. addq $7, %rcx
  5782. movq %rcx, %rcx
  5783. movq %rcx, -8(%rbp)
  5784. addq -16(%rbp), -8(%rbp)
  5785. movq %rcx, %rcx
  5786. negq %rcx
  5787. movq -8(%rbp), -8(%rbp)
  5788. addq %rcx, -8(%rbp)
  5789. movq -8(%rbp), %rdi
  5790. callq _print_int
  5791. \end{lstlisting}
  5792. \end{minipage}
  5793. ${\Rightarrow\qquad}$
  5794. \begin{minipage}{0.20\textwidth}
  5795. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5796. movq $1, %rcx
  5797. movq $42, -16(%rbp)
  5798. addq $7, %rcx
  5799. movq %rcx, -8(%rbp)
  5800. movq -16(%rbp), %rax
  5801. addq %rax, -8(%rbp)
  5802. negq %rcx
  5803. addq %rcx, -8(%rbp)
  5804. movq -8(%rbp), %rdi
  5805. callq print_int
  5806. \end{lstlisting}
  5807. \end{minipage}
  5808. \fi}
  5809. \begin{exercise}\normalfont
  5810. Change your implementation of \code{allocate\_registers} to take move
  5811. biasing into account. Create two new tests that include at least one
  5812. opportunity for move biasing and visually inspect the output x86
  5813. programs to make sure that your move biasing is working properly. Make
  5814. sure that your compiler still passes all of the tests.
  5815. \end{exercise}
  5816. %To do: another neat challenge would be to do
  5817. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5818. %% \subsection{Output of the Running Example}
  5819. %% \label{sec:reg-alloc-output}
  5820. % challenge: prioritize variables based on execution frequencies
  5821. % and the number of uses of a variable
  5822. % challenge: enhance the coloring algorithm using Chaitin's
  5823. % approach of prioritizing high-degree variables
  5824. % by removing low-degree variables (coloring them later)
  5825. % from the interference graph
  5826. \section{Further Reading}
  5827. \label{sec:register-allocation-further-reading}
  5828. Early register allocation algorithms were developed for Fortran
  5829. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5830. of graph coloring began in the late 1970s and early 1980s with the
  5831. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5832. algorithm is based on the following observation of
  5833. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5834. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5835. $v$ removed is also $k$ colorable. To see why, suppose that the
  5836. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5837. different colors, but since there are less than $k$ neighbors, there
  5838. will be one or more colors left over to use for coloring $v$ in $G$.
  5839. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5840. less than $k$ from the graph and recursively colors the rest of the
  5841. graph. Upon returning from the recursion, it colors $v$ with one of
  5842. the available colors and returns. \citet{Chaitin:1982vn} augments
  5843. this algorithm to handle spilling as follows. If there are no vertices
  5844. of degree lower than $k$ then pick a vertex at random, spill it,
  5845. remove it from the graph, and proceed recursively to color the rest of
  5846. the graph.
  5847. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5848. move-related and that don't interfere with each other, a process
  5849. called \emph{coalescing}. While coalescing decreases the number of
  5850. moves, it can make the graph more difficult to
  5851. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5852. which two variables are merged only if they have fewer than $k$
  5853. neighbors of high degree. \citet{George:1996aa} observe that
  5854. conservative coalescing is sometimes too conservative and make it more
  5855. aggressive by iterating the coalescing with the removal of low-degree
  5856. vertices.
  5857. %
  5858. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5859. also propose \emph{biased coloring} in which a variable is assigned to
  5860. the same color as another move-related variable if possible, as
  5861. discussed in Section~\ref{sec:move-biasing}.
  5862. %
  5863. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5864. performs coalescing, graph coloring, and spill code insertion until
  5865. all variables have been assigned a location.
  5866. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5867. spills variables that don't have to be: a high-degree variable can be
  5868. colorable if many of its neighbors are assigned the same color.
  5869. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5870. high-degree vertex is not immediately spilled. Instead the decision is
  5871. deferred until after the recursive call, at which point it is apparent
  5872. whether there is actually an available color or not. We observe that
  5873. this algorithm is equivalent to the smallest-last ordering
  5874. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5875. be registers and the rest to be stack locations.
  5876. %% biased coloring
  5877. Earlier editions of the compiler course at Indiana University
  5878. \citep{Dybvig:2010aa} were based on the algorithm of
  5879. \citet{Briggs:1994kx}.
  5880. The smallest-last ordering algorithm is one of many \emph{greedy}
  5881. coloring algorithms. A greedy coloring algorithm visits all the
  5882. vertices in a particular order and assigns each one the first
  5883. available color. An \emph{offline} greedy algorithm chooses the
  5884. ordering up-front, prior to assigning colors. The algorithm of
  5885. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5886. ordering does not depend on the colors assigned. Other orderings are
  5887. possible. For example, \citet{Chow:1984ys} order variables according
  5888. to an estimate of runtime cost.
  5889. An \emph{online} greedy coloring algorithm uses information about the
  5890. current assignment of colors to influence the order in which the
  5891. remaining vertices are colored. The saturation-based algorithm
  5892. described in this chapter is one such algorithm. We choose to use
  5893. saturation-based coloring because it is fun to introduce graph
  5894. coloring via Sudoku!
  5895. A register allocator may choose to map each variable to just one
  5896. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5897. variable to one or more locations. The later can be achieved by
  5898. \emph{live range splitting}, where a variable is replaced by several
  5899. variables that each handle part of its live
  5900. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5901. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5902. %% replacement algorithm, bottom-up local
  5903. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5904. %% Cooper: top-down (priority bassed), bottom-up
  5905. %% top-down
  5906. %% order variables by priority (estimated cost)
  5907. %% caveat: split variables into two groups:
  5908. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5909. %% color the constrained ones first
  5910. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5911. %% cite J. Cocke for an algorithm that colors variables
  5912. %% in a high-degree first ordering
  5913. %Register Allocation via Usage Counts, Freiburghouse CACM
  5914. \citet{Palsberg:2007si} observe that many of the interference graphs
  5915. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5916. that is, every cycle with four or more edges has an edge which is not
  5917. part of the cycle but which connects two vertices on the cycle. Such
  5918. graphs can be optimally colored by the greedy algorithm with a vertex
  5919. ordering determined by maximum cardinality search.
  5920. In situations where compile time is of utmost importance, such as in
  5921. just-in-time compilers, graph coloring algorithms can be too expensive
  5922. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5923. appropriate.
  5924. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5925. \chapter{Booleans and Conditionals}
  5926. \label{ch:Lif}
  5927. \index{subject}{Boolean}
  5928. \index{subject}{control flow}
  5929. \index{subject}{conditional expression}
  5930. The \LangInt{} and \LangVar{} languages only have a single kind of
  5931. value, the integers. In this chapter we add a second kind of value,
  5932. the Booleans, to create the \LangIf{} language. The Boolean values
  5933. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5934. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5935. language includes several operations that involve Booleans (\key{and},
  5936. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5937. \key{if} expression \python{and statement}. With the addition of
  5938. \key{if}, programs can have non-trivial control flow which
  5939. %
  5940. \racket{impacts \code{explicate\_control} and liveness analysis}
  5941. %
  5942. \python{impacts liveness analysis and motivates a new pass named
  5943. \code{explicate\_control}}.
  5944. %
  5945. Also, because we now have two kinds of values, we need to handle
  5946. programs that apply an operation to the wrong kind of value, such as
  5947. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5948. There are two language design options for such situations. One option
  5949. is to signal an error and the other is to provide a wider
  5950. interpretation of the operation. \racket{The Racket
  5951. language}\python{Python} uses a mixture of these two options,
  5952. depending on the operation and the kind of value. For example, the
  5953. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5954. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5955. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5956. %
  5957. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5958. in Racket because \code{car} expects a pair.}
  5959. %
  5960. \python{On the other hand, \code{1[0]} results in a run-time error
  5961. in Python because an ``\code{int} object is not subscriptable''.}
  5962. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5963. design choices as \racket{Racket}\python{Python}, except much of the
  5964. error detection happens at compile time instead of run
  5965. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5966. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5967. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5968. Racket}\python{MyPy} reports a compile-time error
  5969. %
  5970. \racket{because Racket expects the type of the argument to be of the form
  5971. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5972. %
  5973. \python{stating that a ``value of type \code{int} is not indexable''.}
  5974. The \LangIf{} language performs type checking during compilation like
  5975. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study the
  5976. alternative choice, that is, a dynamically typed language like
  5977. \racket{Racket}\python{Python}.
  5978. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5979. for some operations we are more restrictive, for example, rejecting
  5980. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5981. This chapter is organized as follows. We begin by defining the syntax
  5982. and interpreter for the \LangIf{} language
  5983. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5984. checking and define a type checker for \LangIf{}
  5985. (Section~\ref{sec:type-check-Lif}).
  5986. %
  5987. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5988. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5989. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5990. %
  5991. The remaining sections of this chapter discuss how the addition of
  5992. Booleans and conditional control flow to the language requires changes
  5993. to the existing compiler passes and the addition of new ones. In
  5994. particular, we introduce the \code{shrink} pass to translates some
  5995. operators into others, thereby reducing the number of operators that
  5996. need to be handled in later passes.
  5997. %
  5998. The main event of this chapter is the \code{explicate\_control} pass
  5999. that is responsible for translating \code{if}'s into conditional
  6000. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  6001. %
  6002. Regarding register allocation, there is the interesting question of
  6003. how to handle conditional \code{goto}'s during liveness analysis.
  6004. \section{The \LangIf{} Language}
  6005. \label{sec:lang-if}
  6006. The concrete and abstract syntax of the \LangIf{} language are defined in
  6007. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6008. respectively. The \LangIf{} language includes all of
  6009. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6010. \FALSE{},\racket{ and} the \code{if} expression\python{, and the
  6011. \code{if} statement}. We expand the set of operators to include
  6012. \begin{enumerate}
  6013. \item subtraction on integers,
  6014. \item the logical operators \key{and}, \key{or}, and \key{not},
  6015. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6016. for comparing integers or Booleans for equality, and
  6017. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6018. comparing integers.
  6019. \end{enumerate}
  6020. \racket{We reorganize the abstract syntax for the primitive
  6021. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  6022. rule for all of them. This means that the grammar no longer checks
  6023. whether the arity of an operators matches the number of
  6024. arguments. That responsibility is moved to the type checker for
  6025. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  6026. \newcommand{\LifGrammarRacket}{
  6027. \begin{array}{lcl}
  6028. \Type &::=& \key{Boolean} \\
  6029. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6030. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6031. \Exp &::=& \CSUB{\Exp}{\Exp} \MID \itm{bool}
  6032. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6033. \MID (\key{not}\;\Exp) \\
  6034. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6035. \end{array}
  6036. }
  6037. \newcommand{\LifASTRacket}{
  6038. \begin{array}{lcl}
  6039. \Type &::=& \key{Boolean} \\
  6040. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6041. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6042. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6043. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6044. \end{array}
  6045. }
  6046. \newcommand{\LintOpAST}{
  6047. \begin{array}{rcl}
  6048. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6049. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6050. \end{array}
  6051. }
  6052. \newcommand{\LifGrammarPython}{
  6053. \begin{array}{rcl}
  6054. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6055. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6056. \MID \key{not}~\Exp \\
  6057. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6058. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6059. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6060. \end{array}
  6061. }
  6062. \newcommand{\LifASTPython}{
  6063. \begin{array}{lcl}
  6064. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6065. \itm{unaryop} &::=& \code{Not()} \\
  6066. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6067. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6068. \Exp &::=& \BOOL{\itm{bool}}
  6069. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6070. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6071. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6072. \end{array}
  6073. }
  6074. \begin{figure}[tp]
  6075. \centering
  6076. \fbox{
  6077. \begin{minipage}{0.96\textwidth}
  6078. {\if\edition\racketEd
  6079. \[
  6080. \begin{array}{l}
  6081. \gray{\LintGrammarRacket{}} \\ \hline
  6082. \gray{\LvarGrammarRacket{}} \\ \hline
  6083. \LifGrammarRacket{} \\
  6084. \begin{array}{lcl}
  6085. \LangIfM{} &::=& \Exp
  6086. \end{array}
  6087. \end{array}
  6088. \]
  6089. \fi}
  6090. {\if\edition\pythonEd
  6091. \[
  6092. \begin{array}{l}
  6093. \gray{\LintGrammarPython} \\ \hline
  6094. \gray{\LvarGrammarPython} \\ \hline
  6095. \LifGrammarPython \\
  6096. \begin{array}{rcl}
  6097. \LangIfM{} &::=& \Stmt^{*}
  6098. \end{array}
  6099. \end{array}
  6100. \]
  6101. \fi}
  6102. \end{minipage}
  6103. }
  6104. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6105. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6106. \label{fig:Lif-concrete-syntax}
  6107. \end{figure}
  6108. \begin{figure}[tp]
  6109. \centering
  6110. \fbox{
  6111. \begin{minipage}{0.96\textwidth}
  6112. {\if\edition\racketEd
  6113. \[
  6114. \begin{array}{l}
  6115. \gray{\LintOpAST} \\ \hline
  6116. \gray{\LvarASTRacket{}} \\ \hline
  6117. \LifASTRacket{} \\
  6118. \begin{array}{lcl}
  6119. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6120. \end{array}
  6121. \end{array}
  6122. \]
  6123. \fi}
  6124. {\if\edition\pythonEd
  6125. \[
  6126. \begin{array}{l}
  6127. \gray{\LintASTPython} \\ \hline
  6128. \gray{\LvarASTPython} \\ \hline
  6129. \LifASTPython \\
  6130. \begin{array}{lcl}
  6131. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6132. \end{array}
  6133. \end{array}
  6134. \]
  6135. \fi}
  6136. \end{minipage}
  6137. }
  6138. \caption{The abstract syntax of \LangIf{}.}
  6139. \label{fig:Lif-syntax}
  6140. \end{figure}
  6141. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6142. which inherits from the interpreter for \LangVar{}
  6143. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6144. evaluate to the corresponding Boolean values. The conditional
  6145. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6146. and then either evaluates $e_2$ or $e_3$ depending on whether
  6147. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6148. \code{and}, \code{or}, and \code{not} behave according to
  6149. propositional logic. In addition, the \code{and} and \code{or}
  6150. operations perform \emph{short-circuit evaluation}.
  6151. %
  6152. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6153. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6154. %
  6155. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6156. evaluated if $e_1$ evaluates to \TRUE{}.
  6157. \racket{With the increase in the number of primitive operations, the
  6158. interpreter would become repetitive without some care. We refactor
  6159. the case for \code{Prim}, moving the code that differs with each
  6160. operation into the \code{interp\_op} method shown in in
  6161. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6162. \code{or} operations separately because of their short-circuiting
  6163. behavior.}
  6164. \begin{figure}[tbp]
  6165. {\if\edition\racketEd
  6166. \begin{lstlisting}
  6167. (define interp_Lif_class
  6168. (class interp_Lvar_class
  6169. (super-new)
  6170. (define/public (interp_op op) ...)
  6171. (define/override ((interp_exp env) e)
  6172. (define recur (interp_exp env))
  6173. (match e
  6174. [(Bool b) b]
  6175. [(If cnd thn els)
  6176. (match (recur cnd)
  6177. [#t (recur thn)]
  6178. [#f (recur els)])]
  6179. [(Prim 'and (list e1 e2))
  6180. (match (recur e1)
  6181. [#t (match (recur e2) [#t #t] [#f #f])]
  6182. [#f #f])]
  6183. [(Prim 'or (list e1 e2))
  6184. (define v1 (recur e1))
  6185. (match v1
  6186. [#t #t]
  6187. [#f (match (recur e2) [#t #t] [#f #f])])]
  6188. [(Prim op args)
  6189. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6190. [else ((super interp_exp env) e)]))
  6191. ))
  6192. (define (interp_Lif p)
  6193. (send (new interp_Lif_class) interp_program p))
  6194. \end{lstlisting}
  6195. \fi}
  6196. {\if\edition\pythonEd
  6197. \begin{lstlisting}
  6198. class InterpLif(InterpLvar):
  6199. def interp_exp(self, e, env):
  6200. match e:
  6201. case IfExp(test, body, orelse):
  6202. if self.interp_exp(test, env):
  6203. return self.interp_exp(body, env)
  6204. else:
  6205. return self.interp_exp(orelse, env)
  6206. case BinOp(left, Sub(), right):
  6207. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6208. case UnaryOp(Not(), v):
  6209. return not self.interp_exp(v, env)
  6210. case BoolOp(And(), values):
  6211. if self.interp_exp(values[0], env):
  6212. return self.interp_exp(values[1], env)
  6213. else:
  6214. return False
  6215. case BoolOp(Or(), values):
  6216. if self.interp_exp(values[0], env):
  6217. return True
  6218. else:
  6219. return self.interp_exp(values[1], env)
  6220. case Compare(left, [cmp], [right]):
  6221. l = self.interp_exp(left, env)
  6222. r = self.interp_exp(right, env)
  6223. return self.interp_cmp(cmp)(l, r)
  6224. case _:
  6225. return super().interp_exp(e, env)
  6226. def interp_stmts(self, ss, env):
  6227. if len(ss) == 0:
  6228. return
  6229. match ss[0]:
  6230. case If(test, body, orelse):
  6231. if self.interp_exp(test, env):
  6232. return self.interp_stmts(body + ss[1:], env)
  6233. else:
  6234. return self.interp_stmts(orelse + ss[1:], env)
  6235. case _:
  6236. return super().interp_stmts(ss, env)
  6237. ...
  6238. \end{lstlisting}
  6239. \fi}
  6240. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6241. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6242. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6243. \label{fig:interp-Lif}
  6244. \end{figure}
  6245. {\if\edition\racketEd
  6246. \begin{figure}[tbp]
  6247. \begin{lstlisting}
  6248. (define/public (interp_op op)
  6249. (match op
  6250. ['+ fx+]
  6251. ['- fx-]
  6252. ['read read-fixnum]
  6253. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6254. ['eq? (lambda (v1 v2)
  6255. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6256. (and (boolean? v1) (boolean? v2))
  6257. (and (vector? v1) (vector? v2)))
  6258. (eq? v1 v2)]))]
  6259. ['< (lambda (v1 v2)
  6260. (cond [(and (fixnum? v1) (fixnum? v2))
  6261. (< v1 v2)]))]
  6262. ['<= (lambda (v1 v2)
  6263. (cond [(and (fixnum? v1) (fixnum? v2))
  6264. (<= v1 v2)]))]
  6265. ['> (lambda (v1 v2)
  6266. (cond [(and (fixnum? v1) (fixnum? v2))
  6267. (> v1 v2)]))]
  6268. ['>= (lambda (v1 v2)
  6269. (cond [(and (fixnum? v1) (fixnum? v2))
  6270. (>= v1 v2)]))]
  6271. [else (error 'interp_op "unknown operator")]))
  6272. \end{lstlisting}
  6273. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6274. \label{fig:interp-op-Lif}
  6275. \end{figure}
  6276. \fi}
  6277. {\if\edition\pythonEd
  6278. \begin{figure}
  6279. \begin{lstlisting}
  6280. class InterpLif(InterpLvar):
  6281. ...
  6282. def interp_cmp(self, cmp):
  6283. match cmp:
  6284. case Lt():
  6285. return lambda x, y: x < y
  6286. case LtE():
  6287. return lambda x, y: x <= y
  6288. case Gt():
  6289. return lambda x, y: x > y
  6290. case GtE():
  6291. return lambda x, y: x >= y
  6292. case Eq():
  6293. return lambda x, y: x == y
  6294. case NotEq():
  6295. return lambda x, y: x != y
  6296. \end{lstlisting}
  6297. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6298. \label{fig:interp-cmp-Lif}
  6299. \end{figure}
  6300. \fi}
  6301. \section{Type Checking \LangIf{} Programs}
  6302. \label{sec:type-check-Lif}
  6303. \index{subject}{type checking}
  6304. \index{subject}{semantic analysis}
  6305. It is helpful to think about type checking in two complementary
  6306. ways. A type checker predicts the type of value that will be produced
  6307. by each expression in the program. For \LangIf{}, we have just two types,
  6308. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6309. {\if\edition\racketEd
  6310. \begin{lstlisting}
  6311. (+ 10 (- (+ 12 20)))
  6312. \end{lstlisting}
  6313. \fi}
  6314. {\if\edition\pythonEd
  6315. \begin{lstlisting}
  6316. 10 + -(12 + 20)
  6317. \end{lstlisting}
  6318. \fi}
  6319. \noindent produces a value of type \INTTY{} while
  6320. {\if\edition\racketEd
  6321. \begin{lstlisting}
  6322. (and (not #f) #t)
  6323. \end{lstlisting}
  6324. \fi}
  6325. {\if\edition\pythonEd
  6326. \begin{lstlisting}
  6327. (not False) and True
  6328. \end{lstlisting}
  6329. \fi}
  6330. \noindent produces a value of type \BOOLTY{}.
  6331. A second way to think about type checking is that it enforces a set of
  6332. rules about which operators can be applied to which kinds of
  6333. values. For example, our type checker for \LangIf{} signals an error
  6334. for the below expression {\if\edition\racketEd
  6335. \begin{lstlisting}
  6336. (not (+ 10 (- (+ 12 20))))
  6337. \end{lstlisting}
  6338. \fi}
  6339. {\if\edition\pythonEd
  6340. \begin{lstlisting}
  6341. not (10 + -(12 + 20))
  6342. \end{lstlisting}
  6343. \fi}
  6344. The subexpression
  6345. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6346. has type \INTTY{} but the type checker enforces the rule that the argument of
  6347. \code{not} must be an expression of type \BOOLTY{}.
  6348. We implement type checking using classes and methods because they
  6349. provide the open recursion needed to reuse code as we extend the type
  6350. checker in later chapters, analogous to the use of classes and methods
  6351. for the interpreters (Section~\ref{sec:extensible-interp}).
  6352. We separate the type checker for the \LangVar{} subset into its own
  6353. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6354. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6355. from the type checker for \LangVar{}. These type checkers are in the
  6356. files
  6357. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6358. and
  6359. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6360. of the support code.
  6361. %
  6362. Each type checker is a structurally recursive function over the AST.
  6363. Given an input expression \code{e}, the type checker either signals an
  6364. error or returns \racket{an expression and} its type (\INTTY{} or
  6365. \BOOLTY{}).
  6366. %
  6367. \racket{It returns an expression because there are situations in which
  6368. we want to change or update the expression.}
  6369. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6370. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6371. \INTTY{}. To handle variables, the type checker uses the environment
  6372. \code{env} to map variables to types.
  6373. %
  6374. \racket{Consider the case for \key{let}. We type check the
  6375. initializing expression to obtain its type \key{T} and then
  6376. associate type \code{T} with the variable \code{x} in the
  6377. environment used to type check the body of the \key{let}. Thus,
  6378. when the type checker encounters a use of variable \code{x}, it can
  6379. find its type in the environment.}
  6380. %
  6381. \python{Consider the case for assignment. We type check the
  6382. initializing expression to obtain its type \key{t}. If the variable
  6383. \code{lhs.id} is already in the environment because there was a
  6384. prior assignment, we check that this initializer has the same type
  6385. as the prior one. If this is the first assignment to the variable,
  6386. we associate type \code{t} with the variable \code{lhs.id} in the
  6387. environment. Thus, when the type checker encounters a use of
  6388. variable \code{x}, it can find its type in the environment.}
  6389. %
  6390. \racket{Regarding primitive operators, we recursively analyze the
  6391. arguments and then invoke \code{type\_check\_op} to check whether
  6392. the argument types are allowed.}
  6393. %
  6394. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6395. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6396. \racket{Several auxiliary methods are used in the type checker. The
  6397. method \code{operator-types} defines a dictionary that maps the
  6398. operator names to their parameter and return types. The
  6399. \code{type-equal?} method determines whether two types are equal,
  6400. which for now simply dispatches to \code{equal?} (deep
  6401. equality). The \code{check-type-equal?} method triggers an error if
  6402. the two types are not equal. The \code{type-check-op} method looks
  6403. up the operator in the \code{operator-types} dictionary and then
  6404. checks whether the argument types are equal to the parameter types.
  6405. The result is the return type of the operator.}
  6406. %
  6407. \python{The auxiliary method \code{check\_type\_equal} triggers
  6408. an error if the two types are not equal.}
  6409. \begin{figure}[tbp]
  6410. {\if\edition\racketEd
  6411. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6412. (define type-check-Lvar_class
  6413. (class object%
  6414. (super-new)
  6415. (define/public (operator-types)
  6416. '((+ . ((Integer Integer) . Integer))
  6417. (- . ((Integer) . Integer))
  6418. (read . (() . Integer))))
  6419. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6420. (define/public (check-type-equal? t1 t2 e)
  6421. (unless (type-equal? t1 t2)
  6422. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6423. (define/public (type-check-op op arg-types e)
  6424. (match (dict-ref (operator-types) op)
  6425. [`(,param-types . ,return-type)
  6426. (for ([at arg-types] [pt param-types])
  6427. (check-type-equal? at pt e))
  6428. return-type]
  6429. [else (error 'type-check-op "unrecognized ~a" op)]))
  6430. (define/public (type-check-exp env)
  6431. (lambda (e)
  6432. (match e
  6433. [(Int n) (values (Int n) 'Integer)]
  6434. [(Var x) (values (Var x) (dict-ref env x))]
  6435. [(Let x e body)
  6436. (define-values (e^ Te) ((type-check-exp env) e))
  6437. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6438. (values (Let x e^ b) Tb)]
  6439. [(Prim op es)
  6440. (define-values (new-es ts)
  6441. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6442. (values (Prim op new-es) (type-check-op op ts e))]
  6443. [else (error 'type-check-exp "couldn't match" e)])))
  6444. (define/public (type-check-program e)
  6445. (match e
  6446. [(Program info body)
  6447. (define-values (body^ Tb) ((type-check-exp '()) body))
  6448. (check-type-equal? Tb 'Integer body)
  6449. (Program info body^)]
  6450. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6451. ))
  6452. (define (type-check-Lvar p)
  6453. (send (new type-check-Lvar_class) type-check-program p))
  6454. \end{lstlisting}
  6455. \fi}
  6456. {\if\edition\pythonEd
  6457. \begin{lstlisting}[escapechar=`]
  6458. class TypeCheckLvar:
  6459. def check_type_equal(self, t1, t2, e):
  6460. if t1 != t2:
  6461. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6462. raise Exception(msg)
  6463. def type_check_exp(self, e, env):
  6464. match e:
  6465. case BinOp(left, (Add() | Sub()), right):
  6466. l = self.type_check_exp(left, env)
  6467. check_type_equal(l, int, left)
  6468. r = self.type_check_exp(right, env)
  6469. check_type_equal(r, int, right)
  6470. return int
  6471. case UnaryOp(USub(), v):
  6472. t = self.type_check_exp(v, env)
  6473. check_type_equal(t, int, v)
  6474. return int
  6475. case Name(id):
  6476. return env[id]
  6477. case Constant(value) if isinstance(value, int):
  6478. return int
  6479. case Call(Name('input_int'), []):
  6480. return int
  6481. def type_check_stmts(self, ss, env):
  6482. if len(ss) == 0:
  6483. return
  6484. match ss[0]:
  6485. case Assign([lhs], value):
  6486. t = self.type_check_exp(value, env)
  6487. if lhs.id in env:
  6488. check_type_equal(env[lhs.id], t, value)
  6489. else:
  6490. env[lhs.id] = t
  6491. return self.type_check_stmts(ss[1:], env)
  6492. case Expr(Call(Name('print'), [arg])):
  6493. t = self.type_check_exp(arg, env)
  6494. check_type_equal(t, int, arg)
  6495. return self.type_check_stmts(ss[1:], env)
  6496. case Expr(value):
  6497. self.type_check_exp(value, env)
  6498. return self.type_check_stmts(ss[1:], env)
  6499. def type_check_P(self, p):
  6500. match p:
  6501. case Module(body):
  6502. self.type_check_stmts(body, {})
  6503. \end{lstlisting}
  6504. \fi}
  6505. \caption{Type checker for the \LangVar{} language.}
  6506. \label{fig:type-check-Lvar}
  6507. \end{figure}
  6508. \begin{figure}[tbp]
  6509. {\if\edition\racketEd
  6510. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6511. (define type-check-Lif_class
  6512. (class type-check-Lvar_class
  6513. (super-new)
  6514. (inherit check-type-equal?)
  6515. (define/override (operator-types)
  6516. (append '((- . ((Integer Integer) . Integer))
  6517. (and . ((Boolean Boolean) . Boolean))
  6518. (or . ((Boolean Boolean) . Boolean))
  6519. (< . ((Integer Integer) . Boolean))
  6520. (<= . ((Integer Integer) . Boolean))
  6521. (> . ((Integer Integer) . Boolean))
  6522. (>= . ((Integer Integer) . Boolean))
  6523. (not . ((Boolean) . Boolean))
  6524. )
  6525. (super operator-types)))
  6526. (define/override (type-check-exp env)
  6527. (lambda (e)
  6528. (match e
  6529. [(Bool b) (values (Bool b) 'Boolean)]
  6530. [(Prim 'eq? (list e1 e2))
  6531. (define-values (e1^ T1) ((type-check-exp env) e1))
  6532. (define-values (e2^ T2) ((type-check-exp env) e2))
  6533. (check-type-equal? T1 T2 e)
  6534. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6535. [(If cnd thn els)
  6536. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6537. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6538. (define-values (els^ Te) ((type-check-exp env) els))
  6539. (check-type-equal? Tc 'Boolean e)
  6540. (check-type-equal? Tt Te e)
  6541. (values (If cnd^ thn^ els^) Te)]
  6542. [else ((super type-check-exp env) e)])))
  6543. ))
  6544. (define (type-check-Lif p)
  6545. (send (new type-check-Lif_class) type-check-program p))
  6546. \end{lstlisting}
  6547. \fi}
  6548. {\if\edition\pythonEd
  6549. \begin{lstlisting}
  6550. class TypeCheckLif(TypeCheckLvar):
  6551. def type_check_exp(self, e, env):
  6552. match e:
  6553. case Constant(value) if isinstance(value, bool):
  6554. return bool
  6555. case BinOp(left, Sub(), right):
  6556. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6557. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6558. return int
  6559. case UnaryOp(Not(), v):
  6560. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6561. return bool
  6562. case BoolOp(op, values):
  6563. left = values[0] ; right = values[1]
  6564. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6565. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6566. return bool
  6567. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6568. or isinstance(cmp, NotEq):
  6569. l = self.type_check_exp(left, env)
  6570. r = self.type_check_exp(right, env)
  6571. check_type_equal(l, r, e)
  6572. return bool
  6573. case Compare(left, [cmp], [right]):
  6574. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6575. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6576. return bool
  6577. case IfExp(test, body, orelse):
  6578. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6579. b = self.type_check_exp(body, env)
  6580. o = self.type_check_exp(orelse, env)
  6581. check_type_equal(b, o, e)
  6582. return b
  6583. case _:
  6584. return super().type_check_exp(e, env)
  6585. def type_check_stmts(self, ss, env):
  6586. if len(ss) == 0:
  6587. return
  6588. match ss[0]:
  6589. case If(test, body, orelse):
  6590. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6591. b = self.type_check_stmts(body, env)
  6592. o = self.type_check_stmts(orelse, env)
  6593. check_type_equal(b, o, ss[0])
  6594. return self.type_check_stmts(ss[1:], env)
  6595. case _:
  6596. return super().type_check_stmts(ss, env)
  6597. \end{lstlisting}
  6598. \fi}
  6599. \caption{Type checker for the \LangIf{} language.}
  6600. \label{fig:type-check-Lif}
  6601. \end{figure}
  6602. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6603. checker for \LangIf{}.
  6604. %
  6605. The type of a Boolean constant is \BOOLTY{}.
  6606. %
  6607. \racket{The \code{operator-types} function adds dictionary entries for
  6608. the other new operators.}
  6609. %
  6610. \python{Logical not requires its argument to be a \BOOLTY{} and
  6611. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6612. %
  6613. The equality operators require the two arguments to have the same
  6614. type.
  6615. %
  6616. \python{The other comparisons (less-than, etc.) require their
  6617. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6618. %
  6619. The condition of an \code{if} must
  6620. be of \BOOLTY{} type and the two branches must have the same type.
  6621. \begin{exercise}\normalfont
  6622. Create 10 new test programs in \LangIf{}. Half of the programs should
  6623. have a type error. For those programs, create an empty file with the
  6624. same base name but with file extension \code{.tyerr}. For example, if
  6625. the test
  6626. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6627. is expected to error, then create
  6628. an empty file named \code{cond\_test\_14.tyerr}.
  6629. %
  6630. \racket{This indicates to \code{interp-tests} and
  6631. \code{compiler-tests} that a type error is expected. }
  6632. %
  6633. The other half of the test programs should not have type errors.
  6634. %
  6635. \racket{In the \code{run-tests.rkt} script, change the second argument
  6636. of \code{interp-tests} and \code{compiler-tests} to
  6637. \code{type-check-Lif}, which causes the type checker to run prior to
  6638. the compiler passes. Temporarily change the \code{passes} to an
  6639. empty list and run the script, thereby checking that the new test
  6640. programs either type check or not as intended.}
  6641. %
  6642. Run the test script to check that these test programs type check as
  6643. expected.
  6644. \end{exercise}
  6645. \clearpage
  6646. \section{The \LangCIf{} Intermediate Language}
  6647. \label{sec:Cif}
  6648. {\if\edition\racketEd
  6649. %
  6650. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6651. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6652. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6653. language adds logical and comparison operators to the \Exp{}
  6654. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6655. non-terminal.
  6656. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6657. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6658. statement is a comparison operation and the branches are \code{goto}
  6659. statements, making it straightforward to compile \code{if} statements
  6660. to x86.
  6661. %
  6662. \fi}
  6663. %
  6664. {\if\edition\pythonEd
  6665. %
  6666. The output of \key{explicate\_control} is a language similar to the
  6667. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6668. \code{goto} statements, so we name it \LangCIf{}. The
  6669. concrete syntax for \LangCIf{} is defined in
  6670. Figure~\ref{fig:c1-concrete-syntax}
  6671. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6672. %
  6673. The \LangCIf{} language supports the same operators as \LangIf{} but
  6674. the arguments of operators are restricted to atomic expressions. The
  6675. \LangCIf{} language does not include \code{if} expressions but it does
  6676. include a restricted form of \code{if} statment. The condition must be
  6677. a comparison and the two branches may only contain \code{goto}
  6678. statements. These restrictions make it easier to translate \code{if}
  6679. statements to x86.
  6680. %
  6681. \fi}
  6682. %
  6683. Besides the \code{goto} statement, \LangCIf{}, also adds a
  6684. \code{return} statement to finish a function call with a specified value.
  6685. %
  6686. The \key{CProgram} construct contains
  6687. %
  6688. \racket{an alist}\python{a dictionary}
  6689. %
  6690. mapping labels to
  6691. \racket{$\Tail$ expressions, which can be \code{return} statements,
  6692. an assignment statement followed by a $\Tail$ expression, a
  6693. \code{goto}, or a conditional \code{goto}.}
  6694. \python{lists of statements, which comprise of assignment statements
  6695. and end in a \code{return} statement, a \code{goto}, or a
  6696. conditional \code{goto}.
  6697. \index{subject}{basic block}
  6698. Statement lists of this form are called
  6699. \emph{basic blocks}: there is a control transfer at the end and
  6700. control only enters at the beginning of the list, which is marked by
  6701. the label. }
  6702. \newcommand{\CifGrammarRacket}{
  6703. \begin{array}{lcl}
  6704. \Atm &::=& \itm{bool} \\
  6705. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6706. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6707. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6708. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6709. \end{array}
  6710. }
  6711. \newcommand{\CifASTRacket}{
  6712. \begin{array}{lcl}
  6713. \Atm &::=& \BOOL{\itm{bool}} \\
  6714. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6715. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6716. \Tail &::= & \GOTO{\itm{label}} \\
  6717. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6718. \end{array}
  6719. }
  6720. \newcommand{\CifGrammarPython}{
  6721. \begin{array}{lcl}
  6722. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6723. \Exp &::= & \Atm \MID \CREAD{}
  6724. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6725. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6726. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6727. \Stmt &::=& \CPRINT{\Exp} \MID \Exp \\
  6728. &\MID& \CASSIGN{\Var}{\Exp}
  6729. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6730. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6731. \end{array}
  6732. }
  6733. \newcommand{\CifASTPython}{
  6734. \begin{array}{lcl}
  6735. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6736. \Exp &::= & \Atm \MID \READ{} \\
  6737. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6738. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6739. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6740. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6741. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6742. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6743. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6744. \end{array}
  6745. }
  6746. \begin{figure}[tbp]
  6747. \fbox{
  6748. \begin{minipage}{0.96\textwidth}
  6749. \small
  6750. {\if\edition\racketEd
  6751. \[
  6752. \begin{array}{l}
  6753. \gray{\CvarGrammarRacket} \\ \hline
  6754. \CifGrammarRacket \\
  6755. \begin{array}{lcl}
  6756. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6757. \end{array}
  6758. \end{array}
  6759. \]
  6760. \fi}
  6761. {\if\edition\pythonEd
  6762. \[
  6763. \begin{array}{l}
  6764. \CifGrammarPython \\
  6765. \begin{array}{lcl}
  6766. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6767. \end{array}
  6768. \end{array}
  6769. \]
  6770. \fi}
  6771. \end{minipage}
  6772. }
  6773. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6774. \label{fig:c1-concrete-syntax}
  6775. \end{figure}
  6776. \begin{figure}[tp]
  6777. \fbox{
  6778. \begin{minipage}{0.96\textwidth}
  6779. \small
  6780. {\if\edition\racketEd
  6781. \[
  6782. \begin{array}{l}
  6783. \gray{\CvarASTRacket} \\ \hline
  6784. \CifASTRacket \\
  6785. \begin{array}{lcl}
  6786. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6787. \end{array}
  6788. \end{array}
  6789. \]
  6790. \fi}
  6791. {\if\edition\pythonEd
  6792. \[
  6793. \begin{array}{l}
  6794. \CifASTPython \\
  6795. \begin{array}{lcl}
  6796. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6797. \end{array}
  6798. \end{array}
  6799. \]
  6800. \fi}
  6801. \end{minipage}
  6802. }
  6803. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6804. (Figure~\ref{fig:c0-syntax})}.}
  6805. \label{fig:c1-syntax}
  6806. \end{figure}
  6807. \section{The \LangXIf{} Language}
  6808. \label{sec:x86-if}
  6809. \index{subject}{x86} To implement the new logical operations, the comparison
  6810. operations, and the \key{if} expression\python{ and statement}, we need to delve further into
  6811. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6812. define the concrete and abstract syntax for the \LangXIf{} subset
  6813. of x86, which includes instructions for logical operations,
  6814. comparisons, and \racket{conditional} jumps.
  6815. One challenge is that x86 does not provide an instruction that
  6816. directly implements logical negation (\code{not} in \LangIf{} and
  6817. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6818. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6819. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6820. bit of its arguments, and writes the results into its second argument.
  6821. Recall the truth table for exclusive-or:
  6822. \begin{center}
  6823. \begin{tabular}{l|cc}
  6824. & 0 & 1 \\ \hline
  6825. 0 & 0 & 1 \\
  6826. 1 & 1 & 0
  6827. \end{tabular}
  6828. \end{center}
  6829. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6830. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6831. for the bit $1$, the result is the opposite of the second bit. Thus,
  6832. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6833. the first argument as follows, where $\Arg$ is the translation of
  6834. $\Atm$.
  6835. \[
  6836. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6837. \qquad\Rightarrow\qquad
  6838. \begin{array}{l}
  6839. \key{movq}~ \Arg\key{,} \Var\\
  6840. \key{xorq}~ \key{\$1,} \Var
  6841. \end{array}
  6842. \]
  6843. \begin{figure}[tp]
  6844. \fbox{
  6845. \begin{minipage}{0.96\textwidth}
  6846. \[
  6847. \begin{array}{lcl}
  6848. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6849. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6850. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6851. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6852. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6853. \key{subq} \; \Arg\key{,} \Arg \MID
  6854. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6855. && \gray{ \key{callq} \; \itm{label} \MID
  6856. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6857. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6858. \MID \key{xorq}~\Arg\key{,}~\Arg
  6859. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6860. && \key{set}cc~\Arg
  6861. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6862. \MID \key{j}cc~\itm{label}
  6863. \\
  6864. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6865. & & \gray{ \key{main:} \; \Instr\ldots }
  6866. \end{array}
  6867. \]
  6868. \end{minipage}
  6869. }
  6870. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6871. \label{fig:x86-1-concrete}
  6872. \end{figure}
  6873. \begin{figure}[tp]
  6874. \fbox{
  6875. \begin{minipage}{0.98\textwidth}
  6876. \small
  6877. {\if\edition\racketEd
  6878. \[
  6879. \begin{array}{lcl}
  6880. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6881. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6882. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6883. \MID \BYTEREG{\itm{bytereg}} \\
  6884. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6885. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6886. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6887. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6888. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6889. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6890. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6891. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6892. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6893. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6894. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6895. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6896. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6897. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6898. \end{array}
  6899. \]
  6900. \fi}
  6901. %
  6902. {\if\edition\pythonEd
  6903. \[
  6904. \begin{array}{lcl}
  6905. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  6906. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  6907. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6908. \MID \BYTEREG{\itm{bytereg}} \\
  6909. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  6910. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  6911. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  6912. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  6913. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  6914. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6915. \MID \PUSHQ{\Arg}} \\
  6916. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6917. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  6918. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  6919. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  6920. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  6921. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  6922. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6923. \end{array}
  6924. \]
  6925. \fi}
  6926. \end{minipage}
  6927. }
  6928. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6929. \label{fig:x86-1}
  6930. \end{figure}
  6931. Next we consider the x86 instructions that are relevant for compiling
  6932. the comparison operations. The \key{cmpq} instruction compares its two
  6933. arguments to determine whether one argument is less than, equal, or
  6934. greater than the other argument. The \key{cmpq} instruction is unusual
  6935. regarding the order of its arguments and where the result is
  6936. placed. The argument order is backwards: if you want to test whether
  6937. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6938. \key{cmpq} is placed in the special EFLAGS register. This register
  6939. cannot be accessed directly but it can be queried by a number of
  6940. instructions, including the \key{set} instruction. The instruction
  6941. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6942. depending on whether the comparison comes out according to the
  6943. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6944. for less-or-equal, \key{g} for greater, \key{ge} for
  6945. greater-or-equal). The \key{set} instruction has a quirk in
  6946. that its destination argument must be single byte register, such as
  6947. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6948. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6949. instruction can be used to move from a single byte register to a
  6950. normal 64-bit register. The abstract syntax for the \code{set}
  6951. instruction differs from the concrete syntax in that it separates the
  6952. instruction name from the condition code.
  6953. \python{The x86 instructions for jumping are relevant to the
  6954. compilation of \key{if} expressions.}
  6955. %
  6956. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6957. counter to the address of the instruction after the specified
  6958. label.}
  6959. %
  6960. \racket{The x86 instruction for conditional jump is relevant to the
  6961. compilation of \key{if} expressions.}
  6962. %
  6963. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6964. counter to point to the instruction after \itm{label} depending on
  6965. whether the result in the EFLAGS register matches the condition code
  6966. \itm{cc}, otherwise the jump instruction falls through to the next
  6967. instruction. Like the abstract syntax for \code{set}, the abstract
  6968. syntax for conditional jump separates the instruction name from the
  6969. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6970. to \code{jle foo}. Because the conditional jump instruction relies on
  6971. the EFLAGS register, it is common for it to be immediately preceded by
  6972. a \key{cmpq} instruction to set the EFLAGS register.
  6973. \section{Shrink the \LangIf{} Language}
  6974. \label{sec:shrink-Lif}
  6975. The \LangIf{} language includes several features that are easily
  6976. expressible with other features. For example, \code{and} and \code{or}
  6977. are expressible using \code{if} as follows.
  6978. \begin{align*}
  6979. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6980. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6981. \end{align*}
  6982. By performing these translations in the front-end of the compiler,
  6983. subsequent passes of the compiler do not need to deal with these features,
  6984. making the passes shorter.
  6985. %% For example, subtraction is
  6986. %% expressible using addition and negation.
  6987. %% \[
  6988. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6989. %% \]
  6990. %% Several of the comparison operations are expressible using less-than
  6991. %% and logical negation.
  6992. %% \[
  6993. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6994. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6995. %% \]
  6996. %% The \key{let} is needed in the above translation to ensure that
  6997. %% expression $e_1$ is evaluated before $e_2$.
  6998. On the other hand, sometimes translations reduce the efficiency of the
  6999. generated code by increasing the number of instructions. For example,
  7000. expressing subtraction in terms of negation
  7001. \[
  7002. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7003. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7004. \]
  7005. produces code with two x86 instructions (\code{negq} and \code{addq})
  7006. instead of just one (\code{subq}).
  7007. %% However,
  7008. %% these differences typically do not affect the number of accesses to
  7009. %% memory, which is the primary factor that determines execution time on
  7010. %% modern computer architectures.
  7011. \begin{exercise}\normalfont
  7012. %
  7013. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7014. the language by translating them to \code{if} expressions in \LangIf{}.
  7015. %
  7016. Create four test programs that involve these operators.
  7017. %
  7018. {\if\edition\racketEd
  7019. In the \code{run-tests.rkt} script, add the following entry for
  7020. \code{shrink} to the list of passes (it should be the only pass at
  7021. this point).
  7022. \begin{lstlisting}
  7023. (list "shrink" shrink interp_Lif type-check-Lif)
  7024. \end{lstlisting}
  7025. This instructs \code{interp-tests} to run the intepreter
  7026. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7027. output of \code{shrink}.
  7028. \fi}
  7029. %
  7030. Run the script to test your compiler on all the test programs.
  7031. \end{exercise}
  7032. {\if\edition\racketEd
  7033. \section{Uniquify Variables}
  7034. \label{sec:uniquify-Lif}
  7035. Add cases to \code{uniquify-exp} to handle Boolean constants and
  7036. \code{if} expressions.
  7037. \begin{exercise}\normalfont
  7038. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7039. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7040. \begin{lstlisting}
  7041. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7042. \end{lstlisting}
  7043. Run the script to test your compiler.
  7044. \end{exercise}
  7045. \fi}
  7046. \section{Remove Complex Operands}
  7047. \label{sec:remove-complex-opera-Lif}
  7048. The output language of \code{remove\_complex\_operands} is
  7049. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  7050. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7051. but the \code{if} expression is not. All three sub-expressions of an
  7052. \code{if} are allowed to be complex expressions but the operands of
  7053. \code{not} and the comparisons must be atomic.
  7054. %
  7055. \python{We add a new language form, the \code{Begin} expression, to aid
  7056. in the translation of \code{if} expressions. When we recursively
  7057. process the two branches of the \code{if}, we generate temporary
  7058. variables and their initializing expressions. However, these
  7059. expressions may contain side effects and should only be executed
  7060. when the condition of the \code{if} is true (for the ``then''
  7061. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7062. a way to initialize the temporary variables within the two branches
  7063. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7064. form execute the statements $ss$ and then returns the result of
  7065. expression $e$.}
  7066. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  7067. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  7068. according to whether the output needs to be \Exp{} or \Atm{} as
  7069. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  7070. particularly important to \textbf{not} replace its condition with a
  7071. temporary variable because that would interfere with the generation of
  7072. high-quality output in the \code{explicate\_control} pass.
  7073. \newcommand{\LifMonadASTPython}{
  7074. \begin{array}{rcl}
  7075. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7076. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7077. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7078. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7079. \Atm &::=& \BOOL{\itm{bool}}\\
  7080. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7081. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7082. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7083. \end{array}
  7084. }
  7085. \begin{figure}[tp]
  7086. \centering
  7087. \fbox{
  7088. \begin{minipage}{0.96\textwidth}
  7089. {\if\edition\racketEd
  7090. \[
  7091. \begin{array}{rcl}
  7092. Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  7093. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  7094. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  7095. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7096. &\MID& \UNIOP{\key{not}}{\Atm} \\
  7097. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7098. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7099. \end{array}
  7100. \]
  7101. \fi}
  7102. {\if\edition\pythonEd
  7103. \[
  7104. \begin{array}{l}
  7105. \gray{\LvarMonadASTPython} \\ \hline
  7106. \LifMonadASTPython \\
  7107. \begin{array}{rcl}
  7108. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7109. \end{array}
  7110. \end{array}
  7111. \]
  7112. \fi}
  7113. \end{minipage}
  7114. }
  7115. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  7116. \label{fig:Lif-anf-syntax}
  7117. \end{figure}
  7118. \begin{exercise}\normalfont
  7119. %
  7120. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7121. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7122. %
  7123. Create three new \LangIf{} programs that exercise the interesting
  7124. code in this pass.
  7125. %
  7126. {\if\edition\racketEd
  7127. In the \code{run-tests.rkt} script, add the following entry to the
  7128. list of \code{passes} and then run the script to test your compiler.
  7129. \begin{lstlisting}
  7130. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  7131. \end{lstlisting}
  7132. \fi}
  7133. \end{exercise}
  7134. \section{Explicate Control}
  7135. \label{sec:explicate-control-Lif}
  7136. \racket{Recall that the purpose of \code{explicate\_control} is to
  7137. make the order of evaluation explicit in the syntax of the program.
  7138. With the addition of \key{if} this get more interesting.}
  7139. %
  7140. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7141. %
  7142. The main challenge to overcome is that the condition of an \key{if}
  7143. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7144. condition must be a comparison.
  7145. As a motivating example, consider the following program that has an
  7146. \key{if} expression nested in the condition of another \key{if}.%
  7147. \python{\footnote{Programmers rarely write nested \code{if}
  7148. expressions, but it is not uncommon for the condition of an
  7149. \code{if} statement to be a call of a function that also contains an
  7150. \code{if} statement. When such a function is inlined, the result is
  7151. a nested \code{if} that requires the techniques discussed in this
  7152. section.}}
  7153. % cond_test_41.rkt, if_lt_eq.py
  7154. \begin{center}
  7155. \begin{minipage}{0.96\textwidth}
  7156. {\if\edition\racketEd
  7157. \begin{lstlisting}
  7158. (let ([x (read)])
  7159. (let ([y (read)])
  7160. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7161. (+ y 2)
  7162. (+ y 10))))
  7163. \end{lstlisting}
  7164. \fi}
  7165. {\if\edition\pythonEd
  7166. \begin{lstlisting}
  7167. x = input_int()
  7168. y = input_int()
  7169. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7170. \end{lstlisting}
  7171. \fi}
  7172. \end{minipage}
  7173. \end{center}
  7174. %
  7175. The naive way to compile \key{if} and the comparison operations would
  7176. be to handle each of them in isolation, regardless of their context.
  7177. Each comparison would be translated into a \key{cmpq} instruction
  7178. followed by several instructions to move the result from the EFLAGS
  7179. register into a general purpose register or stack location. Each
  7180. \key{if} would be translated into a \key{cmpq} instruction followed by
  7181. a conditional jump. The generated code for the inner \key{if} in the
  7182. above example would be as follows.
  7183. \begin{center}
  7184. \begin{minipage}{0.96\textwidth}
  7185. \begin{lstlisting}
  7186. cmpq $1, x
  7187. setl %al
  7188. movzbq %al, tmp
  7189. cmpq $1, tmp
  7190. je then_branch_1
  7191. jmp else_branch_1
  7192. \end{lstlisting}
  7193. \end{minipage}
  7194. \end{center}
  7195. However, if we take context into account we can do better and reduce
  7196. the use of \key{cmpq} instructions for accessing the EFLAG register.
  7197. Our goal will be to compile \key{if} expressions so that the relevant
  7198. comparison instruction appears directly before the conditional jump.
  7199. For example, we want to generate the following code for the inner
  7200. \code{if}.
  7201. \begin{center}
  7202. \begin{minipage}{0.96\textwidth}
  7203. \begin{lstlisting}
  7204. cmpq $1, x
  7205. jl then_branch_1
  7206. jmp else_branch_1
  7207. \end{lstlisting}
  7208. \end{minipage}
  7209. \end{center}
  7210. One way to achieve this goal is to reorganize the code at the level of
  7211. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7212. the following code.
  7213. \begin{center}
  7214. \begin{minipage}{0.96\textwidth}
  7215. {\if\edition\racketEd
  7216. \begin{lstlisting}
  7217. (let ([x (read)])
  7218. (let ([y (read)])
  7219. (if (< x 1)
  7220. (if (eq? x 0)
  7221. (+ y 2)
  7222. (+ y 10))
  7223. (if (eq? x 2)
  7224. (+ y 2)
  7225. (+ y 10)))))
  7226. \end{lstlisting}
  7227. \fi}
  7228. {\if\edition\pythonEd
  7229. \begin{lstlisting}
  7230. x = input_int()
  7231. y = intput_int()
  7232. print(((y + 2) if x == 0 else (y + 10)) \
  7233. if (x < 1) \
  7234. else ((y + 2) if (x == 2) else (y + 10)))
  7235. \end{lstlisting}
  7236. \fi}
  7237. \end{minipage}
  7238. \end{center}
  7239. Unfortunately, this approach duplicates the two branches from the
  7240. outer \code{if} and a compiler must never duplicate code! After all,
  7241. the two branches could have been very large expressions.
  7242. We need a way to perform the above transformation but without
  7243. duplicating code. That is, we need a way for different parts of a
  7244. program to refer to the same piece of code.
  7245. %
  7246. Put another way, we need to move away from abstract syntax
  7247. \emph{trees} and instead use \emph{graphs}.
  7248. %
  7249. At the level of x86 assembly this is straightforward because we can
  7250. label the code for each branch and insert jumps in all the places that
  7251. need to execute the branch.
  7252. %
  7253. Likewise, our language \LangCIf{} provides the ability to label a
  7254. sequence of code and to jump to a label via \code{goto}.
  7255. %
  7256. %% In particular, we use a standard program representation called a
  7257. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7258. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7259. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7260. %% edge represents a jump to another block.
  7261. %
  7262. %% The nice thing about the output of \code{explicate\_control} is that
  7263. %% there are no unnecessary comparisons and every comparison is part of a
  7264. %% conditional jump.
  7265. %% The down-side of this output is that it includes
  7266. %% trivial blocks, such as the blocks labeled \code{block92} through
  7267. %% \code{block95}, that only jump to another block. We discuss a solution
  7268. %% to this problem in Section~\ref{sec:opt-jumps}.
  7269. {\if\edition\racketEd
  7270. %
  7271. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7272. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7273. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7274. former function translates expressions in tail position whereas the
  7275. later function translates expressions on the right-hand-side of a
  7276. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7277. have a new kind of position to deal with: the predicate position of
  7278. the \key{if}. We need another function, \code{explicate\_pred}, that
  7279. decides how to compile an \key{if} by analyzing its predicate. So
  7280. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7281. tails for the then-branch and else-branch and outputs a tail. In the
  7282. following paragraphs we discuss specific cases in the
  7283. \code{explicate\_tail}, \code{explicate\_assign}, and
  7284. \code{explicate\_pred} functions.
  7285. %
  7286. \fi}
  7287. %
  7288. {\if\edition\pythonEd
  7289. %
  7290. We recommend implementing \code{explicate\_control} using the
  7291. following four auxiliary functions.
  7292. \begin{description}
  7293. \item[\code{explicate\_effect}] generates code for expressions as
  7294. statements, so their result is ignored and only their side effects
  7295. matter.
  7296. \item[\code{explicate\_assign}] generates code for expressions
  7297. on the right-hand side of an assignment.
  7298. \item[\code{explicate\_pred}] generates code for an \code{if}
  7299. expression or statement by analyzing the condition expression.
  7300. \item[\code{explicate\_stmt}] generates code for statements.
  7301. \end{description}
  7302. These four functions should build the dictionary of basic blocks. The
  7303. following auxiliary function can be used to create a new basic block
  7304. from a list of statements. It returns a \code{goto} statement that
  7305. jumps to the new basic block.
  7306. \begin{center}
  7307. \begin{minipage}{\textwidth}
  7308. \begin{lstlisting}
  7309. def create_block(stmts, basic_blocks):
  7310. label = label_name(generate_name('block'))
  7311. basic_blocks[label] = stmts
  7312. return Goto(label)
  7313. \end{lstlisting}
  7314. \end{minipage}
  7315. \end{center}
  7316. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7317. \code{explicate\_control} pass.
  7318. The \code{explicate\_effect} function has three parameters: 1) the
  7319. expression to be compiled, 2) the already-compiled code for this
  7320. expression's \emph{continuation}, that is, the list of statements that
  7321. should execute after this expression, and 3) the dictionary of
  7322. generated basic blocks. The \code{explicate\_effect} function returns
  7323. a list of \LangCIf{} statements and it may add to the dictionary of
  7324. basic blocks.
  7325. %
  7326. Let's consider a few of the cases for the expression to be compiled.
  7327. If the expression to be compiled is a constant, then it can be
  7328. discarded because it has no side effects. If it's a \CREAD{}, then it
  7329. has a side-effect and should be preserved. So the expression should be
  7330. translated into a statement using the \code{Expr} AST class. If the
  7331. expression to be compiled is an \code{if} expression, we translate the
  7332. two branches using \code{explicate\_effect} and then translate the
  7333. condition expression using \code{explicate\_pred}, which generates
  7334. code for the entire \code{if}.
  7335. The \code{explicate\_assign} function has four parameters: 1) the
  7336. right-hand-side of the assignment, 2) the left-hand-side of the
  7337. assignment (the variable), 3) the continuation, and 4) the dictionary
  7338. of basic blocks. The \code{explicate\_assign} function returns a list
  7339. of \LangCIf{} statements and it may add to the dictionary of basic
  7340. blocks.
  7341. When the right-hand-side is an \code{if} expression, there is some
  7342. work to do. In particular, the two branches should be translated using
  7343. \code{explicate\_assign} and the condition expression should be
  7344. translated using \code{explicate\_pred}. Otherwise we can simply
  7345. generate an assignment statement, with the given left and right-hand
  7346. sides, concatenated with its continuation.
  7347. \begin{figure}[tbp]
  7348. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7349. def explicate_effect(e, cont, basic_blocks):
  7350. match e:
  7351. case IfExp(test, body, orelse):
  7352. ...
  7353. case Call(func, args):
  7354. ...
  7355. case Begin(body, result):
  7356. ...
  7357. case _:
  7358. ...
  7359. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7360. match rhs:
  7361. case IfExp(test, body, orelse):
  7362. ...
  7363. case Begin(body, result):
  7364. ...
  7365. case _:
  7366. return [Assign([lhs], rhs)] + cont
  7367. def explicate_pred(cnd, thn, els, basic_blocks):
  7368. match cnd:
  7369. case Compare(left, [op], [right]):
  7370. goto_thn = create_block(thn, basic_blocks)
  7371. goto_els = create_block(els, basic_blocks)
  7372. return [If(cnd, [goto_thn], [goto_els])]
  7373. case Constant(True):
  7374. return thn;
  7375. case Constant(False):
  7376. return els;
  7377. case UnaryOp(Not(), operand):
  7378. ...
  7379. case IfExp(test, body, orelse):
  7380. ...
  7381. case Begin(body, result):
  7382. ...
  7383. case _:
  7384. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7385. [create_block(els, basic_blocks)],
  7386. [create_block(thn, basic_blocks)])]
  7387. def explicate_stmt(s, cont, basic_blocks):
  7388. match s:
  7389. case Assign([lhs], rhs):
  7390. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7391. case Expr(value):
  7392. return explicate_effect(value, cont, basic_blocks)
  7393. case If(test, body, orelse):
  7394. ...
  7395. def explicate_control(p):
  7396. match p:
  7397. case Module(body):
  7398. new_body = [Return(Constant(0))]
  7399. basic_blocks = {}
  7400. for s in reversed(body):
  7401. new_body = explicate_stmt(s, new_body, basic_blocks)
  7402. basic_blocks[label_name('start')] = new_body
  7403. return CProgram(basic_blocks)
  7404. \end{lstlisting}
  7405. \caption{Skeleton for the \code{explicate\_control} pass.}
  7406. \label{fig:explicate-control-Lif}
  7407. \end{figure}
  7408. \fi}
  7409. {\if\edition\racketEd
  7410. %
  7411. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7412. additional cases for Boolean constants and \key{if}. The cases for
  7413. \code{if} should recursively compile the two branches using either
  7414. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7415. cases should then invoke \code{explicate\_pred} on the condition
  7416. expression, passing in the generated code for the two branches. For
  7417. example, consider the following program with an \code{if} in tail
  7418. position.
  7419. \begin{lstlisting}
  7420. (let ([x (read)])
  7421. (if (eq? x 0) 42 777))
  7422. \end{lstlisting}
  7423. The two branches are recursively compiled to \code{return 42;} and
  7424. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7425. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7426. used as the result for \code{explicate\_tail}.
  7427. Next let us consider a program with an \code{if} on the right-hand
  7428. side of a \code{let}.
  7429. \begin{lstlisting}
  7430. (let ([y (read)])
  7431. (let ([x (if (eq? y 0) 40 777)])
  7432. (+ x 2)))
  7433. \end{lstlisting}
  7434. Note that the body of the inner \code{let} will have already been
  7435. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7436. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7437. to recursively process both branches of the \code{if}, so we generate
  7438. the following block using an auxiliary function named \code{create\_block}.
  7439. \begin{lstlisting}
  7440. block_6:
  7441. return (+ x 2)
  7442. \end{lstlisting}
  7443. and use \code{goto block\_6;} as the \code{cont} argument for
  7444. compiling the branches. So the two branches compile to
  7445. \begin{lstlisting}
  7446. x = 40;
  7447. goto block_6;
  7448. \end{lstlisting}
  7449. and
  7450. \begin{lstlisting}
  7451. x = 777;
  7452. goto block_6;
  7453. \end{lstlisting}
  7454. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7455. 0)} and the above code for the branches.
  7456. \fi}
  7457. {\if\edition\racketEd
  7458. \begin{figure}[tbp]
  7459. \begin{lstlisting}
  7460. (define (explicate_pred cnd thn els)
  7461. (match cnd
  7462. [(Var x) ___]
  7463. [(Let x rhs body) ___]
  7464. [(Prim 'not (list e)) ___]
  7465. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7466. (IfStmt (Prim op es) (create_block thn)
  7467. (create_block els))]
  7468. [(Bool b) (if b thn els)]
  7469. [(If cnd^ thn^ els^) ___]
  7470. [else (error "explicate_pred unhandled case" cnd)]))
  7471. \end{lstlisting}
  7472. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7473. \label{fig:explicate-pred}
  7474. \end{figure}
  7475. \fi}
  7476. \racket{The skeleton for the \code{explicate\_pred} function is given
  7477. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7478. 1) \code{cnd}, the condition expression of the \code{if},
  7479. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7480. and 3) \code{els}, the code generated by
  7481. explicate for the ``else'' branch. The \code{explicate\_pred}
  7482. function should match on \code{cnd} with a case for
  7483. every kind of expression that can have type \code{Boolean}.}
  7484. %
  7485. \python{The \code{explicate\_pred} function has four parameters: 1)
  7486. the condition expression, 2) the generated statements for the
  7487. ``then'' branch, 3) the generated statements for the ``else''
  7488. branch, and 4) the dictionary of basic blocks. The
  7489. \code{explicate\_pred} function returns a list of \LangCIf{}
  7490. statements and it may add to the dictionary of basic blocks.}
  7491. Consider the case for comparison operators. We translate the
  7492. comparison to an \code{if} statement whose branches are \code{goto}
  7493. statements created by applying \code{create\_block} to the code
  7494. generated for the \code{thn} and \code{els} branches. Let us
  7495. illustrate this translation with an example. Returning
  7496. to the program with an \code{if} expression in tail position,
  7497. we invoke \code{explicate\_pred} on its condition
  7498. \racket{\code{(eq? x 0)}}
  7499. \python{\code{x == 0}}
  7500. which happens to be a comparison operator.
  7501. {\if\edition\racketEd
  7502. \begin{lstlisting}
  7503. (let ([x (read)])
  7504. (if (eq? x 0) 42 777))
  7505. \end{lstlisting}
  7506. \fi}
  7507. {\if\edition\pythonEd
  7508. \begin{lstlisting}
  7509. x = input_int()
  7510. 42 if x == 0 else 777
  7511. \end{lstlisting}
  7512. \fi}
  7513. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7514. statements, from which we now create the following blocks.
  7515. \begin{center}
  7516. \begin{minipage}{\textwidth}
  7517. \begin{lstlisting}
  7518. block_1:
  7519. return 42;
  7520. block_2:
  7521. return 777;
  7522. \end{lstlisting}
  7523. \end{minipage}
  7524. \end{center}
  7525. %
  7526. So \code{explicate\_pred} compiles the comparison
  7527. \racket{\code{(eq? x 0)}}
  7528. \python{\code{x == 0}}
  7529. to the following \code{if} statement.
  7530. %
  7531. {\if\edition\racketEd
  7532. \begin{center}
  7533. \begin{minipage}{\textwidth}
  7534. \begin{lstlisting}
  7535. if (eq? x 0)
  7536. goto block_1;
  7537. else
  7538. goto block_2;
  7539. \end{lstlisting}
  7540. \end{minipage}
  7541. \end{center}
  7542. \fi}
  7543. {\if\edition\pythonEd
  7544. \begin{center}
  7545. \begin{minipage}{\textwidth}
  7546. \begin{lstlisting}
  7547. if x == 0:
  7548. goto block_1;
  7549. else
  7550. goto block_2;
  7551. \end{lstlisting}
  7552. \end{minipage}
  7553. \end{center}
  7554. \fi}
  7555. Next consider the case for Boolean constants. We perform a kind of
  7556. partial evaluation\index{subject}{partial evaluation} and output
  7557. either the \code{thn} or \code{els} branch depending on whether the
  7558. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7559. following program.
  7560. {\if\edition\racketEd
  7561. \begin{center}
  7562. \begin{minipage}{\textwidth}
  7563. \begin{lstlisting}
  7564. (if #t 42 777)
  7565. \end{lstlisting}
  7566. \end{minipage}
  7567. \end{center}
  7568. \fi}
  7569. {\if\edition\pythonEd
  7570. \begin{center}
  7571. \begin{minipage}{\textwidth}
  7572. \begin{lstlisting}
  7573. 42 if True else 777
  7574. \end{lstlisting}
  7575. \end{minipage}
  7576. \end{center}
  7577. \fi}
  7578. %
  7579. Again, the two branches \code{42} and \code{777} were compiled to
  7580. \code{return} statements, so \code{explicate\_pred} compiles the
  7581. constant
  7582. \racket{\code{\#t}}
  7583. \python{\code{True}}
  7584. to the code for the ``then'' branch.
  7585. \begin{center}
  7586. \begin{minipage}{\textwidth}
  7587. \begin{lstlisting}
  7588. return 42;
  7589. \end{lstlisting}
  7590. \end{minipage}
  7591. \end{center}
  7592. %
  7593. This case demonstrates that we sometimes discard the \code{thn} or
  7594. \code{els} blocks that are input to \code{explicate\_pred}.
  7595. The case for \key{if} expressions in \code{explicate\_pred} is
  7596. particularly illuminating because it deals with the challenges we
  7597. discussed above regarding nested \key{if} expressions
  7598. (Figure~\ref{fig:explicate-control-s1-38}). The
  7599. \racket{\lstinline{thn^}}\python{\code{body}} and
  7600. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7601. \key{if} inherit their context from the current one, that is,
  7602. predicate context. So you should recursively apply
  7603. \code{explicate\_pred} to the
  7604. \racket{\lstinline{thn^}}\python{\code{body}} and
  7605. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7606. those recursive calls, pass \code{thn} and \code{els} as the extra
  7607. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7608. inside each recursive call. As discussed above, to avoid duplicating
  7609. code, we need to add them to the dictionary of basic blocks so that we
  7610. can instead refer to them by name and execute them with a \key{goto}.
  7611. {\if\edition\pythonEd
  7612. %
  7613. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7614. three parameters: 1) the statement to be compiled, 2) the code for its
  7615. continuation, and 3) the dictionary of basic blocks. The
  7616. \code{explicate\_stmt} returns a list of statements and it may add to
  7617. the dictionary of basic blocks. The cases for assignment and an
  7618. expression-statement are given in full in the skeleton code: they
  7619. simply dispatch to \code{explicate\_assign} and
  7620. \code{explicate\_effect}, respectively. The case for \code{if}
  7621. statements is not given, and is similar to the case for \code{if}
  7622. expressions.
  7623. The \code{explicate\_control} function itself is given in
  7624. Figure~\ref{fig:explicate-control-Lif}. It applies
  7625. \code{explicate\_stmt} to each statement in the program, from back to
  7626. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7627. used as the continuation parameter in the next call to
  7628. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7629. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7630. the dictionary of basic blocks, labeling it as the ``start'' block.
  7631. %
  7632. \fi}
  7633. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7634. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7635. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7636. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7637. %% results from the two recursive calls. We complete the case for
  7638. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7639. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7640. %% the result $B_5$.
  7641. %% \[
  7642. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7643. %% \quad\Rightarrow\quad
  7644. %% B_5
  7645. %% \]
  7646. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7647. %% inherit the current context, so they are in tail position. Thus, the
  7648. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7649. %% \code{explicate\_tail}.
  7650. %% %
  7651. %% We need to pass $B_0$ as the accumulator argument for both of these
  7652. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7653. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7654. %% to the control-flow graph and obtain a promised goto $G_0$.
  7655. %% %
  7656. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7657. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7658. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7659. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7660. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7661. %% \[
  7662. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7663. %% \]
  7664. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7665. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7666. %% should not be confused with the labels for the blocks that appear in
  7667. %% the generated code. We initially construct unlabeled blocks; we only
  7668. %% attach labels to blocks when we add them to the control-flow graph, as
  7669. %% we see in the next case.
  7670. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7671. %% function. The context of the \key{if} is an assignment to some
  7672. %% variable $x$ and then the control continues to some promised block
  7673. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7674. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7675. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7676. %% branches of the \key{if} inherit the current context, so they are in
  7677. %% assignment positions. Let $B_2$ be the result of applying
  7678. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7679. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7680. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7681. %% the result of applying \code{explicate\_pred} to the predicate
  7682. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7683. %% translates to the promise $B_4$.
  7684. %% \[
  7685. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7686. %% \]
  7687. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7688. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7689. \code{remove\_complex\_operands} pass and then the
  7690. \code{explicate\_control} pass on the example program. We walk through
  7691. the output program.
  7692. %
  7693. Following the order of evaluation in the output of
  7694. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7695. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7696. in the predicate of the inner \key{if}. In the output of
  7697. \code{explicate\_control}, in the
  7698. block labeled \code{start}, are two assignment statements followed by a
  7699. \code{if} statement that branches to \code{block\_8} or
  7700. \code{block\_9}. The blocks associated with those labels contain the
  7701. translations of the code
  7702. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7703. and
  7704. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7705. respectively. In particular, we start \code{block\_8} with the
  7706. comparison
  7707. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7708. and then branch to \code{block\_4} or \code{block\_5}.
  7709. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7710. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7711. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7712. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7713. and go directly to \code{block\_2} and \code{block\_3},
  7714. which we investigate in Section~\ref{sec:opt-jumps}.
  7715. Getting back to the example, \code{block\_2} and \code{block\_3},
  7716. corresponds to the two branches of the outer \key{if}, i.e.,
  7717. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7718. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7719. %
  7720. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7721. %
  7722. \python{The \code{block\_1} corresponds to the \code{print} statment
  7723. at the end of the program.}
  7724. \begin{figure}[tbp]
  7725. {\if\edition\racketEd
  7726. \begin{tabular}{lll}
  7727. \begin{minipage}{0.4\textwidth}
  7728. % cond_test_41.rkt
  7729. \begin{lstlisting}
  7730. (let ([x (read)])
  7731. (let ([y (read)])
  7732. (if (if (< x 1)
  7733. (eq? x 0)
  7734. (eq? x 2))
  7735. (+ y 2)
  7736. (+ y 10))))
  7737. \end{lstlisting}
  7738. \end{minipage}
  7739. &
  7740. $\Rightarrow$
  7741. &
  7742. \begin{minipage}{0.55\textwidth}
  7743. \begin{lstlisting}
  7744. start:
  7745. x = (read);
  7746. y = (read);
  7747. if (< x 1)
  7748. goto block_8;
  7749. else
  7750. goto block_9;
  7751. block_8:
  7752. if (eq? x 0)
  7753. goto block_4;
  7754. else
  7755. goto block_5;
  7756. block_9:
  7757. if (eq? x 2)
  7758. goto block_6;
  7759. else
  7760. goto block_7;
  7761. block_4:
  7762. goto block_2;
  7763. block_5:
  7764. goto block_3;
  7765. block_6:
  7766. goto block_2;
  7767. block_7:
  7768. goto block_3;
  7769. block_2:
  7770. return (+ y 2);
  7771. block_3:
  7772. return (+ y 10);
  7773. \end{lstlisting}
  7774. \end{minipage}
  7775. \end{tabular}
  7776. \fi}
  7777. {\if\edition\pythonEd
  7778. \begin{tabular}{lll}
  7779. \begin{minipage}{0.4\textwidth}
  7780. % cond_test_41.rkt
  7781. \begin{lstlisting}
  7782. x = input_int()
  7783. y = input_int()
  7784. print(y + 2 \
  7785. if (x == 0 \
  7786. if x < 1 \
  7787. else x == 2) \
  7788. else y + 10)
  7789. \end{lstlisting}
  7790. \end{minipage}
  7791. &
  7792. $\Rightarrow$
  7793. &
  7794. \begin{minipage}{0.55\textwidth}
  7795. \begin{lstlisting}
  7796. start:
  7797. x = input_int()
  7798. y = input_int()
  7799. if x < 1:
  7800. goto block_8
  7801. else:
  7802. goto block_9
  7803. block_8:
  7804. if x == 0:
  7805. goto block_4
  7806. else:
  7807. goto block_5
  7808. block_9:
  7809. if x == 2:
  7810. goto block_6
  7811. else:
  7812. goto block_7
  7813. block_4:
  7814. goto block_2
  7815. block_5:
  7816. goto block_3
  7817. block_6:
  7818. goto block_2
  7819. block_7:
  7820. goto block_3
  7821. block_2:
  7822. tmp_0 = y + 2
  7823. goto block_1
  7824. block_3:
  7825. tmp_0 = y + 10
  7826. goto block_1
  7827. block_1:
  7828. print(tmp_0)
  7829. return 0
  7830. \end{lstlisting}
  7831. \end{minipage}
  7832. \end{tabular}
  7833. \fi}
  7834. \caption{Translation from \LangIf{} to \LangCIf{}
  7835. via the \code{explicate\_control}.}
  7836. \label{fig:explicate-control-s1-38}
  7837. \end{figure}
  7838. {\if\edition\racketEd
  7839. The way in which the \code{shrink} pass transforms logical operations
  7840. such as \code{and} and \code{or} can impact the quality of code
  7841. generated by \code{explicate\_control}. For example, consider the
  7842. following program.
  7843. % cond_test_21.rkt, and_eq_input.py
  7844. \begin{lstlisting}
  7845. (if (and (eq? (read) 0) (eq? (read) 1))
  7846. 0
  7847. 42)
  7848. \end{lstlisting}
  7849. The \code{and} operation should transform into something that the
  7850. \code{explicate\_pred} function can still analyze and descend through to
  7851. reach the underlying \code{eq?} conditions. Ideally, your
  7852. \code{explicate\_control} pass should generate code similar to the
  7853. following for the above program.
  7854. \begin{center}
  7855. \begin{lstlisting}
  7856. start:
  7857. tmp1 = (read);
  7858. if (eq? tmp1 0) goto block40;
  7859. else goto block39;
  7860. block40:
  7861. tmp2 = (read);
  7862. if (eq? tmp2 1) goto block38;
  7863. else goto block39;
  7864. block38:
  7865. return 0;
  7866. block39:
  7867. return 42;
  7868. \end{lstlisting}
  7869. \end{center}
  7870. \fi}
  7871. \begin{exercise}\normalfont
  7872. \racket{
  7873. Implement the pass \code{explicate\_control} by adding the cases for
  7874. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7875. \code{explicate\_assign} functions. Implement the auxiliary function
  7876. \code{explicate\_pred} for predicate contexts.}
  7877. \python{Implement \code{explicate\_control} pass with its
  7878. four auxiliary functions.}
  7879. %
  7880. Create test cases that exercise all of the new cases in the code for
  7881. this pass.
  7882. %
  7883. {\if\edition\racketEd
  7884. Add the following entry to the list of \code{passes} in
  7885. \code{run-tests.rkt} and then run this script to test your compiler.
  7886. \begin{lstlisting}
  7887. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7888. \end{lstlisting}
  7889. \fi}
  7890. \end{exercise}
  7891. \clearpage
  7892. \section{Select Instructions}
  7893. \label{sec:select-Lif}
  7894. \index{subject}{instruction selection}
  7895. The \code{select\_instructions} pass translates \LangCIf{} to
  7896. \LangXIfVar{}.
  7897. %
  7898. \racket{Recall that we implement this pass using three auxiliary
  7899. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7900. $\Tail$.}
  7901. %
  7902. \racket{For $\Atm$, we have new cases for the Booleans.}
  7903. %
  7904. \python{We begin with the Boolean constants.}
  7905. We take the usual approach of encoding them as integers.
  7906. \[
  7907. \TRUE{} \quad\Rightarrow\quad \key{1}
  7908. \qquad\qquad
  7909. \FALSE{} \quad\Rightarrow\quad \key{0}
  7910. \]
  7911. For translating statements, we discuss a selection of cases. The \code{not}
  7912. operation can be implemented in terms of \code{xorq} as we discussed
  7913. at the beginning of this section. Given an assignment, if the
  7914. left-hand side variable is the same as the argument of \code{not},
  7915. then just the \code{xorq} instruction suffices.
  7916. \[
  7917. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7918. \quad\Rightarrow\quad
  7919. \key{xorq}~\key{\$}1\key{,}~\Var
  7920. \]
  7921. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7922. semantics of x86. In the following translation, let $\Arg$ be the
  7923. result of translating $\Atm$ to x86.
  7924. \[
  7925. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7926. \quad\Rightarrow\quad
  7927. \begin{array}{l}
  7928. \key{movq}~\Arg\key{,}~\Var\\
  7929. \key{xorq}~\key{\$}1\key{,}~\Var
  7930. \end{array}
  7931. \]
  7932. Next consider the cases for equality. Translating this operation to
  7933. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7934. instruction discussed above. We recommend translating an assignment
  7935. with an equality on the right-hand side into a sequence of three
  7936. instructions. \\
  7937. \begin{tabular}{lll}
  7938. \begin{minipage}{0.4\textwidth}
  7939. \begin{lstlisting}
  7940. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7941. \end{lstlisting}
  7942. \end{minipage}
  7943. &
  7944. $\Rightarrow$
  7945. &
  7946. \begin{minipage}{0.4\textwidth}
  7947. \begin{lstlisting}
  7948. cmpq |$\Arg_2$|, |$\Arg_1$|
  7949. sete %al
  7950. movzbq %al, |$\Var$|
  7951. \end{lstlisting}
  7952. \end{minipage}
  7953. \end{tabular} \\
  7954. The translations for the other comparison operators are similar to the
  7955. above but use different suffixes for the \code{set} instruction.
  7956. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7957. \key{goto} and \key{if} statements. Both are straightforward to
  7958. translate to x86.}
  7959. %
  7960. A \key{goto} statement becomes a jump instruction.
  7961. \[
  7962. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7963. \]
  7964. %
  7965. An \key{if} statement becomes a compare instruction followed by a
  7966. conditional jump (for the ``then'' branch) and the fall-through is to
  7967. a regular jump (for the ``else'' branch).\\
  7968. \begin{tabular}{lll}
  7969. \begin{minipage}{0.4\textwidth}
  7970. \begin{lstlisting}
  7971. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7972. goto |$\ell_1$||$\racket{\key{;}}$|
  7973. else|$\python{\key{:}}$|
  7974. goto |$\ell_2$||$\racket{\key{;}}$|
  7975. \end{lstlisting}
  7976. \end{minipage}
  7977. &
  7978. $\Rightarrow$
  7979. &
  7980. \begin{minipage}{0.4\textwidth}
  7981. \begin{lstlisting}
  7982. cmpq |$\Arg_2$|, |$\Arg_1$|
  7983. je |$\ell_1$|
  7984. jmp |$\ell_2$|
  7985. \end{lstlisting}
  7986. \end{minipage}
  7987. \end{tabular} \\
  7988. Again, the translations for the other comparison operators are similar to the
  7989. above but use different suffixes for the conditional jump instruction.
  7990. \python{Regarding the \key{return} statement, we recommend treating it
  7991. as an assignment to the \key{rax} register followed by a jump to the
  7992. conclusion of the \code{main} function.}
  7993. \begin{exercise}\normalfont
  7994. Expand your \code{select\_instructions} pass to handle the new
  7995. features of the \LangIf{} language.
  7996. %
  7997. {\if\edition\racketEd
  7998. Add the following entry to the list of \code{passes} in
  7999. \code{run-tests.rkt}
  8000. \begin{lstlisting}
  8001. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8002. \end{lstlisting}
  8003. \fi}
  8004. %
  8005. Run the script to test your compiler on all the test programs.
  8006. \end{exercise}
  8007. \section{Register Allocation}
  8008. \label{sec:register-allocation-Lif}
  8009. \index{subject}{register allocation}
  8010. The changes required for \LangIf{} affect liveness analysis, building the
  8011. interference graph, and assigning homes, but the graph coloring
  8012. algorithm itself does not change.
  8013. \subsection{Liveness Analysis}
  8014. \label{sec:liveness-analysis-Lif}
  8015. \index{subject}{liveness analysis}
  8016. Recall that for \LangVar{} we implemented liveness analysis for a
  8017. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  8018. the addition of \key{if} expressions to \LangIf{},
  8019. \code{explicate\_control} produces many basic blocks.
  8020. %% We recommend that you create a new auxiliary function named
  8021. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8022. %% control-flow graph.
  8023. The first question is: in what order should we process the basic blocks?
  8024. Recall that to perform liveness analysis on a basic block we need to
  8025. know the live-after set for the last instruction in the block. If a
  8026. basic block has no successors (i.e. contains no jumps to other
  8027. blocks), then it has an empty live-after set and we can immediately
  8028. apply liveness analysis to it. If a basic block has some successors,
  8029. then we need to complete liveness analysis on those blocks
  8030. first. These ordering contraints are the reverse of a
  8031. \emph{topological order}\index{subject}{topological order} on a graph
  8032. representation of the program. In particular, the \emph{control flow
  8033. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8034. of a program has a node for each basic block and an edge for each jump
  8035. from one block to another. It is straightforward to generate a CFG
  8036. from the dictionary of basic blocks. One then transposes the CFG and
  8037. applies the topological sort algorithm.
  8038. %
  8039. %
  8040. \racket{We recommend using the \code{tsort} and \code{transpose}
  8041. functions of the Racket \code{graph} package to accomplish this.}
  8042. %
  8043. \python{We provide implementations of \code{topological\_sort} and
  8044. \code{transpose} in the file \code{graph.py} of the support code.}
  8045. %
  8046. As an aside, a topological ordering is only guaranteed to exist if the
  8047. graph does not contain any cycles. This is the case for the
  8048. control-flow graphs that we generate from \LangIf{} programs.
  8049. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8050. and learn how to handle cycles in the control-flow graph.
  8051. \racket{You'll need to construct a directed graph to represent the
  8052. control-flow graph. Do not use the \code{directed-graph} of the
  8053. \code{graph} package because that only allows at most one edge
  8054. between each pair of vertices, but a control-flow graph may have
  8055. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8056. file in the support code implements a graph representation that
  8057. allows multiple edges between a pair of vertices.}
  8058. {\if\edition\racketEd
  8059. The next question is how to analyze jump instructions. Recall that in
  8060. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8061. \code{label->live} that maps each label to the set of live locations
  8062. at the beginning of its block. We use \code{label->live} to determine
  8063. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8064. that we have many basic blocks, \code{label->live} needs to be updated
  8065. as we process the blocks. In particular, after performing liveness
  8066. analysis on a block, we take the live-before set of its first
  8067. instruction and associate that with the block's label in the
  8068. \code{label->live}.
  8069. \fi}
  8070. %
  8071. {\if\edition\pythonEd
  8072. %
  8073. The next question is how to analyze jump instructions. The locations
  8074. that are live before a \code{jmp} should be the locations in
  8075. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8076. maintaining a dictionary named \code{live\_before\_block} that maps each
  8077. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8078. block. After performing liveness analysis on each block, we take the
  8079. live-before set of its first instruction and associate that with the
  8080. block's label in the \code{live\_before\_block} dictionary.
  8081. %
  8082. \fi}
  8083. In \LangXIfVar{} we also have the conditional jump
  8084. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8085. this instruction is particularly interesting because, during
  8086. compilation, we do not know which way a conditional jump will go. So
  8087. we do not know whether to use the live-before set for the following
  8088. instruction or the live-before set for the block associated with the
  8089. $\itm{label}$. However, there is no harm to the correctness of the
  8090. generated code if we classify more locations as live than the ones
  8091. that are truly live during one particular execution of the
  8092. instruction. Thus, we can take the union of the live-before sets from
  8093. the following instruction and from the mapping for $\itm{label}$ in
  8094. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8095. The auxiliary functions for computing the variables in an
  8096. instruction's argument and for computing the variables read-from ($R$)
  8097. or written-to ($W$) by an instruction need to be updated to handle the
  8098. new kinds of arguments and instructions in \LangXIfVar{}.
  8099. \begin{exercise}\normalfont
  8100. {\if\edition\racketEd
  8101. %
  8102. Update the \code{uncover\_live} pass to apply liveness analysis to
  8103. every basic block in the program.
  8104. %
  8105. Add the following entry to the list of \code{passes} in the
  8106. \code{run-tests.rkt} script.
  8107. \begin{lstlisting}
  8108. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8109. \end{lstlisting}
  8110. \fi}
  8111. {\if\edition\pythonEd
  8112. %
  8113. Update the \code{uncover\_live} function to perform liveness analysis,
  8114. in reverse topological order, on all of the basic blocks in the
  8115. program.
  8116. %
  8117. \fi}
  8118. % Check that the live-after sets that you generate for
  8119. % example X matches the following... -Jeremy
  8120. \end{exercise}
  8121. \subsection{Build the Interference Graph}
  8122. \label{sec:build-interference-Lif}
  8123. Many of the new instructions in \LangXIfVar{} can be handled in the
  8124. same way as the instructions in \LangXVar{}.
  8125. % Thus, if your code was
  8126. % already quite general, it will not need to be changed to handle the
  8127. % new instructions. If your code is not general enough, we recommend that
  8128. % you change your code to be more general. For example, you can factor
  8129. % out the computing of the the read and write sets for each kind of
  8130. % instruction into auxiliary functions.
  8131. %
  8132. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8133. similar to the \key{movq} instruction. See rule number 1 in
  8134. Section~\ref{sec:build-interference}.
  8135. \begin{exercise}\normalfont
  8136. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8137. {\if\edition\racketEd
  8138. Add the following entries to the list of \code{passes} in the
  8139. \code{run-tests.rkt} script.
  8140. \begin{lstlisting}
  8141. (list "build_interference" build_interference interp-pseudo-x86-1)
  8142. (list "allocate_registers" allocate_registers interp-x86-1)
  8143. \end{lstlisting}
  8144. \fi}
  8145. % Check that the interference graph that you generate for
  8146. % example X matches the following graph G... -Jeremy
  8147. \end{exercise}
  8148. \section{Patch Instructions}
  8149. The new instructions \key{cmpq} and \key{movzbq} have some special
  8150. restrictions that need to be handled in the \code{patch\_instructions}
  8151. pass.
  8152. %
  8153. The second argument of the \key{cmpq} instruction must not be an
  8154. immediate value (such as an integer). So if you are comparing two
  8155. immediates, we recommend inserting a \key{movq} instruction to put the
  8156. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8157. one memory reference.
  8158. %
  8159. The second argument of the \key{movzbq} must be a register.
  8160. \begin{exercise}\normalfont
  8161. %
  8162. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8163. %
  8164. {\if\edition\racketEd
  8165. Add the following entry to the list of \code{passes} in
  8166. \code{run-tests.rkt} and then run this script to test your compiler.
  8167. \begin{lstlisting}
  8168. (list "patch_instructions" patch_instructions interp-x86-1)
  8169. \end{lstlisting}
  8170. \fi}
  8171. \end{exercise}
  8172. {\if\edition\pythonEd
  8173. \section{Prelude and Conclusion}
  8174. \label{sec:prelude-conclusion-cond}
  8175. The generation of the \code{main} function with its prelude and
  8176. conclusion must change to accomodate how the program now consists of
  8177. one or more basic blocks. After the prelude in \code{main}, jump to
  8178. the \code{start} block. Place the conclusion in a basic block labelled
  8179. with \code{conclusion}.
  8180. \fi}
  8181. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8182. \LangIf{} translated to x86, showing the results of
  8183. \code{explicate\_control}, \code{select\_instructions}, and the final
  8184. x86 assembly.
  8185. \begin{figure}[tbp]
  8186. {\if\edition\racketEd
  8187. \begin{tabular}{lll}
  8188. \begin{minipage}{0.4\textwidth}
  8189. % cond_test_20.rkt, eq_input.py
  8190. \begin{lstlisting}
  8191. (if (eq? (read) 1) 42 0)
  8192. \end{lstlisting}
  8193. $\Downarrow$
  8194. \begin{lstlisting}
  8195. start:
  8196. tmp7951 = (read);
  8197. if (eq? tmp7951 1)
  8198. goto block7952;
  8199. else
  8200. goto block7953;
  8201. block7952:
  8202. return 42;
  8203. block7953:
  8204. return 0;
  8205. \end{lstlisting}
  8206. $\Downarrow$
  8207. \begin{lstlisting}
  8208. start:
  8209. callq read_int
  8210. movq %rax, tmp7951
  8211. cmpq $1, tmp7951
  8212. je block7952
  8213. jmp block7953
  8214. block7953:
  8215. movq $0, %rax
  8216. jmp conclusion
  8217. block7952:
  8218. movq $42, %rax
  8219. jmp conclusion
  8220. \end{lstlisting}
  8221. \end{minipage}
  8222. &
  8223. $\Rightarrow\qquad$
  8224. \begin{minipage}{0.4\textwidth}
  8225. \begin{lstlisting}
  8226. start:
  8227. callq read_int
  8228. movq %rax, %rcx
  8229. cmpq $1, %rcx
  8230. je block7952
  8231. jmp block7953
  8232. block7953:
  8233. movq $0, %rax
  8234. jmp conclusion
  8235. block7952:
  8236. movq $42, %rax
  8237. jmp conclusion
  8238. .globl main
  8239. main:
  8240. pushq %rbp
  8241. movq %rsp, %rbp
  8242. pushq %r13
  8243. pushq %r12
  8244. pushq %rbx
  8245. pushq %r14
  8246. subq $0, %rsp
  8247. jmp start
  8248. conclusion:
  8249. addq $0, %rsp
  8250. popq %r14
  8251. popq %rbx
  8252. popq %r12
  8253. popq %r13
  8254. popq %rbp
  8255. retq
  8256. \end{lstlisting}
  8257. \end{minipage}
  8258. \end{tabular}
  8259. \fi}
  8260. {\if\edition\pythonEd
  8261. \begin{tabular}{lll}
  8262. \begin{minipage}{0.4\textwidth}
  8263. % cond_test_20.rkt, eq_input.py
  8264. \begin{lstlisting}
  8265. print(42 if input_int() == 1 else 0)
  8266. \end{lstlisting}
  8267. $\Downarrow$
  8268. \begin{lstlisting}
  8269. start:
  8270. tmp_0 = input_int()
  8271. if tmp_0 == 1:
  8272. goto block_3
  8273. else:
  8274. goto block_4
  8275. block_3:
  8276. tmp_1 = 42
  8277. goto block_2
  8278. block_4:
  8279. tmp_1 = 0
  8280. goto block_2
  8281. block_2:
  8282. print(tmp_1)
  8283. return 0
  8284. \end{lstlisting}
  8285. $\Downarrow$
  8286. \begin{lstlisting}
  8287. start:
  8288. callq read_int
  8289. movq %rax, tmp_0
  8290. cmpq 1, tmp_0
  8291. je block_3
  8292. jmp block_4
  8293. block_3:
  8294. movq 42, tmp_1
  8295. jmp block_2
  8296. block_4:
  8297. movq 0, tmp_1
  8298. jmp block_2
  8299. block_2:
  8300. movq tmp_1, %rdi
  8301. callq print_int
  8302. movq 0, %rax
  8303. jmp conclusion
  8304. \end{lstlisting}
  8305. \end{minipage}
  8306. &
  8307. $\Rightarrow\qquad$
  8308. \begin{minipage}{0.4\textwidth}
  8309. \begin{lstlisting}
  8310. .globl main
  8311. main:
  8312. pushq %rbp
  8313. movq %rsp, %rbp
  8314. subq $0, %rsp
  8315. jmp start
  8316. start:
  8317. callq read_int
  8318. movq %rax, %rcx
  8319. cmpq $1, %rcx
  8320. je block_3
  8321. jmp block_4
  8322. block_3:
  8323. movq $42, %rcx
  8324. jmp block_2
  8325. block_4:
  8326. movq $0, %rcx
  8327. jmp block_2
  8328. block_2:
  8329. movq %rcx, %rdi
  8330. callq print_int
  8331. movq $0, %rax
  8332. jmp conclusion
  8333. conclusion:
  8334. addq $0, %rsp
  8335. popq %rbp
  8336. retq
  8337. \end{lstlisting}
  8338. \end{minipage}
  8339. \end{tabular}
  8340. \fi}
  8341. \caption{Example compilation of an \key{if} expression to x86, showing
  8342. the results of \code{explicate\_control},
  8343. \code{select\_instructions}, and the final x86 assembly code. }
  8344. \label{fig:if-example-x86}
  8345. \end{figure}
  8346. \begin{figure}[tbp]
  8347. {\if\edition\racketEd
  8348. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8349. \node (Lif) at (0,2) {\large \LangIf{}};
  8350. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8351. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8352. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8353. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8354. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8355. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8356. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8357. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8358. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8359. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8360. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8361. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8362. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8363. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8364. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8365. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8366. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8367. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8368. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8369. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8370. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8371. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8372. \end{tikzpicture}
  8373. \fi}
  8374. {\if\edition\pythonEd
  8375. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8376. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8377. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8378. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8379. \node (C-1) at (3,0) {\large \LangCIf{}};
  8380. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8381. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8382. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8383. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8384. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8385. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8386. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8387. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8388. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8389. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8390. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8391. \end{tikzpicture}
  8392. \fi}
  8393. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8394. \label{fig:Lif-passes}
  8395. \end{figure}
  8396. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8397. compilation of \LangIf{}.
  8398. \section{Challenge: Optimize Blocks and Remove Jumps}
  8399. \label{sec:opt-jumps}
  8400. We discuss two optional challenges that involve optimizing the
  8401. control-flow of the program.
  8402. \subsection{Optimize Blocks}
  8403. The algorithm for \code{explicate\_control} that we discussed in
  8404. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8405. blocks. It does so in two different ways.
  8406. %
  8407. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8408. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8409. a new basic block from a single \code{goto} statement, whereas we
  8410. could have simply returned the \code{goto} statement. We can solve
  8411. this problem by modifying the \code{create\_block} function to
  8412. recognize this situation.
  8413. Second, \code{explicate\_control} creates a basic block whenever a
  8414. continuation \emph{might} get used more than once (whenever a
  8415. continuation is passed into two or more recursive calls). However,
  8416. some continuation parameters may not be used at all. For example, consider the
  8417. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8418. discard the \code{els} branch. So the question is how can we decide
  8419. whether to create a basic block?
  8420. The solution to this conundrum is to use \emph{lazy
  8421. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8422. to delay creating a basic block until the point in time where we know
  8423. it will be used.
  8424. %
  8425. {\if\edition\racketEd
  8426. %
  8427. Racket provides support for
  8428. lazy evaluation with the
  8429. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8430. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8431. \index{subject}{delay} creates a
  8432. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8433. expressions is postponed. When \key{(force}
  8434. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8435. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8436. result of $e_n$ is cached in the promise and returned. If \code{force}
  8437. is applied again to the same promise, then the cached result is
  8438. returned. If \code{force} is applied to an argument that is not a
  8439. promise, \code{force} simply returns the argument.
  8440. %
  8441. \fi}
  8442. %
  8443. {\if\edition\pythonEd
  8444. %
  8445. While Python does not provide direct support for lazy evaluation, it
  8446. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8447. by wrapping it inside a function with no parameters. We can
  8448. \emph{force} its evaluation by calling the function. However, in some
  8449. cases of \code{explicate\_pred}, etc., we will return a list of
  8450. statements and in other cases we will return a function that computes
  8451. a list of statements. We use the term \emph{promise} to refer to a
  8452. value that may be delayed. To uniformly deal with
  8453. promises, we define the following \code{force} function that checks
  8454. whether its input is delayed (i.e., whether it is a function) and then
  8455. either 1) calls the function, or 2) returns the input.
  8456. \begin{lstlisting}
  8457. def force(promise):
  8458. if isinstance(promise, types.FunctionType):
  8459. return promise()
  8460. else:
  8461. return promise
  8462. \end{lstlisting}
  8463. %
  8464. \fi}
  8465. We use promises for the input and output of the functions
  8466. \code{explicate\_pred}, \code{explicate\_assign},
  8467. %
  8468. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8469. %
  8470. So instead of taking and returning lists of statments, they take and
  8471. return promises. Furthermore, when we come to a situation in which a
  8472. continuation might be used more than once, as in the case for
  8473. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8474. that creates a basic block for each continuation (if there is not
  8475. already one) and then returns a \code{goto} statement to that basic
  8476. block.
  8477. %
  8478. {\if\edition\racketEd
  8479. %
  8480. The following auxiliary function named \code{create\_block} accomplishes
  8481. this task. It begins with \code{delay} to create a promise. When
  8482. forced, this promise will force the original promise. If that returns
  8483. a \code{goto} (because the block was already added to the control-flow
  8484. graph), then we return the \code{goto}. Otherwise we add the block to
  8485. the control-flow graph with another auxiliary function named
  8486. \code{add-node}. That function returns the label for the new block,
  8487. which we use to create a \code{goto}.
  8488. \begin{lstlisting}
  8489. (define (create_block tail)
  8490. (delay
  8491. (define t (force tail))
  8492. (match t
  8493. [(Goto label) (Goto label)]
  8494. [else (Goto (add-node t))])))
  8495. \end{lstlisting}
  8496. \fi}
  8497. {\if\edition\pythonEd
  8498. %
  8499. Here is the new version of the \code{create\_block} auxiliary function
  8500. that works on promises and that checks whether the block consists of a
  8501. solitary \code{goto} statement.\\
  8502. \begin{minipage}{\textwidth}
  8503. \begin{lstlisting}
  8504. def create_block(promise, basic_blocks):
  8505. stmts = force(promise)
  8506. match stmts:
  8507. case [Goto(l)]:
  8508. return Goto(l)
  8509. case _:
  8510. label = label_name(generate_name('block'))
  8511. basic_blocks[label] = stmts
  8512. return Goto(label)
  8513. \end{lstlisting}
  8514. \end{minipage}
  8515. \fi}
  8516. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8517. \code{explicate\_control} on the example of the nested \code{if}
  8518. expressions with the two improvements discussed above. As you can
  8519. see, the number of basic blocks has been reduced from 10 blocks (see
  8520. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8521. \begin{figure}[tbp]
  8522. {\if\edition\racketEd
  8523. \begin{tabular}{lll}
  8524. \begin{minipage}{0.4\textwidth}
  8525. % cond_test_41.rkt
  8526. \begin{lstlisting}
  8527. (let ([x (read)])
  8528. (let ([y (read)])
  8529. (if (if (< x 1)
  8530. (eq? x 0)
  8531. (eq? x 2))
  8532. (+ y 2)
  8533. (+ y 10))))
  8534. \end{lstlisting}
  8535. \end{minipage}
  8536. &
  8537. $\Rightarrow$
  8538. &
  8539. \begin{minipage}{0.55\textwidth}
  8540. \begin{lstlisting}
  8541. start:
  8542. x = (read);
  8543. y = (read);
  8544. if (< x 1) goto block40;
  8545. else goto block41;
  8546. block40:
  8547. if (eq? x 0) goto block38;
  8548. else goto block39;
  8549. block41:
  8550. if (eq? x 2) goto block38;
  8551. else goto block39;
  8552. block38:
  8553. return (+ y 2);
  8554. block39:
  8555. return (+ y 10);
  8556. \end{lstlisting}
  8557. \end{minipage}
  8558. \end{tabular}
  8559. \fi}
  8560. {\if\edition\pythonEd
  8561. \begin{tabular}{lll}
  8562. \begin{minipage}{0.4\textwidth}
  8563. % cond_test_41.rkt
  8564. \begin{lstlisting}
  8565. x = input_int()
  8566. y = input_int()
  8567. print(y + 2 \
  8568. if (x == 0 \
  8569. if x < 1 \
  8570. else x == 2) \
  8571. else y + 10)
  8572. \end{lstlisting}
  8573. \end{minipage}
  8574. &
  8575. $\Rightarrow$
  8576. &
  8577. \begin{minipage}{0.55\textwidth}
  8578. \begin{lstlisting}
  8579. start:
  8580. x = input_int()
  8581. y = input_int()
  8582. if x < 1:
  8583. goto block_4
  8584. else:
  8585. goto block_5
  8586. block_4:
  8587. if x == 0:
  8588. goto block_2
  8589. else:
  8590. goto block_3
  8591. block_5:
  8592. if x == 2:
  8593. goto block_2
  8594. else:
  8595. goto block_3
  8596. block_2:
  8597. tmp_0 = y + 2
  8598. goto block_1
  8599. block_3:
  8600. tmp_0 = y + 10
  8601. goto block_1
  8602. block_1:
  8603. print(tmp_0)
  8604. return 0
  8605. \end{lstlisting}
  8606. \end{minipage}
  8607. \end{tabular}
  8608. \fi}
  8609. \caption{Translation from \LangIf{} to \LangCIf{}
  8610. via the improved \code{explicate\_control}.}
  8611. \label{fig:explicate-control-challenge}
  8612. \end{figure}
  8613. %% Recall that in the example output of \code{explicate\_control} in
  8614. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8615. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8616. %% block. The first goal of this challenge assignment is to remove those
  8617. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8618. %% \code{explicate\_control} on the left and shows the result of bypassing
  8619. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8620. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8621. %% \code{block55}. The optimized code on the right of
  8622. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8623. %% \code{then} branch jumping directly to \code{block55}. The story is
  8624. %% similar for the \code{else} branch, as well as for the two branches in
  8625. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8626. %% have been optimized in this way, there are no longer any jumps to
  8627. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8628. %% \begin{figure}[tbp]
  8629. %% \begin{tabular}{lll}
  8630. %% \begin{minipage}{0.4\textwidth}
  8631. %% \begin{lstlisting}
  8632. %% block62:
  8633. %% tmp54 = (read);
  8634. %% if (eq? tmp54 2) then
  8635. %% goto block59;
  8636. %% else
  8637. %% goto block60;
  8638. %% block61:
  8639. %% tmp53 = (read);
  8640. %% if (eq? tmp53 0) then
  8641. %% goto block57;
  8642. %% else
  8643. %% goto block58;
  8644. %% block60:
  8645. %% goto block56;
  8646. %% block59:
  8647. %% goto block55;
  8648. %% block58:
  8649. %% goto block56;
  8650. %% block57:
  8651. %% goto block55;
  8652. %% block56:
  8653. %% return (+ 700 77);
  8654. %% block55:
  8655. %% return (+ 10 32);
  8656. %% start:
  8657. %% tmp52 = (read);
  8658. %% if (eq? tmp52 1) then
  8659. %% goto block61;
  8660. %% else
  8661. %% goto block62;
  8662. %% \end{lstlisting}
  8663. %% \end{minipage}
  8664. %% &
  8665. %% $\Rightarrow$
  8666. %% &
  8667. %% \begin{minipage}{0.55\textwidth}
  8668. %% \begin{lstlisting}
  8669. %% block62:
  8670. %% tmp54 = (read);
  8671. %% if (eq? tmp54 2) then
  8672. %% goto block55;
  8673. %% else
  8674. %% goto block56;
  8675. %% block61:
  8676. %% tmp53 = (read);
  8677. %% if (eq? tmp53 0) then
  8678. %% goto block55;
  8679. %% else
  8680. %% goto block56;
  8681. %% block56:
  8682. %% return (+ 700 77);
  8683. %% block55:
  8684. %% return (+ 10 32);
  8685. %% start:
  8686. %% tmp52 = (read);
  8687. %% if (eq? tmp52 1) then
  8688. %% goto block61;
  8689. %% else
  8690. %% goto block62;
  8691. %% \end{lstlisting}
  8692. %% \end{minipage}
  8693. %% \end{tabular}
  8694. %% \caption{Optimize jumps by removing trivial blocks.}
  8695. %% \label{fig:optimize-jumps}
  8696. %% \end{figure}
  8697. %% The name of this pass is \code{optimize-jumps}. We recommend
  8698. %% implementing this pass in two phases. The first phrase builds a hash
  8699. %% table that maps labels to possibly improved labels. The second phase
  8700. %% changes the target of each \code{goto} to use the improved label. If
  8701. %% the label is for a trivial block, then the hash table should map the
  8702. %% label to the first non-trivial block that can be reached from this
  8703. %% label by jumping through trivial blocks. If the label is for a
  8704. %% non-trivial block, then the hash table should map the label to itself;
  8705. %% we do not want to change jumps to non-trivial blocks.
  8706. %% The first phase can be accomplished by constructing an empty hash
  8707. %% table, call it \code{short-cut}, and then iterating over the control
  8708. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8709. %% then update the hash table, mapping the block's source to the target
  8710. %% of the \code{goto}. Also, the hash table may already have mapped some
  8711. %% labels to the block's source, to you must iterate through the hash
  8712. %% table and update all of those so that they instead map to the target
  8713. %% of the \code{goto}.
  8714. %% For the second phase, we recommend iterating through the $\Tail$ of
  8715. %% each block in the program, updating the target of every \code{goto}
  8716. %% according to the mapping in \code{short-cut}.
  8717. \begin{exercise}\normalfont
  8718. Implement the improvements to the \code{explicate\_control} pass.
  8719. Check that it removes trivial blocks in a few example programs. Then
  8720. check that your compiler still passes all of your tests.
  8721. \end{exercise}
  8722. \subsection{Remove Jumps}
  8723. There is an opportunity for removing jumps that is apparent in the
  8724. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8725. ends with a jump to \code{block7953} and there are no other jumps to
  8726. \code{block7953} in the rest of the program. In this situation we can
  8727. avoid the runtime overhead of this jump by merging \code{block7953}
  8728. into the preceding block, in this case the \code{start} block.
  8729. Figure~\ref{fig:remove-jumps} shows the output of
  8730. \code{select\_instructions} on the left and the result of this
  8731. optimization on the right.
  8732. \begin{figure}[tbp]
  8733. {\if\edition\racketEd
  8734. \begin{tabular}{lll}
  8735. \begin{minipage}{0.5\textwidth}
  8736. % cond_test_20.rkt
  8737. \begin{lstlisting}
  8738. start:
  8739. callq read_int
  8740. movq %rax, tmp7951
  8741. cmpq $1, tmp7951
  8742. je block7952
  8743. jmp block7953
  8744. block7953:
  8745. movq $0, %rax
  8746. jmp conclusion
  8747. block7952:
  8748. movq $42, %rax
  8749. jmp conclusion
  8750. \end{lstlisting}
  8751. \end{minipage}
  8752. &
  8753. $\Rightarrow\qquad$
  8754. \begin{minipage}{0.4\textwidth}
  8755. \begin{lstlisting}
  8756. start:
  8757. callq read_int
  8758. movq %rax, tmp7951
  8759. cmpq $1, tmp7951
  8760. je block7952
  8761. movq $0, %rax
  8762. jmp conclusion
  8763. block7952:
  8764. movq $42, %rax
  8765. jmp conclusion
  8766. \end{lstlisting}
  8767. \end{minipage}
  8768. \end{tabular}
  8769. \fi}
  8770. {\if\edition\pythonEd
  8771. \begin{tabular}{lll}
  8772. \begin{minipage}{0.5\textwidth}
  8773. % cond_test_20.rkt
  8774. \begin{lstlisting}
  8775. start:
  8776. callq read_int
  8777. movq %rax, tmp_0
  8778. cmpq 1, tmp_0
  8779. je block_3
  8780. jmp block_4
  8781. block_3:
  8782. movq 42, tmp_1
  8783. jmp block_2
  8784. block_4:
  8785. movq 0, tmp_1
  8786. jmp block_2
  8787. block_2:
  8788. movq tmp_1, %rdi
  8789. callq print_int
  8790. movq 0, %rax
  8791. jmp conclusion
  8792. \end{lstlisting}
  8793. \end{minipage}
  8794. &
  8795. $\Rightarrow\qquad$
  8796. \begin{minipage}{0.4\textwidth}
  8797. \begin{lstlisting}
  8798. start:
  8799. callq read_int
  8800. movq %rax, tmp_0
  8801. cmpq 1, tmp_0
  8802. je block_3
  8803. movq 0, tmp_1
  8804. jmp block_2
  8805. block_3:
  8806. movq 42, tmp_1
  8807. jmp block_2
  8808. block_2:
  8809. movq tmp_1, %rdi
  8810. callq print_int
  8811. movq 0, %rax
  8812. jmp conclusion
  8813. \end{lstlisting}
  8814. \end{minipage}
  8815. \end{tabular}
  8816. \fi}
  8817. \caption{Merging basic blocks by removing unnecessary jumps.}
  8818. \label{fig:remove-jumps}
  8819. \end{figure}
  8820. \begin{exercise}\normalfont
  8821. %
  8822. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8823. into their preceding basic block, when there is only one preceding
  8824. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8825. %
  8826. {\if\edition\racketEd
  8827. In the \code{run-tests.rkt} script, add the following entry to the
  8828. list of \code{passes} between \code{allocate\_registers}
  8829. and \code{patch\_instructions}.
  8830. \begin{lstlisting}
  8831. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8832. \end{lstlisting}
  8833. \fi}
  8834. %
  8835. Run the script to test your compiler.
  8836. %
  8837. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8838. blocks on several test programs.
  8839. \end{exercise}
  8840. \section{Further Reading}
  8841. \label{sec:cond-further-reading}
  8842. The algorithm for the \code{explicate\_control} pass is based on the
  8843. \code{explose-basic-blocks} pass in the course notes of
  8844. \citet{Dybvig:2010aa}.
  8845. %
  8846. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8847. \citet{Appel:2003fk}, and is related to translations into continuation
  8848. passing
  8849. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8850. %
  8851. The treatment of conditionals in the \code{explicate\_control} pass is
  8852. similar to short-cut boolean
  8853. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8854. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8855. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8856. \chapter{Loops and Dataflow Analysis}
  8857. \label{ch:Lwhile}
  8858. % TODO: define R'_8
  8859. % TODO: multi-graph
  8860. {\if\edition\racketEd
  8861. %
  8862. In this chapter we study two features that are the hallmarks of
  8863. imperative programming languages: loops and assignments to local
  8864. variables. The following example demonstrates these new features by
  8865. computing the sum of the first five positive integers.
  8866. % similar to loop_test_1.rkt
  8867. \begin{lstlisting}
  8868. (let ([sum 0])
  8869. (let ([i 5])
  8870. (begin
  8871. (while (> i 0)
  8872. (begin
  8873. (set! sum (+ sum i))
  8874. (set! i (- i 1))))
  8875. sum)))
  8876. \end{lstlisting}
  8877. The \code{while} loop consists of a condition and a
  8878. body\footnote{The \code{while} loop in particular is not a built-in
  8879. feature of the Racket language, but Racket includes many looping
  8880. constructs and it is straightforward to define \code{while} as a
  8881. macro.}. The body is evaluated repeatedly so long as the condition
  8882. remains true.
  8883. %
  8884. The \code{set!} consists of a variable and a right-hand-side
  8885. expression. The \code{set!} updates value of the variable to the
  8886. value of the right-hand-side.
  8887. %
  8888. The primary purpose of both the \code{while} loop and \code{set!} is
  8889. to cause side effects, so they do not have a meaningful result
  8890. value. Instead their result is the \code{\#<void>} value. The
  8891. expression \code{(void)} is an explicit way to create the
  8892. \code{\#<void>} value and it has type \code{Void}. The
  8893. \code{\#<void>} value can be passed around just like other values
  8894. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8895. compared for equality with another \code{\#<void>} value. However,
  8896. there are no other operations specific to the the \code{\#<void>}
  8897. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8898. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8899. \code{\#f} otherwise.
  8900. %
  8901. \footnote{Racket's \code{Void} type corresponds to what is called the
  8902. \code{Unit} type in the programming languages literature. Racket's
  8903. \code{Void} type is inhabited by a single value \code{\#<void>}
  8904. which corresponds to \code{unit} or \code{()} in the
  8905. literature~\citep{Pierce:2002hj}.}.
  8906. %
  8907. With the addition of side-effecting features such as \code{while} loop
  8908. and \code{set!}, it is helpful to also include in a language feature
  8909. for sequencing side effects: the \code{begin} expression. It consists
  8910. of one or more subexpressions that are evaluated left-to-right.
  8911. %
  8912. \fi}
  8913. {\if\edition\pythonEd
  8914. %
  8915. In this chapter we study loops, one of the hallmarks of imperative
  8916. programming languages. The following example demonstrates the
  8917. \code{while} loop by computing the sum of the first five positive
  8918. integers.
  8919. \begin{lstlisting}
  8920. sum = 0
  8921. i = 5
  8922. while i > 0:
  8923. sum = sum + i
  8924. i = i - 1
  8925. print(sum)
  8926. \end{lstlisting}
  8927. The \code{while} loop consists of a condition expression and a body (a
  8928. sequence of statements). The body is evaluated repeatedly so long as
  8929. the condition remains true.
  8930. %
  8931. \fi}
  8932. \section{The \LangLoop{} Language}
  8933. \newcommand{\LwhileGrammarRacket}{
  8934. \begin{array}{lcl}
  8935. \Type &::=& \key{Void}\\
  8936. \Exp &::=& \CSETBANG{\Var}{\Exp}
  8937. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8938. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  8939. \end{array}
  8940. }
  8941. \newcommand{\LwhileASTRacket}{
  8942. \begin{array}{lcl}
  8943. \Type &::=& \key{Void}\\
  8944. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  8945. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  8946. \end{array}
  8947. }
  8948. \newcommand{\LwhileGrammarPython}{
  8949. \begin{array}{rcl}
  8950. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  8951. \end{array}
  8952. }
  8953. \newcommand{\LwhileASTPython}{
  8954. \begin{array}{lcl}
  8955. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  8956. \end{array}
  8957. }
  8958. \begin{figure}[tp]
  8959. \centering
  8960. \fbox{
  8961. \begin{minipage}{0.96\textwidth}
  8962. \small
  8963. {\if\edition\racketEd
  8964. \[
  8965. \begin{array}{l}
  8966. \gray{\LintGrammarRacket{}} \\ \hline
  8967. \gray{\LvarGrammarRacket{}} \\ \hline
  8968. \gray{\LifGrammarRacket{}} \\ \hline
  8969. \LwhileGrammarRacket \\
  8970. \begin{array}{lcl}
  8971. \LangLoopM{} &::=& \Exp
  8972. \end{array}
  8973. \end{array}
  8974. \]
  8975. \fi}
  8976. {\if\edition\pythonEd
  8977. \[
  8978. \begin{array}{l}
  8979. \gray{\LintGrammarPython} \\ \hline
  8980. \gray{\LvarGrammarPython} \\ \hline
  8981. \gray{\LifGrammarPython} \\ \hline
  8982. \LwhileGrammarPython \\
  8983. \begin{array}{rcl}
  8984. \LangLoopM{} &::=& \Stmt^{*}
  8985. \end{array}
  8986. \end{array}
  8987. \]
  8988. \fi}
  8989. \end{minipage}
  8990. }
  8991. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  8992. \label{fig:Lwhile-concrete-syntax}
  8993. \end{figure}
  8994. \begin{figure}[tp]
  8995. \centering
  8996. \fbox{
  8997. \begin{minipage}{0.96\textwidth}
  8998. \small
  8999. {\if\edition\racketEd
  9000. \[
  9001. \begin{array}{l}
  9002. \gray{\LintOpAST} \\ \hline
  9003. \gray{\LvarASTRacket{}} \\ \hline
  9004. \gray{\LifASTRacket{}} \\ \hline
  9005. \LwhileASTRacket{} \\
  9006. \begin{array}{lcl}
  9007. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9008. \end{array}
  9009. \end{array}
  9010. \]
  9011. \fi}
  9012. {\if\edition\pythonEd
  9013. \[
  9014. \begin{array}{l}
  9015. \gray{\LintASTPython} \\ \hline
  9016. \gray{\LvarASTPython} \\ \hline
  9017. \gray{\LifASTPython} \\ \hline
  9018. \LwhileASTPython \\
  9019. \begin{array}{lcl}
  9020. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9021. \end{array}
  9022. \end{array}
  9023. \]
  9024. \fi}
  9025. \end{minipage}
  9026. }
  9027. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9028. \label{fig:Lwhile-syntax}
  9029. \end{figure}
  9030. The concrete syntax of \LangLoop{} is defined in
  9031. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9032. in Figure~\ref{fig:Lwhile-syntax}.
  9033. %
  9034. The definitional interpreter for \LangLoop{} is shown in
  9035. Figure~\ref{fig:interp-Rwhile}.
  9036. %
  9037. {\if\edition\racketEd
  9038. %
  9039. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9040. and \code{Void} and we make changes to the cases for \code{Var} and
  9041. \code{Let} regarding variables. To support assignment to variables and
  9042. to make their lifetimes indefinite (see the second example in
  9043. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9044. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9045. value.
  9046. %
  9047. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9048. variable in the environment to obtain a boxed value and then we change
  9049. it using \code{set-box!} to the result of evaluating the right-hand
  9050. side. The result value of a \code{SetBang} is \code{void}.
  9051. %
  9052. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9053. if the result is true, 2) evaluate the body.
  9054. The result value of a \code{while} loop is also \code{void}.
  9055. %
  9056. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9057. subexpressions \itm{es} for their effects and then evaluates
  9058. and returns the result from \itm{body}.
  9059. %
  9060. The $\VOID{}$ expression produces the \code{void} value.
  9061. %
  9062. \fi}
  9063. {\if\edition\pythonEd
  9064. %
  9065. We add a new case for \code{While} in the \code{interp\_stmts}
  9066. function, where we repeatedly interpret the \code{body} so long as the
  9067. \code{test} expression remains true.
  9068. %
  9069. \fi}
  9070. \begin{figure}[tbp]
  9071. {\if\edition\racketEd
  9072. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9073. (define interp-Rwhile_class
  9074. (class interp-Rany_class
  9075. (super-new)
  9076. (define/override ((interp-exp env) e)
  9077. (define recur (interp-exp env))
  9078. (match e
  9079. [(SetBang x rhs)
  9080. (set-box! (lookup x env) (recur rhs))]
  9081. [(WhileLoop cnd body)
  9082. (define (loop)
  9083. (cond [(recur cnd) (recur body) (loop)]
  9084. [else (void)]))
  9085. (loop)]
  9086. [(Begin es body)
  9087. (for ([e es]) (recur e))
  9088. (recur body)]
  9089. [(Void) (void)]
  9090. [else ((super interp-exp env) e)]))
  9091. ))
  9092. (define (interp-Rwhile p)
  9093. (send (new interp-Rwhile_class) interp-program p))
  9094. \end{lstlisting}
  9095. \fi}
  9096. {\if\edition\pythonEd
  9097. \begin{lstlisting}
  9098. class InterpLwhile(InterpLif):
  9099. def interp_stmts(self, ss, env):
  9100. if len(ss) == 0:
  9101. return
  9102. match ss[0]:
  9103. case While(test, body, []):
  9104. while self.interp_exp(test, env):
  9105. self.interp_stmts(body, env)
  9106. return self.interp_stmts(ss[1:], env)
  9107. case _:
  9108. return super().interp_stmts(ss, env)
  9109. \end{lstlisting}
  9110. \fi}
  9111. \caption{Interpreter for \LangLoop{}.}
  9112. \label{fig:interp-Rwhile}
  9113. \end{figure}
  9114. The type checker for \LangLoop{} is defined in
  9115. Figure~\ref{fig:type-check-Rwhile}.
  9116. %
  9117. {\if\edition\racketEd
  9118. %
  9119. For \LangLoop{} we add a type named \code{Void} and the only value of
  9120. this type is the \code{void} value.
  9121. %
  9122. The type checking of the \code{SetBang} expression requires the type of
  9123. the variable and the right-hand-side to agree. The result type is
  9124. \code{Void}. For \code{while}, the condition must be a
  9125. \code{Boolean}. The result type is also \code{Void}. For
  9126. \code{Begin}, the result type is the type of its last subexpression.
  9127. %
  9128. \fi}
  9129. %
  9130. {\if\edition\pythonEd
  9131. %
  9132. A \code{while} loop is well typed if the type of the \code{test}
  9133. expression is \code{bool} and the statements in the \code{body} are
  9134. well typed.
  9135. %
  9136. \fi}
  9137. \begin{figure}[tbp]
  9138. {\if\edition\racketEd
  9139. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9140. (define type-check-Rwhile_class
  9141. (class type-check-Rany_class
  9142. (super-new)
  9143. (inherit check-type-equal?)
  9144. (define/override (type-check-exp env)
  9145. (lambda (e)
  9146. (define recur (type-check-exp env))
  9147. (match e
  9148. [(SetBang x rhs)
  9149. (define-values (rhs^ rhsT) (recur rhs))
  9150. (define varT (dict-ref env x))
  9151. (check-type-equal? rhsT varT e)
  9152. (values (SetBang x rhs^) 'Void)]
  9153. [(WhileLoop cnd body)
  9154. (define-values (cnd^ Tc) (recur cnd))
  9155. (check-type-equal? Tc 'Boolean e)
  9156. (define-values (body^ Tbody) ((type-check-exp env) body))
  9157. (values (WhileLoop cnd^ body^) 'Void)]
  9158. [(Begin es body)
  9159. (define-values (es^ ts)
  9160. (for/lists (l1 l2) ([e es]) (recur e)))
  9161. (define-values (body^ Tbody) (recur body))
  9162. (values (Begin es^ body^) Tbody)]
  9163. [else ((super type-check-exp env) e)])))
  9164. ))
  9165. (define (type-check-Rwhile p)
  9166. (send (new type-check-Rwhile_class) type-check-program p))
  9167. \end{lstlisting}
  9168. \fi}
  9169. {\if\edition\pythonEd
  9170. \begin{lstlisting}
  9171. class TypeCheckLwhile(TypeCheckLif):
  9172. def type_check_stmts(self, ss, env):
  9173. if len(ss) == 0:
  9174. return
  9175. match ss[0]:
  9176. case While(test, body, []):
  9177. test_t = self.type_check_exp(test, env)
  9178. check_type_equal(bool, test_t, test)
  9179. body_t = self.type_check_stmts(body, env)
  9180. return self.type_check_stmts(ss[1:], env)
  9181. case _:
  9182. return super().type_check_stmts(ss, env)
  9183. \end{lstlisting}
  9184. \fi}
  9185. \caption{Type checker for the \LangLoop{} language.}
  9186. \label{fig:type-check-Rwhile}
  9187. \end{figure}
  9188. {\if\edition\racketEd
  9189. %
  9190. At first glance, the translation of these language features to x86
  9191. seems straightforward because the \LangCIf{} intermediate language
  9192. already supports all of the ingredients that we need: assignment,
  9193. \code{goto}, conditional branching, and sequencing. However, there are
  9194. complications that arise which we discuss in the next section. After
  9195. that we introduce the changes necessary to the existing passes.
  9196. %
  9197. \fi}
  9198. {\if\edition\pythonEd
  9199. %
  9200. At first glance, the translation of \code{while} loops to x86 seems
  9201. straightforward because the \LangCIf{} intermediate language already
  9202. supports \code{goto} and conditional branching. However, there are
  9203. complications that arise which we discuss in the next section. After
  9204. that we introduce the changes necessary to the existing passes.
  9205. %
  9206. \fi}
  9207. \section{Cyclic Control Flow and Dataflow Analysis}
  9208. \label{sec:dataflow-analysis}
  9209. Up until this point the control-flow graphs of the programs generated
  9210. in \code{explicate\_control} were guaranteed to be acyclic. However,
  9211. each \code{while} loop introduces a cycle in the control-flow graph.
  9212. But does that matter?
  9213. %
  9214. Indeed it does. Recall that for register allocation, the compiler
  9215. performs liveness analysis to determine which variables can share the
  9216. same register. To accomplish this we analyzed the control-flow graph
  9217. in reverse topological order
  9218. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9219. only well-defined for acyclic graphs.
  9220. Let us return to the example of computing the sum of the first five
  9221. positive integers. Here is the program after instruction selection but
  9222. before register allocation.
  9223. \begin{center}
  9224. {\if\edition\racketEd
  9225. \begin{minipage}{0.45\textwidth}
  9226. \begin{lstlisting}
  9227. (define (main) : Integer
  9228. mainstart:
  9229. movq $0, sum
  9230. movq $5, i
  9231. jmp block5
  9232. block5:
  9233. movq i, tmp3
  9234. cmpq tmp3, $0
  9235. jl block7
  9236. jmp block8
  9237. \end{lstlisting}
  9238. \end{minipage}
  9239. \begin{minipage}{0.45\textwidth}
  9240. \begin{lstlisting}
  9241. block7:
  9242. addq i, sum
  9243. movq $1, tmp4
  9244. negq tmp4
  9245. addq tmp4, i
  9246. jmp block5
  9247. block8:
  9248. movq $27, %rax
  9249. addq sum, %rax
  9250. jmp mainconclusion
  9251. )
  9252. \end{lstlisting}
  9253. \end{minipage}
  9254. \fi}
  9255. {\if\edition\pythonEd
  9256. \begin{minipage}{0.45\textwidth}
  9257. \begin{lstlisting}
  9258. mainstart:
  9259. movq $0, sum
  9260. movq $5, i
  9261. jmp block5
  9262. block5:
  9263. cmpq $0, i
  9264. jg block7
  9265. jmp block8
  9266. \end{lstlisting}
  9267. \end{minipage}
  9268. \begin{minipage}{0.45\textwidth}
  9269. \begin{lstlisting}
  9270. block7:
  9271. addq i, sum
  9272. subq $1, i
  9273. jmp block5
  9274. block8:
  9275. movq sum, %rdi
  9276. callq print_int
  9277. movq $0, %rax
  9278. jmp mainconclusion
  9279. \end{lstlisting}
  9280. \end{minipage}
  9281. \fi}
  9282. \end{center}
  9283. Recall that liveness analysis works backwards, starting at the end
  9284. of each function. For this example we could start with \code{block8}
  9285. because we know what is live at the beginning of the conclusion,
  9286. just \code{rax} and \code{rsp}. So the live-before set
  9287. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9288. %
  9289. Next we might try to analyze \code{block5} or \code{block7}, but
  9290. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9291. we are stuck.
  9292. The way out of this impasse is to realize that we can compute an
  9293. under-approximation of the live-before set by starting with empty
  9294. live-after sets. By \emph{under-approximation}, we mean that the set
  9295. only contains variables that are live for some execution of the
  9296. program, but the set may be missing some variables. Next, the
  9297. under-approximations for each block can be improved by 1) updating the
  9298. live-after set for each block using the approximate live-before sets
  9299. from the other blocks and 2) perform liveness analysis again on each
  9300. block. In fact, by iterating this process, the under-approximations
  9301. eventually become the correct solutions!
  9302. %
  9303. This approach of iteratively analyzing a control-flow graph is
  9304. applicable to many static analysis problems and goes by the name
  9305. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9306. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9307. Washington.
  9308. Let us apply this approach to the above example. We use the empty set
  9309. for the initial live-before set for each block. Let $m_0$ be the
  9310. following mapping from label names to sets of locations (variables and
  9311. registers).
  9312. \begin{center}
  9313. \begin{lstlisting}
  9314. mainstart: {}, block5: {}, block7: {}, block8: {}
  9315. \end{lstlisting}
  9316. \end{center}
  9317. Using the above live-before approximations, we determine the
  9318. live-after for each block and then apply liveness analysis to each
  9319. block. This produces our next approximation $m_1$ of the live-before
  9320. sets.
  9321. \begin{center}
  9322. \begin{lstlisting}
  9323. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9324. \end{lstlisting}
  9325. \end{center}
  9326. For the second round, the live-after for \code{mainstart} is the
  9327. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9328. liveness analysis for \code{mainstart} computes the empty set. The
  9329. live-after for \code{block5} is the union of the live-before sets for
  9330. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9331. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9332. sum\}}. The live-after for \code{block7} is the live-before for
  9333. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9334. So the liveness analysis for \code{block7} remains \code{\{i,
  9335. sum\}}. Together these yield the following approximation $m_2$ of
  9336. the live-before sets.
  9337. \begin{center}
  9338. \begin{lstlisting}
  9339. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9340. \end{lstlisting}
  9341. \end{center}
  9342. In the preceding iteration, only \code{block5} changed, so we can
  9343. limit our attention to \code{mainstart} and \code{block7}, the two
  9344. blocks that jump to \code{block5}. As a result, the live-before sets
  9345. for \code{mainstart} and \code{block7} are updated to include
  9346. \code{rsp}, yielding the following approximation $m_3$.
  9347. \begin{center}
  9348. \begin{lstlisting}
  9349. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9350. \end{lstlisting}
  9351. \end{center}
  9352. Because \code{block7} changed, we analyze \code{block5} once more, but
  9353. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9354. our approximations have converged, so $m_3$ is the solution.
  9355. This iteration process is guaranteed to converge to a solution by the
  9356. Kleene Fixed-Point Theorem, a general theorem about functions on
  9357. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9358. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9359. elements, a least element $\bot$ (pronounced bottom), and a join
  9360. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9361. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9362. working with join semi-lattices.} When two elements are ordered $m_i
  9363. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9364. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9365. approximation than $m_i$. The bottom element $\bot$ represents the
  9366. complete lack of information, i.e., the worst approximation. The join
  9367. operator takes two lattice elements and combines their information,
  9368. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9369. bound}
  9370. A dataflow analysis typically involves two lattices: one lattice to
  9371. represent abstract states and another lattice that aggregates the
  9372. abstract states of all the blocks in the control-flow graph. For
  9373. liveness analysis, an abstract state is a set of locations. We form
  9374. the lattice $L$ by taking its elements to be sets of locations, the
  9375. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9376. set, and the join operator to be set union.
  9377. %
  9378. We form a second lattice $M$ by taking its elements to be mappings
  9379. from the block labels to sets of locations (elements of $L$). We
  9380. order the mappings point-wise, using the ordering of $L$. So given any
  9381. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9382. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9383. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9384. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9385. We can think of one iteration of liveness analysis applied to the
  9386. whole program as being a function $f$ on the lattice $M$. It takes a
  9387. mapping as input and computes a new mapping.
  9388. \[
  9389. f(m_i) = m_{i+1}
  9390. \]
  9391. Next let us think for a moment about what a final solution $m_s$
  9392. should look like. If we perform liveness analysis using the solution
  9393. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9394. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9395. \[
  9396. f(m_s) = m_s
  9397. \]
  9398. Furthermore, the solution should only include locations that are
  9399. forced to be there by performing liveness analysis on the program, so
  9400. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9401. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9402. monotone (better inputs produce better outputs), then the least fixed
  9403. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9404. chain} obtained by starting at $\bot$ and iterating $f$ as
  9405. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9406. \[
  9407. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9408. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9409. \]
  9410. When a lattice contains only finitely-long ascending chains, then
  9411. every Kleene chain tops out at some fixed point after some number of
  9412. iterations of $f$.
  9413. \[
  9414. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9415. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9416. \]
  9417. The liveness analysis is indeed a monotone function and the lattice
  9418. $M$ only has finitely-long ascending chains because there are only a
  9419. finite number of variables and blocks in the program. Thus we are
  9420. guaranteed that iteratively applying liveness analysis to all blocks
  9421. in the program will eventually produce the least fixed point solution.
  9422. Next let us consider dataflow analysis in general and discuss the
  9423. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9424. %
  9425. The algorithm has four parameters: the control-flow graph \code{G}, a
  9426. function \code{transfer} that applies the analysis to one block, the
  9427. \code{bottom} and \code{join} operator for the lattice of abstract
  9428. states. The \code{analyze\_dataflow} function is formulated as a
  9429. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9430. function come from the predecessor nodes in the control-flow
  9431. graph. However, liveness analysis is a \emph{backward} dataflow
  9432. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9433. function with the transpose of the control-flow graph.
  9434. The algorithm begins by creating the bottom mapping, represented by a
  9435. hash table. It then pushes all of the nodes in the control-flow graph
  9436. onto the work list (a queue). The algorithm repeats the \code{while}
  9437. loop as long as there are items in the work list. In each iteration, a
  9438. node is popped from the work list and processed. The \code{input} for
  9439. the node is computed by taking the join of the abstract states of all
  9440. the predecessor nodes. The \code{transfer} function is then applied to
  9441. obtain the \code{output} abstract state. If the output differs from
  9442. the previous state for this block, the mapping for this block is
  9443. updated and its successor nodes are pushed onto the work list.
  9444. \begin{figure}[tb]
  9445. {\if\edition\racketEd
  9446. \begin{lstlisting}
  9447. (define (analyze_dataflow G transfer bottom join)
  9448. (define mapping (make-hash))
  9449. (for ([v (in-vertices G)])
  9450. (dict-set! mapping v bottom))
  9451. (define worklist (make-queue))
  9452. (for ([v (in-vertices G)])
  9453. (enqueue! worklist v))
  9454. (define trans-G (transpose G))
  9455. (while (not (queue-empty? worklist))
  9456. (define node (dequeue! worklist))
  9457. (define input (for/fold ([state bottom])
  9458. ([pred (in-neighbors trans-G node)])
  9459. (join state (dict-ref mapping pred))))
  9460. (define output (transfer node input))
  9461. (cond [(not (equal? output (dict-ref mapping node)))
  9462. (dict-set! mapping node output)
  9463. (for ([v (in-neighbors G node)])
  9464. (enqueue! worklist v))]))
  9465. mapping)
  9466. \end{lstlisting}
  9467. \fi}
  9468. {\if\edition\pythonEd
  9469. \begin{lstlisting}
  9470. def analyze_dataflow(G, transfer, bottom, join):
  9471. trans_G = transpose(G)
  9472. mapping = dict((v, bottom) for v in G.vertices())
  9473. worklist = deque(G.vertices)
  9474. while worklist:
  9475. node = worklist.pop()
  9476. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9477. output = transfer(node, input)
  9478. if output != mapping[node]:
  9479. mapping[node] = output
  9480. worklist.extend(G.adjacent(node))
  9481. \end{lstlisting}
  9482. \fi}
  9483. \caption{Generic work list algorithm for dataflow analysis}
  9484. \label{fig:generic-dataflow}
  9485. \end{figure}
  9486. {\if\edition\racketEd
  9487. \section{Mutable Variables \& Remove Complex Operands}
  9488. There is a subtle interaction between the addition of \code{set!}, the
  9489. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9490. evaluation of Racket. Consider the following example.
  9491. \begin{lstlisting}
  9492. (let ([x 2])
  9493. (+ x (begin (set! x 40) x)))
  9494. \end{lstlisting}
  9495. The result of this program is \code{42} because the first read from
  9496. \code{x} produces \code{2} and the second produces \code{40}. However,
  9497. if we naively apply the \code{remove\_complex\_operands} pass to this
  9498. example we obtain the following program whose result is \code{80}!
  9499. \begin{lstlisting}
  9500. (let ([x 2])
  9501. (let ([tmp (begin (set! x 40) x)])
  9502. (+ x tmp)))
  9503. \end{lstlisting}
  9504. The problem is that, with mutable variables, the ordering between
  9505. reads and writes is important, and the
  9506. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9507. before the first read of \code{x}.
  9508. We recommend solving this problem by giving special treatment to reads
  9509. from mutable variables, that is, variables that occur on the left-hand
  9510. side of a \code{set!}. We mark each read from a mutable variable with
  9511. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9512. that the read operation is effectful in that it can produce different
  9513. results at different points in time. Let's apply this idea to the
  9514. following variation that also involves a variable that is not mutated.
  9515. % loop_test_24.rkt
  9516. \begin{lstlisting}
  9517. (let ([x 2])
  9518. (let ([y 0])
  9519. (+ y (+ x (begin (set! x 40) x)))))
  9520. \end{lstlisting}
  9521. We analyze the above program to discover that variable \code{x} is
  9522. mutable but \code{y} is not. We then transform the program as follows,
  9523. replacing each occurence of \code{x} with \code{(get! x)}.
  9524. \begin{lstlisting}
  9525. (let ([x 2])
  9526. (let ([y 0])
  9527. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9528. \end{lstlisting}
  9529. Now that we have a clear distinction between reads from mutable and
  9530. immutable variables, we can apply the \code{remove\_complex\_operands}
  9531. pass, where reads from immutable variables are still classified as
  9532. atomic expressions but reads from mutable variables are classified as
  9533. complex. Thus, \code{remove\_complex\_operands} yields the following
  9534. program.
  9535. \begin{lstlisting}
  9536. (let ([x 2])
  9537. (let ([y 0])
  9538. (+ y (let ([t1 (get! x)])
  9539. (let ([t2 (begin (set! x 40) (get! x))])
  9540. (+ t1 t2))))))
  9541. \end{lstlisting}
  9542. The temporary variable \code{t1} gets the value of \code{x} before the
  9543. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9544. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9545. do not generate a temporary variable for the occurence of \code{y}
  9546. because it's an immutable variable. We want to avoid such unnecessary
  9547. extra temporaries because they would needless increase the number of
  9548. variables, making it more likely for some of them to be spilled. The
  9549. result of this program is \code{42}, the same as the result prior to
  9550. \code{remove\_complex\_operands}.
  9551. The approach that we've sketched above requires only a small
  9552. modification to \code{remove\_complex\_operands} to handle
  9553. \code{get!}. However, it requires a new pass, called
  9554. \code{uncover-get!}, that we discuss in
  9555. Section~\ref{sec:uncover-get-bang}.
  9556. As an aside, this problematic interaction between \code{set!} and the
  9557. pass \code{remove\_complex\_operands} is particular to Racket and not
  9558. its predecessor, the Scheme language. The key difference is that
  9559. Scheme does not specify an order of evaluation for the arguments of an
  9560. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9561. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9562. would be correct results for the example program. Interestingly,
  9563. Racket is implemented on top of the Chez Scheme
  9564. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9565. presented in this section (using extra \code{let} bindings to control
  9566. the order of evaluation) is used in the translation from Racket to
  9567. Scheme~\citep{Flatt:2019tb}.
  9568. \fi} % racket
  9569. Having discussed the complications that arise from adding support for
  9570. assignment and loops, we turn to discussing the individual compilation
  9571. passes.
  9572. {\if\edition\racketEd
  9573. \section{Uncover \texttt{get!}}
  9574. \label{sec:uncover-get-bang}
  9575. The goal of this pass it to mark uses of mutable variables so that
  9576. \code{remove\_complex\_operands} can treat them as complex expressions
  9577. and thereby preserve their ordering relative to the side-effects in
  9578. other operands. So the first step is to collect all the mutable
  9579. variables. We recommend creating an auxilliary function for this,
  9580. named \code{collect-set!}, that recursively traverses expressions,
  9581. returning a set of all variables that occur on the left-hand side of a
  9582. \code{set!}. Here's an exerpt of its implementation.
  9583. \begin{center}
  9584. \begin{minipage}{\textwidth}
  9585. \begin{lstlisting}
  9586. (define (collect-set! e)
  9587. (match e
  9588. [(Var x) (set)]
  9589. [(Int n) (set)]
  9590. [(Let x rhs body)
  9591. (set-union (collect-set! rhs) (collect-set! body))]
  9592. [(SetBang var rhs)
  9593. (set-union (set var) (collect-set! rhs))]
  9594. ...))
  9595. \end{lstlisting}
  9596. \end{minipage}
  9597. \end{center}
  9598. By placing this pass after \code{uniquify}, we need not worry about
  9599. variable shadowing and our logic for \code{let} can remain simple, as
  9600. in the exerpt above.
  9601. The second step is to mark the occurences of the mutable variables
  9602. with the new \code{GetBang} AST node (\code{get!} in concrete
  9603. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9604. function, which takes two parameters: the set of mutable varaibles
  9605. \code{set!-vars}, and the expression \code{e} to be processed. The
  9606. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9607. mutable variable or leaves it alone if not.
  9608. \begin{center}
  9609. \begin{minipage}{\textwidth}
  9610. \begin{lstlisting}
  9611. (define ((uncover-get!-exp set!-vars) e)
  9612. (match e
  9613. [(Var x)
  9614. (if (set-member? set!-vars x)
  9615. (GetBang x)
  9616. (Var x))]
  9617. ...))
  9618. \end{lstlisting}
  9619. \end{minipage}
  9620. \end{center}
  9621. To wrap things up, define the \code{uncover-get!} function for
  9622. processing a whole program, using \code{collect-set!} to obtain the
  9623. set of mutable variables and then \code{uncover-get!-exp} to replace
  9624. their occurences with \code{GetBang}.
  9625. \fi}
  9626. \section{Remove Complex Operands}
  9627. \label{sec:rco-loop}
  9628. {\if\edition\racketEd
  9629. %
  9630. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9631. \code{while} are all complex expressions. The subexpressions of
  9632. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9633. %
  9634. \fi}
  9635. {\if\edition\pythonEd
  9636. %
  9637. The change needed for this pass is to add a case for the \code{while}
  9638. statement. The condition of a \code{while} loop is allowed to be a
  9639. complex expression, just like the condition of the \code{if}
  9640. statement.
  9641. %
  9642. \fi}
  9643. %
  9644. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9645. \LangLoopANF{} of this pass.
  9646. \newcommand{\LwhileMonadASTPython}{
  9647. \begin{array}{rcl}
  9648. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9649. \end{array}
  9650. }
  9651. \begin{figure}[tp]
  9652. \centering
  9653. \fbox{
  9654. \begin{minipage}{0.96\textwidth}
  9655. \small
  9656. {\if\edition\racketEd
  9657. \[
  9658. \begin{array}{rcl}
  9659. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} } \MID \VOID{} \\
  9660. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9661. &\MID& \GETBANG{\Var}
  9662. \MID \SETBANG{\Var}{\Exp} \\
  9663. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9664. \MID \WHILE{\Exp}{\Exp} \\
  9665. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9666. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9667. \end{array}
  9668. \]
  9669. \fi}
  9670. {\if\edition\pythonEd
  9671. \[
  9672. \begin{array}{l}
  9673. \gray{\LvarMonadASTPython} \\ \hline
  9674. \gray{\LifMonadASTPython} \\ \hline
  9675. \LwhileMonadASTPython \\
  9676. \begin{array}{rcl}
  9677. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9678. \end{array}
  9679. \end{array}
  9680. %% \begin{array}{rcl}
  9681. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9682. %% \Exp &::=& \Atm \MID \READ{} \\
  9683. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9684. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9685. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9686. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9687. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9688. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9689. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9690. %% \end{array}
  9691. \]
  9692. \fi}
  9693. \end{minipage}
  9694. }
  9695. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9696. \label{fig:Rwhile-anf-syntax}
  9697. \end{figure}
  9698. {\if\edition\racketEd
  9699. As usual, when a complex expression appears in a grammar position that
  9700. needs to be atomic, such as the argument of a primitive operator, we
  9701. must introduce a temporary variable and bind it to the complex
  9702. expression. This approach applies, unchanged, to handle the new
  9703. language forms. For example, in the following code there are two
  9704. \code{begin} expressions appearing as arguments to \code{+}. The
  9705. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9706. expressions have been bound to temporary variables. Recall that
  9707. \code{let} expressions in \LangLoopANF{} are allowed to have
  9708. arbitrary expressions in their right-hand-side expression, so it is
  9709. fine to place \code{begin} there.
  9710. \begin{center}
  9711. \begin{minipage}{\textwidth}
  9712. \begin{lstlisting}
  9713. (let ([x0 10])
  9714. (let ([y1 0])
  9715. (+ (+ (begin (set! y1 (read)) x0)
  9716. (begin (set! x0 (read)) y1))
  9717. x0)))
  9718. |$\Rightarrow$|
  9719. (let ([x0 10])
  9720. (let ([y1 0])
  9721. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9722. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9723. (let ([tmp4 (+ tmp2 tmp3)])
  9724. (+ tmp4 x0))))))
  9725. \end{lstlisting}
  9726. \end{minipage}
  9727. \end{center}
  9728. \fi}
  9729. \section{Explicate Control \racket{and \LangCLoop{}}}
  9730. \label{sec:explicate-loop}
  9731. \newcommand{\CloopASTRacket}{
  9732. \begin{array}{lcl}
  9733. \Atm &::=& \VOID \\
  9734. \Stmt &::=& \READ{}\\
  9735. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9736. \end{array}
  9737. }
  9738. {\if\edition\racketEd
  9739. Recall that in the \code{explicate\_control} pass we define one helper
  9740. function for each kind of position in the program. For the \LangVar{}
  9741. language of integers and variables we needed kinds of positions:
  9742. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9743. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9744. yet another kind of position: effect position. Except for the last
  9745. subexpression, the subexpressions inside a \code{begin} are evaluated
  9746. only for their effect. Their result values are discarded. We can
  9747. generate better code by taking this fact into account.
  9748. The output language of \code{explicate\_control} is \LangCLoop{}
  9749. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9750. \LangCIf{}. The only syntactic difference is that \code{read} may also
  9751. appear as a statement. The most significant difference between the
  9752. programs generated by \code{explicate\_control} in
  9753. Chapter~\ref{ch:Lif} versus \code{explicate\_control} in this chapter
  9754. is that the control-flow graphs of the later may contain cycles.
  9755. \begin{figure}[tp]
  9756. \fbox{
  9757. \begin{minipage}{0.96\textwidth}
  9758. \small
  9759. \[
  9760. \begin{array}{l}
  9761. \gray{\CvarASTRacket} \\ \hline
  9762. \gray{\CifASTRacket} \\ \hline
  9763. \CloopASTRacket \\
  9764. \begin{array}{lcl}
  9765. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9766. \end{array}
  9767. \end{array}
  9768. \]
  9769. \end{minipage}
  9770. }
  9771. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9772. \label{fig:c7-syntax}
  9773. \end{figure}
  9774. The new auxiliary function \code{explicate\_effect} takes an
  9775. expression (in an effect position) and a continuation. The function
  9776. returns a $\Tail$ that includes the generated code for the input
  9777. expression followed by the continuation. If the expression is
  9778. obviously pure, that is, never causes side effects, then the
  9779. expression can be removed, so the result is just the continuation.
  9780. %
  9781. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9782. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9783. the loop. Recursively process the \itm{body} (in effect position)
  9784. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9785. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9786. \itm{body'} as the then-branch and the continuation block as the
  9787. else-branch. The result should be added to the control-flow graph with
  9788. the label \itm{loop}. The result for the whole \code{while} loop is a
  9789. \code{goto} to the \itm{loop} label.
  9790. The auxiliary functions for tail, assignment, and predicate positions
  9791. need to be updated. The three new language forms, \code{while},
  9792. \code{set!}, and \code{begin}, can appear in assignment and tail
  9793. positions. Only \code{begin} may appear in predicate positions; the
  9794. other two have result type \code{Void}.
  9795. \fi}
  9796. %
  9797. {\if\edition\pythonEd
  9798. %
  9799. The output of this pass is the language \LangCIf{}. No new language
  9800. features are needed in the output because a \code{while} loop can be
  9801. expressed in terms of \code{goto} and \code{if} statements, which are
  9802. already in \LangCIf{}.
  9803. %
  9804. Add a case for the \code{while} statement to the
  9805. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9806. the condition expression.
  9807. %
  9808. \fi}
  9809. {\if\edition\racketEd
  9810. \section{Select Instructions}
  9811. \label{sec:select-instructions-loop}
  9812. Only three small additions are needed in the
  9813. \code{select\_instructions} pass to handle the changes to
  9814. \LangCLoop{}. That is, a call to
  9815. \racket{\code{read}}\python{\code{input\_int}} may appear as a
  9816. stand-alone statement instead of only appearing on the right-hand side
  9817. of an assignment statement. The code generation is nearly identical;
  9818. just leave off the instruction for moving the result into the
  9819. left-hand side.
  9820. \fi}
  9821. \section{Register Allocation}
  9822. \label{sec:register-allocation-loop}
  9823. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9824. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9825. which complicates the liveness analysis needed for register
  9826. allocation.
  9827. \subsection{Liveness Analysis}
  9828. \label{sec:liveness-analysis-r8}
  9829. We recommend using the generic \code{analyze\_dataflow} function that
  9830. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9831. perform liveness analysis, replacing the code in
  9832. \code{uncover\_live} that processed the basic blocks in topological
  9833. order (Section~\ref{sec:liveness-analysis-Lif}).
  9834. The \code{analyze\_dataflow} function has four parameters.
  9835. \begin{enumerate}
  9836. \item The first parameter \code{G} should be a directed graph from the
  9837. \racket{
  9838. \code{racket/graph} package (see the sidebar in
  9839. Section~\ref{sec:build-interference})}
  9840. \python{\code{graph.py} file in the support code}
  9841. that represents the
  9842. control-flow graph.
  9843. \item The second parameter \code{transfer} is a function that applies
  9844. liveness analysis to a basic block. It takes two parameters: the
  9845. label for the block to analyze and the live-after set for that
  9846. block. The transfer function should return the live-before set for
  9847. the block.
  9848. %
  9849. \racket{Also, as a side-effect, it should update the block's
  9850. $\itm{info}$ with the liveness information for each instruction.}
  9851. %
  9852. \python{Also, as a side-effect, it should update the live-before and
  9853. live-after sets for each instruction.}
  9854. %
  9855. To implement the \code{transfer} function, you should be able to
  9856. reuse the code you already have for analyzing basic blocks.
  9857. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9858. \code{bottom} and \code{join} for the lattice of abstract states,
  9859. i.e. sets of locations. The bottom of the lattice is the empty set
  9860. and the join operator is set union.
  9861. \end{enumerate}
  9862. \begin{figure}[p]
  9863. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9864. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9865. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9866. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9867. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9868. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9869. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9870. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9871. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9872. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9873. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9874. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9875. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9876. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9877. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9878. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9879. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9880. %% \path[->,bend left=15] (Rfun) edge [above] node
  9881. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9882. \path[->,bend left=15] (Rfun) edge [above] node
  9883. {\ttfamily\footnotesize shrink} (Rfun-2);
  9884. \path[->,bend left=15] (Rfun-2) edge [above] node
  9885. {\ttfamily\footnotesize uniquify} (F1-4);
  9886. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9887. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9888. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9889. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9890. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9891. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9892. %% \path[->,bend right=15] (F1-2) edge [above] node
  9893. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9894. %% \path[->,bend right=15] (F1-3) edge [above] node
  9895. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9896. \path[->,bend left=15] (F1-4) edge [above] node
  9897. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9898. \path[->,bend left=15] (F1-5) edge [right] node
  9899. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9900. \path[->,bend left=15] (C3-2) edge [left] node
  9901. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9902. \path[->,bend right=15] (x86-2) edge [left] node
  9903. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9904. \path[->,bend right=15] (x86-2-1) edge [below] node
  9905. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9906. \path[->,bend right=15] (x86-2-2) edge [left] node
  9907. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9908. \path[->,bend left=15] (x86-3) edge [above] node
  9909. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9910. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9911. \end{tikzpicture}
  9912. \caption{Diagram of the passes for \LangLoop{}.}
  9913. \label{fig:Rwhile-passes}
  9914. \end{figure}
  9915. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9916. for the compilation of \LangLoop{}.
  9917. % Further Reading: dataflow analysis
  9918. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9919. \chapter{Tuples and Garbage Collection}
  9920. \label{ch:Lvec}
  9921. \index{subject}{tuple}
  9922. \index{subject}{vector}
  9923. \index{subject}{allocate}
  9924. \index{subject}{heap allocate}
  9925. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9926. %% all the IR grammars are spelled out! \\ --Jeremy}
  9927. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9928. %% the root stack. \\ --Jeremy}
  9929. In this chapter we study the implementation of
  9930. tuples\racket{, called vectors in Racket}.
  9931. %
  9932. This language feature is the first to use the computer's
  9933. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9934. indefinite, that is, a tuple lives forever from the programmer's
  9935. viewpoint. Of course, from an implementer's viewpoint, it is important
  9936. to reclaim the space associated with a tuple when it is no longer
  9937. needed, which is why we also study \emph{garbage collection}
  9938. \index{garbage collection} techniques in this chapter.
  9939. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9940. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9941. language of Chapter~\ref{ch:Lwhile} with tuples.
  9942. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9943. copying live tuples back and forth between two halves of the heap. The
  9944. garbage collector requires coordination with the compiler so that it
  9945. can find all of the live tuples.
  9946. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9947. discuss the necessary changes and additions to the compiler passes,
  9948. including a new compiler pass named \code{expose\_allocation}.
  9949. \section{The \LangVec{} Language}
  9950. \label{sec:r3}
  9951. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  9952. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  9953. %
  9954. \racket{The \LangVec{} language includes the forms: \code{vector} for
  9955. creating a tuple, \code{vector-ref} for reading an element of a
  9956. tuple, \code{vector-set!} for writing to an element of a tuple, and
  9957. \code{vector-length} for obtaining the number of elements of a
  9958. tuple.}
  9959. %
  9960. \python{The \LangVec{} language adds 1) tuple creation via a
  9961. comma-separated list of expressions, 2) accessing an element of a
  9962. tuple with the square bracket notation, i.e., \code{t[n]} returns
  9963. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  9964. operator, and 4) obtaining the number of elements (the length) of a
  9965. tuple. In this chapter, we restrict access indices to constant
  9966. integers.}
  9967. %
  9968. The program below shows an example use of tuples. It creates a tuple
  9969. \code{t} containing the elements \code{40},
  9970. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  9971. contains just \code{2}. The element at index $1$ of \code{t} is
  9972. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  9973. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  9974. to which we add \code{2}, the element at index $0$ of the tuple. So
  9975. the result of the program is \code{42}.
  9976. %
  9977. {\if\edition\racketEd
  9978. \begin{lstlisting}
  9979. (let ([t (vector 40 #t (vector 2))])
  9980. (if (vector-ref t 1)
  9981. (+ (vector-ref t 0)
  9982. (vector-ref (vector-ref t 2) 0))
  9983. 44))
  9984. \end{lstlisting}
  9985. \fi}
  9986. {\if\edition\pythonEd
  9987. \begin{lstlisting}
  9988. t = 40, True, (2,)
  9989. print( t[0] + t[2][0] if t[1] else 44 )
  9990. \end{lstlisting}
  9991. \fi}
  9992. \newcommand{\LtupGrammarRacket}{
  9993. \begin{array}{lcl}
  9994. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9995. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  9996. \MID \LP\key{vector-length}\;\Exp\RP \\
  9997. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9998. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  9999. \end{array}
  10000. }
  10001. \newcommand{\LtupASTRacket}{
  10002. \begin{array}{lcl}
  10003. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  10004. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10005. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10006. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10007. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10008. \end{array}
  10009. }
  10010. \newcommand{\LtupGrammarPython}{
  10011. \begin{array}{rcl}
  10012. \itm{cmp} &::= & \key{is} \\
  10013. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10014. \end{array}
  10015. }
  10016. \newcommand{\LtupASTPython}{
  10017. \begin{array}{lcl}
  10018. \itm{cmp} &::= & \code{Is()} \\
  10019. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10020. &\MID& \LEN{\Exp}
  10021. \end{array}
  10022. }
  10023. \begin{figure}[tbp]
  10024. \centering
  10025. \fbox{
  10026. \begin{minipage}{0.96\textwidth}
  10027. {\if\edition\racketEd
  10028. \[
  10029. \begin{array}{l}
  10030. \gray{\LintGrammarRacket{}} \\ \hline
  10031. \gray{\LvarGrammarRacket{}} \\ \hline
  10032. \gray{\LifGrammarRacket{}} \\ \hline
  10033. \gray{\LwhileGrammarRacket} \\ \hline
  10034. \LtupGrammarRacket \\
  10035. \begin{array}{lcl}
  10036. \LangVecM{} &::=& \Exp
  10037. \end{array}
  10038. \end{array}
  10039. \]
  10040. \fi}
  10041. {\if\edition\pythonEd
  10042. \[
  10043. \begin{array}{l}
  10044. \gray{\LintGrammarPython{}} \\ \hline
  10045. \gray{\LvarGrammarPython{}} \\ \hline
  10046. \gray{\LifGrammarPython{}} \\ \hline
  10047. \gray{\LwhileGrammarPython} \\ \hline
  10048. \LtupGrammarPython \\
  10049. \begin{array}{rcl}
  10050. \LangVecM{} &::=& \Stmt^{*}
  10051. \end{array}
  10052. \end{array}
  10053. \]
  10054. \fi}
  10055. \end{minipage}
  10056. }
  10057. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10058. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10059. \label{fig:Lvec-concrete-syntax}
  10060. \end{figure}
  10061. \begin{figure}[tp]
  10062. \centering
  10063. \fbox{
  10064. \begin{minipage}{0.96\textwidth}
  10065. {\if\edition\racketEd
  10066. \[
  10067. \begin{array}{l}
  10068. \gray{\LintOpAST} \\ \hline
  10069. \gray{\LvarASTRacket{}} \\ \hline
  10070. \gray{\LifASTRacket{}} \\ \hline
  10071. \gray{\LwhileASTRacket{}} \\ \hline
  10072. \LtupASTRacket{} \\
  10073. \begin{array}{lcl}
  10074. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10075. \end{array}
  10076. \end{array}
  10077. \]
  10078. \fi}
  10079. {\if\edition\pythonEd
  10080. \[
  10081. \begin{array}{l}
  10082. \gray{\LintASTPython} \\ \hline
  10083. \gray{\LvarASTPython} \\ \hline
  10084. \gray{\LifASTPython} \\ \hline
  10085. \gray{\LwhileASTPython} \\ \hline
  10086. \LtupASTPython \\
  10087. \begin{array}{lcl}
  10088. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10089. \end{array}
  10090. \end{array}
  10091. \]
  10092. \fi}
  10093. \end{minipage}
  10094. }
  10095. \caption{The abstract syntax of \LangVec{}.}
  10096. \label{fig:Lvec-syntax}
  10097. \end{figure}
  10098. Tuples raise several interesting new issues. First, variable binding
  10099. performs a shallow-copy when dealing with tuples, which means that
  10100. different variables can refer to the same tuple, that is, two
  10101. variables can be \emph{aliases}\index{subject}{alias} for the same
  10102. entity. Consider the following example in which both \code{t1} and
  10103. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10104. different tuple value but with equal elements. The result of the
  10105. program is \code{42}.
  10106. \begin{center}
  10107. \begin{minipage}{0.96\textwidth}
  10108. {\if\edition\racketEd
  10109. \begin{lstlisting}
  10110. (let ([t1 (vector 3 7)])
  10111. (let ([t2 t1])
  10112. (let ([t3 (vector 3 7)])
  10113. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10114. 42
  10115. 0))))
  10116. \end{lstlisting}
  10117. \fi}
  10118. {\if\edition\pythonEd
  10119. \begin{lstlisting}
  10120. t1 = 3, 7
  10121. t2 = t1
  10122. t3 = 3, 7
  10123. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10124. \end{lstlisting}
  10125. \fi}
  10126. \end{minipage}
  10127. \end{center}
  10128. {\if\edition\racketEd
  10129. Whether two variables are aliased or not affects what happens
  10130. when the underlying tuple is mutated\index{subject}{mutation}.
  10131. Consider the following example in which \code{t1} and \code{t2}
  10132. again refer to the same tuple value.
  10133. \begin{center}
  10134. \begin{minipage}{0.96\textwidth}
  10135. \begin{lstlisting}
  10136. (let ([t1 (vector 3 7)])
  10137. (let ([t2 t1])
  10138. (let ([_ (vector-set! t2 0 42)])
  10139. (vector-ref t1 0))))
  10140. \end{lstlisting}
  10141. \end{minipage}
  10142. \end{center}
  10143. The mutation through \code{t2} is visible when referencing the tuple
  10144. from \code{t1}, so the result of this program is \code{42}.
  10145. \fi}
  10146. The next issue concerns the lifetime of tuples. When does their
  10147. lifetime end? Notice that \LangVec{} does not include an operation
  10148. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10149. to any notion of static scoping.
  10150. %
  10151. {\if\edition\racketEd
  10152. %
  10153. For example, the following program returns \code{42} even though the
  10154. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10155. that reads from the vector it was bound to.
  10156. \begin{center}
  10157. \begin{minipage}{0.96\textwidth}
  10158. \begin{lstlisting}
  10159. (let ([v (vector (vector 44))])
  10160. (let ([x (let ([w (vector 42)])
  10161. (let ([_ (vector-set! v 0 w)])
  10162. 0))])
  10163. (+ x (vector-ref (vector-ref v 0) 0))))
  10164. \end{lstlisting}
  10165. \end{minipage}
  10166. \end{center}
  10167. \fi}
  10168. %
  10169. {\if\edition\pythonEd
  10170. %
  10171. For example, the following program returns \code{42} even though the
  10172. variable \code{x} goes out of scope when the function returns, prior
  10173. to reading the tuple element at index zero. (We study the compilation
  10174. of functions in Chapter~\ref{ch:Lfun}.)
  10175. %
  10176. \begin{center}
  10177. \begin{minipage}{0.96\textwidth}
  10178. \begin{lstlisting}
  10179. def f():
  10180. x = 42, 43
  10181. return x
  10182. t = f()
  10183. print( t[0] )
  10184. \end{lstlisting}
  10185. \end{minipage}
  10186. \end{center}
  10187. \fi}
  10188. %
  10189. From the perspective of programmer-observable behavior, tuples live
  10190. forever. However, if they really lived forever then many long-running
  10191. programs would run out of memory. To solve this problem, the
  10192. language's runtime system performs automatic garbage collection.
  10193. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10194. \LangVec{} language.
  10195. %
  10196. \racket{We define the \code{vector}, \code{vector-ref},
  10197. \code{vector-set!}, and \code{vector-length} operations for
  10198. \LangVec{} in terms of the corresponding operations in Racket. One
  10199. subtle point is that the \code{vector-set!} operation returns the
  10200. \code{\#<void>} value.}
  10201. %
  10202. \python{We represent tuples with Python lists in the interpreter
  10203. because we need to write to them
  10204. (Section~\ref{sec:expose-allocation}). (Python tuples are
  10205. immutable.) We define element access, the \code{is} operator, and
  10206. the \code{len} operator for \LangVec{} in terms of the corresponding
  10207. operations in Python.}
  10208. \begin{figure}[tbp]
  10209. {\if\edition\racketEd
  10210. \begin{lstlisting}
  10211. (define interp-Lvec_class
  10212. (class interp-Lif_class
  10213. (super-new)
  10214. (define/override (interp-op op)
  10215. (match op
  10216. ['eq? (lambda (v1 v2)
  10217. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10218. (and (boolean? v1) (boolean? v2))
  10219. (and (vector? v1) (vector? v2))
  10220. (and (void? v1) (void? v2)))
  10221. (eq? v1 v2)]))]
  10222. ['vector vector]
  10223. ['vector-length vector-length]
  10224. ['vector-ref vector-ref]
  10225. ['vector-set! vector-set!]
  10226. [else (super interp-op op)]
  10227. ))
  10228. (define/override ((interp-exp env) e)
  10229. (define recur (interp-exp env))
  10230. (match e
  10231. [(HasType e t) (recur e)]
  10232. [(Void) (void)]
  10233. [else ((super interp-exp env) e)]
  10234. ))
  10235. ))
  10236. (define (interp-Lvec p)
  10237. (send (new interp-Lvec_class) interp-program p))
  10238. \end{lstlisting}
  10239. \fi}
  10240. %
  10241. {\if\edition\pythonEd
  10242. \begin{lstlisting}
  10243. class InterpLtup(InterpLwhile):
  10244. def interp_cmp(self, cmp):
  10245. match cmp:
  10246. case Is():
  10247. return lambda x, y: x is y
  10248. case _:
  10249. return super().interp_cmp(cmp)
  10250. def interp_exp(self, e, env):
  10251. match e:
  10252. case Tuple(es, Load()):
  10253. return tuple([self.interp_exp(e, env) for e in es])
  10254. case Subscript(tup, index, Load()):
  10255. t = self.interp_exp(tup, env)
  10256. n = self.interp_exp(index, env)
  10257. return t[n]
  10258. case _:
  10259. return super().interp_exp(e, env)
  10260. \end{lstlisting}
  10261. \fi}
  10262. \caption{Interpreter for the \LangVec{} language.}
  10263. \label{fig:interp-Lvec}
  10264. \end{figure}
  10265. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10266. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10267. we need to know which elements of the tuple are themselves tuples for
  10268. the purposes of garbage collection. We can obtain this information
  10269. during type checking. The type checker in
  10270. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10271. expression, it also
  10272. %
  10273. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10274. where $T$ is the vector's type.
  10275. To create the s-expression for the \code{Vector} type in
  10276. Figure~\ref{fig:type-check-Lvec}, we use the
  10277. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10278. operator} \code{,@} to insert the list \code{t*} without its usual
  10279. start and end parentheses. \index{subject}{unquote-slicing}}
  10280. %
  10281. \python{records the type of each tuple expression in a new field
  10282. named \code{has\_type}. Because the type checker has to compute the type
  10283. of each tuple access, the index must be a constant.}
  10284. \begin{figure}[tp]
  10285. {\if\edition\racketEd
  10286. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10287. (define type-check-Lvec_class
  10288. (class type-check-Lif_class
  10289. (super-new)
  10290. (inherit check-type-equal?)
  10291. (define/override (type-check-exp env)
  10292. (lambda (e)
  10293. (define recur (type-check-exp env))
  10294. (match e
  10295. [(Void) (values (Void) 'Void)]
  10296. [(Prim 'vector es)
  10297. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10298. (define t `(Vector ,@t*))
  10299. (values (HasType (Prim 'vector e*) t) t)]
  10300. [(Prim 'vector-ref (list e1 (Int i)))
  10301. (define-values (e1^ t) (recur e1))
  10302. (match t
  10303. [`(Vector ,ts ...)
  10304. (unless (and (0 . <= . i) (i . < . (length ts)))
  10305. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10306. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10307. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10308. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10309. (define-values (e-vec t-vec) (recur e1))
  10310. (define-values (e-arg^ t-arg) (recur arg))
  10311. (match t-vec
  10312. [`(Vector ,ts ...)
  10313. (unless (and (0 . <= . i) (i . < . (length ts)))
  10314. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10315. (check-type-equal? (list-ref ts i) t-arg e)
  10316. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10317. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10318. [(Prim 'vector-length (list e))
  10319. (define-values (e^ t) (recur e))
  10320. (match t
  10321. [`(Vector ,ts ...)
  10322. (values (Prim 'vector-length (list e^)) 'Integer)]
  10323. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10324. [(Prim 'eq? (list arg1 arg2))
  10325. (define-values (e1 t1) (recur arg1))
  10326. (define-values (e2 t2) (recur arg2))
  10327. (match* (t1 t2)
  10328. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10329. [(other wise) (check-type-equal? t1 t2 e)])
  10330. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10331. [(HasType (Prim 'vector es) t)
  10332. ((type-check-exp env) (Prim 'vector es))]
  10333. [(HasType e1 t)
  10334. (define-values (e1^ t^) (recur e1))
  10335. (check-type-equal? t t^ e)
  10336. (values (HasType e1^ t) t)]
  10337. [else ((super type-check-exp env) e)]
  10338. )))
  10339. ))
  10340. (define (type-check-Lvec p)
  10341. (send (new type-check-Lvec_class) type-check-program p))
  10342. \end{lstlisting}
  10343. \fi}
  10344. {\if\edition\pythonEd
  10345. \begin{lstlisting}
  10346. class TypeCheckLtup(TypeCheckLwhile):
  10347. def type_check_exp(self, e, env):
  10348. match e:
  10349. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10350. l = self.type_check_exp(left, env)
  10351. r = self.type_check_exp(right, env)
  10352. check_type_equal(l, r, e)
  10353. return bool
  10354. case Tuple(es, Load()):
  10355. ts = [self.type_check_exp(e, env) for e in es]
  10356. e.has_type = tuple(ts)
  10357. return e.has_type
  10358. case Subscript(tup, Constant(index), Load()):
  10359. tup_ty = self.type_check_exp(tup, env)
  10360. index_ty = self.type_check_exp(Constant(index), env)
  10361. check_type_equal(index_ty, int, index)
  10362. match tup_ty:
  10363. case tuple(ts):
  10364. return ts[index]
  10365. case _:
  10366. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10367. case _:
  10368. return super().type_check_exp(e, env)
  10369. \end{lstlisting}
  10370. \fi}
  10371. \caption{Type checker for the \LangVec{} language.}
  10372. \label{fig:type-check-Lvec}
  10373. \end{figure}
  10374. \section{Garbage Collection}
  10375. \label{sec:GC}
  10376. Garbage collection is a runtime technique for reclaiming space on the
  10377. heap that will not be used in the future of the running program. We
  10378. use the term \emph{object}\index{subject}{object} to refer to any
  10379. value that is stored in the heap, which for now only includes
  10380. tuples.%
  10381. %
  10382. \footnote{The term ``object'' as used in the context of
  10383. object-oriented programming has a more specific meaning than how we
  10384. are using the term here.}
  10385. %
  10386. Unfortunately, it is impossible to know precisely which objects will
  10387. be accessed in the future and which will not. Instead, garbage
  10388. collectors overapproximate the set of objects that will be accessed by
  10389. identifying which objects can possibly be accessed. The running
  10390. program can directly access objects that are in registers and on the
  10391. procedure call stack. It can also transitively access the elements of
  10392. tuples, starting with a tuple whose address is in a register or on the
  10393. procedure call stack. We define the \emph{root
  10394. set}\index{subject}{root set} to be all the tuple addresses that are
  10395. in registers or on the procedure call stack. We define the \emph{live
  10396. objects}\index{subject}{live objects} to be the objects that are
  10397. reachable from the root set. Garbage collectors reclaim the space that
  10398. is allocated to objects that are no longer live. That means that some
  10399. objects may not get reclaimed as soon as they could be, but at least
  10400. garbage collectors do not reclaim the space dedicated to objects that
  10401. will be accessed in the future! The programmer can influence which
  10402. objects get reclaimed by causing them to become unreachable.
  10403. So the goal of the garbage collector is twofold:
  10404. \begin{enumerate}
  10405. \item preserve all the live objects, and
  10406. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10407. \end{enumerate}
  10408. \subsection{Two-Space Copying Collector}
  10409. Here we study a relatively simple algorithm for garbage collection
  10410. that is the basis of many state-of-the-art garbage
  10411. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10412. particular, we describe a two-space copying
  10413. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10414. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10415. collector} \index{subject}{two-space copying collector}
  10416. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10417. what happens in a two-space collector, showing two time steps, prior
  10418. to garbage collection (on the top) and after garbage collection (on
  10419. the bottom). In a two-space collector, the heap is divided into two
  10420. parts named the FromSpace\index{subject}{FromSpace} and the
  10421. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10422. FromSpace until there is not enough room for the next allocation
  10423. request. At that point, the garbage collector goes to work to room for
  10424. the next allocation.
  10425. A copying collector makes more room by copying all of the live objects
  10426. from the FromSpace into the ToSpace and then performs a sleight of
  10427. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10428. as the new ToSpace. In the example of
  10429. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10430. root set, one in a register and two on the stack. All of the live
  10431. objects have been copied to the ToSpace (the right-hand side of
  10432. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10433. pointer relationships. For example, the pointer in the register still
  10434. points to a tuple that in turn points to two other tuples. There are
  10435. four tuples that are not reachable from the root set and therefore do
  10436. not get copied into the ToSpace.
  10437. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10438. created by a well-typed program in \LangVec{} because it contains a
  10439. cycle. However, creating cycles will be possible once we get to
  10440. \LangDyn{}. We design the garbage collector to deal with cycles to
  10441. begin with so we will not need to revisit this issue.
  10442. \begin{figure}[tbp]
  10443. \centering
  10444. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10445. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10446. \\[5ex]
  10447. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10448. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10449. \caption{A copying collector in action.}
  10450. \label{fig:copying-collector}
  10451. \end{figure}
  10452. \subsection{Graph Copying via Cheney's Algorithm}
  10453. \label{sec:cheney}
  10454. \index{subject}{Cheney's algorithm}
  10455. Let us take a closer look at the copying of the live objects. The
  10456. allocated objects and pointers can be viewed as a graph and we need to
  10457. copy the part of the graph that is reachable from the root set. To
  10458. make sure we copy all of the reachable vertices in the graph, we need
  10459. an exhaustive graph traversal algorithm, such as depth-first search or
  10460. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10461. such algorithms take into account the possibility of cycles by marking
  10462. which vertices have already been visited, so as to ensure termination
  10463. of the algorithm. These search algorithms also use a data structure
  10464. such as a stack or queue as a to-do list to keep track of the vertices
  10465. that need to be visited. We use breadth-first search and a trick
  10466. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10467. and copying tuples into the ToSpace.
  10468. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10469. copy progresses. The queue is represented by a chunk of contiguous
  10470. memory at the beginning of the ToSpace, using two pointers to track
  10471. the front and the back of the queue, called the \emph{free pointer}
  10472. and the \emph{scan pointer} respectively. The algorithm starts by
  10473. copying all tuples that are immediately reachable from the root set
  10474. into the ToSpace to form the initial queue. When we copy a tuple, we
  10475. mark the old tuple to indicate that it has been visited. We discuss
  10476. how this marking is accomplish in Section~\ref{sec:data-rep-gc}. Note
  10477. that any pointers inside the copied tuples in the queue still point
  10478. back to the FromSpace. Once the initial queue has been created, the
  10479. algorithm enters a loop in which it repeatedly processes the tuple at
  10480. the front of the queue and pops it off the queue. To process a tuple,
  10481. the algorithm copies all the tuple that are directly reachable from it
  10482. to the ToSpace, placing them at the back of the queue. The algorithm
  10483. then updates the pointers in the popped tuple so they point to the
  10484. newly copied tuples.
  10485. \begin{figure}[tbp]
  10486. \centering
  10487. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10488. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10489. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10490. \label{fig:cheney}
  10491. \end{figure}
  10492. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10493. tuple whose second element is $42$ to the back of the queue. The other
  10494. pointer goes to a tuple that has already been copied, so we do not
  10495. need to copy it again, but we do need to update the pointer to the new
  10496. location. This can be accomplished by storing a \emph{forwarding
  10497. pointer}\index{subect}{forwarding pointer} to the new location in the
  10498. old tuple, back when we initially copied the tuple into the
  10499. ToSpace. This completes one step of the algorithm. The algorithm
  10500. continues in this way until the queue is empty, that is, when the scan
  10501. pointer catches up with the free pointer.
  10502. \subsection{Data Representation}
  10503. \label{sec:data-rep-gc}
  10504. The garbage collector places some requirements on the data
  10505. representations used by our compiler. First, the garbage collector
  10506. needs to distinguish between pointers and other kinds of data such as
  10507. integers. There are several ways to accomplish this.
  10508. \begin{enumerate}
  10509. \item Attached a tag to each object that identifies what type of
  10510. object it is~\citep{McCarthy:1960dz}.
  10511. \item Store different types of objects in different
  10512. regions~\citep{Steele:1977ab}.
  10513. \item Use type information from the program to either generate
  10514. type-specific code for collecting or to generate tables that can
  10515. guide the
  10516. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10517. \end{enumerate}
  10518. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10519. need to tag objects anyways, so option 1 is a natural choice for those
  10520. languages. However, \LangVec{} is a statically typed language, so it
  10521. would be unfortunate to require tags on every object, especially small
  10522. and pervasive objects like integers and Booleans. Option 3 is the
  10523. best-performing choice for statically typed languages, but comes with
  10524. a relatively high implementation complexity. To keep this chapter
  10525. within a reasonable time budget, we recommend a combination of options
  10526. 1 and 2, using separate strategies for the stack and the heap.
  10527. Regarding the stack, we recommend using a separate stack for pointers,
  10528. which we call the \emph{root stack}\index{subject}{root stack}
  10529. (a.k.a. ``shadow
  10530. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10531. is, when a local variable needs to be spilled and is of type
  10532. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10533. root stack instead of putting it on the procedure call
  10534. stack. Furthermore, we always spill tuple-typed variables if they are
  10535. live during a call to the collector, thereby ensuring that no pointers
  10536. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10537. reproduces the example from Figure~\ref{fig:copying-collector} and
  10538. contrasts it with the data layout using a root stack. The root stack
  10539. contains the two pointers from the regular stack and also the pointer
  10540. in the second register.
  10541. \begin{figure}[tbp]
  10542. \centering
  10543. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10544. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10545. \caption{Maintaining a root stack to facilitate garbage collection.}
  10546. \label{fig:shadow-stack}
  10547. \end{figure}
  10548. The problem of distinguishing between pointers and other kinds of data
  10549. also arises inside of each tuple on the heap. We solve this problem by
  10550. attaching a tag, an extra 64-bits, to each
  10551. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10552. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10553. that we have drawn the bits in a big-endian way, from right-to-left,
  10554. with bit location 0 (the least significant bit) on the far right,
  10555. which corresponds to the direction of the x86 shifting instructions
  10556. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10557. is dedicated to specifying which elements of the tuple are pointers,
  10558. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10559. indicates there is a pointer and a 0 bit indicates some other kind of
  10560. data. The pointer mask starts at bit location 7. We limit tuples to a
  10561. maximum size of 50 elements, so we just need 50 bits for the pointer
  10562. mask.%
  10563. %
  10564. \footnote{A production-quality compiler would handle
  10565. arbitrary-sized tuples and use a more complex approach.}
  10566. %
  10567. The tag also contains two other pieces of information. The length of
  10568. the tuple (number of elements) is stored in bits location 1 through
  10569. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10570. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10571. has not yet been copied. If the bit has value 0 then the entire tag
  10572. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10573. zero anyways because our tuples are 8-byte aligned.)
  10574. \begin{figure}[tbp]
  10575. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10576. \caption{Representation of tuples in the heap.}
  10577. \label{fig:tuple-rep}
  10578. \end{figure}
  10579. \subsection{Implementation of the Garbage Collector}
  10580. \label{sec:organize-gz}
  10581. \index{subject}{prelude}
  10582. An implementation of the copying collector is provided in the
  10583. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10584. interface to the garbage collector that is used by the compiler. The
  10585. \code{initialize} function creates the FromSpace, ToSpace, and root
  10586. stack and should be called in the prelude of the \code{main}
  10587. function. The arguments of \code{initialize} are the root stack size
  10588. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10589. good choice for both. The \code{initialize} function puts the address
  10590. of the beginning of the FromSpace into the global variable
  10591. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10592. the address that is 1-past the last element of the FromSpace. (We use
  10593. half-open intervals to represent chunks of
  10594. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10595. points to the first element of the root stack.
  10596. As long as there is room left in the FromSpace, your generated code
  10597. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10598. %
  10599. The amount of room left in FromSpace is the difference between the
  10600. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10601. function should be called when there is not enough room left in the
  10602. FromSpace for the next allocation. The \code{collect} function takes
  10603. a pointer to the current top of the root stack (one past the last item
  10604. that was pushed) and the number of bytes that need to be
  10605. allocated. The \code{collect} function performs the copying collection
  10606. and leaves the heap in a state such that the next allocation will
  10607. succeed.
  10608. \begin{figure}[tbp]
  10609. \begin{lstlisting}
  10610. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10611. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10612. int64_t* free_ptr;
  10613. int64_t* fromspace_begin;
  10614. int64_t* fromspace_end;
  10615. int64_t** rootstack_begin;
  10616. \end{lstlisting}
  10617. \caption{The compiler's interface to the garbage collector.}
  10618. \label{fig:gc-header}
  10619. \end{figure}
  10620. %% \begin{exercise}
  10621. %% In the file \code{runtime.c} you will find the implementation of
  10622. %% \code{initialize} and a partial implementation of \code{collect}.
  10623. %% The \code{collect} function calls another function, \code{cheney},
  10624. %% to perform the actual copy, and that function is left to the reader
  10625. %% to implement. The following is the prototype for \code{cheney}.
  10626. %% \begin{lstlisting}
  10627. %% static void cheney(int64_t** rootstack_ptr);
  10628. %% \end{lstlisting}
  10629. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10630. %% rootstack (which is an array of pointers). The \code{cheney} function
  10631. %% also communicates with \code{collect} through the global
  10632. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10633. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10634. %% the ToSpace:
  10635. %% \begin{lstlisting}
  10636. %% static int64_t* tospace_begin;
  10637. %% static int64_t* tospace_end;
  10638. %% \end{lstlisting}
  10639. %% The job of the \code{cheney} function is to copy all the live
  10640. %% objects (reachable from the root stack) into the ToSpace, update
  10641. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10642. %% update the root stack so that it points to the objects in the
  10643. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10644. %% and ToSpace.
  10645. %% \end{exercise}
  10646. The introduction of garbage collection has a non-trivial impact on our
  10647. compiler passes. We introduce a new compiler pass named
  10648. \code{expose\_allocation}. We make significant changes to
  10649. \code{select\_instructions}, \code{build\_interference},
  10650. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10651. make minor changes in several more passes. The following program will
  10652. serve as our running example. It creates two tuples, one nested
  10653. inside the other. Both tuples have length one. The program accesses
  10654. the element in the inner tuple.
  10655. % tests/vectors_test_17.rkt
  10656. {\if\edition\racketEd
  10657. \begin{lstlisting}
  10658. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10659. \end{lstlisting}
  10660. \fi}
  10661. {\if\edition\pythonEd
  10662. \begin{lstlisting}
  10663. print( ((42,),)[0][0] )
  10664. \end{lstlisting}
  10665. \fi}
  10666. {\if\edition\racketEd
  10667. \section{Shrink}
  10668. \label{sec:shrink-Lvec}
  10669. Recall that the \code{shrink} pass translates the primitives operators
  10670. into a smaller set of primitives.
  10671. %
  10672. This pass comes after type checking and the type checker adds a
  10673. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10674. need to add a case for \code{HasType} to the \code{shrink} pass.
  10675. \fi}
  10676. \section{Expose Allocation}
  10677. \label{sec:expose-allocation}
  10678. The pass \code{expose\_allocation} lowers tuple creation into a
  10679. conditional call to the collector followed by allocating the
  10680. appropriate amount of memory and initializing it. We choose to place
  10681. the \code{expose\_allocation} pass before
  10682. \code{remove\_complex\_operands} because the code generated by
  10683. \code{expose\_allocation} contains complex operands.
  10684. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10685. that extends \LangVec{} with new forms that we use in the translation
  10686. of tuple creation.
  10687. %
  10688. {\if\edition\racketEd
  10689. \[
  10690. \begin{array}{lcl}
  10691. \Exp &::=& \cdots
  10692. \MID (\key{collect} \,\itm{int})
  10693. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10694. \MID (\key{global-value} \,\itm{name})
  10695. \end{array}
  10696. \]
  10697. \fi}
  10698. {\if\edition\pythonEd
  10699. \[
  10700. \begin{array}{lcl}
  10701. \Exp &::=& \cdots\\
  10702. &\MID& \key{collect}(\itm{int})
  10703. \MID \key{allocate}(\itm{int},\itm{type})
  10704. \MID \key{global\_value}(\itm{name}) \\
  10705. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10706. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10707. \end{array}
  10708. \]
  10709. \fi}
  10710. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10711. make sure that there are $n$ bytes ready to be allocated. During
  10712. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10713. the \code{collect} function in \code{runtime.c}.
  10714. %
  10715. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10716. space at the front for the 64 bit tag), but the elements are not
  10717. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10718. of the tuple:
  10719. %
  10720. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10721. %
  10722. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10723. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10724. as \code{free\_ptr}.
  10725. %
  10726. \python{The \code{begin} form is an expression that executes a
  10727. sequence of statements and then produces the value of the expression
  10728. at the end.}
  10729. The following shows the transformation of tuple creation into 1) a
  10730. sequence of temporary variables bindings for the initializing
  10731. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10732. \code{allocate}, and 4) the initialization of the tuple. The
  10733. \itm{len} placeholder refers to the length of the tuple and
  10734. \itm{bytes} is how many total bytes need to be allocated for the
  10735. tuple, which is 8 for the tag plus \itm{len} times 8.
  10736. %
  10737. \python{The \itm{type} needed for the second argument of the
  10738. \code{allocate} form can be obtained from the \code{has\_type} field
  10739. of the tuple AST node, which is stored there by running the type
  10740. checker for \LangVec{} immediately before this pass.}
  10741. %
  10742. \begin{center}
  10743. \begin{minipage}{\textwidth}
  10744. {\if\edition\racketEd
  10745. \begin{lstlisting}
  10746. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10747. |$\Longrightarrow$|
  10748. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10749. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10750. (global-value fromspace_end))
  10751. (void)
  10752. (collect |\itm{bytes}|))])
  10753. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10754. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10755. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10756. |$v$|) ... )))) ...)
  10757. \end{lstlisting}
  10758. \fi}
  10759. {\if\edition\pythonEd
  10760. \begin{lstlisting}
  10761. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10762. |$\Longrightarrow$|
  10763. begin:
  10764. |$x_0$| = |$e_0$|
  10765. |$\vdots$|
  10766. |$x_{n-1}$| = |$e_{n-1}$|
  10767. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10768. 0
  10769. else:
  10770. collect(|\itm{bytes}|)
  10771. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10772. |$v$|[0] = |$x_0$|
  10773. |$\vdots$|
  10774. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10775. |$v$|
  10776. \end{lstlisting}
  10777. \fi}
  10778. \end{minipage}
  10779. \end{center}
  10780. %
  10781. \noindent The sequencing of the initializing expressions
  10782. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10783. they may trigger garbage collection and we cannot have an allocated
  10784. but uninitialized tuple on the heap during a collection.
  10785. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10786. \code{expose\_allocation} pass on our running example.
  10787. \begin{figure}[tbp]
  10788. % tests/s2_17.rkt
  10789. {\if\edition\racketEd
  10790. \begin{lstlisting}
  10791. (vector-ref
  10792. (vector-ref
  10793. (let ([vecinit7976
  10794. (let ([vecinit7972 42])
  10795. (let ([collectret7974
  10796. (if (< (+ (global-value free_ptr) 16)
  10797. (global-value fromspace_end))
  10798. (void)
  10799. (collect 16)
  10800. )])
  10801. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10802. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10803. alloc7971))))])
  10804. (let ([collectret7978
  10805. (if (< (+ (global-value free_ptr) 16)
  10806. (global-value fromspace_end))
  10807. (void)
  10808. (collect 16)
  10809. )])
  10810. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10811. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10812. alloc7975))))
  10813. 0)
  10814. 0)
  10815. \end{lstlisting}
  10816. \fi}
  10817. {\if\edition\pythonEd
  10818. \begin{lstlisting}
  10819. print( |$T_1$|[0][0] )
  10820. \end{lstlisting}
  10821. where $T_1$ is
  10822. \begin{lstlisting}
  10823. begin:
  10824. tmp.1 = |$T_2$|
  10825. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10826. 0
  10827. else:
  10828. collect(16)
  10829. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10830. tmp.2[0] = tmp.1
  10831. tmp.2
  10832. \end{lstlisting}
  10833. and $T_2$ is
  10834. \begin{lstlisting}
  10835. begin:
  10836. tmp.3 = 42
  10837. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10838. 0
  10839. else:
  10840. collect(16)
  10841. tmp.4 = allocate(1, TupleType([int]))
  10842. tmp.4[0] = tmp.3
  10843. tmp.4
  10844. \end{lstlisting}
  10845. \fi}
  10846. \caption{Output of the \code{expose\_allocation} pass.}
  10847. \label{fig:expose-alloc-output}
  10848. \end{figure}
  10849. \section{Remove Complex Operands}
  10850. \label{sec:remove-complex-opera-Lvec}
  10851. {\if\edition\racketEd
  10852. %
  10853. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10854. should be treated as complex operands.
  10855. %
  10856. \fi}
  10857. %
  10858. {\if\edition\pythonEd
  10859. %
  10860. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10861. and tuple access should be treated as complex operands. The
  10862. sub-expressions of tuple access must be atomic.
  10863. %
  10864. \fi}
  10865. %% A new case for
  10866. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10867. %% handled carefully to prevent the \code{Prim} node from being separated
  10868. %% from its enclosing \code{HasType}.
  10869. Figure~\ref{fig:Lvec-anf-syntax}
  10870. shows the grammar for the output language \LangAllocANF{} of this
  10871. pass, which is \LangAlloc{} in monadic normal form.
  10872. \newcommand{\LtupMonadASTPython}{
  10873. \begin{array}{rcl}
  10874. \Exp &::=& \GET{\Atm}{\Atm} \\
  10875. &\MID& \LEN{\Atm}\\
  10876. &\MID& \ALLOCATE{\Int}{\Type}
  10877. \MID \GLOBALVALUE{\Var} \\
  10878. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  10879. &\MID& \COLLECT{\Int}
  10880. \end{array}
  10881. }
  10882. \begin{figure}[tp]
  10883. \centering
  10884. \fbox{
  10885. \begin{minipage}{0.96\textwidth}
  10886. \small
  10887. {\if\edition\racketEd
  10888. \[
  10889. \begin{array}{rcl}
  10890. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10891. \MID \VOID{} } \\
  10892. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10893. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10894. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10895. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10896. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10897. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10898. \MID \GLOBALVALUE{\Var}\\
  10899. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10900. \LangAllocANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10901. \end{array}
  10902. \]
  10903. \fi}
  10904. {\if\edition\pythonEd
  10905. \[
  10906. \begin{array}{l}
  10907. \gray{\LvarMonadASTPython} \\ \hline
  10908. \gray{\LifMonadASTPython} \\ \hline
  10909. \gray{\LwhileMonadASTPython} \\ \hline
  10910. \LtupMonadASTPython \\
  10911. \begin{array}{rcl}
  10912. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10913. \end{array}
  10914. \end{array}
  10915. %% \begin{array}{lcl}
  10916. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  10917. %% \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10918. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10919. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  10920. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  10921. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10922. %% \Exp &::=& \Atm \MID \READ{} \MID \\
  10923. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  10924. %% \MID \UNIOP{\itm{unaryop}}{\Atm}\\
  10925. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  10926. %% % \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp} \\ % removed by RCO
  10927. %% &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10928. %% &\MID& \GET{\Atm}{\Atm} \\
  10929. %% &\MID& \LEN{\Exp}\\
  10930. %% &\MID& \ALLOCATE{\Int}{\Type}
  10931. %% \MID \GLOBALVALUE{\Var}\RP\\
  10932. %% &\MID& \BEGIN{\Stmt^{*}}{\Atm} \\ % can use this in place of \LET;
  10933. %% % why have \LET?
  10934. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10935. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10936. %% &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10937. %% &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10938. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10939. %% \MID \COLLECT{\Int} \\
  10940. %% \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10941. %% \end{array}
  10942. \]
  10943. \fi}
  10944. \end{minipage}
  10945. }
  10946. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  10947. \label{fig:Lvec-anf-syntax}
  10948. \end{figure}
  10949. \section{Explicate Control and the \LangCVec{} language}
  10950. \label{sec:explicate-control-r3}
  10951. \newcommand{\CtupASTRacket}{
  10952. \begin{array}{lcl}
  10953. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10954. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  10955. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10956. &\MID& \VECLEN{\Atm} \\
  10957. &\MID& \GLOBALVALUE{\Var} \\
  10958. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10959. &\MID& \LP\key{Collect} \,\itm{int}\RP
  10960. \end{array}
  10961. }
  10962. \newcommand{\CtupASTPython}{
  10963. \begin{array}{lcl}
  10964. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  10965. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  10966. \Stmt &::=& \COLLECT{\Int} \\
  10967. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  10968. \end{array}
  10969. }
  10970. \begin{figure}[tp]
  10971. \fbox{
  10972. \begin{minipage}{0.96\textwidth}
  10973. \small
  10974. {\if\edition\racketEd
  10975. \[
  10976. \begin{array}{l}
  10977. \gray{\CvarASTRacket} \\ \hline
  10978. \gray{\CifASTRacket} \\ \hline
  10979. \gray{\CloopASTRacket} \\ \hline
  10980. \CtupASTRacket \\
  10981. \begin{array}{lcl}
  10982. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10983. \end{array}
  10984. \end{array}
  10985. \]
  10986. \fi}
  10987. {\if\edition\pythonEd
  10988. \[
  10989. \begin{array}{l}
  10990. \gray{\CifASTPython} \\ \hline
  10991. \CtupASTPython \\
  10992. \begin{array}{lcl}
  10993. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  10994. \end{array}
  10995. \end{array}
  10996. \]
  10997. \fi}
  10998. \end{minipage}
  10999. }
  11000. \caption{The abstract syntax of \LangCVec{}, extending
  11001. \racket{\LangCLoop{} (Figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11002. (Figure~\ref{fig:c1-syntax})}.}
  11003. \label{fig:c2-syntax}
  11004. \end{figure}
  11005. The output of \code{explicate\_control} is a program in the
  11006. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11007. Figure~\ref{fig:c2-syntax}.
  11008. %
  11009. \racket{(The concrete syntax is defined in
  11010. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11011. %
  11012. The new expressions of \LangCVec{} include \key{allocate},
  11013. %
  11014. \racket{\key{vector-ref}, and \key{vector-set!},}
  11015. %
  11016. \python{accessing tuple elements,}
  11017. %
  11018. and \key{global\_value}.
  11019. %
  11020. \python{\LangCVec{} also includes the \code{collect} statement and
  11021. assignment to a tuple element.}
  11022. %
  11023. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11024. %
  11025. The \code{explicate\_control} pass can treat these new forms much like
  11026. the other forms that we've already encoutered.
  11027. \section{Select Instructions and the \LangXGlobal{} Language}
  11028. \label{sec:select-instructions-gc}
  11029. \index{subject}{instruction selection}
  11030. %% void (rep as zero)
  11031. %% allocate
  11032. %% collect (callq collect)
  11033. %% vector-ref
  11034. %% vector-set!
  11035. %% vector-length
  11036. %% global (postpone)
  11037. In this pass we generate x86 code for most of the new operations that
  11038. were needed to compile tuples, including \code{Allocate},
  11039. \code{Collect}, and accessing tuple elements.
  11040. %
  11041. We compile \code{GlobalValue} to \code{Global} because the later has a
  11042. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11043. \ref{fig:x86-2}). \index{subject}{x86}
  11044. The tuple read and write forms translate into \code{movq}
  11045. instructions. (The plus one in the offset is to get past the tag at
  11046. the beginning of the tuple representation.)
  11047. %
  11048. \begin{center}
  11049. \begin{minipage}{\textwidth}
  11050. {\if\edition\racketEd
  11051. \begin{lstlisting}
  11052. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11053. |$\Longrightarrow$|
  11054. movq |$\itm{tup}'$|, %r11
  11055. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11056. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11057. |$\Longrightarrow$|
  11058. movq |$\itm{tup}'$|, %r11
  11059. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11060. movq $0, |$\itm{lhs'}$|
  11061. \end{lstlisting}
  11062. \fi}
  11063. {\if\edition\pythonEd
  11064. \begin{lstlisting}
  11065. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11066. |$\Longrightarrow$|
  11067. movq |$\itm{tup}'$|, %r11
  11068. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11069. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11070. |$\Longrightarrow$|
  11071. movq |$\itm{tup}'$|, %r11
  11072. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11073. \end{lstlisting}
  11074. \fi}
  11075. \end{minipage}
  11076. \end{center}
  11077. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11078. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11079. are obtained by translating from \LangCVec{} to x86.
  11080. %
  11081. The move of $\itm{tup}'$ to
  11082. register \code{r11} ensures that offset expression
  11083. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  11084. removing \code{r11} from consideration by the register allocating.
  11085. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11086. \code{rax}. Then the generated code for tuple assignment would be
  11087. \begin{lstlisting}
  11088. movq |$\itm{tup}'$|, %rax
  11089. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11090. \end{lstlisting}
  11091. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11092. \code{patch\_instructions} would insert a move through \code{rax}
  11093. as follows.
  11094. \begin{lstlisting}
  11095. movq |$\itm{tup}'$|, %rax
  11096. movq |$\itm{rhs}'$|, %rax
  11097. movq %rax, |$8(n+1)$|(%rax)
  11098. \end{lstlisting}
  11099. But the above sequence of instructions does not work because we're
  11100. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11101. $\itm{rhs}'$) at the same time!
  11102. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11103. be translated into a sequence of instructions that read the tag of the
  11104. tuple and extract the six bits that represent the tuple length, which
  11105. are the bits starting at index 1 and going up to and including bit 6.
  11106. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11107. (shift right) can be used to accomplish this.
  11108. We compile the \code{allocate} form to operations on the
  11109. \code{free\_ptr}, as shown below. This approach is called \emph{inline
  11110. allocation} as it implements allocation by bumping the allocation
  11111. pointer. It is much more efficient than calling a function for each
  11112. allocation. The address in the \code{free\_ptr}
  11113. is the next free address in the FromSpace, so we copy it into
  11114. \code{r11} and then move it forward by enough space for the tuple
  11115. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  11116. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  11117. initialize the \itm{tag} and finally copy the address in \code{r11} to
  11118. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  11119. tag is organized.
  11120. %
  11121. \racket{We recommend using the Racket operations
  11122. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11123. during compilation.}
  11124. %
  11125. \python{We recommend using the bitwise-or operator \code{|} and the
  11126. shift-left operator \code{<<} to compute the tag during
  11127. compilation.}
  11128. %
  11129. The type annotation in the \code{allocate} form is used to determine
  11130. the pointer mask region of the tag.
  11131. %
  11132. Do not worry about the addressing mode \verb!free_ptr(%rip)!. It
  11133. essentially stands for the address \code{free\_ptr}, but uses a
  11134. special instruction-pointer relative addressing mode of the x86-64
  11135. processor.
  11136. %
  11137. {\if\edition\racketEd
  11138. \begin{lstlisting}
  11139. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11140. |$\Longrightarrow$|
  11141. movq free_ptr(%rip), %r11
  11142. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11143. movq $|$\itm{tag}$|, 0(%r11)
  11144. movq %r11, |$\itm{lhs}'$|
  11145. \end{lstlisting}
  11146. \fi}
  11147. {\if\edition\pythonEd
  11148. \begin{lstlisting}
  11149. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11150. |$\Longrightarrow$|
  11151. movq free_ptr(%rip), %r11
  11152. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11153. movq $|$\itm{tag}$|, 0(%r11)
  11154. movq %r11, |$\itm{lhs}'$|
  11155. \end{lstlisting}
  11156. \fi}
  11157. The \code{collect} form is compiled to a call to the \code{collect}
  11158. function in the runtime. The arguments to \code{collect} are 1) the
  11159. top of the root stack and 2) the number of bytes that need to be
  11160. allocated. We use another dedicated register, \code{r15}, to
  11161. store the pointer to the top of the root stack. So \code{r15} is not
  11162. available for use by the register allocator.
  11163. {\if\edition\racketEd
  11164. \begin{lstlisting}
  11165. (collect |$\itm{bytes}$|)
  11166. |$\Longrightarrow$|
  11167. movq %r15, %rdi
  11168. movq $|\itm{bytes}|, %rsi
  11169. callq collect
  11170. \end{lstlisting}
  11171. \fi}
  11172. {\if\edition\pythonEd
  11173. \begin{lstlisting}
  11174. collect(|$\itm{bytes}$|)
  11175. |$\Longrightarrow$|
  11176. movq %r15, %rdi
  11177. movq $|\itm{bytes}|, %rsi
  11178. callq collect
  11179. \end{lstlisting}
  11180. \fi}
  11181. \begin{figure}[tp]
  11182. \fbox{
  11183. \begin{minipage}{0.96\textwidth}
  11184. \[
  11185. \begin{array}{lcl}
  11186. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  11187. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  11188. & & \gray{ \key{main:} \; \Instr^{*} }
  11189. \end{array}
  11190. \]
  11191. \end{minipage}
  11192. }
  11193. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11194. \label{fig:x86-2-concrete}
  11195. \end{figure}
  11196. \begin{figure}[tp]
  11197. \fbox{
  11198. \begin{minipage}{0.96\textwidth}
  11199. \small
  11200. \[
  11201. \begin{array}{lcl}
  11202. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11203. \MID \BYTEREG{\Reg}} \\
  11204. &\MID& \GLOBAL{\Var} \\
  11205. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  11206. \end{array}
  11207. \]
  11208. \end{minipage}
  11209. }
  11210. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11211. \label{fig:x86-2}
  11212. \end{figure}
  11213. The concrete and abstract syntax of the \LangXGlobal{} language is
  11214. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11215. differs from \LangXIf{} just in the addition of global variables.
  11216. %
  11217. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11218. \code{select\_instructions} pass on the running example.
  11219. \begin{figure}[tbp]
  11220. \centering
  11221. % tests/s2_17.rkt
  11222. \begin{minipage}[t]{0.5\textwidth}
  11223. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11224. block35:
  11225. movq free_ptr(%rip), alloc9024
  11226. addq $16, free_ptr(%rip)
  11227. movq alloc9024, %r11
  11228. movq $131, 0(%r11)
  11229. movq alloc9024, %r11
  11230. movq vecinit9025, 8(%r11)
  11231. movq $0, initret9026
  11232. movq alloc9024, %r11
  11233. movq 8(%r11), tmp9034
  11234. movq tmp9034, %r11
  11235. movq 8(%r11), %rax
  11236. jmp conclusion
  11237. block36:
  11238. movq $0, collectret9027
  11239. jmp block35
  11240. block38:
  11241. movq free_ptr(%rip), alloc9020
  11242. addq $16, free_ptr(%rip)
  11243. movq alloc9020, %r11
  11244. movq $3, 0(%r11)
  11245. movq alloc9020, %r11
  11246. movq vecinit9021, 8(%r11)
  11247. movq $0, initret9022
  11248. movq alloc9020, vecinit9025
  11249. movq free_ptr(%rip), tmp9031
  11250. movq tmp9031, tmp9032
  11251. addq $16, tmp9032
  11252. movq fromspace_end(%rip), tmp9033
  11253. cmpq tmp9033, tmp9032
  11254. jl block36
  11255. jmp block37
  11256. block37:
  11257. movq %r15, %rdi
  11258. movq $16, %rsi
  11259. callq 'collect
  11260. jmp block35
  11261. block39:
  11262. movq $0, collectret9023
  11263. jmp block38
  11264. \end{lstlisting}
  11265. \end{minipage}
  11266. \begin{minipage}[t]{0.45\textwidth}
  11267. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11268. start:
  11269. movq $42, vecinit9021
  11270. movq free_ptr(%rip), tmp9028
  11271. movq tmp9028, tmp9029
  11272. addq $16, tmp9029
  11273. movq fromspace_end(%rip), tmp9030
  11274. cmpq tmp9030, tmp9029
  11275. jl block39
  11276. jmp block40
  11277. block40:
  11278. movq %r15, %rdi
  11279. movq $16, %rsi
  11280. callq 'collect
  11281. jmp block38
  11282. \end{lstlisting}
  11283. \end{minipage}
  11284. \caption{Output of the \code{select\_instructions} pass.}
  11285. \label{fig:select-instr-output-gc}
  11286. \end{figure}
  11287. \clearpage
  11288. \section{Register Allocation}
  11289. \label{sec:reg-alloc-gc}
  11290. \index{subject}{register allocation}
  11291. As discussed earlier in this chapter, the garbage collector needs to
  11292. access all the pointers in the root set, that is, all variables that
  11293. are tuples. It will be the responsibility of the register allocator
  11294. to make sure that:
  11295. \begin{enumerate}
  11296. \item the root stack is used for spilling tuple-typed variables, and
  11297. \item if a tuple-typed variable is live during a call to the
  11298. collector, it must be spilled to ensure it is visible to the
  11299. collector.
  11300. \end{enumerate}
  11301. The later responsibility can be handled during construction of the
  11302. interference graph, by adding interference edges between the call-live
  11303. tuple-typed variables and all the callee-saved registers. (They
  11304. already interfere with the caller-saved registers.)
  11305. %
  11306. \racket{The type information for variables is in the \code{Program}
  11307. form, so we recommend adding another parameter to the
  11308. \code{build\_interference} function to communicate this alist.}
  11309. %
  11310. \python{The type information for variables is generated by the type
  11311. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11312. the \code{CProgram} AST mode. You'll need to propagate that
  11313. information so that it is available in this pass.}
  11314. The spilling of tuple-typed variables to the root stack can be handled
  11315. after graph coloring, when choosing how to assign the colors
  11316. (integers) to registers and stack locations. The
  11317. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11318. changes to also record the number of spills to the root stack.
  11319. % build-interference
  11320. %
  11321. % callq
  11322. % extra parameter for var->type assoc. list
  11323. % update 'program' and 'if'
  11324. % allocate-registers
  11325. % allocate spilled vectors to the rootstack
  11326. % don't change color-graph
  11327. % TODO:
  11328. %\section{Patch Instructions}
  11329. %[mention that global variables are memory references]
  11330. \section{Prelude and Conclusion}
  11331. \label{sec:print-x86-gc}
  11332. \label{sec:prelude-conclusion-x86-gc}
  11333. \index{subject}{prelude}\index{subject}{conclusion}
  11334. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11335. \code{prelude\_and\_conclusion} pass on the running example. In the
  11336. prelude and conclusion of the \code{main} function, we allocate space
  11337. on the root stack to make room for the spills of tuple-typed
  11338. variables. We do so by bumping the root stack
  11339. pointer (\code{r15}) taking care that the root stack grows up instead of down. For the running
  11340. example, there was just one spill so we increment \code{r15} by 8
  11341. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11342. One issue that deserves special care is that there may be a call to
  11343. \code{collect} prior to the initializing assignments for all the
  11344. variables in the root stack. We do not want the garbage collector to
  11345. accidentally think that some uninitialized variable is a pointer that
  11346. needs to be followed. Thus, we zero-out all locations on the root
  11347. stack in the prelude of \code{main}. In
  11348. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11349. %
  11350. \lstinline{movq $0, 0(%r15)}
  11351. %
  11352. is sufficient to accomplish this task because there is only one spill.
  11353. In general, we have to clear as many words as there are spills of
  11354. tuple-typed variables. The garbage collector tests each root to see
  11355. if it is null prior to dereferencing it.
  11356. \begin{figure}[htbp]
  11357. % TODO: Python Version -Jeremy
  11358. \begin{minipage}[t]{0.5\textwidth}
  11359. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11360. block35:
  11361. movq free_ptr(%rip), %rcx
  11362. addq $16, free_ptr(%rip)
  11363. movq %rcx, %r11
  11364. movq $131, 0(%r11)
  11365. movq %rcx, %r11
  11366. movq -8(%r15), %rax
  11367. movq %rax, 8(%r11)
  11368. movq $0, %rdx
  11369. movq %rcx, %r11
  11370. movq 8(%r11), %rcx
  11371. movq %rcx, %r11
  11372. movq 8(%r11), %rax
  11373. jmp conclusion
  11374. block36:
  11375. movq $0, %rcx
  11376. jmp block35
  11377. block38:
  11378. movq free_ptr(%rip), %rcx
  11379. addq $16, free_ptr(%rip)
  11380. movq %rcx, %r11
  11381. movq $3, 0(%r11)
  11382. movq %rcx, %r11
  11383. movq %rbx, 8(%r11)
  11384. movq $0, %rdx
  11385. movq %rcx, -8(%r15)
  11386. movq free_ptr(%rip), %rcx
  11387. addq $16, %rcx
  11388. movq fromspace_end(%rip), %rdx
  11389. cmpq %rdx, %rcx
  11390. jl block36
  11391. movq %r15, %rdi
  11392. movq $16, %rsi
  11393. callq collect
  11394. jmp block35
  11395. block39:
  11396. movq $0, %rcx
  11397. jmp block38
  11398. \end{lstlisting}
  11399. \end{minipage}
  11400. \begin{minipage}[t]{0.45\textwidth}
  11401. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11402. start:
  11403. movq $42, %rbx
  11404. movq free_ptr(%rip), %rdx
  11405. addq $16, %rdx
  11406. movq fromspace_end(%rip), %rcx
  11407. cmpq %rcx, %rdx
  11408. jl block39
  11409. movq %r15, %rdi
  11410. movq $16, %rsi
  11411. callq collect
  11412. jmp block38
  11413. .globl main
  11414. main:
  11415. pushq %rbp
  11416. movq %rsp, %rbp
  11417. pushq %r13
  11418. pushq %r12
  11419. pushq %rbx
  11420. pushq %r14
  11421. subq $0, %rsp
  11422. movq $16384, %rdi
  11423. movq $16384, %rsi
  11424. callq initialize
  11425. movq rootstack_begin(%rip), %r15
  11426. movq $0, 0(%r15)
  11427. addq $8, %r15
  11428. jmp start
  11429. conclusion:
  11430. subq $8, %r15
  11431. addq $0, %rsp
  11432. popq %r14
  11433. popq %rbx
  11434. popq %r12
  11435. popq %r13
  11436. popq %rbp
  11437. retq
  11438. \end{lstlisting}
  11439. \end{minipage}
  11440. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11441. \label{fig:print-x86-output-gc}
  11442. \end{figure}
  11443. \begin{figure}[tbp]
  11444. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11445. \node (Lvec) at (0,2) {\large \LangVec{}};
  11446. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11447. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11448. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11449. \node (Lvec-5) at (9,0) {\large \LangAllocANF{}};
  11450. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11451. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11452. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11453. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11454. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11455. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11456. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11457. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11458. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11459. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11460. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11461. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11462. \path[->,bend left=10] (Lvec-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11463. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11464. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11465. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11466. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11467. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11468. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11469. \end{tikzpicture}
  11470. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11471. \label{fig:Lvec-passes}
  11472. \end{figure}
  11473. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11474. for the compilation of \LangVec{}.
  11475. \clearpage
  11476. {\if\edition\racketEd
  11477. \section{Challenge: Simple Structures}
  11478. \label{sec:simple-structures}
  11479. \index{subject}{struct}
  11480. \index{subject}{structure}
  11481. The language \LangStruct{} extends \LangVec{} with support for simple
  11482. structures. Its concrete syntax is defined in
  11483. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11484. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11485. Racket is a user-defined data type that contains named fields and that
  11486. is heap allocated, similar to a vector. The following is an example of
  11487. a structure definition, in this case the definition of a \code{point}
  11488. type.
  11489. \begin{lstlisting}
  11490. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11491. \end{lstlisting}
  11492. \newcommand{\LstructGrammarRacket}{
  11493. \begin{array}{lcl}
  11494. \Type &::=& \Var \\
  11495. \Exp &::=& (\Var\;\Exp \ldots)\\
  11496. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11497. \end{array}
  11498. }
  11499. \newcommand{\LstructASTRacket}{
  11500. \begin{array}{lcl}
  11501. \Type &::=& \VAR{\Var} \\
  11502. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11503. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11504. \end{array}
  11505. }
  11506. \begin{figure}[tbp]
  11507. \centering
  11508. \fbox{
  11509. \begin{minipage}{0.96\textwidth}
  11510. \[
  11511. \begin{array}{l}
  11512. \gray{\LintGrammarRacket{}} \\ \hline
  11513. \gray{\LvarGrammarRacket{}} \\ \hline
  11514. \gray{\LifGrammarRacket{}} \\ \hline
  11515. \gray{\LwhileGrammarRacket} \\ \hline
  11516. \gray{\LtupGrammarRacket} \\ \hline
  11517. \LstructGrammarRacket \\
  11518. \begin{array}{lcl}
  11519. \LangStruct{} &::=& \Def \ldots \; \Exp
  11520. \end{array}
  11521. \end{array}
  11522. \]
  11523. \end{minipage}
  11524. }
  11525. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11526. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11527. \label{fig:Lstruct-concrete-syntax}
  11528. \end{figure}
  11529. \begin{figure}[tbp]
  11530. \centering
  11531. \fbox{
  11532. \begin{minipage}{0.96\textwidth}
  11533. \[
  11534. \begin{array}{l}
  11535. \gray{\LintASTRacket{}} \\ \hline
  11536. \gray{\LvarASTRacket{}} \\ \hline
  11537. \gray{\LifASTRacket{}} \\ \hline
  11538. \gray{\LwhileASTRacket} \\ \hline
  11539. \gray{\LtupASTRacket} \\ \hline
  11540. \LstructASTRacket \\
  11541. \begin{array}{lcl}
  11542. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11543. \end{array}
  11544. \end{array}
  11545. \]
  11546. \end{minipage}
  11547. }
  11548. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11549. (Figure~\ref{fig:Lvec-syntax}).}
  11550. \label{fig:Lstruct-syntax}
  11551. \end{figure}
  11552. An instance of a structure is created using function call syntax, with
  11553. the name of the structure in the function position:
  11554. \begin{lstlisting}
  11555. (point 7 12)
  11556. \end{lstlisting}
  11557. Function-call syntax is also used to read the value in a field of a
  11558. structure. The function name is formed by the structure name, a dash,
  11559. and the field name. The following example uses \code{point-x} and
  11560. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11561. instances.
  11562. \begin{center}
  11563. \begin{lstlisting}
  11564. (let ([pt1 (point 7 12)])
  11565. (let ([pt2 (point 4 3)])
  11566. (+ (- (point-x pt1) (point-x pt2))
  11567. (- (point-y pt1) (point-y pt2)))))
  11568. \end{lstlisting}
  11569. \end{center}
  11570. Similarly, to write to a field of a structure, use its set function,
  11571. whose name starts with \code{set-}, followed by the structure name,
  11572. then a dash, then the field name, and concluded with an exclamation
  11573. mark. The following example uses \code{set-point-x!} to change the
  11574. \code{x} field from \code{7} to \code{42}.
  11575. \begin{center}
  11576. \begin{lstlisting}
  11577. (let ([pt (point 7 12)])
  11578. (let ([_ (set-point-x! pt 42)])
  11579. (point-x pt)))
  11580. \end{lstlisting}
  11581. \end{center}
  11582. \begin{exercise}\normalfont
  11583. Create a type checker for \LangStruct{} by extending the type
  11584. checker for \LangVec{}. Extend your compiler with support for simple
  11585. structures, compiling \LangStruct{} to x86 assembly code. Create
  11586. five new test cases that use structures and test your compiler.
  11587. \end{exercise}
  11588. % TODO: create an interpreter for L_struct
  11589. \clearpage
  11590. \section{Challenge: Arrays}
  11591. \label{sec:arrays}
  11592. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11593. elements whose length is determined at compile-time and where each
  11594. element of a tuple may have a different type (they are
  11595. heterogeous). This challenge is also about sequences, but this time
  11596. the length is determined at run-time and all the elements have the same
  11597. type (they are homogeneous). We use the term ``array'' for this later
  11598. kind of sequence.
  11599. The Racket language does not distinguish between tuples and arrays,
  11600. they are both represented by vectors. However, Typed Racket
  11601. distinguishes between tuples and arrays: the \code{Vector} type is for
  11602. tuples and the \code{Vectorof} type is for arrays.
  11603. %
  11604. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11605. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11606. and the \code{make-vector} primitive operator for creating an array,
  11607. whose arguments are the length of the array and an initial value for
  11608. all the elements in the array. The \code{vector-length},
  11609. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11610. for tuples become overloaded for use with arrays.
  11611. %
  11612. We also include integer multiplication in \LangArray{}, as it is
  11613. useful in many examples involving arrays such as computing the
  11614. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11615. \begin{figure}[tp]
  11616. \centering
  11617. \fbox{
  11618. \begin{minipage}{0.96\textwidth}
  11619. \small
  11620. {\if\edition\racketEd
  11621. \[
  11622. \begin{array}{lcl}
  11623. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11624. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11625. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11626. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11627. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11628. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11629. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11630. \MID \LP\key{not}\;\Exp\RP } \\
  11631. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11632. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11633. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11634. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11635. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11636. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11637. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11638. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11639. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11640. \MID \CWHILE{\Exp}{\Exp} } \\
  11641. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11642. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11643. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11644. \end{array}
  11645. \]
  11646. \fi}
  11647. {\if\edition\pythonEd
  11648. UNDER CONSTRUCTION
  11649. \fi}
  11650. \end{minipage}
  11651. }
  11652. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11653. \label{fig:Lvecof-concrete-syntax}
  11654. \end{figure}
  11655. \begin{figure}[tp]
  11656. \begin{lstlisting}
  11657. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11658. [n : Integer]) : Integer
  11659. (let ([i 0])
  11660. (let ([prod 0])
  11661. (begin
  11662. (while (< i n)
  11663. (begin
  11664. (set! prod (+ prod (* (vector-ref A i)
  11665. (vector-ref B i))))
  11666. (set! i (+ i 1))
  11667. ))
  11668. prod))))
  11669. (let ([A (make-vector 2 2)])
  11670. (let ([B (make-vector 2 3)])
  11671. (+ (inner-product A B 2)
  11672. 30)))
  11673. \end{lstlisting}
  11674. \caption{Example program that computes the inner-product.}
  11675. \label{fig:inner-product}
  11676. \end{figure}
  11677. The type checker for \LangArray{} is define in
  11678. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11679. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11680. of the intializing expression. The length expression is required to
  11681. have type \code{Integer}. The type checking of the operators
  11682. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11683. updated to handle the situation where the vector has type
  11684. \code{Vectorof}. In these cases we translate the operators to their
  11685. \code{vectorof} form so that later passes can easily distinguish
  11686. between operations on tuples versus arrays. We override the
  11687. \code{operator-types} method to provide the type signature for
  11688. multiplication: it takes two integers and returns an integer. To
  11689. support injection and projection of arrays to the \code{Any} type
  11690. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11691. predicate.
  11692. \begin{figure}[tbp]
  11693. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11694. (define type-check-Lvecof_class
  11695. (class type-check-Rwhile_class
  11696. (super-new)
  11697. (inherit check-type-equal?)
  11698. (define/override (flat-ty? ty)
  11699. (match ty
  11700. ['(Vectorof Any) #t]
  11701. [else (super flat-ty? ty)]))
  11702. (define/override (operator-types)
  11703. (append '((* . ((Integer Integer) . Integer)))
  11704. (super operator-types)))
  11705. (define/override (type-check-exp env)
  11706. (lambda (e)
  11707. (define recur (type-check-exp env))
  11708. (match e
  11709. [(Prim 'make-vector (list e1 e2))
  11710. (define-values (e1^ t1) (recur e1))
  11711. (define-values (e2^ elt-type) (recur e2))
  11712. (define vec-type `(Vectorof ,elt-type))
  11713. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11714. vec-type)]
  11715. [(Prim 'vector-ref (list e1 e2))
  11716. (define-values (e1^ t1) (recur e1))
  11717. (define-values (e2^ t2) (recur e2))
  11718. (match* (t1 t2)
  11719. [(`(Vectorof ,elt-type) 'Integer)
  11720. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11721. [(other wise) ((super type-check-exp env) e)])]
  11722. [(Prim 'vector-set! (list e1 e2 e3) )
  11723. (define-values (e-vec t-vec) (recur e1))
  11724. (define-values (e2^ t2) (recur e2))
  11725. (define-values (e-arg^ t-arg) (recur e3))
  11726. (match t-vec
  11727. [`(Vectorof ,elt-type)
  11728. (check-type-equal? elt-type t-arg e)
  11729. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11730. [else ((super type-check-exp env) e)])]
  11731. [(Prim 'vector-length (list e1))
  11732. (define-values (e1^ t1) (recur e1))
  11733. (match t1
  11734. [`(Vectorof ,t)
  11735. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11736. [else ((super type-check-exp env) e)])]
  11737. [else ((super type-check-exp env) e)])))
  11738. ))
  11739. (define (type-check-Lvecof p)
  11740. (send (new type-check-Lvecof_class) type-check-program p))
  11741. \end{lstlisting}
  11742. \caption{Type checker for the \LangArray{} language.}
  11743. \label{fig:type-check-Lvecof}
  11744. \end{figure}
  11745. The interpreter for \LangArray{} is defined in
  11746. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11747. implemented with Racket's \code{make-vector} function and
  11748. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11749. integers.
  11750. \begin{figure}[tbp]
  11751. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11752. (define interp-Lvecof_class
  11753. (class interp-Rwhile_class
  11754. (super-new)
  11755. (define/override (interp-op op)
  11756. (verbose "Lvecof/interp-op" op)
  11757. (match op
  11758. ['make-vector make-vector]
  11759. ['* fx*]
  11760. [else (super interp-op op)]))
  11761. ))
  11762. (define (interp-Lvecof p)
  11763. (send (new interp-Lvecof_class) interp-program p))
  11764. \end{lstlisting}
  11765. \caption{Interpreter for \LangArray{}.}
  11766. \label{fig:interp-Lvecof}
  11767. \end{figure}
  11768. \subsection{Data Representation}
  11769. \label{sec:array-rep}
  11770. Just like tuples, we store arrays on the heap which means that the
  11771. garbage collector will need to inspect arrays. An immediate thought is
  11772. to use the same representation for arrays that we use for tuples.
  11773. However, we limit tuples to a length of $50$ so that their length and
  11774. pointer mask can fit into the 64-bit tag at the beginning of each
  11775. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11776. millions of elements, so we need more bits to store the length.
  11777. However, because arrays are homogeneous, we only need $1$ bit for the
  11778. pointer mask instead of one bit per array elements. Finally, the
  11779. garbage collector will need to be able to distinguish between tuples
  11780. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11781. arrive at the following layout for the 64-bit tag at the beginning of
  11782. an array:
  11783. \begin{itemize}
  11784. \item The right-most bit is the forwarding bit, just like in a tuple.
  11785. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11786. it is not.
  11787. \item The next bit to the left is the pointer mask. A $0$ indicates
  11788. that none of the elements are pointers to the heap and a $1$
  11789. indicates that all of the elements are pointers.
  11790. \item The next $61$ bits store the length of the array.
  11791. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11792. array ($1$).
  11793. \end{itemize}
  11794. Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  11795. differentiate the kinds of values that have been injected into the
  11796. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11797. to indicate that the value is an array.
  11798. In the following subsections we provide hints regarding how to update
  11799. the passes to handle arrays.
  11800. \subsection{Reveal Casts}
  11801. The array-access operators \code{vectorof-ref} and
  11802. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11803. \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  11804. that the type checker cannot tell whether the index will be in bounds,
  11805. so the bounds check must be performed at run time. Recall that the
  11806. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11807. an \code{If} arround a vector reference for update to check whether
  11808. the index is less than the length. You should do the same for
  11809. \code{vectorof-ref} and \code{vectorof-set!} .
  11810. In addition, the handling of the \code{any-vector} operators in
  11811. \code{reveal-casts} needs to be updated to account for arrays that are
  11812. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11813. generated code should test whether the tag is for tuples (\code{010})
  11814. or arrays (\code{110}) and then dispatch to either
  11815. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11816. we add a case in \code{select\_instructions} to generate the
  11817. appropriate instructions for accessing the array length from the
  11818. header of an array.
  11819. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11820. the generated code needs to check that the index is less than the
  11821. vector length, so like the code for \code{any-vector-length}, check
  11822. the tag to determine whether to use \code{any-vector-length} or
  11823. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11824. is complete, the generated code can use \code{any-vector-ref} and
  11825. \code{any-vector-set!} for both tuples and arrays because the
  11826. instructions used for those operators do not look at the tag at the
  11827. front of the tuple or array.
  11828. \subsection{Expose Allocation}
  11829. This pass should translate the \code{make-vector} operator into
  11830. lower-level operations. In particular, the new AST node
  11831. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11832. length specified by the $\Exp$, but does not initialize the elements
  11833. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11834. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11835. element type for the array. Regarding the initialization of the array,
  11836. we recommend generated a \code{while} loop that uses
  11837. \code{vector-set!} to put the initializing value into every element of
  11838. the array.
  11839. \subsection{Remove Complex Operands}
  11840. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11841. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11842. complex and its subexpression must be atomic.
  11843. \subsection{Explicate Control}
  11844. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11845. \code{explicate\_assign}.
  11846. \subsection{Select Instructions}
  11847. Generate instructions for \code{AllocateArray} similar to those for
  11848. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11849. that the tag at the front of the array should instead use the
  11850. representation discussed in Section~\ref{sec:array-rep}.
  11851. Regarding \code{vectorof-length}, extract the length from the tag
  11852. according to the representation discussed in
  11853. Section~\ref{sec:array-rep}.
  11854. The instructions generated for \code{vectorof-ref} differ from those
  11855. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11856. that the index is not a constant so the offset must be computed at
  11857. runtime, similar to the instructions generated for
  11858. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11859. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11860. appear in an assignment and as a stand-alone statement, so make sure
  11861. to handle both situations in this pass.
  11862. Finally, the instructions for \code{any-vectorof-length} should be
  11863. similar to those for \code{vectorof-length}, except that one must
  11864. first project the array by writing zeroes into the $3$-bit tag
  11865. \begin{exercise}\normalfont
  11866. Implement a compiler for the \LangArray{} language by extending your
  11867. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11868. programs, including the one in Figure~\ref{fig:inner-product} and also
  11869. a program that multiplies two matrices. Note that matrices are
  11870. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11871. arrays by laying out each row in the array, one after the next.
  11872. \end{exercise}
  11873. \section{Challenge: Generational Collection}
  11874. The copying collector described in Section~\ref{sec:GC} can incur
  11875. significant runtime overhead because the call to \code{collect} takes
  11876. time proportional to all of the live data. One way to reduce this
  11877. overhead is to reduce how much data is inspected in each call to
  11878. \code{collect}. In particular, researchers have observed that recently
  11879. allocated data is more likely to become garbage then data that has
  11880. survived one or more previous calls to \code{collect}. This insight
  11881. motivated the creation of \emph{generational garbage collectors}
  11882. \index{subject}{generational garbage collector} that
  11883. 1) segregates data according to its age into two or more generations,
  11884. 2) allocates less space for younger generations, so collecting them is
  11885. faster, and more space for the older generations, and 3) performs
  11886. collection on the younger generations more frequently then for older
  11887. generations~\citep{Wilson:1992fk}.
  11888. For this challenge assignment, the goal is to adapt the copying
  11889. collector implemented in \code{runtime.c} to use two generations, one
  11890. for young data and one for old data. Each generation consists of a
  11891. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11892. \code{collect} function to use the two generations.
  11893. \begin{enumerate}
  11894. \item Copy the young generation's FromSpace to its ToSpace then switch
  11895. the role of the ToSpace and FromSpace
  11896. \item If there is enough space for the requested number of bytes in
  11897. the young FromSpace, then return from \code{collect}.
  11898. \item If there is not enough space in the young FromSpace for the
  11899. requested bytes, then move the data from the young generation to the
  11900. old one with the following steps:
  11901. \begin{enumerate}
  11902. \item If there is enough room in the old FromSpace, copy the young
  11903. FromSpace to the old FromSpace and then return.
  11904. \item If there is not enough room in the old FromSpace, then collect
  11905. the old generation by copying the old FromSpace to the old ToSpace
  11906. and swap the roles of the old FromSpace and ToSpace.
  11907. \item If there is enough room now, copy the young FromSpace to the
  11908. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11909. and ToSpace for the old generation. Copy the young FromSpace and
  11910. the old FromSpace into the larger FromSpace for the old
  11911. generation and then return.
  11912. \end{enumerate}
  11913. \end{enumerate}
  11914. We recommend that you generalize the \code{cheney} function so that it
  11915. can be used for all the copies mentioned above: between the young
  11916. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11917. between the young FromSpace and old FromSpace. This can be
  11918. accomplished by adding parameters to \code{cheney} that replace its
  11919. use of the global variables \code{fromspace\_begin},
  11920. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11921. Note that the collection of the young generation does not traverse the
  11922. old generation. This introduces a potential problem: there may be
  11923. young data that is only reachable through pointers in the old
  11924. generation. If these pointers are not taken into account, the
  11925. collector could throw away young data that is live! One solution,
  11926. called \emph{pointer recording}, is to maintain a set of all the
  11927. pointers from the old generation into the new generation and consider
  11928. this set as part of the root set. To maintain this set, the compiler
  11929. must insert extra instructions around every \code{vector-set!}. If the
  11930. vector being modified is in the old generation, and if the value being
  11931. written is a pointer into the new generation, than that pointer must
  11932. be added to the set. Also, if the value being overwritten was a
  11933. pointer into the new generation, then that pointer should be removed
  11934. from the set.
  11935. \begin{exercise}\normalfont
  11936. Adapt the \code{collect} function in \code{runtime.c} to implement
  11937. generational garbage collection, as outlined in this section.
  11938. Update the code generation for \code{vector-set!} to implement
  11939. pointer recording. Make sure that your new compiler and runtime
  11940. passes your test suite.
  11941. \end{exercise}
  11942. \fi}
  11943. \section{Further Reading}
  11944. There are many alternatives to copying collectors (and their bigger
  11945. siblings, the generational collectors) when its comes to garbage
  11946. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  11947. reference counting~\citep{Collins:1960aa}. The strengths of copying
  11948. collectors are that allocation is fast (just a comparison and pointer
  11949. increment), there is no fragmentation, cyclic garbage is collected,
  11950. and the time complexity of collection only depends on the amount of
  11951. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  11952. main disadvantages of a two-space copying collector is that it uses a
  11953. lot of extra space and takes a long time to perform the copy, though
  11954. these problems are ameliorated in generational collectors.
  11955. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  11956. small objects and generate a lot of garbage, so copying and
  11957. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  11958. Garbage collection is an active research topic, especially concurrent
  11959. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  11960. developing new techniques and revisiting old
  11961. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  11962. meet every year at the International Symposium on Memory Management to
  11963. present these findings.
  11964. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11965. \chapter{Functions}
  11966. \label{ch:Lfun}
  11967. \index{subject}{function}
  11968. This chapter studies the compilation of a subset of \racket{Typed
  11969. Racket}\python{Python} in which only top-level function definitions
  11970. are allowed..
  11971. This kind of function is a realistic example as the C language imposes
  11972. similar restrictions. It is also an important stepping stone to
  11973. implementing lexically-scoped functions in the form of \key{lambda}
  11974. abstractions, which is the topic of Chapter~\ref{ch:Llambda}.
  11975. \section{The \LangFun{} Language}
  11976. The concrete and abstract syntax for function definitions and function
  11977. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  11978. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  11979. \LangFun{} begin with zero or more function definitions. The function
  11980. names from these definitions are in-scope for the entire program,
  11981. including all other function definitions (so the ordering of function
  11982. definitions does not matter).
  11983. %
  11984. \python{The abstract syntax for function parameters in
  11985. Figure~\ref{fig:Rfun-syntax} is a list of pairs, where each pair
  11986. consists of a parameter name and its type. This design differs from
  11987. Python's \code{ast} module, which has a more complex structure for
  11988. function parameters to handle keyword parameters,
  11989. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  11990. complex Python abstract syntax into the simpler syntax of
  11991. Figure~\ref{fig:Rfun-syntax}. The fourth and sixth parameters of the
  11992. \code{FunctionDef} constructor are for decorators and a type
  11993. comment, neither of which are used by our compiler. We recommend
  11994. replacing them with \code{None} in the \code{shrink} pass.
  11995. }
  11996. %
  11997. The concrete syntax for function application\index{subject}{function
  11998. application} is
  11999. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12000. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12001. where the first expression
  12002. must evaluate to a function and the remaining expressions are the arguments. The
  12003. abstract syntax for function application is
  12004. $\APPLY{\Exp}{\Exp^*}$.
  12005. %% The syntax for function application does not include an explicit
  12006. %% keyword, which is error prone when using \code{match}. To alleviate
  12007. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12008. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12009. Functions are first-class in the sense that a function pointer
  12010. \index{subject}{function pointer} is data and can be stored in memory or passed
  12011. as a parameter to another function. Thus, there is a function
  12012. type, written
  12013. {\if\edition\racketEd
  12014. \begin{lstlisting}
  12015. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12016. \end{lstlisting}
  12017. \fi}
  12018. {\if\edition\pythonEd
  12019. \begin{lstlisting}
  12020. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12021. \end{lstlisting}
  12022. \fi}
  12023. %
  12024. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12025. through $\Type_n$ and whose return type is $\Type_R$. The main
  12026. limitation of these functions (with respect to
  12027. \racket{Racket}\python{Python} functions) is that they are not
  12028. lexically scoped. That is, the only external entities that can be
  12029. referenced from inside a function body are other globally-defined
  12030. functions. The syntax of \LangFun{} prevents function definitions from being
  12031. nested inside each other.
  12032. \newcommand{\LfunGrammarRacket}{
  12033. \begin{array}{lcl}
  12034. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12035. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12036. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12037. \end{array}
  12038. }
  12039. \newcommand{\LfunASTRacket}{
  12040. \begin{array}{lcl}
  12041. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12042. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12043. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12044. \end{array}
  12045. }
  12046. \newcommand{\LfunGrammarPython}{
  12047. \begin{array}{lcl}
  12048. \Type &::=& \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12049. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12050. \Stmt &::=& \CRETURN{\Exp} \\
  12051. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12052. \end{array}
  12053. }
  12054. \newcommand{\LfunASTPython}{
  12055. \begin{array}{lcl}
  12056. \Type &::=& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12057. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12058. \Stmt &::=& \RETURN{\Exp} \\
  12059. \Params &::=& \LP\Var\key{,}\Type\RP^*
  12060. % was: \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS
  12061. \\
  12062. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12063. \end{array}
  12064. }
  12065. \begin{figure}[tp]
  12066. \centering
  12067. \fbox{
  12068. \begin{minipage}{0.96\textwidth}
  12069. \small
  12070. {\if\edition\racketEd
  12071. \[
  12072. \begin{array}{l}
  12073. \gray{\LintGrammarRacket{}} \\ \hline
  12074. \gray{\LvarGrammarRacket{}} \\ \hline
  12075. \gray{\LifGrammarRacket{}} \\ \hline
  12076. \gray{\LwhileGrammarRacket} \\ \hline
  12077. \gray{\LtupGrammarRacket} \\ \hline
  12078. \LfunGrammarRacket \\
  12079. \begin{array}{lcl}
  12080. \LangFunM{} &::=& \Def \ldots \; \Exp
  12081. \end{array}
  12082. \end{array}
  12083. \]
  12084. \fi}
  12085. {\if\edition\pythonEd
  12086. \[
  12087. \begin{array}{l}
  12088. \gray{\LintGrammarPython{}} \\ \hline
  12089. \gray{\LvarGrammarPython{}} \\ \hline
  12090. \gray{\LifGrammarPython{}} \\ \hline
  12091. \gray{\LwhileGrammarPython} \\ \hline
  12092. \gray{\LtupGrammarPython} \\ \hline
  12093. \LfunGrammarPython \\
  12094. \begin{array}{rcl}
  12095. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12096. \end{array}
  12097. \end{array}
  12098. \]
  12099. \fi}
  12100. \end{minipage}
  12101. }
  12102. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  12103. \label{fig:Rfun-concrete-syntax}
  12104. \end{figure}
  12105. \begin{figure}[tp]
  12106. \centering
  12107. \fbox{
  12108. \begin{minipage}{0.96\textwidth}
  12109. \small
  12110. {\if\edition\racketEd
  12111. \[
  12112. \begin{array}{l}
  12113. \gray{\LintOpAST} \\ \hline
  12114. \gray{\LvarASTRacket{}} \\ \hline
  12115. \gray{\LifASTRacket{}} \\ \hline
  12116. \gray{\LwhileASTRacket{}} \\ \hline
  12117. \gray{\LtupASTRacket{}} \\ \hline
  12118. \LfunASTRacket \\
  12119. \begin{array}{lcl}
  12120. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12121. \end{array}
  12122. \end{array}
  12123. \]
  12124. \fi}
  12125. {\if\edition\pythonEd
  12126. \[
  12127. \begin{array}{l}
  12128. \gray{\LintASTPython{}} \\ \hline
  12129. \gray{\LvarASTPython{}} \\ \hline
  12130. \gray{\LifASTPython{}} \\ \hline
  12131. \gray{\LwhileASTPython} \\ \hline
  12132. \gray{\LtupASTPython} \\ \hline
  12133. \LfunASTPython \\
  12134. \begin{array}{rcl}
  12135. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12136. \end{array}
  12137. \end{array}
  12138. \]
  12139. \fi}
  12140. \end{minipage}
  12141. }
  12142. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12143. \label{fig:Rfun-syntax}
  12144. \end{figure}
  12145. The program in Figure~\ref{fig:Rfun-function-example} is a
  12146. representative example of defining and using functions in \LangFun{}.
  12147. We define a function \code{map} that applies some other function
  12148. \code{f} to both elements of a tuple and returns a new tuple
  12149. containing the results. We also define a function \code{inc}. The
  12150. program applies \code{map} to \code{inc} and
  12151. %
  12152. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12153. %
  12154. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12155. %
  12156. from which we return the \code{42}.
  12157. \begin{figure}[tbp]
  12158. {\if\edition\racketEd
  12159. \begin{lstlisting}
  12160. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12161. : (Vector Integer Integer)
  12162. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12163. (define (inc [x : Integer]) : Integer
  12164. (+ x 1))
  12165. (vector-ref (map inc (vector 0 41)) 1)
  12166. \end{lstlisting}
  12167. \fi}
  12168. {\if\edition\pythonEd
  12169. \begin{lstlisting}
  12170. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12171. return f(v[0]), f(v[1])
  12172. def inc(x : int) -> int:
  12173. return x + 1
  12174. print( map(inc, (0, 41))[1] )
  12175. \end{lstlisting}
  12176. \fi}
  12177. \caption{Example of using functions in \LangFun{}.}
  12178. \label{fig:Rfun-function-example}
  12179. \end{figure}
  12180. The definitional interpreter for \LangFun{} is in
  12181. Figure~\ref{fig:interp-Rfun}. The case for the
  12182. %
  12183. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12184. %
  12185. AST is responsible for setting up the mutual recursion between the
  12186. top-level function definitions.
  12187. %
  12188. \racket{We use the classic back-patching
  12189. \index{subject}{back-patching} approach that uses mutable variables
  12190. and makes two passes over the function
  12191. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12192. top-level environment using a mutable cons cell for each function
  12193. definition. Note that the \code{lambda} value for each function is
  12194. incomplete; it does not yet include the environment. Once the
  12195. top-level environment is constructed, we then iterate over it and
  12196. update the \code{lambda} values to use the top-level environment.}
  12197. %
  12198. \python{We create a dictionary named \code{env} and fill it in
  12199. by mapping each function name to a new \code{Function} value,
  12200. each of which stores a reference to the \code{env}.
  12201. (We define the class \code{Function} for this purpose.)}
  12202. %
  12203. To interpret a function \racket{application}\python{call}, we match
  12204. the result of the function expression to obtain a function value. We
  12205. then extend the function's environment with mapping of parameters to
  12206. argument values. Finally, we interpret the body of the function in
  12207. this extended environment.
  12208. \begin{figure}[tp]
  12209. {\if\edition\racketEd
  12210. \begin{lstlisting}
  12211. (define interp-Rfun_class
  12212. (class interp-Lvec_class
  12213. (super-new)
  12214. (define/override ((interp-exp env) e)
  12215. (define recur (interp-exp env))
  12216. (match e
  12217. [(Var x) (unbox (dict-ref env x))]
  12218. [(Let x e body)
  12219. (define new-env (dict-set env x (box (recur e))))
  12220. ((interp-exp new-env) body)]
  12221. [(Apply fun args)
  12222. (define fun-val (recur fun))
  12223. (define arg-vals (for/list ([e args]) (recur e)))
  12224. (match fun-val
  12225. [`(function (,xs ...) ,body ,fun-env)
  12226. (define params-args (for/list ([x xs] [arg arg-vals])
  12227. (cons x (box arg))))
  12228. (define new-env (append params-args fun-env))
  12229. ((interp-exp new-env) body)]
  12230. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12231. [else ((super interp-exp env) e)]
  12232. ))
  12233. (define/public (interp-def d)
  12234. (match d
  12235. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12236. (cons f (box `(function ,xs ,body ())))]))
  12237. (define/override (interp-program p)
  12238. (match p
  12239. [(ProgramDefsExp info ds body)
  12240. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12241. (for/list ([f (in-dict-values top-level)])
  12242. (set-box! f (match (unbox f)
  12243. [`(function ,xs ,body ())
  12244. `(function ,xs ,body ,top-level)])))
  12245. ((interp-exp top-level) body))]))
  12246. ))
  12247. (define (interp-Rfun p)
  12248. (send (new interp-Rfun_class) interp-program p))
  12249. \end{lstlisting}
  12250. \fi}
  12251. {\if\edition\pythonEd
  12252. \begin{lstlisting}
  12253. class InterpLfun(InterpLtup):
  12254. def apply_fun(self, fun, args, e):
  12255. match fun:
  12256. case Function(name, xs, body, env):
  12257. new_env = {x: v for (x,v) in env.items()}
  12258. for (x,arg) in zip(xs, args):
  12259. new_env[x] = arg
  12260. return self.interp_stmts(body, new_env)
  12261. case _:
  12262. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12263. def interp_exp(self, e, env):
  12264. match e:
  12265. case Call(Name('input_int'), []):
  12266. return super().interp_exp(e, env)
  12267. case Call(func, args):
  12268. f = self.interp_exp(func, env)
  12269. vs = [self.interp_exp(arg, env) for arg in args]
  12270. return self.apply_fun(f, vs, e)
  12271. case _:
  12272. return super().interp_exp(e, env)
  12273. def interp_stmts(self, ss, env):
  12274. if len(ss) == 0:
  12275. return
  12276. match ss[0]:
  12277. case Return(value):
  12278. return self.interp_exp(value, env)
  12279. case _:
  12280. return super().interp_stmts(ss, env)
  12281. def interp(self, p):
  12282. match p:
  12283. case Module(defs):
  12284. env = {}
  12285. for d in defs:
  12286. match d:
  12287. case FunctionDef(name, params, bod, dl, returns, comment):
  12288. env[name] = Function(name, [x for (x,t) in params], bod, env)
  12289. self.apply_fun(env['main'], [], None)
  12290. case _:
  12291. raise Exception('interp: unexpected ' + repr(p))
  12292. \end{lstlisting}
  12293. \fi}
  12294. \caption{Interpreter for the \LangFun{} language.}
  12295. \label{fig:interp-Rfun}
  12296. \end{figure}
  12297. %\margincomment{TODO: explain type checker}
  12298. The type checker for \LangFun{} is in
  12299. Figure~\ref{fig:type-check-Rfun}. (We omit the code that parses
  12300. function parameters into the simpler abstract syntax.) Similar to the
  12301. interpreter, the case for the
  12302. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12303. %
  12304. AST is responsible for setting up the mutual recursion between the
  12305. top-level function definitions. We begin by create a mapping
  12306. \code{env} from every function name to its type. We then type check
  12307. the program using this mapping.
  12308. %
  12309. In the case for function \racket{application}\python{call}, we match
  12310. the type of the function expression to a function type and check that
  12311. the types of the argument expressions are equal to the function's
  12312. parameter types. The type of the \racket{application}\python{call} as
  12313. a whole is the return type from the function type.
  12314. \begin{figure}[tp]
  12315. {\if\edition\racketEd
  12316. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12317. (define type-check-Rfun_class
  12318. (class type-check-Lvec_class
  12319. (super-new)
  12320. (inherit check-type-equal?)
  12321. (define/public (type-check-apply env e es)
  12322. (define-values (e^ ty) ((type-check-exp env) e))
  12323. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12324. ((type-check-exp env) e)))
  12325. (match ty
  12326. [`(,ty^* ... -> ,rt)
  12327. (for ([arg-ty ty*] [param-ty ty^*])
  12328. (check-type-equal? arg-ty param-ty (Apply e es)))
  12329. (values e^ e* rt)]))
  12330. (define/override (type-check-exp env)
  12331. (lambda (e)
  12332. (match e
  12333. [(FunRef f)
  12334. (values (FunRef f) (dict-ref env f))]
  12335. [(Apply e es)
  12336. (define-values (e^ es^ rt) (type-check-apply env e es))
  12337. (values (Apply e^ es^) rt)]
  12338. [(Call e es)
  12339. (define-values (e^ es^ rt) (type-check-apply env e es))
  12340. (values (Call e^ es^) rt)]
  12341. [else ((super type-check-exp env) e)])))
  12342. (define/public (type-check-def env)
  12343. (lambda (e)
  12344. (match e
  12345. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12346. (define new-env (append (map cons xs ps) env))
  12347. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12348. (check-type-equal? ty^ rt body)
  12349. (Def f p:t* rt info body^)])))
  12350. (define/public (fun-def-type d)
  12351. (match d
  12352. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12353. (define/override (type-check-program e)
  12354. (match e
  12355. [(ProgramDefsExp info ds body)
  12356. (define env (for/list ([d ds])
  12357. (cons (Def-name d) (fun-def-type d))))
  12358. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12359. (define-values (body^ ty) ((type-check-exp env) body))
  12360. (check-type-equal? ty 'Integer body)
  12361. (ProgramDefsExp info ds^ body^)]))))
  12362. (define (type-check-Rfun p)
  12363. (send (new type-check-Rfun_class) type-check-program p))
  12364. \end{lstlisting}
  12365. \fi}
  12366. {\if\edition\pythonEd
  12367. \begin{lstlisting}
  12368. class TypeCheckLfun(TypeCheckLtup):
  12369. def type_check_exp(self, e, env):
  12370. match e:
  12371. case Call(Name('input_int'), []):
  12372. return super().type_check_exp(e, env)
  12373. case Call(func, args):
  12374. func_t = self.type_check_exp(func, env)
  12375. args_t = [self.type_check_exp(arg, env) for arg in args]
  12376. match func_t:
  12377. case FunctionType(params_t, return_t):
  12378. for (arg_t, param_t) in zip(args_t, params_t):
  12379. check_type_equal(param_t, arg_t, e)
  12380. return return_t
  12381. case _:
  12382. raise Exception('type_check_exp: in call, unexpected ' + \
  12383. repr(func_t))
  12384. case _:
  12385. return super().type_check_exp(e, env)
  12386. def type_check_stmts(self, ss, env):
  12387. if len(ss) == 0:
  12388. return
  12389. match ss[0]:
  12390. case FunctionDef(name, params, body, dl, returns, comment):
  12391. new_env = {x: t for (x,t) in env.items()}
  12392. for (x,t) in params:
  12393. new_env[x] = t
  12394. rt = self.type_check_stmts(body, new_env)
  12395. check_type_equal(returns, rt, ss[0])
  12396. return self.type_check_stmts(ss[1:], env)
  12397. case Return(value):
  12398. return self.type_check_exp(value, env)
  12399. case _:
  12400. return super().type_check_stmts(ss, env)
  12401. def type_check(self, p):
  12402. match p:
  12403. case Module(body):
  12404. env = {}
  12405. for s in body:
  12406. match s:
  12407. case FunctionDef(name, params, bod, dl, returns, comment):
  12408. params_t = [t for (x,t) in params]
  12409. env[name] = FunctionType(params_t, returns)
  12410. self.type_check_stmts(body, env)
  12411. case _:
  12412. raise Exception('type_check: unexpected ' + repr(p))
  12413. \end{lstlisting}
  12414. \fi}
  12415. \caption{Type checker for the \LangFun{} language.}
  12416. \label{fig:type-check-Rfun}
  12417. \end{figure}
  12418. \clearpage
  12419. \section{Functions in x86}
  12420. \label{sec:fun-x86}
  12421. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12422. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12423. %% \margincomment{\tiny Talk about the return address on the
  12424. %% stack and what callq and retq does.\\ --Jeremy }
  12425. The x86 architecture provides a few features to support the
  12426. implementation of functions. We have already seen that there are
  12427. labels in x86 so that one can refer to the location of an instruction, as is
  12428. needed for jump instructions. Labels can also be used to mark the
  12429. beginning of the instructions for a function. Going further, we can
  12430. obtain the address of a label by using the \key{leaq} instruction and
  12431. PC-relative addressing. For example, the following puts the
  12432. address of the \code{inc} label into the \code{rbx} register.
  12433. \begin{lstlisting}
  12434. leaq inc(%rip), %rbx
  12435. \end{lstlisting}
  12436. The instruction pointer register \key{rip} (aka. the program counter
  12437. \index{subject}{program counter}) always points to the next
  12438. instruction to be executed. When combined with a label, as in
  12439. \code{inc(\%rip)}, the assembler computes the distance $d$ between the
  12440. address of \code{inc} and where the \code{rip} would be at that moment
  12441. and then changes the \code{inc(\%rip)} argument to \code{$d$(\%rip)},
  12442. which at runtime will compute the address of \code{inc}.
  12443. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12444. to functions whose locations were given by a label, such as
  12445. \code{read\_int}. To support function calls in this chapter we instead
  12446. will be jumping to functions whose location are given by an address in
  12447. a register, that is, we need to make an \emph{indirect function
  12448. call}. The x86 syntax for this is a \code{callq} instruction but with
  12449. an asterisk before the register name.\index{subject}{indirect function
  12450. call}
  12451. \begin{lstlisting}
  12452. callq *%rbx
  12453. \end{lstlisting}
  12454. \subsection{Calling Conventions}
  12455. \index{subject}{calling conventions}
  12456. The \code{callq} instruction provides partial support for implementing
  12457. functions: it pushes the return address on the stack and it jumps to
  12458. the target. However, \code{callq} does not handle
  12459. \begin{enumerate}
  12460. \item parameter passing,
  12461. \item pushing frames on the procedure call stack and popping them off,
  12462. or
  12463. \item determining how registers are shared by different functions.
  12464. \end{enumerate}
  12465. Regarding (1) parameter passing, recall that the following six
  12466. registers are used to pass arguments to a function, in this order.
  12467. \begin{lstlisting}
  12468. rdi rsi rdx rcx r8 r9
  12469. \end{lstlisting}
  12470. If there are
  12471. more than six arguments, then the convention is to use space on the
  12472. frame of the caller for the rest of the arguments. However, to ease
  12473. the implementation of efficient tail calls
  12474. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12475. arguments.
  12476. %
  12477. Also recall that the register \code{rax} is for the return value of
  12478. the function.
  12479. \index{subject}{prelude}\index{subject}{conclusion}
  12480. Regarding (2) frames \index{subject}{frame} and the procedure call
  12481. stack, \index{subject}{procedure call stack} recall from
  12482. Section~\ref{sec:x86} that the stack grows down and each function call
  12483. uses a chunk of space on the stack called a frame. The caller sets the
  12484. stack pointer, register \code{rsp}, to the last data item in its
  12485. frame. The callee must not change anything in the caller's frame, that
  12486. is, anything that is at or above the stack pointer. The callee is free
  12487. to use locations that are below the stack pointer.
  12488. Recall that we are storing variables of tuple type on the root stack.
  12489. So the prelude needs to move the root stack pointer \code{r15} up
  12490. according to the number of variables of tuple type and
  12491. the conclusion needs to move the root stack pointer back down. Also,
  12492. the prelude must initialize to \code{0} this frame's slots in the root
  12493. stack to signal to the garbage collector that those slots do not yet
  12494. contain a pointer to a vector. Otherwise the garbage collector will
  12495. interpret the garbage bits in those slots as memory addresses and try
  12496. to traverse them, causing serious mayhem!
  12497. Regarding (3) the sharing of registers between different functions,
  12498. recall from Section~\ref{sec:calling-conventions} that the registers
  12499. are divided into two groups, the caller-saved registers and the
  12500. callee-saved registers. The caller should assume that all the
  12501. caller-saved registers get overwritten with arbitrary values by the
  12502. callee. For that reason we recommend in
  12503. Section~\ref{sec:calling-conventions} that variables that are live
  12504. during a function call should not be assigned to caller-saved
  12505. registers.
  12506. On the flip side, if the callee wants to use a callee-saved register,
  12507. the callee must save the contents of those registers on their stack
  12508. frame and then put them back prior to returning to the caller. For
  12509. that reason we recommend in Section~\ref{sec:calling-conventions} that if
  12510. the register allocator assigns a variable to a callee-saved register,
  12511. then the prelude of the \code{main} function must save that register
  12512. to the stack and the conclusion of \code{main} must restore it. This
  12513. recommendation now generalizes to all functions.
  12514. Recall that the base pointer, register \code{rbp}, is used as a
  12515. point-of-reference within a frame, so that each local variable can be
  12516. accessed at a fixed offset from the base pointer
  12517. (Section~\ref{sec:x86}).
  12518. %
  12519. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12520. and callee frames.
  12521. \begin{figure}[tbp]
  12522. \centering
  12523. \begin{tabular}{r|r|l|l} \hline
  12524. Caller View & Callee View & Contents & Frame \\ \hline
  12525. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12526. 0(\key{\%rbp}) & & old \key{rbp} \\
  12527. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12528. \ldots & & \ldots \\
  12529. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12530. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12531. \ldots & & \ldots \\
  12532. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12533. %% & & \\
  12534. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12535. %% & \ldots & \ldots \\
  12536. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12537. \hline
  12538. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12539. & 0(\key{\%rbp}) & old \key{rbp} \\
  12540. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12541. & \ldots & \ldots \\
  12542. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12543. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12544. & \ldots & \ldots \\
  12545. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12546. \end{tabular}
  12547. \caption{Memory layout of caller and callee frames.}
  12548. \label{fig:call-frames}
  12549. \end{figure}
  12550. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12551. %% local variables and for storing the values of callee-saved registers
  12552. %% (we shall refer to all of these collectively as ``locals''), and that
  12553. %% at the beginning of a function we move the stack pointer \code{rsp}
  12554. %% down to make room for them.
  12555. %% We recommend storing the local variables
  12556. %% first and then the callee-saved registers, so that the local variables
  12557. %% can be accessed using \code{rbp} the same as before the addition of
  12558. %% functions.
  12559. %% To make additional room for passing arguments, we shall
  12560. %% move the stack pointer even further down. We count how many stack
  12561. %% arguments are needed for each function call that occurs inside the
  12562. %% body of the function and find their maximum. Adding this number to the
  12563. %% number of locals gives us how much the \code{rsp} should be moved at
  12564. %% the beginning of the function. In preparation for a function call, we
  12565. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12566. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12567. %% so on.
  12568. %% Upon calling the function, the stack arguments are retrieved by the
  12569. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12570. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12571. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12572. %% the layout of the caller and callee frames. Notice how important it is
  12573. %% that we correctly compute the maximum number of arguments needed for
  12574. %% function calls; if that number is too small then the arguments and
  12575. %% local variables will smash into each other!
  12576. \subsection{Efficient Tail Calls}
  12577. \label{sec:tail-call}
  12578. In general, the amount of stack space used by a program is determined
  12579. by the longest chain of nested function calls. That is, if function
  12580. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, $f_n$, then the amount
  12581. of stack space is linear in $n$. The depth $n$ can grow quite large
  12582. if functions are (mutually) recursive. However, in
  12583. some cases we can arrange to use only a constant amount of space for a
  12584. long chain of nested function calls.
  12585. A \emph{tail call}\index{subject}{tail call} is a function call that
  12586. happens as the last action in a function body.
  12587. For example, in the following
  12588. program, the recursive call to \code{tail\_sum} is a tail call.
  12589. \begin{center}
  12590. {\if\edition\racketEd
  12591. \begin{lstlisting}
  12592. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12593. (if (eq? n 0)
  12594. r
  12595. (tail_sum (- n 1) (+ n r))))
  12596. (+ (tail_sum 3 0) 36)
  12597. \end{lstlisting}
  12598. \fi}
  12599. {\if\edition\pythonEd
  12600. \begin{lstlisting}
  12601. def tail_sum(n : int, r : int) -> int:
  12602. if n == 0:
  12603. return r
  12604. else:
  12605. return tail_sum(n - 1, n + r)
  12606. print( tail_sum(3, 0) + 36)
  12607. \end{lstlisting}
  12608. \fi}
  12609. \end{center}
  12610. At a tail call, the frame of the caller is no longer needed, so we can
  12611. pop the caller's frame before making the tail call. With this
  12612. approach, a recursive function that only makes tail calls ends up
  12613. using a constant amount of stack space. Functional languages like
  12614. Racket rely heavily on recursive functions, so the definition of
  12615. Racket \emph{requires} that all tail calls be optimized in this way.
  12616. \index{subject}{frame}
  12617. Some care is needed with regards to argument passing in tail calls.
  12618. As mentioned above, for arguments beyond the sixth, the convention is
  12619. to use space in the caller's frame for passing arguments. But for a
  12620. tail call we pop the caller's frame and can no longer use it. An
  12621. alternative is to use space in the callee's frame for passing
  12622. arguments. However, this option is also problematic because the caller
  12623. and callee's frames overlap in memory. As we begin to copy the
  12624. arguments from their sources in the caller's frame, the target
  12625. locations in the callee's frame might collide with the sources for
  12626. later arguments! We solve this problem by using the heap instead of
  12627. the stack for passing more than six arguments, which we describe in
  12628. the Section~\ref{sec:limit-functions-r4}.
  12629. As mentioned above, for a tail call we pop the caller's frame prior to
  12630. making the tail call. The instructions for popping a frame are the
  12631. instructions that we usually place in the conclusion of a
  12632. function. Thus, we also need to place such code immediately before
  12633. each tail call. These instructions include restoring the callee-saved
  12634. registers, so it is fortunate that the argument passing registers are
  12635. all caller-saved registers!
  12636. One last note regarding which instruction to use to make the tail
  12637. call. When the callee is finished, it should not return to the current
  12638. function, but it should return to the function that called the current
  12639. one. Thus, the return address that is already on the stack is the
  12640. right one, and we should not use \key{callq} to make the tail call, as
  12641. that would unnecessarily overwrite the return address. Instead we can
  12642. simply use the \key{jmp} instruction. Like the indirect function call,
  12643. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12644. register prefixed with an asterisk. We recommend using \code{rax} to
  12645. hold the jump target because the preceding conclusion can overwrite
  12646. just about everything else.
  12647. \begin{lstlisting}
  12648. jmp *%rax
  12649. \end{lstlisting}
  12650. \section{Shrink \LangFun{}}
  12651. \label{sec:shrink-r4}
  12652. The \code{shrink} pass performs a minor modification to ease the
  12653. later passes. This pass introduces an explicit \code{main} function
  12654. that gobbles up all the top-level statements of the module.
  12655. %
  12656. \racket{It also changes the top \code{ProgramDefsExp} form to
  12657. \code{ProgramDefs}.}
  12658. {\if\edition\racketEd
  12659. \begin{lstlisting}
  12660. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12661. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12662. \end{lstlisting}
  12663. where $\itm{mainDef}$ is
  12664. \begin{lstlisting}
  12665. (Def 'main '() 'Integer '() |$\Exp'$|)
  12666. \end{lstlisting}
  12667. \fi}
  12668. {\if\edition\pythonEd
  12669. \begin{lstlisting}
  12670. Module(|$\Def\ldots\Stmt\ldots$|)
  12671. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12672. \end{lstlisting}
  12673. where $\itm{mainDef}$ is
  12674. \begin{lstlisting}
  12675. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  12676. \end{lstlisting}
  12677. \fi}
  12678. \section{Reveal Functions and the \LangFunRef{} language}
  12679. \label{sec:reveal-functions-r4}
  12680. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12681. in that it conflates the use of function names and local
  12682. variables. This is a problem because we need to compile the use of a
  12683. function name differently than the use of a local variable; we need to
  12684. use \code{leaq} to convert the function name (a label in x86) to an
  12685. address in a register. Thus, we create a new pass that changes
  12686. function references from $\VAR{f}$ to $\FUNREF{f}$. This pass is named
  12687. \code{reveal\_functions} and the output language, \LangFunRef{}, is
  12688. defined in Figure~\ref{fig:f1-syntax}.
  12689. %% The concrete syntax for a
  12690. %% function reference is $\CFUNREF{f}$.
  12691. \begin{figure}[tp]
  12692. \centering
  12693. \fbox{
  12694. \begin{minipage}{0.96\textwidth}
  12695. {\if\edition\racketEd
  12696. \[
  12697. \begin{array}{lcl}
  12698. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  12699. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12700. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12701. \end{array}
  12702. \]
  12703. \fi}
  12704. {\if\edition\pythonEd
  12705. \[
  12706. \begin{array}{lcl}
  12707. \Exp &::=& \FUNREF{\Var}\\
  12708. \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12709. \end{array}
  12710. \]
  12711. \fi}
  12712. \end{minipage}
  12713. }
  12714. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12715. (Figure~\ref{fig:Rfun-syntax}).}
  12716. \label{fig:f1-syntax}
  12717. \end{figure}
  12718. %% Distinguishing between calls in tail position and non-tail position
  12719. %% requires the pass to have some notion of context. We recommend using
  12720. %% two mutually recursive functions, one for processing expressions in
  12721. %% tail position and another for the rest.
  12722. \racket{Placing this pass after \code{uniquify} will make sure that
  12723. there are no local variables and functions that share the same
  12724. name.}
  12725. %
  12726. The \code{reveal\_functions} pass should come before the
  12727. \code{remove\_complex\_operands} pass because function references
  12728. should be categorized as complex expressions.
  12729. \section{Limit Functions}
  12730. \label{sec:limit-functions-r4}
  12731. Recall that we wish to limit the number of function parameters to six
  12732. so that we do not need to use the stack for argument passing, which
  12733. makes it easier to implement efficient tail calls. However, because
  12734. the input language \LangFun{} supports arbitrary numbers of function
  12735. arguments, we have some work to do!
  12736. This pass transforms functions and function calls that involve more
  12737. than six arguments to pass the first five arguments as usual, but it
  12738. packs the rest of the arguments into a vector and passes it as the
  12739. sixth argument.
  12740. Each function definition with seven or more parameters is transformed as
  12741. follows.
  12742. {\if\edition\racketEd
  12743. \begin{lstlisting}
  12744. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12745. |$\Rightarrow$|
  12746. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12747. \end{lstlisting}
  12748. \fi}
  12749. {\if\edition\pythonEd
  12750. \begin{lstlisting}
  12751. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  12752. |$\Rightarrow$|
  12753. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  12754. |$T_r$|, None, |$\itm{body}'$|, None)
  12755. \end{lstlisting}
  12756. \fi}
  12757. %
  12758. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12759. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12760. the $k$th element of the tuple, where $k = i - 6$.
  12761. %
  12762. {\if\edition\racketEd
  12763. \begin{lstlisting}
  12764. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12765. \end{lstlisting}
  12766. \fi}
  12767. {\if\edition\pythonEd
  12768. \begin{lstlisting}
  12769. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  12770. \end{lstlisting}
  12771. \fi}
  12772. For function calls with too many arguments, the \code{limit\_functions}
  12773. pass transforms them in the following way.
  12774. \begin{tabular}{lll}
  12775. \begin{minipage}{0.3\textwidth}
  12776. {\if\edition\racketEd
  12777. \begin{lstlisting}
  12778. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12779. \end{lstlisting}
  12780. \fi}
  12781. {\if\edition\pythonEd
  12782. \begin{lstlisting}
  12783. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12784. \end{lstlisting}
  12785. \fi}
  12786. \end{minipage}
  12787. &
  12788. $\Rightarrow$
  12789. &
  12790. \begin{minipage}{0.5\textwidth}
  12791. {\if\edition\racketEd
  12792. \begin{lstlisting}
  12793. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12794. \end{lstlisting}
  12795. \fi}
  12796. {\if\edition\pythonEd
  12797. \begin{lstlisting}
  12798. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12799. \end{lstlisting}
  12800. \fi}
  12801. \end{minipage}
  12802. \end{tabular}
  12803. \section{Remove Complex Operands}
  12804. \label{sec:rco-r4}
  12805. The primary decisions to make for this pass is whether to classify
  12806. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12807. atomic or complex expressions. Recall that a simple expression will
  12808. eventually end up as just an immediate argument of an x86
  12809. instruction. Function application will be translated to a sequence of
  12810. instructions, so \racket{\code{Apply}}\python{\code{Call}} must be
  12811. classified as complex expression. On the other hand, the arguments of
  12812. \racket{\code{Apply}}\python{\code{Call}} should be atomic expressions.
  12813. %
  12814. Regarding \code{FunRef}, as discussed above, the function label needs
  12815. to be converted to an address using the \code{leaq} instruction. Thus,
  12816. even though \code{FunRef} seems rather simple, it needs to be
  12817. classified as a complex expression so that we generate an assignment
  12818. statement with a left-hand side that can serve as the target of the
  12819. \code{leaq}.
  12820. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  12821. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  12822. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  12823. %
  12824. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  12825. % TODO: Return?
  12826. %% Figure~\ref{fig:Rfun-anf-syntax} defines the output language
  12827. %% \LangFunANF{} of this pass.
  12828. %% \begin{figure}[tp]
  12829. %% \centering
  12830. %% \fbox{
  12831. %% \begin{minipage}{0.96\textwidth}
  12832. %% \small
  12833. %% \[
  12834. %% \begin{array}{rcl}
  12835. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12836. %% \MID \VOID{} } \\
  12837. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12838. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12839. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12840. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12841. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12842. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12843. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  12844. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12845. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12846. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12847. %% \end{array}
  12848. %% \]
  12849. %% \end{minipage}
  12850. %% }
  12851. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12852. %% \label{fig:Rfun-anf-syntax}
  12853. %% \end{figure}
  12854. \section{Explicate Control and the \LangCFun{} language}
  12855. \label{sec:explicate-control-r4}
  12856. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12857. output of \code{explicate\_control}.
  12858. %
  12859. \racket{(The concrete syntax is given in
  12860. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  12861. %
  12862. The auxiliary functions for assignment\racket{and tail contexts} should
  12863. be updated with cases for
  12864. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  12865. function for predicate context should be updated for
  12866. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  12867. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  12868. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  12869. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  12870. auxiliary function for processing function definitions. This code is
  12871. similar to the case for \code{Program} in \LangVec{}. The top-level
  12872. \code{explicate\_control} function that handles the \code{ProgramDefs}
  12873. form of \LangFun{} can then apply this new function to all the
  12874. function definitions.
  12875. {\if\edition\pythonEd
  12876. The translation of \code{Return} statements requires a new auxiliary
  12877. function to handle expressions in tail context, called
  12878. \code{explicate\_tail}. The function should take an expression and the
  12879. dictionary of basic blocks and produce a list of statements in the
  12880. \LangCFun{} language. The \code{explicate\_tail} function should
  12881. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  12882. and a default case for other kinds of expressions. The default case
  12883. should produce a \code{Return} statement. The case for \code{Call}
  12884. should change it into \code{TailCall}. The other cases should
  12885. recursively process their subexpressions and statements, choosing the
  12886. appropriate explicate functions for the various contexts.
  12887. \fi}
  12888. \newcommand{\CfunASTRacket}{
  12889. \begin{array}{lcl}
  12890. \Exp &::= & \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12891. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  12892. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12893. \end{array}
  12894. }
  12895. \newcommand{\CfunASTPython}{
  12896. \begin{array}{lcl}
  12897. \Exp &::= & \FUNREF{\itm{label}} \MID \CALL{\Atm}{\Atm^{*}} \\
  12898. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  12899. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  12900. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  12901. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  12902. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  12903. \end{array}
  12904. }
  12905. \begin{figure}[tp]
  12906. \fbox{
  12907. \begin{minipage}{0.96\textwidth}
  12908. \small
  12909. {\if\edition\racketEd
  12910. \[
  12911. \begin{array}{l}
  12912. \gray{\CvarASTRacket} \\ \hline
  12913. \gray{\CifASTRacket} \\ \hline
  12914. \gray{\CloopASTRacket} \\ \hline
  12915. \gray{\CtupASTRacket} \\ \hline
  12916. \CfunASTRacket \\
  12917. \begin{array}{lcl}
  12918. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12919. \end{array}
  12920. \end{array}
  12921. \]
  12922. \fi}
  12923. {\if\edition\pythonEd
  12924. \[
  12925. \begin{array}{l}
  12926. \gray{\CifASTPython} \\ \hline
  12927. \gray{\CtupASTPython} \\ \hline
  12928. \CfunASTPython \\
  12929. \begin{array}{lcl}
  12930. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12931. \end{array}
  12932. \end{array}
  12933. \]
  12934. \fi}
  12935. \end{minipage}
  12936. }
  12937. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  12938. \label{fig:c3-syntax}
  12939. \end{figure}
  12940. \section{Select Instructions and the \LangXIndCall{} Language}
  12941. \label{sec:select-r4}
  12942. \index{subject}{instruction selection}
  12943. The output of select instructions is a program in the \LangXIndCall{}
  12944. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  12945. \index{subject}{x86}
  12946. \begin{figure}[tp]
  12947. \fbox{
  12948. \begin{minipage}{0.96\textwidth}
  12949. \small
  12950. \[
  12951. \begin{array}{lcl}
  12952. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  12953. \itm{cc} & ::= & \gray{ \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  12954. \Instr &::=& \ldots
  12955. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  12956. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  12957. \Block &::= & \itm{label}\key{:}\, \Instr^{*} \\
  12958. \Def &::= & \key{.globl}\,\itm{label}\; \Block^{*} \\
  12959. \LangXIndCallM{} &::= & \Def\ldots
  12960. \end{array}
  12961. \]
  12962. \end{minipage}
  12963. }
  12964. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  12965. \label{fig:x86-3-concrete}
  12966. \end{figure}
  12967. \begin{figure}[tp]
  12968. \fbox{
  12969. \begin{minipage}{0.96\textwidth}
  12970. \small
  12971. {\if\edition\racketEd
  12972. \[
  12973. \begin{array}{lcl}
  12974. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12975. \MID \BYTEREG{\Reg} } \\
  12976. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}} \\
  12977. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12978. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12979. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  12980. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  12981. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  12982. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12983. \end{array}
  12984. \]
  12985. \fi}
  12986. {\if\edition\pythonEd
  12987. \[
  12988. \begin{array}{lcl}
  12989. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12990. \MID \BYTEREG{\Reg} } \\
  12991. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}} \\
  12992. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12993. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12994. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  12995. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  12996. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  12997. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  12998. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12999. \end{array}
  13000. \]
  13001. \fi}
  13002. \end{minipage}
  13003. }
  13004. \caption{The abstract syntax of \LangXIndCall{} (extends
  13005. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  13006. \label{fig:x86-3}
  13007. \end{figure}
  13008. An assignment of a function reference to a variable becomes a
  13009. load-effective-address instruction as follows, where $\itm{lhs}'$
  13010. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  13011. to \Arg{} in \LangXIndCallVar{}. \\
  13012. \begin{tabular}{lcl}
  13013. \begin{minipage}{0.35\textwidth}
  13014. {\if\edition\racketEd
  13015. \begin{lstlisting}
  13016. |$\itm{lhs}$| = (fun-ref |$f$|);
  13017. \end{lstlisting}
  13018. \fi}
  13019. {\if\edition\pythonEd
  13020. \begin{lstlisting}
  13021. |$\itm{lhs}$| = FunRef(|$f$|);
  13022. \end{lstlisting}
  13023. \fi}
  13024. \end{minipage}
  13025. &
  13026. $\Rightarrow$\qquad\qquad
  13027. &
  13028. \begin{minipage}{0.3\textwidth}
  13029. {\if\edition\racketEd
  13030. \begin{lstlisting}
  13031. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  13032. \end{lstlisting}
  13033. \fi}
  13034. {\if\edition\pythonEd
  13035. \begin{lstlisting}
  13036. leaq (FunRef(|$f$|)), |$\itm{lhs}'$|
  13037. \end{lstlisting}
  13038. \fi}
  13039. \end{minipage}
  13040. \end{tabular} \\
  13041. Regarding function definitions, we need to remove the parameters and
  13042. instead perform parameter passing using the conventions discussed in
  13043. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13044. registers. We recommend turning the parameters into local variables
  13045. and generating instructions at the beginning of the function to move
  13046. from the argument passing registers to these local variables.
  13047. {\if\edition\racketEd
  13048. \begin{lstlisting}
  13049. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13050. |$\Rightarrow$|
  13051. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13052. \end{lstlisting}
  13053. \fi}
  13054. {\if\edition\pythonEd
  13055. \begin{lstlisting}
  13056. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13057. |$\Rightarrow$|
  13058. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13059. \end{lstlisting}
  13060. \fi}
  13061. The basic blocks $B'$ are the same as $B$ except that the
  13062. \code{start} block is modified to add the instructions for moving from
  13063. the argument registers to the parameter variables. So the \code{start}
  13064. block of $B$ shown on the left is changed to the code on the right.
  13065. \begin{center}
  13066. \begin{minipage}{0.3\textwidth}
  13067. \begin{lstlisting}
  13068. start:
  13069. |$\itm{instr}_1$|
  13070. |$\cdots$|
  13071. |$\itm{instr}_n$|
  13072. \end{lstlisting}
  13073. \end{minipage}
  13074. $\Rightarrow$
  13075. \begin{minipage}{0.3\textwidth}
  13076. \begin{lstlisting}
  13077. start:
  13078. movq %rdi, |$x_1$|
  13079. |$\cdots$|
  13080. |$\itm{instr}_1$|
  13081. |$\cdots$|
  13082. |$\itm{instr}_n$|
  13083. \end{lstlisting}
  13084. \end{minipage}
  13085. \end{center}
  13086. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13087. parameters the function expects, but the parameters are no longer in
  13088. the syntax of function definitions. Instead, add an entry to
  13089. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13090. to construct $\itm{info}'$.}
  13091. By changing the parameters to local variables, we are giving the
  13092. register allocator control over which registers or stack locations to
  13093. use for them. If you implemented the move-biasing challenge
  13094. (Section~\ref{sec:move-biasing}), the register allocator will try to
  13095. assign the parameter variables to the corresponding argument register,
  13096. in which case the \code{patch\_instructions} pass will remove the
  13097. \code{movq} instruction. This happens in the example translation in
  13098. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  13099. the \code{add} function.
  13100. %
  13101. Also, note that the register allocator will perform liveness analysis
  13102. on this sequence of move instructions and build the interference
  13103. graph. So, for example, $x_1$ will be marked as interfering with
  13104. \code{rsi} and that will prevent the assignment of $x_1$ to
  13105. \code{rsi}, which is good, because that would overwrite the argument
  13106. that needs to move into $x_2$.
  13107. Next, consider the compilation of function calls. In the mirror image
  13108. of handling the parameters of function definitions, the arguments need
  13109. to be moved to the argument passing registers. The function call
  13110. itself is performed with an indirect function call. The return value
  13111. from the function is stored in \code{rax}, so it needs to be moved
  13112. into the \itm{lhs}.
  13113. \begin{lstlisting}
  13114. |\itm{lhs}| = |$\CALL{\itm{fun}}{\itm{arg}_1\ldots}$|
  13115. |$\Rightarrow$|
  13116. movq |$\itm{arg}_1$|, %rdi
  13117. movq |$\itm{arg}_2$|, %rsi
  13118. |$\vdots$|
  13119. callq *|\itm{fun}|
  13120. movq %rax, |\itm{lhs}|
  13121. \end{lstlisting}
  13122. The \code{IndirectCallq} AST node includes an integer for the arity of
  13123. the function, i.e., the number of parameters. That information is
  13124. useful in the \code{uncover\_live} pass for determining which
  13125. argument-passing registers are potentially read during the call.
  13126. For tail calls, the parameter passing is the same as non-tail calls:
  13127. generate instructions to move the arguments into the argument
  13128. passing registers. After that we need to pop the frame from the
  13129. procedure call stack. However, we do not yet know how big the frame
  13130. is; that gets determined during register allocation. So instead of
  13131. generating those instructions here, we invent a new instruction that
  13132. means ``pop the frame and then do an indirect jump'', which we name
  13133. \code{TailJmp}. The abstract syntax for this instruction includes an
  13134. argument that specifies where to jump and an integer that represents
  13135. the arity of the function being called.
  13136. Recall that we use the label \code{start} for the initial block of a
  13137. program, and in Section~\ref{sec:select-Lvar} we recommend labeling
  13138. the conclusion of the program with \code{conclusion}, so that
  13139. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13140. by a jump to \code{conclusion}. With the addition of function
  13141. definitions, there is a start block and conclusion for each function,
  13142. but their labels need to be unique. We recommend prepending the
  13143. function's name to \code{start} and \code{conclusion}, respectively,
  13144. to obtain unique labels.
  13145. \section{Register Allocation}
  13146. \label{sec:register-allocation-r4}
  13147. \subsection{Liveness Analysis}
  13148. \label{sec:liveness-analysis-r4}
  13149. \index{subject}{liveness analysis}
  13150. %% The rest of the passes need only minor modifications to handle the new
  13151. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13152. %% \code{leaq}.
  13153. The \code{IndirectCallq} instruction should be treated like
  13154. \code{Callq} regarding its written locations $W$, in that they should
  13155. include all the caller-saved registers. Recall that the reason for
  13156. that is to force variables that are live across a function call to be assigned to callee-saved
  13157. registers or to be spilled to the stack.
  13158. Regarding the set of read locations $R$, the arity field of
  13159. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13160. argument-passing registers should be considered as read by those
  13161. instructions. Also, the target field of \code{TailJmp} and
  13162. \code{IndirectCallq} should be included in the set of read locations
  13163. $R$.
  13164. \subsection{Build Interference Graph}
  13165. \label{sec:build-interference-r4}
  13166. With the addition of function definitions, we compute a separate interference
  13167. graph for each function (not just one for the whole program).
  13168. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13169. spill vector-typed variables that are live during a call to
  13170. \code{collect}, the garbage collector. With the addition of functions to our language, we
  13171. need to revisit this issue. Functions that perform allocation contain
  13172. calls to the collector. Thus, we should
  13173. not only spill a vector-typed variable when it is live during a call
  13174. to \code{collect}, but we should spill the variable if it is live
  13175. during call to a user-defined function. Thus, in the \code{build\_interference} pass,
  13176. we recommend adding interference edges between call-live vector-typed
  13177. variables and the callee-saved registers (in addition to the usual
  13178. addition of edges between call-live variables and the caller-saved
  13179. registers).
  13180. \subsection{Allocate Registers}
  13181. The primary change to the \code{allocate\_registers} pass is adding an
  13182. auxiliary function for handling definitions (the \Def{} non-terminal
  13183. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13184. logic is the same as described in
  13185. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13186. allocation is performed many times, once for each function definition,
  13187. instead of just once for the whole program.
  13188. \section{Patch Instructions}
  13189. In \code{patch\_instructions}, you should deal with the x86
  13190. idiosyncrasy that the destination argument of \code{leaq} must be a
  13191. register. Additionally, you should ensure that the argument of
  13192. \code{TailJmp} is \itm{rax}, our reserved register---mostly to make
  13193. code generation more convenient, because we trample many registers
  13194. before the tail call (as explained in the next section).
  13195. \section{Prelude and Conclusion}
  13196. %% For the \code{print\_x86} pass, the cases for \code{FunRef} and
  13197. %% \code{IndirectCallq} are straightforward: output their concrete
  13198. %% syntax.
  13199. %% \begin{lstlisting}
  13200. %% (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  13201. %% (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  13202. %% \end{lstlisting}
  13203. Now that register allocation is complete, we can translate the
  13204. \code{TailJmp} into a sequence of instructions. A straightforward
  13205. translation of \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}.
  13206. However, before the jump we need to pop the current frame. This
  13207. sequence of instructions is the same as the code for the conclusion of
  13208. a function, except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  13209. Regarding function definitions, you need to generate a prelude
  13210. and conclusion for each one. This code is similar to the prelude and
  13211. conclusion generated for the \code{main} function in
  13212. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  13213. should carry out the following steps.
  13214. % TODO: .align the functions!
  13215. \begin{enumerate}
  13216. %% \item Start with \code{.global} and \code{.align} directives followed
  13217. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13218. %% example.)
  13219. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13220. pointer.
  13221. \item Push to the stack all of the callee-saved registers that were
  13222. used for register allocation.
  13223. \item Move the stack pointer \code{rsp} down by the size of the stack
  13224. frame for this function, which depends on the number of regular
  13225. spills. (Aligned to 16 bytes.)
  13226. \item Move the root stack pointer \code{r15} up by the size of the
  13227. root-stack frame for this function, which depends on the number of
  13228. spilled vectors. \label{root-stack-init}
  13229. \item Initialize to zero all new entries in the root-stack frame.
  13230. \item Jump to the start block.
  13231. \end{enumerate}
  13232. The prelude of the \code{main} function has one additional task: call
  13233. the \code{initialize} function to set up the garbage collector and
  13234. move the value of the global \code{rootstack\_begin} in
  13235. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13236. above, which depends on \code{r15}.
  13237. The conclusion of every function should do the following.
  13238. \begin{enumerate}
  13239. \item Move the stack pointer back up by the size of the stack frame
  13240. for this function.
  13241. \item Restore the callee-saved registers by popping them from the
  13242. stack.
  13243. \item Move the root stack pointer back down by the size of the
  13244. root-stack frame for this function.
  13245. \item Restore \code{rbp} by popping it from the stack.
  13246. \item Return to the caller with the \code{retq} instruction.
  13247. \end{enumerate}
  13248. \begin{exercise}\normalfont
  13249. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13250. Create 5 new programs that use functions, including examples that pass
  13251. functions and return functions from other functions, recursive
  13252. functions, functions that create vectors, and functions that make tail
  13253. calls. Test your compiler on these new programs and all of your
  13254. previously created test programs.
  13255. \end{exercise}
  13256. \begin{figure}[tbp]
  13257. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13258. \node (Rfun) at (0,2) {\large \LangFun{}};
  13259. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  13260. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  13261. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13262. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13263. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13264. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  13265. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13266. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13267. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13268. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13269. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13270. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13271. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13272. \path[->,bend left=15] (Rfun) edge [above] node
  13273. {\ttfamily\footnotesize shrink} (Rfun-1);
  13274. \path[->,bend left=15] (Rfun-1) edge [above] node
  13275. {\ttfamily\footnotesize uniquify} (Rfun-2);
  13276. \path[->,bend left=15] (Rfun-2) edge [above] node
  13277. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13278. \path[->,bend left=15] (F1-1) edge [right] node
  13279. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13280. \path[->,bend right=15] (F1-2) edge [above] node
  13281. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13282. \path[->,bend right=15] (F1-3) edge [above] node
  13283. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  13284. \path[->,bend left=15] (F1-4) edge [right] node
  13285. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13286. \path[->,bend right=15] (C3-2) edge [left] node
  13287. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13288. \path[->,bend left=15] (x86-2) edge [left] node
  13289. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13290. \path[->,bend right=15] (x86-2-1) edge [below] node
  13291. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13292. \path[->,bend right=15] (x86-2-2) edge [left] node
  13293. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13294. \path[->,bend left=15] (x86-3) edge [above] node
  13295. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13296. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  13297. \end{tikzpicture}
  13298. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13299. \label{fig:Rfun-passes}
  13300. \end{figure}
  13301. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  13302. compiling \LangFun{} to x86.
  13303. \section{An Example Translation}
  13304. \label{sec:functions-example}
  13305. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13306. function in \LangFun{} to x86. The figure also includes the results of the
  13307. \code{explicate\_control} and \code{select\_instructions} passes.
  13308. \begin{figure}[htbp]
  13309. \begin{tabular}{ll}
  13310. \begin{minipage}{0.4\textwidth}
  13311. % s3_2.rkt
  13312. {\if\edition\racketEd
  13313. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13314. (define (add [x : Integer] [y : Integer])
  13315. : Integer
  13316. (+ x y))
  13317. (add 40 2)
  13318. \end{lstlisting}
  13319. \fi}
  13320. {\if\edition\pythonEd
  13321. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13322. def add(x:int, y:int) -> int:
  13323. return x + y
  13324. print(add(40, 2))
  13325. \end{lstlisting}
  13326. \fi}
  13327. $\Downarrow$
  13328. {\if\edition\racketEd
  13329. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13330. (define (add86 [x87 : Integer]
  13331. [y88 : Integer]) : Integer
  13332. add86start:
  13333. return (+ x87 y88);
  13334. )
  13335. (define (main) : Integer ()
  13336. mainstart:
  13337. tmp89 = (fun-ref add86);
  13338. (tail-call tmp89 40 2)
  13339. )
  13340. \end{lstlisting}
  13341. \fi}
  13342. {\if\edition\pythonEd
  13343. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13344. def add(x:int, y:int) -> int:
  13345. addstart:
  13346. return x + y
  13347. def main() -> int:
  13348. mainstart:
  13349. fun.0 = add
  13350. tmp.1 = fun.0(40, 2)
  13351. print(tmp.1)
  13352. return 0
  13353. \end{lstlisting}
  13354. \fi}
  13355. \end{minipage}
  13356. &
  13357. $\Rightarrow$
  13358. \begin{minipage}{0.5\textwidth}
  13359. {\if\edition\racketEd
  13360. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13361. (define (add86) : Integer
  13362. add86start:
  13363. movq %rdi, x87
  13364. movq %rsi, y88
  13365. movq x87, %rax
  13366. addq y88, %rax
  13367. jmp inc1389conclusion
  13368. )
  13369. (define (main) : Integer
  13370. mainstart:
  13371. leaq (fun-ref add86), tmp89
  13372. movq $40, %rdi
  13373. movq $2, %rsi
  13374. tail-jmp tmp89
  13375. )
  13376. \end{lstlisting}
  13377. \fi}
  13378. {\if\edition\pythonEd
  13379. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13380. def add() -> int:
  13381. addstart:
  13382. movq %rdi, x
  13383. movq %rsi, y
  13384. movq x, %rax
  13385. addq y, %rax
  13386. jmp addconclusion
  13387. def main() -> int:
  13388. mainstart:
  13389. leaq add, fun.0
  13390. movq $40, %rdi
  13391. movq $2, %rsi
  13392. callq *fun.0
  13393. movq %rax, tmp.1
  13394. movq tmp.1, %rdi
  13395. callq print_int
  13396. movq $0, %rax
  13397. jmp mainconclusion
  13398. \end{lstlisting}
  13399. \fi}
  13400. $\Downarrow$
  13401. \end{minipage}
  13402. \end{tabular}
  13403. \begin{tabular}{ll}
  13404. \begin{minipage}{0.3\textwidth}
  13405. {\if\edition\racketEd
  13406. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13407. .globl add86
  13408. .align 16
  13409. add86:
  13410. pushq %rbp
  13411. movq %rsp, %rbp
  13412. jmp add86start
  13413. add86start:
  13414. movq %rdi, %rax
  13415. addq %rsi, %rax
  13416. jmp add86conclusion
  13417. add86conclusion:
  13418. popq %rbp
  13419. retq
  13420. \end{lstlisting}
  13421. \fi}
  13422. {\if\edition\pythonEd
  13423. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13424. .align 16
  13425. add:
  13426. pushq %rbp
  13427. movq %rsp, %rbp
  13428. subq $0, %rsp
  13429. jmp addstart
  13430. addstart:
  13431. movq %rdi, %rdx
  13432. movq %rsi, %rcx
  13433. movq %rdx, %rax
  13434. addq %rcx, %rax
  13435. jmp addconclusion
  13436. addconclusion:
  13437. subq $0, %r15
  13438. addq $0, %rsp
  13439. popq %rbp
  13440. retq
  13441. \end{lstlisting}
  13442. \fi}
  13443. \end{minipage}
  13444. &
  13445. \begin{minipage}{0.5\textwidth}
  13446. {\if\edition\racketEd
  13447. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13448. .globl main
  13449. .align 16
  13450. main:
  13451. pushq %rbp
  13452. movq %rsp, %rbp
  13453. movq $16384, %rdi
  13454. movq $16384, %rsi
  13455. callq initialize
  13456. movq rootstack_begin(%rip), %r15
  13457. jmp mainstart
  13458. mainstart:
  13459. leaq add86(%rip), %rcx
  13460. movq $40, %rdi
  13461. movq $2, %rsi
  13462. movq %rcx, %rax
  13463. popq %rbp
  13464. jmp *%rax
  13465. mainconclusion:
  13466. popq %rbp
  13467. retq
  13468. \end{lstlisting}
  13469. \fi}
  13470. {\if\edition\pythonEd
  13471. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13472. .globl main
  13473. .align 16
  13474. main:
  13475. pushq %rbp
  13476. movq %rsp, %rbp
  13477. subq $0, %rsp
  13478. movq $65536, %rdi
  13479. movq $65536, %rsi
  13480. callq initialize
  13481. movq rootstack_begin(%rip), %r15
  13482. jmp mainstart
  13483. mainstart:
  13484. leaq add(%rip), %rcx
  13485. movq $40, %rdi
  13486. movq $2, %rsi
  13487. callq *%rcx
  13488. movq %rax, %rcx
  13489. movq %rcx, %rdi
  13490. callq print_int
  13491. movq $0, %rax
  13492. jmp mainconclusion
  13493. mainconclusion:
  13494. subq $0, %r15
  13495. addq $0, %rsp
  13496. popq %rbp
  13497. retq
  13498. \end{lstlisting}
  13499. \fi}
  13500. \end{minipage}
  13501. \end{tabular}
  13502. \caption{Example compilation of a simple function to x86.}
  13503. \label{fig:add-fun}
  13504. \end{figure}
  13505. % Challenge idea: inlining! (simple version)
  13506. % Further Reading
  13507. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13508. \chapter{Lexically Scoped Functions}
  13509. \label{ch:Llambda}
  13510. \index{subject}{lambda}
  13511. \index{subject}{lexical scoping}
  13512. This chapter studies lexically scoped functions. Lexical scoping means
  13513. that a function's body may refer to variables whose binding site is
  13514. outside of the function, in an enclosing scope.
  13515. %
  13516. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13517. \LangLam{}, which extends \LangFun{} with lexically scoped functions
  13518. using the \key{lambda} form. The body of the \key{lambda} refers to
  13519. three variables: \code{x}, \code{y}, and \code{z}. The binding sites
  13520. for \code{x} and \code{y} are outside of the \key{lambda}. Variable
  13521. \code{y} is \racket{bound by the enclosing \key{let}}\python{a local
  13522. variable of function \code{f}} and \code{x} is a parameter of
  13523. function \code{f}. The \key{lambda} is returned from the function
  13524. \code{f}. The main expression of the program includes two calls to
  13525. \code{f} with different arguments for \code{x}, first \code{5} then
  13526. \code{3}. The functions returned from \code{f} are bound to variables
  13527. \code{g} and \code{h}. Even though these two functions were created by
  13528. the same \code{lambda}, they are really different functions because
  13529. they use different values for \code{x}. Applying \code{g} to \code{11}
  13530. produces \code{20} whereas applying \code{h} to \code{15} produces
  13531. \code{22}. The result of this program is \code{42}.
  13532. \begin{figure}[btp]
  13533. {\if\edition\racketEd
  13534. % lambda_test_21.rkt
  13535. \begin{lstlisting}
  13536. (define (f [x : Integer]) : (Integer -> Integer)
  13537. (let ([y 4])
  13538. (lambda: ([z : Integer]) : Integer
  13539. (+ x (+ y z)))))
  13540. (let ([g (f 5)])
  13541. (let ([h (f 3)])
  13542. (+ (g 11) (h 15))))
  13543. \end{lstlisting}
  13544. \fi}
  13545. {\if\edition\pythonEd
  13546. \begin{lstlisting}
  13547. def f(x : int) -> Callable[[int], int]:
  13548. y = 4
  13549. return lambda z: x + y + z
  13550. g = f(5)
  13551. h = f(3)
  13552. print( g(11) + h(15) )
  13553. \end{lstlisting}
  13554. \fi}
  13555. \caption{Example of a lexically scoped function.}
  13556. \label{fig:lexical-scoping}
  13557. \end{figure}
  13558. The approach that we take for implementing lexically scoped functions
  13559. is to compile them into top-level function definitions, translating
  13560. from \LangLam{} into \LangFun{}. However, the compiler must give
  13561. special treatment to variable occurrences such as \code{x} and
  13562. \code{y} in the body of the \code{lambda} of
  13563. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13564. may not refer to variables defined outside of it. To identify such
  13565. variable occurrences, we review the standard notion of free variable.
  13566. \begin{definition}
  13567. A variable is \textbf{free in expression} $e$ if the variable occurs
  13568. inside $e$ but does not have an enclosing definition that is also in
  13569. $e$.\index{subject}{free variable}
  13570. \end{definition}
  13571. For example, in the expression
  13572. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  13573. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13574. only \code{x} and \code{y} are free in the following expression
  13575. because \code{z} is defined by the \code{lambda}.
  13576. {\if\edition\racketEd
  13577. \begin{lstlisting}
  13578. (lambda: ([z : Integer]) : Integer
  13579. (+ x (+ y z)))
  13580. \end{lstlisting}
  13581. \fi}
  13582. {\if\edition\pythonEd
  13583. \begin{lstlisting}
  13584. lambda z: x + y + z
  13585. \end{lstlisting}
  13586. \fi}
  13587. %
  13588. So the free variables of a \code{lambda} are the ones that need
  13589. special treatment. We need to transport, at runtime, the values of
  13590. those variables from the point where the \code{lambda} was created to
  13591. the point where the \code{lambda} is applied. An efficient solution to
  13592. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  13593. of the free variables together with a function pointer into a tuple,
  13594. an arrangement called a \emph{flat closure} (which we shorten to just
  13595. ``closure''). \index{subject}{closure}\index{subject}{flat closure}
  13596. Fortunately, we have all the ingredients to make closures:
  13597. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  13598. function pointers. The function pointer resides at index $0$ and the
  13599. values for the free variables fill in the rest of the tuple.
  13600. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13601. how closures work. It's a three-step dance. The program calls function
  13602. \code{f}, which creates a closure for the \code{lambda}. The closure
  13603. is a tuple whose first element is a pointer to the top-level function
  13604. that we will generate for the \code{lambda}, the second element is the
  13605. value of \code{x}, which is \code{5}, and the third element is
  13606. \code{4}, the value of \code{y}. The closure does not contain an
  13607. element for \code{z} because \code{z} is not a free variable of the
  13608. \code{lambda}. Creating the closure is step 1 of the dance. The
  13609. closure is returned from \code{f} and bound to \code{g}, as shown in
  13610. Figure~\ref{fig:closures}.
  13611. %
  13612. The second call to \code{f} creates another closure, this time with
  13613. \code{3} in the second slot (for \code{x}). This closure is also
  13614. returned from \code{f} but bound to \code{h}, which is also shown in
  13615. Figure~\ref{fig:closures}.
  13616. \begin{figure}[tbp]
  13617. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  13618. \caption{Flat closure representations for the two functions
  13619. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  13620. \label{fig:closures}
  13621. \end{figure}
  13622. Continuing with the example, consider the application of \code{g} to
  13623. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13624. obtain the function pointer in the first element of the closure and
  13625. call it, passing in the closure itself and then the regular arguments,
  13626. in this case \code{11}. This technique for applying a closure is step
  13627. 2 of the dance.
  13628. %
  13629. But doesn't this \code{lambda} only take 1 argument, for parameter
  13630. \code{z}? The third and final step of the dance is generating a
  13631. top-level function for a \code{lambda}. We add an additional
  13632. parameter for the closure and we insert an initialization at the beginning
  13633. of the function for each free variable, to bind those variables to the
  13634. appropriate elements from the closure parameter.
  13635. %
  13636. This three-step dance is known as \emph{closure conversion}. We
  13637. discuss the details of closure conversion in
  13638. Section~\ref{sec:closure-conversion} and the code generated from the
  13639. example in Section~\ref{sec:example-lambda}. But first we define the
  13640. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13641. \section{The \LangLam{} Language}
  13642. \label{sec:r5}
  13643. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13644. functions and lexical scoping, is defined in
  13645. Figures~\ref{fig:Rlam-concrete-syntax} and \ref{fig:Rlam-syntax}. It adds
  13646. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13647. syntax for function application.
  13648. \python{The syntax also includes an assignment statement that includes
  13649. a type annotation for the variable on the left-hand side.}
  13650. \newcommand{\LlambdaGrammarRacket}{
  13651. \begin{array}{lcl}
  13652. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  13653. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  13654. \end{array}
  13655. }
  13656. \newcommand{\LlambdaASTRacket}{
  13657. \begin{array}{lcl}
  13658. \itm{op} &::=& \code{procedure-arity} \\
  13659. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  13660. \end{array}
  13661. }
  13662. \newcommand{\LlambdaGrammarPython}{
  13663. \begin{array}{lcl}
  13664. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  13665. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  13666. \end{array}
  13667. }
  13668. \newcommand{\LlambdaASTPython}{
  13669. \begin{array}{lcl}
  13670. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \\
  13671. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  13672. \end{array}
  13673. }
  13674. % include AnnAssign in ASTPython
  13675. \begin{figure}[tp]
  13676. \centering
  13677. \fbox{
  13678. \begin{minipage}{0.96\textwidth}
  13679. \small
  13680. {\if\edition\racketEd
  13681. \[
  13682. \begin{array}{l}
  13683. \gray{\LintGrammarRacket{}} \\ \hline
  13684. \gray{\LvarGrammarRacket{}} \\ \hline
  13685. \gray{\LifGrammarRacket{}} \\ \hline
  13686. \gray{\LwhileGrammarRacket} \\ \hline
  13687. \gray{\LtupGrammarRacket} \\ \hline
  13688. \gray{\LfunGrammarRacket} \\ \hline
  13689. \LlambdaGrammarRacket \\
  13690. \begin{array}{lcl}
  13691. \LangLamM{} &::=& \Def\ldots \; \Exp
  13692. \end{array}
  13693. \end{array}
  13694. \]
  13695. \fi}
  13696. {\if\edition\pythonEd
  13697. \[
  13698. \begin{array}{l}
  13699. \gray{\LintGrammarPython{}} \\ \hline
  13700. \gray{\LvarGrammarPython{}} \\ \hline
  13701. \gray{\LifGrammarPython{}} \\ \hline
  13702. \gray{\LwhileGrammarPython} \\ \hline
  13703. \gray{\LtupGrammarPython} \\ \hline
  13704. \gray{\LfunGrammarPython} \\ \hline
  13705. \LlambdaGrammarPython \\
  13706. \begin{array}{lcl}
  13707. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13708. \end{array}
  13709. \end{array}
  13710. \]
  13711. \fi}
  13712. \end{minipage}
  13713. }
  13714. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  13715. with \key{lambda}.}
  13716. \label{fig:Rlam-concrete-syntax}
  13717. \end{figure}
  13718. \begin{figure}[tp]
  13719. \centering
  13720. \fbox{
  13721. \begin{minipage}{0.96\textwidth}
  13722. \small
  13723. {\if\edition\racketEd
  13724. \[
  13725. \begin{array}{l}
  13726. \gray{\LintOpAST} \\ \hline
  13727. \gray{\LvarASTRacket{}} \\ \hline
  13728. \gray{\LifASTRacket{}} \\ \hline
  13729. \gray{\LwhileASTRacket{}} \\ \hline
  13730. \gray{\LtupASTRacket{}} \\ \hline
  13731. \gray{\LfunASTRacket} \\ \hline
  13732. \LlambdaASTRacket \\
  13733. \begin{array}{lcl}
  13734. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13735. \end{array}
  13736. \end{array}
  13737. \]
  13738. \fi}
  13739. {\if\edition\pythonEd
  13740. \[
  13741. \begin{array}{l}
  13742. \gray{\LintASTPython} \\ \hline
  13743. \gray{\LvarASTPython{}} \\ \hline
  13744. \gray{\LifASTPython{}} \\ \hline
  13745. \gray{\LwhileASTPython{}} \\ \hline
  13746. \gray{\LtupASTPython{}} \\ \hline
  13747. \gray{\LfunASTPython} \\ \hline
  13748. \LlambdaASTPython \\
  13749. \begin{array}{lcl}
  13750. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13751. \end{array}
  13752. \end{array}
  13753. \]
  13754. \fi}
  13755. \end{minipage}
  13756. }
  13757. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  13758. \label{fig:Rlam-syntax}
  13759. \end{figure}
  13760. \index{subject}{interpreter}
  13761. \label{sec:interp-Rlambda}
  13762. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  13763. \LangLam{}. The case for \key{Lambda} saves the current environment
  13764. inside the returned function value. Recall that during function
  13765. application, the environment stored in the function value, extended
  13766. with the mapping of parameters to argument values, is used to
  13767. interpret the body of the function.
  13768. \begin{figure}[tbp]
  13769. {\if\edition\racketEd
  13770. \begin{lstlisting}
  13771. (define interp-Rlambda_class
  13772. (class interp-Rfun_class
  13773. (super-new)
  13774. (define/override (interp-op op)
  13775. (match op
  13776. ['procedure-arity
  13777. (lambda (v)
  13778. (match v
  13779. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13780. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13781. [else (super interp-op op)]))
  13782. (define/override ((interp-exp env) e)
  13783. (define recur (interp-exp env))
  13784. (match e
  13785. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13786. `(function ,xs ,body ,env)]
  13787. [else ((super interp-exp env) e)]))
  13788. ))
  13789. (define (interp-Rlambda p)
  13790. (send (new interp-Rlambda_class) interp-program p))
  13791. \end{lstlisting}
  13792. \fi}
  13793. {\if\edition\pythonEd
  13794. \begin{lstlisting}
  13795. class InterpLlambda(InterpLfun):
  13796. def interp_exp(self, e, env):
  13797. match e:
  13798. case Lambda(params, body):
  13799. return Function('lambda', params, [Return(body)], env)
  13800. case _:
  13801. return super().interp_exp(e, env)
  13802. def interp_stmts(self, ss, env):
  13803. if len(ss) == 0:
  13804. return
  13805. match ss[0]:
  13806. case AnnAssign(lhs, typ, value, simple):
  13807. env[lhs.id] = self.interp_exp(value, env)
  13808. return self.interp_stmts(ss[1:], env)
  13809. case _:
  13810. return super().interp_stmts(ss, env)
  13811. \end{lstlisting}
  13812. \fi}
  13813. \caption{Interpreter for \LangLam{}.}
  13814. \label{fig:interp-Rlambda}
  13815. \end{figure}
  13816. \label{sec:type-check-r5}
  13817. \index{subject}{type checking}
  13818. {\if\edition\racketEd
  13819. %
  13820. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  13821. \key{lambda} form. The body of the \key{lambda} is checked in an
  13822. environment that includes the current environment (because it is
  13823. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13824. require the body's type to match the declared return type.
  13825. %
  13826. \fi}
  13827. {\if\edition\pythonEd
  13828. %
  13829. Figures~\ref{fig:type-check-Llambda} and
  13830. \ref{fig:type-check-Llambda-part2} define the type checker for
  13831. \LangLam{}, which is more complex than one might expect. The reason
  13832. for the added complexity is that the syntax of \key{lambda} does not
  13833. include type annotations for the parameters or return type. Instead
  13834. they must be inferred. There are many approaches of type inference to
  13835. choose from of varying degrees of complexity. We choose one of the
  13836. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  13837. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  13838. this book is compilation, not type inference.
  13839. The main idea of bidirectional type inference is to add an auxilliary
  13840. function, here named \code{check\_exp}, that takes an expected type
  13841. and checks whether the given expression is of that type. Thus, in
  13842. \code{check\_exp}, type information flows in a top-down manner with
  13843. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  13844. function, where type information flows in a primarily bottom-up
  13845. manner.
  13846. %
  13847. The idea then is to use \code{check\_exp} in all the places where we
  13848. already know what the type of an expression should be, such as in the
  13849. \code{return} statement of a top-level function definition, or on the
  13850. right-hand side of an annotated assignment statement.
  13851. Getting back to \code{lambda}, it is straightforward to check a
  13852. \code{lambda} inside \code{check\_exp} because the expected type
  13853. provides the parameter types and the return type. On the other hand,
  13854. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  13855. that we do not allow \code{lambda} in contexts where we don't already
  13856. know its type. This restriction does not incur a loss of
  13857. expressiveness for \LangLam{} because it is straightforward to modify
  13858. a program to sidestep the restriction, for example, by using an
  13859. annotated assignment statement to assign the \code{lambda} to a
  13860. temporary variable.
  13861. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  13862. checker records their type in a \code{has\_type} field. This type
  13863. information is used later in this chapter.
  13864. %
  13865. \fi}
  13866. \begin{figure}[tbp]
  13867. {\if\edition\racketEd
  13868. \begin{lstlisting}
  13869. (define (type-check-Rlambda env)
  13870. (lambda (e)
  13871. (match e
  13872. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  13873. (define-values (new-body bodyT)
  13874. ((type-check-exp (append (map cons xs Ts) env)) body))
  13875. (define ty `(,@Ts -> ,rT))
  13876. (cond
  13877. [(equal? rT bodyT)
  13878. (values (HasType (Lambda params rT new-body) ty) ty)]
  13879. [else
  13880. (error "mismatch in return type" bodyT rT)])]
  13881. ...
  13882. )))
  13883. \end{lstlisting}
  13884. \fi}
  13885. {\if\edition\pythonEd
  13886. \begin{lstlisting}
  13887. class TypeCheckLlambda(TypeCheckLfun):
  13888. def type_check_exp(self, e, env):
  13889. match e:
  13890. case Name(id):
  13891. e.has_type = env[id]
  13892. return env[id]
  13893. case Lambda(params, body):
  13894. raise Exception('cannot synthesize a type for a lambda')
  13895. case _:
  13896. return super().type_check_exp(e, env)
  13897. def check_exp(self, e, ty, env):
  13898. match e:
  13899. case Lambda(params, body):
  13900. e.has_type = ty
  13901. match ty:
  13902. case FunctionType(params_t, return_t):
  13903. new_env = {x:t for (x,t) in env.items()}
  13904. for (p,t) in zip(params, params_t):
  13905. new_env[p] = t
  13906. self.check_exp(body, return_t, new_env)
  13907. case _:
  13908. raise Exception('lambda does not have type ' + str(ty))
  13909. case Call(func, args):
  13910. func_t = self.type_check_exp(func, env)
  13911. match func_t:
  13912. case FunctionType(params_t, return_t):
  13913. for (arg, param_t) in zip(args, params_t):
  13914. self.check_exp(arg, param_t, env)
  13915. self.check_type_equal(return_t, ty, e)
  13916. case _:
  13917. raise Exception('type_check_exp: in call, unexpected ' + \
  13918. repr(func_t))
  13919. case _:
  13920. t = self.type_check_exp(e, env)
  13921. self.check_type_equal(t, ty, e)
  13922. \end{lstlisting}
  13923. \fi}
  13924. \caption{Type checking \LangLam{}\python{, part 1}.}
  13925. \label{fig:type-check-Llambda}
  13926. \end{figure}
  13927. {\if\edition\pythonEd
  13928. \begin{figure}[tbp]
  13929. \begin{lstlisting}
  13930. def check_stmts(self, ss, return_ty, env):
  13931. if len(ss) == 0:
  13932. return
  13933. match ss[0]:
  13934. case FunctionDef(name, params, body, dl, returns, comment):
  13935. new_env = {x: t for (x,t) in env.items()}
  13936. for (x,t) in params:
  13937. new_env[x] = t
  13938. rt = self.check_stmts(body, returns, new_env)
  13939. self.check_stmts(ss[1:], return_ty, env)
  13940. case Return(value):
  13941. self.check_exp(value, return_ty, env)
  13942. case Assign([Name(id)], value):
  13943. if id in env:
  13944. self.check_exp(value, env[id], env)
  13945. else:
  13946. env[id] = self.type_check_exp(value, env)
  13947. self.check_stmts(ss[1:], return_ty, env)
  13948. case Assign([Subscript(tup, Constant(index), Store())], value):
  13949. tup_t = self.type_check_exp(tup, env)
  13950. match tup_t:
  13951. case TupleType(ts):
  13952. self.check_exp(value, ts[index], env)
  13953. case _:
  13954. raise Exception('expected a tuple, not ' + repr(tup_t))
  13955. self.check_stmts(ss[1:], return_ty, env)
  13956. case AnnAssign(Name(id), ty, value, simple):
  13957. ss[0].annotation = ty_annot
  13958. if id in env:
  13959. self.check_type_equal(env[id], ty)
  13960. else:
  13961. env[id] = ty_annot
  13962. self.check_exp(value, ty_annot, env)
  13963. case _:
  13964. self.type_check_stmts(ss, env)
  13965. def type_check(self, p):
  13966. match p:
  13967. case Module(body):
  13968. env = {}
  13969. for s in body:
  13970. match s:
  13971. case FunctionDef(name, params, bod, dl, returns, comment):
  13972. params_t = [t for (x,t) in params]
  13973. env[name] = FunctionType(params_t, returns)
  13974. self.check_stmts(body, int, env)
  13975. \end{lstlisting}
  13976. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  13977. \label{fig:type-check-Llambda-part2}
  13978. \end{figure}
  13979. \fi}
  13980. \clearpage
  13981. \section{Assignment and Lexically Scoped Functions}
  13982. \label{sec:assignment-scoping}
  13983. The combination of lexically-scoped functions and assignment to
  13984. variables raises a challenge with our approach to implementing
  13985. lexically-scoped functions. Consider the following example in which
  13986. function \code{f} has a free variable \code{x} that is changed after
  13987. \code{f} is created but before the call to \code{f}.
  13988. % loop_test_11.rkt
  13989. {\if\edition\racketEd
  13990. \begin{lstlisting}
  13991. (let ([x 0])
  13992. (let ([y 0])
  13993. (let ([z 20])
  13994. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  13995. (begin
  13996. (set! x 10)
  13997. (set! y 12)
  13998. (f y))))))
  13999. \end{lstlisting}
  14000. \fi}
  14001. {\if\edition\pythonEd
  14002. % box_free_assign.py
  14003. \begin{lstlisting}
  14004. def g(z : int) -> int:
  14005. x = 0
  14006. y = 0
  14007. f : Callable[[int],int] = lambda a: a + x + z
  14008. x = 10
  14009. y = 12
  14010. return f(y)
  14011. print( g(20) )
  14012. \end{lstlisting}
  14013. \fi}
  14014. The correct output for this example is \code{42} because the call to
  14015. \code{f} is required to use the current value of \code{x} (which is
  14016. \code{10}). Unfortunately, the closure conversion pass
  14017. (Section~\ref{sec:closure-conversion}) generates code for the
  14018. \code{lambda} that copies the old value of \code{x} into a
  14019. closure. Thus, if we naively add support for assignment to our current
  14020. compiler, the output of this program would be \code{32}.
  14021. A first attempt at solving this problem would be to save a pointer to
  14022. \code{x} in the closure and change the occurrences of \code{x} inside
  14023. the lambda to dereference the pointer. Of course, this would require
  14024. assigning \code{x} to the stack and not to a register. However, the
  14025. problem goes a bit deeper.
  14026. %% Consider the following example in which we
  14027. %% create a counter abstraction by creating a pair of functions that
  14028. %% share the free variable \code{x}.
  14029. Consider the following example that returns a function that refers to
  14030. a local variable of the enclosing function.
  14031. \begin{center}
  14032. \begin{minipage}{\textwidth}
  14033. {\if\edition\racketEd
  14034. % similar to loop_test_10.rkt
  14035. %% \begin{lstlisting}
  14036. %% (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  14037. %% (vector
  14038. %% (lambda: () : Integer x)
  14039. %% (lambda: () : Void (set! x (+ 1 x)))))
  14040. %% (let ([counter (f 0)])
  14041. %% (let ([get (vector-ref counter 0)])
  14042. %% (let ([inc (vector-ref counter 1)])
  14043. %% (begin
  14044. %% (inc)
  14045. %% (get)))))
  14046. %% \end{lstlisting}
  14047. \begin{lstlisting}
  14048. (define (f []) : Integer
  14049. (let ([x 0])
  14050. (let ([g (lambda: () : Integer x)])
  14051. (begin
  14052. (set! x 42)
  14053. g))))
  14054. ((f))
  14055. \end{lstlisting}
  14056. \fi}
  14057. {\if\edition\pythonEd
  14058. % counter.py
  14059. \begin{lstlisting}
  14060. def f():
  14061. x = 0
  14062. g = lambda: x
  14063. x = 42
  14064. return g
  14065. print( f()() )
  14066. \end{lstlisting}
  14067. \fi}
  14068. \end{minipage}
  14069. \end{center}
  14070. In this example, the lifetime of \code{x} extends beyond the lifetime
  14071. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14072. stack frame for the call to \code{f}, it would be gone by the time we
  14073. call \code{g}, leaving us with dangling pointers for
  14074. \code{x}. This example demonstrates that when a variable occurs free
  14075. inside a function, its lifetime becomes indefinite. Thus, the value of
  14076. the variable needs to live on the heap. The verb
  14077. \emph{box}\index{subject}{box} is often used for allocating a single
  14078. value on the heap, producing a pointer, and
  14079. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14080. %% {\if\edition\racketEd
  14081. %% We recommend solving these problems by boxing the local variables that
  14082. %% are in the intersection of 1) variables that appear on the
  14083. %% left-hand-side of a \code{set!} and 2) variables that occur free
  14084. %% inside a \code{lambda}.
  14085. %% \fi}
  14086. %% {\if\edition\pythonEd
  14087. %% We recommend solving these problems by boxing the local variables that
  14088. %% are in the intersection of 1) variables whose values may change and 2)
  14089. %% variables that occur free inside a \code{lambda}.
  14090. %% \fi}
  14091. We shall introduce a new pass named
  14092. \code{convert\_assignments} in Section~\ref{sec:convert-assignments}
  14093. to address this challenge.
  14094. %
  14095. \racket{But before diving into the compiler passes, we have one more
  14096. problem to discuss.}
  14097. \if\edition\pythonEd
  14098. \section{Uniquify Variables}
  14099. \label{sec:uniquify-lambda}
  14100. With the addition of \code{lambda} we have a complication to deal
  14101. with: name shadowing. Consider the following program with a function
  14102. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14103. \code{lambda} expressions. The first \code{lambda} has a parameter
  14104. that is also named \code{x}.
  14105. \begin{lstlisting}
  14106. def f(x:int, y:int) -> Callable[[int], int]:
  14107. g : Callable[[int],int] = (lambda x: x + y)
  14108. h : Callable[[int],int] = (lambda y: x + y)
  14109. x = input_int()
  14110. return g
  14111. print(f(0, 10)(32))
  14112. \end{lstlisting}
  14113. Many of our compiler passes rely on being able to connect variable
  14114. uses with their definitions using just the name of the variable,
  14115. including new passes in this chapter. However, in the above example
  14116. the name of the variable does not uniquely determine its
  14117. definition. To solve this problem we recommend implementing a pass
  14118. named \code{uniquify} that renames every variable in the program to
  14119. make sure they are all unique.
  14120. The following shows the result of \code{uniquify} for the above
  14121. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14122. and the \code{x} parameter of the \code{lambda} is renamed to
  14123. \code{x\_4}.
  14124. \begin{lstlisting}
  14125. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14126. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14127. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14128. x_0 = input_int()
  14129. return g_2
  14130. def main() -> int :
  14131. print(f(0, 10)(32))
  14132. return 0
  14133. \end{lstlisting}
  14134. \fi
  14135. \if\edition\racketEd
  14136. \section{Reveal Functions and the $F_2$ language}
  14137. \label{sec:reveal-functions-r5}
  14138. To support the \code{procedure-arity} operator we need to communicate
  14139. the arity of a function to the point of closure creation. We can
  14140. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  14141. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  14142. output of this pass is the language $F_2$, whose syntax is defined in
  14143. Figure~\ref{fig:f2-syntax}.
  14144. \begin{figure}[tp]
  14145. \centering
  14146. \fbox{
  14147. \begin{minipage}{0.96\textwidth}
  14148. \[
  14149. \begin{array}{lcl}
  14150. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  14151. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14152. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  14153. \end{array}
  14154. \]
  14155. \end{minipage}
  14156. }
  14157. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  14158. (Figure~\ref{fig:Rlam-syntax}).}
  14159. \label{fig:f2-syntax}
  14160. \end{figure}
  14161. \fi
  14162. \section{Assignment Conversion}
  14163. \label{sec:convert-assignments}
  14164. The purpose of the \code{convert\_assignments} pass is address the
  14165. challenge posed in Section~\ref{sec:assignment-scoping} regarding the
  14166. interaction between variable assignments and closure conversion.
  14167. First we identify which variables need to be boxed, then we transform
  14168. the program to box those variables. In general, boxing introduces
  14169. runtime overhead that we would like to avoid, so we should box as few
  14170. variables as possible. We recommend boxing the variables in the
  14171. intersection of the following two sets of variables:
  14172. \begin{enumerate}
  14173. \item The variables that are free in a \code{lambda}.
  14174. \item The variables that appear on the left-hand side of an
  14175. assignment.
  14176. \end{enumerate}
  14177. Consider again the first example from
  14178. Section~\ref{sec:assignment-scoping}:
  14179. %
  14180. {\if\edition\racketEd
  14181. \begin{lstlisting}
  14182. (let ([x 0])
  14183. (let ([y 0])
  14184. (let ([z 20])
  14185. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14186. (begin
  14187. (set! x 10)
  14188. (set! y 12)
  14189. (f y))))))
  14190. \end{lstlisting}
  14191. \fi}
  14192. {\if\edition\pythonEd
  14193. \begin{lstlisting}
  14194. def g(z : int) -> int:
  14195. x = 0
  14196. y = 0
  14197. f : Callable[[int],int] = lambda a: a + x + z
  14198. x = 10
  14199. y = 12
  14200. return f(y)
  14201. print( g(20) )
  14202. \end{lstlisting}
  14203. \fi}
  14204. %
  14205. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14206. variables \code{x} and \code{z} occur free inside the
  14207. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14208. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14209. transformations: initialize \code{x} with a tuple, replace reads from
  14210. \code{x} with tuple reads, and replace each assignment to \code{x}
  14211. with a tuple writes. The output of \code{convert\_assignments} for
  14212. this example is as follows.
  14213. %
  14214. {\if\edition\racketEd
  14215. \begin{lstlisting}
  14216. (define (main) : Integer
  14217. (let ([x0 (vector 0)])
  14218. (let ([y1 0])
  14219. (let ([z2 20])
  14220. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14221. (+ a3 (+ (vector-ref x0 0) z2)))])
  14222. (begin
  14223. (vector-set! x0 0 10)
  14224. (set! y1 12)
  14225. (f4 y1)))))))
  14226. \end{lstlisting}
  14227. \fi}
  14228. %
  14229. {\if\edition\pythonEd
  14230. \begin{lstlisting}
  14231. def g(z : int)-> int:
  14232. x = (0,)
  14233. x[0] = 0
  14234. y = 0
  14235. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14236. x[0] = 10
  14237. y = 12
  14238. return f(y)
  14239. def main() -> int:
  14240. print(g(20))
  14241. return 0
  14242. \end{lstlisting}
  14243. \fi}
  14244. To compute the free variables of all the \code{lambda} expressions, we
  14245. recommend defining two auxiliary functions:
  14246. \begin{enumerate}
  14247. \item \code{free\_variables} computes the free variables of an expression, and
  14248. \item \code{free\_in\_lambda} collects all of the variables that are
  14249. free in any of the \code{lambda} expressions, using
  14250. \code{free\_variables} in the case for each \code{lambda}.
  14251. \end{enumerate}
  14252. {\if\edition\racketEd
  14253. %
  14254. To compute the variables that are assigned-to, we recommend using the
  14255. \code{collect-set!} function that we introduced in
  14256. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14257. forms such as \code{Lambda}.
  14258. %
  14259. \fi}
  14260. {\if\edition\pythonEd
  14261. %
  14262. To compute the variables that are assigned-to, we recommend defining
  14263. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14264. the set of variables that occur in the left-hand side of an assignment
  14265. statement, and otherwise returns the empty set.
  14266. %
  14267. \fi}
  14268. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14269. free in a \code{lambda} and that are assigned-to in the enclosing
  14270. function definition.
  14271. Next we discuss the \code{convert\_assignments} pass. In the case for
  14272. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14273. $\VAR{x}$ to a tuple read.
  14274. %
  14275. {\if\edition\racketEd
  14276. \begin{lstlisting}
  14277. (Var |$x$|)
  14278. |$\Rightarrow$|
  14279. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14280. \end{lstlisting}
  14281. \fi}
  14282. %
  14283. {\if\edition\pythonEd
  14284. \begin{lstlisting}
  14285. Name(|$x$|)
  14286. |$\Rightarrow$|
  14287. Subscript(Name(|$x$|), Constant(0), Load())
  14288. \end{lstlisting}
  14289. \fi}
  14290. %
  14291. %
  14292. In the case for assignment, recursively process the right-hand side
  14293. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in $\mathit{AF}$, translate
  14294. the assignment into a tuple-write as follows.
  14295. %
  14296. {\if\edition\racketEd
  14297. \begin{lstlisting}
  14298. (SetBang |$x$| |$\itm{rhs}$|)
  14299. |$\Rightarrow$|
  14300. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14301. \end{lstlisting}
  14302. \fi}
  14303. {\if\edition\pythonEd
  14304. \begin{lstlisting}
  14305. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14306. |$\Rightarrow$|
  14307. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14308. \end{lstlisting}
  14309. \fi}
  14310. %
  14311. {\if\edition\racketEd
  14312. The case for \code{Lambda} is non-trivial, but it is similar to the
  14313. case for function definitions, which we discuss next.
  14314. \fi}
  14315. To translate a function definition, we first compute $\mathit{AF}$,
  14316. the intersection of the variables that are free in a \code{lambda} and
  14317. that are assigned-to. We then apply assignment conversion to the body
  14318. of the function definition. Finally, we box the parameters of this
  14319. function definition that are in $\mathit{AF}$. For example,
  14320. the parameter \code{x} of the follow function \code{g}
  14321. needs to be boxed.
  14322. {\if\edition\racketEd
  14323. \begin{lstlisting}
  14324. (define (g [x : Integer]) : Integer
  14325. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14326. (begin
  14327. (set! x 10)
  14328. (f 32))))
  14329. \end{lstlisting}
  14330. \fi}
  14331. %
  14332. {\if\edition\pythonEd
  14333. \begin{lstlisting}
  14334. def g(x : int) -> int:
  14335. f : Callable[[int],int] = lambda a: a + x
  14336. x = 10
  14337. return f(32)
  14338. \end{lstlisting}
  14339. \fi}
  14340. %
  14341. \noindent We box parameter \code{x} by creating a local variable named
  14342. \code{x} that is initialized to a tuple whose contents is the value of
  14343. the parameter, which we has been renamed.
  14344. %
  14345. {\if\edition\racketEd
  14346. \begin{lstlisting}
  14347. (define (g [x_0 : Integer]) : Integer
  14348. (let ([x (vector x_0)])
  14349. (let ([f (lambda: ([a : Integer]) : Integer
  14350. (+ a (vector-ref x 0)))])
  14351. (begin
  14352. (vector-set! x 0 10)
  14353. (f 32)))))
  14354. \end{lstlisting}
  14355. \fi}
  14356. %
  14357. {\if\edition\pythonEd
  14358. \begin{lstlisting}
  14359. def g(x_0 : int)-> int:
  14360. x = (x_0,)
  14361. f : Callable[[int], int] = (lambda a: a + x[0])
  14362. x[0] = 10
  14363. return f(32)
  14364. \end{lstlisting}
  14365. \fi}
  14366. %% Recall the second example in Section~\ref{sec:assignment-scoping}
  14367. %% involving a counter abstraction. The following is the output of
  14368. %% assignment version for function \code{f}.
  14369. %% \begin{lstlisting}
  14370. %% (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  14371. %% (vector
  14372. %% (lambda: () : Integer x1)
  14373. %% (lambda: () : Void (set! x1 (+ 1 x1)))))
  14374. %% |$\Rightarrow$|
  14375. %% (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  14376. %% (let ([x1 (vector param_x1)])
  14377. %% (vector (lambda: () : Integer (vector-ref x1 0))
  14378. %% (lambda: () : Void
  14379. %% (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  14380. %% \end{lstlisting}
  14381. \section{Closure Conversion}
  14382. \label{sec:closure-conversion}
  14383. \index{subject}{closure conversion}
  14384. The compiling of lexically-scoped functions into top-level function
  14385. definitions is accomplished in the pass \code{convert\_to\_closures}
  14386. that comes after \code{reveal\_functions} and before
  14387. \code{limit\_functions}.
  14388. As usual, we implement the pass as a recursive function over the
  14389. AST. The interesting cases are the ones for \key{lambda} and function
  14390. application. We transform a \key{lambda} expression into an expression
  14391. that creates a closure, that is, a tuple whose first element is a
  14392. function pointer and the rest of the elements are the values of the
  14393. free variables of the \key{lambda}.
  14394. %
  14395. \racket{However, we use the \code{Closure}
  14396. AST node instead of using a tuple so that we can record the arity
  14397. which is needed for \code{procedure-arity} and
  14398. to distinguish closures from tuples in
  14399. Section~\ref{sec:optimize-closures}.}
  14400. %
  14401. In the generated code below, \itm{fvs} is the free variables of the
  14402. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14403. %
  14404. \racket{The \itm{arity} is the number of parameters (the length of
  14405. \itm{ps}).}
  14406. %
  14407. {\if\edition\racketEd
  14408. \begin{lstlisting}
  14409. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14410. |$\Rightarrow$|
  14411. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  14412. \end{lstlisting}
  14413. \fi}
  14414. %
  14415. {\if\edition\pythonEd
  14416. \begin{lstlisting}
  14417. Lambda(|\itm{ps}|, |\itm{body}|)
  14418. |$\Rightarrow$|
  14419. Tuple([FunRef(|\itm{name}|), |\itm{fvs}, \ldots|])
  14420. \end{lstlisting}
  14421. \fi}
  14422. %
  14423. In addition to transforming each \key{Lambda} AST node into a
  14424. tuple, we create a top-level function definition for each
  14425. \key{Lambda}, as shown below.\\
  14426. \begin{minipage}{0.8\textwidth}
  14427. {\if\edition\racketEd
  14428. \begin{lstlisting}
  14429. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14430. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14431. ...
  14432. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14433. |\itm{body'}|)...))
  14434. \end{lstlisting}
  14435. \fi}
  14436. {\if\edition\pythonEd
  14437. \begin{lstlisting}
  14438. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14439. |$\itm{fvs}_1$| = clos[1]
  14440. |$\ldots$|
  14441. |$\itm{fvs}_n$| = clos[|$n$|]
  14442. |\itm{body'}|
  14443. \end{lstlisting}
  14444. \fi}
  14445. \end{minipage}\\
  14446. The \code{clos} parameter refers to the closure. Translate the type
  14447. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14448. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14449. \itm{closTy} is a tuple type whose first element type is
  14450. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14451. the element types are the types of the free variables in the
  14452. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14453. is non-trivial to give a type to the function in the closure's type.%
  14454. %
  14455. \footnote{To give an accurate type to a closure, we would need to add
  14456. existential types to the type checker~\citep{Minamide:1996ys}.}
  14457. %
  14458. %% The dummy type is considered to be equal to any other type during type
  14459. %% checking.
  14460. The free variables become local variables that are initialized with
  14461. their values in the closure.
  14462. Closure conversion turns every function into a tuple, so the type
  14463. annotations in the program must also be translated. We recommend
  14464. defining an auxiliary recursive function for this purpose. Function
  14465. types should be translated as follows.
  14466. %
  14467. {\if\edition\racketEd
  14468. \begin{lstlisting}
  14469. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14470. |$\Rightarrow$|
  14471. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14472. \end{lstlisting}
  14473. \fi}
  14474. {\if\edition\pythonEd
  14475. \begin{lstlisting}
  14476. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14477. |$\Rightarrow$|
  14478. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14479. \end{lstlisting}
  14480. \fi}
  14481. %
  14482. The above type says that the first thing in the tuple is a
  14483. function. The first parameter of the function is a tuple (a closure)
  14484. and the rest of the parameters are the ones from the original
  14485. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14486. omits the types of the free variables because 1) those types are not
  14487. available in this context and 2) we do not need them in the code that
  14488. is generated for function application.
  14489. We transform function application into code that retrieves the
  14490. function from the closure and then calls the function, passing in the
  14491. closure as the first argument. We place $e'$ in a temporary variable
  14492. to avoid code duplication.
  14493. \begin{center}
  14494. \begin{minipage}{\textwidth}
  14495. {\if\edition\racketEd
  14496. \begin{lstlisting}
  14497. (Apply |$e$| |$\itm{es}$|)
  14498. |$\Rightarrow$|
  14499. (Let |$\itm{tmp}$| |$e'$|
  14500. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons |$\itm{tmp}$| |$\itm{es'}$|)))
  14501. \end{lstlisting}
  14502. \fi}
  14503. %
  14504. {\if\edition\pythonEd
  14505. \begin{lstlisting}
  14506. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14507. |$\Rightarrow$|
  14508. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  14509. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14510. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14511. \end{lstlisting}
  14512. \fi}
  14513. \end{minipage}
  14514. \end{center}
  14515. There is also the question of what to do with references to top-level
  14516. function definitions. To maintain a uniform translation of function
  14517. application, we turn function references into closures.
  14518. \begin{tabular}{lll}
  14519. \begin{minipage}{0.3\textwidth}
  14520. {\if\edition\racketEd
  14521. \begin{lstlisting}
  14522. (FunRefArity |$f$| |$n$|)
  14523. \end{lstlisting}
  14524. \fi}
  14525. {\if\edition\pythonEd
  14526. \begin{lstlisting}
  14527. FunRefArity(|$f$|, |$n$|)
  14528. \end{lstlisting}
  14529. \fi}
  14530. \end{minipage}
  14531. &
  14532. $\Rightarrow$
  14533. &
  14534. \begin{minipage}{0.5\textwidth}
  14535. {\if\edition\racketEd
  14536. \begin{lstlisting}
  14537. (Closure |$n$| (FunRef |$f$|) '())
  14538. \end{lstlisting}
  14539. \fi}
  14540. {\if\edition\pythonEd
  14541. \begin{lstlisting}
  14542. Tuple([FunRef(|$f$|)])
  14543. \end{lstlisting}
  14544. \fi}
  14545. \end{minipage}
  14546. \end{tabular} \\
  14547. %
  14548. The top-level function definitions need to be updated as well to take
  14549. an extra closure parameter.
  14550. \section{An Example Translation}
  14551. \label{sec:example-lambda}
  14552. Figure~\ref{fig:lexical-functions-example} shows the result of
  14553. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14554. program demonstrating lexical scoping that we discussed at the
  14555. beginning of this chapter.
  14556. \begin{figure}[tbp]
  14557. \begin{minipage}{0.8\textwidth}
  14558. {\if\edition\racketEd
  14559. % tests/lambda_test_6.rkt
  14560. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14561. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14562. (let ([y8 4])
  14563. (lambda: ([z9 : Integer]) : Integer
  14564. (+ x7 (+ y8 z9)))))
  14565. (define (main) : Integer
  14566. (let ([g0 ((fun-ref-arity f6 1) 5)])
  14567. (let ([h1 ((fun-ref-arity f6 1) 3)])
  14568. (+ (g0 11) (h1 15)))))
  14569. \end{lstlisting}
  14570. $\Rightarrow$
  14571. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14572. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14573. (let ([y8 4])
  14574. (closure 1 (list (fun-ref lambda2) x7 y8))))
  14575. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14576. (let ([x7 (vector-ref fvs3 1)])
  14577. (let ([y8 (vector-ref fvs3 2)])
  14578. (+ x7 (+ y8 z9)))))
  14579. (define (main) : Integer
  14580. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  14581. ((vector-ref clos5 0) clos5 5))])
  14582. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  14583. ((vector-ref clos6 0) clos6 3))])
  14584. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14585. \end{lstlisting}
  14586. \fi}
  14587. %
  14588. {\if\edition\pythonEd
  14589. % free_var.py
  14590. \begin{lstlisting}
  14591. def f(x : int) -> Callable[[int], int]:
  14592. y = 4
  14593. return lambda z: x + y + z
  14594. g = f(5)
  14595. h = f(3)
  14596. print( g(11) + h(15) )
  14597. \end{lstlisting}
  14598. $\Rightarrow$
  14599. \begin{lstlisting}
  14600. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  14601. x = fvs_1[1]
  14602. y = fvs_1[2]
  14603. return x + y[0] + z
  14604. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  14605. y = (777,)
  14606. y[0] = 4
  14607. return (lambda_0, y, x)
  14608. def main() -> int:
  14609. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  14610. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  14611. print((let clos_5 = g in clos_5[0](clos_5, 11))
  14612. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  14613. return 0
  14614. \end{lstlisting}
  14615. \fi}
  14616. \end{minipage}
  14617. \caption{Example of closure conversion.}
  14618. \label{fig:lexical-functions-example}
  14619. \end{figure}
  14620. \begin{exercise}\normalfont
  14621. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14622. Create 5 new programs that use \key{lambda} functions and make use of
  14623. lexical scoping. Test your compiler on these new programs and all of
  14624. your previously created test programs.
  14625. \end{exercise}
  14626. \if\edition\racketEd
  14627. \section{Expose Allocation}
  14628. \label{sec:expose-allocation-r5}
  14629. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  14630. that allocates and initializes a vector, similar to the translation of
  14631. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  14632. The only difference is replacing the use of
  14633. \ALLOC{\itm{len}}{\itm{type}} with
  14634. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14635. \section{Explicate Control and \LangCLam{}}
  14636. \label{sec:explicate-r5}
  14637. The output language of \code{explicate\_control} is \LangCLam{} whose
  14638. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  14639. difference with respect to \LangCFun{} is the addition of the
  14640. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  14641. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  14642. similar to the handling of other expressions such as primitive
  14643. operators.
  14644. \begin{figure}[tp]
  14645. \fbox{
  14646. \begin{minipage}{0.96\textwidth}
  14647. \small
  14648. {\if\edition\racketEd
  14649. \[
  14650. \begin{array}{lcl}
  14651. \Exp &::= & \ldots
  14652. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14653. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14654. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  14655. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14656. \MID \GOTO{\itm{label}} } \\
  14657. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14658. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  14659. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14660. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14661. \end{array}
  14662. \]
  14663. \fi}
  14664. \end{minipage}
  14665. }
  14666. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14667. \label{fig:c4-syntax}
  14668. \end{figure}
  14669. \section{Select Instructions}
  14670. \label{sec:select-instructions-Rlambda}
  14671. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14672. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14673. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14674. that you should place the \itm{arity} in the tag that is stored at
  14675. position $0$ of the vector. Recall that in
  14676. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14677. was not used. We store the arity in the $5$ bits starting at position
  14678. $58$.
  14679. Compile the \code{procedure-arity} operator into a sequence of
  14680. instructions that access the tag from position $0$ of the vector and
  14681. extract the $5$-bits starting at position $58$ from the tag.
  14682. \fi
  14683. \begin{figure}[p]
  14684. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14685. \node (Rfun) at (0,2) {\large \LangLam{}};
  14686. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  14687. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  14688. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14689. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  14690. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  14691. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  14692. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  14693. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14694. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14695. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14696. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14697. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14698. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14699. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14700. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14701. \path[->,bend left=15] (Rfun) edge [above] node
  14702. {\ttfamily\footnotesize shrink} (Rfun-2);
  14703. \path[->,bend left=15] (Rfun-2) edge [above] node
  14704. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14705. \path[->,bend left=15] (Rfun-3) edge [above] node
  14706. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14707. \path[->,bend left=15] (F1-0) edge [right] node
  14708. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  14709. \path[->,bend left=15] (F1-1) edge [below] node
  14710. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14711. \path[->,bend right=15] (F1-2) edge [above] node
  14712. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14713. \path[->,bend right=15] (F1-3) edge [above] node
  14714. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14715. \path[->,bend right=15] (F1-4) edge [above] node
  14716. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14717. \path[->,bend right=15] (F1-5) edge [right] node
  14718. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14719. \path[->,bend left=15] (C3-2) edge [left] node
  14720. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14721. \path[->,bend right=15] (x86-2) edge [left] node
  14722. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14723. \path[->,bend right=15] (x86-2-1) edge [below] node
  14724. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14725. \path[->,bend right=15] (x86-2-2) edge [left] node
  14726. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14727. \path[->,bend left=15] (x86-3) edge [above] node
  14728. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14729. \path[->,bend left=15] (x86-4) edge [right] node
  14730. {\ttfamily\footnotesize print\_x86} (x86-5);
  14731. \end{tikzpicture}
  14732. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14733. functions.}
  14734. \label{fig:Rlambda-passes}
  14735. \end{figure}
  14736. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  14737. for the compilation of \LangLam{}.
  14738. \clearpage
  14739. \section{Challenge: Optimize Closures}
  14740. \label{sec:optimize-closures}
  14741. In this chapter we compiled lexically-scoped functions into a
  14742. relatively efficient representation: flat closures. However, even this
  14743. representation comes with some overhead. For example, consider the
  14744. following program with a function \code{tail\_sum} that does not have
  14745. any free variables and where all the uses of \code{tail\_sum} are in
  14746. applications where we know that only \code{tail\_sum} is being applied
  14747. (and not any other functions).
  14748. \begin{center}
  14749. \begin{minipage}{0.95\textwidth}
  14750. {\if\edition\racketEd
  14751. \begin{lstlisting}
  14752. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  14753. (if (eq? n 0)
  14754. s
  14755. (tail_sum (- n 1) (+ n s))))
  14756. (+ (tail_sum 3 0) 36)
  14757. \end{lstlisting}
  14758. \fi}
  14759. {\if\edition\pythonEd
  14760. \begin{lstlisting}
  14761. def tail_sum(n : int, s : int) -> int:
  14762. if n == 0:
  14763. return s
  14764. else:
  14765. return tail_sum(n - 1, n + s)
  14766. print( tail_sum(3, 0) + 36)
  14767. \end{lstlisting}
  14768. \fi}
  14769. \end{minipage}
  14770. \end{center}
  14771. As described in this chapter, we uniformly apply closure conversion to
  14772. all functions, obtaining the following output for this program.
  14773. \begin{center}
  14774. \begin{minipage}{0.95\textwidth}
  14775. {\if\edition\racketEd
  14776. \begin{lstlisting}
  14777. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  14778. (if (eq? n2 0)
  14779. s3
  14780. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  14781. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  14782. (define (main) : Integer
  14783. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  14784. ((vector-ref clos6 0) clos6 3 0)) 27))
  14785. \end{lstlisting}
  14786. \fi}
  14787. {\if\edition\pythonEd
  14788. \begin{lstlisting}
  14789. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  14790. if n_0 == 0:
  14791. return s_1
  14792. else:
  14793. return (let clos_2 = (tail_sum,)
  14794. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  14795. def main() -> int :
  14796. print((let clos_4 = (tail_sum,)
  14797. in clos_4[0](clos_4, 3, 0)) + 36)
  14798. return 0
  14799. \end{lstlisting}
  14800. \fi}
  14801. \end{minipage}
  14802. \end{center}
  14803. In the previous chapter, there would be no allocation in the program
  14804. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  14805. the above program allocates memory for each closure and the calls to
  14806. \code{tail\_sum} are indirect. These two differences incur
  14807. considerable overhead in a program such as this one, where the
  14808. allocations and indirect calls occur inside a tight loop.
  14809. One might think that this problem is trivial to solve: can't we just
  14810. recognize calls of the form \APPLY{\FUNREF{$f$}}{$\mathit{args}$}
  14811. and compile them to direct calls instead of treating it like a call to
  14812. a closure? We would also drop the new \code{fvs} parameter of
  14813. \code{tail\_sum}.
  14814. %
  14815. However, this problem is not so trivial because a global function may
  14816. ``escape'' and become involved in applications that also involve
  14817. closures. Consider the following example in which the application
  14818. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  14819. application, because the \code{lambda} may flow into \code{f}, but the
  14820. \code{inc} function might also flow into \code{f}.
  14821. \begin{center}
  14822. \begin{minipage}{\textwidth}
  14823. % lambda_test_30.rkt
  14824. {\if\edition\racketEd
  14825. \begin{lstlisting}
  14826. (define (inc [x : Integer]) : Integer
  14827. (+ x 1))
  14828. (let ([y (read)])
  14829. (let ([f (if (eq? (read) 0)
  14830. inc
  14831. (lambda: ([x : Integer]) : Integer (- x y)))])
  14832. (f 41)))
  14833. \end{lstlisting}
  14834. \fi}
  14835. {\if\edition\pythonEd
  14836. \begin{lstlisting}
  14837. def add1(x : int) -> int:
  14838. return x + 1
  14839. y = input_int()
  14840. g : Callable[[int], int] = lambda x: x - y
  14841. f = add1 if input_int() == 0 else g
  14842. print( f(41) )
  14843. \end{lstlisting}
  14844. \fi}
  14845. \end{minipage}
  14846. \end{center}
  14847. If a global function name is used in any way other than as the
  14848. operator in a direct call, then we say that the function
  14849. \emph{escapes}. If a global function does not escape, then we do not
  14850. need to perform closure conversion on the function.
  14851. \begin{exercise}\normalfont
  14852. Implement an auxiliary function for detecting which global
  14853. functions escape. Using that function, implement an improved version
  14854. of closure conversion that does not apply closure conversion to
  14855. global functions that do not escape but instead compiles them as
  14856. regular functions. Create several new test cases that check whether
  14857. you properly detect whether global functions escape or not.
  14858. \end{exercise}
  14859. So far we have reduced the overhead of calling global functions, but
  14860. it would also be nice to reduce the overhead of calling a
  14861. \code{lambda} when we can determine at compile time which
  14862. \code{lambda} will be called. We refer to such calls as \emph{known
  14863. calls}. Consider the following example in which a \code{lambda} is
  14864. bound to \code{f} and then applied.
  14865. {\if\edition\racketEd
  14866. % lambda_test_9.rkt
  14867. \begin{lstlisting}
  14868. (let ([y (read)])
  14869. (let ([f (lambda: ([x : Integer]) : Integer
  14870. (+ x y))])
  14871. (f 21)))
  14872. \end{lstlisting}
  14873. \fi}
  14874. {\if\edition\pythonEd
  14875. \begin{lstlisting}
  14876. y = input_int()
  14877. f : Callable[[int],int] = lambda x: x + y
  14878. print( f(21) )
  14879. \end{lstlisting}
  14880. \fi}
  14881. %
  14882. \noindent Closure conversion compiles the application
  14883. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  14884. %
  14885. {\if\edition\racketEd
  14886. \begin{lstlisting}
  14887. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  14888. (let ([y2 (vector-ref fvs6 1)])
  14889. (+ x3 y2)))
  14890. (define (main) : Integer
  14891. (let ([y2 (read)])
  14892. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  14893. ((vector-ref f4 0) f4 21))))
  14894. \end{lstlisting}
  14895. \fi}
  14896. {\if\edition\pythonEd
  14897. \begin{lstlisting}
  14898. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  14899. y_1 = fvs_4[1]
  14900. return x_2 + y_1[0]
  14901. def main() -> int:
  14902. y_1 = (777,)
  14903. y_1[0] = input_int()
  14904. f_0 = (lambda_3, y_1)
  14905. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  14906. return 0
  14907. \end{lstlisting}
  14908. \fi}
  14909. %
  14910. \noindent but we can instead compile the application
  14911. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  14912. %
  14913. {\if\edition\racketEd
  14914. \begin{lstlisting}
  14915. (define (main) : Integer
  14916. (let ([y2 (read)])
  14917. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  14918. ((fun-ref lambda5) f4 21))))
  14919. \end{lstlisting}
  14920. \fi}
  14921. {\if\edition\pythonEd
  14922. \begin{lstlisting}
  14923. def main() -> int:
  14924. y_1 = (777,)
  14925. y_1[0] = input_int()
  14926. f_0 = (lambda_3, y_1)
  14927. print(lambda_3(f_0, 21))
  14928. return 0
  14929. \end{lstlisting}
  14930. \fi}
  14931. The problem of determining which \code{lambda} will be called from a
  14932. particular application is quite challenging in general and the topic
  14933. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  14934. following exercise we recommend that you compile an application to a
  14935. direct call when the operator is a variable and \racket{the variable
  14936. is \code{let}-bound to a closure} \python{the previous assignment to
  14937. the variable is a closure}. This can be accomplished by maintaining
  14938. an environment mapping variables to function names. Extend the
  14939. environment whenever you encounter a closure on the right-hand side of
  14940. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  14941. name of the global function for the closure. This pass should come
  14942. after closure conversion.
  14943. \begin{exercise}\normalfont
  14944. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  14945. compiles known calls into direct calls. Verify that your compiler is
  14946. successful in this regard on several example programs.
  14947. \end{exercise}
  14948. These exercises only scratches the surface of optimizing of
  14949. closures. A good next step for the interested reader is to look at the
  14950. work of \citet{Keep:2012ab}.
  14951. \section{Further Reading}
  14952. The notion of lexically scoped functions predates modern computers by
  14953. about a decade. They were invented by \citet{Church:1932aa}, who
  14954. proposed the lambda calculus as a foundation for logic. Anonymous
  14955. functions were included in the LISP~\citep{McCarthy:1960dz}
  14956. programming language but were initially dynamically scoped. The Scheme
  14957. dialect of LISP adopted lexical scoping and
  14958. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  14959. Scheme programs. However, environments were represented as linked
  14960. lists, so variable lookup was linear in the size of the
  14961. environment. In this chapter we represent environments using flat
  14962. closures, which were invented by
  14963. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  14964. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  14965. closures, variable lookup is constant time but the time to create a
  14966. closure is proportional to the number of its free variables. Flat
  14967. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  14968. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  14969. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14970. \chapter{Dynamic Typing}
  14971. \label{ch:Ldyn}
  14972. \index{subject}{dynamic typing}
  14973. In this chapter we discuss the compilation of \LangDyn{}, a
  14974. dynamically typed language. This is in contrast to the previous
  14975. chapters, which have studied the compilation of statically typed
  14976. languages. In dynamically typed languages such as \LangDyn{}, a
  14977. particular expression may produce a value of a different type each
  14978. time it is executed. Consider the following example with a conditional
  14979. \code{if} expression that may return a Boolean or an integer depending
  14980. on the input to the program.
  14981. % part of dynamic_test_25.rkt
  14982. {\if\edition\racketEd
  14983. \begin{lstlisting}
  14984. (not (if (eq? (read) 1) #f 0))
  14985. \end{lstlisting}
  14986. \fi}
  14987. {\if\edition\pythonEd
  14988. \begin{lstlisting}
  14989. not (False if input_int() == 1 else 0)
  14990. \end{lstlisting}
  14991. \fi}
  14992. Languages that allow expressions to produce different kinds of values
  14993. are called \emph{polymorphic}, a word composed of the Greek roots
  14994. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  14995. are several kinds of polymorphism in programming languages, such as
  14996. subtype polymorphism and parametric
  14997. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  14998. study in this chapter does not have a special name but it is the kind
  14999. that arises in dynamically typed languages.
  15000. Another characteristic of dynamically typed languages is that
  15001. primitive operations, such as \code{not}, are often defined to operate
  15002. on many different types of values. In fact, in
  15003. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15004. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15005. given anything else it returns \FALSE{}.
  15006. Furthermore, even when primitive operations restrict their inputs to
  15007. values of a certain type, this restriction is enforced at runtime
  15008. instead of during compilation. For example, the following tuple read
  15009. operation results in a run-time error because it requires a tuple, not
  15010. a Boolean such as \TRUE{}.
  15011. %
  15012. {\if\edition\racketEd
  15013. \begin{lstlisting}
  15014. (vector-ref #t 0)
  15015. \end{lstlisting}
  15016. \fi}
  15017. %
  15018. {\if\edition\pythonEd
  15019. \begin{lstlisting}
  15020. True[0]
  15021. \end{lstlisting}
  15022. \fi}
  15023. \begin{figure}[tp]
  15024. \centering
  15025. \fbox{
  15026. \begin{minipage}{0.97\textwidth}
  15027. {\if\edition\racketEd
  15028. \[
  15029. \begin{array}{rcl}
  15030. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  15031. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  15032. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  15033. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  15034. &\MID& \key{\#t} \MID \key{\#f}
  15035. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  15036. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  15037. \MID \CUNIOP{\key{not}}{\Exp} \\
  15038. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15039. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  15040. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  15041. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  15042. &\MID& \LP\Exp \; \Exp\ldots\RP
  15043. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15044. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15045. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15046. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  15047. \LangDynM{} &::=& \Def\ldots\; \Exp
  15048. \end{array}
  15049. \]
  15050. \fi}
  15051. {\if\edition\pythonEd
  15052. UNDER CONSTRUCTION
  15053. \fi}
  15054. \end{minipage}
  15055. }
  15056. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15057. \label{fig:r7-concrete-syntax}
  15058. \end{figure}
  15059. \begin{figure}[tp]
  15060. \centering
  15061. \fbox{
  15062. \begin{minipage}{0.96\textwidth}
  15063. \small
  15064. {\if\edition\racketEd
  15065. \[
  15066. \begin{array}{lcl}
  15067. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  15068. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  15069. &\MID& \BOOL{\itm{bool}}
  15070. \MID \IF{\Exp}{\Exp}{\Exp} \\
  15071. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  15072. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15073. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  15074. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15075. \end{array}
  15076. \]
  15077. \fi}
  15078. {\if\edition\pythonEd
  15079. UNDER CONSTRUCTION
  15080. \fi}
  15081. \end{minipage}
  15082. }
  15083. \caption{The abstract syntax of \LangDyn{}.}
  15084. \label{fig:r7-syntax}
  15085. \end{figure}
  15086. The concrete and abstract syntax of \LangDyn{}, our subset of
  15087. \racket{Racket}\python{Python}, is defined in
  15088. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15089. %
  15090. There is no type checker for \LangDyn{} because it is not a statically
  15091. typed language (it's dynamically typed!).
  15092. UNDER CONSTRUCTION
  15093. The definitional interpreter for \LangDyn{} is presented in
  15094. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined in
  15095. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  15096. \INT{n}. Instead of simply returning the integer \code{n} (as
  15097. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  15098. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15099. value} that combines an underlying value with a tag that identifies
  15100. what kind of value it is. We define the following struct
  15101. to represented tagged values.
  15102. \begin{lstlisting}
  15103. (struct Tagged (value tag) #:transparent)
  15104. \end{lstlisting}
  15105. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  15106. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  15107. but don't always capture all the information that a type does. For
  15108. example, a vector of type \code{(Vector Any Any)} is tagged with
  15109. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  15110. is tagged with \code{Procedure}.
  15111. Next consider the match case for \code{vector-ref}. The
  15112. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  15113. is used to ensure that the first argument is a vector and the second
  15114. is an integer. If they are not, a \code{trapped-error} is raised.
  15115. Recall from Section~\ref{sec:interp_Lint} that when a definition
  15116. interpreter raises a \code{trapped-error} error, the compiled code
  15117. must also signal an error by exiting with return code \code{255}. A
  15118. \code{trapped-error} is also raised if the index is not less than
  15119. length of the vector.
  15120. \begin{figure}[tbp]
  15121. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15122. (define ((interp-Rdyn-exp env) ast)
  15123. (define recur (interp-Rdyn-exp env))
  15124. (match ast
  15125. [(Var x) (lookup x env)]
  15126. [(Int n) (Tagged n 'Integer)]
  15127. [(Bool b) (Tagged b 'Boolean)]
  15128. [(Lambda xs rt body)
  15129. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15130. [(Prim 'vector es)
  15131. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15132. [(Prim 'vector-ref (list e1 e2))
  15133. (define vec (recur e1)) (define i (recur e2))
  15134. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15135. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15136. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15137. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15138. [(Prim 'vector-set! (list e1 e2 e3))
  15139. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15140. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15141. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15142. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15143. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15144. (Tagged (void) 'Void)]
  15145. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  15146. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15147. [(Prim 'or (list e1 e2))
  15148. (define v1 (recur e1))
  15149. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15150. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15151. [(Prim op (list e1))
  15152. #:when (set-member? type-predicates op)
  15153. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15154. [(Prim op es)
  15155. (define args (map recur es))
  15156. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15157. (unless (for/or ([expected-tags (op-tags op)])
  15158. (equal? expected-tags tags))
  15159. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15160. (tag-value
  15161. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15162. [(If q t f)
  15163. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15164. [(Apply f es)
  15165. (define new-f (recur f)) (define args (map recur es))
  15166. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15167. (match f-val
  15168. [`(function ,xs ,body ,lam-env)
  15169. (unless (eq? (length xs) (length args))
  15170. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15171. (define new-env (append (map cons xs args) lam-env))
  15172. ((interp-Rdyn-exp new-env) body)]
  15173. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  15174. \end{lstlisting}
  15175. \caption{Interpreter for the \LangDyn{} language.}
  15176. \label{fig:interp-Rdyn}
  15177. \end{figure}
  15178. \begin{figure}[tbp]
  15179. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15180. (define (interp-op op)
  15181. (match op
  15182. ['+ fx+]
  15183. ['- fx-]
  15184. ['read read-fixnum]
  15185. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  15186. ['< (lambda (v1 v2)
  15187. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  15188. ['<= (lambda (v1 v2)
  15189. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  15190. ['> (lambda (v1 v2)
  15191. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  15192. ['>= (lambda (v1 v2)
  15193. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  15194. ['boolean? boolean?]
  15195. ['integer? fixnum?]
  15196. ['void? void?]
  15197. ['vector? vector?]
  15198. ['vector-length vector-length]
  15199. ['procedure? (match-lambda
  15200. [`(functions ,xs ,body ,env) #t] [else #f])]
  15201. [else (error 'interp-op "unknown operator" op)]))
  15202. (define (op-tags op)
  15203. (match op
  15204. ['+ '((Integer Integer))]
  15205. ['- '((Integer Integer) (Integer))]
  15206. ['read '(())]
  15207. ['not '((Boolean))]
  15208. ['< '((Integer Integer))]
  15209. ['<= '((Integer Integer))]
  15210. ['> '((Integer Integer))]
  15211. ['>= '((Integer Integer))]
  15212. ['vector-length '((Vector))]))
  15213. (define type-predicates
  15214. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15215. (define (tag-value v)
  15216. (cond [(boolean? v) (Tagged v 'Boolean)]
  15217. [(fixnum? v) (Tagged v 'Integer)]
  15218. [(procedure? v) (Tagged v 'Procedure)]
  15219. [(vector? v) (Tagged v 'Vector)]
  15220. [(void? v) (Tagged v 'Void)]
  15221. [else (error 'tag-value "unidentified value ~a" v)]))
  15222. (define (check-tag val expected ast)
  15223. (define tag (Tagged-tag val))
  15224. (unless (eq? tag expected)
  15225. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  15226. \end{lstlisting}
  15227. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  15228. \label{fig:interp-Rdyn-aux}
  15229. \end{figure}
  15230. \clearpage
  15231. \section{Representation of Tagged Values}
  15232. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  15233. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  15234. values at the bit level. Because almost every operation in \LangDyn{}
  15235. involves manipulating tagged values, the representation must be
  15236. efficient. Recall that all of our values are 64 bits. We shall steal
  15237. the 3 right-most bits to encode the tag. We use $001$ to identify
  15238. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  15239. and $101$ for the void value. We define the following auxiliary
  15240. function for mapping types to tag codes.
  15241. \begin{align*}
  15242. \itm{tagof}(\key{Integer}) &= 001 \\
  15243. \itm{tagof}(\key{Boolean}) &= 100 \\
  15244. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  15245. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  15246. \itm{tagof}(\key{Void}) &= 101
  15247. \end{align*}
  15248. This stealing of 3 bits comes at some price: our integers are reduced
  15249. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  15250. affect vectors and procedures because those values are addresses, and
  15251. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  15252. they are always $000$. Thus, we do not lose information by overwriting
  15253. the rightmost 3 bits with the tag and we can simply zero-out the tag
  15254. to recover the original address.
  15255. To make tagged values into first-class entities, we can give them a
  15256. type, called \code{Any}, and define operations such as \code{Inject}
  15257. and \code{Project} for creating and using them, yielding the \LangAny{}
  15258. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  15259. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  15260. in greater detail.
  15261. \section{The \LangAny{} Language}
  15262. \label{sec:Rany-lang}
  15263. \newcommand{\LAnyAST}{
  15264. \begin{array}{lcl}
  15265. \Type &::= & \key{Any} \\
  15266. \itm{op} &::= & \code{any-vector-length}
  15267. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15268. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15269. \MID \code{procedure?} \MID \code{void?} \\
  15270. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  15271. \end{array}
  15272. }
  15273. \begin{figure}[tp]
  15274. \centering
  15275. \fbox{
  15276. \begin{minipage}{0.96\textwidth}
  15277. \small
  15278. {\if\edition\racketEd
  15279. \[
  15280. \begin{array}{l}
  15281. \gray{\LintOpAST} \\ \hline
  15282. \gray{\LvarASTRacket{}} \\ \hline
  15283. \gray{\LifASTRacket{}} \\ \hline
  15284. \gray{\LwhileASTRacket{}} \\ \hline
  15285. \gray{\LtupASTRacket{}} \\ \hline
  15286. \gray{\LfunASTRacket} \\ \hline
  15287. \gray{\LlambdaASTRacket} \\ \hline
  15288. \LAnyAST \\
  15289. \begin{array}{lcl}
  15290. %% \Type &::= & \ldots \MID \key{Any} \\
  15291. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  15292. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15293. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15294. %% \MID \code{procedure?} \MID \code{void?} \\
  15295. %% \Exp &::=& \ldots
  15296. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  15297. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15298. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  15299. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15300. \end{array}
  15301. \end{array}
  15302. \]
  15303. \fi}
  15304. {\if\edition\pythonEd
  15305. UNDER CONSTRUCTION
  15306. \fi}
  15307. \end{minipage}
  15308. }
  15309. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  15310. \label{fig:Rany-syntax}
  15311. \end{figure}
  15312. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  15313. (The concrete syntax of \LangAny{} is in the Appendix,
  15314. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  15315. converts the value produced by expression $e$ of type $T$ into a
  15316. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  15317. produced by expression $e$ into a value of type $T$ or else halts the
  15318. program if the type tag is not equivalent to $T$.
  15319. %
  15320. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  15321. restricted to a flat type $\FType$, which simplifies the
  15322. implementation and corresponds with what is needed for compiling \LangDyn{}.
  15323. The \code{any-vector} operators adapt the vector operations so that
  15324. they can be applied to a value of type \code{Any}. They also
  15325. generalize the vector operations in that the index is not restricted
  15326. to be a literal integer in the grammar but is allowed to be any
  15327. expression.
  15328. The type predicates such as \key{boolean?} expect their argument to
  15329. produce a tagged value; they return \key{\#t} if the tag corresponds
  15330. to the predicate and they return \key{\#f} otherwise.
  15331. The type checker for \LangAny{} is shown in
  15332. Figures~\ref{fig:type-check-Rany-part-1} and
  15333. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  15334. Figure~\ref{fig:type-check-Rany-aux}.
  15335. %
  15336. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  15337. auxiliary functions \code{apply-inject} and \code{apply-project} are
  15338. in Figure~\ref{fig:apply-project}.
  15339. \begin{figure}[btp]
  15340. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15341. (define type-check-Rany_class
  15342. (class type-check-Rlambda_class
  15343. (super-new)
  15344. (inherit check-type-equal?)
  15345. (define/override (type-check-exp env)
  15346. (lambda (e)
  15347. (define recur (type-check-exp env))
  15348. (match e
  15349. [(Inject e1 ty)
  15350. (unless (flat-ty? ty)
  15351. (error 'type-check "may only inject from flat type, not ~a" ty))
  15352. (define-values (new-e1 e-ty) (recur e1))
  15353. (check-type-equal? e-ty ty e)
  15354. (values (Inject new-e1 ty) 'Any)]
  15355. [(Project e1 ty)
  15356. (unless (flat-ty? ty)
  15357. (error 'type-check "may only project to flat type, not ~a" ty))
  15358. (define-values (new-e1 e-ty) (recur e1))
  15359. (check-type-equal? e-ty 'Any e)
  15360. (values (Project new-e1 ty) ty)]
  15361. [(Prim 'any-vector-length (list e1))
  15362. (define-values (e1^ t1) (recur e1))
  15363. (check-type-equal? t1 'Any e)
  15364. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  15365. [(Prim 'any-vector-ref (list e1 e2))
  15366. (define-values (e1^ t1) (recur e1))
  15367. (define-values (e2^ t2) (recur e2))
  15368. (check-type-equal? t1 'Any e)
  15369. (check-type-equal? t2 'Integer e)
  15370. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  15371. [(Prim 'any-vector-set! (list e1 e2 e3))
  15372. (define-values (e1^ t1) (recur e1))
  15373. (define-values (e2^ t2) (recur e2))
  15374. (define-values (e3^ t3) (recur e3))
  15375. (check-type-equal? t1 'Any e)
  15376. (check-type-equal? t2 'Integer e)
  15377. (check-type-equal? t3 'Any e)
  15378. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  15379. \end{lstlisting}
  15380. \caption{Type checker for the \LangAny{} language, part 1.}
  15381. \label{fig:type-check-Rany-part-1}
  15382. \end{figure}
  15383. \begin{figure}[btp]
  15384. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15385. [(ValueOf e ty)
  15386. (define-values (new-e e-ty) (recur e))
  15387. (values (ValueOf new-e ty) ty)]
  15388. [(Prim pred (list e1))
  15389. #:when (set-member? (type-predicates) pred)
  15390. (define-values (new-e1 e-ty) (recur e1))
  15391. (check-type-equal? e-ty 'Any e)
  15392. (values (Prim pred (list new-e1)) 'Boolean)]
  15393. [(If cnd thn els)
  15394. (define-values (cnd^ Tc) (recur cnd))
  15395. (define-values (thn^ Tt) (recur thn))
  15396. (define-values (els^ Te) (recur els))
  15397. (check-type-equal? Tc 'Boolean cnd)
  15398. (check-type-equal? Tt Te e)
  15399. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  15400. [(Exit) (values (Exit) '_)]
  15401. [(Prim 'eq? (list arg1 arg2))
  15402. (define-values (e1 t1) (recur arg1))
  15403. (define-values (e2 t2) (recur arg2))
  15404. (match* (t1 t2)
  15405. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  15406. [(other wise) (check-type-equal? t1 t2 e)])
  15407. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  15408. [else ((super type-check-exp env) e)])))
  15409. ))
  15410. \end{lstlisting}
  15411. \caption{Type checker for the \LangAny{} language, part 2.}
  15412. \label{fig:type-check-Rany-part-2}
  15413. \end{figure}
  15414. \begin{figure}[tbp]
  15415. \begin{lstlisting}
  15416. (define/override (operator-types)
  15417. (append
  15418. '((integer? . ((Any) . Boolean))
  15419. (vector? . ((Any) . Boolean))
  15420. (procedure? . ((Any) . Boolean))
  15421. (void? . ((Any) . Boolean))
  15422. (tag-of-any . ((Any) . Integer))
  15423. (make-any . ((_ Integer) . Any))
  15424. )
  15425. (super operator-types)))
  15426. (define/public (type-predicates)
  15427. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15428. (define/public (combine-types t1 t2)
  15429. (match (list t1 t2)
  15430. [(list '_ t2) t2]
  15431. [(list t1 '_) t1]
  15432. [(list `(Vector ,ts1 ...)
  15433. `(Vector ,ts2 ...))
  15434. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  15435. (combine-types t1 t2)))]
  15436. [(list `(,ts1 ... -> ,rt1)
  15437. `(,ts2 ... -> ,rt2))
  15438. `(,@(for/list ([t1 ts1] [t2 ts2])
  15439. (combine-types t1 t2))
  15440. -> ,(combine-types rt1 rt2))]
  15441. [else t1]))
  15442. (define/public (flat-ty? ty)
  15443. (match ty
  15444. [(or `Integer `Boolean '_ `Void) #t]
  15445. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  15446. [`(,ts ... -> ,rt)
  15447. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  15448. [else #f]))
  15449. \end{lstlisting}
  15450. \caption{Auxiliary methods for type checking \LangAny{}.}
  15451. \label{fig:type-check-Rany-aux}
  15452. \end{figure}
  15453. \begin{figure}[btp]
  15454. \begin{lstlisting}
  15455. (define interp-Rany_class
  15456. (class interp-Rlambda_class
  15457. (super-new)
  15458. (define/override (interp-op op)
  15459. (match op
  15460. ['boolean? (match-lambda
  15461. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  15462. [else #f])]
  15463. ['integer? (match-lambda
  15464. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  15465. [else #f])]
  15466. ['vector? (match-lambda
  15467. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  15468. [else #f])]
  15469. ['procedure? (match-lambda
  15470. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  15471. [else #f])]
  15472. ['eq? (match-lambda*
  15473. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  15474. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  15475. [ls (apply (super interp-op op) ls)])]
  15476. ['any-vector-ref (lambda (v i)
  15477. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  15478. ['any-vector-set! (lambda (v i a)
  15479. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  15480. ['any-vector-length (lambda (v)
  15481. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  15482. [else (super interp-op op)]))
  15483. (define/override ((interp-exp env) e)
  15484. (define recur (interp-exp env))
  15485. (match e
  15486. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  15487. [(Project e ty2) (apply-project (recur e) ty2)]
  15488. [else ((super interp-exp env) e)]))
  15489. ))
  15490. (define (interp-Rany p)
  15491. (send (new interp-Rany_class) interp-program p))
  15492. \end{lstlisting}
  15493. \caption{Interpreter for \LangAny{}.}
  15494. \label{fig:interp-Rany}
  15495. \end{figure}
  15496. \begin{figure}[tbp]
  15497. \begin{lstlisting}
  15498. (define/public (apply-inject v tg) (Tagged v tg))
  15499. (define/public (apply-project v ty2)
  15500. (define tag2 (any-tag ty2))
  15501. (match v
  15502. [(Tagged v1 tag1)
  15503. (cond
  15504. [(eq? tag1 tag2)
  15505. (match ty2
  15506. [`(Vector ,ts ...)
  15507. (define l1 ((interp-op 'vector-length) v1))
  15508. (cond
  15509. [(eq? l1 (length ts)) v1]
  15510. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  15511. l1 (length ts))])]
  15512. [`(,ts ... -> ,rt)
  15513. (match v1
  15514. [`(function ,xs ,body ,env)
  15515. (cond [(eq? (length xs) (length ts)) v1]
  15516. [else
  15517. (error 'apply-project "arity mismatch ~a != ~a"
  15518. (length xs) (length ts))])]
  15519. [else (error 'apply-project "expected function not ~a" v1)])]
  15520. [else v1])]
  15521. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  15522. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  15523. \end{lstlisting}
  15524. \caption{Auxiliary functions for injection and projection.}
  15525. \label{fig:apply-project}
  15526. \end{figure}
  15527. \clearpage
  15528. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  15529. \label{sec:compile-r7}
  15530. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  15531. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  15532. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  15533. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  15534. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  15535. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  15536. the Boolean \code{\#t}, which must be injected to produce an
  15537. expression of type \key{Any}.
  15538. %
  15539. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  15540. addition, is representative of compilation for many primitive
  15541. operations: the arguments have type \key{Any} and must be projected to
  15542. \key{Integer} before the addition can be performed.
  15543. The compilation of \key{lambda} (third row of
  15544. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  15545. produce type annotations: we simply use \key{Any}.
  15546. %
  15547. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  15548. has to account for some differences in behavior between \LangDyn{} and
  15549. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  15550. kind of values can be used in various places. For example, the
  15551. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  15552. the arguments need not be of the same type (in that case the
  15553. result is \code{\#f}).
  15554. \begin{figure}[btp]
  15555. \centering
  15556. \begin{tabular}{|lll|} \hline
  15557. \begin{minipage}{0.27\textwidth}
  15558. \begin{lstlisting}
  15559. #t
  15560. \end{lstlisting}
  15561. \end{minipage}
  15562. &
  15563. $\Rightarrow$
  15564. &
  15565. \begin{minipage}{0.65\textwidth}
  15566. \begin{lstlisting}
  15567. (inject #t Boolean)
  15568. \end{lstlisting}
  15569. \end{minipage}
  15570. \\[2ex]\hline
  15571. \begin{minipage}{0.27\textwidth}
  15572. \begin{lstlisting}
  15573. (+ |$e_1$| |$e_2$|)
  15574. \end{lstlisting}
  15575. \end{minipage}
  15576. &
  15577. $\Rightarrow$
  15578. &
  15579. \begin{minipage}{0.65\textwidth}
  15580. \begin{lstlisting}
  15581. (inject
  15582. (+ (project |$e'_1$| Integer)
  15583. (project |$e'_2$| Integer))
  15584. Integer)
  15585. \end{lstlisting}
  15586. \end{minipage}
  15587. \\[2ex]\hline
  15588. \begin{minipage}{0.27\textwidth}
  15589. \begin{lstlisting}
  15590. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  15591. \end{lstlisting}
  15592. \end{minipage}
  15593. &
  15594. $\Rightarrow$
  15595. &
  15596. \begin{minipage}{0.65\textwidth}
  15597. \begin{lstlisting}
  15598. (inject
  15599. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  15600. (Any|$\ldots$|Any -> Any))
  15601. \end{lstlisting}
  15602. \end{minipage}
  15603. \\[2ex]\hline
  15604. \begin{minipage}{0.27\textwidth}
  15605. \begin{lstlisting}
  15606. (|$e_0$| |$e_1 \ldots e_n$|)
  15607. \end{lstlisting}
  15608. \end{minipage}
  15609. &
  15610. $\Rightarrow$
  15611. &
  15612. \begin{minipage}{0.65\textwidth}
  15613. \begin{lstlisting}
  15614. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  15615. \end{lstlisting}
  15616. \end{minipage}
  15617. \\[2ex]\hline
  15618. \begin{minipage}{0.27\textwidth}
  15619. \begin{lstlisting}
  15620. (vector-ref |$e_1$| |$e_2$|)
  15621. \end{lstlisting}
  15622. \end{minipage}
  15623. &
  15624. $\Rightarrow$
  15625. &
  15626. \begin{minipage}{0.65\textwidth}
  15627. \begin{lstlisting}
  15628. (any-vector-ref |$e_1'$| |$e_2'$|)
  15629. \end{lstlisting}
  15630. \end{minipage}
  15631. \\[2ex]\hline
  15632. \begin{minipage}{0.27\textwidth}
  15633. \begin{lstlisting}
  15634. (if |$e_1$| |$e_2$| |$e_3$|)
  15635. \end{lstlisting}
  15636. \end{minipage}
  15637. &
  15638. $\Rightarrow$
  15639. &
  15640. \begin{minipage}{0.65\textwidth}
  15641. \begin{lstlisting}
  15642. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  15643. \end{lstlisting}
  15644. \end{minipage}
  15645. \\[2ex]\hline
  15646. \begin{minipage}{0.27\textwidth}
  15647. \begin{lstlisting}
  15648. (eq? |$e_1$| |$e_2$|)
  15649. \end{lstlisting}
  15650. \end{minipage}
  15651. &
  15652. $\Rightarrow$
  15653. &
  15654. \begin{minipage}{0.65\textwidth}
  15655. \begin{lstlisting}
  15656. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  15657. \end{lstlisting}
  15658. \end{minipage}
  15659. \\[2ex]\hline
  15660. \begin{minipage}{0.27\textwidth}
  15661. \begin{lstlisting}
  15662. (not |$e_1$|)
  15663. \end{lstlisting}
  15664. \end{minipage}
  15665. &
  15666. $\Rightarrow$
  15667. &
  15668. \begin{minipage}{0.65\textwidth}
  15669. \begin{lstlisting}
  15670. (if (eq? |$e'_1$| (inject #f Boolean))
  15671. (inject #t Boolean) (inject #f Boolean))
  15672. \end{lstlisting}
  15673. \end{minipage}
  15674. \\[2ex]\hline
  15675. \end{tabular}
  15676. \caption{Cast Insertion}
  15677. \label{fig:compile-r7-Rany}
  15678. \end{figure}
  15679. \section{Reveal Casts}
  15680. \label{sec:reveal-casts-Rany}
  15681. % TODO: define R'_6
  15682. In the \code{reveal-casts} pass we recommend compiling \code{project}
  15683. into an \code{if} expression that checks whether the value's tag
  15684. matches the target type; if it does, the value is converted to a value
  15685. of the target type by removing the tag; if it does not, the program
  15686. exits. To perform these actions we need a new primitive operation,
  15687. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  15688. The \code{tag-of-any} operation retrieves the type tag from a tagged
  15689. value of type \code{Any}. The \code{ValueOf} form retrieves the
  15690. underlying value from a tagged value. The \code{ValueOf} form
  15691. includes the type for the underlying value which is used by the type
  15692. checker. Finally, the \code{Exit} form ends the execution of the
  15693. program.
  15694. If the target type of the projection is \code{Boolean} or
  15695. \code{Integer}, then \code{Project} can be translated as follows.
  15696. \begin{center}
  15697. \begin{minipage}{1.0\textwidth}
  15698. \begin{lstlisting}
  15699. (Project |$e$| |$\FType$|)
  15700. |$\Rightarrow$|
  15701. (Let |$\itm{tmp}$| |$e'$|
  15702. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  15703. (Int |$\itm{tagof}(\FType)$|)))
  15704. (ValueOf |$\itm{tmp}$| |$\FType$|)
  15705. (Exit)))
  15706. \end{lstlisting}
  15707. \end{minipage}
  15708. \end{center}
  15709. If the target type of the projection is a vector or function type,
  15710. then there is a bit more work to do. For vectors, check that the
  15711. length of the vector type matches the length of the vector (using the
  15712. \code{vector-length} primitive). For functions, check that the number
  15713. of parameters in the function type matches the function's arity (using
  15714. \code{procedure-arity}).
  15715. Regarding \code{inject}, we recommend compiling it to a slightly
  15716. lower-level primitive operation named \code{make-any}. This operation
  15717. takes a tag instead of a type.
  15718. \begin{center}
  15719. \begin{minipage}{1.0\textwidth}
  15720. \begin{lstlisting}
  15721. (Inject |$e$| |$\FType$|)
  15722. |$\Rightarrow$|
  15723. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  15724. \end{lstlisting}
  15725. \end{minipage}
  15726. \end{center}
  15727. The type predicates (\code{boolean?}, etc.) can be translated into
  15728. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  15729. translation of \code{Project}.
  15730. The \code{any-vector-ref} and \code{any-vector-set!} operations
  15731. combine the projection action with the vector operation. Also, the
  15732. read and write operations allow arbitrary expressions for the index so
  15733. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  15734. cannot guarantee that the index is within bounds. Thus, we insert code
  15735. to perform bounds checking at runtime. The translation for
  15736. \code{any-vector-ref} is as follows and the other two operations are
  15737. translated in a similar way.
  15738. \begin{lstlisting}
  15739. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  15740. |$\Rightarrow$|
  15741. (Let |$v$| |$e'_1$|
  15742. (Let |$i$| |$e'_2$|
  15743. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  15744. (If (Prim '< (list (Var |$i$|)
  15745. (Prim 'any-vector-length (list (Var |$v$|)))))
  15746. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  15747. (Exit))))
  15748. \end{lstlisting}
  15749. \section{Remove Complex Operands}
  15750. \label{sec:rco-Rany}
  15751. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  15752. The subexpression of \code{ValueOf} must be atomic.
  15753. \section{Explicate Control and \LangCAny{}}
  15754. \label{sec:explicate-Rany}
  15755. The output of \code{explicate\_control} is the \LangCAny{} language whose
  15756. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  15757. form that we added to \LangAny{} remains an expression and the \code{Exit}
  15758. expression becomes a $\Tail$. Also, note that the index argument of
  15759. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  15760. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  15761. \begin{figure}[tp]
  15762. \fbox{
  15763. \begin{minipage}{0.96\textwidth}
  15764. \small
  15765. {\if\edition\racketEd
  15766. \[
  15767. \begin{array}{lcl}
  15768. \Exp &::= & \ldots
  15769. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  15770. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  15771. &\MID& \VALUEOF{\Exp}{\FType} \\
  15772. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  15773. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  15774. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  15775. \MID \GOTO{\itm{label}} } \\
  15776. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  15777. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  15778. \MID \LP\key{Exit}\RP \\
  15779. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  15780. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  15781. \end{array}
  15782. \]
  15783. \fi}
  15784. {\if\edition\pythonEd
  15785. UNDER CONSTRUCTION
  15786. \fi}
  15787. \end{minipage}
  15788. }
  15789. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  15790. \label{fig:c5-syntax}
  15791. \end{figure}
  15792. \section{Select Instructions}
  15793. \label{sec:select-Rany}
  15794. In the \code{select\_instructions} pass we translate the primitive
  15795. operations on the \code{Any} type to x86 instructions that involve
  15796. manipulating the 3 tag bits of the tagged value.
  15797. \paragraph{Make-any}
  15798. We recommend compiling the \key{make-any} primitive as follows if the
  15799. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  15800. shifts the destination to the left by the number of bits specified its
  15801. source argument (in this case $3$, the length of the tag) and it
  15802. preserves the sign of the integer. We use the \key{orq} instruction to
  15803. combine the tag and the value to form the tagged value. \\
  15804. \begin{lstlisting}
  15805. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  15806. |$\Rightarrow$|
  15807. movq |$e'$|, |\itm{lhs'}|
  15808. salq $3, |\itm{lhs'}|
  15809. orq $|$\itm{tag}$|, |\itm{lhs'}|
  15810. \end{lstlisting}
  15811. The instruction selection for vectors and procedures is different
  15812. because their is no need to shift them to the left. The rightmost 3
  15813. bits are already zeros as described at the beginning of this
  15814. chapter. So we just combine the value and the tag using \key{orq}. \\
  15815. \begin{lstlisting}
  15816. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  15817. |$\Rightarrow$|
  15818. movq |$e'$|, |\itm{lhs'}|
  15819. orq $|$\itm{tag}$|, |\itm{lhs'}|
  15820. \end{lstlisting}
  15821. \paragraph{Tag-of-any}
  15822. Recall that the \code{tag-of-any} operation extracts the type tag from
  15823. a value of type \code{Any}. The type tag is the bottom three bits, so
  15824. we obtain the tag by taking the bitwise-and of the value with $111$
  15825. ($7$ in decimal).
  15826. \begin{lstlisting}
  15827. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  15828. |$\Rightarrow$|
  15829. movq |$e'$|, |\itm{lhs'}|
  15830. andq $7, |\itm{lhs'}|
  15831. \end{lstlisting}
  15832. \paragraph{ValueOf}
  15833. Like \key{make-any}, the instructions for \key{ValueOf} are different
  15834. depending on whether the type $T$ is a pointer (vector or procedure)
  15835. or not (Integer or Boolean). The following shows the instruction
  15836. selection for Integer and Boolean. We produce an untagged value by
  15837. shifting it to the right by 3 bits.
  15838. \begin{lstlisting}
  15839. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  15840. |$\Rightarrow$|
  15841. movq |$e'$|, |\itm{lhs'}|
  15842. sarq $3, |\itm{lhs'}|
  15843. \end{lstlisting}
  15844. %
  15845. In the case for vectors and procedures, there is no need to
  15846. shift. Instead we just need to zero-out the rightmost 3 bits. We
  15847. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  15848. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  15849. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  15850. then apply \code{andq} with the tagged value to get the desired
  15851. result. \\
  15852. \begin{lstlisting}
  15853. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  15854. |$\Rightarrow$|
  15855. movq $|$-8$|, |\itm{lhs'}|
  15856. andq |$e'$|, |\itm{lhs'}|
  15857. \end{lstlisting}
  15858. %% \paragraph{Type Predicates} We leave it to the reader to
  15859. %% devise a sequence of instructions to implement the type predicates
  15860. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  15861. \paragraph{Any-vector-length}
  15862. \begin{lstlisting}
  15863. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  15864. |$\Longrightarrow$|
  15865. movq |$\neg 111$|, %r11
  15866. andq |$a_1'$|, %r11
  15867. movq 0(%r11), %r11
  15868. andq $126, %r11
  15869. sarq $1, %r11
  15870. movq %r11, |$\itm{lhs'}$|
  15871. \end{lstlisting}
  15872. \paragraph{Any-vector-ref}
  15873. The index may be an arbitrary atom so instead of computing the offset
  15874. at compile time, instructions need to be generated to compute the
  15875. offset at runtime as follows. Note the use of the new instruction
  15876. \code{imulq}.
  15877. \begin{center}
  15878. \begin{minipage}{0.96\textwidth}
  15879. \begin{lstlisting}
  15880. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  15881. |$\Longrightarrow$|
  15882. movq |$\neg 111$|, %r11
  15883. andq |$a_1'$|, %r11
  15884. movq |$a_2'$|, %rax
  15885. addq $1, %rax
  15886. imulq $8, %rax
  15887. addq %rax, %r11
  15888. movq 0(%r11) |$\itm{lhs'}$|
  15889. \end{lstlisting}
  15890. \end{minipage}
  15891. \end{center}
  15892. \paragraph{Any-vector-set!}
  15893. The code generation for \code{any-vector-set!} is similar to the other
  15894. \code{any-vector} operations.
  15895. \section{Register Allocation for \LangAny{}}
  15896. \label{sec:register-allocation-Rany}
  15897. \index{subject}{register allocation}
  15898. There is an interesting interaction between tagged values and garbage
  15899. collection that has an impact on register allocation. A variable of
  15900. type \code{Any} might refer to a vector and therefore it might be a
  15901. root that needs to be inspected and copied during garbage
  15902. collection. Thus, we need to treat variables of type \code{Any} in a
  15903. similar way to variables of type \code{Vector} for purposes of
  15904. register allocation. In particular,
  15905. \begin{itemize}
  15906. \item If a variable of type \code{Any} is live during a function call,
  15907. then it must be spilled. This can be accomplished by changing
  15908. \code{build\_interference} to mark all variables of type \code{Any}
  15909. that are live after a \code{callq} as interfering with all the
  15910. registers.
  15911. \item If a variable of type \code{Any} is spilled, it must be spilled
  15912. to the root stack instead of the normal procedure call stack.
  15913. \end{itemize}
  15914. Another concern regarding the root stack is that the garbage collector
  15915. needs to differentiate between (1) plain old pointers to tuples, (2) a
  15916. tagged value that points to a tuple, and (3) a tagged value that is
  15917. not a tuple. We enable this differentiation by choosing not to use the
  15918. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  15919. reserved for identifying plain old pointers to tuples. That way, if
  15920. one of the first three bits is set, then we have a tagged value and
  15921. inspecting the tag can differentiation between vectors ($010$) and the
  15922. other kinds of values.
  15923. \begin{exercise}\normalfont
  15924. Expand your compiler to handle \LangAny{} as discussed in the last few
  15925. sections. Create 5 new programs that use the \code{Any} type and the
  15926. new operations (\code{inject}, \code{project}, \code{boolean?},
  15927. etc.). Test your compiler on these new programs and all of your
  15928. previously created test programs.
  15929. \end{exercise}
  15930. \begin{exercise}\normalfont
  15931. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  15932. Create tests for \LangDyn{} by adapting ten of your previous test programs
  15933. by removing type annotations. Add 5 more tests programs that
  15934. specifically rely on the language being dynamically typed. That is,
  15935. they should not be legal programs in a statically typed language, but
  15936. nevertheless, they should be valid \LangDyn{} programs that run to
  15937. completion without error.
  15938. \end{exercise}
  15939. \begin{figure}[p]
  15940. \begin{tikzpicture}[baseline=(current bounding box.center)]
  15941. \node (Rfun) at (0,4) {\large \LangDyn{}};
  15942. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  15943. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  15944. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  15945. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  15946. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  15947. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  15948. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  15949. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  15950. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  15951. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  15952. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  15953. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15954. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15955. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15956. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15957. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15958. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15959. \path[->,bend left=15] (Rfun) edge [above] node
  15960. {\ttfamily\footnotesize shrink} (Rfun-2);
  15961. \path[->,bend left=15] (Rfun-2) edge [above] node
  15962. {\ttfamily\footnotesize uniquify} (Rfun-3);
  15963. \path[->,bend left=15] (Rfun-3) edge [above] node
  15964. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  15965. \path[->,bend right=15] (Rfun-4) edge [left] node
  15966. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  15967. \path[->,bend left=15] (Rfun-5) edge [above] node
  15968. {\ttfamily\footnotesize check\_bounds} (Rfun-6);
  15969. \path[->,bend left=15] (Rfun-6) edge [left] node
  15970. {\ttfamily\footnotesize reveal\_casts} (Rfun-7);
  15971. \path[->,bend left=15] (Rfun-7) edge [below] node
  15972. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15973. \path[->,bend right=15] (F1-2) edge [above] node
  15974. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15975. \path[->,bend right=15] (F1-3) edge [above] node
  15976. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15977. \path[->,bend right=15] (F1-4) edge [above] node
  15978. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  15979. \path[->,bend right=15] (F1-5) edge [right] node
  15980. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15981. \path[->,bend left=15] (C3-2) edge [left] node
  15982. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15983. \path[->,bend right=15] (x86-2) edge [left] node
  15984. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15985. \path[->,bend right=15] (x86-2-1) edge [below] node
  15986. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15987. \path[->,bend right=15] (x86-2-2) edge [left] node
  15988. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15989. \path[->,bend left=15] (x86-3) edge [above] node
  15990. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15991. \path[->,bend left=15] (x86-4) edge [right] node
  15992. {\ttfamily\footnotesize print\_x86} (x86-5);
  15993. \end{tikzpicture}
  15994. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  15995. \label{fig:Rdyn-passes}
  15996. \end{figure}
  15997. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  15998. for the compilation of \LangDyn{}.
  15999. % Further Reading
  16000. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16001. {\if\edition\pythonEd
  16002. \chapter{Objects}
  16003. \label{ch:Lobject}
  16004. \index{subject}{objects}
  16005. \index{subject}{classes}
  16006. \fi}
  16007. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16008. \chapter{Gradual Typing}
  16009. \label{ch:Lgrad}
  16010. \index{subject}{gradual typing}
  16011. \if\edition\racketEd
  16012. This chapter studies a language, \LangGrad{}, in which the programmer
  16013. can choose between static and dynamic type checking in different parts
  16014. of a program, thereby mixing the statically typed \LangLoop{} language
  16015. with the dynamically typed \LangDyn{}. There are several approaches to
  16016. mixing static and dynamic typing, including multi-language
  16017. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  16018. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  16019. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  16020. programmer controls the amount of static versus dynamic checking by
  16021. adding or removing type annotations on parameters and
  16022. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  16023. %
  16024. The concrete syntax of \LangGrad{} is defined in
  16025. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  16026. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  16027. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  16028. non-terminals that make type annotations optional. The return types
  16029. are not optional in the abstract syntax; the parser fills in
  16030. \code{Any} when the return type is not specified in the concrete
  16031. syntax.
  16032. \begin{figure}[tp]
  16033. \centering
  16034. \fbox{
  16035. \begin{minipage}{0.96\textwidth}
  16036. \small
  16037. \[
  16038. \begin{array}{lcl}
  16039. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16040. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  16041. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  16042. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  16043. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  16044. &\MID& \gray{\key{\#t} \MID \key{\#f}
  16045. \MID (\key{and}\;\Exp\;\Exp)
  16046. \MID (\key{or}\;\Exp\;\Exp)
  16047. \MID (\key{not}\;\Exp) } \\
  16048. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  16049. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  16050. (\key{vector-ref}\;\Exp\;\Int)} \\
  16051. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  16052. \MID (\Exp \; \Exp\ldots) } \\
  16053. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  16054. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  16055. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  16056. \MID \CBEGIN{\Exp\ldots}{\Exp}
  16057. \MID \CWHILE{\Exp}{\Exp} } \\
  16058. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  16059. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  16060. \end{array}
  16061. \]
  16062. \end{minipage}
  16063. }
  16064. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  16065. \label{fig:Rgrad-concrete-syntax}
  16066. \end{figure}
  16067. \begin{figure}[tp]
  16068. \centering
  16069. \fbox{
  16070. \begin{minipage}{0.96\textwidth}
  16071. \small
  16072. \[
  16073. \begin{array}{lcl}
  16074. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16075. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  16076. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  16077. &\MID& \gray{ \BOOL{\itm{bool}}
  16078. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  16079. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  16080. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  16081. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  16082. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  16083. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  16084. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  16085. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16086. \end{array}
  16087. \]
  16088. \end{minipage}
  16089. }
  16090. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  16091. \label{fig:Rgrad-syntax}
  16092. \end{figure}
  16093. Both the type checker and the interpreter for \LangGrad{} require some
  16094. interesting changes to enable gradual typing, which we discuss in the
  16095. next two sections in the context of the \code{map} example from
  16096. Chapter~\ref{ch:Lfun}. In Figure~\ref{fig:gradual-map} we
  16097. revised the \code{map} example, omitting the type annotations from
  16098. the \code{inc} function.
  16099. \begin{figure}[btp]
  16100. % gradual_test_9.rkt
  16101. \begin{lstlisting}
  16102. (define (map [f : (Integer -> Integer)]
  16103. [v : (Vector Integer Integer)])
  16104. : (Vector Integer Integer)
  16105. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16106. (define (inc x) (+ x 1))
  16107. (vector-ref (map inc (vector 0 41)) 1)
  16108. \end{lstlisting}
  16109. \caption{A partially-typed version of the \code{map} example.}
  16110. \label{fig:gradual-map}
  16111. \end{figure}
  16112. \section{Type Checking \LangGrad{} and \LangCast{}}
  16113. \label{sec:gradual-type-check}
  16114. The type checker for \LangGrad{} uses the \code{Any} type for missing
  16115. parameter and return types. For example, the \code{x} parameter of
  16116. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  16117. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  16118. consider the \code{+} operator inside \code{inc}. It expects both
  16119. arguments to have type \code{Integer}, but its first argument \code{x}
  16120. has type \code{Any}. In a gradually typed language, such differences
  16121. are allowed so long as the types are \emph{consistent}, that is, they
  16122. are equal except in places where there is an \code{Any} type. The type
  16123. \code{Any} is consistent with every other type.
  16124. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  16125. \begin{figure}[tbp]
  16126. \begin{lstlisting}
  16127. (define/public (consistent? t1 t2)
  16128. (match* (t1 t2)
  16129. [('Integer 'Integer) #t]
  16130. [('Boolean 'Boolean) #t]
  16131. [('Void 'Void) #t]
  16132. [('Any t2) #t]
  16133. [(t1 'Any) #t]
  16134. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16135. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  16136. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16137. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  16138. (consistent? rt1 rt2))]
  16139. [(other wise) #f]))
  16140. \end{lstlisting}
  16141. \caption{The consistency predicate on types.}
  16142. \label{fig:consistent}
  16143. \end{figure}
  16144. Returning to the \code{map} example of
  16145. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  16146. \code{(Any -> Any)} but parameter \code{f} of \code{map} has type
  16147. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  16148. because the two types are consistent. In particular, \code{->} is
  16149. equal to \code{->} and because \code{Any} is consistent with
  16150. \code{Integer}.
  16151. Next consider a program with an error, such as applying the
  16152. \code{map} to a function that sometimes returns a Boolean, as
  16153. shown in Figure~\ref{fig:map-maybe-inc}. The type checker for
  16154. \LangGrad{} accepts this program because the type of \code{maybe-inc} is
  16155. consistent with the type of parameter \code{f} of \code{map}, that
  16156. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  16157. Integer)}. One might say that a gradual type checker is optimistic
  16158. in that it accepts programs that might execute without a runtime type
  16159. error.
  16160. %
  16161. Unfortunately, running this program with input \code{1} triggers an
  16162. error when the \code{maybe-inc} function returns \code{\#t}. \LangGrad{}
  16163. performs checking at runtime to ensure the integrity of the static
  16164. types, such as the \code{(Integer -> Integer)} annotation on parameter
  16165. \code{f} of \code{map}. This runtime checking is carried out by a
  16166. new \code{Cast} form that is inserted by the type checker. Thus, the
  16167. output of the type checker is a program in the \LangCast{} language, which
  16168. adds \code{Cast} to \LangLoop{}, as shown in
  16169. Figure~\ref{fig:Rgrad-prime-syntax}.
  16170. \begin{figure}[tp]
  16171. \centering
  16172. \fbox{
  16173. \begin{minipage}{0.96\textwidth}
  16174. \small
  16175. \[
  16176. \begin{array}{lcl}
  16177. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  16178. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16179. \end{array}
  16180. \]
  16181. \end{minipage}
  16182. }
  16183. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  16184. \label{fig:Rgrad-prime-syntax}
  16185. \end{figure}
  16186. \begin{figure}[tbp]
  16187. \begin{lstlisting}
  16188. (define (map [f : (Integer -> Integer)]
  16189. [v : (Vector Integer Integer)])
  16190. : (Vector Integer Integer)
  16191. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16192. (define (inc x) (+ x 1))
  16193. (define (true) #t)
  16194. (define (maybe-inc x) (if (eq? 0 (read)) (inc x) (true)))
  16195. (vector-ref (map maybe-inc (vector 0 41)) 0)
  16196. \end{lstlisting}
  16197. \caption{A variant of the \code{map} example with an error.}
  16198. \label{fig:map-maybe-inc}
  16199. \end{figure}
  16200. Figure~\ref{fig:map-cast} shows the output of the type checker for
  16201. \code{map} and \code{maybe-inc}. The idea is that \code{Cast} is
  16202. inserted every time the type checker sees two types that are
  16203. consistent but not equal. In the \code{inc} function, \code{x} is
  16204. cast to \code{Integer} and the result of the \code{+} is cast to
  16205. \code{Any}. In the call to \code{map}, the \code{inc} argument
  16206. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  16207. \begin{figure}[btp]
  16208. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16209. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  16210. : (Vector Integer Integer)
  16211. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16212. (define (inc [x : Any]) : Any
  16213. (cast (+ (cast x Any Integer) 1) Integer Any))
  16214. (define (true) : Any (cast #t Boolean Any))
  16215. (define (maybe-inc [x : Any]) : Any
  16216. (if (eq? 0 (read)) (inc x) (true)))
  16217. (vector-ref (map (cast maybe-inc (Any -> Any) (Integer -> Integer))
  16218. (vector 0 41)) 0)
  16219. \end{lstlisting}
  16220. \caption{Output of type checking \code{map}
  16221. and \code{maybe-inc}.}
  16222. \label{fig:map-cast}
  16223. \end{figure}
  16224. The type checker for \LangGrad{} is defined in
  16225. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  16226. and \ref{fig:type-check-Rgradual-3}.
  16227. \begin{figure}[tbp]
  16228. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16229. (define type-check-gradual_class
  16230. (class type-check-Rwhile_class
  16231. (super-new)
  16232. (inherit operator-types type-predicates)
  16233. (define/override (type-check-exp env)
  16234. (lambda (e)
  16235. (define recur (type-check-exp env))
  16236. (match e
  16237. [(Prim 'vector-length (list e1))
  16238. (define-values (e1^ t) (recur e1))
  16239. (match t
  16240. [`(Vector ,ts ...)
  16241. (values (Prim 'vector-length (list e1^)) 'Integer)]
  16242. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  16243. [(Prim 'vector-ref (list e1 e2))
  16244. (define-values (e1^ t1) (recur e1))
  16245. (define-values (e2^ t2) (recur e2))
  16246. (check-consistent? t2 'Integer e)
  16247. (match t1
  16248. [`(Vector ,ts ...)
  16249. (match e2^
  16250. [(Int i)
  16251. (unless (and (0 . <= . i) (i . < . (length ts)))
  16252. (error 'type-check "invalid index ~a in ~a" i e))
  16253. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  16254. [else (define e1^^ (make-cast e1^ t1 'Any))
  16255. (define e2^^ (make-cast e2^ t2 'Integer))
  16256. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  16257. ['Any
  16258. (define e2^^ (make-cast e2^ t2 'Integer))
  16259. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  16260. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  16261. [(Prim 'vector-set! (list e1 e2 e3) )
  16262. (define-values (e1^ t1) (recur e1))
  16263. (define-values (e2^ t2) (recur e2))
  16264. (define-values (e3^ t3) (recur e3))
  16265. (check-consistent? t2 'Integer e)
  16266. (match t1
  16267. [`(Vector ,ts ...)
  16268. (match e2^
  16269. [(Int i)
  16270. (unless (and (0 . <= . i) (i . < . (length ts)))
  16271. (error 'type-check "invalid index ~a in ~a" i e))
  16272. (check-consistent? (list-ref ts i) t3 e)
  16273. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  16274. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  16275. [else
  16276. (define e1^^ (make-cast e1^ t1 'Any))
  16277. (define e2^^ (make-cast e2^ t2 'Integer))
  16278. (define e3^^ (make-cast e3^ t3 'Any))
  16279. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  16280. ['Any
  16281. (define e2^^ (make-cast e2^ t2 'Integer))
  16282. (define e3^^ (make-cast e3^ t3 'Any))
  16283. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  16284. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  16285. \end{lstlisting}
  16286. \caption{Type checker for the \LangGrad{} language, part 1.}
  16287. \label{fig:type-check-Rgradual-1}
  16288. \end{figure}
  16289. \begin{figure}[tbp]
  16290. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16291. [(Prim 'eq? (list e1 e2))
  16292. (define-values (e1^ t1) (recur e1))
  16293. (define-values (e2^ t2) (recur e2))
  16294. (check-consistent? t1 t2 e)
  16295. (define T (meet t1 t2))
  16296. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  16297. 'Boolean)]
  16298. [(Prim 'not (list e1))
  16299. (define-values (e1^ t1) (recur e1))
  16300. (match t1
  16301. ['Any
  16302. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  16303. (Bool #t) (Bool #f)))]
  16304. [else
  16305. (define-values (t-ret new-es^)
  16306. (type-check-op 'not (list t1) (list e1^) e))
  16307. (values (Prim 'not new-es^) t-ret)])]
  16308. [(Prim 'and (list e1 e2))
  16309. (recur (If e1 e2 (Bool #f)))]
  16310. [(Prim 'or (list e1 e2))
  16311. (define tmp (gensym 'tmp))
  16312. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  16313. [(Prim op es)
  16314. #:when (not (set-member? explicit-prim-ops op))
  16315. (define-values (new-es ts)
  16316. (for/lists (exprs types) ([e es])
  16317. (recur e)))
  16318. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  16319. (values (Prim op new-es^) t-ret)]
  16320. [(If e1 e2 e3)
  16321. (define-values (e1^ T1) (recur e1))
  16322. (define-values (e2^ T2) (recur e2))
  16323. (define-values (e3^ T3) (recur e3))
  16324. (check-consistent? T2 T3 e)
  16325. (match T1
  16326. ['Boolean
  16327. (define Tif (join T2 T3))
  16328. (values (If e1^ (make-cast e2^ T2 Tif)
  16329. (make-cast e3^ T3 Tif)) Tif)]
  16330. ['Any
  16331. (define Tif (meet T2 T3))
  16332. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  16333. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  16334. Tif)]
  16335. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  16336. [(HasType e1 T)
  16337. (define-values (e1^ T1) (recur e1))
  16338. (check-consistent? T1 T)
  16339. (values (make-cast e1^ T1 T) T)]
  16340. [(SetBang x e1)
  16341. (define-values (e1^ T1) (recur e1))
  16342. (define varT (dict-ref env x))
  16343. (check-consistent? T1 varT e)
  16344. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  16345. [(WhileLoop e1 e2)
  16346. (define-values (e1^ T1) (recur e1))
  16347. (check-consistent? T1 'Boolean e)
  16348. (define-values (e2^ T2) ((type-check-exp env) e2))
  16349. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  16350. \end{lstlisting}
  16351. \caption{Type checker for the \LangGrad{} language, part 2.}
  16352. \label{fig:type-check-Rgradual-2}
  16353. \end{figure}
  16354. \begin{figure}[tbp]
  16355. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16356. [(Apply e1 e2s)
  16357. (define-values (e1^ T1) (recur e1))
  16358. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  16359. (match T1
  16360. [`(,T1ps ... -> ,T1rt)
  16361. (for ([T2 T2s] [Tp T1ps])
  16362. (check-consistent? T2 Tp e))
  16363. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  16364. (make-cast e2 src tgt)))
  16365. (values (Apply e1^ e2s^^) T1rt)]
  16366. [`Any
  16367. (define e1^^ (make-cast e1^ 'Any
  16368. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  16369. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  16370. (make-cast e2 src 'Any)))
  16371. (values (Apply e1^^ e2s^^) 'Any)]
  16372. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  16373. [(Lambda params Tr e1)
  16374. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  16375. (match p
  16376. [`[,x : ,T] (values x T)]
  16377. [(? symbol? x) (values x 'Any)])))
  16378. (define-values (e1^ T1)
  16379. ((type-check-exp (append (map cons xs Ts) env)) e1))
  16380. (check-consistent? Tr T1 e)
  16381. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  16382. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  16383. [else ((super type-check-exp env) e)]
  16384. )))
  16385. \end{lstlisting}
  16386. \caption{Type checker for the \LangGrad{} language, part 3.}
  16387. \label{fig:type-check-Rgradual-3}
  16388. \end{figure}
  16389. \begin{figure}[tbp]
  16390. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  16391. (define/public (join t1 t2)
  16392. (match* (t1 t2)
  16393. [('Integer 'Integer) 'Integer]
  16394. [('Boolean 'Boolean) 'Boolean]
  16395. [('Void 'Void) 'Void]
  16396. [('Any t2) t2]
  16397. [(t1 'Any) t1]
  16398. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16399. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  16400. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16401. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  16402. -> ,(join rt1 rt2))]))
  16403. (define/public (meet t1 t2)
  16404. (match* (t1 t2)
  16405. [('Integer 'Integer) 'Integer]
  16406. [('Boolean 'Boolean) 'Boolean]
  16407. [('Void 'Void) 'Void]
  16408. [('Any t2) 'Any]
  16409. [(t1 'Any) 'Any]
  16410. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16411. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  16412. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16413. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  16414. -> ,(meet rt1 rt2))]))
  16415. (define/public (make-cast e src tgt)
  16416. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  16417. (define/public (check-consistent? t1 t2 e)
  16418. (unless (consistent? t1 t2)
  16419. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  16420. (define/override (type-check-op op arg-types args e)
  16421. (match (dict-ref (operator-types) op)
  16422. [`(,param-types . ,return-type)
  16423. (for ([at arg-types] [pt param-types])
  16424. (check-consistent? at pt e))
  16425. (values return-type
  16426. (for/list ([e args] [s arg-types] [t param-types])
  16427. (make-cast e s t)))]
  16428. [else (error 'type-check-op "unrecognized ~a" op)]))
  16429. (define explicit-prim-ops
  16430. (set-union
  16431. (type-predicates)
  16432. (set 'procedure-arity 'eq?
  16433. 'vector 'vector-length 'vector-ref 'vector-set!
  16434. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  16435. (define/override (fun-def-type d)
  16436. (match d
  16437. [(Def f params rt info body)
  16438. (define ps
  16439. (for/list ([p params])
  16440. (match p
  16441. [`[,x : ,T] T]
  16442. [(? symbol?) 'Any]
  16443. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  16444. `(,@ps -> ,rt)]
  16445. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  16446. \end{lstlisting}
  16447. \caption{Auxiliary functions for type checking \LangGrad{}.}
  16448. \label{fig:type-check-Rgradual-aux}
  16449. \end{figure}
  16450. \clearpage
  16451. \section{Interpreting \LangCast{}}
  16452. \label{sec:interp-casts}
  16453. The runtime behavior of first-order casts is straightforward, that is,
  16454. casts involving simple types such as \code{Integer} and
  16455. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  16456. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  16457. puts the integer into a tagged value
  16458. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  16459. \code{Integer} is accomplished with the \code{Project} operator, that
  16460. is, by checking the value's tag and either retrieving the underlying
  16461. integer or signaling an error if it the tag is not the one for
  16462. integers (Figure~\ref{fig:apply-project}).
  16463. %
  16464. Things get more interesting for higher-order casts, that is, casts
  16465. involving function or vector types.
  16466. Consider the cast of the function \code{maybe-inc} from \code{(Any ->
  16467. Any)} to \code{(Integer -> Integer)}. When a function flows through
  16468. this cast at runtime, we can't know in general whether the function
  16469. will always return an integer.\footnote{Predicting the return value of
  16470. a function is equivalent to the halting problem, which is
  16471. undecidable.} The \LangCast{} interpreter therefore delays the checking
  16472. of the cast until the function is applied. This is accomplished by
  16473. wrapping \code{maybe-inc} in a new function that casts its parameter
  16474. from \code{Integer} to \code{Any}, applies \code{maybe-inc}, and then
  16475. casts the return value from \code{Any} to \code{Integer}.
  16476. Turning our attention to casts involving vector types, we consider the
  16477. example in Figure~\ref{fig:map-bang} that defines a
  16478. partially-typed version of \code{map} whose parameter \code{v} has
  16479. type \code{(Vector Any Any)} and that updates \code{v} in place
  16480. instead of returning a new vector. So we name this function
  16481. \code{map!}. We apply \code{map!} to a vector of integers, so
  16482. the type checker inserts a cast from \code{(Vector Integer Integer)}
  16483. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  16484. cast between vector types would be a build a new vector whose elements
  16485. are the result of casting each of the original elements to the
  16486. appropriate target type. However, this approach is only valid for
  16487. immutable vectors; and our vectors are mutable. In the example of
  16488. Figure~\ref{fig:map-bang}, if the cast created a new vector, then
  16489. the updates inside of \code{map!} would happen to the new vector
  16490. and not the original one.
  16491. \begin{figure}[tbp]
  16492. % gradual_test_11.rkt
  16493. \begin{lstlisting}
  16494. (define (map! [f : (Any -> Any)]
  16495. [v : (Vector Any Any)]) : Void
  16496. (begin
  16497. (vector-set! v 0 (f (vector-ref v 0)))
  16498. (vector-set! v 1 (f (vector-ref v 1)))))
  16499. (define (inc x) (+ x 1))
  16500. (let ([v (vector 0 41)])
  16501. (begin (map! inc v) (vector-ref v 1)))
  16502. \end{lstlisting}
  16503. \caption{An example involving casts on vectors.}
  16504. \label{fig:map-bang}
  16505. \end{figure}
  16506. Instead the interpreter needs to create a new kind of value, a
  16507. \emph{vector proxy}, that intercepts every vector operation. On a
  16508. read, the proxy reads from the underlying vector and then applies a
  16509. cast to the resulting value. On a write, the proxy casts the argument
  16510. value and then performs the write to the underlying vector. For the
  16511. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  16512. \code{0} from \code{Integer} to \code{Any}. For the first
  16513. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  16514. to \code{Integer}.
  16515. The final category of cast that we need to consider are casts between
  16516. the \code{Any} type and either a function or a vector
  16517. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  16518. in which parameter \code{v} does not have a type annotation, so it is
  16519. given type \code{Any}. In the call to \code{map!}, the vector has
  16520. type \code{(Vector Integer Integer)} so the type checker inserts a
  16521. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  16522. thought is to use \code{Inject}, but that doesn't work because
  16523. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  16524. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  16525. to \code{Any}.
  16526. \begin{figure}[tbp]
  16527. \begin{lstlisting}
  16528. (define (map! [f : (Any -> Any)] v) : Void
  16529. (begin
  16530. (vector-set! v 0 (f (vector-ref v 0)))
  16531. (vector-set! v 1 (f (vector-ref v 1)))))
  16532. (define (inc x) (+ x 1))
  16533. (let ([v (vector 0 41)])
  16534. (begin (map! inc v) (vector-ref v 1)))
  16535. \end{lstlisting}
  16536. \caption{Casting a vector to \code{Any}.}
  16537. \label{fig:map-any}
  16538. \end{figure}
  16539. The \LangCast{} interpreter uses an auxiliary function named
  16540. \code{apply-cast} to cast a value from a source type to a target type,
  16541. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  16542. of the kinds of casts that we've discussed in this section.
  16543. \begin{figure}[tbp]
  16544. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16545. (define/public (apply-cast v s t)
  16546. (match* (s t)
  16547. [(t1 t2) #:when (equal? t1 t2) v]
  16548. [('Any t2)
  16549. (match t2
  16550. [`(,ts ... -> ,rt)
  16551. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  16552. (define v^ (apply-project v any->any))
  16553. (apply-cast v^ any->any `(,@ts -> ,rt))]
  16554. [`(Vector ,ts ...)
  16555. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  16556. (define v^ (apply-project v vec-any))
  16557. (apply-cast v^ vec-any `(Vector ,@ts))]
  16558. [else (apply-project v t2)])]
  16559. [(t1 'Any)
  16560. (match t1
  16561. [`(,ts ... -> ,rt)
  16562. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  16563. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  16564. (apply-inject v^ (any-tag any->any))]
  16565. [`(Vector ,ts ...)
  16566. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  16567. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  16568. (apply-inject v^ (any-tag vec-any))]
  16569. [else (apply-inject v (any-tag t1))])]
  16570. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16571. (define x (gensym 'x))
  16572. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  16573. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  16574. (define cast-writes
  16575. (for/list ([t1 ts1] [t2 ts2])
  16576. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  16577. `(vector-proxy ,(vector v (apply vector cast-reads)
  16578. (apply vector cast-writes)))]
  16579. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16580. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  16581. `(function ,xs ,(Cast
  16582. (Apply (Value v)
  16583. (for/list ([x xs][t1 ts1][t2 ts2])
  16584. (Cast (Var x) t2 t1)))
  16585. rt1 rt2) ())]
  16586. ))
  16587. \end{lstlisting}
  16588. \caption{The \code{apply-cast} auxiliary method.}
  16589. \label{fig:apply-cast}
  16590. \end{figure}
  16591. The interpreter for \LangCast{} is defined in
  16592. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  16593. dispatching to \code{apply-cast}. To handle the addition of vector
  16594. proxies, we update the vector primitives in \code{interp-op} using the
  16595. functions in Figure~\ref{fig:guarded-vector}.
  16596. \begin{figure}[tbp]
  16597. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16598. (define interp-Rcast_class
  16599. (class interp-Rwhile_class
  16600. (super-new)
  16601. (inherit apply-fun apply-inject apply-project)
  16602. (define/override (interp-op op)
  16603. (match op
  16604. ['vector-length guarded-vector-length]
  16605. ['vector-ref guarded-vector-ref]
  16606. ['vector-set! guarded-vector-set!]
  16607. ['any-vector-ref (lambda (v i)
  16608. (match v [`(tagged ,v^ ,tg)
  16609. (guarded-vector-ref v^ i)]))]
  16610. ['any-vector-set! (lambda (v i a)
  16611. (match v [`(tagged ,v^ ,tg)
  16612. (guarded-vector-set! v^ i a)]))]
  16613. ['any-vector-length (lambda (v)
  16614. (match v [`(tagged ,v^ ,tg)
  16615. (guarded-vector-length v^)]))]
  16616. [else (super interp-op op)]
  16617. ))
  16618. (define/override ((interp-exp env) e)
  16619. (define (recur e) ((interp-exp env) e))
  16620. (match e
  16621. [(Value v) v]
  16622. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  16623. [else ((super interp-exp env) e)]))
  16624. ))
  16625. (define (interp-Rcast p)
  16626. (send (new interp-Rcast_class) interp-program p))
  16627. \end{lstlisting}
  16628. \caption{The interpreter for \LangCast{}.}
  16629. \label{fig:interp-Rcast}
  16630. \end{figure}
  16631. \begin{figure}[tbp]
  16632. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16633. (define (guarded-vector-ref vec i)
  16634. (match vec
  16635. [`(vector-proxy ,proxy)
  16636. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  16637. (define rd (vector-ref (vector-ref proxy 1) i))
  16638. (apply-fun rd (list val) 'guarded-vector-ref)]
  16639. [else (vector-ref vec i)]))
  16640. (define (guarded-vector-set! vec i arg)
  16641. (match vec
  16642. [`(vector-proxy ,proxy)
  16643. (define wr (vector-ref (vector-ref proxy 2) i))
  16644. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  16645. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  16646. [else (vector-set! vec i arg)]))
  16647. (define (guarded-vector-length vec)
  16648. (match vec
  16649. [`(vector-proxy ,proxy)
  16650. (guarded-vector-length (vector-ref proxy 0))]
  16651. [else (vector-length vec)]))
  16652. \end{lstlisting}
  16653. \caption{The guarded-vector auxiliary functions.}
  16654. \label{fig:guarded-vector}
  16655. \end{figure}
  16656. \section{Lower Casts}
  16657. \label{sec:lower-casts}
  16658. The next step in the journey towards x86 is the \code{lower-casts}
  16659. pass that translates the casts in \LangCast{} to the lower-level
  16660. \code{Inject} and \code{Project} operators and a new operator for
  16661. creating vector proxies, extending the \LangLoop{} language to create
  16662. \LangProxy{}. We recommend creating an auxiliary function named
  16663. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  16664. and a target type, and translates it to expression in \LangProxy{} that has
  16665. the same behavior as casting the expression from the source to the
  16666. target type in the interpreter.
  16667. The \code{lower-cast} function can follow a code structure similar to
  16668. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  16669. the interpreter for \LangCast{} because it must handle the same cases as
  16670. \code{apply-cast} and it needs to mimic the behavior of
  16671. \code{apply-cast}. The most interesting cases are those concerning the
  16672. casts between two vector types and between two function types.
  16673. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  16674. type to another vector type is accomplished by creating a proxy that
  16675. intercepts the operations on the underlying vector. Here we make the
  16676. creation of the proxy explicit with the \code{vector-proxy} primitive
  16677. operation. It takes three arguments, the first is an expression for
  16678. the vector, the second is a vector of functions for casting an element
  16679. that is being read from the vector, and the third is a vector of
  16680. functions for casting an element that is being written to the vector.
  16681. You can create the functions using \code{Lambda}. Also, as we shall
  16682. see in the next section, we need to differentiate these vectors from
  16683. the user-created ones, so we recommend using a new primitive operator
  16684. named \code{raw-vector} instead of \code{vector} to create these
  16685. vectors of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  16686. the output of \code{lower-casts} on the example in
  16687. Figure~\ref{fig:map-bang} that involved casting a vector of
  16688. integers to a vector of \code{Any}.
  16689. \begin{figure}[tbp]
  16690. \begin{lstlisting}
  16691. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  16692. (begin
  16693. (vector-set! v 0 (f (vector-ref v 0)))
  16694. (vector-set! v 1 (f (vector-ref v 1)))))
  16695. (define (inc [x : Any]) : Any
  16696. (inject (+ (project x Integer) 1) Integer))
  16697. (let ([v (vector 0 41)])
  16698. (begin
  16699. (map! inc (vector-proxy v
  16700. (raw-vector (lambda: ([x9 : Integer]) : Any
  16701. (inject x9 Integer))
  16702. (lambda: ([x9 : Integer]) : Any
  16703. (inject x9 Integer)))
  16704. (raw-vector (lambda: ([x9 : Any]) : Integer
  16705. (project x9 Integer))
  16706. (lambda: ([x9 : Any]) : Integer
  16707. (project x9 Integer)))))
  16708. (vector-ref v 1)))
  16709. \end{lstlisting}
  16710. \caption{Output of \code{lower-casts} on the example in
  16711. Figure~\ref{fig:map-bang}.}
  16712. \label{fig:map-bang-lower-cast}
  16713. \end{figure}
  16714. A cast from one function type to another function type is accomplished
  16715. by generating a \code{Lambda} whose parameter and return types match
  16716. the target function type. The body of the \code{Lambda} should cast
  16717. the parameters from the target type to the source type (yes,
  16718. backwards! functions are contravariant\index{subject}{contravariant} in the
  16719. parameters), then call the underlying function, and finally cast the
  16720. result from the source return type to the target return type.
  16721. Figure~\ref{fig:map-lower-cast} shows the output of the
  16722. \code{lower-casts} pass on the \code{map} example in
  16723. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument
  16724. in the call to \code{map} is wrapped in a \code{lambda}.
  16725. \begin{figure}[tbp]
  16726. \begin{lstlisting}
  16727. (define (map [f : (Integer -> Integer)]
  16728. [v : (Vector Integer Integer)])
  16729. : (Vector Integer Integer)
  16730. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16731. (define (inc [x : Any]) : Any
  16732. (inject (+ (project x Integer) 1) Integer))
  16733. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  16734. (project (inc (inject x9 Integer)) Integer))
  16735. (vector 0 41)) 1)
  16736. \end{lstlisting}
  16737. \caption{Output of \code{lower-casts} on the example in
  16738. Figure~\ref{fig:gradual-map}.}
  16739. \label{fig:map-lower-cast}
  16740. \end{figure}
  16741. \section{Differentiate Proxies}
  16742. \label{sec:differentiate-proxies}
  16743. So far the job of differentiating vectors and vector proxies has been
  16744. the job of the interpreter. For example, the interpreter for \LangCast{}
  16745. implements \code{vector-ref} using the \code{guarded-vector-ref}
  16746. function in Figure~\ref{fig:guarded-vector}. In the
  16747. \code{differentiate-proxies} pass we shift this responsibility to the
  16748. generated code.
  16749. We begin by designing the output language $R^p_8$. In
  16750. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  16751. proxies. In $R^p_8$ we return the \code{Vector} type to
  16752. its original meaning, as the type of real vectors, and we introduce a
  16753. new type, \code{PVector}, whose values can be either real vectors or
  16754. vector proxies. This new type comes with a suite of new primitive
  16755. operations for creating and using values of type \code{PVector}. We
  16756. don't need to introduce a new type to represent vector proxies. A
  16757. proxy is represented by a vector containing three things: 1) the
  16758. underlying vector, 2) a vector of functions for casting elements that
  16759. are read from the vector, and 3) a vector of functions for casting
  16760. values to be written to the vector. So we define the following
  16761. abbreviation for the type of a vector proxy:
  16762. \[
  16763. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  16764. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  16765. \to (\key{PVector}~ T' \ldots)
  16766. \]
  16767. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  16768. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  16769. %
  16770. Next we describe each of the new primitive operations.
  16771. \begin{description}
  16772. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  16773. (\key{PVector} $T \ldots$)]\ \\
  16774. %
  16775. This operation brands a vector as a value of the \code{PVector} type.
  16776. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  16777. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  16778. %
  16779. This operation brands a vector proxy as value of the \code{PVector} type.
  16780. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  16781. \code{Boolean}] \ \\
  16782. %
  16783. returns true if the value is a vector proxy and false if it is a
  16784. real vector.
  16785. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  16786. (\key{Vector} $T \ldots$)]\ \\
  16787. %
  16788. Assuming that the input is a vector (and not a proxy), this
  16789. operation returns the vector.
  16790. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  16791. $\to$ \code{Boolean}]\ \\
  16792. %
  16793. Given a vector proxy, this operation returns the length of the
  16794. underlying vector.
  16795. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  16796. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  16797. %
  16798. Given a vector proxy, this operation returns the $i$th element of
  16799. the underlying vector.
  16800. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  16801. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  16802. proxy, this operation writes a value to the $i$th element of the
  16803. underlying vector.
  16804. \end{description}
  16805. Now to discuss the translation that differentiates vectors from
  16806. proxies. First, every type annotation in the program must be
  16807. translated (recursively) to replace \code{Vector} with \code{PVector}.
  16808. Next, we must insert uses of \code{PVector} operations in the
  16809. appropriate places. For example, we wrap every vector creation with an
  16810. \code{inject-vector}.
  16811. \begin{lstlisting}
  16812. (vector |$e_1 \ldots e_n$|)
  16813. |$\Rightarrow$|
  16814. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  16815. \end{lstlisting}
  16816. The \code{raw-vector} operator that we introduced in the previous
  16817. section does not get injected.
  16818. \begin{lstlisting}
  16819. (raw-vector |$e_1 \ldots e_n$|)
  16820. |$\Rightarrow$|
  16821. (vector |$e'_1 \ldots e'_n$|)
  16822. \end{lstlisting}
  16823. The \code{vector-proxy} primitive translates as follows.
  16824. \begin{lstlisting}
  16825. (vector-proxy |$e_1~e_2~e_3$|)
  16826. |$\Rightarrow$|
  16827. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  16828. \end{lstlisting}
  16829. We translate the vector operations into conditional expressions that
  16830. check whether the value is a proxy and then dispatch to either the
  16831. appropriate proxy vector operation or the regular vector operation.
  16832. For example, the following is the translation for \code{vector-ref}.
  16833. \begin{lstlisting}
  16834. (vector-ref |$e_1$| |$i$|)
  16835. |$\Rightarrow$|
  16836. (let ([|$v~e_1$|])
  16837. (if (proxy? |$v$|)
  16838. (proxy-vector-ref |$v$| |$i$|)
  16839. (vector-ref (project-vector |$v$|) |$i$|)
  16840. \end{lstlisting}
  16841. Note in the case of a real vector, we must apply \code{project-vector}
  16842. before the \code{vector-ref}.
  16843. \section{Reveal Casts}
  16844. \label{sec:reveal-casts-gradual}
  16845. Recall that the \code{reveal-casts} pass
  16846. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  16847. \code{Inject} and \code{Project} into lower-level operations. In
  16848. particular, \code{Project} turns into a conditional expression that
  16849. inspects the tag and retrieves the underlying value. Here we need to
  16850. augment the translation of \code{Project} to handle the situation when
  16851. the target type is \code{PVector}. Instead of using
  16852. \code{vector-length} we need to use \code{proxy-vector-length}.
  16853. \begin{lstlisting}
  16854. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  16855. |$\Rightarrow$|
  16856. (let |$\itm{tmp}$| |$e'$|
  16857. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  16858. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  16859. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  16860. (exit)))
  16861. \end{lstlisting}
  16862. \section{Closure Conversion}
  16863. \label{sec:closure-conversion-gradual}
  16864. The closure conversion pass only requires one minor adjustment. The
  16865. auxiliary function that translates type annotations needs to be
  16866. updated to handle the \code{PVector} type.
  16867. \section{Explicate Control}
  16868. \label{sec:explicate-control-gradual}
  16869. Update the \code{explicate\_control} pass to handle the new primitive
  16870. operations on the \code{PVector} type.
  16871. \section{Select Instructions}
  16872. \label{sec:select-instructions-gradual}
  16873. Recall that the \code{select\_instructions} pass is responsible for
  16874. lowering the primitive operations into x86 instructions. So we need
  16875. to translate the new \code{PVector} operations to x86. To do so, the
  16876. first question we need to answer is how will we differentiate the two
  16877. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  16878. We need just one bit to accomplish this, and use the bit in position
  16879. $57$ of the 64-bit tag at the front of every vector (see
  16880. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  16881. for \code{inject-vector} we leave it that way.
  16882. \begin{lstlisting}
  16883. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  16884. |$\Rightarrow$|
  16885. movq |$e'_1$|, |$\itm{lhs'}$|
  16886. \end{lstlisting}
  16887. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  16888. \begin{lstlisting}
  16889. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  16890. |$\Rightarrow$|
  16891. movq |$e'_1$|, %r11
  16892. movq |$(1 << 57)$|, %rax
  16893. orq 0(%r11), %rax
  16894. movq %rax, 0(%r11)
  16895. movq %r11, |$\itm{lhs'}$|
  16896. \end{lstlisting}
  16897. The \code{proxy?} operation consumes the information so carefully
  16898. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  16899. isolates the $57$th bit to tell whether the value is a real vector or
  16900. a proxy.
  16901. \begin{lstlisting}
  16902. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  16903. |$\Rightarrow$|
  16904. movq |$e_1'$|, %r11
  16905. movq 0(%r11), %rax
  16906. sarq $57, %rax
  16907. andq $1, %rax
  16908. movq %rax, |$\itm{lhs'}$|
  16909. \end{lstlisting}
  16910. The \code{project-vector} operation is straightforward to translate,
  16911. so we leave it up to the reader.
  16912. Regarding the \code{proxy-vector} operations, the runtime provides
  16913. procedures that implement them (they are recursive functions!) so
  16914. here we simply need to translate these vector operations into the
  16915. appropriate function call. For example, here is the translation for
  16916. \code{proxy-vector-ref}.
  16917. \begin{lstlisting}
  16918. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  16919. |$\Rightarrow$|
  16920. movq |$e_1'$|, %rdi
  16921. movq |$e_2'$|, %rsi
  16922. callq proxy_vector_ref
  16923. movq %rax, |$\itm{lhs'}$|
  16924. \end{lstlisting}
  16925. We have another batch of vector operations to deal with, those for the
  16926. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  16927. \code{any-vector-ref} when there is a \code{vector-ref} on something
  16928. of type \code{Any}, and similarly for \code{any-vector-set!} and
  16929. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  16930. Section~\ref{sec:select-Rany} we selected instructions for these
  16931. operations based on the idea that the underlying value was a real
  16932. vector. But in the current setting, the underlying value is of type
  16933. \code{PVector}. So \code{any-vector-ref} can be translates to
  16934. pseudo-x86 as follows. We begin by projecting the underlying value out
  16935. of the tagged value and then call the \code{proxy\_vector\_ref}
  16936. procedure in the runtime.
  16937. \begin{lstlisting}
  16938. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16939. movq |$\neg 111$|, %rdi
  16940. andq |$e_1'$|, %rdi
  16941. movq |$e_2'$|, %rsi
  16942. callq proxy_vector_ref
  16943. movq %rax, |$\itm{lhs'}$|
  16944. \end{lstlisting}
  16945. The \code{any-vector-set!} and \code{any-vector-length} operators can
  16946. be translated in a similar way.
  16947. \begin{exercise}\normalfont
  16948. Implement a compiler for the gradually-typed \LangGrad{} language by
  16949. extending and adapting your compiler for \LangLoop{}. Create 10 new
  16950. partially-typed test programs. In addition to testing with these
  16951. new programs, also test your compiler on all the tests for \LangLoop{}
  16952. and tests for \LangDyn{}. Sometimes you may get a type checking error
  16953. on the \LangDyn{} programs but you can adapt them by inserting
  16954. a cast to the \code{Any} type around each subexpression
  16955. causing a type error. While \LangDyn{} does not have explicit casts,
  16956. you can induce one by wrapping the subexpression \code{e}
  16957. with a call to an un-annotated identity function, like this:
  16958. \code{((lambda (x) x) e)}.
  16959. \end{exercise}
  16960. \begin{figure}[p]
  16961. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16962. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  16963. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  16964. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  16965. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  16966. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  16967. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  16968. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  16969. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  16970. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  16971. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  16972. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  16973. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  16974. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  16975. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  16976. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16977. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16978. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16979. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16980. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16981. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16982. \path[->,bend right=15] (Rgradual) edge [above] node
  16983. {\ttfamily\footnotesize type\_check} (Rgradualp);
  16984. \path[->,bend right=15] (Rgradualp) edge [above] node
  16985. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  16986. \path[->,bend right=15] (Rwhilepp) edge [right] node
  16987. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  16988. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  16989. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  16990. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  16991. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  16992. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  16993. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  16994. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  16995. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  16996. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  16997. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16998. \path[->,bend left=15] (F1-1) edge [below] node
  16999. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17000. \path[->,bend right=15] (F1-2) edge [above] node
  17001. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17002. \path[->,bend right=15] (F1-3) edge [above] node
  17003. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17004. \path[->,bend right=15] (F1-4) edge [above] node
  17005. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  17006. \path[->,bend right=15] (F1-5) edge [right] node
  17007. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17008. \path[->,bend left=15] (C3-2) edge [left] node
  17009. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17010. \path[->,bend right=15] (x86-2) edge [left] node
  17011. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17012. \path[->,bend right=15] (x86-2-1) edge [below] node
  17013. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17014. \path[->,bend right=15] (x86-2-2) edge [left] node
  17015. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17016. \path[->,bend left=15] (x86-3) edge [above] node
  17017. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17018. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  17019. \end{tikzpicture}
  17020. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  17021. \label{fig:Rgradual-passes}
  17022. \end{figure}
  17023. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  17024. for the compilation of \LangGrad{}.
  17025. \section{Further Reading}
  17026. This chapter just scratches the surface of gradual typing. The basic
  17027. approach described here is missing two key ingredients that one would
  17028. want in a implementation of gradual typing: blame
  17029. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  17030. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  17031. problem addressed by blame tracking is that when a cast on a
  17032. higher-order value fails, it often does so at a point in the program
  17033. that is far removed from the original cast. Blame tracking is a
  17034. technique for propagating extra information through casts and proxies
  17035. so that when a cast fails, the error message can point back to the
  17036. original location of the cast in the source program.
  17037. The problem addressed by space-efficient casts also relates to
  17038. higher-order casts. It turns out that in partially typed programs, a
  17039. function or vector can flow through very-many casts at runtime. With
  17040. the approach described in this chapter, each cast adds another
  17041. \code{lambda} wrapper or a vector proxy. Not only does this take up
  17042. considerable space, but it also makes the function calls and vector
  17043. operations slow. For example, a partially-typed version of quicksort
  17044. could, in the worst case, build a chain of proxies of length $O(n)$
  17045. around the vector, changing the overall time complexity of the
  17046. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  17047. solution to this problem by representing casts using the coercion
  17048. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  17049. long chains of proxies by compressing them into a concise normal
  17050. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  17051. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  17052. the Grift compiler.
  17053. \begin{center}
  17054. \url{https://github.com/Gradual-Typing/Grift}
  17055. \end{center}
  17056. There are also interesting interactions between gradual typing and
  17057. other language features, such as parametetric polymorphism,
  17058. information-flow types, and type inference, to name a few. We
  17059. recommend the reader to the online gradual typing bibliography:
  17060. \begin{center}
  17061. \url{http://samth.github.io/gradual-typing-bib/}
  17062. \end{center}
  17063. % TODO: challenge problem:
  17064. % type analysis and type specialization?
  17065. % coercions?
  17066. \fi
  17067. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17068. \chapter{Parametric Polymorphism}
  17069. \label{ch:Lpoly}
  17070. \index{subject}{parametric polymorphism}
  17071. \index{subject}{generics}
  17072. \if\edition\racketEd
  17073. This chapter studies the compilation of parametric
  17074. polymorphism\index{subject}{parametric polymorphism}
  17075. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  17076. Racket. Parametric polymorphism enables improved code reuse by
  17077. parameterizing functions and data structures with respect to the types
  17078. that they operate on. For example, Figure~\ref{fig:map-poly}
  17079. revisits the \code{map} example but this time gives it a more
  17080. fitting type. This \code{map} function is parameterized with
  17081. respect to the element type of the vector. The type of \code{map}
  17082. is the following polymorphic type as specified by the \code{All} and
  17083. the type parameter \code{a}.
  17084. \begin{lstlisting}
  17085. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17086. \end{lstlisting}
  17087. The idea is that \code{map} can be used at \emph{all} choices of a
  17088. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  17089. \code{map} to a vector of integers, a choice of \code{Integer} for
  17090. \code{a}, but we could have just as well applied \code{map} to a
  17091. vector of Booleans (and a function on Booleans).
  17092. \begin{figure}[tbp]
  17093. % poly_test_2.rkt
  17094. \begin{lstlisting}
  17095. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  17096. (define (map f v)
  17097. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17098. (define (inc [x : Integer]) : Integer (+ x 1))
  17099. (vector-ref (map inc (vector 0 41)) 1)
  17100. \end{lstlisting}
  17101. \caption{The \code{map} example using parametric polymorphism.}
  17102. \label{fig:map-poly}
  17103. \end{figure}
  17104. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  17105. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  17106. syntax. We add a second form for function definitions in which a type
  17107. declaration comes before the \code{define}. In the abstract syntax,
  17108. the return type in the \code{Def} is \code{Any}, but that should be
  17109. ignored in favor of the return type in the type declaration. (The
  17110. \code{Any} comes from using the same parser as in
  17111. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  17112. enables the use of an \code{All} type for a function, thereby making
  17113. it polymorphic. The grammar for types is extended to include
  17114. polymorphic types and type variables.
  17115. \begin{figure}[tp]
  17116. \centering
  17117. \fbox{
  17118. \begin{minipage}{0.96\textwidth}
  17119. \small
  17120. \[
  17121. \begin{array}{lcl}
  17122. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17123. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  17124. &\MID& \LP\key{:}~\Var~\Type\RP \\
  17125. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  17126. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  17127. \end{array}
  17128. \]
  17129. \end{minipage}
  17130. }
  17131. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  17132. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  17133. \label{fig:Rpoly-concrete-syntax}
  17134. \end{figure}
  17135. \begin{figure}[tp]
  17136. \centering
  17137. \fbox{
  17138. \begin{minipage}{0.96\textwidth}
  17139. \small
  17140. \[
  17141. \begin{array}{lcl}
  17142. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17143. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  17144. &\MID& \DECL{\Var}{\Type} \\
  17145. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  17146. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17147. \end{array}
  17148. \]
  17149. \end{minipage}
  17150. }
  17151. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  17152. (Figure~\ref{fig:Lwhile-syntax}).}
  17153. \label{fig:Rpoly-syntax}
  17154. \end{figure}
  17155. By including polymorphic types in the $\Type$ non-terminal we choose
  17156. to make them first-class which has interesting repercussions on the
  17157. compiler. Many languages with polymorphism, such as
  17158. C++~\citep{stroustrup88:_param_types} and Standard
  17159. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  17160. it is useful to see an example of first-class polymorphism. In
  17161. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  17162. whose parameter is a polymorphic function. The occurrence of a
  17163. polymorphic type underneath a function type is enabled by the normal
  17164. recursive structure of the grammar for $\Type$ and the categorization
  17165. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  17166. applies the polymorphic function to a Boolean and to an integer.
  17167. \begin{figure}[tbp]
  17168. \begin{lstlisting}
  17169. (: apply-twice ((All (b) (b -> b)) -> Integer))
  17170. (define (apply-twice f)
  17171. (if (f #t) (f 42) (f 777)))
  17172. (: id (All (a) (a -> a)))
  17173. (define (id x) x)
  17174. (apply-twice id)
  17175. \end{lstlisting}
  17176. \caption{An example illustrating first-class polymorphism.}
  17177. \label{fig:apply-twice}
  17178. \end{figure}
  17179. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  17180. three new responsibilities (compared to \LangLoop{}). The type checking of
  17181. function application is extended to handle the case where the operator
  17182. expression is a polymorphic function. In that case the type arguments
  17183. are deduced by matching the type of the parameters with the types of
  17184. the arguments.
  17185. %
  17186. The \code{match-types} auxiliary function carries out this deduction
  17187. by recursively descending through a parameter type \code{pt} and the
  17188. corresponding argument type \code{at}, making sure that they are equal
  17189. except when there is a type parameter on the left (in the parameter
  17190. type). If it's the first time that the type parameter has been
  17191. encountered, then the algorithm deduces an association of the type
  17192. parameter to the corresponding type on the right (in the argument
  17193. type). If it's not the first time that the type parameter has been
  17194. encountered, the algorithm looks up its deduced type and makes sure
  17195. that it is equal to the type on the right.
  17196. %
  17197. Once the type arguments are deduced, the operator expression is
  17198. wrapped in an \code{Inst} AST node (for instantiate) that records the
  17199. type of the operator, but more importantly, records the deduced type
  17200. arguments. The return type of the application is the return type of
  17201. the polymorphic function, but with the type parameters replaced by the
  17202. deduced type arguments, using the \code{subst-type} function.
  17203. The second responsibility of the type checker is extending the
  17204. function \code{type-equal?} to handle the \code{All} type. This is
  17205. not quite a simple as equal on other types, such as function and
  17206. vector types, because two polymorphic types can be syntactically
  17207. different even though they are equivalent types. For example,
  17208. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  17209. Two polymorphic types should be considered equal if they differ only
  17210. in the choice of the names of the type parameters. The
  17211. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  17212. renames the type parameters of the first type to match the type
  17213. parameters of the second type.
  17214. The third responsibility of the type checker is making sure that only
  17215. defined type variables appear in type annotations. The
  17216. \code{check-well-formed} function defined in
  17217. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  17218. sure that each type variable has been defined.
  17219. The output language of the type checker is \LangInst{}, defined in
  17220. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  17221. declaration and polymorphic function into a single definition, using
  17222. the \code{Poly} form, to make polymorphic functions more convenient to
  17223. process in next pass of the compiler.
  17224. \begin{figure}[tp]
  17225. \centering
  17226. \fbox{
  17227. \begin{minipage}{0.96\textwidth}
  17228. \small
  17229. \[
  17230. \begin{array}{lcl}
  17231. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17232. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  17233. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  17234. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  17235. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17236. \end{array}
  17237. \]
  17238. \end{minipage}
  17239. }
  17240. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  17241. (Figure~\ref{fig:Lwhile-syntax}).}
  17242. \label{fig:Rpoly-prime-syntax}
  17243. \end{figure}
  17244. The output of the type checker on the polymorphic \code{map}
  17245. example is listed in Figure~\ref{fig:map-type-check}.
  17246. \begin{figure}[tbp]
  17247. % poly_test_2.rkt
  17248. \begin{lstlisting}
  17249. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  17250. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  17251. (define (inc [x : Integer]) : Integer (+ x 1))
  17252. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17253. (Integer))
  17254. inc (vector 0 41)) 1)
  17255. \end{lstlisting}
  17256. \caption{Output of the type checker on the \code{map} example.}
  17257. \label{fig:map-type-check}
  17258. \end{figure}
  17259. \begin{figure}[tbp]
  17260. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17261. (define type-check-poly-class
  17262. (class type-check-Rwhile-class
  17263. (super-new)
  17264. (inherit check-type-equal?)
  17265. (define/override (type-check-apply env e1 es)
  17266. (define-values (e^ ty) ((type-check-exp env) e1))
  17267. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  17268. ((type-check-exp env) e)))
  17269. (match ty
  17270. [`(,ty^* ... -> ,rt)
  17271. (for ([arg-ty ty*] [param-ty ty^*])
  17272. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  17273. (values e^ es^ rt)]
  17274. [`(All ,xs (,tys ... -> ,rt))
  17275. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  17276. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  17277. (match-types env^^ param-ty arg-ty)))
  17278. (define targs
  17279. (for/list ([x xs])
  17280. (match (dict-ref env^^ x (lambda () #f))
  17281. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  17282. x (Apply e1 es))]
  17283. [ty ty])))
  17284. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  17285. [else (error 'type-check "expected a function, not ~a" ty)]))
  17286. (define/override ((type-check-exp env) e)
  17287. (match e
  17288. [(Lambda `([,xs : ,Ts] ...) rT body)
  17289. (for ([T Ts]) ((check-well-formed env) T))
  17290. ((check-well-formed env) rT)
  17291. ((super type-check-exp env) e)]
  17292. [(HasType e1 ty)
  17293. ((check-well-formed env) ty)
  17294. ((super type-check-exp env) e)]
  17295. [else ((super type-check-exp env) e)]))
  17296. (define/override ((type-check-def env) d)
  17297. (verbose 'type-check "poly/def" d)
  17298. (match d
  17299. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  17300. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  17301. (for ([p ps]) ((check-well-formed ts-env) p))
  17302. ((check-well-formed ts-env) rt)
  17303. (define new-env (append ts-env (map cons xs ps) env))
  17304. (define-values (body^ ty^) ((type-check-exp new-env) body))
  17305. (check-type-equal? ty^ rt body)
  17306. (Generic ts (Def f p:t* rt info body^))]
  17307. [else ((super type-check-def env) d)]))
  17308. (define/override (type-check-program p)
  17309. (match p
  17310. [(Program info body)
  17311. (type-check-program (ProgramDefsExp info '() body))]
  17312. [(ProgramDefsExp info ds body)
  17313. (define ds^ (combine-decls-defs ds))
  17314. (define new-env (for/list ([d ds^])
  17315. (cons (def-name d) (fun-def-type d))))
  17316. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  17317. (define-values (body^ ty) ((type-check-exp new-env) body))
  17318. (check-type-equal? ty 'Integer body)
  17319. (ProgramDefsExp info ds^^ body^)]))
  17320. ))
  17321. \end{lstlisting}
  17322. \caption{Type checker for the \LangPoly{} language.}
  17323. \label{fig:type-check-Lvar0}
  17324. \end{figure}
  17325. \begin{figure}[tbp]
  17326. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17327. (define/override (type-equal? t1 t2)
  17328. (match* (t1 t2)
  17329. [(`(All ,xs ,T1) `(All ,ys ,T2))
  17330. (define env (map cons xs ys))
  17331. (type-equal? (subst-type env T1) T2)]
  17332. [(other wise)
  17333. (super type-equal? t1 t2)]))
  17334. (define/public (match-types env pt at)
  17335. (match* (pt at)
  17336. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  17337. [('Void 'Void) env] [('Any 'Any) env]
  17338. [(`(Vector ,pts ...) `(Vector ,ats ...))
  17339. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  17340. (match-types env^ pt1 at1))]
  17341. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  17342. (define env^ (match-types env prt art))
  17343. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  17344. (match-types env^^ pt1 at1))]
  17345. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  17346. (define env^ (append (map cons pxs axs) env))
  17347. (match-types env^ pt1 at1)]
  17348. [((? symbol? x) at)
  17349. (match (dict-ref env x (lambda () #f))
  17350. [#f (error 'type-check "undefined type variable ~a" x)]
  17351. ['Type (cons (cons x at) env)]
  17352. [t^ (check-type-equal? at t^ 'matching) env])]
  17353. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  17354. (define/public (subst-type env pt)
  17355. (match pt
  17356. ['Integer 'Integer] ['Boolean 'Boolean]
  17357. ['Void 'Void] ['Any 'Any]
  17358. [`(Vector ,ts ...)
  17359. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  17360. [`(,ts ... -> ,rt)
  17361. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  17362. [`(All ,xs ,t)
  17363. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  17364. [(? symbol? x) (dict-ref env x)]
  17365. [else (error 'type-check "expected a type not ~a" pt)]))
  17366. (define/public (combine-decls-defs ds)
  17367. (match ds
  17368. ['() '()]
  17369. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  17370. (unless (equal? name f)
  17371. (error 'type-check "name mismatch, ~a != ~a" name f))
  17372. (match type
  17373. [`(All ,xs (,ps ... -> ,rt))
  17374. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  17375. (cons (Generic xs (Def name params^ rt info body))
  17376. (combine-decls-defs ds^))]
  17377. [`(,ps ... -> ,rt)
  17378. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  17379. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  17380. [else (error 'type-check "expected a function type, not ~a" type) ])]
  17381. [`(,(Def f params rt info body) . ,ds^)
  17382. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  17383. \end{lstlisting}
  17384. \caption{Auxiliary functions for type checking \LangPoly{}.}
  17385. \label{fig:type-check-Lvar0-aux}
  17386. \end{figure}
  17387. \begin{figure}[tbp]
  17388. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  17389. (define/public ((check-well-formed env) ty)
  17390. (match ty
  17391. ['Integer (void)]
  17392. ['Boolean (void)]
  17393. ['Void (void)]
  17394. [(? symbol? a)
  17395. (match (dict-ref env a (lambda () #f))
  17396. ['Type (void)]
  17397. [else (error 'type-check "undefined type variable ~a" a)])]
  17398. [`(Vector ,ts ...)
  17399. (for ([t ts]) ((check-well-formed env) t))]
  17400. [`(,ts ... -> ,t)
  17401. (for ([t ts]) ((check-well-formed env) t))
  17402. ((check-well-formed env) t)]
  17403. [`(All ,xs ,t)
  17404. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  17405. ((check-well-formed env^) t)]
  17406. [else (error 'type-check "unrecognized type ~a" ty)]))
  17407. \end{lstlisting}
  17408. \caption{Well-formed types.}
  17409. \label{fig:well-formed-types}
  17410. \end{figure}
  17411. % TODO: interpreter for R'_10
  17412. \section{Compiling Polymorphism}
  17413. \label{sec:compiling-poly}
  17414. Broadly speaking, there are four approaches to compiling parametric
  17415. polymorphism, which we describe below.
  17416. \begin{description}
  17417. \item[Monomorphization] generates a different version of a polymorphic
  17418. function for each set of type arguments that it is used with,
  17419. producing type-specialized code. This approach results in the most
  17420. efficient code but requires whole-program compilation (no separate
  17421. compilation) and increases code size. For our current purposes
  17422. monomorphization is a non-starter because, with first-class
  17423. polymorphism, it is sometimes not possible to determine which
  17424. generic functions are used with which type arguments during
  17425. compilation. (It can be done at runtime, with just-in-time
  17426. compilation.) This approach is used to compile C++
  17427. templates~\citep{stroustrup88:_param_types} and polymorphic
  17428. functions in NESL~\citep{Blelloch:1993aa} and
  17429. ML~\citep{Weeks:2006aa}.
  17430. \item[Uniform representation] generates one version of each
  17431. polymorphic function but requires all values have a common ``boxed''
  17432. format, such as the tagged values of type \code{Any} in
  17433. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  17434. similarly to code in a dynamically typed language (like \LangDyn{}),
  17435. in which primitive operators require their arguments to be projected
  17436. from \code{Any} and their results are injected into \code{Any}. (In
  17437. object-oriented languages, the projection is accomplished via
  17438. virtual method dispatch.) The uniform representation approach is
  17439. compatible with separate compilation and with first-class
  17440. polymorphism. However, it produces the least-efficient code because
  17441. it introduces overhead in the entire program, including
  17442. non-polymorphic code. This approach is used in implementations of
  17443. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  17444. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  17445. Java~\citep{Bracha:1998fk}.
  17446. \item[Mixed representation] generates one version of each polymorphic
  17447. function, using a boxed representation for type
  17448. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  17449. and conversions are performed at the boundaries between monomorphic
  17450. and polymorphic (e.g. when a polymorphic function is instantiated
  17451. and called). This approach is compatible with separate compilation
  17452. and first-class polymorphism and maintains the efficiency of
  17453. monomorphic code. The tradeoff is increased overhead at the boundary
  17454. between monomorphic and polymorphic code. This approach is used in
  17455. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  17456. Java 5 with the addition of autoboxing.
  17457. \item[Type passing] uses the unboxed representation in both
  17458. monomorphic and polymorphic code. Each polymorphic function is
  17459. compiled to a single function with extra parameters that describe
  17460. the type arguments. The type information is used by the generated
  17461. code to know how to access the unboxed values at runtime. This
  17462. approach is used in implementation of the Napier88
  17463. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  17464. passing is compatible with separate compilation and first-class
  17465. polymorphism and maintains the efficiency for monomorphic
  17466. code. There is runtime overhead in polymorphic code from dispatching
  17467. on type information.
  17468. \end{description}
  17469. In this chapter we use the mixed representation approach, partly
  17470. because of its favorable attributes, and partly because it is
  17471. straightforward to implement using the tools that we have already
  17472. built to support gradual typing. To compile polymorphic functions, we
  17473. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  17474. \LangCast{}.
  17475. \section{Erase Types}
  17476. \label{sec:erase-types}
  17477. We use the \code{Any} type from Chapter~\ref{ch:Ldyn} to
  17478. represent type variables. For example, Figure~\ref{fig:map-erase}
  17479. shows the output of the \code{erase-types} pass on the polymorphic
  17480. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  17481. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  17482. \code{All} types are removed from the type of \code{map}.
  17483. \begin{figure}[tbp]
  17484. \begin{lstlisting}
  17485. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  17486. : (Vector Any Any)
  17487. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17488. (define (inc [x : Integer]) : Integer (+ x 1))
  17489. (vector-ref ((cast map
  17490. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  17491. ((Integer -> Integer) (Vector Integer Integer)
  17492. -> (Vector Integer Integer)))
  17493. inc (vector 0 41)) 1)
  17494. \end{lstlisting}
  17495. \caption{The polymorphic \code{map} example after type erasure.}
  17496. \label{fig:map-erase}
  17497. \end{figure}
  17498. This process of type erasure creates a challenge at points of
  17499. instantiation. For example, consider the instantiation of
  17500. \code{map} in Figure~\ref{fig:map-type-check}.
  17501. The type of \code{map} is
  17502. \begin{lstlisting}
  17503. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17504. \end{lstlisting}
  17505. and it is instantiated to
  17506. \begin{lstlisting}
  17507. ((Integer -> Integer) (Vector Integer Integer)
  17508. -> (Vector Integer Integer))
  17509. \end{lstlisting}
  17510. After erasure, the type of \code{map} is
  17511. \begin{lstlisting}
  17512. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  17513. \end{lstlisting}
  17514. but we need to convert it to the instantiated type. This is easy to
  17515. do in the target language \LangCast{} with a single \code{cast}. In
  17516. Figure~\ref{fig:map-erase}, the instantiation of \code{map}
  17517. has been compiled to a \code{cast} from the type of \code{map} to
  17518. the instantiated type. The source and target type of a cast must be
  17519. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  17520. because both the source and target are obtained from the same
  17521. polymorphic type of \code{map}, replacing the type parameters with
  17522. \code{Any} in the former and with the deduced type arguments in the
  17523. later. (Recall that the \code{Any} type is consistent with any type.)
  17524. To implement the \code{erase-types} pass, we recommend defining a
  17525. recursive auxiliary function named \code{erase-type} that applies the
  17526. following two transformations. It replaces type variables with
  17527. \code{Any}
  17528. \begin{lstlisting}
  17529. |$x$|
  17530. |$\Rightarrow$|
  17531. Any
  17532. \end{lstlisting}
  17533. and it removes the polymorphic \code{All} types.
  17534. \begin{lstlisting}
  17535. (All |$xs$| |$T_1$|)
  17536. |$\Rightarrow$|
  17537. |$T'_1$|
  17538. \end{lstlisting}
  17539. Apply the \code{erase-type} function to all of the type annotations in
  17540. the program.
  17541. Regarding the translation of expressions, the case for \code{Inst} is
  17542. the interesting one. We translate it into a \code{Cast}, as shown
  17543. below. The type of the subexpression $e$ is the polymorphic type
  17544. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  17545. $T$, the type $T'$. The target type $T''$ is the result of
  17546. substituting the arguments types $ts$ for the type parameters $xs$ in
  17547. $T$ followed by doing type erasure.
  17548. \begin{lstlisting}
  17549. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  17550. |$\Rightarrow$|
  17551. (Cast |$e'$| |$T'$| |$T''$|)
  17552. \end{lstlisting}
  17553. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  17554. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  17555. Finally, each polymorphic function is translated to a regular
  17556. functions in which type erasure has been applied to all the type
  17557. annotations and the body.
  17558. \begin{lstlisting}
  17559. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  17560. |$\Rightarrow$|
  17561. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  17562. \end{lstlisting}
  17563. \begin{exercise}\normalfont
  17564. Implement a compiler for the polymorphic language \LangPoly{} by
  17565. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  17566. programs that use polymorphic functions. Some of them should make
  17567. use of first-class polymorphism.
  17568. \end{exercise}
  17569. \begin{figure}[p]
  17570. \begin{tikzpicture}[baseline=(current bounding box.center)]
  17571. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  17572. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  17573. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  17574. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  17575. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  17576. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  17577. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  17578. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  17579. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  17580. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  17581. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  17582. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  17583. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  17584. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  17585. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  17586. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17587. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17588. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17589. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17590. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17591. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17592. \path[->,bend right=15] (Rpoly) edge [above] node
  17593. {\ttfamily\footnotesize type\_check} (Rpolyp);
  17594. \path[->,bend right=15] (Rpolyp) edge [above] node
  17595. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  17596. \path[->,bend right=15] (Rgradualp) edge [above] node
  17597. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  17598. \path[->,bend right=15] (Rwhilepp) edge [right] node
  17599. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  17600. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  17601. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  17602. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  17603. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  17604. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  17605. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  17606. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  17607. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  17608. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  17609. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  17610. \path[->,bend left=15] (F1-1) edge [below] node
  17611. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17612. \path[->,bend right=15] (F1-2) edge [above] node
  17613. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17614. \path[->,bend right=15] (F1-3) edge [above] node
  17615. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17616. \path[->,bend right=15] (F1-4) edge [above] node
  17617. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  17618. \path[->,bend right=15] (F1-5) edge [right] node
  17619. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17620. \path[->,bend left=15] (C3-2) edge [left] node
  17621. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17622. \path[->,bend right=15] (x86-2) edge [left] node
  17623. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17624. \path[->,bend right=15] (x86-2-1) edge [below] node
  17625. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17626. \path[->,bend right=15] (x86-2-2) edge [left] node
  17627. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17628. \path[->,bend left=15] (x86-3) edge [above] node
  17629. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17630. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  17631. \end{tikzpicture}
  17632. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  17633. \label{fig:Rpoly-passes}
  17634. \end{figure}
  17635. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  17636. for the compilation of \LangPoly{}.
  17637. % TODO: challenge problem: specialization of instantiations
  17638. % Further Reading
  17639. \fi
  17640. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17641. \clearpage
  17642. \appendix
  17643. \chapter{Appendix}
  17644. \if\edition\racketEd
  17645. \section{Interpreters}
  17646. \label{appendix:interp}
  17647. \index{subject}{interpreter}
  17648. We provide interpreters for each of the source languages \LangInt{},
  17649. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  17650. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  17651. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  17652. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  17653. and x86 are in the \key{interp.rkt} file.
  17654. \section{Utility Functions}
  17655. \label{appendix:utilities}
  17656. The utility functions described in this section are in the
  17657. \key{utilities.rkt} file of the support code.
  17658. \paragraph{\code{interp-tests}}
  17659. The \key{interp-tests} function runs the compiler passes and the
  17660. interpreters on each of the specified tests to check whether each pass
  17661. is correct. The \key{interp-tests} function has the following
  17662. parameters:
  17663. \begin{description}
  17664. \item[name (a string)] a name to identify the compiler,
  17665. \item[typechecker] a function of exactly one argument that either
  17666. raises an error using the \code{error} function when it encounters a
  17667. type error, or returns \code{\#f} when it encounters a type
  17668. error. If there is no type error, the type checker returns the
  17669. program.
  17670. \item[passes] a list with one entry per pass. An entry is a list with
  17671. four things:
  17672. \begin{enumerate}
  17673. \item a string giving the name of the pass,
  17674. \item the function that implements the pass (a translator from AST
  17675. to AST),
  17676. \item a function that implements the interpreter (a function from
  17677. AST to result value) for the output language,
  17678. \item and a type checker for the output language. Type checkers for
  17679. the $R$ and $C$ languages are provided in the support code. For
  17680. example, the type checkers for \LangVar{} and \LangCVar{} are in
  17681. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  17682. type checker entry is optional. The support code does not provide
  17683. type checkers for the x86 languages.
  17684. \end{enumerate}
  17685. \item[source-interp] an interpreter for the source language. The
  17686. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  17687. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  17688. \item[tests] a list of test numbers that specifies which tests to
  17689. run. (see below)
  17690. \end{description}
  17691. %
  17692. The \key{interp-tests} function assumes that the subdirectory
  17693. \key{tests} has a collection of Racket programs whose names all start
  17694. with the family name, followed by an underscore and then the test
  17695. number, ending with the file extension \key{.rkt}. Also, for each test
  17696. program that calls \code{read} one or more times, there is a file with
  17697. the same name except that the file extension is \key{.in} that
  17698. provides the input for the Racket program. If the test program is
  17699. expected to fail type checking, then there should be an empty file of
  17700. the same name but with extension \key{.tyerr}.
  17701. \paragraph{\code{compiler-tests}}
  17702. runs the compiler passes to generate x86 (a \key{.s} file) and then
  17703. runs the GNU C compiler (gcc) to generate machine code. It runs the
  17704. machine code and checks that the output is $42$. The parameters to the
  17705. \code{compiler-tests} function are similar to those of the
  17706. \code{interp-tests} function, and consist of
  17707. \begin{itemize}
  17708. \item a compiler name (a string),
  17709. \item a type checker,
  17710. \item description of the passes,
  17711. \item name of a test-family, and
  17712. \item a list of test numbers.
  17713. \end{itemize}
  17714. \paragraph{\code{compile-file}}
  17715. takes a description of the compiler passes (see the comment for
  17716. \key{interp-tests}) and returns a function that, given a program file
  17717. name (a string ending in \key{.rkt}), applies all of the passes and
  17718. writes the output to a file whose name is the same as the program file
  17719. name but with \key{.rkt} replaced with \key{.s}.
  17720. \paragraph{\code{read-program}}
  17721. takes a file path and parses that file (it must be a Racket program)
  17722. into an abstract syntax tree.
  17723. \paragraph{\code{parse-program}}
  17724. takes an S-expression representation of an abstract syntax tree and converts it into
  17725. the struct-based representation.
  17726. \paragraph{\code{assert}}
  17727. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  17728. and displays the message \key{msg} if the Boolean \key{bool} is false.
  17729. \paragraph{\code{lookup}}
  17730. % remove discussion of lookup? -Jeremy
  17731. takes a key and an alist, and returns the first value that is
  17732. associated with the given key, if there is one. If not, an error is
  17733. triggered. The alist may contain both immutable pairs (built with
  17734. \key{cons}) and mutable pairs (built with \key{mcons}).
  17735. %The \key{map2} function ...
  17736. \fi %\racketEd
  17737. \section{x86 Instruction Set Quick-Reference}
  17738. \label{sec:x86-quick-reference}
  17739. \index{subject}{x86}
  17740. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  17741. do. We write $A \to B$ to mean that the value of $A$ is written into
  17742. location $B$. Address offsets are given in bytes. The instruction
  17743. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  17744. registers (such as \code{\%rax}), or memory references (such as
  17745. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  17746. reference per instruction. Other operands must be immediates or
  17747. registers.
  17748. \begin{table}[tbp]
  17749. \centering
  17750. \begin{tabular}{l|l}
  17751. \textbf{Instruction} & \textbf{Operation} \\ \hline
  17752. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  17753. \texttt{negq} $A$ & $- A \to A$ \\
  17754. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  17755. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  17756. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  17757. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  17758. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  17759. \texttt{retq} & Pops the return address and jumps to it \\
  17760. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  17761. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  17762. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  17763. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  17764. be an immediate) \\
  17765. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  17766. matches the condition code of the instruction, otherwise go to the
  17767. next instructions. The condition codes are \key{e} for ``equal'',
  17768. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  17769. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  17770. \texttt{jl} $L$ & \\
  17771. \texttt{jle} $L$ & \\
  17772. \texttt{jg} $L$ & \\
  17773. \texttt{jge} $L$ & \\
  17774. \texttt{jmp} $L$ & Jump to label $L$ \\
  17775. \texttt{movq} $A$, $B$ & $A \to B$ \\
  17776. \texttt{movzbq} $A$, $B$ &
  17777. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  17778. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  17779. and the extra bytes of $B$ are set to zero.} \\
  17780. & \\
  17781. & \\
  17782. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  17783. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  17784. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  17785. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  17786. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  17787. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  17788. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  17789. description of the condition codes. $A$ must be a single byte register
  17790. (e.g., \texttt{al} or \texttt{cl}).} \\
  17791. \texttt{setl} $A$ & \\
  17792. \texttt{setle} $A$ & \\
  17793. \texttt{setg} $A$ & \\
  17794. \texttt{setge} $A$ &
  17795. \end{tabular}
  17796. \vspace{5pt}
  17797. \caption{Quick-reference for the x86 instructions used in this book.}
  17798. \label{tab:x86-instr}
  17799. \end{table}
  17800. \if\edition\racketEd
  17801. \cleardoublepage
  17802. \section{Concrete Syntax for Intermediate Languages}
  17803. The concrete syntax of \LangAny{} is defined in
  17804. Figure~\ref{fig:Rany-concrete-syntax}.
  17805. \begin{figure}[tp]
  17806. \centering
  17807. \fbox{
  17808. \begin{minipage}{0.97\textwidth}\small
  17809. \[
  17810. \begin{array}{lcl}
  17811. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  17812. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  17813. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  17814. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17815. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  17816. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  17817. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  17818. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  17819. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  17820. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  17821. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  17822. \MID \LP\key{void?}\;\Exp\RP \\
  17823. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  17824. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  17825. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  17826. \end{array}
  17827. \]
  17828. \end{minipage}
  17829. }
  17830. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  17831. (Figure~\ref{fig:Rlam-syntax}).}
  17832. \label{fig:Rany-concrete-syntax}
  17833. \end{figure}
  17834. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  17835. defined in Figures~\ref{fig:c0-concrete-syntax},
  17836. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  17837. and \ref{fig:c3-concrete-syntax}, respectively.
  17838. \begin{figure}[tbp]
  17839. \fbox{
  17840. \begin{minipage}{0.96\textwidth}
  17841. \small
  17842. \[
  17843. \begin{array}{lcl}
  17844. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  17845. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  17846. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  17847. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  17848. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  17849. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  17850. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  17851. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  17852. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  17853. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  17854. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  17855. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  17856. \end{array}
  17857. \]
  17858. \end{minipage}
  17859. }
  17860. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  17861. \label{fig:c2-concrete-syntax}
  17862. \end{figure}
  17863. \begin{figure}[tp]
  17864. \fbox{
  17865. \begin{minipage}{0.96\textwidth}
  17866. \small
  17867. \[
  17868. \begin{array}{lcl}
  17869. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  17870. \\
  17871. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  17872. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  17873. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  17874. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  17875. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  17876. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  17877. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  17878. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  17879. \MID \LP\key{collect} \,\itm{int}\RP }\\
  17880. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  17881. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  17882. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  17883. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  17884. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  17885. \LangCFunM{} & ::= & \Def\ldots
  17886. \end{array}
  17887. \]
  17888. \end{minipage}
  17889. }
  17890. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  17891. \label{fig:c3-concrete-syntax}
  17892. \end{figure}
  17893. \fi % racketEd
  17894. \backmatter
  17895. \addtocontents{toc}{\vspace{11pt}}
  17896. %% \addtocontents{toc}{\vspace{11pt}}
  17897. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  17898. \nocite{*}\let\bibname\refname
  17899. \addcontentsline{toc}{fmbm}{\refname}
  17900. \printbibliography
  17901. \printindex{authors}{Author Index}
  17902. \printindex{subject}{Subject Index}
  17903. \end{document}
  17904. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  17905. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  17906. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  17907. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  17908. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  17909. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  17910. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  17911. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  17912. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  17913. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  17914. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  17915. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  17916. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  17917. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  17918. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  17919. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  17920. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  17921. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  17922. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  17923. % LocalWords: morekeywords fullflexible