book.tex 720 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864
  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. \usepackage[all]{xy}
  18. \definecolor{lightgray}{gray}{1}
  19. \newcommand{\black}[1]{{\color{black} #1}}
  20. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  21. \newcommand{\gray}[1]{{\color{gray} #1}}
  22. \def\racketEd{0}
  23. \def\pythonEd{1}
  24. \def\edition{1}
  25. % material that is specific to the Racket edition of the book
  26. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  27. % would like a command for: \if\edition\racketEd\color{olive}
  28. % and : \fi\color{black}
  29. % material that is specific to the Python edition of the book
  30. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  31. %% For multiple indices:
  32. \usepackage{multind}
  33. \makeindex{subject}
  34. %\makeindex{authors}
  35. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  36. \if\edition\racketEd
  37. \lstset{%
  38. language=Lisp,
  39. basicstyle=\ttfamily\small,
  40. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  41. deletekeywords={read,mapping,vector},
  42. escapechar=|,
  43. columns=flexible,
  44. moredelim=[is][\color{red}]{~}{~},
  45. showstringspaces=false
  46. }
  47. \fi
  48. \if\edition\pythonEd
  49. \lstset{%
  50. language=Python,
  51. basicstyle=\ttfamily\small,
  52. morekeywords={match,case,bool,int,let},
  53. deletekeywords={},
  54. escapechar=|,
  55. columns=flexible,
  56. moredelim=[is][\color{red}]{~}{~},
  57. showstringspaces=false
  58. }
  59. \fi
  60. %%% Any shortcut own defined macros place here
  61. %% sample of author macro:
  62. \input{defs}
  63. \newtheorem{exercise}[theorem]{Exercise}
  64. % Adjusted settings
  65. \setlength{\columnsep}{4pt}
  66. %% \begingroup
  67. %% \setlength{\intextsep}{0pt}%
  68. %% \setlength{\columnsep}{0pt}%
  69. %% \begin{wrapfigure}{r}{0.5\textwidth}
  70. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  71. %% \caption{Basic layout}
  72. %% \end{wrapfigure}
  73. %% \lipsum[1]
  74. %% \endgroup
  75. \newbox\oiintbox
  76. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  77. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  78. \def\oiint{\copy\oiintbox}
  79. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  80. %\usepackage{showframe}
  81. \def\ShowFrameLinethickness{0.125pt}
  82. \addbibresource{book.bib}
  83. \begin{document}
  84. \frontmatter
  85. \HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  86. \halftitlepage
  87. \Title{Essentials of Compilation}
  88. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  89. %\edition{First Edition}
  90. \BookAuthor{Jeremy G. Siek}
  91. \imprint{The MIT Press\\
  92. Cambridge, Massachusetts\\
  93. London, England}
  94. \begin{copyrightpage}
  95. \textcopyright\ 2022 Jeremy G. Siek. Available for free viewing
  96. or personal downloading under the
  97. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  98. license.
  99. Copyright in this monograph has been licensed exclusively to The MIT
  100. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  101. version to the public in 2022. All inquiries regarding rights should
  102. be addressed to The MIT Press, Rights and Permissions Department.
  103. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  104. %% All rights reserved. No part of this book may be reproduced in any
  105. %% form by any electronic or mechanical means (including photocopying,
  106. %% recording, or information storage and retrieval) without permission in
  107. %% writing from the publisher.
  108. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  109. %% United States of America.
  110. %% Library of Congress Cataloging-in-Publication Data is available.
  111. %% ISBN:
  112. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  113. \end{copyrightpage}
  114. \dedication{This book is dedicated to the programming language wonks
  115. at Indiana University.}
  116. %% \begin{epigraphpage}
  117. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  118. %% \textit{Book Name if any}}
  119. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  120. %% \end{epigraphpage}
  121. \tableofcontents
  122. %\listoffigures
  123. %\listoftables
  124. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  125. \chapter*{Preface}
  126. \addcontentsline{toc}{fmbm}{Preface}
  127. There is a magical moment when a programmer presses the ``run'' button
  128. and the software begins to execute. Somehow a program written in a
  129. high-level language is running on a computer that is only capable of
  130. shuffling bits. Here we reveal the wizardry that makes that moment
  131. possible. Beginning with the groundbreaking work of Backus and
  132. colleagues in the 1950s, computer scientists discovered techniques for
  133. constructing programs, called \emph{compilers}, that automatically
  134. translate high-level programs into machine code.
  135. We take you on a journey of constructing your own compiler for a small
  136. but powerful language. Along the way we explain the essential
  137. concepts, algorithms, and data structures that underlie compilers. We
  138. develop your understanding of how programs are mapped onto computer
  139. hardware, which is helpful when reasoning about properties at the
  140. junction between hardware and software such as execution time,
  141. software errors, and security vulnerabilities. For those interested
  142. in pursuing compiler construction as a career, our goal is to provide a
  143. stepping-stone to advanced topics such as just-in-time compilation,
  144. program analysis, and program optimization. For those interested in
  145. designing and implementing programming languages, we connect
  146. language design choices to their impact on the compiler and the generated
  147. code.
  148. A compiler is typically organized as a sequence of stages that
  149. progressively translate a program to the code that runs on
  150. hardware. We take this approach to the extreme by partitioning our
  151. compiler into a large number of \emph{nanopasses}, each of which
  152. performs a single task. This enables the testing of each pass in
  153. isolation and focuses our attention, making the compiler far easier to
  154. understand.
  155. The most familiar approach to describing compilers is with each
  156. chapter dedicated to one pass. The problem with that approach is it
  157. obfuscates how language features motivate design choices in a
  158. compiler. We instead take an \emph{incremental} approach in which we
  159. build a complete compiler in each chapter, starting with a small input
  160. language that includes only arithmetic and variables. We add new
  161. language features in subsequent chapters, extending the compiler as
  162. necessary.
  163. Our choice of language features is designed to elicit fundamental
  164. concepts and algorithms used in compilers.
  165. \begin{itemize}
  166. \item We begin with integer arithmetic and local variables in
  167. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  168. the fundamental tools of compiler construction: \emph{abstract
  169. syntax trees} and \emph{recursive functions}.
  170. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  171. \emph{graph coloring} to assign variables to machine registers.
  172. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  173. motivates an elegant recursive algorithm for translating them into
  174. conditional \code{goto}'s.
  175. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  176. variables}. This elicits the need for \emph{dataflow
  177. analysis} in the register allocator.
  178. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  179. \emph{garbage collection}.
  180. \item Chapter~\ref{ch:Lfun} adds functions as first-class values but
  181. without lexical scoping, similar to functions in the C programming
  182. language~\citep{Kernighan:1988nx}. The reader learns about the
  183. procedure call stack and \emph{calling conventions} and how they interact
  184. with register allocation and garbage collection. The chapter also
  185. describes how to generate efficient tail calls.
  186. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  187. scoping, i.e., \emph{lambda} expressions. The reader learns about
  188. \emph{closure conversion}, in which lambdas are translated into a
  189. combination of functions and tuples.
  190. % Chapter about classes and objects?
  191. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  192. point the input languages are statically typed. The reader extends
  193. the statically typed language with an \code{Any} type which serves
  194. as a target for compiling the dynamically typed language.
  195. {\if\edition\pythonEd
  196. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  197. \emph{classes}.
  198. \fi}
  199. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type of
  200. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  201. in which different regions of a program may be static or dynamically
  202. typed. The reader implements runtime support for \emph{proxies} that
  203. allow values to safely move between regions.
  204. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  205. leveraging the \code{Any} type and type casts developed in Chapters
  206. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  207. \end{itemize}
  208. There are many language features that we do not include. Our choices
  209. balance the incidental complexity of a feature versus the fundamental
  210. concepts that it exposes. For example, we include tuples and not
  211. records because they both elicit the study of heap allocation and
  212. garbage collection but records come with more incidental complexity.
  213. Since 2009 drafts of this book have served as the textbook for 16-week
  214. compiler courses for upper-level undergraduates and first-year
  215. graduate students at the University of Colorado and Indiana
  216. University.
  217. %
  218. Students come into the course having learned the basics of
  219. programming, data structures and algorithms, and discrete
  220. mathematics.
  221. %
  222. At the beginning of the course, students form groups of 2-4 people.
  223. The groups complete one chapter every two weeks, starting with
  224. Chapter~\ref{ch:Lvar} and finishing with
  225. Chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  226. that we assign to the graduate students. The last two weeks of the
  227. course involve a final project in which students design and implement
  228. a compiler extension of their choosing. The later chapters can be
  229. used in support of these projects. For compiler courses at
  230. universities on the quarter system (about 10 weeks in length), we
  231. recommend completing up through Chapter~\ref{ch:Lvec} or
  232. Chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  233. students for each compiler pass.
  234. %
  235. The course can be adapted to emphasize functional languages by
  236. skipping Chapter~\ref{ch:Lwhile} (loops) and including
  237. Chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  238. dynamically typed languages by including Chapter~\ref{ch:Ldyn}.
  239. %
  240. \python{A course that emphasizes object-oriented languages would
  241. include Chapter~\ref{ch:Lobject}.}
  242. %
  243. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  244. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  245. Chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  246. tail calls.
  247. This book has been used in compiler courses at California Polytechnic
  248. State University, Portland State University, Rose–Hulman Institute of
  249. Technology, University of Freiburg, University of Massachusetts
  250. Lowell, and the University of Vermont.
  251. \begin{figure}[tp]
  252. \begin{tcolorbox}[colback=white]
  253. {\if\edition\racketEd
  254. \begin{tikzpicture}[baseline=(current bounding box.center)]
  255. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  256. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  257. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  258. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  259. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  260. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  261. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  262. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  263. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  264. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  265. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  266. \path[->] (C1) edge [above] node {} (C2);
  267. \path[->] (C2) edge [above] node {} (C3);
  268. \path[->] (C3) edge [above] node {} (C4);
  269. \path[->] (C4) edge [above] node {} (C5);
  270. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  271. \path[->] (C5) edge [above] node {} (C7);
  272. \path[->] (C6) edge [above] node {} (C7);
  273. \path[->] (C4) edge [above] node {} (C8);
  274. \path[->] (C4) edge [above] node {} (C9);
  275. \path[->] (C7) edge [above] node {} (C10);
  276. \path[->] (C8) edge [above] node {} (C10);
  277. \path[->] (C10) edge [above] node {} (C11);
  278. \end{tikzpicture}
  279. \fi}
  280. {\if\edition\pythonEd
  281. \begin{tikzpicture}[baseline=(current bounding box.center)]
  282. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  283. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  284. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  285. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  286. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  287. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  288. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  289. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  290. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  291. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  292. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  293. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  294. \path[->] (C1) edge [above] node {} (C2);
  295. \path[->] (C2) edge [above] node {} (C3);
  296. \path[->] (C3) edge [above] node {} (C4);
  297. \path[->] (C4) edge [above] node {} (C5);
  298. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  299. \path[->] (C5) edge [above] node {} (C7);
  300. \path[->] (C6) edge [above] node {} (C7);
  301. \path[->] (C4) edge [above] node {} (C8);
  302. \path[->] (C4) edge [above] node {} (C9);
  303. \path[->] (C7) edge [above] node {} (C10);
  304. \path[->] (C8) edge [above] node {} (C10);
  305. \path[->] (C8) edge [above] node {} (CO);
  306. \path[->] (C10) edge [above] node {} (C11);
  307. \end{tikzpicture}
  308. \fi}
  309. \end{tcolorbox}
  310. \caption{Diagram of chapter dependencies.}
  311. \label{fig:chapter-dependences}
  312. \end{figure}
  313. \racket{
  314. We use the \href{https://racket-lang.org/}{Racket} language both for
  315. the implementation of the compiler and for the input language, so the
  316. reader should be proficient with Racket or Scheme. There are many
  317. excellent resources for learning Scheme and
  318. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  319. }
  320. \python{
  321. This edition of the book uses \href{https://www.python.org/}{Python}
  322. both for the implementation of the compiler and for the input language, so the
  323. reader should be proficient with Python. There are many
  324. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  325. }
  326. The support code for this book is in the github repository at
  327. the following location:
  328. \if\edition\racketEd
  329. \begin{center}\small
  330. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  331. \end{center}
  332. \fi
  333. \if\edition\pythonEd
  334. \begin{center}\small
  335. \url{https://github.com/IUCompilerCourse/}
  336. \end{center}
  337. \fi
  338. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  339. is helpful but not necessary for the reader to have taken a computer
  340. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  341. assembly language that are needed in the compiler.
  342. %
  343. We follow the System V calling
  344. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  345. that we generate works with the runtime system (written in C) when it
  346. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  347. operating systems on Intel hardware.
  348. %
  349. On the Windows operating system, \code{gcc} uses the Microsoft x64
  350. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  351. assembly code that we generate does \emph{not} work with the runtime
  352. system on Windows. One workaround is to use a virtual machine with
  353. Linux as the guest operating system.
  354. \section*{Acknowledgments}
  355. The tradition of compiler construction at Indiana University goes back
  356. to research and courses on programming languages by Daniel Friedman in
  357. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  358. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  359. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  360. the compiler course and continued the development of Chez Scheme.
  361. %
  362. The compiler course evolved to incorporate novel pedagogical ideas
  363. while also including elements of real-world compilers. One of
  364. Friedman's ideas was to split the compiler into many small
  365. passes. Another idea, called ``the game'', was to test the code
  366. generated by each pass using interpreters.
  367. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  368. developed infrastructure to support this approach and evolved the
  369. course to use even smaller
  370. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  371. design decisions in this book are inspired by the assignment
  372. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  373. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  374. organization of the course made it difficult for students to
  375. understand the rationale for the compiler design. Ghuloum proposed the
  376. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  377. on.
  378. We thank the many students who served as teaching assistants for the
  379. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  380. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  381. garbage collector and x86 interpreter, Michael Vollmer for work on
  382. efficient tail calls, and Michael Vitousek for help with the first
  383. offering of the incremental compiler course at IU.
  384. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  385. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  386. Michael Wollowski for teaching courses based on drafts of this book
  387. and for their feedback.
  388. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  389. course in the early 2000's and especially for finding the bug that
  390. sent our garbage collector on a wild goose chase!
  391. \mbox{}\\
  392. \noindent Jeremy G. Siek \\
  393. Bloomington, Indiana
  394. \mainmatter
  395. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  396. \chapter{Preliminaries}
  397. \label{ch:trees-recur}
  398. In this chapter we review the basic tools that are needed to implement
  399. a compiler. Programs are typically input by a programmer as text,
  400. i.e., a sequence of characters. The program-as-text representation is
  401. called \emph{concrete syntax}. We use concrete syntax to concisely
  402. write down and talk about programs. Inside the compiler, we use
  403. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  404. that efficiently supports the operations that the compiler needs to
  405. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  406. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  407. from concrete syntax to abstract syntax is a process called
  408. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  409. implementation of parsing in this book.
  410. %
  411. \racket{A parser is provided in the support code for translating from
  412. concrete to abstract syntax.}
  413. %
  414. \python{We use Python's \code{ast} module to translate from concrete
  415. to abstract syntax.}
  416. ASTs can be represented in many different ways inside the compiler,
  417. depending on the programming language used to write the compiler.
  418. %
  419. \racket{We use Racket's
  420. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  421. feature to represent ASTs (Section~\ref{sec:ast}).}
  422. %
  423. \python{We use Python classes and objects to represent ASTs, especially the
  424. classes defined in the standard \code{ast} module for the Python
  425. source language.}
  426. %
  427. We use grammars to define the abstract syntax of programming languages
  428. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  429. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  430. recursive functions to construct and deconstruct ASTs
  431. (Section~\ref{sec:recursion}). This chapter provides an brief
  432. introduction to these ideas.
  433. \racket{\index{subject}{struct}}
  434. \python{\index{subject}{class}\index{subject}{object}}
  435. \section{Abstract Syntax Trees}
  436. \label{sec:ast}
  437. Compilers use abstract syntax trees to represent programs because they
  438. often need to ask questions like: for a given part of a program, what
  439. kind of language feature is it? What are its sub-parts? Consider the
  440. program on the left and its AST on the right. This program is an
  441. addition operation and it has two sub-parts, a
  442. \racket{read}\python{input} operation and a negation. The negation has
  443. another sub-part, the integer constant \code{8}. By using a tree to
  444. represent the program, we can easily follow the links to go from one
  445. part of a program to its sub-parts.
  446. \begin{center}
  447. \begin{minipage}{0.4\textwidth}
  448. \if\edition\racketEd
  449. \begin{lstlisting}
  450. (+ (read) (- 8))
  451. \end{lstlisting}
  452. \fi
  453. \if\edition\pythonEd
  454. \begin{lstlisting}
  455. input_int() + -8
  456. \end{lstlisting}
  457. \fi
  458. \end{minipage}
  459. \begin{minipage}{0.4\textwidth}
  460. \begin{equation}
  461. \begin{tikzpicture}
  462. \node[draw] (plus) at (0 , 0) {\key{+}};
  463. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  464. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  465. \node[draw] (8) at (1 , -3) {\key{8}};
  466. \draw[->] (plus) to (read);
  467. \draw[->] (plus) to (minus);
  468. \draw[->] (minus) to (8);
  469. \end{tikzpicture}
  470. \label{eq:arith-prog}
  471. \end{equation}
  472. \end{minipage}
  473. \end{center}
  474. We use the standard terminology for trees to describe ASTs: each
  475. rectangle above is called a \emph{node}. The arrows connect a node to its
  476. \emph{children} (which are also nodes). The top-most node is the
  477. \emph{root}. Every node except for the root has a \emph{parent} (the
  478. node it is the child of). If a node has no children, it is a
  479. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  480. \index{subject}{node}
  481. \index{subject}{children}
  482. \index{subject}{root}
  483. \index{subject}{parent}
  484. \index{subject}{leaf}
  485. \index{subject}{internal node}
  486. %% Recall that an \emph{symbolic expression} (S-expression) is either
  487. %% \begin{enumerate}
  488. %% \item an atom, or
  489. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  490. %% where $e_1$ and $e_2$ are each an S-expression.
  491. %% \end{enumerate}
  492. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  493. %% null value \code{'()}, etc. We can create an S-expression in Racket
  494. %% simply by writing a backquote (called a quasi-quote in Racket)
  495. %% followed by the textual representation of the S-expression. It is
  496. %% quite common to use S-expressions to represent a list, such as $a, b
  497. %% ,c$ in the following way:
  498. %% \begin{lstlisting}
  499. %% `(a . (b . (c . ())))
  500. %% \end{lstlisting}
  501. %% Each element of the list is in the first slot of a pair, and the
  502. %% second slot is either the rest of the list or the null value, to mark
  503. %% the end of the list. Such lists are so common that Racket provides
  504. %% special notation for them that removes the need for the periods
  505. %% and so many parenthesis:
  506. %% \begin{lstlisting}
  507. %% `(a b c)
  508. %% \end{lstlisting}
  509. %% The following expression creates an S-expression that represents AST
  510. %% \eqref{eq:arith-prog}.
  511. %% \begin{lstlisting}
  512. %% `(+ (read) (- 8))
  513. %% \end{lstlisting}
  514. %% When using S-expressions to represent ASTs, the convention is to
  515. %% represent each AST node as a list and to put the operation symbol at
  516. %% the front of the list. The rest of the list contains the children. So
  517. %% in the above case, the root AST node has operation \code{`+} and its
  518. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  519. %% diagram \eqref{eq:arith-prog}.
  520. %% To build larger S-expressions one often needs to splice together
  521. %% several smaller S-expressions. Racket provides the comma operator to
  522. %% splice an S-expression into a larger one. For example, instead of
  523. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  524. %% we could have first created an S-expression for AST
  525. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  526. %% S-expression.
  527. %% \begin{lstlisting}
  528. %% (define ast1.4 `(- 8))
  529. %% (define ast1_1 `(+ (read) ,ast1.4))
  530. %% \end{lstlisting}
  531. %% In general, the Racket expression that follows the comma (splice)
  532. %% can be any expression that produces an S-expression.
  533. {\if\edition\racketEd
  534. We define a Racket \code{struct} for each kind of node. For this
  535. chapter we require just two kinds of nodes: one for integer constants
  536. and one for primitive operations. The following is the \code{struct}
  537. definition for integer constants.\footnote{All of the AST structures are
  538. defined in the file \code{utilities.rkt} in the support code.}
  539. \begin{lstlisting}
  540. (struct Int (value))
  541. \end{lstlisting}
  542. An integer node includes just one thing: the integer value.
  543. To create an AST node for the integer $8$, we write \INT{8}.
  544. \begin{lstlisting}
  545. (define eight (Int 8))
  546. \end{lstlisting}
  547. We say that the value created by \INT{8} is an
  548. \emph{instance} of the
  549. \code{Int} structure.
  550. The following is the \code{struct} definition for primitive operations.
  551. \begin{lstlisting}
  552. (struct Prim (op args))
  553. \end{lstlisting}
  554. A primitive operation node includes an operator symbol \code{op} and a
  555. list of child \code{args}. For example, to create an AST that negates
  556. the number $8$, we write the following.
  557. \begin{lstlisting}
  558. (define neg-eight (Prim '- (list eight)))
  559. \end{lstlisting}
  560. Primitive operations may have zero or more children. The \code{read}
  561. operator has zero:
  562. \begin{lstlisting}
  563. (define rd (Prim 'read '()))
  564. \end{lstlisting}
  565. The addition operator has two children:
  566. \begin{lstlisting}
  567. (define ast1_1 (Prim '+ (list rd neg-eight)))
  568. \end{lstlisting}
  569. We have made a design choice regarding the \code{Prim} structure.
  570. Instead of using one structure for many different operations
  571. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  572. structure for each operation, as follows.
  573. \begin{lstlisting}
  574. (struct Read ())
  575. (struct Add (left right))
  576. (struct Neg (value))
  577. \end{lstlisting}
  578. The reason we choose to use just one structure is that in many parts
  579. of the compiler the code for the different primitive operators is the
  580. same, so we might as well just write that code once, which is enabled
  581. by using a single structure.
  582. \fi}
  583. {\if\edition\pythonEd
  584. We use a Python \code{class} for each kind of node.
  585. The following is the class definition for constants.
  586. \begin{lstlisting}
  587. class Constant:
  588. def __init__(self, value):
  589. self.value = value
  590. \end{lstlisting}
  591. An integer constant node includes just one thing: the integer value.
  592. To create an AST node for the integer $8$, we write \INT{8}.
  593. \begin{lstlisting}
  594. eight = Constant(8)
  595. \end{lstlisting}
  596. We say that the value created by \INT{8} is an
  597. \emph{instance} of the \code{Constant} class.
  598. The following is the class definition for unary operators.
  599. \begin{lstlisting}
  600. class UnaryOp:
  601. def __init__(self, op, operand):
  602. self.op = op
  603. self.operand = operand
  604. \end{lstlisting}
  605. The specific operation is specified by the \code{op} parameter. For
  606. example, the class \code{USub} is for unary subtraction. (More unary
  607. operators are introduced in later chapters.) To create an AST that
  608. negates the number $8$, we write the following.
  609. \begin{lstlisting}
  610. neg_eight = UnaryOp(USub(), eight)
  611. \end{lstlisting}
  612. The call to the \code{input\_int} function is represented by the
  613. \code{Call} and \code{Name} classes.
  614. \begin{lstlisting}
  615. class Call:
  616. def __init__(self, func, args):
  617. self.func = func
  618. self.args = args
  619. class Name:
  620. def __init__(self, id):
  621. self.id = id
  622. \end{lstlisting}
  623. To create an AST node that calls \code{input\_int}, we write
  624. \begin{lstlisting}
  625. read = Call(Name('input_int'), [])
  626. \end{lstlisting}
  627. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  628. the \code{BinOp} class for binary operators.
  629. \begin{lstlisting}
  630. class BinOp:
  631. def __init__(self, left, op, right):
  632. self.op = op
  633. self.left = left
  634. self.right = right
  635. \end{lstlisting}
  636. Similar to \code{UnaryOp}, the specific operation is specified by the
  637. \code{op} parameter, which for now is just an instance of the
  638. \code{Add} class. So to create the AST node that adds negative eight
  639. to some user input, we write the following.
  640. \begin{lstlisting}
  641. ast1_1 = BinOp(read, Add(), neg_eight)
  642. \end{lstlisting}
  643. \fi}
  644. When compiling a program such as \eqref{eq:arith-prog}, we need to
  645. know that the operation associated with the root node is addition and
  646. we need to be able to access its two children. \racket{Racket}\python{Python}
  647. provides pattern matching to support these kinds of queries, as we see in
  648. Section~\ref{sec:pattern-matching}.
  649. We often write down the concrete syntax of a program even when we
  650. really have in mind the AST because the concrete syntax is more
  651. concise. We recommend that, in your mind, you always think of
  652. programs as abstract syntax trees.
  653. \section{Grammars}
  654. \label{sec:grammar}
  655. \index{subject}{integer}
  656. \index{subject}{literal}
  657. \index{subject}{constant}
  658. A programming language can be thought of as a \emph{set} of programs.
  659. The set is typically infinite (one can always create larger and larger
  660. programs) so one cannot simply describe a language by listing all of
  661. the programs in the language. Instead we write down a set of rules, a
  662. \emph{grammar}, for building programs. Grammars are often used to
  663. define the concrete syntax of a language but they can also be used to
  664. describe the abstract syntax. We write our rules in a variant of
  665. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  666. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  667. As an example, we describe a small language, named \LangInt{}, that consists of
  668. integers and arithmetic operations.
  669. \index{subject}{grammar}
  670. The first grammar rule for the abstract syntax of \LangInt{} says that an
  671. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  672. \begin{equation}
  673. \Exp ::= \INT{\Int} \label{eq:arith-int}
  674. \end{equation}
  675. %
  676. Each rule has a left-hand-side and a right-hand-side.
  677. If you have an AST node that matches the
  678. right-hand-side, then you can categorize it according to the
  679. left-hand-side.
  680. %
  681. Symbols in typewriter font are \emph{terminal} symbols and must
  682. literally appear in the program for the rule to be applicable.
  683. \index{subject}{terminal}
  684. %
  685. Our grammars do not mention \emph{white-space}, that is, separating characters
  686. like spaces, tabulators, and newlines. White-space may be inserted
  687. between symbols for disambiguation and to improve readability.
  688. \index{subject}{white-space}
  689. %
  690. A name such as $\Exp$ that is defined by the grammar rules is a
  691. \emph{non-terminal}. \index{subject}{non-terminal}
  692. %
  693. The name $\Int$ is also a non-terminal, but instead of defining it
  694. with a grammar rule, we define it with the following explanation. An
  695. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  696. $-$ (for negative integers), such that the sequence of decimals
  697. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  698. the representation of integers using 63 bits, which simplifies several
  699. aspects of compilation. \racket{Thus, these integers correspond to
  700. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  701. \python{In contrast, integers in Python have unlimited precision, but
  702. the techniques needed to handle unlimited precision fall outside the
  703. scope of this book.}
  704. The second grammar rule is the \READOP{} operation that receives an
  705. input integer from the user of the program.
  706. \begin{equation}
  707. \Exp ::= \READ{} \label{eq:arith-read}
  708. \end{equation}
  709. The third rule categorizes the negation of an $\Exp$ node as an
  710. $\Exp$.
  711. \begin{equation}
  712. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  713. \end{equation}
  714. We can apply these rules to categorize the ASTs that are in the
  715. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  716. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  717. following AST is an $\Exp$.
  718. \begin{center}
  719. \begin{minipage}{0.5\textwidth}
  720. \NEG{\INT{\code{8}}}
  721. \end{minipage}
  722. \begin{minipage}{0.25\textwidth}
  723. \begin{equation}
  724. \begin{tikzpicture}
  725. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  726. \node[draw, circle] (8) at (0, -1.2) {$8$};
  727. \draw[->] (minus) to (8);
  728. \end{tikzpicture}
  729. \label{eq:arith-neg8}
  730. \end{equation}
  731. \end{minipage}
  732. \end{center}
  733. The next grammar rules are for addition and subtraction expressions:
  734. \begin{align}
  735. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  736. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  737. \end{align}
  738. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  739. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  740. \eqref{eq:arith-read} and we have already categorized
  741. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  742. to show that
  743. \[
  744. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  745. \]
  746. is an $\Exp$ in the \LangInt{} language.
  747. If you have an AST for which the above rules do not apply, then the
  748. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  749. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  750. because there is no rule for the \key{*} operator. Whenever we
  751. define a language with a grammar, the language only includes those
  752. programs that are justified by the grammar rules.
  753. {\if\edition\pythonEd
  754. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  755. There is a statement for printing the value of an expression
  756. \[
  757. \Stmt{} ::= \PRINT{\Exp}
  758. \]
  759. and a statement that evaluates an expression but ignores the result.
  760. \[
  761. \Stmt{} ::= \EXPR{\Exp}
  762. \]
  763. \fi}
  764. {\if\edition\racketEd
  765. The last grammar rule for \LangInt{} states that there is a
  766. \code{Program} node to mark the top of the whole program:
  767. \[
  768. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  769. \]
  770. The \code{Program} structure is defined as follows
  771. \begin{lstlisting}
  772. (struct Program (info body))
  773. \end{lstlisting}
  774. where \code{body} is an expression. In later chapters, the \code{info}
  775. part will be used to store auxiliary information but for now it is
  776. just the empty list.
  777. \fi}
  778. {\if\edition\pythonEd
  779. The last grammar rule for \LangInt{} states that there is a
  780. \code{Module} node to mark the top of the whole program:
  781. \[
  782. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  783. \]
  784. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  785. this case, a list of statements.
  786. %
  787. The \code{Module} class is defined as follows
  788. \begin{lstlisting}
  789. class Module:
  790. def __init__(self, body):
  791. self.body = body
  792. \end{lstlisting}
  793. where \code{body} is a list of statements.
  794. \fi}
  795. It is common to have many grammar rules with the same left-hand side
  796. but different right-hand sides, such as the rules for $\Exp$ in the
  797. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  798. combine several right-hand-sides into a single rule.
  799. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  800. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  801. defined in Figure~\ref{fig:r0-concrete-syntax}.
  802. \racket{The \code{read-program} function provided in
  803. \code{utilities.rkt} of the support code reads a program in from a
  804. file (the sequence of characters in the concrete syntax of Racket)
  805. and parses it into an abstract syntax tree. See the description of
  806. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  807. details.}
  808. \python{The \code{parse} function in Python's \code{ast} module
  809. converts the concrete syntax (represented as a string) into an
  810. abstract syntax tree.}
  811. \newcommand{\LintGrammarRacket}{
  812. \begin{array}{rcl}
  813. \Type &::=& \key{Integer} \\
  814. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  815. \MID \CSUB{\Exp}{\Exp}
  816. \end{array}
  817. }
  818. \newcommand{\LintASTRacket}{
  819. \begin{array}{rcl}
  820. \Type &::=& \key{Integer} \\
  821. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  822. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  823. \end{array}
  824. }
  825. \newcommand{\LintGrammarPython}{
  826. \begin{array}{rcl}
  827. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  828. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  829. \end{array}
  830. }
  831. \newcommand{\LintASTPython}{
  832. \begin{array}{rcl}
  833. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  834. \itm{unaryop} &::= & \code{USub()} \\
  835. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  836. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  837. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  838. \end{array}
  839. }
  840. \begin{figure}[tp]
  841. \begin{tcolorbox}[colback=white]
  842. {\if\edition\racketEd
  843. \[
  844. \begin{array}{l}
  845. \LintGrammarRacket \\
  846. \begin{array}{rcl}
  847. \LangInt{} &::=& \Exp
  848. \end{array}
  849. \end{array}
  850. \]
  851. \fi}
  852. {\if\edition\pythonEd
  853. \[
  854. \begin{array}{l}
  855. \LintGrammarPython \\
  856. \begin{array}{rcl}
  857. \LangInt{} &::=& \Stmt^{*}
  858. \end{array}
  859. \end{array}
  860. \]
  861. \fi}
  862. \end{tcolorbox}
  863. \caption{The concrete syntax of \LangInt{}.}
  864. \label{fig:r0-concrete-syntax}
  865. \end{figure}
  866. \begin{figure}[tp]
  867. \begin{tcolorbox}[colback=white]
  868. {\if\edition\racketEd
  869. \[
  870. \begin{array}{l}
  871. \LintASTRacket{} \\
  872. \begin{array}{rcl}
  873. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  874. \end{array}
  875. \end{array}
  876. \]
  877. \fi}
  878. {\if\edition\pythonEd
  879. \[
  880. \begin{array}{l}
  881. \LintASTPython\\
  882. \begin{array}{rcl}
  883. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  884. \end{array}
  885. \end{array}
  886. \]
  887. \fi}
  888. \end{tcolorbox}
  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 and binds its parts to the
  920. three pattern variables \texttt{op}, \texttt{child1}, and
  921. \texttt{child2}. In general, a match clause consists of a
  922. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  923. recursively defined to be either a pattern variable, a structure name
  924. followed by a pattern for each of the structure's arguments, or an
  925. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  926. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  927. and Chapter 9 of The Racket
  928. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  929. for complete descriptions of \code{match}.)
  930. %
  931. The body of a match clause may contain arbitrary Racket code. The
  932. pattern variables can be used in the scope of the body, such as
  933. \code{op} in \code{(print op)}.
  934. %
  935. \fi}
  936. %
  937. %
  938. {\if\edition\pythonEd
  939. %
  940. In the above example, the \texttt{match} form checks whether the AST
  941. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  942. three pattern variables \texttt{child1}, \texttt{op}, and
  943. \texttt{child2}, and then prints out the operator. In general, each
  944. \code{case} consists of a \emph{pattern} and a
  945. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  946. to be either a pattern variable, a class name followed by a pattern
  947. for each of its constructor's arguments, or other literals such as
  948. strings, lists, etc.
  949. %
  950. The body of each \code{case} may contain arbitrary Python code. The
  951. pattern variables can be used in the body, such as \code{op} in
  952. \code{print(op)}.
  953. %
  954. \fi}
  955. A \code{match} form may contain several clauses, as in the following
  956. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  957. the AST. The \code{match} proceeds through the clauses in order,
  958. checking whether the pattern can match the input AST. The body of the
  959. first clause that matches is executed. The output of \code{leaf} for
  960. several ASTs is shown on the right.
  961. \begin{center}
  962. \begin{minipage}{0.6\textwidth}
  963. {\if\edition\racketEd
  964. \begin{lstlisting}
  965. (define (leaf arith)
  966. (match arith
  967. [(Int n) #t]
  968. [(Prim 'read '()) #t]
  969. [(Prim '- (list e1)) #f]
  970. [(Prim '+ (list e1 e2)) #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. case BinOp(e1, Sub(), e2):
  990. return False
  991. print(leaf(Call(Name('input_int'), [])))
  992. print(leaf(UnaryOp(USub(), eight)))
  993. print(leaf(Constant(8)))
  994. \end{lstlisting}
  995. \fi}
  996. \end{minipage}
  997. \vrule
  998. \begin{minipage}{0.25\textwidth}
  999. {\if\edition\racketEd
  1000. \begin{lstlisting}
  1001. #t
  1002. #f
  1003. #t
  1004. \end{lstlisting}
  1005. \fi}
  1006. {\if\edition\pythonEd
  1007. \begin{lstlisting}
  1008. True
  1009. False
  1010. True
  1011. \end{lstlisting}
  1012. \fi}
  1013. \end{minipage}
  1014. \end{center}
  1015. When constructing a \code{match} expression, we refer to the grammar
  1016. definition to identify which non-terminal we are expecting to match
  1017. against, then we make sure that 1) we have one
  1018. \racket{clause}\python{case} for each alternative of that non-terminal
  1019. and 2) that the pattern in each \racket{clause}\python{case}
  1020. corresponds to the corresponding right-hand side of a grammar
  1021. rule. For the \code{match} in the \code{leaf} function, we refer to
  1022. the grammar for \LangInt{} in Figure~\ref{fig:r0-syntax}. The $\Exp$
  1023. non-terminal has 4 alternatives, so the \code{match} has 4
  1024. \racket{clauses}\python{cases}. The pattern in each
  1025. \racket{clause}\python{case} corresponds to the right-hand side of a
  1026. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1027. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1028. translating from grammars to patterns, replace non-terminals such as
  1029. $\Exp$ with pattern variables of your choice (e.g. \code{e1} and
  1030. \code{e2}).
  1031. \section{Recursive Functions}
  1032. \label{sec:recursion}
  1033. \index{subject}{recursive function}
  1034. Programs are inherently recursive. For example, an expression is often
  1035. made of smaller expressions. Thus, the natural way to process an
  1036. entire program is with a recursive function. As a first example of
  1037. such a recursive function, we define the function \code{is\_exp} in
  1038. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1039. determines whether or not it is an expression in \LangInt{}.
  1040. %
  1041. We say that a function is defined by \emph{structural recursion} when
  1042. it is defined using a sequence of match \racket{clauses}\python{cases}
  1043. that correspond to a grammar, and the body of each
  1044. \racket{clause}\python{case} makes a recursive call on each child
  1045. node.\footnote{This principle of structuring code according to the
  1046. data definition is advocated in the book \emph{How to Design
  1047. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1048. second function, named \code{stmt}, that recognizes whether a value
  1049. is a \LangInt{} statement.} \python{Finally, }
  1050. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{is\_Lint},
  1051. which determines whether an AST is a program in \LangInt{}. In
  1052. general we can write one recursive function to handle each
  1053. non-terminal in a grammar.\index{subject}{structural recursion} Of the
  1054. two examples at the bottom of the figure, the first is in
  1055. \LangInt{} and the second is not.
  1056. \begin{figure}[tp]
  1057. \begin{tcolorbox}[colback=white]
  1058. {\if\edition\racketEd
  1059. \begin{lstlisting}
  1060. (define (is_exp ast)
  1061. (match ast
  1062. [(Int n) #t]
  1063. [(Prim 'read '()) #t]
  1064. [(Prim '- (list e)) (is_exp e)]
  1065. [(Prim '+ (list e1 e2))
  1066. (and (is_exp e1) (is_exp e2))]
  1067. [(Prim '- (list e1 e2))
  1068. (and (is_exp e1) (is_exp e2))]
  1069. [else #f]))
  1070. (define (is_Lint ast)
  1071. (match ast
  1072. [(Program '() e) (is_exp e)]
  1073. [else #f]))
  1074. (is_Lint (Program '() ast1_1)
  1075. (is_Lint (Program '()
  1076. (Prim '* (list (Prim 'read '())
  1077. (Prim '+ (list (Int 8)))))))
  1078. \end{lstlisting}
  1079. \fi}
  1080. {\if\edition\pythonEd
  1081. \begin{lstlisting}
  1082. def is_exp(e):
  1083. match e:
  1084. case Constant(n):
  1085. return True
  1086. case Call(Name('input_int'), []):
  1087. return True
  1088. case UnaryOp(USub(), e1):
  1089. return is_exp(e1)
  1090. case BinOp(e1, Add(), e2):
  1091. return is_exp(e1) and is_exp(e2)
  1092. case BinOp(e1, Sub(), e2):
  1093. return is_exp(e1) and is_exp(e2)
  1094. case _:
  1095. return False
  1096. def stmt(s):
  1097. match s:
  1098. case Expr(Call(Name('print'), [e])):
  1099. return is_exp(e)
  1100. case Expr(e):
  1101. return is_exp(e)
  1102. case _:
  1103. return False
  1104. def is_Lint(p):
  1105. match p:
  1106. case Module(body):
  1107. return all([stmt(s) for s in body])
  1108. case _:
  1109. return False
  1110. print(is_Lint(Module([Expr(ast1_1)])))
  1111. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1112. UnaryOp(Add(), Constant(8))))])))
  1113. \end{lstlisting}
  1114. \fi}
  1115. \end{tcolorbox}
  1116. \caption{Example of recursive functions for \LangInt{}. These functions
  1117. recognize whether an AST is in \LangInt{}.}
  1118. \label{fig:exp-predicate}
  1119. \end{figure}
  1120. %% You may be tempted to merge the two functions into one, like this:
  1121. %% \begin{center}
  1122. %% \begin{minipage}{0.5\textwidth}
  1123. %% \begin{lstlisting}
  1124. %% (define (Lint ast)
  1125. %% (match ast
  1126. %% [(Int n) #t]
  1127. %% [(Prim 'read '()) #t]
  1128. %% [(Prim '- (list e)) (Lint e)]
  1129. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1130. %% [(Program '() e) (Lint e)]
  1131. %% [else #f]))
  1132. %% \end{lstlisting}
  1133. %% \end{minipage}
  1134. %% \end{center}
  1135. %% %
  1136. %% Sometimes such a trick will save a few lines of code, especially when
  1137. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1138. %% \emph{not} recommended because it can get you into trouble.
  1139. %% %
  1140. %% For example, the above function is subtly wrong:
  1141. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1142. %% returns true when it should return false.
  1143. \section{Interpreters}
  1144. \label{sec:interp_Lint}
  1145. \index{subject}{interpreter}
  1146. The behavior of a program is defined by the specification of the
  1147. programming language.
  1148. %
  1149. \racket{For example, the Scheme language is defined in the report by
  1150. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1151. reference manual~\citep{plt-tr}.}
  1152. %
  1153. \python{For example, the Python language is defined in the Python
  1154. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1155. %
  1156. In this book we use interpreters to specify each language that we
  1157. consider. An interpreter that is designated as the definition of a
  1158. language is called a \emph{definitional
  1159. interpreter}~\citep{reynolds72:_def_interp}.
  1160. \index{subject}{definitional interpreter} We warm up by creating a
  1161. definitional interpreter for the \LangInt{} language. This interpreter
  1162. serves as a second example of structural recursion. The
  1163. \code{interp\_Lint} function is defined in
  1164. Figure~\ref{fig:interp_Lint}.
  1165. %
  1166. \racket{The body of the function is a match on the input program
  1167. followed by a call to the \lstinline{interp_exp} helper function,
  1168. which in turn has one match clause per grammar rule for \LangInt{}
  1169. expressions.}
  1170. %
  1171. \python{The body of the function matches on the \code{Module} AST node
  1172. and then invokes \code{interp\_stmt} on each statement in the
  1173. module. The \code{interp\_stmt} function includes a case for each
  1174. grammar rule of the \Stmt{} non-terminal and it calls
  1175. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1176. function includes a case for each grammar rule of the \Exp{}
  1177. non-terminal.}
  1178. \begin{figure}[tp]
  1179. \begin{tcolorbox}[colback=white]
  1180. {\if\edition\racketEd
  1181. \begin{lstlisting}
  1182. (define (interp_exp e)
  1183. (match e
  1184. [(Int n) n]
  1185. [(Prim 'read '())
  1186. (define r (read))
  1187. (cond [(fixnum? r) r]
  1188. [else (error 'interp_exp "read expected an integer" r)])]
  1189. [(Prim '- (list e))
  1190. (define v (interp_exp e))
  1191. (fx- 0 v)]
  1192. [(Prim '+ (list e1 e2))
  1193. (define v1 (interp_exp e1))
  1194. (define v2 (interp_exp e2))
  1195. (fx+ v1 v2)]
  1196. [(Prim '- (list e1 e2))
  1197. (define v1 ((interp-exp env) e1))
  1198. (define v2 ((interp-exp env) e2))
  1199. (fx- v1 v2)]))
  1200. (define (interp_Lint p)
  1201. (match p
  1202. [(Program '() e) (interp_exp e)]))
  1203. \end{lstlisting}
  1204. \fi}
  1205. {\if\edition\pythonEd
  1206. \begin{lstlisting}
  1207. def interp_exp(e):
  1208. match e:
  1209. case BinOp(left, Add(), right):
  1210. l = interp_exp(left); r = interp_exp(right)
  1211. return l + r
  1212. case BinOp(left, Sub(), right):
  1213. l = interp_exp(left); r = interp_exp(right)
  1214. return l - r
  1215. case UnaryOp(USub(), v):
  1216. return - interp_exp(v)
  1217. case Constant(value):
  1218. return value
  1219. case Call(Name('input_int'), []):
  1220. return int(input())
  1221. def interp_stmt(s):
  1222. match s:
  1223. case Expr(Call(Name('print'), [arg])):
  1224. print(interp_exp(arg))
  1225. case Expr(value):
  1226. interp_exp(value)
  1227. def interp_Lint(p):
  1228. match p:
  1229. case Module(body):
  1230. for s in body:
  1231. interp_stmt(s)
  1232. \end{lstlisting}
  1233. \fi}
  1234. \end{tcolorbox}
  1235. \caption{Interpreter for the \LangInt{} language.}
  1236. \label{fig:interp_Lint}
  1237. \end{figure}
  1238. Let us consider the result of interpreting a few \LangInt{} programs. The
  1239. following program adds two integers.
  1240. {\if\edition\racketEd
  1241. \begin{lstlisting}
  1242. (+ 10 32)
  1243. \end{lstlisting}
  1244. \fi}
  1245. {\if\edition\pythonEd
  1246. \begin{lstlisting}
  1247. print(10 + 32)
  1248. \end{lstlisting}
  1249. \fi}
  1250. %
  1251. \noindent The result is \key{42}, the answer to life, the universe,
  1252. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1253. the Galaxy} by Douglas Adams.}
  1254. %
  1255. We wrote the above program in concrete syntax whereas the parsed
  1256. abstract syntax is:
  1257. {\if\edition\racketEd
  1258. \begin{lstlisting}
  1259. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1260. \end{lstlisting}
  1261. \fi}
  1262. {\if\edition\pythonEd
  1263. \begin{lstlisting}
  1264. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1265. \end{lstlisting}
  1266. \fi}
  1267. The next example demonstrates that expressions may be nested within
  1268. each other, in this case nesting several additions and negations.
  1269. {\if\edition\racketEd
  1270. \begin{lstlisting}
  1271. (+ 10 (- (+ 12 20)))
  1272. \end{lstlisting}
  1273. \fi}
  1274. {\if\edition\pythonEd
  1275. \begin{lstlisting}
  1276. print(10 + -(12 + 20))
  1277. \end{lstlisting}
  1278. \fi}
  1279. %
  1280. \noindent What is the result of the above program?
  1281. {\if\edition\racketEd
  1282. As mentioned previously, the \LangInt{} language does not support
  1283. arbitrarily-large integers, but only $63$-bit integers, so we
  1284. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1285. in Racket.
  1286. Suppose
  1287. \[
  1288. n = 999999999999999999
  1289. \]
  1290. which indeed fits in $63$-bits. What happens when we run the
  1291. following program in our interpreter?
  1292. \begin{lstlisting}
  1293. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1294. \end{lstlisting}
  1295. It produces an error:
  1296. \begin{lstlisting}
  1297. fx+: result is not a fixnum
  1298. \end{lstlisting}
  1299. We establish the convention that if running the definitional
  1300. interpreter on a program produces an error then the meaning of that
  1301. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1302. error is a \code{trapped-error}. A compiler for the language is under
  1303. no obligations regarding programs with unspecified behavior; it does
  1304. not have to produce an executable, and if it does, that executable can
  1305. do anything. On the other hand, if the error is a
  1306. \code{trapped-error}, then the compiler must produce an executable and
  1307. it is required to report that an error occurred. To signal an error,
  1308. exit with a return code of \code{255}. The interpreters in chapters
  1309. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1310. \code{trapped-error}.
  1311. \fi}
  1312. % TODO: how to deal with too-large integers in the Python interpreter?
  1313. %% This convention applies to the languages defined in this
  1314. %% book, as a way to simplify the student's task of implementing them,
  1315. %% but this convention is not applicable to all programming languages.
  1316. %%
  1317. Moving on to the last feature of the \LangInt{} language, the
  1318. \READOP{} operation prompts the user of the program for an integer.
  1319. Recall that program \eqref{eq:arith-prog} requests an integer input
  1320. and then subtracts \code{8}. So if we run
  1321. {\if\edition\racketEd
  1322. \begin{lstlisting}
  1323. (interp_Lint (Program '() ast1_1))
  1324. \end{lstlisting}
  1325. \fi}
  1326. {\if\edition\pythonEd
  1327. \begin{lstlisting}
  1328. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1329. \end{lstlisting}
  1330. \fi}
  1331. \noindent and if the input is \code{50}, the result is \code{42}.
  1332. We include the \READOP{} operation in \LangInt{} so a clever student
  1333. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1334. during compilation to obtain the output and then generates the trivial
  1335. code to produce the output.\footnote{Yes, a clever student did this in the
  1336. first instance of this course!}
  1337. The job of a compiler is to translate a program in one language into a
  1338. program in another language so that the output program behaves the
  1339. same way as the input program. This idea is depicted in the
  1340. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1341. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1342. Given a compiler that translates from language $\mathcal{L}_1$ to
  1343. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1344. compiler must translate it into some program $P_2$ such that
  1345. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1346. same input $i$ yields the same output $o$.
  1347. \begin{equation} \label{eq:compile-correct}
  1348. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1349. \node (p1) at (0, 0) {$P_1$};
  1350. \node (p2) at (3, 0) {$P_2$};
  1351. \node (o) at (3, -2.5) {$o$};
  1352. \path[->] (p1) edge [above] node {compile} (p2);
  1353. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1354. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1355. \end{tikzpicture}
  1356. \end{equation}
  1357. In the next section we see our first example of a compiler.
  1358. \section{Example Compiler: a Partial Evaluator}
  1359. \label{sec:partial-evaluation}
  1360. In this section we consider a compiler that translates \LangInt{}
  1361. programs into \LangInt{} programs that may be more efficient. The
  1362. compiler eagerly computes the parts of the program that do not depend
  1363. on any inputs, a process known as \emph{partial
  1364. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1365. For example, given the following program
  1366. {\if\edition\racketEd
  1367. \begin{lstlisting}
  1368. (+ (read) (- (+ 5 3)))
  1369. \end{lstlisting}
  1370. \fi}
  1371. {\if\edition\pythonEd
  1372. \begin{lstlisting}
  1373. print(input_int() + -(5 + 3) )
  1374. \end{lstlisting}
  1375. \fi}
  1376. \noindent our compiler translates it into the program
  1377. {\if\edition\racketEd
  1378. \begin{lstlisting}
  1379. (+ (read) -8)
  1380. \end{lstlisting}
  1381. \fi}
  1382. {\if\edition\pythonEd
  1383. \begin{lstlisting}
  1384. print(input_int() + -8)
  1385. \end{lstlisting}
  1386. \fi}
  1387. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1388. evaluator for the \LangInt{} language. The output of the partial evaluator
  1389. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1390. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1391. whereas the code for partially evaluating the negation and addition
  1392. operations is factored into three auxiliary functions:
  1393. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1394. functions is the output of partially evaluating the children.
  1395. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1396. arguments are integers and if they are, perform the appropriate
  1397. arithmetic. Otherwise, they create an AST node for the arithmetic
  1398. operation.
  1399. \begin{figure}[tp]
  1400. \begin{tcolorbox}[colback=white]
  1401. {\if\edition\racketEd
  1402. \begin{lstlisting}
  1403. (define (pe_neg r)
  1404. (match r
  1405. [(Int n) (Int (fx- 0 n))]
  1406. [else (Prim '- (list r))]))
  1407. (define (pe_add r1 r2)
  1408. (match* (r1 r2)
  1409. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1410. [(_ _) (Prim '+ (list r1 r2))]))
  1411. (define (pe_sub r1 r2)
  1412. (match* (r1 r2)
  1413. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1414. [(_ _) (Prim '- (list r1 r2))]))
  1415. (define (pe_exp e)
  1416. (match e
  1417. [(Int n) (Int n)]
  1418. [(Prim 'read '()) (Prim 'read '())]
  1419. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1420. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1421. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1422. (define (pe_Lint p)
  1423. (match p
  1424. [(Program '() e) (Program '() (pe_exp e))]))
  1425. \end{lstlisting}
  1426. \fi}
  1427. {\if\edition\pythonEd
  1428. \begin{lstlisting}
  1429. def pe_neg(r):
  1430. match r:
  1431. case Constant(n):
  1432. return Constant(-n)
  1433. case _:
  1434. return UnaryOp(USub(), r)
  1435. def pe_add(r1, r2):
  1436. match (r1, r2):
  1437. case (Constant(n1), Constant(n2)):
  1438. return Constant(n1 + n2)
  1439. case _:
  1440. return BinOp(r1, Add(), r2)
  1441. def pe_sub(r1, r2):
  1442. match (r1, r2):
  1443. case (Constant(n1), Constant(n2)):
  1444. return Constant(n1 - n2)
  1445. case _:
  1446. return BinOp(r1, Sub(), r2)
  1447. def pe_exp(e):
  1448. match e:
  1449. case BinOp(left, Add(), right):
  1450. return pe_add(pe_exp(left), pe_exp(right))
  1451. case BinOp(left, Sub(), right):
  1452. return pe_sub(pe_exp(left), pe_exp(right))
  1453. case UnaryOp(USub(), v):
  1454. return pe_neg(pe_exp(v))
  1455. case Constant(value):
  1456. return e
  1457. case Call(Name('input_int'), []):
  1458. return e
  1459. def pe_stmt(s):
  1460. match s:
  1461. case Expr(Call(Name('print'), [arg])):
  1462. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1463. case Expr(value):
  1464. return Expr(pe_exp(value))
  1465. def pe_P_int(p):
  1466. match p:
  1467. case Module(body):
  1468. new_body = [pe_stmt(s) for s in body]
  1469. return Module(new_body)
  1470. \end{lstlisting}
  1471. \fi}
  1472. \end{tcolorbox}
  1473. \caption{A partial evaluator for \LangInt{}.}
  1474. \label{fig:pe-arith}
  1475. \end{figure}
  1476. To gain some confidence that the partial evaluator is correct, we can
  1477. test whether it produces programs that produce the same result as the
  1478. input programs. That is, we can test whether it satisfies Diagram
  1479. \ref{eq:compile-correct}.
  1480. %
  1481. {\if\edition\racketEd
  1482. The following code runs the partial evaluator on several examples and
  1483. tests the output program. The \texttt{parse-program} and
  1484. \texttt{assert} functions are defined in
  1485. Appendix~\ref{appendix:utilities}.\\
  1486. \begin{minipage}{1.0\textwidth}
  1487. \begin{lstlisting}
  1488. (define (test_pe p)
  1489. (assert "testing pe_Lint"
  1490. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1491. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1492. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1493. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1494. \end{lstlisting}
  1495. \end{minipage}
  1496. \fi}
  1497. % TODO: python version of testing the PE
  1498. \begin{exercise}\normalfont\normalsize
  1499. Create three programs in the \LangInt{} language and test whether
  1500. partially evaluating them with \code{pe\_Lint} and then
  1501. interpreting them with \code{interp\_Lint} gives the same result
  1502. as directly interpreting them with \code{interp\_Lint}.
  1503. \end{exercise}
  1504. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1505. \chapter{Integers and Variables}
  1506. \label{ch:Lvar}
  1507. This chapter is about compiling a subset of
  1508. \racket{Racket}\python{Python} to x86-64 assembly
  1509. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1510. integer arithmetic and local variables. We often refer to x86-64
  1511. simply as x86. The chapter begins with a description of the
  1512. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1513. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1514. large so we discuss only the instructions needed for compiling
  1515. \LangVar{}. We introduce more x86 instructions in later chapters.
  1516. After introducing \LangVar{} and x86, we reflect on their differences
  1517. and come up with a plan to break down the translation from \LangVar{}
  1518. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1519. rest of the sections in this chapter give detailed hints regarding
  1520. each step. We hope to give enough hints that the well-prepared
  1521. reader, together with a few friends, can implement a compiler from
  1522. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1523. the scale of this first compiler, the instructor solution for the
  1524. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1525. code.
  1526. \section{The \LangVar{} Language}
  1527. \label{sec:s0}
  1528. \index{subject}{variable}
  1529. The \LangVar{} language extends the \LangInt{} language with
  1530. variables. The concrete syntax of the \LangVar{} language is defined
  1531. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1532. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1533. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1534. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1535. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1536. syntax of \LangVar{} includes the \racket{\key{Program}
  1537. struct}\python{\key{Module} instance} to mark the top of the
  1538. program.
  1539. %% The $\itm{info}$
  1540. %% field of the \key{Program} structure contains an \emph{association
  1541. %% list} (a list of key-value pairs) that is used to communicate
  1542. %% auxiliary data from one compiler pass the next.
  1543. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1544. exhibit several compilation techniques.
  1545. \newcommand{\LvarGrammarRacket}{
  1546. \begin{array}{rcl}
  1547. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1548. \end{array}
  1549. }
  1550. \newcommand{\LvarASTRacket}{
  1551. \begin{array}{rcl}
  1552. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1553. \end{array}
  1554. }
  1555. \newcommand{\LvarGrammarPython}{
  1556. \begin{array}{rcl}
  1557. \Exp &::=& \Var{} \\
  1558. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1559. \end{array}
  1560. }
  1561. \newcommand{\LvarASTPython}{
  1562. \begin{array}{rcl}
  1563. \Exp{} &::=& \VAR{\Var{}} \\
  1564. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1565. \end{array}
  1566. }
  1567. \begin{figure}[tp]
  1568. \centering
  1569. \begin{tcolorbox}[colback=white]
  1570. {\if\edition\racketEd
  1571. \[
  1572. \begin{array}{l}
  1573. \gray{\LintGrammarRacket{}} \\ \hline
  1574. \LvarGrammarRacket{} \\
  1575. \begin{array}{rcl}
  1576. \LangVarM{} &::=& \Exp
  1577. \end{array}
  1578. \end{array}
  1579. \]
  1580. \fi}
  1581. {\if\edition\pythonEd
  1582. \[
  1583. \begin{array}{l}
  1584. \gray{\LintGrammarPython} \\ \hline
  1585. \LvarGrammarPython \\
  1586. \begin{array}{rcl}
  1587. \LangVarM{} &::=& \Stmt^{*}
  1588. \end{array}
  1589. \end{array}
  1590. \]
  1591. \fi}
  1592. \end{tcolorbox}
  1593. \caption{The concrete syntax of \LangVar{}.}
  1594. \label{fig:Lvar-concrete-syntax}
  1595. \end{figure}
  1596. \begin{figure}[tp]
  1597. \centering
  1598. \begin{tcolorbox}[colback=white]
  1599. {\if\edition\racketEd
  1600. \[
  1601. \begin{array}{l}
  1602. \gray{\LintASTRacket{}} \\ \hline
  1603. \LvarASTRacket \\
  1604. \begin{array}{rcl}
  1605. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1606. \end{array}
  1607. \end{array}
  1608. \]
  1609. \fi}
  1610. {\if\edition\pythonEd
  1611. \[
  1612. \begin{array}{l}
  1613. \gray{\LintASTPython}\\ \hline
  1614. \LvarASTPython \\
  1615. \begin{array}{rcl}
  1616. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1617. \end{array}
  1618. \end{array}
  1619. \]
  1620. \fi}
  1621. \end{tcolorbox}
  1622. \caption{The abstract syntax of \LangVar{}.}
  1623. \label{fig:Lvar-syntax}
  1624. \end{figure}
  1625. {\if\edition\racketEd
  1626. Let us dive further into the syntax and semantics of the \LangVar{}
  1627. language. The \key{let} feature defines a variable for use within its
  1628. body and initializes the variable with the value of an expression.
  1629. The abstract syntax for \key{let} is defined in
  1630. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1631. \begin{lstlisting}
  1632. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1633. \end{lstlisting}
  1634. For example, the following program initializes \code{x} to $32$ and then
  1635. evaluates the body \code{(+ 10 x)}, producing $42$.
  1636. \begin{lstlisting}
  1637. (let ([x (+ 12 20)]) (+ 10 x))
  1638. \end{lstlisting}
  1639. \fi}
  1640. %
  1641. {\if\edition\pythonEd
  1642. %
  1643. The \LangVar{} language includes assignment statements, which define a
  1644. variable for use in later statements and initializes the variable with
  1645. the value of an expression. The abstract syntax for assignment is
  1646. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1647. assignment is
  1648. \begin{lstlisting}
  1649. |$\itm{var}$| = |$\itm{exp}$|
  1650. \end{lstlisting}
  1651. For example, the following program initializes the variable \code{x}
  1652. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1653. \begin{lstlisting}
  1654. x = 12 + 20
  1655. print(10 + x)
  1656. \end{lstlisting}
  1657. \fi}
  1658. {\if\edition\racketEd
  1659. %
  1660. When there are multiple \key{let}'s for the same variable, the closest
  1661. enclosing \key{let} is used. That is, variable definitions overshadow
  1662. prior definitions. Consider the following program with two \key{let}'s
  1663. that define two variables named \code{x}. Can you figure out the
  1664. result?
  1665. \begin{lstlisting}
  1666. (let ([x 32]) (+ (let ([x 10]) x) x))
  1667. \end{lstlisting}
  1668. For the purposes of depicting which variable occurrences correspond to
  1669. which definitions, the following shows the \code{x}'s annotated with
  1670. subscripts to distinguish them. Double check that your answer for the
  1671. above is the same as your answer for this annotated version of the
  1672. program.
  1673. \begin{lstlisting}
  1674. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1675. \end{lstlisting}
  1676. The initializing expression is always evaluated before the body of the
  1677. \key{let}, so in the following, the \key{read} for \code{x} is
  1678. performed before the \key{read} for \code{y}. Given the input
  1679. $52$ then $10$, the following produces $42$ (not $-42$).
  1680. \begin{lstlisting}
  1681. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1682. \end{lstlisting}
  1683. \fi}
  1684. \subsection{Extensible Interpreters via Method Overriding}
  1685. \label{sec:extensible-interp}
  1686. To prepare for discussing the interpreter of \LangVar{}, we explain
  1687. why we implement it in an object-oriented style. Throughout this book
  1688. we define many interpreters, one for each of language that we
  1689. study. Because each language builds on the prior one, there is a lot
  1690. of commonality between these interpreters. We want to write down the
  1691. common parts just once instead of many times. A naive
  1692. interpreter for \LangVar{} would handle the
  1693. \racket{cases for variables and \code{let}}
  1694. \python{case for variables}
  1695. but dispatch to an interpreter for \LangInt{}
  1696. in the rest of the cases. The following code sketches this idea. (We
  1697. explain the \code{env} parameter soon, in
  1698. Section~\ref{sec:interp-Lvar}.)
  1699. \begin{center}
  1700. {\if\edition\racketEd
  1701. \begin{minipage}{0.45\textwidth}
  1702. \begin{lstlisting}
  1703. (define ((interp_Lint env) e)
  1704. (match e
  1705. [(Prim '- (list e1))
  1706. (fx- 0 ((interp_Lint env) e1))]
  1707. ...))
  1708. \end{lstlisting}
  1709. \end{minipage}
  1710. \begin{minipage}{0.45\textwidth}
  1711. \begin{lstlisting}
  1712. (define ((interp_Lvar env) e)
  1713. (match e
  1714. [(Var x)
  1715. (dict-ref env x)]
  1716. [(Let x e body)
  1717. (define v ((interp_exp env) e))
  1718. (define env^ (dict-set env x v))
  1719. ((interp_exp env^) body)]
  1720. [else ((interp_Lint env) e)]))
  1721. \end{lstlisting}
  1722. \end{minipage}
  1723. \fi}
  1724. {\if\edition\pythonEd
  1725. \begin{minipage}{0.45\textwidth}
  1726. \begin{lstlisting}
  1727. def interp_Lint(e, env):
  1728. match e:
  1729. case UnaryOp(USub(), e1):
  1730. return - interp_Lint(e1, env)
  1731. ...
  1732. \end{lstlisting}
  1733. \end{minipage}
  1734. \begin{minipage}{0.45\textwidth}
  1735. \begin{lstlisting}
  1736. def interp_Lvar(e, env):
  1737. match e:
  1738. case Name(id):
  1739. return env[id]
  1740. case _:
  1741. return interp_Lint(e, env)
  1742. \end{lstlisting}
  1743. \end{minipage}
  1744. \fi}
  1745. \end{center}
  1746. The problem with this naive approach is that it does not handle
  1747. situations in which an \LangVar{} feature, such as a variable, is
  1748. nested inside an \LangInt{} feature, like the \code{-} operator, as in
  1749. the following program.
  1750. %
  1751. {\if\edition\racketEd
  1752. \begin{lstlisting}
  1753. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1754. \end{lstlisting}
  1755. \fi}
  1756. {\if\edition\pythonEd
  1757. \begin{lstlisting}
  1758. y = 10
  1759. print(-y)
  1760. \end{lstlisting}
  1761. \fi}
  1762. %
  1763. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1764. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1765. then it recursively calls \code{interp\_Lint} again on its argument.
  1766. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1767. an error!
  1768. To make our interpreters extensible we need something called
  1769. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1770. recursive knot is delayed to when the functions are
  1771. composed. Object-oriented languages provide open recursion via
  1772. method overriding\index{subject}{method overriding}. The
  1773. following code uses method overriding to interpret \LangInt{} and
  1774. \LangVar{} using
  1775. %
  1776. \racket{the
  1777. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1778. \index{subject}{class} feature of Racket.}
  1779. %
  1780. \python{a Python \code{class} definition.}
  1781. %
  1782. We define one class for each language and define a method for
  1783. interpreting expressions inside each class. The class for \LangVar{}
  1784. inherits from the class for \LangInt{} and the method
  1785. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1786. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1787. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1788. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1789. \code{interp\_exp} in \LangInt{}.
  1790. \begin{center}
  1791. \hspace{-20pt}
  1792. {\if\edition\racketEd
  1793. \begin{minipage}{0.45\textwidth}
  1794. \begin{lstlisting}
  1795. (define interp-Lint-class
  1796. (class object%
  1797. (define/public ((interp_exp env) e)
  1798. (match e
  1799. [(Prim '- (list e))
  1800. (fx- 0 ((interp_exp env) e))]
  1801. ...))
  1802. ...))
  1803. \end{lstlisting}
  1804. \end{minipage}
  1805. \begin{minipage}{0.45\textwidth}
  1806. \begin{lstlisting}
  1807. (define interp-Lvar-class
  1808. (class interp-Lint-class
  1809. (define/override ((interp_exp env) e)
  1810. (match e
  1811. [(Var x)
  1812. (dict-ref env x)]
  1813. [(Let x e body)
  1814. (define v ((interp_exp env) e))
  1815. (define env^ (dict-set env x v))
  1816. ((interp_exp env^) body)]
  1817. [else
  1818. (super (interp_exp env) e)]))
  1819. ...
  1820. ))
  1821. \end{lstlisting}
  1822. \end{minipage}
  1823. \fi}
  1824. {\if\edition\pythonEd
  1825. \begin{minipage}{0.45\textwidth}
  1826. \begin{lstlisting}
  1827. class InterpLint:
  1828. def interp_exp(e):
  1829. match e:
  1830. case UnaryOp(USub(), e1):
  1831. return -self.interp_exp(e1)
  1832. ...
  1833. ...
  1834. \end{lstlisting}
  1835. \end{minipage}
  1836. \begin{minipage}{0.45\textwidth}
  1837. \begin{lstlisting}
  1838. def InterpLvar(InterpLint):
  1839. def interp_exp(e):
  1840. match e:
  1841. case Name(id):
  1842. return env[id]
  1843. case _:
  1844. return super().interp_exp(e)
  1845. ...
  1846. \end{lstlisting}
  1847. \end{minipage}
  1848. \fi}
  1849. \end{center}
  1850. Getting back to the troublesome example, repeated here:
  1851. {\if\edition\racketEd
  1852. \begin{lstlisting}
  1853. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1854. \end{lstlisting}
  1855. \fi}
  1856. {\if\edition\pythonEd
  1857. \begin{lstlisting}
  1858. y = 10
  1859. print(-y)
  1860. \end{lstlisting}
  1861. \fi}
  1862. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1863. \racket{on this expression,}
  1864. \python{on the \code{-y} expression,}
  1865. %
  1866. call it \code{e0}, by creating an object of the \LangVar{} class
  1867. and calling the \code{interp\_exp} method.
  1868. {\if\edition\racketEd
  1869. \begin{lstlisting}
  1870. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1871. \end{lstlisting}
  1872. \fi}
  1873. {\if\edition\pythonEd
  1874. \begin{lstlisting}
  1875. InterpLvar().interp_exp(e0)
  1876. \end{lstlisting}
  1877. \fi}
  1878. \noindent To process the \code{-} operator, the default case of
  1879. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1880. method in \LangInt{}. But then for the recursive method call, it
  1881. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1882. \code{Var} node is handled correctly. Thus, method overriding gives us
  1883. the open recursion that we need to implement our interpreters in an
  1884. extensible way.
  1885. \subsection{Definitional Interpreter for \LangVar{}}
  1886. \label{sec:interp-Lvar}
  1887. {\if\edition\racketEd
  1888. \begin{figure}[tp]
  1889. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1890. \small
  1891. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1892. An \emph{association list} (alist) is a list of key-value pairs.
  1893. For example, we can map people to their ages with an alist.
  1894. \index{subject}{alist}\index{subject}{association list}
  1895. \begin{lstlisting}[basicstyle=\ttfamily]
  1896. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1897. \end{lstlisting}
  1898. The \emph{dictionary} interface is for mapping keys to values.
  1899. Every alist implements this interface. \index{subject}{dictionary} The package
  1900. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1901. provides many functions for working with dictionaries. Here
  1902. are a few of them:
  1903. \begin{description}
  1904. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1905. returns the value associated with the given $\itm{key}$.
  1906. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1907. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1908. but otherwise is the same as $\itm{dict}$.
  1909. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1910. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1911. of keys and values in $\itm{dict}$. For example, the following
  1912. creates a new alist in which the ages are incremented.
  1913. \end{description}
  1914. \vspace{-10pt}
  1915. \begin{lstlisting}[basicstyle=\ttfamily]
  1916. (for/list ([(k v) (in-dict ages)])
  1917. (cons k (add1 v)))
  1918. \end{lstlisting}
  1919. \end{tcolorbox}
  1920. %\end{wrapfigure}
  1921. \caption{Association lists implement the dictionary interface.}
  1922. \label{fig:alist}
  1923. \end{figure}
  1924. \fi}
  1925. Having justified the use of classes and methods to implement
  1926. interpreters, we revisit the definitional interpreter for \LangInt{}
  1927. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1928. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1929. interpreter for \LangVar{} adds two new \key{match} cases for
  1930. variables and \racket{\key{let}}\python{assignment}. For
  1931. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1932. value bound to a variable to all the uses of the variable. To
  1933. accomplish this, we maintain a mapping from variables to values
  1934. called an \emph{environment}\index{subject}{environment}.
  1935. %
  1936. We use
  1937. %
  1938. \racket{an association list (alist) }%
  1939. %
  1940. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1941. %
  1942. to represent the environment.
  1943. %
  1944. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1945. and the \code{racket/dict} package.}
  1946. %
  1947. The \code{interp\_exp} function takes the current environment,
  1948. \code{env}, as an extra parameter. When the interpreter encounters a
  1949. variable, it looks up the corresponding value in the dictionary.
  1950. %
  1951. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1952. initializing expression, extends the environment with the result
  1953. value bound to the variable, using \code{dict-set}, then evaluates
  1954. the body of the \key{Let}.}
  1955. %
  1956. \python{When the interpreter encounters an assignment, it evaluates
  1957. the initializing expression and then associates the resulting value
  1958. with the variable in the environment.}
  1959. \begin{figure}[tp]
  1960. \begin{tcolorbox}[colback=white]
  1961. {\if\edition\racketEd
  1962. \begin{lstlisting}
  1963. (define interp-Lint-class
  1964. (class object%
  1965. (super-new)
  1966. (define/public ((interp_exp env) e)
  1967. (match e
  1968. [(Int n) n]
  1969. [(Prim 'read '())
  1970. (define r (read))
  1971. (cond [(fixnum? r) r]
  1972. [else (error 'interp_exp "expected an integer" r)])]
  1973. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1974. [(Prim '+ (list e1 e2))
  1975. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1976. [(Prim '- (list e1 e2))
  1977. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1978. (define/public (interp_program p)
  1979. (match p
  1980. [(Program '() e) ((interp_exp '()) e)]))
  1981. ))
  1982. \end{lstlisting}
  1983. \fi}
  1984. {\if\edition\pythonEd
  1985. \begin{lstlisting}
  1986. class InterpLint:
  1987. def interp_exp(self, e, env):
  1988. match e:
  1989. case BinOp(left, Add(), right):
  1990. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1991. case BinOp(left, Sub(), right):
  1992. return self.interp_exp(left, env) - self.interp_exp(right, env)
  1993. case UnaryOp(USub(), v):
  1994. return - self.interp_exp(v, env)
  1995. case Constant(value):
  1996. return value
  1997. case Call(Name('input_int'), []):
  1998. return int(input())
  1999. def interp_stmts(self, ss, env):
  2000. if len(ss) == 0:
  2001. return
  2002. match ss[0]:
  2003. case Expr(Call(Name('print'), [arg])):
  2004. print(self.interp_exp(arg, env), end='')
  2005. return self.interp_stmts(ss[1:], env)
  2006. case Expr(value):
  2007. self.interp_exp(value, env)
  2008. return self.interp_stmts(ss[1:], env)
  2009. def interp(self, p):
  2010. match p:
  2011. case Module(body):
  2012. self.interp_stmts(body, {})
  2013. def interp_Lint(p):
  2014. return InterpLint().interp(p)
  2015. \end{lstlisting}
  2016. \fi}
  2017. \end{tcolorbox}
  2018. \caption{Interpreter for \LangInt{} as a class.}
  2019. \label{fig:interp-Lint-class}
  2020. \end{figure}
  2021. \begin{figure}[tp]
  2022. \begin{tcolorbox}[colback=white]
  2023. {\if\edition\racketEd
  2024. \begin{lstlisting}
  2025. (define interp-Lvar-class
  2026. (class interp-Lint-class
  2027. (super-new)
  2028. (define/override ((interp_exp env) e)
  2029. (match e
  2030. [(Var x) (dict-ref env x)]
  2031. [(Let x e body)
  2032. (define new-env (dict-set env x ((interp_exp env) e)))
  2033. ((interp_exp new-env) body)]
  2034. [else ((super interp-exp env) e)]))
  2035. ))
  2036. (define (interp_Lvar p)
  2037. (send (new interp-Lvar-class) interp_program p))
  2038. \end{lstlisting}
  2039. \fi}
  2040. {\if\edition\pythonEd
  2041. \begin{lstlisting}
  2042. class InterpLvar(InterpLint):
  2043. def interp_exp(self, e, env):
  2044. match e:
  2045. case Name(id):
  2046. return env[id]
  2047. case _:
  2048. return super().interp_exp(e, env)
  2049. def interp_stmts(self, ss, env):
  2050. if len(ss) == 0:
  2051. return
  2052. match ss[0]:
  2053. case Assign([lhs], value):
  2054. env[lhs.id] = self.interp_exp(value, env)
  2055. return self.interp_stmts(ss[1:], env)
  2056. case _:
  2057. return super().interp_stmts(ss, env)
  2058. def interp_Lvar(p):
  2059. return InterpLvar().interp(p)
  2060. \end{lstlisting}
  2061. \fi}
  2062. \end{tcolorbox}
  2063. \caption{Interpreter for the \LangVar{} language.}
  2064. \label{fig:interp-Lvar}
  2065. \end{figure}
  2066. The goal for this chapter is to implement a compiler that translates
  2067. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2068. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2069. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2070. That is, they output the same integer $n$. We depict this correctness
  2071. criteria in the following diagram.
  2072. \[
  2073. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2074. \node (p1) at (0, 0) {$P_1$};
  2075. \node (p2) at (4, 0) {$P_2$};
  2076. \node (o) at (4, -2) {$n$};
  2077. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2078. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2079. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2080. \end{tikzpicture}
  2081. \]
  2082. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2083. compiling \LangVar{}.
  2084. \section{The \LangXInt{} Assembly Language}
  2085. \label{sec:x86}
  2086. \index{subject}{x86}
  2087. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2088. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2089. assembler.
  2090. %
  2091. A program begins with a \code{main} label followed by a sequence of
  2092. instructions. The \key{globl} directive says that the \key{main}
  2093. procedure is externally visible, which is necessary so that the
  2094. operating system can call it.
  2095. %
  2096. An x86 program is stored in the computer's memory. For our purposes,
  2097. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2098. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2099. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2100. the address of the next instruction to be executed. For most
  2101. instructions, the program counter is incremented after the instruction
  2102. is executed, so it points to the next instruction in memory. Most x86
  2103. instructions take two operands, where each operand is either an
  2104. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2105. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2106. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2107. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2108. && \key{r8} \MID \key{r9} \MID \key{r10}
  2109. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2110. \MID \key{r14} \MID \key{r15}}
  2111. \newcommand{\GrammarXInt}{
  2112. \begin{array}{rcl}
  2113. \Reg &::=& \allregisters{} \\
  2114. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2115. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2116. \key{subq} \; \Arg\key{,} \Arg \MID
  2117. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2118. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2119. \key{callq} \; \mathit{label} \MID
  2120. \key{retq} \MID
  2121. \key{jmp}\,\itm{label} \MID \\
  2122. && \itm{label}\key{:}\; \Instr
  2123. \end{array}
  2124. }
  2125. \begin{figure}[tp]
  2126. \begin{tcolorbox}[colback=white]
  2127. {\if\edition\racketEd
  2128. \[
  2129. \begin{array}{l}
  2130. \GrammarXInt \\
  2131. \begin{array}{lcl}
  2132. \LangXIntM{} &::= & \key{.globl main}\\
  2133. & & \key{main:} \; \Instr\ldots
  2134. \end{array}
  2135. \end{array}
  2136. \]
  2137. \fi}
  2138. {\if\edition\pythonEd
  2139. \[
  2140. \begin{array}{lcl}
  2141. \Reg &::=& \allregisters{} \\
  2142. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2143. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2144. \key{subq} \; \Arg\key{,} \Arg \MID
  2145. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2146. && \key{callq} \; \mathit{label} \MID
  2147. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2148. \LangXIntM{} &::= & \key{.globl main}\\
  2149. & & \key{main:} \; \Instr^{*}
  2150. \end{array}
  2151. \]
  2152. \fi}
  2153. \end{tcolorbox}
  2154. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2155. \label{fig:x86-int-concrete}
  2156. \end{figure}
  2157. A register is a special kind of variable that holds a 64-bit
  2158. value. There are 16 general-purpose registers in the computer and
  2159. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2160. is written with a \key{\%} followed by the register name, such as
  2161. \key{\%rax}.
  2162. An immediate value is written using the notation \key{\$}$n$ where $n$
  2163. is an integer.
  2164. %
  2165. %
  2166. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2167. which obtains the address stored in register $r$ and then adds $n$
  2168. bytes to the address. The resulting address is used to load or store
  2169. to memory depending on whether it occurs as a source or destination
  2170. argument of an instruction.
  2171. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2172. source $s$ and destination $d$, applies the arithmetic operation, then
  2173. writes the result back to the destination $d$. \index{subject}{instruction}
  2174. %
  2175. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2176. stores the result in $d$.
  2177. %
  2178. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2179. specified by the label and $\key{retq}$ returns from a procedure to
  2180. its caller.
  2181. %
  2182. We discuss procedure calls in more detail later in this chapter and in
  2183. Chapter~\ref{ch:Lfun}.
  2184. %
  2185. The last letter \key{q} indicates that these instructions operate on
  2186. quadwords, i.e., 64-bit values.
  2187. %
  2188. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2189. counter to the address of the instruction after the specified
  2190. label.}
  2191. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2192. all of the x86 instructions used in this book.
  2193. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2194. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2195. \lstinline{movq $10, %rax}
  2196. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2197. adds $32$ to the $10$ in \key{rax} and
  2198. puts the result, $42$, back into \key{rax}.
  2199. %
  2200. The last instruction \key{retq} finishes the \key{main} function by
  2201. returning the integer in \key{rax} to the operating system. The
  2202. operating system interprets this integer as the program's exit
  2203. code. By convention, an exit code of 0 indicates that a program
  2204. completed successfully, and all other exit codes indicate various
  2205. errors.
  2206. %
  2207. \racket{Nevertheless, in this book we return the result of the program
  2208. as the exit code.}
  2209. \begin{figure}[tbp]
  2210. \begin{minipage}{0.45\textwidth}
  2211. \begin{tcolorbox}[colback=white]
  2212. \begin{lstlisting}
  2213. .globl main
  2214. main:
  2215. movq $10, %rax
  2216. addq $32, %rax
  2217. retq
  2218. \end{lstlisting}
  2219. \end{tcolorbox}
  2220. \end{minipage}
  2221. \caption{An x86 program that computes
  2222. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2223. \label{fig:p0-x86}
  2224. \end{figure}
  2225. We exhibit the use of memory for storing intermediate results in the
  2226. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2227. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2228. uses a region of memory called the \emph{procedure call stack} (or
  2229. \emph{stack} for
  2230. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2231. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2232. for each procedure call. The memory layout for an individual frame is
  2233. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2234. \emph{stack pointer}\index{subject}{stack pointer} and it contains the
  2235. address of the item at the top of the stack. In general, we use the
  2236. term \emph{pointer}\index{subject}{pointer} for something that
  2237. contains an address. The stack grows downward in memory, so we
  2238. increase the size of the stack by subtracting from the stack pointer.
  2239. In the context of a procedure call, the \emph{return
  2240. address}\index{subject}{return address} is the instruction after the
  2241. call instruction on the caller side. The function call instruction,
  2242. \code{callq}, pushes the return address onto the stack prior to
  2243. jumping to the procedure. The register \key{rbp} is the \emph{base
  2244. pointer}\index{subject}{base pointer} and is used to access
  2245. variables that are stored in the frame of the current procedure call.
  2246. The base pointer of the caller is stored after the return address. In
  2247. Figure~\ref{fig:frame} we number the variables from $1$ to
  2248. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2249. at $-16\key{(\%rbp)}$, etc.
  2250. \begin{figure}[tbp]
  2251. \begin{minipage}{0.66\textwidth}
  2252. \begin{tcolorbox}[colback=white]
  2253. {\if\edition\racketEd
  2254. \begin{lstlisting}
  2255. start:
  2256. movq $10, -8(%rbp)
  2257. negq -8(%rbp)
  2258. movq -8(%rbp), %rax
  2259. addq $52, %rax
  2260. jmp conclusion
  2261. .globl main
  2262. main:
  2263. pushq %rbp
  2264. movq %rsp, %rbp
  2265. subq $16, %rsp
  2266. jmp start
  2267. conclusion:
  2268. addq $16, %rsp
  2269. popq %rbp
  2270. retq
  2271. \end{lstlisting}
  2272. \fi}
  2273. {\if\edition\pythonEd
  2274. \begin{lstlisting}
  2275. .globl main
  2276. main:
  2277. pushq %rbp
  2278. movq %rsp, %rbp
  2279. subq $16, %rsp
  2280. movq $10, -8(%rbp)
  2281. negq -8(%rbp)
  2282. movq -8(%rbp), %rax
  2283. addq $52, %rax
  2284. addq $16, %rsp
  2285. popq %rbp
  2286. retq
  2287. \end{lstlisting}
  2288. \fi}
  2289. \end{tcolorbox}
  2290. \end{minipage}
  2291. \caption{An x86 program that computes
  2292. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2293. \label{fig:p1-x86}
  2294. \end{figure}
  2295. \begin{figure}[tbp]
  2296. \centering
  2297. \begin{tabular}{|r|l|} \hline
  2298. Position & Contents \\ \hline
  2299. 8(\key{\%rbp}) & return address \\
  2300. 0(\key{\%rbp}) & old \key{rbp} \\
  2301. -8(\key{\%rbp}) & variable $1$ \\
  2302. -16(\key{\%rbp}) & variable $2$ \\
  2303. \ldots & \ldots \\
  2304. 0(\key{\%rsp}) & variable $n$\\ \hline
  2305. \end{tabular}
  2306. \caption{Memory layout of a frame.}
  2307. \label{fig:frame}
  2308. \end{figure}
  2309. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2310. control is transferred from the operating system to the \code{main}
  2311. function. The operating system issues a \code{callq main} instruction
  2312. which pushes its return address on the stack and then jumps to
  2313. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2314. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2315. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2316. alignment (because the \code{callq} pushed the return address). The
  2317. first three instructions are the typical
  2318. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2319. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2320. pointer \code{rsp} and then saves the base pointer of the caller at
  2321. address \code{rsp} on the stack. The next instruction \code{movq
  2322. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2323. which is pointing at the location of the old base pointer. The
  2324. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2325. make enough room for storing variables. This program needs one
  2326. variable ($8$ bytes) but we round up to 16 bytes so that \code{rsp} is
  2327. 16-byte aligned and we're ready to make calls to other functions.
  2328. \racket{The last instruction of the prelude is \code{jmp start}, which
  2329. transfers control to the instructions that were generated from the
  2330. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2331. \racket{The first instruction under the \code{start} label is}
  2332. %
  2333. \python{The first instruction after the prelude is}
  2334. %
  2335. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2336. %
  2337. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2338. $1$ to $-10$.
  2339. %
  2340. The next instruction moves the $-10$ from variable $1$ into the
  2341. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2342. the value in \code{rax}, updating its contents to $42$.
  2343. \racket{The three instructions under the label \code{conclusion} are the
  2344. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2345. %
  2346. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2347. \code{main} function consists of the last three instructions.}
  2348. %
  2349. The first two restore the \code{rsp} and \code{rbp} registers to the
  2350. state they were in at the beginning of the procedure. In particular,
  2351. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2352. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2353. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2354. \key{retq}, jumps back to the procedure that called this one and adds
  2355. $8$ to the stack pointer.
  2356. Our compiler needs a convenient representation for manipulating x86
  2357. programs, so we define an abstract syntax for x86 in
  2358. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2359. \LangXInt{}.
  2360. %
  2361. {\if\edition\pythonEd%
  2362. The main difference compared to the concrete syntax of \LangXInt{}
  2363. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2364. names, and register names are explicitly represented by strings.
  2365. \fi} %
  2366. {\if\edition\racketEd
  2367. The main difference compared to the concrete syntax of \LangXInt{}
  2368. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2369. front of every instruction. Instead instructions are grouped into
  2370. \emph{basic blocks}\index{subject}{basic block} with a
  2371. label associated with every basic block, which is why the \key{X86Program}
  2372. struct includes an alist mapping labels to basic blocks. The reason for this
  2373. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2374. introduce conditional branching. The \code{Block} structure includes
  2375. an $\itm{info}$ field that is not needed for this chapter but becomes
  2376. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2377. $\itm{info}$ field should contain an empty list.
  2378. \fi}
  2379. %
  2380. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2381. node includes an integer for representing the arity of the function,
  2382. i.e., the number of arguments, which is helpful to know during
  2383. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2384. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2385. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2386. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2387. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2388. \MID \skey{r14} \MID \skey{r15}}
  2389. \newcommand{\ASTXIntRacket}{
  2390. \begin{array}{lcl}
  2391. \Reg &::=& \allregisters{} \\
  2392. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2393. \MID \DEREF{\Reg}{\Int} \\
  2394. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2395. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}
  2396. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2397. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2398. \MID \PUSHQ{\Arg}
  2399. \MID \POPQ{\Arg} \\
  2400. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2401. \MID \RETQ{}
  2402. \MID \JMP{\itm{label}} \\
  2403. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2404. \end{array}
  2405. }
  2406. \begin{figure}[tp]
  2407. \begin{tcolorbox}[colback=white]
  2408. \small
  2409. {\if\edition\racketEd
  2410. \[\arraycolsep=3pt
  2411. \begin{array}{l}
  2412. \ASTXIntRacket \\
  2413. \begin{array}{lcl}
  2414. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2415. \end{array}
  2416. \end{array}
  2417. \]
  2418. \fi}
  2419. {\if\edition\pythonEd
  2420. \[
  2421. \begin{array}{lcl}
  2422. \Reg &::=& \allastregisters{} \\
  2423. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2424. \MID \DEREF{\Reg}{\Int} \\
  2425. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2426. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2427. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2428. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2429. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2430. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2431. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2432. \end{array}
  2433. \]
  2434. \fi}
  2435. \end{tcolorbox}
  2436. \caption{The abstract syntax of \LangXInt{} assembly.}
  2437. \label{fig:x86-int-ast}
  2438. \end{figure}
  2439. \section{Planning the trip to x86}
  2440. \label{sec:plan-s0-x86}
  2441. To compile one language to another it helps to focus on the
  2442. differences between the two languages because the compiler will need
  2443. to bridge those differences. What are the differences between \LangVar{}
  2444. and x86 assembly? Here are some of the most important ones:
  2445. \begin{enumerate}
  2446. \item x86 arithmetic instructions typically have two arguments and
  2447. update the second argument in place. In contrast, \LangVar{}
  2448. arithmetic operations take two arguments and produce a new value.
  2449. An x86 instruction may have at most one memory-accessing argument.
  2450. Furthermore, some x86 instructions place special restrictions on
  2451. their arguments.
  2452. \item An argument of an \LangVar{} operator can be a deeply-nested
  2453. expression, whereas x86 instructions restrict their arguments to be
  2454. integer constants, registers, and memory locations.
  2455. {\if\edition\racketEd
  2456. \item The order of execution in x86 is explicit in the syntax: a
  2457. sequence of instructions and jumps to labeled positions, whereas in
  2458. \LangVar{} the order of evaluation is a left-to-right depth-first
  2459. traversal of the abstract syntax tree.
  2460. \fi}
  2461. \item A program in \LangVar{} can have any number of variables
  2462. whereas x86 has 16 registers and the procedure call stack.
  2463. {\if\edition\racketEd
  2464. \item Variables in \LangVar{} can shadow other variables with the
  2465. same name. In x86, registers have unique names and memory locations
  2466. have unique addresses.
  2467. \fi}
  2468. \end{enumerate}
  2469. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2470. down the problem into several steps, dealing with the above
  2471. differences one at a time. Each of these steps is called a \emph{pass}
  2472. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2473. %
  2474. This terminology comes from the way each step passes over, or
  2475. traverses, the AST of the program.
  2476. %
  2477. Furthermore, we follow the nanopass approach, which means we strive
  2478. for each pass to accomplish one clear objective (not two or three at
  2479. the same time).
  2480. %
  2481. We begin by sketching how we might implement each pass, and give them
  2482. names. We then figure out an ordering of the passes and the
  2483. input/output language for each pass. The very first pass has
  2484. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2485. its output language. In between we can choose whichever language is
  2486. most convenient for expressing the output of each pass, whether that
  2487. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2488. our own design. Finally, to implement each pass we write one
  2489. recursive function per non-terminal in the grammar of the input
  2490. language of the pass. \index{subject}{intermediate language}
  2491. Our compiler for \LangVar{} consists of the following passes.
  2492. %
  2493. \begin{description}
  2494. {\if\edition\racketEd
  2495. \item[\key{uniquify}] deals with the shadowing of variables by
  2496. renaming every variable to a unique name.
  2497. \fi}
  2498. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2499. of a primitive operation or function call is a variable or integer,
  2500. that is, an \emph{atomic} expression. We refer to non-atomic
  2501. expressions as \emph{complex}. This pass introduces temporary
  2502. variables to hold the results of complex
  2503. subexpressions.\index{subject}{atomic
  2504. expression}\index{subject}{complex expression}%
  2505. {\if\edition\racketEd
  2506. \item[\key{explicate\_control}] makes the execution order of the
  2507. program explicit. It converts the abstract syntax tree
  2508. representation into a graph in which each node is a labeled sequence
  2509. of statements and the edges are \code{goto} statements.
  2510. \fi}
  2511. \item[\key{select\_instructions}] handles the difference between
  2512. \LangVar{} operations and x86 instructions. This pass converts each
  2513. \LangVar{} operation to a short sequence of instructions that
  2514. accomplishes the same task.
  2515. \item[\key{assign\_homes}] replaces variables with registers or stack
  2516. locations.
  2517. \end{description}
  2518. %
  2519. {\if\edition\racketEd
  2520. %
  2521. Our treatment of \code{remove\_complex\_operands} and
  2522. \code{explicate\_control} as separate passes is an example of the
  2523. nanopass approach\footnote{For analogous decompositions of the
  2524. translation into continuation passing style, see the work of
  2525. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2526. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2527. %
  2528. \fi}
  2529. The next question is: in what order should we apply these passes? This
  2530. question can be challenging because it is difficult to know ahead of
  2531. time which orderings will be better (easier to implement, produce more
  2532. efficient code, etc.) so oftentimes trial-and-error is
  2533. involved. Nevertheless, we can plan ahead and make educated choices
  2534. regarding the ordering.
  2535. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2536. \key{uniquify}? The \key{uniquify} pass should come first because
  2537. \key{explicate\_control} changes all the \key{let}-bound variables to
  2538. become local variables whose scope is the entire program, which would
  2539. confuse variables with the same name.}
  2540. %
  2541. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2542. because the later removes the \key{let} form, but it is convenient to
  2543. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2544. %
  2545. \racket{The ordering of \key{uniquify} with respect to
  2546. \key{remove\_complex\_operands} does not matter so we arbitrarily choose
  2547. \key{uniquify} to come first.}
  2548. The \key{select\_instructions} and \key{assign\_homes} passes are
  2549. intertwined.
  2550. %
  2551. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2552. passing arguments to functions and it is preferable to assign
  2553. parameters to their corresponding registers. This suggests that it
  2554. would be better to start with the \key{select\_instructions} pass,
  2555. which generates the instructions for argument passing, before
  2556. performing register allocation.
  2557. %
  2558. On the other hand, by selecting instructions first we may run into a
  2559. dead end in \key{assign\_homes}. Recall that only one argument of an
  2560. x86 instruction may be a memory access but \key{assign\_homes} might
  2561. be forced to assign both arguments to memory locations.
  2562. %
  2563. A sophisticated approach is to repeat the two passes until a solution
  2564. is found. However, to reduce implementation complexity we recommend
  2565. placing \key{select\_instructions} first, followed by the
  2566. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2567. that uses a reserved register to fix outstanding problems.
  2568. \begin{figure}[tbp]
  2569. \begin{tcolorbox}[colback=white]
  2570. {\if\edition\racketEd
  2571. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2572. \node (Lvar) at (0,2) {\large \LangVar{}};
  2573. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2574. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2575. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2576. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2577. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2578. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2579. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2580. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2581. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2582. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2583. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2584. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2585. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2586. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2587. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2588. \end{tikzpicture}
  2589. \fi}
  2590. {\if\edition\pythonEd
  2591. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2592. \node (Lvar) at (0,2) {\large \LangVar{}};
  2593. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2594. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2595. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2596. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2597. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2598. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2599. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2600. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2601. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2602. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2603. \end{tikzpicture}
  2604. \fi}
  2605. \end{tcolorbox}
  2606. \caption{Diagram of the passes for compiling \LangVar{}. }
  2607. \label{fig:Lvar-passes}
  2608. \end{figure}
  2609. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2610. passes and identifies the input and output language of each pass.
  2611. %
  2612. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2613. language, which extends \LangXInt{} with an unbounded number of
  2614. program-scope variables and removes the restrictions regarding
  2615. instruction arguments.
  2616. %
  2617. The last pass, \key{prelude\_and\_conclusion}, places the program
  2618. instructions inside a \code{main} function with instructions for the
  2619. prelude and conclusion.
  2620. %
  2621. \racket{In the next section we discuss the \LangCVar{} intermediate
  2622. language that serves as the output of \code{explicate\_control}.}
  2623. %
  2624. The remainder of this chapter provides guidance on the implementation
  2625. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2626. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2627. %% are programs that are still in the \LangVar{} language, though the
  2628. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2629. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2630. %% %
  2631. %% The output of \code{explicate\_control} is in an intermediate language
  2632. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2633. %% syntax, which we introduce in the next section. The
  2634. %% \key{select-instruction} pass translates from \LangCVar{} to
  2635. %% \LangXVar{}. The \key{assign-homes} and
  2636. %% \key{patch-instructions}
  2637. %% passes input and output variants of x86 assembly.
  2638. \newcommand{\CvarGrammarRacket}{
  2639. \begin{array}{lcl}
  2640. \Atm &::=& \Int \MID \Var \\
  2641. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2642. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2643. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2644. \end{array}
  2645. }
  2646. \newcommand{\CvarASTRacket}{
  2647. \begin{array}{lcl}
  2648. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2649. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2650. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2651. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2652. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2653. \end{array}
  2654. }
  2655. {\if\edition\racketEd
  2656. \subsection{The \LangCVar{} Intermediate Language}
  2657. The output of \code{explicate\_control} is similar to the $C$
  2658. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2659. categories for expressions and statements, so we name it \LangCVar{}.
  2660. This style of intermediate language is also known as
  2661. \emph{three-address code}, to emphasize that the typical form of a
  2662. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2663. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2664. The concrete syntax for \LangCVar{} is defined in
  2665. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2666. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2667. %
  2668. The \LangCVar{} language supports the same operators as \LangVar{} but
  2669. the arguments of operators are restricted to atomic
  2670. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2671. assignment statements which can be executed in sequence using the
  2672. \key{Seq} form. A sequence of statements always ends with
  2673. \key{Return}, a guarantee that is baked into the grammar rules for
  2674. \itm{tail}. The naming of this non-terminal comes from the term
  2675. \emph{tail position}\index{subject}{tail position}, which refers to an
  2676. expression that is the last one to execute within a function or
  2677. program.
  2678. A \LangCVar{} program consists of an alist mapping labels to
  2679. tails. This is more general than necessary for the present chapter, as
  2680. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2681. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2682. there will be just one label, \key{start}, and the whole program is
  2683. its tail.
  2684. %
  2685. The $\itm{info}$ field of the \key{CProgram} form, after the
  2686. \code{explicate\_control} pass, contains a mapping from the symbol
  2687. \key{locals} to a list of variables, that is, a list of all the
  2688. variables used in the program. At the start of the program, these
  2689. variables are uninitialized; they become initialized on their first
  2690. assignment.
  2691. \begin{figure}[tbp]
  2692. \begin{tcolorbox}[colback=white]
  2693. \[
  2694. \begin{array}{l}
  2695. \CvarGrammarRacket \\
  2696. \begin{array}{lcl}
  2697. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2698. \end{array}
  2699. \end{array}
  2700. \]
  2701. \end{tcolorbox}
  2702. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2703. \label{fig:c0-concrete-syntax}
  2704. \end{figure}
  2705. \begin{figure}[tbp]
  2706. \begin{tcolorbox}[colback=white]
  2707. \[
  2708. \begin{array}{l}
  2709. \CvarASTRacket \\
  2710. \begin{array}{lcl}
  2711. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2712. \end{array}
  2713. \end{array}
  2714. \]
  2715. \end{tcolorbox}
  2716. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2717. \label{fig:c0-syntax}
  2718. \end{figure}
  2719. The definitional interpreter for \LangCVar{} is in the support code,
  2720. in the file \code{interp-Cvar.rkt}.
  2721. \fi}
  2722. {\if\edition\racketEd
  2723. \section{Uniquify Variables}
  2724. \label{sec:uniquify-Lvar}
  2725. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2726. programs in which every \key{let} binds a unique variable name. For
  2727. example, the \code{uniquify} pass should translate the program on the
  2728. left into the program on the right.
  2729. \begin{transformation}
  2730. \begin{lstlisting}
  2731. (let ([x 32])
  2732. (+ (let ([x 10]) x) x))
  2733. \end{lstlisting}
  2734. \compilesto
  2735. \begin{lstlisting}
  2736. (let ([x.1 32])
  2737. (+ (let ([x.2 10]) x.2) x.1))
  2738. \end{lstlisting}
  2739. \end{transformation}
  2740. The following is another example translation, this time of a program
  2741. with a \key{let} nested inside the initializing expression of another
  2742. \key{let}.
  2743. \begin{transformation}
  2744. \begin{lstlisting}
  2745. (let ([x (let ([x 4])
  2746. (+ x 1))])
  2747. (+ x 2))
  2748. \end{lstlisting}
  2749. \compilesto
  2750. \begin{lstlisting}
  2751. (let ([x.2 (let ([x.1 4])
  2752. (+ x.1 1))])
  2753. (+ x.2 2))
  2754. \end{lstlisting}
  2755. \end{transformation}
  2756. We recommend implementing \code{uniquify} by creating a structurally
  2757. recursive function named \code{uniquify\_exp} that mostly just copies
  2758. an expression. However, when encountering a \key{let}, it should
  2759. generate a unique name for the variable and associate the old name
  2760. with the new name in an alist.\footnote{The Racket function
  2761. \code{gensym} is handy for generating unique variable names.} The
  2762. \code{uniquify\_exp} function needs to access this alist when it gets
  2763. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2764. for the alist.
  2765. The skeleton of the \code{uniquify\_exp} function is shown in
  2766. Figure~\ref{fig:uniquify-Lvar}.
  2767. %% The function is curried so that it is
  2768. %% convenient to partially apply it to an alist and then apply it to
  2769. %% different expressions, as in the last case for primitive operations in
  2770. %% Figure~\ref{fig:uniquify-Lvar}.
  2771. The
  2772. %
  2773. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2774. %
  2775. form of Racket is useful for transforming the element of a list to
  2776. produce a new list.\index{subject}{for/list}
  2777. \begin{figure}[tbp]
  2778. \begin{tcolorbox}[colback=white]
  2779. \begin{lstlisting}
  2780. (define (uniquify_exp env)
  2781. (lambda (e)
  2782. (match e
  2783. [(Var x) ___]
  2784. [(Int n) (Int n)]
  2785. [(Let x e body) ___]
  2786. [(Prim op es)
  2787. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2788. (define (uniquify p)
  2789. (match p
  2790. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2791. \end{lstlisting}
  2792. \end{tcolorbox}
  2793. \caption{Skeleton for the \key{uniquify} pass.}
  2794. \label{fig:uniquify-Lvar}
  2795. \end{figure}
  2796. \begin{exercise}
  2797. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2798. Complete the \code{uniquify} pass by filling in the blanks in
  2799. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2800. variables and for the \key{let} form in the file \code{compiler.rkt}
  2801. in the support code.
  2802. \end{exercise}
  2803. \begin{exercise}
  2804. \normalfont\normalsize
  2805. \label{ex:Lvar}
  2806. Create five \LangVar{} programs that exercise the most interesting
  2807. parts of the \key{uniquify} pass, that is, the programs should include
  2808. \key{let} forms, variables, and variables that shadow each other.
  2809. The five programs should be placed in the subdirectory named
  2810. \key{tests} and the file names should start with \code{var\_test\_}
  2811. followed by a unique integer and end with the file extension
  2812. \key{.rkt}.
  2813. %
  2814. The \key{run-tests.rkt} script in the support code checks whether the
  2815. output programs produce the same result as the input programs. The
  2816. script uses the \key{interp-tests} function
  2817. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2818. your \key{uniquify} pass on the example programs. The \code{passes}
  2819. parameter of \key{interp-tests} is a list that should have one entry
  2820. for each pass in your compiler. For now, define \code{passes} to
  2821. contain just one entry for \code{uniquify} as shown below.
  2822. \begin{lstlisting}
  2823. (define passes
  2824. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2825. \end{lstlisting}
  2826. Run the \key{run-tests.rkt} script in the support code to check
  2827. whether the output programs produce the same result as the input
  2828. programs.
  2829. \end{exercise}
  2830. \fi}
  2831. \section{Remove Complex Operands}
  2832. \label{sec:remove-complex-opera-Lvar}
  2833. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2834. into a restricted form in which the arguments of operations are atomic
  2835. expressions. Put another way, this pass removes complex
  2836. operands\index{subject}{complex operand}, such as the expression
  2837. \racket{\code{(- 10)}}\python{\code{-10}}
  2838. in the program below. This is accomplished by introducing a new
  2839. temporary variable, assigning the complex operand to the new
  2840. variable, and then using the new variable in place of the complex
  2841. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2842. right.
  2843. {\if\edition\racketEd
  2844. \begin{transformation}
  2845. % var_test_19.rkt
  2846. \begin{lstlisting}
  2847. (let ([x (+ 42 (- 10))])
  2848. (+ x 10))
  2849. \end{lstlisting}
  2850. \compilesto
  2851. \begin{lstlisting}
  2852. (let ([x (let ([tmp.1 (- 10)])
  2853. (+ 42 tmp.1))])
  2854. (+ x 10))
  2855. \end{lstlisting}
  2856. \end{transformation}
  2857. \fi}
  2858. {\if\edition\pythonEd
  2859. \begin{transformation}
  2860. \begin{lstlisting}
  2861. x = 42 + -10
  2862. print(x + 10)
  2863. \end{lstlisting}
  2864. \compilesto
  2865. \begin{lstlisting}
  2866. tmp_0 = -10
  2867. x = 42 + tmp_0
  2868. tmp_1 = x + 10
  2869. print(tmp_1)
  2870. \end{lstlisting}
  2871. \end{transformation}
  2872. \fi}
  2873. \newcommand{\LvarMonadASTRacket}{
  2874. \begin{array}{rcl}
  2875. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2876. \Exp &::=& \Atm \MID \READ{} \\
  2877. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2878. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2879. \end{array}
  2880. }
  2881. \newcommand{\LvarMonadASTPython}{
  2882. \begin{array}{rcl}
  2883. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2884. \Exp{} &::=& \Atm \MID \READ{} \\
  2885. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2886. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2887. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2888. \end{array}
  2889. }
  2890. \begin{figure}[tp]
  2891. \centering
  2892. \begin{tcolorbox}[colback=white]
  2893. {\if\edition\racketEd
  2894. \[
  2895. \begin{array}{l}
  2896. \LvarMonadASTRacket \\
  2897. \begin{array}{rcl}
  2898. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2899. \end{array}
  2900. \end{array}
  2901. \]
  2902. \fi}
  2903. {\if\edition\pythonEd
  2904. \[
  2905. \begin{array}{l}
  2906. \LvarMonadASTPython \\
  2907. \begin{array}{rcl}
  2908. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2909. \end{array}
  2910. \end{array}
  2911. \]
  2912. \fi}
  2913. \end{tcolorbox}
  2914. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2915. atomic expressions.}
  2916. \label{fig:Lvar-anf-syntax}
  2917. \end{figure}
  2918. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2919. of this pass, the language \LangVarANF{}. The only difference is that
  2920. operator arguments are restricted to be atomic expressions that are
  2921. defined by the \Atm{} non-terminal. In particular, integer constants
  2922. and variables are atomic.
  2923. The atomic expressions are pure (they do not cause or depend on
  2924. side-effects) whereas complex expressions may have side effects, such
  2925. as \READ{}. A language with this separation between pure versus
  2926. side-effecting expressions is said to be in monadic normal
  2927. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2928. in the name \LangVarANF{}. An important invariant of the
  2929. \code{remove\_complex\_operands} pass is that the relative ordering
  2930. among complex expressions is not changed, but the relative ordering
  2931. between atomic expressions and complex expressions can change and
  2932. often does. The reason that these changes are behavior preserving is
  2933. that the atomic expressions are pure.
  2934. Another well-known form for intermediate languages is the
  2935. \emph{administrative normal form}
  2936. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2937. \index{subject}{administrative normal form} \index{subject}{ANF}
  2938. %
  2939. The \LangVarANF{} language is not quite in ANF because we allow the
  2940. right-hand side of a \code{let} to be a complex expression.
  2941. {\if\edition\racketEd
  2942. We recommend implementing this pass with two mutually recursive
  2943. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2944. \code{rco\_atom} to subexpressions that need to become atomic and to
  2945. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2946. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2947. returns an expression. The \code{rco\_atom} function returns two
  2948. things: an atomic expression and an alist mapping temporary variables to
  2949. complex subexpressions. You can return multiple things from a function
  2950. using Racket's \key{values} form and you can receive multiple things
  2951. from a function call using the \key{define-values} form.
  2952. \fi}
  2953. %
  2954. {\if\edition\pythonEd
  2955. %
  2956. We recommend implementing this pass with an auxiliary method named
  2957. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2958. Boolean that specifies whether the expression needs to become atomic
  2959. or not. The \code{rco\_exp} method should return a pair consisting of
  2960. the new expression and a list of pairs, associating new temporary
  2961. variables with their initializing expressions.
  2962. %
  2963. \fi}
  2964. {\if\edition\racketEd
  2965. %
  2966. Returning to the example program with the expression \code{(+ 42 (-
  2967. 10))}, the subexpression \code{(- 10)} should be processed using the
  2968. \code{rco\_atom} function because it is an argument of the \code{+}
  2969. operator and therefore needs to become atomic. The output of
  2970. \code{rco\_atom} applied to \code{(- 10)} is as follows.
  2971. \begin{transformation}
  2972. \begin{lstlisting}
  2973. (- 10)
  2974. \end{lstlisting}
  2975. \compilesto
  2976. \begin{lstlisting}
  2977. tmp.1
  2978. ((tmp.1 . (- 10)))
  2979. \end{lstlisting}
  2980. \end{transformation}
  2981. \fi}
  2982. %
  2983. {\if\edition\pythonEd
  2984. %
  2985. Returning to the example program with the expression \code{42 + -10},
  2986. the subexpression \code{-10} should be processed using the
  2987. \code{rco\_exp} function with \code{True} as the second argument
  2988. because \code{-10} is an argument of the \code{+} operator and
  2989. therefore needs to become atomic. The output of \code{rco\_exp}
  2990. applied to \code{-10} is as follows.
  2991. \begin{transformation}
  2992. \begin{lstlisting}
  2993. -10
  2994. \end{lstlisting}
  2995. \compilesto
  2996. \begin{lstlisting}
  2997. tmp_1
  2998. [(tmp_1, -10)]
  2999. \end{lstlisting}
  3000. \end{transformation}
  3001. %
  3002. \fi}
  3003. Take special care of programs such as the following that
  3004. %
  3005. \racket{bind a variable to an atomic expression.}
  3006. %
  3007. \python{assign an atomic expression to a variable.}
  3008. %
  3009. You should leave such \racket{variable bindings}\python{assignments}
  3010. unchanged, as shown in the program on the right\\
  3011. %
  3012. {\if\edition\racketEd
  3013. \begin{transformation}
  3014. % var_test_20.rkt
  3015. \begin{lstlisting}
  3016. (let ([a 42])
  3017. (let ([b a])
  3018. b))
  3019. \end{lstlisting}
  3020. \compilesto
  3021. \begin{lstlisting}
  3022. (let ([a 42])
  3023. (let ([b a])
  3024. b))
  3025. \end{lstlisting}
  3026. \end{transformation}
  3027. \fi}
  3028. {\if\edition\pythonEd
  3029. \begin{transformation}
  3030. \begin{lstlisting}
  3031. a = 42
  3032. b = a
  3033. print(b)
  3034. \end{lstlisting}
  3035. \compilesto
  3036. \begin{lstlisting}
  3037. a = 42
  3038. b = a
  3039. print(b)
  3040. \end{lstlisting}
  3041. \end{transformation}
  3042. \fi}
  3043. %
  3044. \noindent A careless implementation might produce the following output with
  3045. unnecessary temporary variables.
  3046. \begin{center}
  3047. \begin{minipage}{0.4\textwidth}
  3048. {\if\edition\racketEd
  3049. \begin{lstlisting}
  3050. (let ([tmp.1 42])
  3051. (let ([a tmp.1])
  3052. (let ([tmp.2 a])
  3053. (let ([b tmp.2])
  3054. b))))
  3055. \end{lstlisting}
  3056. \fi}
  3057. {\if\edition\pythonEd
  3058. \begin{lstlisting}
  3059. tmp_1 = 42
  3060. a = tmp_1
  3061. tmp_2 = a
  3062. b = tmp_2
  3063. print(b)
  3064. \end{lstlisting}
  3065. \fi}
  3066. \end{minipage}
  3067. \end{center}
  3068. \begin{exercise}
  3069. \normalfont\normalsize
  3070. {\if\edition\racketEd
  3071. Implement the \code{remove\_complex\_operands} function in
  3072. \code{compiler.rkt}.
  3073. %
  3074. Create three new \LangVar{} programs that exercise the interesting
  3075. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3076. regarding file names described in Exercise~\ref{ex:Lvar}.
  3077. %
  3078. In the \code{run-tests.rkt} script, add the following entry to the
  3079. list of \code{passes} and then run the script to test your compiler.
  3080. \begin{lstlisting}
  3081. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3082. \end{lstlisting}
  3083. While debugging your compiler, it is often useful to see the
  3084. intermediate programs that are output from each pass. To print the
  3085. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3086. \code{interp-tests} in \code{run-tests.rkt}.
  3087. \fi}
  3088. %
  3089. {\if\edition\pythonEd
  3090. Implement the \code{remove\_complex\_operands} pass in
  3091. \code{compiler.py}, creating auxiliary functions for each
  3092. non-terminal in the grammar, i.e., \code{rco\_exp}
  3093. and \code{rco\_stmt}. We recommend you use the function
  3094. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3095. \fi}
  3096. \end{exercise}
  3097. {\if\edition\pythonEd
  3098. \begin{exercise}
  3099. \normalfont\normalsize
  3100. \label{ex:Lvar}
  3101. Create five \LangVar{} programs that exercise the most interesting
  3102. parts of the \code{remove\_complex\_operands} pass. The five programs
  3103. should be placed in the subdirectory named \key{tests} and the file
  3104. names should start with \code{var\_test\_} followed by a unique
  3105. integer and end with the file extension \key{.py}.
  3106. %% The \key{run-tests.rkt} script in the support code checks whether the
  3107. %% output programs produce the same result as the input programs. The
  3108. %% script uses the \key{interp-tests} function
  3109. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3110. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3111. %% parameter of \key{interp-tests} is a list that should have one entry
  3112. %% for each pass in your compiler. For now, define \code{passes} to
  3113. %% contain just one entry for \code{uniquify} as shown below.
  3114. %% \begin{lstlisting}
  3115. %% (define passes
  3116. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3117. %% \end{lstlisting}
  3118. Run the \key{run-tests.py} script in the support code to check
  3119. whether the output programs produce the same result as the input
  3120. programs.
  3121. \end{exercise}
  3122. \fi}
  3123. {\if\edition\racketEd
  3124. \section{Explicate Control}
  3125. \label{sec:explicate-control-Lvar}
  3126. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3127. programs that make the order of execution explicit in their
  3128. syntax. For now this amounts to flattening \key{let} constructs into a
  3129. sequence of assignment statements. For example, consider the following
  3130. \LangVar{} program.\\
  3131. % var_test_11.rkt
  3132. \begin{minipage}{0.96\textwidth}
  3133. \begin{lstlisting}
  3134. (let ([y (let ([x 20])
  3135. (+ x (let ([x 22]) x)))])
  3136. y)
  3137. \end{lstlisting}
  3138. \end{minipage}\\
  3139. %
  3140. The output of the previous pass is shown below, on the left, and the
  3141. output of \code{explicate\_control} is on the right. Recall that the
  3142. right-hand-side of a \key{let} executes before its body, so the order
  3143. of evaluation for this program is to assign \code{20} to \code{x.1},
  3144. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, then
  3145. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3146. this ordering explicit.
  3147. \begin{transformation}
  3148. \begin{lstlisting}
  3149. (let ([y (let ([x.1 20])
  3150. (let ([x.2 22])
  3151. (+ x.1 x.2)))])
  3152. y)
  3153. \end{lstlisting}
  3154. \compilesto
  3155. \begin{lstlisting}[language=C]
  3156. start:
  3157. x.1 = 20;
  3158. x.2 = 22;
  3159. y = (+ x.1 x.2);
  3160. return y;
  3161. \end{lstlisting}
  3162. \end{transformation}
  3163. \begin{figure}[tbp]
  3164. \begin{tcolorbox}[colback=white]
  3165. \begin{lstlisting}
  3166. (define (explicate_tail e)
  3167. (match e
  3168. [(Var x) ___]
  3169. [(Int n) (Return (Int n))]
  3170. [(Let x rhs body) ___]
  3171. [(Prim op es) ___]
  3172. [else (error "explicate_tail unhandled case" e)]))
  3173. (define (explicate_assign e x cont)
  3174. (match e
  3175. [(Var x) ___]
  3176. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3177. [(Let y rhs body) ___]
  3178. [(Prim op es) ___]
  3179. [else (error "explicate_assign unhandled case" e)]))
  3180. (define (explicate_control p)
  3181. (match p
  3182. [(Program info body) ___]))
  3183. \end{lstlisting}
  3184. \end{tcolorbox}
  3185. \caption{Skeleton for the \code{explicate\_control} pass.}
  3186. \label{fig:explicate-control-Lvar}
  3187. \end{figure}
  3188. The organization of this pass depends on the notion of tail position
  3189. that we have alluded to earlier. Here is the definition.
  3190. \begin{definition}
  3191. The following rules define when an expression is in \textbf{\emph{tail
  3192. position}}\index{subject}{tail position} for the language \LangVar{}.
  3193. \begin{enumerate}
  3194. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3195. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3196. \end{enumerate}
  3197. \end{definition}
  3198. We recommend implementing \code{explicate\_control} using two
  3199. recursive functions, \code{explicate\_tail} and
  3200. \code{explicate\_assign}, as suggested in the skeleton code in
  3201. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3202. function should be applied to expressions in tail position whereas the
  3203. \code{explicate\_assign} should be applied to expressions that occur on
  3204. the right-hand-side of a \key{let}.
  3205. %
  3206. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3207. input and produces a \Tail{} in \LangCVar{} (see
  3208. Figure~\ref{fig:c0-syntax}).
  3209. %
  3210. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3211. the variable that it is to be assigned to, and a \Tail{} in
  3212. \LangCVar{} for the code that comes after the assignment. The
  3213. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3214. The \code{explicate\_assign} function is in accumulator-passing style:
  3215. the \code{cont} parameter is used for accumulating the output. This
  3216. accumulator-passing style plays an important role in how we generate
  3217. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3218. The abbreviation \code{cont} is for continuation because it contains
  3219. the generated code that should come after the current assignment.
  3220. This code organization is also related to continuation-passing style,
  3221. except that \code{cont} is not what happens next during compilation,
  3222. but what happens next in the generated code.
  3223. \begin{exercise}\normalfont\normalsize
  3224. %
  3225. Implement the \code{explicate\_control} function in
  3226. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3227. exercise the code in \code{explicate\_control}.
  3228. %
  3229. In the \code{run-tests.rkt} script, add the following entry to the
  3230. list of \code{passes} and then run the script to test your compiler.
  3231. \begin{lstlisting}
  3232. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3233. \end{lstlisting}
  3234. \end{exercise}
  3235. \fi}
  3236. \section{Select Instructions}
  3237. \label{sec:select-Lvar}
  3238. \index{subject}{instruction selection}
  3239. In the \code{select\_instructions} pass we begin the work of
  3240. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3241. language of this pass is a variant of x86 that still uses variables,
  3242. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3243. non-terminal of the \LangXInt{} abstract syntax
  3244. (Figure~\ref{fig:x86-int-ast}).
  3245. \racket{We recommend implementing the
  3246. \code{select\_instructions} with three auxiliary functions, one for
  3247. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3248. $\Tail$.}
  3249. \python{We recommend implementing an auxiliary function
  3250. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3251. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3252. same and integer constants change to immediates, that is, $\INT{n}$
  3253. changes to $\IMM{n}$.}
  3254. Next consider the cases for the $\Stmt$ non-terminal, starting with
  3255. arithmetic operations. For example, consider the addition operation
  3256. below, on the left side. There is an \key{addq} instruction in x86,
  3257. but it performs an in-place update. So we could move $\Arg_1$
  3258. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3259. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3260. $\Atm_1$ and $\Atm_2$ respectively.
  3261. \begin{transformation}
  3262. {\if\edition\racketEd
  3263. \begin{lstlisting}
  3264. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3265. \end{lstlisting}
  3266. \fi}
  3267. {\if\edition\pythonEd
  3268. \begin{lstlisting}
  3269. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3270. \end{lstlisting}
  3271. \fi}
  3272. \compilesto
  3273. \begin{lstlisting}
  3274. movq |$\Arg_1$|, |$\itm{var}$|
  3275. addq |$\Arg_2$|, |$\itm{var}$|
  3276. \end{lstlisting}
  3277. \end{transformation}
  3278. There are also cases that require special care to avoid generating
  3279. needlessly complicated code. For example, if one of the arguments of
  3280. the addition is the same variable as the left-hand side of the
  3281. assignment, as shown below, then there is no need for the extra move
  3282. instruction. The assignment statement can be translated into a single
  3283. \key{addq} instruction as follows.
  3284. \begin{transformation}
  3285. {\if\edition\racketEd
  3286. \begin{lstlisting}
  3287. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3288. \end{lstlisting}
  3289. \fi}
  3290. {\if\edition\pythonEd
  3291. \begin{lstlisting}
  3292. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3293. \end{lstlisting}
  3294. \fi}
  3295. \compilesto
  3296. \begin{lstlisting}
  3297. addq |$\Arg_1$|, |$\itm{var}$|
  3298. \end{lstlisting}
  3299. \end{transformation}
  3300. The \READOP{} operation does not have a direct counterpart in x86
  3301. assembly, so we provide this functionality with the function
  3302. \code{read\_int} in the file \code{runtime.c}, written in
  3303. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3304. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3305. system}, or simply the \emph{runtime} for short. When compiling your
  3306. generated x86 assembly code, you need to compile \code{runtime.c} to
  3307. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3308. \code{-c}) and link it into the executable. For our purposes of code
  3309. generation, all you need to do is translate an assignment of
  3310. \READOP{} into a call to the \code{read\_int} function followed by a
  3311. move from \code{rax} to the left-hand-side variable. (Recall that the
  3312. return value of a function goes into \code{rax}.)
  3313. \begin{transformation}
  3314. {\if\edition\racketEd
  3315. \begin{lstlisting}
  3316. |$\itm{var}$| = (read);
  3317. \end{lstlisting}
  3318. \fi}
  3319. {\if\edition\pythonEd
  3320. \begin{lstlisting}
  3321. |$\itm{var}$| = input_int();
  3322. \end{lstlisting}
  3323. \fi}
  3324. \compilesto
  3325. \begin{lstlisting}
  3326. callq read_int
  3327. movq %rax, |$\itm{var}$|
  3328. \end{lstlisting}
  3329. \end{transformation}
  3330. {\if\edition\pythonEd
  3331. %
  3332. Similarly, we translate the \code{print} operation, shown below, into
  3333. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3334. In x86, the first six arguments to functions are passed in registers,
  3335. with the first argument passed in register \code{rdi}. So we move the
  3336. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3337. \code{callq} instruction.
  3338. \begin{transformation}
  3339. \begin{lstlisting}
  3340. print(|$\Atm$|)
  3341. \end{lstlisting}
  3342. \compilesto
  3343. \begin{lstlisting}
  3344. movq |$\Arg$|, %rdi
  3345. callq print_int
  3346. \end{lstlisting}
  3347. \end{transformation}
  3348. %
  3349. \fi}
  3350. {\if\edition\racketEd
  3351. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3352. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3353. assignment to the \key{rax} register followed by a jump to the
  3354. conclusion of the program (so the conclusion needs to be labeled).
  3355. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3356. recursively and then append the resulting instructions.
  3357. \fi}
  3358. {\if\edition\pythonEd
  3359. We recommend that you use the function \code{utils.label\_name()} to
  3360. transform a string into an label argument suitably suitable for, e.g.,
  3361. the target of the \code{callq} instruction. This practice makes your
  3362. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3363. all labels.
  3364. \fi}
  3365. \begin{exercise}
  3366. \normalfont\normalsize
  3367. {\if\edition\racketEd
  3368. Implement the \code{select\_instructions} pass in
  3369. \code{compiler.rkt}. Create three new example programs that are
  3370. designed to exercise all of the interesting cases in this pass.
  3371. %
  3372. In the \code{run-tests.rkt} script, add the following entry to the
  3373. list of \code{passes} and then run the script to test your compiler.
  3374. \begin{lstlisting}
  3375. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3376. \end{lstlisting}
  3377. \fi}
  3378. {\if\edition\pythonEd
  3379. Implement the \key{select\_instructions} pass in
  3380. \code{compiler.py}. Create three new example programs that are
  3381. designed to exercise all of the interesting cases in this pass.
  3382. Run the \code{run-tests.py} script to to check
  3383. whether the output programs produce the same result as the input
  3384. programs.
  3385. \fi}
  3386. \end{exercise}
  3387. \section{Assign Homes}
  3388. \label{sec:assign-Lvar}
  3389. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3390. \LangXVar{} programs that no longer use program variables.
  3391. Thus, the \code{assign\_homes} pass is responsible for placing all of
  3392. the program variables in registers or on the stack. For runtime
  3393. efficiency, it is better to place variables in registers, but as there
  3394. are only 16 registers, some programs must necessarily resort to
  3395. placing some variables on the stack. In this chapter we focus on the
  3396. mechanics of placing variables on the stack. We study an algorithm for
  3397. placing variables in registers in
  3398. Chapter~\ref{ch:register-allocation-Lvar}.
  3399. Consider again the following \LangVar{} program from
  3400. Section~\ref{sec:remove-complex-opera-Lvar}.
  3401. % var_test_20.rkt
  3402. {\if\edition\racketEd
  3403. \begin{lstlisting}
  3404. (let ([a 42])
  3405. (let ([b a])
  3406. b))
  3407. \end{lstlisting}
  3408. \fi}
  3409. {\if\edition\pythonEd
  3410. \begin{lstlisting}
  3411. a = 42
  3412. b = a
  3413. print(b)
  3414. \end{lstlisting}
  3415. \fi}
  3416. %
  3417. The output of \code{select\_instructions} is shown below, on the left,
  3418. and the output of \code{assign\_homes} is on the right. In this
  3419. example, we assign variable \code{a} to stack location
  3420. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3421. \begin{transformation}
  3422. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3423. movq $42, a
  3424. movq a, b
  3425. movq b, %rax
  3426. \end{lstlisting}
  3427. \compilesto
  3428. %stack-space: 16
  3429. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3430. movq $42, -8(%rbp)
  3431. movq -8(%rbp), -16(%rbp)
  3432. movq -16(%rbp), %rax
  3433. \end{lstlisting}
  3434. \end{transformation}
  3435. \racket{
  3436. The \code{assign\_homes} pass should replace all variables
  3437. with stack locations.
  3438. The list of variables can be obtain from
  3439. the \code{locals-types} entry in the $\itm{info}$ of the
  3440. \code{X86Program} node. The \code{locals-types} entry is an alist
  3441. mapping all the variables in the program to their types
  3442. (for now just \code{Integer}).
  3443. As an aside, the \code{locals-types} entry is
  3444. computed by \code{type-check-Cvar} in the support code, which
  3445. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3446. which you should propagate to the \code{X86Program} node.}
  3447. %
  3448. \python{The \code{assign\_homes} pass should replace all uses of
  3449. variables with stack locations.}
  3450. %
  3451. In the process of assigning variables to stack locations, it is
  3452. convenient for you to compute and store the size of the frame (in
  3453. bytes) in
  3454. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3455. %
  3456. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3457. %
  3458. which is needed later to generate the conclusion of the \code{main}
  3459. procedure. The x86-64 standard requires the frame size to be a
  3460. multiple of 16 bytes.\index{subject}{frame}
  3461. % TODO: store the number of variables instead? -Jeremy
  3462. \begin{exercise}\normalfont\normalsize
  3463. Implement the \code{assign\_homes} pass in
  3464. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3465. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3466. grammar. We recommend that the auxiliary functions take an extra
  3467. parameter that maps variable names to homes (stack locations for now).
  3468. %
  3469. {\if\edition\racketEd
  3470. In the \code{run-tests.rkt} script, add the following entry to the
  3471. list of \code{passes} and then run the script to test your compiler.
  3472. \begin{lstlisting}
  3473. (list "assign homes" assign-homes interp_x86-0)
  3474. \end{lstlisting}
  3475. \fi}
  3476. {\if\edition\pythonEd
  3477. Run the \code{run-tests.py} script to to check
  3478. whether the output programs produce the same result as the input
  3479. programs.
  3480. \fi}
  3481. \end{exercise}
  3482. \section{Patch Instructions}
  3483. \label{sec:patch-s0}
  3484. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3485. \LangXInt{} by making sure that each instruction adheres to the
  3486. restriction that at most one argument of an instruction may be a
  3487. memory reference.
  3488. We return to the following example.\\
  3489. \begin{minipage}{0.5\textwidth}
  3490. % var_test_20.rkt
  3491. {\if\edition\racketEd
  3492. \begin{lstlisting}
  3493. (let ([a 42])
  3494. (let ([b a])
  3495. b))
  3496. \end{lstlisting}
  3497. \fi}
  3498. {\if\edition\pythonEd
  3499. \begin{lstlisting}
  3500. a = 42
  3501. b = a
  3502. print(b)
  3503. \end{lstlisting}
  3504. \fi}
  3505. \end{minipage}\\
  3506. The \code{assign\_homes} pass produces the following translation. \\
  3507. \begin{minipage}{0.5\textwidth}
  3508. {\if\edition\racketEd
  3509. \begin{lstlisting}
  3510. movq $42, -8(%rbp)
  3511. movq -8(%rbp), -16(%rbp)
  3512. movq -16(%rbp), %rax
  3513. \end{lstlisting}
  3514. \fi}
  3515. {\if\edition\pythonEd
  3516. \begin{lstlisting}
  3517. movq 42, -8(%rbp)
  3518. movq -8(%rbp), -16(%rbp)
  3519. movq -16(%rbp), %rdi
  3520. callq print_int
  3521. \end{lstlisting}
  3522. \fi}
  3523. \end{minipage}\\
  3524. The second \key{movq} instruction is problematic because both
  3525. arguments are stack locations. We suggest fixing this problem by
  3526. moving from the source location to the register \key{rax} and then
  3527. from \key{rax} to the destination location, as follows.
  3528. \begin{lstlisting}
  3529. movq -8(%rbp), %rax
  3530. movq %rax, -16(%rbp)
  3531. \end{lstlisting}
  3532. \begin{exercise}
  3533. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3534. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3535. Create three new example programs that are
  3536. designed to exercise all of the interesting cases in this pass.
  3537. %
  3538. {\if\edition\racketEd
  3539. In the \code{run-tests.rkt} script, add the following entry to the
  3540. list of \code{passes} and then run the script to test your compiler.
  3541. \begin{lstlisting}
  3542. (list "patch instructions" patch_instructions interp_x86-0)
  3543. \end{lstlisting}
  3544. \fi}
  3545. {\if\edition\pythonEd
  3546. Run the \code{run-tests.py} script to to check
  3547. whether the output programs produce the same result as the input
  3548. programs.
  3549. \fi}
  3550. \end{exercise}
  3551. \section{Generate Prelude and Conclusion}
  3552. \label{sec:print-x86}
  3553. \index{subject}{prelude}\index{subject}{conclusion}
  3554. The last step of the compiler from \LangVar{} to x86 is to generate
  3555. the \code{main} function with a prelude and conclusion wrapped around
  3556. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3557. discussed in Section~\ref{sec:x86}.
  3558. When running on Mac OS X, your compiler should prefix an underscore to
  3559. all labels, e.g., changing \key{main} to \key{\_main}.
  3560. %
  3561. \racket{The Racket call \code{(system-type 'os)} is useful for
  3562. determining which operating system the compiler is running on. It
  3563. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3564. %
  3565. \python{The Python \code{platform} library includes a \code{system()}
  3566. function that returns \code{'Linux'}, \code{'Windows'}, or
  3567. \code{'Darwin'} (for Mac).}
  3568. \begin{exercise}\normalfont\normalsize
  3569. %
  3570. Implement the \key{prelude\_and\_conclusion} pass in
  3571. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3572. %
  3573. {\if\edition\racketEd
  3574. In the \code{run-tests.rkt} script, add the following entry to the
  3575. list of \code{passes} and then run the script to test your compiler.
  3576. \begin{lstlisting}
  3577. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3578. \end{lstlisting}
  3579. %
  3580. Uncomment the call to the \key{compiler-tests} function
  3581. (Appendix~\ref{appendix:utilities}), which tests your complete
  3582. compiler by executing the generated x86 code. It translates the x86
  3583. AST that you produce into a string by invoking the \code{print-x86}
  3584. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3585. the provided \key{runtime.c} file to \key{runtime.o} using
  3586. \key{gcc}. Run the script to test your compiler.
  3587. %
  3588. \fi}
  3589. {\if\edition\pythonEd
  3590. %
  3591. Run the \code{run-tests.py} script to to check whether the output
  3592. programs produce the same result as the input programs. That script
  3593. translates the x86 AST that you produce into a string by invoking the
  3594. \code{repr} method that is implemented by the x86 AST classes in
  3595. \code{x86\_ast.py}.
  3596. %
  3597. \fi}
  3598. \end{exercise}
  3599. \section{Challenge: Partial Evaluator for \LangVar{}}
  3600. \label{sec:pe-Lvar}
  3601. \index{subject}{partial evaluation}
  3602. This section describes two optional challenge exercises that involve
  3603. adapting and improving the partial evaluator for \LangInt{} that was
  3604. introduced in Section~\ref{sec:partial-evaluation}.
  3605. \begin{exercise}\label{ex:pe-Lvar}
  3606. \normalfont\normalsize
  3607. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3608. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3609. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3610. %
  3611. \racket{\key{let} binding}\python{assignment}
  3612. %
  3613. to the \LangInt{} language, so you will need to add cases for them in
  3614. the \code{pe\_exp}
  3615. %
  3616. \racket{function.}
  3617. %
  3618. \python{and \code{pe\_stmt} functions.}
  3619. %
  3620. Once complete, add the partial evaluation pass to the front of your
  3621. compiler and make sure that your compiler still passes all of the
  3622. tests.
  3623. \end{exercise}
  3624. \begin{exercise}
  3625. \normalfont\normalsize
  3626. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3627. \code{pe\_add} auxiliary functions with functions that know more about
  3628. arithmetic. For example, your partial evaluator should translate
  3629. {\if\edition\racketEd
  3630. \[
  3631. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3632. \code{(+ 2 (read))}
  3633. \]
  3634. \fi}
  3635. {\if\edition\pythonEd
  3636. \[
  3637. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3638. \code{2 + input\_int()}
  3639. \]
  3640. \fi}
  3641. To accomplish this, the \code{pe\_exp} function should produce output
  3642. in the form of the $\itm{residual}$ non-terminal of the following
  3643. grammar. The idea is that when processing an addition expression, we
  3644. can always produce either 1) an integer constant, 2) an addition
  3645. expression with an integer constant on the left-hand side but not the
  3646. right-hand side, or 3) or an addition expression in which neither
  3647. subexpression is a constant.
  3648. {\if\edition\racketEd
  3649. \[
  3650. \begin{array}{lcl}
  3651. \itm{inert} &::=& \Var
  3652. \MID \LP\key{read}\RP
  3653. \MID \LP\key{-} ~\Var\RP
  3654. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3655. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3656. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3657. \itm{residual} &::=& \Int
  3658. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3659. \MID \itm{inert}
  3660. \end{array}
  3661. \]
  3662. \fi}
  3663. {\if\edition\pythonEd
  3664. \[
  3665. \begin{array}{lcl}
  3666. \itm{inert} &::=& \Var
  3667. \MID \key{input\_int}\LP\RP
  3668. \MID \key{-} \Var
  3669. \MID \key{-} \key{input\_int}\LP\RP
  3670. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3671. \itm{residual} &::=& \Int
  3672. \MID \Int ~ \key{+} ~ \itm{inert}
  3673. \MID \itm{inert}
  3674. \end{array}
  3675. \]
  3676. \fi}
  3677. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3678. inputs are $\itm{residual}$ expressions and they should return
  3679. $\itm{residual}$ expressions. Once the improvements are complete,
  3680. make sure that your compiler still passes all of the tests. After
  3681. all, fast code is useless if it produces incorrect results!
  3682. \end{exercise}
  3683. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3684. \chapter{Register Allocation}
  3685. \label{ch:register-allocation-Lvar}
  3686. \index{subject}{register allocation}
  3687. In Chapter~\ref{ch:Lvar} we compiled \LangVar{} to x86, storing
  3688. variables on the procedure call stack. It can take 10s to 100s of
  3689. cycles for the CPU to access locations on the stack whereas accessing
  3690. a register takes only a single cycle. In this chapter we improve the
  3691. efficiency of our generated code by storing some variables in
  3692. registers. The goal of register allocation is to fit as many variables
  3693. into registers as possible. Some programs have more variables than
  3694. registers so we cannot always map each variable to a different
  3695. register. Fortunately, it is common for different variables to be
  3696. in-use during different periods of time during program execution, and
  3697. in those cases we can map multiple variables to the same register.
  3698. The program in Figure~\ref{fig:reg-eg} serves as a running
  3699. example. The source program is on the left and the output of
  3700. instruction selection is on the right. The program is almost in the
  3701. x86 assembly language but it still uses variables. Consider variables
  3702. \code{x} and \code{z}. After the variable \code{x} is moved to
  3703. \code{z} it is no longer in-use. Variable \code{z}, on the other
  3704. hand, is used only after this point, so \code{x} and \code{z} could
  3705. share the same register.
  3706. \begin{figure}
  3707. \begin{tcolorbox}[colback=white]
  3708. \begin{minipage}{0.45\textwidth}
  3709. Example \LangVar{} program:
  3710. % var_test_28.rkt
  3711. {\if\edition\racketEd
  3712. \begin{lstlisting}
  3713. (let ([v 1])
  3714. (let ([w 42])
  3715. (let ([x (+ v 7)])
  3716. (let ([y x])
  3717. (let ([z (+ x w)])
  3718. (+ z (- y)))))))
  3719. \end{lstlisting}
  3720. \fi}
  3721. {\if\edition\pythonEd
  3722. \begin{lstlisting}
  3723. v = 1
  3724. w = 42
  3725. x = v + 7
  3726. y = x
  3727. z = x + w
  3728. print(z + (- y))
  3729. \end{lstlisting}
  3730. \fi}
  3731. \end{minipage}
  3732. \begin{minipage}{0.45\textwidth}
  3733. After instruction selection:
  3734. {\if\edition\racketEd
  3735. \begin{lstlisting}
  3736. locals-types:
  3737. x : Integer, y : Integer,
  3738. z : Integer, t : Integer,
  3739. v : Integer, w : Integer
  3740. start:
  3741. movq $1, v
  3742. movq $42, w
  3743. movq v, x
  3744. addq $7, x
  3745. movq x, y
  3746. movq x, z
  3747. addq w, z
  3748. movq y, t
  3749. negq t
  3750. movq z, %rax
  3751. addq t, %rax
  3752. jmp conclusion
  3753. \end{lstlisting}
  3754. \fi}
  3755. {\if\edition\pythonEd
  3756. \begin{lstlisting}
  3757. movq $1, v
  3758. movq $42, w
  3759. movq v, x
  3760. addq $7, x
  3761. movq x, y
  3762. movq x, z
  3763. addq w, z
  3764. movq y, tmp_0
  3765. negq tmp_0
  3766. movq z, tmp_1
  3767. addq tmp_0, tmp_1
  3768. movq tmp_1, %rdi
  3769. callq print_int
  3770. \end{lstlisting}
  3771. \fi}
  3772. \end{minipage}
  3773. \end{tcolorbox}
  3774. \caption{A running example for register allocation.}
  3775. \label{fig:reg-eg}
  3776. \end{figure}
  3777. The topic of Section~\ref{sec:liveness-analysis-Lvar} is how to
  3778. compute where a variable is in-use. Once we have that information, we
  3779. compute which variables are in-use at the same time, i.e., which ones
  3780. \emph{interfere}\index{subject}{interfere} with each other, and
  3781. represent this relation as an undirected graph whose vertices are
  3782. variables and edges indicate when two variables interfere
  3783. (Section~\ref{sec:build-interference}). We then model register
  3784. allocation as a graph coloring problem
  3785. (Section~\ref{sec:graph-coloring}).
  3786. If we run out of registers despite these efforts, we place the
  3787. remaining variables on the stack, similar to what we did in
  3788. Chapter~\ref{ch:Lvar}. It is common to use the verb
  3789. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3790. location. The decision to spill a variable is handled as part of the
  3791. graph coloring process.
  3792. We make the simplifying assumption that each variable is assigned to
  3793. one location (a register or stack address). A more sophisticated
  3794. approach is to assign a variable to one or more locations in different
  3795. regions of the program. For example, if a variable is used many times
  3796. in short sequence and then only used again after many other
  3797. instructions, it could be more efficient to assign the variable to a
  3798. register during the initial sequence and then move it to the stack for
  3799. the rest of its lifetime. We refer the interested reader to
  3800. \citet{Cooper:2011aa} (Chapter 13) for more information about that
  3801. approach.
  3802. % discuss prioritizing variables based on how much they are used.
  3803. \section{Registers and Calling Conventions}
  3804. \label{sec:calling-conventions}
  3805. \index{subject}{calling conventions}
  3806. As we perform register allocation, we must be aware of the
  3807. \emph{calling conventions} \index{subject}{calling conventions} that
  3808. govern how functions calls are performed in x86.
  3809. %
  3810. Even though \LangVar{} does not include programmer-defined functions,
  3811. our generated code includes a \code{main} function that is called by
  3812. the operating system and our generated code contains calls to the
  3813. \code{read\_int} function.
  3814. Function calls require coordination between two pieces of code that
  3815. may be written by different programmers or generated by different
  3816. compilers. Here we follow the System V calling conventions that are
  3817. used by the GNU C compiler on Linux and
  3818. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3819. %
  3820. The calling conventions include rules about how functions share the
  3821. use of registers. In particular, the caller is responsible for freeing
  3822. up some registers prior to the function call for use by the callee.
  3823. These are called the \emph{caller-saved registers}
  3824. \index{subject}{caller-saved registers}
  3825. and they are
  3826. \begin{lstlisting}
  3827. rax rcx rdx rsi rdi r8 r9 r10 r11
  3828. \end{lstlisting}
  3829. On the other hand, the callee is responsible for preserving the values
  3830. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3831. which are
  3832. \begin{lstlisting}
  3833. rsp rbp rbx r12 r13 r14 r15
  3834. \end{lstlisting}
  3835. We can think about this caller/callee convention from two points of
  3836. view, the caller view and the callee view:
  3837. \begin{itemize}
  3838. \item The caller should assume that all the caller-saved registers get
  3839. overwritten with arbitrary values by the callee. On the other hand,
  3840. the caller can safely assume that all the callee-saved registers
  3841. retain their original values.
  3842. \item The callee can freely use any of the caller-saved registers.
  3843. However, if the callee wants to use a callee-saved register, the
  3844. callee must arrange to put the original value back in the register
  3845. prior to returning to the caller. This can be accomplished by saving
  3846. the value to the stack in the prelude of the function and restoring
  3847. the value in the conclusion of the function.
  3848. \end{itemize}
  3849. In x86, registers are also used for passing arguments to a function
  3850. and for the return value. In particular, the first six arguments of a
  3851. function are passed in the following six registers, in this order.
  3852. \index{subject}{argument-passing registers}
  3853. \index{subject}{parameter-passing registers}
  3854. \begin{lstlisting}
  3855. rdi rsi rdx rcx r8 r9
  3856. \end{lstlisting}
  3857. If there are more than six arguments, then the convention is to use
  3858. space on the frame of the caller for the rest of the
  3859. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3860. need more than six arguments.
  3861. %
  3862. \racket{For now, the only function we care about is \code{read\_int}
  3863. and it takes zero arguments.}
  3864. %
  3865. \python{For now, the only functions we care about are \code{read\_int}
  3866. and \code{print\_int}, which take zero and one argument, respectively.}
  3867. %
  3868. The register \code{rax} is used for the return value of a function.
  3869. The next question is how these calling conventions impact register
  3870. allocation. Consider the \LangVar{} program in
  3871. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3872. example from the caller point of view and then from the callee point
  3873. of view. We refer to a variable that is in-use during a function call
  3874. as being a \emph{call-live variable}\index{subject}{call-live
  3875. variable}.
  3876. The program makes two calls to \READOP{}. The variable \code{x} is
  3877. call-live because it is in-use during the second call to \READOP{}; we
  3878. must ensure that the value in \code{x} does not get overwritten during
  3879. the call to \READOP{}. One obvious approach is to save all the values
  3880. that reside in caller-saved registers to the stack prior to each
  3881. function call, and restore them after each call. That way, if the
  3882. register allocator chooses to assign \code{x} to a caller-saved
  3883. register, its value will be preserved across the call to \READOP{}.
  3884. However, saving and restoring to the stack is relatively slow. If
  3885. \code{x} is not used many times, it may be better to assign \code{x}
  3886. to a stack location in the first place. Or better yet, if we can
  3887. arrange for \code{x} to be placed in a callee-saved register, then it
  3888. won't need to be saved and restored during function calls.
  3889. The approach that we recommend for call-live variables is to either
  3890. assign them to callee-saved registers or to spill them to the
  3891. stack. On the other hand, for variables that are not call-live, we try
  3892. the following alternatives in order 1) look for an available
  3893. caller-saved register (to leave room for other variables in the
  3894. callee-saved register), 2) look for a callee-saved register, and 3)
  3895. spill the variable to the stack.
  3896. It is straightforward to implement this approach in a graph coloring
  3897. register allocator. First, we know which variables are call-live
  3898. because we already need to compute which variables are in-use at every
  3899. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3900. we build the interference graph
  3901. (Section~\ref{sec:build-interference}), we can place an edge between
  3902. each of the call-live variables and the caller-saved registers in the
  3903. interference graph. This will prevent the graph coloring algorithm
  3904. from assigning them to caller-saved registers.
  3905. Returning to the example in
  3906. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3907. generated x86 code on the right-hand side. Notice that variable
  3908. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3909. is already in a safe place during the second call to
  3910. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3911. \code{rcx}, a caller-saved register, because \code{y} is not a
  3912. call-live variable.
  3913. Next we analyze the example from the callee point of view, focusing on
  3914. the prelude and conclusion of the \code{main} function. As usual the
  3915. prelude begins with saving the \code{rbp} register to the stack and
  3916. setting the \code{rbp} to the current stack pointer. We now know why
  3917. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3918. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3919. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3920. (\code{x}). The other callee-saved registers are not saved in the
  3921. prelude because they are not used. The prelude subtracts 8 bytes from
  3922. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3923. conclusion, we see that \code{rbx} is restored from the stack with a
  3924. \code{popq} instruction.
  3925. \index{subject}{prelude}\index{subject}{conclusion}
  3926. \begin{figure}[tp]
  3927. \begin{tcolorbox}[colback=white]
  3928. \begin{minipage}{0.45\textwidth}
  3929. Example \LangVar{} program:
  3930. %var_test_14.rkt
  3931. {\if\edition\racketEd
  3932. \begin{lstlisting}
  3933. (let ([x (read)])
  3934. (let ([y (read)])
  3935. (+ (+ x y) 42)))
  3936. \end{lstlisting}
  3937. \fi}
  3938. {\if\edition\pythonEd
  3939. \begin{lstlisting}
  3940. x = input_int()
  3941. y = input_int()
  3942. print((x + y) + 42)
  3943. \end{lstlisting}
  3944. \fi}
  3945. \end{minipage}
  3946. \begin{minipage}{0.45\textwidth}
  3947. Generated x86 assembly:
  3948. {\if\edition\racketEd
  3949. \begin{lstlisting}
  3950. start:
  3951. callq read_int
  3952. movq %rax, %rbx
  3953. callq read_int
  3954. movq %rax, %rcx
  3955. addq %rcx, %rbx
  3956. movq %rbx, %rax
  3957. addq $42, %rax
  3958. jmp _conclusion
  3959. .globl main
  3960. main:
  3961. pushq %rbp
  3962. movq %rsp, %rbp
  3963. pushq %rbx
  3964. subq $8, %rsp
  3965. jmp start
  3966. conclusion:
  3967. addq $8, %rsp
  3968. popq %rbx
  3969. popq %rbp
  3970. retq
  3971. \end{lstlisting}
  3972. \fi}
  3973. {\if\edition\pythonEd
  3974. \begin{lstlisting}
  3975. .globl main
  3976. main:
  3977. pushq %rbp
  3978. movq %rsp, %rbp
  3979. pushq %rbx
  3980. subq $8, %rsp
  3981. callq read_int
  3982. movq %rax, %rbx
  3983. callq read_int
  3984. movq %rax, %rcx
  3985. movq %rbx, %rdx
  3986. addq %rcx, %rdx
  3987. movq %rdx, %rcx
  3988. addq $42, %rcx
  3989. movq %rcx, %rdi
  3990. callq print_int
  3991. addq $8, %rsp
  3992. popq %rbx
  3993. popq %rbp
  3994. retq
  3995. \end{lstlisting}
  3996. \fi}
  3997. \end{minipage}
  3998. \end{tcolorbox}
  3999. \caption{An example with function calls.}
  4000. \label{fig:example-calling-conventions}
  4001. \end{figure}
  4002. %\clearpage
  4003. \section{Liveness Analysis}
  4004. \label{sec:liveness-analysis-Lvar}
  4005. \index{subject}{liveness analysis}
  4006. The \code{uncover\_live} \racket{pass}\python{function} performs
  4007. \emph{liveness analysis}, that is, it discovers which variables are
  4008. in-use in different regions of a program.
  4009. %
  4010. A variable or register is \emph{live} at a program point if its
  4011. current value is used at some later point in the program. We refer to
  4012. variables, stack locations, and registers collectively as
  4013. \emph{locations}.
  4014. %
  4015. Consider the following code fragment in which there are two writes to
  4016. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4017. time?
  4018. \begin{center}
  4019. \begin{minipage}{0.96\textwidth}
  4020. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4021. movq $5, a
  4022. movq $30, b
  4023. movq a, c
  4024. movq $10, b
  4025. addq b, c
  4026. \end{lstlisting}
  4027. \end{minipage}
  4028. \end{center}
  4029. The answer is no because \code{a} is live from line 1 to 3 and
  4030. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4031. line 2 is never used because it is overwritten (line 4) before the
  4032. next read (line 5).
  4033. The live locations for each instruction can be computed by traversing
  4034. the instruction sequence back to front (i.e., backwards in execution
  4035. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4036. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4037. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  4038. locations before instruction $I_k$. \racket{We recommend representing
  4039. these sets with the Racket \code{set} data structure described in
  4040. Figure~\ref{fig:set}.} \python{We recommend representing these sets
  4041. with the Python
  4042. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4043. data structure.}
  4044. {\if\edition\racketEd
  4045. \begin{figure}[tp]
  4046. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4047. \small
  4048. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4049. A \emph{set} is an unordered collection of elements without duplicates.
  4050. Here are some of the operations defined on sets.
  4051. \index{subject}{set}
  4052. \begin{description}
  4053. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4054. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4055. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4056. difference of the two sets.
  4057. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4058. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4059. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4060. \end{description}
  4061. \end{tcolorbox}
  4062. %\end{wrapfigure}
  4063. \caption{The \code{set} data structure.}
  4064. \label{fig:set}
  4065. \end{figure}
  4066. \fi}
  4067. The live locations after an instruction are always the same as the
  4068. live locations before the next instruction.
  4069. \index{subject}{live-after} \index{subject}{live-before}
  4070. \begin{equation} \label{eq:live-after-before-next}
  4071. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4072. \end{equation}
  4073. To start things off, there are no live locations after the last
  4074. instruction, so
  4075. \begin{equation}\label{eq:live-last-empty}
  4076. L_{\mathsf{after}}(n) = \emptyset
  4077. \end{equation}
  4078. We then apply the following rule repeatedly, traversing the
  4079. instruction sequence back to front.
  4080. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4081. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4082. \end{equation}
  4083. where $W(k)$ are the locations written to by instruction $I_k$ and
  4084. $R(k)$ are the locations read by instruction $I_k$.
  4085. {\if\edition\racketEd
  4086. %
  4087. There is a special case for \code{jmp} instructions. The locations
  4088. that are live before a \code{jmp} should be the locations in
  4089. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  4090. maintaining an alist named \code{label->live} that maps each label to
  4091. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  4092. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4093. conclusion. (For example, see Figure~\ref{fig:reg-eg}.) The
  4094. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4095. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4096. %
  4097. \fi}
  4098. Let us walk through the above example, applying these formulas
  4099. starting with the instruction on line 5. We collect the answers in
  4100. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  4101. \code{addq b, c} instruction is $\emptyset$ because it is the last
  4102. instruction (formula~\ref{eq:live-last-empty}). The
  4103. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4104. because it reads from variables \code{b} and \code{c}
  4105. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4106. \[
  4107. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4108. \]
  4109. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4110. the live-before set from line 5 to be the live-after set for this
  4111. instruction (formula~\ref{eq:live-after-before-next}).
  4112. \[
  4113. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4114. \]
  4115. This move instruction writes to \code{b} and does not read from any
  4116. variables, so we have the following live-before set
  4117. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4118. \[
  4119. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4120. \]
  4121. The live-before for instruction \code{movq a, c}
  4122. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4123. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4124. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4125. variable that is not live and does not read from a variable.
  4126. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4127. because it writes to variable \code{a}.
  4128. \begin{figure}[tbp]
  4129. \centering
  4130. \begin{tcolorbox}[colback=white]
  4131. \hspace{10pt}
  4132. \begin{minipage}{0.4\textwidth}
  4133. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4134. movq $5, a
  4135. movq $30, b
  4136. movq a, c
  4137. movq $10, b
  4138. addq b, c
  4139. \end{lstlisting}
  4140. \end{minipage}
  4141. \vrule\hspace{10pt}
  4142. \begin{minipage}{0.45\textwidth}
  4143. \begin{align*}
  4144. L_{\mathsf{before}}(1)= \emptyset,
  4145. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4146. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4147. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4148. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4149. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4150. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4151. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4152. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4153. L_{\mathsf{after}}(5)= \emptyset
  4154. \end{align*}
  4155. \end{minipage}
  4156. \end{tcolorbox}
  4157. \caption{Example output of liveness analysis on a short example.}
  4158. \label{fig:liveness-example-0}
  4159. \end{figure}
  4160. \begin{exercise}\normalfont\normalsize
  4161. Perform liveness analysis by hand on the running example in
  4162. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4163. sets for each instruction. Compare your answers to the solution
  4164. shown in Figure~\ref{fig:live-eg}.
  4165. \end{exercise}
  4166. \begin{figure}[tp]
  4167. \hspace{20pt}
  4168. \begin{minipage}{0.55\textwidth}
  4169. \begin{tcolorbox}[colback=white]
  4170. {\if\edition\racketEd
  4171. \begin{lstlisting}
  4172. |$\{\ttm{rsp}\}$|
  4173. movq $1, v
  4174. |$\{\ttm{v},\ttm{rsp}\}$|
  4175. movq $42, w
  4176. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4177. movq v, x
  4178. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4179. addq $7, x
  4180. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4181. movq x, y
  4182. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4183. movq x, z
  4184. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4185. addq w, z
  4186. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4187. movq y, t
  4188. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4189. negq t
  4190. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4191. movq z, %rax
  4192. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4193. addq t, %rax
  4194. |$\{\ttm{rax},\ttm{rsp}\}$|
  4195. jmp conclusion
  4196. \end{lstlisting}
  4197. \fi}
  4198. {\if\edition\pythonEd
  4199. \begin{lstlisting}
  4200. movq $1, v
  4201. |$\{\ttm{v}\}$|
  4202. movq $42, w
  4203. |$\{\ttm{w}, \ttm{v}\}$|
  4204. movq v, x
  4205. |$\{\ttm{w}, \ttm{x}\}$|
  4206. addq $7, x
  4207. |$\{\ttm{w}, \ttm{x}\}$|
  4208. movq x, y
  4209. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4210. movq x, z
  4211. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4212. addq w, z
  4213. |$\{\ttm{y}, \ttm{z}\}$|
  4214. movq y, tmp_0
  4215. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4216. negq tmp_0
  4217. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4218. movq z, tmp_1
  4219. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4220. addq tmp_0, tmp_1
  4221. |$\{\ttm{tmp\_1}\}$|
  4222. movq tmp_1, %rdi
  4223. |$\{\ttm{rdi}\}$|
  4224. callq print_int
  4225. |$\{\}$|
  4226. \end{lstlisting}
  4227. \fi}
  4228. \end{tcolorbox}
  4229. \end{minipage}
  4230. \caption{The running example annotated with live-after sets.}
  4231. \label{fig:live-eg}
  4232. \end{figure}
  4233. \begin{exercise}\normalfont\normalsize
  4234. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4235. %
  4236. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4237. field of the \code{Block} structure.}
  4238. %
  4239. \python{Return a dictionary that maps each instruction to its
  4240. live-after set.}
  4241. %
  4242. \racket{We recommend creating an auxiliary function that takes a list
  4243. of instructions and an initial live-after set (typically empty) and
  4244. returns the list of live-after sets.}
  4245. %
  4246. We recommend creating auxiliary functions to 1) compute the set
  4247. of locations that appear in an \Arg{}, 2) compute the locations read
  4248. by an instruction (the $R$ function), and 3) the locations written by
  4249. an instruction (the $W$ function). The \code{callq} instruction should
  4250. include all of the caller-saved registers in its write-set $W$ because
  4251. the calling convention says that those registers may be written to
  4252. during the function call. Likewise, the \code{callq} instruction
  4253. should include the appropriate argument-passing registers in its
  4254. read-set $R$, depending on the arity of the function being
  4255. called. (This is why the abstract syntax for \code{callq} includes the
  4256. arity.)
  4257. \end{exercise}
  4258. %\clearpage
  4259. \section{Build the Interference Graph}
  4260. \label{sec:build-interference}
  4261. {\if\edition\racketEd
  4262. \begin{figure}[tp]
  4263. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4264. \small
  4265. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4266. A \emph{graph} is a collection of vertices and edges where each
  4267. edge connects two vertices. A graph is \emph{directed} if each
  4268. edge points from a source to a target. Otherwise the graph is
  4269. \emph{undirected}.
  4270. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4271. \begin{description}
  4272. %% We currently don't use directed graphs. We instead use
  4273. %% directed multi-graphs. -Jeremy
  4274. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4275. directed graph from a list of edges. Each edge is a list
  4276. containing the source and target vertex.
  4277. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4278. undirected graph from a list of edges. Each edge is represented by
  4279. a list containing two vertices.
  4280. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4281. inserts a vertex into the graph.
  4282. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4283. inserts an edge between the two vertices.
  4284. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4285. returns a sequence of vertices adjacent to the vertex.
  4286. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4287. returns a sequence of all vertices in the graph.
  4288. \end{description}
  4289. \end{tcolorbox}
  4290. %\end{wrapfigure}
  4291. \caption{The Racket \code{graph} package.}
  4292. \label{fig:graph}
  4293. \end{figure}
  4294. \fi}
  4295. Based on the liveness analysis, we know where each location is live.
  4296. However, during register allocation, we need to answer questions of
  4297. the specific form: are locations $u$ and $v$ live at the same time?
  4298. (And therefore cannot be assigned to the same register.) To make this
  4299. question more efficient to answer, we create an explicit data
  4300. structure, an \emph{interference graph}\index{subject}{interference
  4301. graph}. An interference graph is an undirected graph that has an
  4302. edge between two locations if they are live at the same time, that is,
  4303. if they interfere with each other.
  4304. %
  4305. \racket{We recommend using the Racket \code{graph} package
  4306. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4307. %
  4308. \python{We provide implementations of directed and undirected graph
  4309. data structures in the file \code{graph.py} of the support code.}
  4310. A straightforward way to compute the interference graph is to look at
  4311. the set of live locations between each instruction and add an edge to
  4312. the graph for every pair of variables in the same set. This approach
  4313. is less than ideal for two reasons. First, it can be expensive because
  4314. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4315. locations. Second, in the special case where two locations hold the
  4316. same value (because one was assigned to the other), they can be live
  4317. at the same time without interfering with each other.
  4318. A better way to compute the interference graph is to focus on
  4319. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4320. must not overwrite something in a live location. So for each
  4321. instruction, we create an edge between the locations being written to
  4322. and the live locations. (Except that a location never interferes with
  4323. itself.) For the \key{callq} instruction, we consider all of the
  4324. caller-saved registers as being written to, so an edge is added
  4325. between every live variable and every caller-saved register. Also, for
  4326. \key{movq} there is the special case of two variables holding the same
  4327. value. If a live variable $v$ is the same as the source of the
  4328. \key{movq}, then there is no need to add an edge between $v$ and the
  4329. destination, because they both hold the same value.
  4330. %
  4331. So we have the following two rules.
  4332. \begin{enumerate}
  4333. \item If instruction $I_k$ is a move instruction of the form
  4334. \key{movq} $s$\key{,} $d$, then for every $v \in
  4335. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4336. $(d,v)$.
  4337. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4338. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4339. $(d,v)$.
  4340. \end{enumerate}
  4341. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4342. the above rules to each instruction. We highlight a few of the
  4343. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4344. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4345. so \code{v} interferes with \code{rsp}.}
  4346. %
  4347. \python{The first instruction is \lstinline{movq $1, v} and the
  4348. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4349. no interference because $\ttm{v}$ is the destination of the move.}
  4350. %
  4351. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4352. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4353. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4354. %
  4355. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4356. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4357. $\ttm{x}$ interferes with \ttm{w}.}
  4358. %
  4359. \racket{The next instruction is \lstinline{movq x, y} and the
  4360. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4361. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4362. \ttm{x} because \ttm{x} is the source of the move and therefore
  4363. \ttm{x} and \ttm{y} hold the same value.}
  4364. %
  4365. \python{The next instruction is \lstinline{movq x, y} and the
  4366. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4367. applies, so \ttm{y} interferes with \ttm{w} but not
  4368. \ttm{x} because \ttm{x} is the source of the move and therefore
  4369. \ttm{x} and \ttm{y} hold the same value.}
  4370. %
  4371. Figure~\ref{fig:interference-results} lists the interference results
  4372. for all of the instructions and the resulting interference graph is
  4373. shown in Figure~\ref{fig:interfere}.
  4374. \begin{figure}[tbp]
  4375. \begin{tcolorbox}[colback=white]
  4376. \begin{quote}
  4377. {\if\edition\racketEd
  4378. \begin{tabular}{ll}
  4379. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4380. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4381. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4382. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4383. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4384. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4385. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4386. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4387. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4388. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4389. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4390. \lstinline!jmp conclusion!& no interference.
  4391. \end{tabular}
  4392. \fi}
  4393. {\if\edition\pythonEd
  4394. \begin{tabular}{ll}
  4395. \lstinline!movq $1, v!& no interference\\
  4396. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4397. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4398. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4399. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4400. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4401. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4402. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4403. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4404. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4405. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4406. \lstinline!movq tmp_1, %rdi! & no interference \\
  4407. \lstinline!callq print_int!& no interference.
  4408. \end{tabular}
  4409. \fi}
  4410. \end{quote}
  4411. \end{tcolorbox}
  4412. \caption{Interference results for the running example.}
  4413. \label{fig:interference-results}
  4414. \end{figure}
  4415. \begin{figure}[tbp]
  4416. \begin{tcolorbox}[colback=white]
  4417. \large
  4418. {\if\edition\racketEd
  4419. \[
  4420. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4421. \node (rax) at (0,0) {$\ttm{rax}$};
  4422. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4423. \node (t1) at (0,2) {$\ttm{t}$};
  4424. \node (z) at (3,2) {$\ttm{z}$};
  4425. \node (x) at (6,2) {$\ttm{x}$};
  4426. \node (y) at (3,0) {$\ttm{y}$};
  4427. \node (w) at (6,0) {$\ttm{w}$};
  4428. \node (v) at (9,0) {$\ttm{v}$};
  4429. \draw (t1) to (rax);
  4430. \draw (t1) to (z);
  4431. \draw (z) to (y);
  4432. \draw (z) to (w);
  4433. \draw (x) to (w);
  4434. \draw (y) to (w);
  4435. \draw (v) to (w);
  4436. \draw (v) to (rsp);
  4437. \draw (w) to (rsp);
  4438. \draw (x) to (rsp);
  4439. \draw (y) to (rsp);
  4440. \path[-.,bend left=15] (z) edge node {} (rsp);
  4441. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4442. \draw (rax) to (rsp);
  4443. \end{tikzpicture}
  4444. \]
  4445. \fi}
  4446. {\if\edition\pythonEd
  4447. \[
  4448. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4449. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4450. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4451. \node (z) at (3,2) {$\ttm{z}$};
  4452. \node (x) at (6,2) {$\ttm{x}$};
  4453. \node (y) at (3,0) {$\ttm{y}$};
  4454. \node (w) at (6,0) {$\ttm{w}$};
  4455. \node (v) at (9,0) {$\ttm{v}$};
  4456. \draw (t0) to (t1);
  4457. \draw (t0) to (z);
  4458. \draw (z) to (y);
  4459. \draw (z) to (w);
  4460. \draw (x) to (w);
  4461. \draw (y) to (w);
  4462. \draw (v) to (w);
  4463. \end{tikzpicture}
  4464. \]
  4465. \fi}
  4466. \end{tcolorbox}
  4467. \caption{The interference graph of the example program.}
  4468. \label{fig:interfere}
  4469. \end{figure}
  4470. %% Our next concern is to choose a data structure for representing the
  4471. %% interference graph. There are many choices for how to represent a
  4472. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4473. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4474. %% data structure is to study the algorithm that uses the data structure,
  4475. %% determine what operations need to be performed, and then choose the
  4476. %% data structure that provide the most efficient implementations of
  4477. %% those operations. Often times the choice of data structure can have an
  4478. %% effect on the time complexity of the algorithm, as it does here. If
  4479. %% you skim the next section, you will see that the register allocation
  4480. %% algorithm needs to ask the graph for all of its vertices and, given a
  4481. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4482. %% correct choice of graph representation is that of an adjacency
  4483. %% list. There are helper functions in \code{utilities.rkt} for
  4484. %% representing graphs using the adjacency list representation:
  4485. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4486. %% (Appendix~\ref{appendix:utilities}).
  4487. %% %
  4488. %% \margincomment{\footnotesize To do: change to use the
  4489. %% Racket graph library. \\ --Jeremy}
  4490. %% %
  4491. %% In particular, those functions use a hash table to map each vertex to
  4492. %% the set of adjacent vertices, and the sets are represented using
  4493. %% Racket's \key{set}, which is also a hash table.
  4494. \begin{exercise}\normalfont\normalsize
  4495. \racket{Implement the compiler pass named \code{build\_interference} according
  4496. to the algorithm suggested above. We recommend using the Racket
  4497. \code{graph} package to create and inspect the interference graph.
  4498. The output graph of this pass should be stored in the $\itm{info}$ field of
  4499. the program, under the key \code{conflicts}.}
  4500. %
  4501. \python{Implement a function named \code{build\_interference}
  4502. according to the algorithm suggested above that
  4503. returns the interference graph.}
  4504. \end{exercise}
  4505. \section{Graph Coloring via Sudoku}
  4506. \label{sec:graph-coloring}
  4507. \index{subject}{graph coloring}
  4508. \index{subject}{Sudoku}
  4509. \index{subject}{color}
  4510. We come to the main event of this chapter, mapping variables to
  4511. registers and stack locations. Variables that interfere with each
  4512. other must be mapped to different locations. In terms of the
  4513. interference graph, this means that adjacent vertices must be mapped
  4514. to different locations. If we think of locations as colors, the
  4515. register allocation problem becomes the graph coloring
  4516. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4517. The reader may be more familiar with the graph coloring problem than he
  4518. or she realizes; the popular game of Sudoku is an instance of the
  4519. graph coloring problem. The following describes how to build a graph
  4520. out of an initial Sudoku board.
  4521. \begin{itemize}
  4522. \item There is one vertex in the graph for each Sudoku square.
  4523. \item There is an edge between two vertices if the corresponding squares
  4524. are in the same row, in the same column, or if the squares are in
  4525. the same $3\times 3$ region.
  4526. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4527. \item Based on the initial assignment of numbers to squares in the
  4528. Sudoku board, assign the corresponding colors to the corresponding
  4529. vertices in the graph.
  4530. \end{itemize}
  4531. If you can color the remaining vertices in the graph with the nine
  4532. colors, then you have also solved the corresponding game of Sudoku.
  4533. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4534. the corresponding graph with colored vertices. We map the Sudoku
  4535. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4536. sampling of the vertices (the colored ones) because showing edges for
  4537. all of the vertices would make the graph unreadable.
  4538. \begin{figure}[tbp]
  4539. \begin{tcolorbox}[colback=white]
  4540. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  4541. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4542. \end{tcolorbox}
  4543. \caption{A Sudoku game board and the corresponding colored graph.}
  4544. \label{fig:sudoku-graph}
  4545. \end{figure}
  4546. Some techniques for playing Sudoku correspond to heuristics used in
  4547. graph coloring algorithms. For example, one of the basic techniques
  4548. for Sudoku is called Pencil Marks. The idea is to use a process of
  4549. elimination to determine what numbers are no longer available for a
  4550. square and write down those numbers in the square (writing very
  4551. small). For example, if the number $1$ is assigned to a square, then
  4552. write the pencil mark $1$ in all the squares in the same row, column,
  4553. and region to indicate that $1$ is no longer an option for those other
  4554. squares.
  4555. %
  4556. The Pencil Marks technique corresponds to the notion of
  4557. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4558. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4559. are no longer available. In graph terminology, we have the following
  4560. definition:
  4561. \begin{equation*}
  4562. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4563. \text{ and } \mathrm{color}(v) = c \}
  4564. \end{equation*}
  4565. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4566. edge with $u$.
  4567. The Pencil Marks technique leads to a simple strategy for filling in
  4568. numbers: if there is a square with only one possible number left, then
  4569. choose that number! But what if there are no squares with only one
  4570. possibility left? One brute-force approach is to try them all: choose
  4571. the first one and if that ultimately leads to a solution, great. If
  4572. not, backtrack and choose the next possibility. One good thing about
  4573. Pencil Marks is that it reduces the degree of branching in the search
  4574. tree. Nevertheless, backtracking can be terribly time consuming. One
  4575. way to reduce the amount of backtracking is to use the
  4576. most-constrained-first heuristic (aka. minimum remaining
  4577. values)~\citep{Russell2003}. That is, when choosing a square, always
  4578. choose one with the fewest possibilities left (the vertex with the
  4579. highest saturation). The idea is that choosing highly constrained
  4580. squares earlier rather than later is better because later on there may
  4581. not be any possibilities left in the highly saturated squares.
  4582. However, register allocation is easier than Sudoku because the
  4583. register allocator can fall back to assigning variables to stack
  4584. locations when the registers run out. Thus, it makes sense to replace
  4585. backtracking with greedy search: make the best choice at the time and
  4586. keep going. We still wish to minimize the number of colors needed, so
  4587. we use the most-constrained-first heuristic in the greedy search.
  4588. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4589. algorithm for register allocation based on saturation and the
  4590. most-constrained-first heuristic. It is roughly equivalent to the
  4591. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4592. %,Gebremedhin:1999fk,Omari:2006uq
  4593. Just as in Sudoku, the algorithm represents colors with integers. The
  4594. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4595. for register allocation. The integers $k$ and larger correspond to
  4596. stack locations. The registers that are not used for register
  4597. allocation, such as \code{rax}, are assigned to negative integers. In
  4598. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4599. %% One might wonder why we include registers at all in the liveness
  4600. %% analysis and interference graph. For example, we never allocate a
  4601. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4602. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4603. %% to use register for passing arguments to functions, it will be
  4604. %% necessary for those registers to appear in the interference graph
  4605. %% because those registers will also be assigned to variables, and we
  4606. %% don't want those two uses to encroach on each other. Regarding
  4607. %% registers such as \code{rax} and \code{rsp} that are not used for
  4608. %% variables, we could omit them from the interference graph but that
  4609. %% would require adding special cases to our algorithm, which would
  4610. %% complicate the logic for little gain.
  4611. \begin{figure}[btp]
  4612. \begin{tcolorbox}[colback=white]
  4613. \centering
  4614. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4615. Algorithm: DSATUR
  4616. Input: a graph |$G$|
  4617. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4618. |$W \gets \mathrm{vertices}(G)$|
  4619. while |$W \neq \emptyset$| do
  4620. pick a vertex |$u$| from |$W$| with the highest saturation,
  4621. breaking ties randomly
  4622. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4623. |$\mathrm{color}[u] \gets c$|
  4624. |$W \gets W - \{u\}$|
  4625. \end{lstlisting}
  4626. \end{tcolorbox}
  4627. \caption{The saturation-based greedy graph coloring algorithm.}
  4628. \label{fig:satur-algo}
  4629. \end{figure}
  4630. {\if\edition\racketEd
  4631. With the DSATUR algorithm in hand, let us return to the running
  4632. example and consider how to color the interference graph in
  4633. Figure~\ref{fig:interfere}.
  4634. %
  4635. We start by assigning the register nodes to their own color. For
  4636. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4637. assigned $-2$. The variables are not yet colored, so they are
  4638. annotated with a dash. We then update the saturation for vertices that
  4639. are adjacent to a register, obtaining the following annotated
  4640. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4641. it interferes with both \code{rax} and \code{rsp}.
  4642. \[
  4643. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4644. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4645. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4646. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4647. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4648. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4649. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4650. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4651. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4652. \draw (t1) to (rax);
  4653. \draw (t1) to (z);
  4654. \draw (z) to (y);
  4655. \draw (z) to (w);
  4656. \draw (x) to (w);
  4657. \draw (y) to (w);
  4658. \draw (v) to (w);
  4659. \draw (v) to (rsp);
  4660. \draw (w) to (rsp);
  4661. \draw (x) to (rsp);
  4662. \draw (y) to (rsp);
  4663. \path[-.,bend left=15] (z) edge node {} (rsp);
  4664. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4665. \draw (rax) to (rsp);
  4666. \end{tikzpicture}
  4667. \]
  4668. The algorithm says to select a maximally saturated vertex. So we pick
  4669. $\ttm{t}$ and color it with the first available integer, which is
  4670. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4671. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4672. \[
  4673. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4674. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4675. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4676. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4677. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4678. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4679. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4680. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4681. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4682. \draw (t1) to (rax);
  4683. \draw (t1) to (z);
  4684. \draw (z) to (y);
  4685. \draw (z) to (w);
  4686. \draw (x) to (w);
  4687. \draw (y) to (w);
  4688. \draw (v) to (w);
  4689. \draw (v) to (rsp);
  4690. \draw (w) to (rsp);
  4691. \draw (x) to (rsp);
  4692. \draw (y) to (rsp);
  4693. \path[-.,bend left=15] (z) edge node {} (rsp);
  4694. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4695. \draw (rax) to (rsp);
  4696. \end{tikzpicture}
  4697. \]
  4698. We repeat the process, selecting a maximally saturated vertex,
  4699. choosing is \code{z}, and color it with the first available number, which
  4700. is $1$. We add $1$ to the saturation for the neighboring vertices
  4701. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4702. \[
  4703. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4704. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4705. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4706. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4707. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4708. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4709. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4710. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4711. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4712. \draw (t1) to (rax);
  4713. \draw (t1) to (z);
  4714. \draw (z) to (y);
  4715. \draw (z) to (w);
  4716. \draw (x) to (w);
  4717. \draw (y) to (w);
  4718. \draw (v) to (w);
  4719. \draw (v) to (rsp);
  4720. \draw (w) to (rsp);
  4721. \draw (x) to (rsp);
  4722. \draw (y) to (rsp);
  4723. \path[-.,bend left=15] (z) edge node {} (rsp);
  4724. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4725. \draw (rax) to (rsp);
  4726. \end{tikzpicture}
  4727. \]
  4728. The most saturated vertices are now \code{w} and \code{y}. We color
  4729. \code{w} with the first available color, which is $0$.
  4730. \[
  4731. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4732. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4733. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4734. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4735. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4736. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4737. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4738. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4739. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4740. \draw (t1) to (rax);
  4741. \draw (t1) to (z);
  4742. \draw (z) to (y);
  4743. \draw (z) to (w);
  4744. \draw (x) to (w);
  4745. \draw (y) to (w);
  4746. \draw (v) to (w);
  4747. \draw (v) to (rsp);
  4748. \draw (w) to (rsp);
  4749. \draw (x) to (rsp);
  4750. \draw (y) to (rsp);
  4751. \path[-.,bend left=15] (z) edge node {} (rsp);
  4752. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4753. \draw (rax) to (rsp);
  4754. \end{tikzpicture}
  4755. \]
  4756. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4757. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4758. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4759. and \code{z}, whose colors are $0$ and $1$ respectively.
  4760. \[
  4761. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4762. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4763. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4764. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4765. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4766. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4767. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4768. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4769. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4770. \draw (t1) to (rax);
  4771. \draw (t1) to (z);
  4772. \draw (z) to (y);
  4773. \draw (z) to (w);
  4774. \draw (x) to (w);
  4775. \draw (y) to (w);
  4776. \draw (v) to (w);
  4777. \draw (v) to (rsp);
  4778. \draw (w) to (rsp);
  4779. \draw (x) to (rsp);
  4780. \draw (y) to (rsp);
  4781. \path[-.,bend left=15] (z) edge node {} (rsp);
  4782. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4783. \draw (rax) to (rsp);
  4784. \end{tikzpicture}
  4785. \]
  4786. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4787. \[
  4788. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4789. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4790. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4791. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4792. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4793. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4794. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4795. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4796. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4797. \draw (t1) to (rax);
  4798. \draw (t1) to (z);
  4799. \draw (z) to (y);
  4800. \draw (z) to (w);
  4801. \draw (x) to (w);
  4802. \draw (y) to (w);
  4803. \draw (v) to (w);
  4804. \draw (v) to (rsp);
  4805. \draw (w) to (rsp);
  4806. \draw (x) to (rsp);
  4807. \draw (y) to (rsp);
  4808. \path[-.,bend left=15] (z) edge node {} (rsp);
  4809. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4810. \draw (rax) to (rsp);
  4811. \end{tikzpicture}
  4812. \]
  4813. In the last step of the algorithm, we color \code{x} with $1$.
  4814. \[
  4815. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4816. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4817. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4818. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4819. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4820. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4821. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4822. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4823. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4824. \draw (t1) to (rax);
  4825. \draw (t1) to (z);
  4826. \draw (z) to (y);
  4827. \draw (z) to (w);
  4828. \draw (x) to (w);
  4829. \draw (y) to (w);
  4830. \draw (v) to (w);
  4831. \draw (v) to (rsp);
  4832. \draw (w) to (rsp);
  4833. \draw (x) to (rsp);
  4834. \draw (y) to (rsp);
  4835. \path[-.,bend left=15] (z) edge node {} (rsp);
  4836. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4837. \draw (rax) to (rsp);
  4838. \end{tikzpicture}
  4839. \]
  4840. So we obtain the following coloring:
  4841. \[
  4842. \{
  4843. \ttm{rax} \mapsto -1,
  4844. \ttm{rsp} \mapsto -2,
  4845. \ttm{t} \mapsto 0,
  4846. \ttm{z} \mapsto 1,
  4847. \ttm{x} \mapsto 1,
  4848. \ttm{y} \mapsto 2,
  4849. \ttm{w} \mapsto 0,
  4850. \ttm{v} \mapsto 1
  4851. \}
  4852. \]
  4853. \fi}
  4854. %
  4855. {\if\edition\pythonEd
  4856. %
  4857. With the DSATUR algorithm in hand, let us return to the running
  4858. example and consider how to color the interference graph in
  4859. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4860. to indicate that it has not yet been assigned a color. The saturation
  4861. sets are also shown for each node; all of them start as the empty set.
  4862. (We do not include the register nodes in the graph below because there
  4863. were no interference edges involving registers in this program, but in
  4864. general there can be.)
  4865. %
  4866. \[
  4867. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4868. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4869. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4870. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4871. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4872. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4873. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4874. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4875. \draw (t0) to (t1);
  4876. \draw (t0) to (z);
  4877. \draw (z) to (y);
  4878. \draw (z) to (w);
  4879. \draw (x) to (w);
  4880. \draw (y) to (w);
  4881. \draw (v) to (w);
  4882. \end{tikzpicture}
  4883. \]
  4884. The algorithm says to select a maximally saturated vertex, but they
  4885. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4886. then color it with the first available integer, which is $0$. We mark
  4887. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4888. they interfere with $\ttm{tmp\_0}$.
  4889. \[
  4890. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4891. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4892. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4893. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4894. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4895. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4896. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4897. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4898. \draw (t0) to (t1);
  4899. \draw (t0) to (z);
  4900. \draw (z) to (y);
  4901. \draw (z) to (w);
  4902. \draw (x) to (w);
  4903. \draw (y) to (w);
  4904. \draw (v) to (w);
  4905. \end{tikzpicture}
  4906. \]
  4907. We repeat the process. The most saturated vertices are \code{z} and
  4908. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4909. available number, which is $1$. We add $1$ to the saturation for the
  4910. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4911. \[
  4912. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4913. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4914. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4915. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4916. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4917. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4918. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4919. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4920. \draw (t0) to (t1);
  4921. \draw (t0) to (z);
  4922. \draw (z) to (y);
  4923. \draw (z) to (w);
  4924. \draw (x) to (w);
  4925. \draw (y) to (w);
  4926. \draw (v) to (w);
  4927. \end{tikzpicture}
  4928. \]
  4929. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4930. \code{y}. We color \code{w} with the first available color, which
  4931. is $0$.
  4932. \[
  4933. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4934. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4935. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4936. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4937. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4938. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4939. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4940. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4941. \draw (t0) to (t1);
  4942. \draw (t0) to (z);
  4943. \draw (z) to (y);
  4944. \draw (z) to (w);
  4945. \draw (x) to (w);
  4946. \draw (y) to (w);
  4947. \draw (v) to (w);
  4948. \end{tikzpicture}
  4949. \]
  4950. Now \code{y} is the most saturated, so we color it with $2$.
  4951. \[
  4952. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4953. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4954. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4955. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4956. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4957. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4958. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4959. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4960. \draw (t0) to (t1);
  4961. \draw (t0) to (z);
  4962. \draw (z) to (y);
  4963. \draw (z) to (w);
  4964. \draw (x) to (w);
  4965. \draw (y) to (w);
  4966. \draw (v) to (w);
  4967. \end{tikzpicture}
  4968. \]
  4969. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4970. We choose to color \code{v} with $1$.
  4971. \[
  4972. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4973. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4974. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4975. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4976. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4977. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4978. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4979. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4980. \draw (t0) to (t1);
  4981. \draw (t0) to (z);
  4982. \draw (z) to (y);
  4983. \draw (z) to (w);
  4984. \draw (x) to (w);
  4985. \draw (y) to (w);
  4986. \draw (v) to (w);
  4987. \end{tikzpicture}
  4988. \]
  4989. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4990. \[
  4991. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4992. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4993. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4994. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4995. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4996. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4997. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4998. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4999. \draw (t0) to (t1);
  5000. \draw (t0) to (z);
  5001. \draw (z) to (y);
  5002. \draw (z) to (w);
  5003. \draw (x) to (w);
  5004. \draw (y) to (w);
  5005. \draw (v) to (w);
  5006. \end{tikzpicture}
  5007. \]
  5008. So we obtain the following coloring:
  5009. \[
  5010. \{ \ttm{tmp\_0} \mapsto 0,
  5011. \ttm{tmp\_1} \mapsto 1,
  5012. \ttm{z} \mapsto 1,
  5013. \ttm{x} \mapsto 1,
  5014. \ttm{y} \mapsto 2,
  5015. \ttm{w} \mapsto 0,
  5016. \ttm{v} \mapsto 1 \}
  5017. \]
  5018. \fi}
  5019. We recommend creating an auxiliary function named \code{color\_graph}
  5020. that takes an interference graph and a list of all the variables in
  5021. the program. This function should return a mapping of variables to
  5022. their colors (represented as natural numbers). By creating this helper
  5023. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  5024. when we add support for functions.
  5025. To prioritize the processing of highly saturated nodes inside the
  5026. \code{color\_graph} function, we recommend using the priority queue
  5027. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5028. addition, you will need to maintain a mapping from variables to their
  5029. ``handles'' in the priority queue so that you can notify the priority
  5030. queue when their saturation changes.}
  5031. {\if\edition\racketEd
  5032. \begin{figure}[tp]
  5033. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5034. \small
  5035. \begin{tcolorbox}[title=Priority Queue]
  5036. A \emph{priority queue} is a collection of items in which the
  5037. removal of items is governed by priority. In a ``min'' queue,
  5038. lower priority items are removed first. An implementation is in
  5039. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5040. queue} \index{subject}{minimum priority queue}
  5041. \begin{description}
  5042. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5043. priority queue that uses the $\itm{cmp}$ predicate to determine
  5044. whether its first argument has lower or equal priority to its
  5045. second argument.
  5046. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5047. items in the queue.
  5048. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5049. the item into the queue and returns a handle for the item in the
  5050. queue.
  5051. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5052. the lowest priority.
  5053. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5054. notifies the queue that the priority has decreased for the item
  5055. associated with the given handle.
  5056. \end{description}
  5057. \end{tcolorbox}
  5058. %\end{wrapfigure}
  5059. \caption{The priority queue data structure.}
  5060. \label{fig:priority-queue}
  5061. \end{figure}
  5062. \fi}
  5063. With the coloring complete, we finalize the assignment of variables to
  5064. registers and stack locations. We map the first $k$ colors to the $k$
  5065. registers and the rest of the colors to stack locations. Suppose for
  5066. the moment that we have just one register to use for register
  5067. allocation, \key{rcx}. Then we have the following map from colors to
  5068. locations.
  5069. \[
  5070. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5071. \]
  5072. Composing this mapping with the coloring, we arrive at the following
  5073. assignment of variables to locations.
  5074. {\if\edition\racketEd
  5075. \begin{gather*}
  5076. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5077. \ttm{w} \mapsto \key{\%rcx}, \,
  5078. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5079. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5080. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5081. \ttm{t} \mapsto \key{\%rcx} \}
  5082. \end{gather*}
  5083. \fi}
  5084. {\if\edition\pythonEd
  5085. \begin{gather*}
  5086. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5087. \ttm{w} \mapsto \key{\%rcx}, \,
  5088. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5089. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5090. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5091. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5092. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5093. \end{gather*}
  5094. \fi}
  5095. Adapt the code from the \code{assign\_homes} pass
  5096. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  5097. assigned location. Applying the above assignment to our running
  5098. example, on the left, yields the program on the right.
  5099. % why frame size of 32? -JGS
  5100. \begin{center}
  5101. {\if\edition\racketEd
  5102. \begin{minipage}{0.3\textwidth}
  5103. \begin{lstlisting}
  5104. movq $1, v
  5105. movq $42, w
  5106. movq v, x
  5107. addq $7, x
  5108. movq x, y
  5109. movq x, z
  5110. addq w, z
  5111. movq y, t
  5112. negq t
  5113. movq z, %rax
  5114. addq t, %rax
  5115. jmp conclusion
  5116. \end{lstlisting}
  5117. \end{minipage}
  5118. $\Rightarrow\qquad$
  5119. \begin{minipage}{0.45\textwidth}
  5120. \begin{lstlisting}
  5121. movq $1, -8(%rbp)
  5122. movq $42, %rcx
  5123. movq -8(%rbp), -8(%rbp)
  5124. addq $7, -8(%rbp)
  5125. movq -8(%rbp), -16(%rbp)
  5126. movq -8(%rbp), -8(%rbp)
  5127. addq %rcx, -8(%rbp)
  5128. movq -16(%rbp), %rcx
  5129. negq %rcx
  5130. movq -8(%rbp), %rax
  5131. addq %rcx, %rax
  5132. jmp conclusion
  5133. \end{lstlisting}
  5134. \end{minipage}
  5135. \fi}
  5136. {\if\edition\pythonEd
  5137. \begin{minipage}{0.3\textwidth}
  5138. \begin{lstlisting}
  5139. movq $1, v
  5140. movq $42, w
  5141. movq v, x
  5142. addq $7, x
  5143. movq x, y
  5144. movq x, z
  5145. addq w, z
  5146. movq y, tmp_0
  5147. negq tmp_0
  5148. movq z, tmp_1
  5149. addq tmp_0, tmp_1
  5150. movq tmp_1, %rdi
  5151. callq print_int
  5152. \end{lstlisting}
  5153. \end{minipage}
  5154. $\Rightarrow\qquad$
  5155. \begin{minipage}{0.45\textwidth}
  5156. \begin{lstlisting}
  5157. movq $1, -8(%rbp)
  5158. movq $42, %rcx
  5159. movq -8(%rbp), -8(%rbp)
  5160. addq $7, -8(%rbp)
  5161. movq -8(%rbp), -16(%rbp)
  5162. movq -8(%rbp), -8(%rbp)
  5163. addq %rcx, -8(%rbp)
  5164. movq -16(%rbp), %rcx
  5165. negq %rcx
  5166. movq -8(%rbp), -8(%rbp)
  5167. addq %rcx, -8(%rbp)
  5168. movq -8(%rbp), %rdi
  5169. callq print_int
  5170. \end{lstlisting}
  5171. \end{minipage}
  5172. \fi}
  5173. \end{center}
  5174. \begin{exercise}\normalfont\normalsize
  5175. Implement the \code{allocate\_registers} pass.
  5176. Create five programs that exercise all aspects of the register
  5177. allocation algorithm, including spilling variables to the stack.
  5178. %
  5179. {\if\edition\racketEd
  5180. Replace \code{assign\_homes} in the list of \code{passes} in the
  5181. \code{run-tests.rkt} script with the three new passes:
  5182. \code{uncover\_live}, \code{build\_interference}, and
  5183. \code{allocate\_registers}.
  5184. Temporarily remove the call to \code{compiler-tests}.
  5185. Run the script to test the register allocator.
  5186. \fi}
  5187. %
  5188. {\if\edition\pythonEd
  5189. Run the \code{run-tests.py} script to to check whether the
  5190. output programs produce the same result as the input programs.
  5191. \fi}
  5192. \end{exercise}
  5193. \section{Patch Instructions}
  5194. \label{sec:patch-instructions}
  5195. The remaining step in the compilation to x86 is to ensure that the
  5196. instructions have at most one argument that is a memory access.
  5197. %
  5198. In the running example, the instruction \code{movq -8(\%rbp),
  5199. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5200. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5201. then move \code{rax} into \code{-16(\%rbp)}.
  5202. %
  5203. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5204. problematic, but they can simply be deleted. In general, we recommend
  5205. deleting all the trivial moves whose source and destination are the
  5206. same location.
  5207. %
  5208. The following is the output of \code{patch\_instructions} on the
  5209. running example.
  5210. \begin{center}
  5211. {\if\edition\racketEd
  5212. \begin{minipage}{0.4\textwidth}
  5213. \begin{lstlisting}
  5214. movq $1, -8(%rbp)
  5215. movq $42, %rcx
  5216. movq -8(%rbp), -8(%rbp)
  5217. addq $7, -8(%rbp)
  5218. movq -8(%rbp), -16(%rbp)
  5219. movq -8(%rbp), -8(%rbp)
  5220. addq %rcx, -8(%rbp)
  5221. movq -16(%rbp), %rcx
  5222. negq %rcx
  5223. movq -8(%rbp), %rax
  5224. addq %rcx, %rax
  5225. jmp conclusion
  5226. \end{lstlisting}
  5227. \end{minipage}
  5228. $\Rightarrow\qquad$
  5229. \begin{minipage}{0.45\textwidth}
  5230. \begin{lstlisting}
  5231. movq $1, -8(%rbp)
  5232. movq $42, %rcx
  5233. addq $7, -8(%rbp)
  5234. movq -8(%rbp), %rax
  5235. movq %rax, -16(%rbp)
  5236. addq %rcx, -8(%rbp)
  5237. movq -16(%rbp), %rcx
  5238. negq %rcx
  5239. movq -8(%rbp), %rax
  5240. addq %rcx, %rax
  5241. jmp conclusion
  5242. \end{lstlisting}
  5243. \end{minipage}
  5244. \fi}
  5245. {\if\edition\pythonEd
  5246. \begin{minipage}{0.4\textwidth}
  5247. \begin{lstlisting}
  5248. movq $1, -8(%rbp)
  5249. movq $42, %rcx
  5250. movq -8(%rbp), -8(%rbp)
  5251. addq $7, -8(%rbp)
  5252. movq -8(%rbp), -16(%rbp)
  5253. movq -8(%rbp), -8(%rbp)
  5254. addq %rcx, -8(%rbp)
  5255. movq -16(%rbp), %rcx
  5256. negq %rcx
  5257. movq -8(%rbp), -8(%rbp)
  5258. addq %rcx, -8(%rbp)
  5259. movq -8(%rbp), %rdi
  5260. callq print_int
  5261. \end{lstlisting}
  5262. \end{minipage}
  5263. $\Rightarrow\qquad$
  5264. \begin{minipage}{0.45\textwidth}
  5265. \begin{lstlisting}
  5266. movq $1, -8(%rbp)
  5267. movq $42, %rcx
  5268. addq $7, -8(%rbp)
  5269. movq -8(%rbp), %rax
  5270. movq %rax, -16(%rbp)
  5271. addq %rcx, -8(%rbp)
  5272. movq -16(%rbp), %rcx
  5273. negq %rcx
  5274. addq %rcx, -8(%rbp)
  5275. movq -8(%rbp), %rdi
  5276. callq print_int
  5277. \end{lstlisting}
  5278. \end{minipage}
  5279. \fi}
  5280. \end{center}
  5281. \begin{exercise}\normalfont\normalsize
  5282. %
  5283. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5284. %
  5285. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5286. %in the \code{run-tests.rkt} script.
  5287. %
  5288. Run the script to test the \code{patch\_instructions} pass.
  5289. \end{exercise}
  5290. \section{Prelude and Conclusion}
  5291. \label{sec:print-x86-reg-alloc}
  5292. \index{subject}{calling conventions}
  5293. \index{subject}{prelude}\index{subject}{conclusion}
  5294. Recall that this pass generates the prelude and conclusion
  5295. instructions to satisfy the x86 calling conventions
  5296. (Section~\ref{sec:calling-conventions}). With the addition of the
  5297. register allocator, the callee-saved registers used by the register
  5298. allocator must be saved in the prelude and restored in the conclusion.
  5299. In the \code{allocate\_registers} pass,
  5300. %
  5301. \racket{add an entry to the \itm{info}
  5302. of \code{X86Program} named \code{used\_callee}}
  5303. %
  5304. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5305. %
  5306. that stores the set of callee-saved registers that were assigned to
  5307. variables. The \code{prelude\_and\_conclusion} pass can then access
  5308. this information to decide which callee-saved registers need to be
  5309. saved and restored.
  5310. %
  5311. When calculating the amount to adjust the \code{rsp} in the prelude,
  5312. make sure to take into account the space used for saving the
  5313. callee-saved registers. Also, don't forget that the frame needs to be
  5314. a multiple of 16 bytes! We recommend using the following equation for
  5315. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5316. of spilled variables and $C$ be the number of callee-saved registers
  5317. that were allocated to variables. The $\itm{align}$ function rounds a
  5318. number up to the nearest 16 bytes.
  5319. \[
  5320. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5321. \]
  5322. The reason we subtract $8\itm{C}$ in the above equation is because the
  5323. prelude uses \code{pushq} to save each of the callee-saved registers,
  5324. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5325. \racket{An overview of all of the passes involved in register
  5326. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5327. {\if\edition\racketEd
  5328. \begin{figure}[tbp]
  5329. \begin{tcolorbox}[colback=white]
  5330. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5331. \node (Lvar) at (0,2) {\large \LangVar{}};
  5332. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5333. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5334. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5335. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5336. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5337. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5338. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5339. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5340. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5341. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5342. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5343. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5344. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5345. \path[->,bend left=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5346. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5347. \path[->,bend right=15] (x86-2-2) edge [left] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5348. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5349. \path[->,bend left=15] (x86-4) edge [left] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5350. \end{tikzpicture}
  5351. \end{tcolorbox}
  5352. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5353. \label{fig:reg-alloc-passes}
  5354. \end{figure}
  5355. \fi}
  5356. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5357. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5358. use of registers and the stack, we limit the register allocator for
  5359. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5360. the prelude\index{subject}{prelude} of the \code{main} function, we
  5361. push \code{rbx} onto the stack because it is a callee-saved register
  5362. and it was assigned to a variable by the register allocator. We
  5363. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5364. reserve space for the one spilled variable. After that subtraction,
  5365. the \code{rsp} is aligned to 16 bytes.
  5366. Moving on to the program proper, we see how the registers were
  5367. allocated.
  5368. %
  5369. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5370. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5371. %
  5372. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5373. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5374. were assigned to \code{rbx}.}
  5375. %
  5376. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5377. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5378. callee-save register \code{rbx} onto the stack. The spilled variables
  5379. must be placed lower on the stack than the saved callee-save
  5380. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5381. \code{-16(\%rbp)}.
  5382. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5383. done in the prelude. We move the stack pointer up by \code{8} bytes
  5384. (the room for spilled variables), then we pop the old values of
  5385. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5386. \code{retq} to return control to the operating system.
  5387. \begin{figure}[tbp]
  5388. \begin{minipage}{0.55\textwidth}
  5389. \begin{tcolorbox}[colback=white]
  5390. % var_test_28.rkt
  5391. % (use-minimal-set-of-registers! #t)
  5392. % and only rbx rcx
  5393. % tmp 0 rbx
  5394. % z 1 rcx
  5395. % y 0 rbx
  5396. % w 2 16(%rbp)
  5397. % v 0 rbx
  5398. % x 0 rbx
  5399. {\if\edition\racketEd
  5400. \begin{lstlisting}
  5401. start:
  5402. movq $1, %rbx
  5403. movq $42, -16(%rbp)
  5404. addq $7, %rbx
  5405. movq %rbx, %rcx
  5406. addq -16(%rbp), %rcx
  5407. negq %rbx
  5408. movq %rcx, %rax
  5409. addq %rbx, %rax
  5410. jmp conclusion
  5411. .globl main
  5412. main:
  5413. pushq %rbp
  5414. movq %rsp, %rbp
  5415. pushq %rbx
  5416. subq $8, %rsp
  5417. jmp start
  5418. conclusion:
  5419. addq $8, %rsp
  5420. popq %rbx
  5421. popq %rbp
  5422. retq
  5423. \end{lstlisting}
  5424. \fi}
  5425. {\if\edition\pythonEd
  5426. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5427. \begin{lstlisting}
  5428. .globl main
  5429. main:
  5430. pushq %rbp
  5431. movq %rsp, %rbp
  5432. pushq %rbx
  5433. subq $8, %rsp
  5434. movq $1, %rcx
  5435. movq $42, %rbx
  5436. addq $7, %rcx
  5437. movq %rcx, -16(%rbp)
  5438. addq %rbx, -16(%rbp)
  5439. negq %rcx
  5440. movq -16(%rbp), %rbx
  5441. addq %rcx, %rbx
  5442. movq %rbx, %rdi
  5443. callq print_int
  5444. addq $8, %rsp
  5445. popq %rbx
  5446. popq %rbp
  5447. retq
  5448. \end{lstlisting}
  5449. \fi}
  5450. \end{tcolorbox}
  5451. \end{minipage}
  5452. \caption{The x86 output from the running example
  5453. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5454. and \code{rcx}.}
  5455. \label{fig:running-example-x86}
  5456. \end{figure}
  5457. \begin{exercise}\normalfont\normalsize
  5458. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5459. %
  5460. \racket{
  5461. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5462. list of passes and the call to \code{compiler-tests}.}
  5463. %
  5464. Run the script to test the complete compiler for \LangVar{} that
  5465. performs register allocation.
  5466. \end{exercise}
  5467. \section{Challenge: Move Biasing}
  5468. \label{sec:move-biasing}
  5469. \index{subject}{move biasing}
  5470. This section describes an enhancement to the register allocator,
  5471. called move biasing, for students who are looking for an extra
  5472. challenge.
  5473. {\if\edition\racketEd
  5474. To motivate the need for move biasing we return to the running example
  5475. but this time we use all of the general purpose registers. So we have
  5476. the following mapping of color numbers to registers.
  5477. \[
  5478. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5479. \]
  5480. Using the same assignment of variables to color numbers that was
  5481. produced by the register allocator described in the last section, we
  5482. get the following program.
  5483. \begin{center}
  5484. \begin{minipage}{0.3\textwidth}
  5485. \begin{lstlisting}
  5486. movq $1, v
  5487. movq $42, w
  5488. movq v, x
  5489. addq $7, x
  5490. movq x, y
  5491. movq x, z
  5492. addq w, z
  5493. movq y, t
  5494. negq t
  5495. movq z, %rax
  5496. addq t, %rax
  5497. jmp conclusion
  5498. \end{lstlisting}
  5499. \end{minipage}
  5500. $\Rightarrow\qquad$
  5501. \begin{minipage}{0.45\textwidth}
  5502. \begin{lstlisting}
  5503. movq $1, %rdx
  5504. movq $42, %rcx
  5505. movq %rdx, %rdx
  5506. addq $7, %rdx
  5507. movq %rdx, %rsi
  5508. movq %rdx, %rdx
  5509. addq %rcx, %rdx
  5510. movq %rsi, %rcx
  5511. negq %rcx
  5512. movq %rdx, %rax
  5513. addq %rcx, %rax
  5514. jmp conclusion
  5515. \end{lstlisting}
  5516. \end{minipage}
  5517. \end{center}
  5518. In the above output code there are two \key{movq} instructions that
  5519. can be removed because their source and target are the same. However,
  5520. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5521. register, we could instead remove three \key{movq} instructions. We
  5522. can accomplish this by taking into account which variables appear in
  5523. \key{movq} instructions with which other variables.
  5524. \fi}
  5525. {\if\edition\pythonEd
  5526. %
  5527. To motivate the need for move biasing we return to the running example
  5528. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5529. remove three trivial move instructions from the running
  5530. example. However, we could remove another trivial move if we were able
  5531. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5532. We say that two variables $p$ and $q$ are \emph{move
  5533. related}\index{subject}{move related} if they participate together in
  5534. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5535. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5536. when there are multiple variables with the same saturation, prefer
  5537. variables that can be assigned to a color that is the same as the
  5538. color of a move related variable. Furthermore, when the register
  5539. allocator chooses a color for a variable, it should prefer a color
  5540. that has already been used for a move-related variable (assuming that
  5541. they do not interfere). Of course, this preference should not override
  5542. the preference for registers over stack locations. So this preference
  5543. should be used as a tie breaker when choosing between registers or
  5544. when choosing between stack locations.
  5545. We recommend representing the move relationships in a graph, similar
  5546. to how we represented interference. The following is the \emph{move
  5547. graph} for our running example.
  5548. {\if\edition\racketEd
  5549. \[
  5550. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5551. \node (rax) at (0,0) {$\ttm{rax}$};
  5552. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5553. \node (t) at (0,2) {$\ttm{t}$};
  5554. \node (z) at (3,2) {$\ttm{z}$};
  5555. \node (x) at (6,2) {$\ttm{x}$};
  5556. \node (y) at (3,0) {$\ttm{y}$};
  5557. \node (w) at (6,0) {$\ttm{w}$};
  5558. \node (v) at (9,0) {$\ttm{v}$};
  5559. \draw (v) to (x);
  5560. \draw (x) to (y);
  5561. \draw (x) to (z);
  5562. \draw (y) to (t);
  5563. \end{tikzpicture}
  5564. \]
  5565. \fi}
  5566. %
  5567. {\if\edition\pythonEd
  5568. \[
  5569. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5570. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5571. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5572. \node (z) at (3,2) {$\ttm{z}$};
  5573. \node (x) at (6,2) {$\ttm{x}$};
  5574. \node (y) at (3,0) {$\ttm{y}$};
  5575. \node (w) at (6,0) {$\ttm{w}$};
  5576. \node (v) at (9,0) {$\ttm{v}$};
  5577. \draw (y) to (t0);
  5578. \draw (z) to (x);
  5579. \draw (z) to (t1);
  5580. \draw (x) to (y);
  5581. \draw (x) to (v);
  5582. \end{tikzpicture}
  5583. \]
  5584. \fi}
  5585. {\if\edition\racketEd
  5586. Now we replay the graph coloring, pausing to see the coloring of
  5587. \code{y}. Recall the following configuration. The most saturated vertices
  5588. were \code{w} and \code{y}.
  5589. \[
  5590. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5591. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5592. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5593. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5594. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5595. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5596. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5597. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5598. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5599. \draw (t1) to (rax);
  5600. \draw (t1) to (z);
  5601. \draw (z) to (y);
  5602. \draw (z) to (w);
  5603. \draw (x) to (w);
  5604. \draw (y) to (w);
  5605. \draw (v) to (w);
  5606. \draw (v) to (rsp);
  5607. \draw (w) to (rsp);
  5608. \draw (x) to (rsp);
  5609. \draw (y) to (rsp);
  5610. \path[-.,bend left=15] (z) edge node {} (rsp);
  5611. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5612. \draw (rax) to (rsp);
  5613. \end{tikzpicture}
  5614. \]
  5615. %
  5616. Last time we chose to color \code{w} with $0$. But this time we see
  5617. that \code{w} is not move related to any vertex, but \code{y} is move
  5618. related to \code{t}. So we choose to color \code{y} with $0$, the
  5619. same color as \code{t}.
  5620. \[
  5621. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5622. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5623. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5624. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5625. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5626. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5627. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5628. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5629. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5630. \draw (t1) to (rax);
  5631. \draw (t1) to (z);
  5632. \draw (z) to (y);
  5633. \draw (z) to (w);
  5634. \draw (x) to (w);
  5635. \draw (y) to (w);
  5636. \draw (v) to (w);
  5637. \draw (v) to (rsp);
  5638. \draw (w) to (rsp);
  5639. \draw (x) to (rsp);
  5640. \draw (y) to (rsp);
  5641. \path[-.,bend left=15] (z) edge node {} (rsp);
  5642. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5643. \draw (rax) to (rsp);
  5644. \end{tikzpicture}
  5645. \]
  5646. Now \code{w} is the most saturated, so we color it $2$.
  5647. \[
  5648. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5649. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5650. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5651. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5652. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5653. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5654. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5655. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5656. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5657. \draw (t1) to (rax);
  5658. \draw (t1) to (z);
  5659. \draw (z) to (y);
  5660. \draw (z) to (w);
  5661. \draw (x) to (w);
  5662. \draw (y) to (w);
  5663. \draw (v) to (w);
  5664. \draw (v) to (rsp);
  5665. \draw (w) to (rsp);
  5666. \draw (x) to (rsp);
  5667. \draw (y) to (rsp);
  5668. \path[-.,bend left=15] (z) edge node {} (rsp);
  5669. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5670. \draw (rax) to (rsp);
  5671. \end{tikzpicture}
  5672. \]
  5673. At this point, vertices \code{x} and \code{v} are most saturated, but
  5674. \code{x} is move related to \code{y} and \code{z}, so we color
  5675. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5676. \[
  5677. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5678. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5679. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5680. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5681. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5682. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5683. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5684. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5685. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5686. \draw (t1) to (rax);
  5687. \draw (t) to (z);
  5688. \draw (z) to (y);
  5689. \draw (z) to (w);
  5690. \draw (x) to (w);
  5691. \draw (y) to (w);
  5692. \draw (v) to (w);
  5693. \draw (v) to (rsp);
  5694. \draw (w) to (rsp);
  5695. \draw (x) to (rsp);
  5696. \draw (y) to (rsp);
  5697. \path[-.,bend left=15] (z) edge node {} (rsp);
  5698. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5699. \draw (rax) to (rsp);
  5700. \end{tikzpicture}
  5701. \]
  5702. \fi}
  5703. %
  5704. {\if\edition\pythonEd
  5705. Now we replay the graph coloring, pausing before the coloring of
  5706. \code{w}. Recall the following configuration. The most saturated vertices
  5707. were \code{tmp\_1}, \code{w}, and \code{y}.
  5708. \[
  5709. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5710. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5711. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5712. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5713. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5714. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5715. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5716. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5717. \draw (t0) to (t1);
  5718. \draw (t0) to (z);
  5719. \draw (z) to (y);
  5720. \draw (z) to (w);
  5721. \draw (x) to (w);
  5722. \draw (y) to (w);
  5723. \draw (v) to (w);
  5724. \end{tikzpicture}
  5725. \]
  5726. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5727. or \code{y}, but note that \code{w} is not move related to any
  5728. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5729. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5730. \code{y} and color it $0$, we can delete another move instruction.
  5731. \[
  5732. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5733. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5734. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5735. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5736. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5737. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5738. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5739. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5740. \draw (t0) to (t1);
  5741. \draw (t0) to (z);
  5742. \draw (z) to (y);
  5743. \draw (z) to (w);
  5744. \draw (x) to (w);
  5745. \draw (y) to (w);
  5746. \draw (v) to (w);
  5747. \end{tikzpicture}
  5748. \]
  5749. Now \code{w} is the most saturated, so we color it $2$.
  5750. \[
  5751. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5752. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5753. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5754. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5755. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5756. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5757. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5758. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5759. \draw (t0) to (t1);
  5760. \draw (t0) to (z);
  5761. \draw (z) to (y);
  5762. \draw (z) to (w);
  5763. \draw (x) to (w);
  5764. \draw (y) to (w);
  5765. \draw (v) to (w);
  5766. \end{tikzpicture}
  5767. \]
  5768. To finish the coloring, \code{x} and \code{v} get $0$ and
  5769. \code{tmp\_1} gets $1$.
  5770. \[
  5771. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5772. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5773. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5774. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5775. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5776. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5777. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5778. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5779. \draw (t0) to (t1);
  5780. \draw (t0) to (z);
  5781. \draw (z) to (y);
  5782. \draw (z) to (w);
  5783. \draw (x) to (w);
  5784. \draw (y) to (w);
  5785. \draw (v) to (w);
  5786. \end{tikzpicture}
  5787. \]
  5788. \fi}
  5789. So we have the following assignment of variables to registers.
  5790. {\if\edition\racketEd
  5791. \begin{gather*}
  5792. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5793. \ttm{w} \mapsto \key{\%rsi}, \,
  5794. \ttm{x} \mapsto \key{\%rcx}, \,
  5795. \ttm{y} \mapsto \key{\%rcx}, \,
  5796. \ttm{z} \mapsto \key{\%rdx}, \,
  5797. \ttm{t} \mapsto \key{\%rcx} \}
  5798. \end{gather*}
  5799. \fi}
  5800. {\if\edition\pythonEd
  5801. \begin{gather*}
  5802. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5803. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5804. \ttm{x} \mapsto \key{\%rcx}, \,
  5805. \ttm{y} \mapsto \key{\%rcx}, \\
  5806. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5807. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5808. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5809. \end{gather*}
  5810. \fi}
  5811. We apply this register assignment to the running example, on the left,
  5812. to obtain the code in the middle. The \code{patch\_instructions} then
  5813. deletes the trivial moves to obtain the code on the right.
  5814. {\if\edition\racketEd
  5815. \begin{minipage}{0.25\textwidth}
  5816. \begin{lstlisting}
  5817. movq $1, v
  5818. movq $42, w
  5819. movq v, x
  5820. addq $7, x
  5821. movq x, y
  5822. movq x, z
  5823. addq w, z
  5824. movq y, t
  5825. negq t
  5826. movq z, %rax
  5827. addq t, %rax
  5828. jmp conclusion
  5829. \end{lstlisting}
  5830. \end{minipage}
  5831. $\Rightarrow\qquad$
  5832. \begin{minipage}{0.25\textwidth}
  5833. \begin{lstlisting}
  5834. movq $1, %rcx
  5835. movq $42, %rsi
  5836. movq %rcx, %rcx
  5837. addq $7, %rcx
  5838. movq %rcx, %rcx
  5839. movq %rcx, %rdx
  5840. addq %rsi, %rdx
  5841. movq %rcx, %rcx
  5842. negq %rcx
  5843. movq %rdx, %rax
  5844. addq %rcx, %rax
  5845. jmp conclusion
  5846. \end{lstlisting}
  5847. \end{minipage}
  5848. $\Rightarrow\qquad$
  5849. \begin{minipage}{0.25\textwidth}
  5850. \begin{lstlisting}
  5851. movq $1, %rcx
  5852. movq $42, %rsi
  5853. addq $7, %rcx
  5854. movq %rcx, %rdx
  5855. addq %rsi, %rdx
  5856. negq %rcx
  5857. movq %rdx, %rax
  5858. addq %rcx, %rax
  5859. jmp conclusion
  5860. \end{lstlisting}
  5861. \end{minipage}
  5862. \fi}
  5863. {\if\edition\pythonEd
  5864. \begin{minipage}{0.20\textwidth}
  5865. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5866. movq $1, v
  5867. movq $42, w
  5868. movq v, x
  5869. addq $7, x
  5870. movq x, y
  5871. movq x, z
  5872. addq w, z
  5873. movq y, tmp_0
  5874. negq tmp_0
  5875. movq z, tmp_1
  5876. addq tmp_0, tmp_1
  5877. movq tmp_1, %rdi
  5878. callq _print_int
  5879. \end{lstlisting}
  5880. \end{minipage}
  5881. ${\Rightarrow\qquad}$
  5882. \begin{minipage}{0.30\textwidth}
  5883. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5884. movq $1, %rcx
  5885. movq $42, -16(%rbp)
  5886. movq %rcx, %rcx
  5887. addq $7, %rcx
  5888. movq %rcx, %rcx
  5889. movq %rcx, -8(%rbp)
  5890. addq -16(%rbp), -8(%rbp)
  5891. movq %rcx, %rcx
  5892. negq %rcx
  5893. movq -8(%rbp), -8(%rbp)
  5894. addq %rcx, -8(%rbp)
  5895. movq -8(%rbp), %rdi
  5896. callq _print_int
  5897. \end{lstlisting}
  5898. \end{minipage}
  5899. ${\Rightarrow\qquad}$
  5900. \begin{minipage}{0.20\textwidth}
  5901. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5902. movq $1, %rcx
  5903. movq $42, -16(%rbp)
  5904. addq $7, %rcx
  5905. movq %rcx, -8(%rbp)
  5906. movq -16(%rbp), %rax
  5907. addq %rax, -8(%rbp)
  5908. negq %rcx
  5909. addq %rcx, -8(%rbp)
  5910. movq -8(%rbp), %rdi
  5911. callq print_int
  5912. \end{lstlisting}
  5913. \end{minipage}
  5914. \fi}
  5915. \begin{exercise}\normalfont\normalsize
  5916. Change your implementation of \code{allocate\_registers} to take move
  5917. biasing into account. Create two new tests that include at least one
  5918. opportunity for move biasing and visually inspect the output x86
  5919. programs to make sure that your move biasing is working properly. Make
  5920. sure that your compiler still passes all of the tests.
  5921. \end{exercise}
  5922. %To do: another neat challenge would be to do
  5923. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5924. %% \subsection{Output of the Running Example}
  5925. %% \label{sec:reg-alloc-output}
  5926. % challenge: prioritize variables based on execution frequencies
  5927. % and the number of uses of a variable
  5928. % challenge: enhance the coloring algorithm using Chaitin's
  5929. % approach of prioritizing high-degree variables
  5930. % by removing low-degree variables (coloring them later)
  5931. % from the interference graph
  5932. \section{Further Reading}
  5933. \label{sec:register-allocation-further-reading}
  5934. Early register allocation algorithms were developed for Fortran
  5935. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5936. of graph coloring began in the late 1970s and early 1980s with the
  5937. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5938. algorithm is based on the following observation of
  5939. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5940. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5941. $v$ removed is also $k$ colorable. To see why, suppose that the
  5942. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5943. different colors, but since there are less than $k$ neighbors, there
  5944. will be one or more colors left over to use for coloring $v$ in $G$.
  5945. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5946. less than $k$ from the graph and recursively colors the rest of the
  5947. graph. Upon returning from the recursion, it colors $v$ with one of
  5948. the available colors and returns. \citet{Chaitin:1982vn} augments
  5949. this algorithm to handle spilling as follows. If there are no vertices
  5950. of degree lower than $k$ then pick a vertex at random, spill it,
  5951. remove it from the graph, and proceed recursively to color the rest of
  5952. the graph.
  5953. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5954. move-related and that don't interfere with each other, a process
  5955. called \emph{coalescing}. While coalescing decreases the number of
  5956. moves, it can make the graph more difficult to
  5957. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5958. which two variables are merged only if they have fewer than $k$
  5959. neighbors of high degree. \citet{George:1996aa} observe that
  5960. conservative coalescing is sometimes too conservative and make it more
  5961. aggressive by iterating the coalescing with the removal of low-degree
  5962. vertices.
  5963. %
  5964. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5965. also propose \emph{biased coloring} in which a variable is assigned to
  5966. the same color as another move-related variable if possible, as
  5967. discussed in Section~\ref{sec:move-biasing}.
  5968. %
  5969. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5970. performs coalescing, graph coloring, and spill code insertion until
  5971. all variables have been assigned a location.
  5972. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5973. spills variables that don't have to be: a high-degree variable can be
  5974. colorable if many of its neighbors are assigned the same color.
  5975. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5976. high-degree vertex is not immediately spilled. Instead the decision is
  5977. deferred until after the recursive call, at which point it is apparent
  5978. whether there is actually an available color or not. We observe that
  5979. this algorithm is equivalent to the smallest-last ordering
  5980. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5981. be registers and the rest to be stack locations.
  5982. %% biased coloring
  5983. Earlier editions of the compiler course at Indiana University
  5984. \citep{Dybvig:2010aa} were based on the algorithm of
  5985. \citet{Briggs:1994kx}.
  5986. The smallest-last ordering algorithm is one of many \emph{greedy}
  5987. coloring algorithms. A greedy coloring algorithm visits all the
  5988. vertices in a particular order and assigns each one the first
  5989. available color. An \emph{offline} greedy algorithm chooses the
  5990. ordering up-front, prior to assigning colors. The algorithm of
  5991. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5992. ordering does not depend on the colors assigned. Other orderings are
  5993. possible. For example, \citet{Chow:1984ys} order variables according
  5994. to an estimate of runtime cost.
  5995. An \emph{online} greedy coloring algorithm uses information about the
  5996. current assignment of colors to influence the order in which the
  5997. remaining vertices are colored. The saturation-based algorithm
  5998. described in this chapter is one such algorithm. We choose to use
  5999. saturation-based coloring because it is fun to introduce graph
  6000. coloring via Sudoku!
  6001. A register allocator may choose to map each variable to just one
  6002. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6003. variable to one or more locations. The later can be achieved by
  6004. \emph{live range splitting}, where a variable is replaced by several
  6005. variables that each handle part of its live
  6006. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6007. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6008. %% replacement algorithm, bottom-up local
  6009. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6010. %% Cooper: top-down (priority bassed), bottom-up
  6011. %% top-down
  6012. %% order variables by priority (estimated cost)
  6013. %% caveat: split variables into two groups:
  6014. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6015. %% color the constrained ones first
  6016. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6017. %% cite J. Cocke for an algorithm that colors variables
  6018. %% in a high-degree first ordering
  6019. %Register Allocation via Usage Counts, Freiburghouse CACM
  6020. \citet{Palsberg:2007si} observe that many of the interference graphs
  6021. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  6022. that is, every cycle with four or more edges has an edge which is not
  6023. part of the cycle but which connects two vertices on the cycle. Such
  6024. graphs can be optimally colored by the greedy algorithm with a vertex
  6025. ordering determined by maximum cardinality search.
  6026. In situations where compile time is of utmost importance, such as in
  6027. just-in-time compilers, graph coloring algorithms can be too expensive
  6028. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  6029. appropriate.
  6030. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6031. \chapter{Booleans and Conditionals}
  6032. \label{ch:Lif}
  6033. \index{subject}{Boolean}
  6034. \index{subject}{control flow}
  6035. \index{subject}{conditional expression}
  6036. The \LangVar{} language only has a single kind of value, the
  6037. integers. In this chapter we add a second kind of value, the Booleans,
  6038. to create the \LangIf{} language. The Boolean values \emph{true} and
  6039. \emph{false} are written \TRUE{} and \FALSE{} respectively in
  6040. \racket{Racket}\python{Python}. The \LangIf{} language includes
  6041. several operations that involve Booleans (\key{and}, \key{not},
  6042. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6043. expression \python{and statement}. With the addition of \key{if},
  6044. programs can have non-trivial control flow which
  6045. %
  6046. \racket{impacts \code{explicate\_control} and liveness analysis}
  6047. %
  6048. \python{impacts liveness analysis and motivates a new pass named
  6049. \code{explicate\_control}}.
  6050. %
  6051. Also, because we now have two kinds of values, we need to handle
  6052. programs that apply an operation to the wrong kind of value, such as
  6053. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6054. There are two language design options for such situations. One option
  6055. is to signal an error and the other is to provide a wider
  6056. interpretation of the operation. \racket{The Racket
  6057. language}\python{Python} uses a mixture of these two options,
  6058. depending on the operation and the kind of value. For example, the
  6059. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6060. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6061. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6062. %
  6063. \racket{On the other hand, \code{(car 1)} results in a run-time error
  6064. in Racket because \code{car} expects a pair.}
  6065. %
  6066. \python{On the other hand, \code{1[0]} results in a run-time error
  6067. in Python because an ``\code{int} object is not subscriptable''.}
  6068. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6069. design choices as \racket{Racket}\python{Python}, except much of the
  6070. error detection happens at compile time instead of run
  6071. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6072. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6073. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  6074. Racket}\python{MyPy} reports a compile-time error
  6075. %
  6076. \racket{because Racket expects the type of the argument to be of the form
  6077. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6078. %
  6079. \python{stating that a ``value of type \code{int} is not indexable''.}
  6080. The \LangIf{} language performs type checking during compilation like
  6081. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study
  6082. the alternative choice, that is, a dynamically typed language like
  6083. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6084. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6085. restrictive, for example, rejecting \racket{\code{(not
  6086. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6087. fairly simple because the focus of this book is on compilation, not
  6088. type systems, about which there are already several excellent
  6089. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6090. This chapter is organized as follows. We begin by defining the syntax
  6091. and interpreter for the \LangIf{} language
  6092. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  6093. checking and define a type checker for \LangIf{}
  6094. (Section~\ref{sec:type-check-Lif}).
  6095. %
  6096. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6097. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  6098. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  6099. %
  6100. The remaining sections of this chapter discuss how Booleans and
  6101. conditional control flow require changes to the existing compiler
  6102. passes and the addition of new ones. We introduce the \code{shrink}
  6103. pass to translates some operators into others, thereby reducing the
  6104. number of operators that need to be handled in later passes.
  6105. %
  6106. The main event of this chapter is the \code{explicate\_control} pass
  6107. that is responsible for translating \code{if}'s into conditional
  6108. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  6109. %
  6110. Regarding register allocation, there is the interesting question of
  6111. how to handle conditional \code{goto}'s during liveness analysis.
  6112. \section{The \LangIf{} Language}
  6113. \label{sec:lang-if}
  6114. The concrete and abstract syntax of the \LangIf{} language are defined in
  6115. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6116. respectively. The \LangIf{} language includes all of
  6117. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6118. \FALSE{},\racket{ and} the \code{if} expression\python{, and the
  6119. \code{if} statement}. We expand the set of operators to include
  6120. \begin{enumerate}
  6121. \item the logical operators \key{and}, \key{or}, and \key{not},
  6122. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6123. for comparing integers or Booleans for equality, and
  6124. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6125. comparing integers.
  6126. \end{enumerate}
  6127. \racket{We reorganize the abstract syntax for the primitive
  6128. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  6129. rule for all of them. This means that the grammar no longer checks
  6130. whether the arity of an operators matches the number of
  6131. arguments. That responsibility is moved to the type checker for
  6132. \LangIf{} (Section~\ref{sec:type-check-Lif}).}
  6133. \newcommand{\LifGrammarRacket}{
  6134. \begin{array}{lcl}
  6135. \Type &::=& \key{Boolean} \\
  6136. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6137. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6138. \Exp &::=& \itm{bool}
  6139. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6140. \MID (\key{not}\;\Exp) \\
  6141. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6142. \end{array}
  6143. }
  6144. \newcommand{\LifASTRacket}{
  6145. \begin{array}{lcl}
  6146. \Type &::=& \key{Boolean} \\
  6147. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6148. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6149. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6150. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6151. \end{array}
  6152. }
  6153. \newcommand{\LintOpAST}{
  6154. \begin{array}{rcl}
  6155. \Type &::=& \key{Integer} \\
  6156. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6157. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6158. \end{array}
  6159. }
  6160. \newcommand{\LifGrammarPython}{
  6161. \begin{array}{rcl}
  6162. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6163. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6164. \MID \key{not}~\Exp \\
  6165. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6166. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6167. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6168. \end{array}
  6169. }
  6170. \newcommand{\LifASTPython}{
  6171. \begin{array}{lcl}
  6172. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6173. \itm{unaryop} &::=& \code{Not()} \\
  6174. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6175. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6176. \Exp &::=& \BOOL{\itm{bool}}
  6177. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6178. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6179. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6180. \end{array}
  6181. }
  6182. \begin{figure}[tp]
  6183. \centering
  6184. \begin{tcolorbox}[colback=white]
  6185. {\if\edition\racketEd
  6186. \[
  6187. \begin{array}{l}
  6188. \gray{\LintGrammarRacket{}} \\ \hline
  6189. \gray{\LvarGrammarRacket{}} \\ \hline
  6190. \LifGrammarRacket{} \\
  6191. \begin{array}{lcl}
  6192. \LangIfM{} &::=& \Exp
  6193. \end{array}
  6194. \end{array}
  6195. \]
  6196. \fi}
  6197. {\if\edition\pythonEd
  6198. \[
  6199. \begin{array}{l}
  6200. \gray{\LintGrammarPython} \\ \hline
  6201. \gray{\LvarGrammarPython} \\ \hline
  6202. \LifGrammarPython \\
  6203. \begin{array}{rcl}
  6204. \LangIfM{} &::=& \Stmt^{*}
  6205. \end{array}
  6206. \end{array}
  6207. \]
  6208. \fi}
  6209. \end{tcolorbox}
  6210. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6211. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6212. \label{fig:Lif-concrete-syntax}
  6213. \end{figure}
  6214. \begin{figure}[tp]
  6215. \begin{minipage}{0.66\textwidth}
  6216. \begin{tcolorbox}[colback=white]
  6217. \centering
  6218. {\if\edition\racketEd
  6219. \[
  6220. \begin{array}{l}
  6221. \gray{\LintOpAST} \\ \hline
  6222. \gray{\LvarASTRacket{}} \\ \hline
  6223. \LifASTRacket{} \\
  6224. \begin{array}{lcl}
  6225. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6226. \end{array}
  6227. \end{array}
  6228. \]
  6229. \fi}
  6230. {\if\edition\pythonEd
  6231. \[
  6232. \begin{array}{l}
  6233. \gray{\LintASTPython} \\ \hline
  6234. \gray{\LvarASTPython} \\ \hline
  6235. \LifASTPython \\
  6236. \begin{array}{lcl}
  6237. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6238. \end{array}
  6239. \end{array}
  6240. \]
  6241. \fi}
  6242. \end{tcolorbox}
  6243. \end{minipage}
  6244. \caption{The abstract syntax of \LangIf{}.}
  6245. \label{fig:Lif-syntax}
  6246. \end{figure}
  6247. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6248. which inherits from the interpreter for \LangVar{}
  6249. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6250. evaluate to the corresponding Boolean values. The conditional
  6251. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6252. and then either evaluates $e_2$ or $e_3$ depending on whether
  6253. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6254. \code{and}, \code{or}, and \code{not} behave according to
  6255. propositional logic. In addition, the \code{and} and \code{or}
  6256. operations perform \emph{short-circuit evaluation}.
  6257. %
  6258. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6259. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6260. %
  6261. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6262. evaluated if $e_1$ evaluates to \TRUE{}.
  6263. \racket{With the increase in the number of primitive operations, the
  6264. interpreter would become repetitive without some care. We refactor
  6265. the case for \code{Prim}, moving the code that differs with each
  6266. operation into the \code{interp\_op} method shown in in
  6267. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6268. \code{or} operations separately because of their short-circuiting
  6269. behavior.}
  6270. \begin{figure}[tbp]
  6271. \begin{tcolorbox}[colback=white]
  6272. {\if\edition\racketEd
  6273. \begin{lstlisting}
  6274. (define interp-Lif-class
  6275. (class interp-Lvar-class
  6276. (super-new)
  6277. (define/public (interp_op op) ...)
  6278. (define/override ((interp_exp env) e)
  6279. (define recur (interp_exp env))
  6280. (match e
  6281. [(Bool b) b]
  6282. [(If cnd thn els)
  6283. (match (recur cnd)
  6284. [#t (recur thn)]
  6285. [#f (recur els)])]
  6286. [(Prim 'and (list e1 e2))
  6287. (match (recur e1)
  6288. [#t (match (recur e2) [#t #t] [#f #f])]
  6289. [#f #f])]
  6290. [(Prim 'or (list e1 e2))
  6291. (define v1 (recur e1))
  6292. (match v1
  6293. [#t #t]
  6294. [#f (match (recur e2) [#t #t] [#f #f])])]
  6295. [(Prim op args)
  6296. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6297. [else ((super interp_exp env) e)]))
  6298. ))
  6299. (define (interp_Lif p)
  6300. (send (new interp-Lif-class) interp_program p))
  6301. \end{lstlisting}
  6302. \fi}
  6303. {\if\edition\pythonEd
  6304. \begin{lstlisting}
  6305. class InterpLif(InterpLvar):
  6306. def interp_exp(self, e, env):
  6307. match e:
  6308. case IfExp(test, body, orelse):
  6309. if self.interp_exp(test, env):
  6310. return self.interp_exp(body, env)
  6311. else:
  6312. return self.interp_exp(orelse, env)
  6313. case UnaryOp(Not(), v):
  6314. return not self.interp_exp(v, env)
  6315. case BoolOp(And(), values):
  6316. if self.interp_exp(values[0], env):
  6317. return self.interp_exp(values[1], env)
  6318. else:
  6319. return False
  6320. case BoolOp(Or(), values):
  6321. if self.interp_exp(values[0], env):
  6322. return True
  6323. else:
  6324. return self.interp_exp(values[1], env)
  6325. case Compare(left, [cmp], [right]):
  6326. l = self.interp_exp(left, env)
  6327. r = self.interp_exp(right, env)
  6328. return self.interp_cmp(cmp)(l, r)
  6329. case _:
  6330. return super().interp_exp(e, env)
  6331. def interp_stmts(self, ss, env):
  6332. if len(ss) == 0:
  6333. return
  6334. match ss[0]:
  6335. case If(test, body, orelse):
  6336. if self.interp_exp(test, env):
  6337. return self.interp_stmts(body + ss[1:], env)
  6338. else:
  6339. return self.interp_stmts(orelse + ss[1:], env)
  6340. case _:
  6341. return super().interp_stmts(ss, env)
  6342. ...
  6343. \end{lstlisting}
  6344. \fi}
  6345. \end{tcolorbox}
  6346. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6347. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6348. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6349. \label{fig:interp-Lif}
  6350. \end{figure}
  6351. {\if\edition\racketEd
  6352. \begin{figure}[tbp]
  6353. \begin{tcolorbox}[colback=white]
  6354. \begin{lstlisting}
  6355. (define/public (interp_op op)
  6356. (match op
  6357. ['+ fx+]
  6358. ['- fx-]
  6359. ['read read-fixnum]
  6360. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6361. ['eq? (lambda (v1 v2)
  6362. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6363. (and (boolean? v1) (boolean? v2))
  6364. (and (vector? v1) (vector? v2)))
  6365. (eq? v1 v2)]))]
  6366. ['< (lambda (v1 v2)
  6367. (cond [(and (fixnum? v1) (fixnum? v2))
  6368. (< v1 v2)]))]
  6369. ['<= (lambda (v1 v2)
  6370. (cond [(and (fixnum? v1) (fixnum? v2))
  6371. (<= v1 v2)]))]
  6372. ['> (lambda (v1 v2)
  6373. (cond [(and (fixnum? v1) (fixnum? v2))
  6374. (> v1 v2)]))]
  6375. ['>= (lambda (v1 v2)
  6376. (cond [(and (fixnum? v1) (fixnum? v2))
  6377. (>= v1 v2)]))]
  6378. [else (error 'interp_op "unknown operator")]))
  6379. \end{lstlisting}
  6380. \end{tcolorbox}
  6381. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6382. \label{fig:interp-op-Lif}
  6383. \end{figure}
  6384. \fi}
  6385. {\if\edition\pythonEd
  6386. \begin{figure}
  6387. \begin{tcolorbox}[colback=white]
  6388. \begin{lstlisting}
  6389. class InterpLif(InterpLvar):
  6390. ...
  6391. def interp_cmp(self, cmp):
  6392. match cmp:
  6393. case Lt():
  6394. return lambda x, y: x < y
  6395. case LtE():
  6396. return lambda x, y: x <= y
  6397. case Gt():
  6398. return lambda x, y: x > y
  6399. case GtE():
  6400. return lambda x, y: x >= y
  6401. case Eq():
  6402. return lambda x, y: x == y
  6403. case NotEq():
  6404. return lambda x, y: x != y
  6405. \end{lstlisting}
  6406. \end{tcolorbox}
  6407. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6408. \label{fig:interp-cmp-Lif}
  6409. \end{figure}
  6410. \fi}
  6411. \section{Type Checking \LangIf{} Programs}
  6412. \label{sec:type-check-Lif}
  6413. \index{subject}{type checking}
  6414. \index{subject}{semantic analysis}
  6415. It is helpful to think about type checking in two complementary
  6416. ways. A type checker predicts the type of value that will be produced
  6417. by each expression in the program. For \LangIf{}, we have just two types,
  6418. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6419. {\if\edition\racketEd
  6420. \begin{lstlisting}
  6421. (+ 10 (- (+ 12 20)))
  6422. \end{lstlisting}
  6423. \fi}
  6424. {\if\edition\pythonEd
  6425. \begin{lstlisting}
  6426. 10 + -(12 + 20)
  6427. \end{lstlisting}
  6428. \fi}
  6429. \noindent produces a value of type \INTTY{} while
  6430. {\if\edition\racketEd
  6431. \begin{lstlisting}
  6432. (and (not #f) #t)
  6433. \end{lstlisting}
  6434. \fi}
  6435. {\if\edition\pythonEd
  6436. \begin{lstlisting}
  6437. (not False) and True
  6438. \end{lstlisting}
  6439. \fi}
  6440. \noindent produces a value of type \BOOLTY{}.
  6441. A second way to think about type checking is that it enforces a set of
  6442. rules about which operators can be applied to which kinds of
  6443. values. For example, our type checker for \LangIf{} signals an error
  6444. for the below expression {\if\edition\racketEd
  6445. \begin{lstlisting}
  6446. (not (+ 10 (- (+ 12 20))))
  6447. \end{lstlisting}
  6448. \fi}
  6449. {\if\edition\pythonEd
  6450. \begin{lstlisting}
  6451. not (10 + -(12 + 20))
  6452. \end{lstlisting}
  6453. \fi}
  6454. \noindent The subexpression
  6455. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6456. \python{\code{(10 + -(12 + 20))}}
  6457. has type \INTTY{} but the type checker enforces the rule that the
  6458. argument of \code{not} must be an expression of type \BOOLTY{}.
  6459. We implement type checking using classes and methods because they
  6460. provide the open recursion needed to reuse code as we extend the type
  6461. checker in later chapters, analogous to the use of classes and methods
  6462. for the interpreters (Section~\ref{sec:extensible-interp}).
  6463. We separate the type checker for the \LangVar{} subset into its own
  6464. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6465. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6466. from the type checker for \LangVar{}. These type checkers are in the
  6467. files
  6468. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6469. and
  6470. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6471. of the support code.
  6472. %
  6473. Each type checker is a structurally recursive function over the AST.
  6474. Given an input expression \code{e}, the type checker either signals an
  6475. error or returns \racket{an expression and} its type.
  6476. %
  6477. \racket{It returns an expression because there are situations in which
  6478. we want to change or update the expression.}
  6479. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6480. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6481. \INTTY{}. To handle variables, the type checker uses the environment
  6482. \code{env} to map variables to types.
  6483. %
  6484. \racket{Consider the case for \key{let}. We type check the
  6485. initializing expression to obtain its type \key{T} and then
  6486. associate type \code{T} with the variable \code{x} in the
  6487. environment used to type check the body of the \key{let}. Thus,
  6488. when the type checker encounters a use of variable \code{x}, it can
  6489. find its type in the environment.}
  6490. %
  6491. \python{Consider the case for assignment. We type check the
  6492. initializing expression to obtain its type \key{t}. If the variable
  6493. \code{lhs.id} is already in the environment because there was a
  6494. prior assignment, we check that this initializer has the same type
  6495. as the prior one. If this is the first assignment to the variable,
  6496. we associate type \code{t} with the variable \code{lhs.id} in the
  6497. environment. Thus, when the type checker encounters a use of
  6498. variable \code{x}, it can find its type in the environment.}
  6499. %
  6500. \racket{Regarding primitive operators, we recursively analyze the
  6501. arguments and then invoke \code{type\_check\_op} to check whether
  6502. the argument types are allowed.}
  6503. %
  6504. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6505. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6506. \racket{Several auxiliary methods are used in the type checker. The
  6507. method \code{operator-types} defines a dictionary that maps the
  6508. operator names to their parameter and return types. The
  6509. \code{type-equal?} method determines whether two types are equal,
  6510. which for now simply dispatches to \code{equal?} (deep
  6511. equality). The \code{check-type-equal?} method triggers an error if
  6512. the two types are not equal. The \code{type-check-op} method looks
  6513. up the operator in the \code{operator-types} dictionary and then
  6514. checks whether the argument types are equal to the parameter types.
  6515. The result is the return type of the operator.}
  6516. %
  6517. \python{The auxiliary method \code{check\_type\_equal} triggers
  6518. an error if the two types are not equal.}
  6519. \begin{figure}[tbp]
  6520. \begin{tcolorbox}[colback=white]
  6521. {\if\edition\racketEd
  6522. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6523. (define type-check-Lvar-class
  6524. (class object%
  6525. (super-new)
  6526. (define/public (operator-types)
  6527. '((+ . ((Integer Integer) . Integer))
  6528. (- . ((Integer Integer) . Integer))
  6529. (read . (() . Integer))))
  6530. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6531. (define/public (check-type-equal? t1 t2 e)
  6532. (unless (type-equal? t1 t2)
  6533. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6534. (define/public (type-check-op op arg-types e)
  6535. (match (dict-ref (operator-types) op)
  6536. [`(,param-types . ,return-type)
  6537. (for ([at arg-types] [pt param-types])
  6538. (check-type-equal? at pt e))
  6539. return-type]
  6540. [else (error 'type-check-op "unrecognized ~a" op)]))
  6541. (define/public (type-check-exp env)
  6542. (lambda (e)
  6543. (match e
  6544. [(Int n) (values (Int n) 'Integer)]
  6545. [(Var x) (values (Var x) (dict-ref env x))]
  6546. [(Let x e body)
  6547. (define-values (e^ Te) ((type-check-exp env) e))
  6548. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6549. (values (Let x e^ b) Tb)]
  6550. [(Prim op es)
  6551. (define-values (new-es ts)
  6552. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6553. (values (Prim op new-es) (type-check-op op ts e))]
  6554. [else (error 'type-check-exp "couldn't match" e)])))
  6555. (define/public (type-check-program e)
  6556. (match e
  6557. [(Program info body)
  6558. (define-values (body^ Tb) ((type-check-exp '()) body))
  6559. (check-type-equal? Tb 'Integer body)
  6560. (Program info body^)]
  6561. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6562. ))
  6563. (define (type-check-Lvar p)
  6564. (send (new type-check-Lvar-class) type-check-program p))
  6565. \end{lstlisting}
  6566. \fi}
  6567. {\if\edition\pythonEd
  6568. \begin{lstlisting}[escapechar=`]
  6569. class TypeCheckLvar:
  6570. def check_type_equal(self, t1, t2, e):
  6571. if t1 != t2:
  6572. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6573. raise Exception(msg)
  6574. def type_check_exp(self, e, env):
  6575. match e:
  6576. case BinOp(left, (Add() | Sub()), right):
  6577. l = self.type_check_exp(left, env)
  6578. check_type_equal(l, int, left)
  6579. r = self.type_check_exp(right, env)
  6580. check_type_equal(r, int, right)
  6581. return int
  6582. case UnaryOp(USub(), v):
  6583. t = self.type_check_exp(v, env)
  6584. check_type_equal(t, int, v)
  6585. return int
  6586. case Name(id):
  6587. return env[id]
  6588. case Constant(value) if isinstance(value, int):
  6589. return int
  6590. case Call(Name('input_int'), []):
  6591. return int
  6592. def type_check_stmts(self, ss, env):
  6593. if len(ss) == 0:
  6594. return
  6595. match ss[0]:
  6596. case Assign([lhs], value):
  6597. t = self.type_check_exp(value, env)
  6598. if lhs.id in env:
  6599. check_type_equal(env[lhs.id], t, value)
  6600. else:
  6601. env[lhs.id] = t
  6602. return self.type_check_stmts(ss[1:], env)
  6603. case Expr(Call(Name('print'), [arg])):
  6604. t = self.type_check_exp(arg, env)
  6605. check_type_equal(t, int, arg)
  6606. return self.type_check_stmts(ss[1:], env)
  6607. case Expr(value):
  6608. self.type_check_exp(value, env)
  6609. return self.type_check_stmts(ss[1:], env)
  6610. def type_check_P(self, p):
  6611. match p:
  6612. case Module(body):
  6613. self.type_check_stmts(body, {})
  6614. \end{lstlisting}
  6615. \fi}
  6616. \end{tcolorbox}
  6617. \caption{Type checker for the \LangVar{} language.}
  6618. \label{fig:type-check-Lvar}
  6619. \end{figure}
  6620. \begin{figure}[tbp]
  6621. \begin{tcolorbox}[colback=white]
  6622. {\if\edition\racketEd
  6623. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6624. (define type-check-Lif-class
  6625. (class type-check-Lvar-class
  6626. (super-new)
  6627. (inherit check-type-equal?)
  6628. (define/override (operator-types)
  6629. (append '((and . ((Boolean Boolean) . Boolean))
  6630. (or . ((Boolean Boolean) . Boolean))
  6631. (< . ((Integer Integer) . Boolean))
  6632. (<= . ((Integer Integer) . Boolean))
  6633. (> . ((Integer Integer) . Boolean))
  6634. (>= . ((Integer Integer) . Boolean))
  6635. (not . ((Boolean) . Boolean)))
  6636. (super operator-types)))
  6637. (define/override (type-check-exp env)
  6638. (lambda (e)
  6639. (match e
  6640. [(Bool b) (values (Bool b) 'Boolean)]
  6641. [(Prim 'eq? (list e1 e2))
  6642. (define-values (e1^ T1) ((type-check-exp env) e1))
  6643. (define-values (e2^ T2) ((type-check-exp env) e2))
  6644. (check-type-equal? T1 T2 e)
  6645. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6646. [(If cnd thn els)
  6647. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6648. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6649. (define-values (els^ Te) ((type-check-exp env) els))
  6650. (check-type-equal? Tc 'Boolean e)
  6651. (check-type-equal? Tt Te e)
  6652. (values (If cnd^ thn^ els^) Te)]
  6653. [else ((super type-check-exp env) e)])))
  6654. ))
  6655. (define (type-check-Lif p)
  6656. (send (new type-check-Lif-class) type-check-program p))
  6657. \end{lstlisting}
  6658. \fi}
  6659. {\if\edition\pythonEd
  6660. \begin{lstlisting}
  6661. class TypeCheckLif(TypeCheckLvar):
  6662. def type_check_exp(self, e, env):
  6663. match e:
  6664. case Constant(value) if isinstance(value, bool):
  6665. return bool
  6666. case BinOp(left, Sub(), right):
  6667. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6668. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6669. return int
  6670. case UnaryOp(Not(), v):
  6671. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6672. return bool
  6673. case BoolOp(op, values):
  6674. left = values[0] ; right = values[1]
  6675. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6676. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6677. return bool
  6678. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6679. or isinstance(cmp, NotEq):
  6680. l = self.type_check_exp(left, env)
  6681. r = self.type_check_exp(right, env)
  6682. check_type_equal(l, r, e)
  6683. return bool
  6684. case Compare(left, [cmp], [right]):
  6685. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6686. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6687. return bool
  6688. case IfExp(test, body, orelse):
  6689. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6690. b = self.type_check_exp(body, env)
  6691. o = self.type_check_exp(orelse, env)
  6692. check_type_equal(b, o, e)
  6693. return b
  6694. case _:
  6695. return super().type_check_exp(e, env)
  6696. def type_check_stmts(self, ss, env):
  6697. if len(ss) == 0:
  6698. return
  6699. match ss[0]:
  6700. case If(test, body, orelse):
  6701. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6702. b = self.type_check_stmts(body, env)
  6703. o = self.type_check_stmts(orelse, env)
  6704. check_type_equal(b, o, ss[0])
  6705. return self.type_check_stmts(ss[1:], env)
  6706. case _:
  6707. return super().type_check_stmts(ss, env)
  6708. \end{lstlisting}
  6709. \fi}
  6710. \end{tcolorbox}
  6711. \caption{Type checker for the \LangIf{} language.}
  6712. \label{fig:type-check-Lif}
  6713. \end{figure}
  6714. The type checker for \LangIf{} is defined in
  6715. Figure~\ref{fig:type-check-Lif}.
  6716. %
  6717. The type of a Boolean constant is \BOOLTY{}.
  6718. %
  6719. \racket{The \code{operator-types} function adds dictionary entries for
  6720. the new operators.}
  6721. %
  6722. \python{Logical not requires its argument to be a \BOOLTY{} and
  6723. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6724. %
  6725. The equality operator requires the two arguments to have the same type
  6726. and therefore we handle it separately from the other operators.
  6727. %
  6728. \python{The other comparisons (less-than, etc.) require their
  6729. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6730. %
  6731. The condition of an \code{if} must
  6732. be of \BOOLTY{} type and the two branches must have the same type.
  6733. \begin{exercise}\normalfont\normalsize
  6734. Create 10 new test programs in \LangIf{}. Half of the programs should
  6735. have a type error. For those programs, create an empty file with the
  6736. same base name but with file extension \code{.tyerr}. For example, if
  6737. the test
  6738. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6739. is expected to error, then create
  6740. an empty file named \code{cond\_test\_14.tyerr}.
  6741. %
  6742. \racket{This indicates to \code{interp-tests} and
  6743. \code{compiler-tests} that a type error is expected. }
  6744. %
  6745. The other half of the test programs should not have type errors.
  6746. %
  6747. \racket{In the \code{run-tests.rkt} script, change the second argument
  6748. of \code{interp-tests} and \code{compiler-tests} to
  6749. \code{type-check-Lif}, which causes the type checker to run prior to
  6750. the compiler passes. Temporarily change the \code{passes} to an
  6751. empty list and run the script, thereby checking that the new test
  6752. programs either type check or not as intended.}
  6753. %
  6754. Run the test script to check that these test programs type check as
  6755. expected.
  6756. \end{exercise}
  6757. \clearpage
  6758. \section{The \LangCIf{} Intermediate Language}
  6759. \label{sec:Cif}
  6760. {\if\edition\racketEd
  6761. %
  6762. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  6763. comparison operators to the \Exp{} non-terminal and the literals
  6764. \TRUE{} and \FALSE{} to the \Arg{} non-terminal. Regarding control
  6765. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  6766. \Tail{} non-terminal. The condition of an \code{if} statement is a
  6767. comparison operation and the branches are \code{goto} statements,
  6768. making it straightforward to compile \code{if} statements to x86. The
  6769. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  6770. expressions. A \code{goto} statement transfers control to the $\Tail$
  6771. expression corresponding to its label.
  6772. %
  6773. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6774. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6775. defines its abstract syntax.
  6776. %
  6777. \fi}
  6778. %
  6779. {\if\edition\pythonEd
  6780. %
  6781. The output of \key{explicate\_control} is a language similar to the
  6782. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6783. \code{goto} statements, so we name it \LangCIf{}.
  6784. %
  6785. The \LangCIf{} language supports the same operators as \LangIf{} but
  6786. the arguments of operators are restricted to atomic expressions. The
  6787. \LangCIf{} language does not include \code{if} expressions but it does
  6788. include a restricted form of \code{if} statement. The condition must be
  6789. a comparison and the two branches may only contain \code{goto}
  6790. statements. These restrictions make it easier to translate \code{if}
  6791. statements to x86. The \LangCIf{} language also adds a \code{return}
  6792. statement to finish the program with a specified value.
  6793. %
  6794. The \key{CProgram} construct contains a dictionary mapping labels to
  6795. lists of statements that end with a \code{return} statement, a
  6796. \code{goto}, or a conditional \code{goto}.
  6797. %% Statement lists of this
  6798. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  6799. %% is a control transfer at the end and control only enters at the
  6800. %% beginning of the list, which is marked by the label.
  6801. %
  6802. A \code{goto} statement transfers control to the sequence of statements
  6803. associated with its label.
  6804. %
  6805. The concrete syntax for \LangCIf{} is defined in
  6806. Figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  6807. in Figure~\ref{fig:c1-syntax}.
  6808. %
  6809. \fi}
  6810. %
  6811. \newcommand{\CifGrammarRacket}{
  6812. \begin{array}{lcl}
  6813. \Atm &::=& \itm{bool} \\
  6814. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6815. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6816. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6817. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6818. \end{array}
  6819. }
  6820. \newcommand{\CifASTRacket}{
  6821. \begin{array}{lcl}
  6822. \Atm &::=& \BOOL{\itm{bool}} \\
  6823. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6824. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6825. \Tail &::= & \GOTO{\itm{label}} \\
  6826. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6827. \end{array}
  6828. }
  6829. \newcommand{\CifGrammarPython}{
  6830. \begin{array}{lcl}
  6831. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6832. \Exp &::= & \Atm \MID \CREAD{}
  6833. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6834. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6835. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6836. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  6837. &\MID& \CASSIGN{\Var}{\Exp}
  6838. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6839. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6840. \end{array}
  6841. }
  6842. \newcommand{\CifASTPython}{
  6843. \begin{array}{lcl}
  6844. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6845. \Exp &::= & \Atm \MID \READ{} \\
  6846. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6847. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6848. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6849. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6850. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6851. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6852. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6853. \end{array}
  6854. }
  6855. \begin{figure}[tbp]
  6856. \begin{tcolorbox}[colback=white]
  6857. \small
  6858. {\if\edition\racketEd
  6859. \[
  6860. \begin{array}{l}
  6861. \gray{\CvarGrammarRacket} \\ \hline
  6862. \CifGrammarRacket \\
  6863. \begin{array}{lcl}
  6864. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6865. \end{array}
  6866. \end{array}
  6867. \]
  6868. \fi}
  6869. {\if\edition\pythonEd
  6870. \[
  6871. \begin{array}{l}
  6872. \CifGrammarPython \\
  6873. \begin{array}{lcl}
  6874. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6875. \end{array}
  6876. \end{array}
  6877. \]
  6878. \fi}
  6879. \end{tcolorbox}
  6880. \caption{The concrete syntax of the \LangCIf{} intermediate language,
  6881. an extension of \LangCVar{} (Figure~\ref{fig:c0-concrete-syntax}).}
  6882. \label{fig:c1-concrete-syntax}
  6883. \end{figure}
  6884. \begin{figure}[tp]
  6885. \begin{tcolorbox}[colback=white]
  6886. \small
  6887. {\if\edition\racketEd
  6888. \[
  6889. \begin{array}{l}
  6890. \gray{\CvarASTRacket} \\ \hline
  6891. \CifASTRacket \\
  6892. \begin{array}{lcl}
  6893. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6894. \end{array}
  6895. \end{array}
  6896. \]
  6897. \fi}
  6898. {\if\edition\pythonEd
  6899. \[
  6900. \begin{array}{l}
  6901. \CifASTPython \\
  6902. \begin{array}{lcl}
  6903. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6904. \end{array}
  6905. \end{array}
  6906. \]
  6907. \fi}
  6908. \end{tcolorbox}
  6909. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6910. (Figure~\ref{fig:c0-syntax})}.}
  6911. \label{fig:c1-syntax}
  6912. \end{figure}
  6913. \section{The \LangXIf{} Language}
  6914. \label{sec:x86-if}
  6915. \index{subject}{x86} To implement the new logical operations, the
  6916. comparison operations, and the \key{if} expression\python{ and
  6917. statement}, we delve further into the x86
  6918. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  6919. the concrete and abstract syntax for the \LangXIf{} subset of x86,
  6920. which includes instructions for logical operations, comparisons, and
  6921. \racket{conditional} jumps.
  6922. %
  6923. \python{The abstract syntax for an \LangXIf{} program contains a
  6924. dictionary mapping labels to sequences of instructions, each of
  6925. which we refer to as a \emph{basic block}\index{subject}{basic
  6926. block}.}
  6927. One challenge is that x86 does not provide an instruction that
  6928. directly implements logical negation (\code{not} in \LangIf{} and
  6929. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6930. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6931. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6932. bit of its arguments, and writes the results into its second argument.
  6933. Recall the truth table for exclusive-or:
  6934. \begin{center}
  6935. \begin{tabular}{l|cc}
  6936. & 0 & 1 \\ \hline
  6937. 0 & 0 & 1 \\
  6938. 1 & 1 & 0
  6939. \end{tabular}
  6940. \end{center}
  6941. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6942. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6943. for the bit $1$, the result is the opposite of the second bit. Thus,
  6944. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6945. the first argument as follows, where $\Arg$ is the translation of
  6946. $\Atm$ to x86.
  6947. \[
  6948. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6949. \qquad\Rightarrow\qquad
  6950. \begin{array}{l}
  6951. \key{movq}~ \Arg\key{,} \Var\\
  6952. \key{xorq}~ \key{\$1,} \Var
  6953. \end{array}
  6954. \]
  6955. \newcommand{\GrammarXIf}{
  6956. \begin{array}{lcl}
  6957. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6958. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6959. \Arg &::=& \key{\%}\itm{bytereg}\\
  6960. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6961. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  6962. \MID \key{cmpq}~\Arg\key{,}~\Arg
  6963. \MID \key{set}cc~\Arg
  6964. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  6965. &\MID& \key{j}cc~\itm{label} \\
  6966. \end{array}
  6967. }
  6968. \begin{figure}[tp]
  6969. \begin{tcolorbox}[colback=white]
  6970. \[
  6971. \begin{array}{l}
  6972. \gray{\GrammarXInt} \\ \hline
  6973. \GrammarXIf \\
  6974. \begin{array}{lcl}
  6975. \LangXIfM{} &::= & \key{.globl main} \\
  6976. & & \key{main:} \; \Instr\ldots
  6977. \end{array}
  6978. \end{array}
  6979. \]
  6980. \end{tcolorbox}
  6981. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6982. \label{fig:x86-1-concrete}
  6983. \end{figure}
  6984. \newcommand{\ASTXIfRacket}{
  6985. \begin{array}{lcl}
  6986. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6987. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6988. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  6989. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6990. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6991. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6992. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6993. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6994. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  6995. \end{array}
  6996. }
  6997. \begin{figure}[tp]
  6998. \begin{tcolorbox}[colback=white]
  6999. \small
  7000. {\if\edition\racketEd
  7001. \[\arraycolsep=3pt
  7002. \begin{array}{l}
  7003. \gray{\ASTXIntRacket} \\ \hline
  7004. \ASTXIfRacket \\
  7005. \begin{array}{lcl}
  7006. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7007. \end{array}
  7008. \end{array}
  7009. \]
  7010. \fi}
  7011. %
  7012. {\if\edition\pythonEd
  7013. \[
  7014. \begin{array}{lcl}
  7015. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7016. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7017. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7018. \MID \BYTEREG{\itm{bytereg}} \\
  7019. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7020. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7021. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7022. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7023. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7024. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7025. \MID \PUSHQ{\Arg}} \\
  7026. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7027. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7028. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7029. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7030. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7031. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7032. \Block &::= & \Instr^{+} \\
  7033. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7034. \end{array}
  7035. \]
  7036. \fi}
  7037. \end{tcolorbox}
  7038. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  7039. \label{fig:x86-1}
  7040. \end{figure}
  7041. Next we consider the x86 instructions that are relevant for compiling
  7042. the comparison operations. The \key{cmpq} instruction compares its two
  7043. arguments to determine whether one argument is less than, equal, or
  7044. greater than the other argument. The \key{cmpq} instruction is unusual
  7045. regarding the order of its arguments and where the result is
  7046. placed. The argument order is backwards: if you want to test whether
  7047. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7048. \key{cmpq} is placed in the special EFLAGS register. This register
  7049. cannot be accessed directly but it can be queried by a number of
  7050. instructions, including the \key{set} instruction. The instruction
  7051. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  7052. depending on whether the contents of the EFLAGS register matches the
  7053. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7054. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7055. The \key{set} instruction has a quirk in that its destination argument
  7056. must be single byte register, such as \code{al} (L for lower bits) or
  7057. \code{ah} (H for higher bits), which are part of the \code{rax}
  7058. register. Thankfully, the \key{movzbq} instruction can be used to
  7059. move from a single byte register to a normal 64-bit register. The
  7060. abstract syntax for the \code{set} instruction differs from the
  7061. concrete syntax in that it separates the instruction name from the
  7062. condition code.
  7063. \python{The x86 instructions for jumping are relevant to the
  7064. compilation of \key{if} expressions.}
  7065. %
  7066. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7067. counter to the address of the instruction after the specified
  7068. label.}
  7069. %
  7070. \racket{The x86 instruction for conditional jump is relevant to the
  7071. compilation of \key{if} expressions.}
  7072. %
  7073. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7074. counter to point to the instruction after \itm{label} depending on
  7075. whether the result in the EFLAGS register matches the condition code
  7076. \itm{cc}, otherwise the jump instruction falls through to the next
  7077. instruction. Like the abstract syntax for \code{set}, the abstract
  7078. syntax for conditional jump separates the instruction name from the
  7079. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7080. corresponds to \code{jle foo}. Because the conditional jump instruction
  7081. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7082. a \key{cmpq} instruction to set the EFLAGS register.
  7083. \section{Shrink the \LangIf{} Language}
  7084. \label{sec:shrink-Lif}
  7085. The \LangIf{} language includes several features that are easily
  7086. expressible with other features. For example, \code{and} and \code{or}
  7087. are expressible using \code{if} as follows.
  7088. \begin{align*}
  7089. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7090. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7091. \end{align*}
  7092. By performing these translations in the front-end of the compiler,
  7093. subsequent passes of the compiler do not need to deal with these features,
  7094. making the passes shorter.
  7095. On the other hand, sometimes translations reduce the efficiency of the
  7096. generated code by increasing the number of instructions. For example,
  7097. expressing subtraction in terms of negation
  7098. \[
  7099. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7100. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7101. \]
  7102. produces code with two x86 instructions (\code{negq} and \code{addq})
  7103. instead of just one (\code{subq}).
  7104. \begin{exercise}\normalfont\normalsize
  7105. %
  7106. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7107. the language by translating them to \code{if} expressions in \LangIf{}.
  7108. %
  7109. Create four test programs that involve these operators.
  7110. %
  7111. {\if\edition\racketEd
  7112. In the \code{run-tests.rkt} script, add the following entry for
  7113. \code{shrink} to the list of passes (it should be the only pass at
  7114. this point).
  7115. \begin{lstlisting}
  7116. (list "shrink" shrink interp_Lif type-check-Lif)
  7117. \end{lstlisting}
  7118. This instructs \code{interp-tests} to run the interpreter
  7119. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7120. output of \code{shrink}.
  7121. \fi}
  7122. %
  7123. Run the script to test your compiler on all the test programs.
  7124. \end{exercise}
  7125. {\if\edition\racketEd
  7126. \section{Uniquify Variables}
  7127. \label{sec:uniquify-Lif}
  7128. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7129. \code{if} expressions.
  7130. \begin{exercise}\normalfont\normalsize
  7131. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7132. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7133. \begin{lstlisting}
  7134. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7135. \end{lstlisting}
  7136. Run the script to test your compiler.
  7137. \end{exercise}
  7138. \fi}
  7139. \section{Remove Complex Operands}
  7140. \label{sec:remove-complex-opera-Lif}
  7141. The output language of \code{remove\_complex\_operands} is
  7142. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the monadic
  7143. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7144. but the \code{if} expression is not. All three sub-expressions of an
  7145. \code{if} are allowed to be complex expressions but the operands of
  7146. \code{not} and the comparisons must be atomic.
  7147. %
  7148. \python{We add a new language form, the \code{Begin} expression, to aid
  7149. in the translation of \code{if} expressions. When we recursively
  7150. process the two branches of the \code{if}, we generate temporary
  7151. variables and their initializing expressions. However, these
  7152. expressions may contain side effects and should only be executed
  7153. when the condition of the \code{if} is true (for the ``then''
  7154. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7155. a way to initialize the temporary variables within the two branches
  7156. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7157. form execute the statements $ss$ and then returns the result of
  7158. expression $e$.}
  7159. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7160. the new features in \LangIf{}. When recursively processing
  7161. subexpressions, recall that you should invoke \code{rco\_atom} when
  7162. the output needs to be an \Atm{} (as specified in the grammar for
  7163. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7164. \Exp{}. Regarding \code{if}, it is particularly important to
  7165. \textbf{not} replace its condition with a temporary variable because
  7166. that would interfere with the generation of high-quality output in the
  7167. upcoming \code{explicate\_control} pass.
  7168. \newcommand{\LifMonadASTRacket}{
  7169. \begin{array}{rcl}
  7170. \Atm &::=& \BOOL{\itm{bool}}\\
  7171. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7172. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7173. \MID \IF{\Exp}{\Exp}{\Exp}
  7174. \end{array}
  7175. }
  7176. \newcommand{\LifMonadASTPython}{
  7177. \begin{array}{rcl}
  7178. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7179. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7180. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7181. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7182. \Atm &::=& \BOOL{\itm{bool}}\\
  7183. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7184. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7185. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7186. \end{array}
  7187. }
  7188. \begin{figure}[tp]
  7189. \centering
  7190. \begin{tcolorbox}[colback=white]
  7191. {\if\edition\racketEd
  7192. \[
  7193. \begin{array}{l}
  7194. \gray{\LvarMonadASTRacket} \\ \hline
  7195. \LifMonadASTRacket \\
  7196. \begin{array}{rcl}
  7197. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7198. \end{array}
  7199. \end{array}
  7200. \]
  7201. \fi}
  7202. {\if\edition\pythonEd
  7203. \[
  7204. \begin{array}{l}
  7205. \gray{\LvarMonadASTPython} \\ \hline
  7206. \LifMonadASTPython \\
  7207. \begin{array}{rcl}
  7208. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7209. \end{array}
  7210. \end{array}
  7211. \]
  7212. \fi}
  7213. \end{tcolorbox}
  7214. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7215. (extends \LangVarANF in Figure~\ref{fig:Lvar-anf-syntax}).}
  7216. \label{fig:Lif-anf-syntax}
  7217. \end{figure}
  7218. \begin{exercise}\normalfont\normalsize
  7219. %
  7220. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7221. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7222. %
  7223. Create three new \LangIf{} programs that exercise the interesting
  7224. code in this pass.
  7225. %
  7226. {\if\edition\racketEd
  7227. In the \code{run-tests.rkt} script, add the following entry to the
  7228. list of \code{passes} and then run the script to test your compiler.
  7229. \begin{lstlisting}
  7230. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7231. \end{lstlisting}
  7232. \fi}
  7233. \end{exercise}
  7234. \section{Explicate Control}
  7235. \label{sec:explicate-control-Lif}
  7236. \racket{Recall that the purpose of \code{explicate\_control} is to
  7237. make the order of evaluation explicit in the syntax of the program.
  7238. With the addition of \key{if} this gets more interesting.}
  7239. %
  7240. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7241. %
  7242. The main challenge to overcome is that the condition of an \key{if}
  7243. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7244. condition must be a comparison.
  7245. As a motivating example, consider the following program that has an
  7246. \key{if} expression nested in the condition of another \key{if}.%
  7247. \python{\footnote{Programmers rarely write nested \code{if}
  7248. expressions, but it is not uncommon for the condition of an
  7249. \code{if} statement to be a call of a function that also contains an
  7250. \code{if} statement. When such a function is inlined, the result is
  7251. a nested \code{if} that requires the techniques discussed in this
  7252. section.}}
  7253. % cond_test_41.rkt, if_lt_eq.py
  7254. \begin{center}
  7255. \begin{minipage}{0.96\textwidth}
  7256. {\if\edition\racketEd
  7257. \begin{lstlisting}
  7258. (let ([x (read)])
  7259. (let ([y (read)])
  7260. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7261. (+ y 2)
  7262. (+ y 10))))
  7263. \end{lstlisting}
  7264. \fi}
  7265. {\if\edition\pythonEd
  7266. \begin{lstlisting}
  7267. x = input_int()
  7268. y = input_int()
  7269. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7270. \end{lstlisting}
  7271. \fi}
  7272. \end{minipage}
  7273. \end{center}
  7274. %
  7275. The naive way to compile \key{if} and the comparison operations would
  7276. be to handle each of them in isolation, regardless of their context.
  7277. Each comparison would be translated into a \key{cmpq} instruction
  7278. followed by several instructions to move the result from the EFLAGS
  7279. register into a general purpose register or stack location. Each
  7280. \key{if} would be translated into a \key{cmpq} instruction followed by
  7281. a conditional jump. The generated code for the inner \key{if} in the
  7282. above example would be as follows.
  7283. \begin{center}
  7284. \begin{minipage}{0.96\textwidth}
  7285. \begin{lstlisting}
  7286. cmpq $1, x
  7287. setl %al
  7288. movzbq %al, tmp
  7289. cmpq $1, tmp
  7290. je then_branch_1
  7291. jmp else_branch_1
  7292. \end{lstlisting}
  7293. \end{minipage}
  7294. \end{center}
  7295. Notice that the three instructions starting with \code{setl} are
  7296. redundant: the conditional jump could come immediately after the first
  7297. \code{cmpq}.
  7298. Our goal will be to compile \key{if} expressions so that the relevant
  7299. comparison instruction appears directly before the conditional jump.
  7300. For example, we want to generate the following code for the inner
  7301. \code{if}.
  7302. \begin{center}
  7303. \begin{minipage}{0.96\textwidth}
  7304. \begin{lstlisting}
  7305. cmpq $1, x
  7306. jl then_branch_1
  7307. jmp else_branch_1
  7308. \end{lstlisting}
  7309. \end{minipage}
  7310. \end{center}
  7311. One way to achieve this goal is to reorganize the code at the level of
  7312. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7313. the following code.
  7314. \begin{center}
  7315. \begin{minipage}{0.96\textwidth}
  7316. {\if\edition\racketEd
  7317. \begin{lstlisting}
  7318. (let ([x (read)])
  7319. (let ([y (read)])
  7320. (if (< x 1)
  7321. (if (eq? x 0)
  7322. (+ y 2)
  7323. (+ y 10))
  7324. (if (eq? x 2)
  7325. (+ y 2)
  7326. (+ y 10)))))
  7327. \end{lstlisting}
  7328. \fi}
  7329. {\if\edition\pythonEd
  7330. \begin{lstlisting}
  7331. x = input_int()
  7332. y = input_int()
  7333. print(((y + 2) if x == 0 else (y + 10)) \
  7334. if (x < 1) \
  7335. else ((y + 2) if (x == 2) else (y + 10)))
  7336. \end{lstlisting}
  7337. \fi}
  7338. \end{minipage}
  7339. \end{center}
  7340. Unfortunately, this approach duplicates the two branches from the
  7341. outer \code{if} and a compiler must never duplicate code! After all,
  7342. the two branches could be very large expressions.
  7343. How can we apply the above transformation but without duplicating
  7344. code? In other words, how can two different parts of a program refer
  7345. to one piece of code.
  7346. %
  7347. The answer is that we must move away from abstract syntax \emph{trees}
  7348. and instead use \emph{graphs}.
  7349. %
  7350. At the level of x86 assembly this is straightforward because we can
  7351. label the code for each branch and insert jumps in all the places that
  7352. need to execute the branch. In this way, jump instructions are edges
  7353. in the graph and the basic blocks are the nodes.
  7354. %
  7355. Likewise, our language \LangCIf{} provides the ability to label a
  7356. sequence of statements and to jump to a label via \code{goto}.
  7357. As a preview of what \code{explicate\_control} will do,
  7358. Figure~\ref{fig:explicate-control-s1-38} shows the output of
  7359. \code{explicate\_control} on the above example. Note how the condition
  7360. of every \code{if} is a comparison operation and that we have not
  7361. duplicated any code, but instead used labels and \code{goto} to enable
  7362. sharing of code.
  7363. \begin{figure}[tbp]
  7364. \begin{tcolorbox}[colback=white]
  7365. {\if\edition\racketEd
  7366. \begin{tabular}{lll}
  7367. \begin{minipage}{0.4\textwidth}
  7368. % cond_test_41.rkt
  7369. \begin{lstlisting}
  7370. (let ([x (read)])
  7371. (let ([y (read)])
  7372. (if (if (< x 1)
  7373. (eq? x 0)
  7374. (eq? x 2))
  7375. (+ y 2)
  7376. (+ y 10))))
  7377. \end{lstlisting}
  7378. \end{minipage}
  7379. &
  7380. $\Rightarrow$
  7381. &
  7382. \begin{minipage}{0.55\textwidth}
  7383. \begin{lstlisting}
  7384. start:
  7385. x = (read);
  7386. y = (read);
  7387. if (< x 1)
  7388. goto block_4;
  7389. else
  7390. goto block_5;
  7391. block_4:
  7392. if (eq? x 0)
  7393. goto block_2;
  7394. else
  7395. goto block_3;
  7396. block_5:
  7397. if (eq? x 2)
  7398. goto block_2;
  7399. else
  7400. goto block_3;
  7401. block_2:
  7402. return (+ y 2);
  7403. block_3:
  7404. return (+ y 10);
  7405. \end{lstlisting}
  7406. \end{minipage}
  7407. \end{tabular}
  7408. \fi}
  7409. {\if\edition\pythonEd
  7410. \begin{tabular}{lll}
  7411. \begin{minipage}{0.4\textwidth}
  7412. % cond_test_41.rkt
  7413. \begin{lstlisting}
  7414. x = input_int()
  7415. y = input_int()
  7416. print(y + 2 \
  7417. if (x == 0 \
  7418. if x < 1 \
  7419. else x == 2) \
  7420. else y + 10)
  7421. \end{lstlisting}
  7422. \end{minipage}
  7423. &
  7424. $\Rightarrow$
  7425. &
  7426. \begin{minipage}{0.55\textwidth}
  7427. \begin{lstlisting}
  7428. start:
  7429. x = input_int()
  7430. y = input_int()
  7431. if x < 1:
  7432. goto block_8
  7433. else:
  7434. goto block_9
  7435. block_8:
  7436. if x == 0:
  7437. goto block_4
  7438. else:
  7439. goto block_5
  7440. block_9:
  7441. if x == 2:
  7442. goto block_6
  7443. else:
  7444. goto block_7
  7445. block_4:
  7446. goto block_2
  7447. block_5:
  7448. goto block_3
  7449. block_6:
  7450. goto block_2
  7451. block_7:
  7452. goto block_3
  7453. block_2:
  7454. tmp_0 = y + 2
  7455. goto block_1
  7456. block_3:
  7457. tmp_0 = y + 10
  7458. goto block_1
  7459. block_1:
  7460. print(tmp_0)
  7461. return 0
  7462. \end{lstlisting}
  7463. \end{minipage}
  7464. \end{tabular}
  7465. \fi}
  7466. \end{tcolorbox}
  7467. \caption{Translation from \LangIf{} to \LangCIf{}
  7468. via the \code{explicate\_control}.}
  7469. \label{fig:explicate-control-s1-38}
  7470. \end{figure}
  7471. {\if\edition\racketEd
  7472. %
  7473. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7474. \code{explicate\_control} for \LangVar{} using two recursive
  7475. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7476. former function translates expressions in tail position whereas the
  7477. later function translates expressions on the right-hand-side of a
  7478. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  7479. have a new kind of position to deal with: the predicate position of
  7480. the \key{if}. We need another function, \code{explicate\_pred}, that
  7481. decides how to compile an \key{if} by analyzing its condition. So
  7482. \code{explicate\_pred} takes an \LangIf{} expression and two
  7483. \LangCIf{} tails for the then-branch and else-branch and outputs a
  7484. tail. In the following paragraphs we discuss specific cases in the
  7485. \code{explicate\_tail}, \code{explicate\_assign}, and
  7486. \code{explicate\_pred} functions.
  7487. %
  7488. \fi}
  7489. %
  7490. {\if\edition\pythonEd
  7491. %
  7492. We recommend implementing \code{explicate\_control} using the
  7493. following four auxiliary functions.
  7494. \begin{description}
  7495. \item[\code{explicate\_effect}] generates code for expressions as
  7496. statements, so their result is ignored and only their side effects
  7497. matter.
  7498. \item[\code{explicate\_assign}] generates code for expressions
  7499. on the right-hand side of an assignment.
  7500. \item[\code{explicate\_pred}] generates code for an \code{if}
  7501. expression or statement by analyzing the condition expression.
  7502. \item[\code{explicate\_stmt}] generates code for statements.
  7503. \end{description}
  7504. These four functions should build the dictionary of basic blocks. The
  7505. following auxiliary function can be used to create a new basic block
  7506. from a list of statements. It returns a \code{goto} statement that
  7507. jumps to the new basic block.
  7508. \begin{center}
  7509. \begin{minipage}{\textwidth}
  7510. \begin{lstlisting}
  7511. def create_block(stmts, basic_blocks):
  7512. label = label_name(generate_name('block'))
  7513. basic_blocks[label] = stmts
  7514. return Goto(label)
  7515. \end{lstlisting}
  7516. \end{minipage}
  7517. \end{center}
  7518. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7519. \code{explicate\_control} pass.
  7520. The \code{explicate\_effect} function has three parameters: 1) the
  7521. expression to be compiled, 2) the already-compiled code for this
  7522. expression's \emph{continuation}, that is, the list of statements that
  7523. should execute after this expression, and 3) the dictionary of
  7524. generated basic blocks. The \code{explicate\_effect} function returns
  7525. a list of \LangCIf{} statements and it may add to the dictionary of
  7526. basic blocks.
  7527. %
  7528. Let's consider a few of the cases for the expression to be compiled.
  7529. If the expression to be compiled is a constant, then it can be
  7530. discarded because it has no side effects. If it's a \CREAD{}, then it
  7531. has a side-effect and should be preserved. So the expression should be
  7532. translated into a statement using the \code{Expr} AST class. If the
  7533. expression to be compiled is an \code{if} expression, we translate the
  7534. two branches using \code{explicate\_effect} and then translate the
  7535. condition expression using \code{explicate\_pred}, which generates
  7536. code for the entire \code{if}.
  7537. The \code{explicate\_assign} function has four parameters: 1) the
  7538. right-hand-side of the assignment, 2) the left-hand-side of the
  7539. assignment (the variable), 3) the continuation, and 4) the dictionary
  7540. of basic blocks. The \code{explicate\_assign} function returns a list
  7541. of \LangCIf{} statements and it may add to the dictionary of basic
  7542. blocks.
  7543. When the right-hand-side is an \code{if} expression, there is some
  7544. work to do. In particular, the two branches should be translated using
  7545. \code{explicate\_assign} and the condition expression should be
  7546. translated using \code{explicate\_pred}. Otherwise we can simply
  7547. generate an assignment statement, with the given left and right-hand
  7548. sides, concatenated with its continuation.
  7549. \begin{figure}[tbp]
  7550. \begin{tcolorbox}[colback=white]
  7551. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7552. def explicate_effect(e, cont, basic_blocks):
  7553. match e:
  7554. case IfExp(test, body, orelse):
  7555. ...
  7556. case Call(func, args):
  7557. ...
  7558. case Begin(body, result):
  7559. ...
  7560. case _:
  7561. ...
  7562. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7563. match rhs:
  7564. case IfExp(test, body, orelse):
  7565. ...
  7566. case Begin(body, result):
  7567. ...
  7568. case _:
  7569. return [Assign([lhs], rhs)] + cont
  7570. def explicate_pred(cnd, thn, els, basic_blocks):
  7571. match cnd:
  7572. case Compare(left, [op], [right]):
  7573. goto_thn = create_block(thn, basic_blocks)
  7574. goto_els = create_block(els, basic_blocks)
  7575. return [If(cnd, [goto_thn], [goto_els])]
  7576. case Constant(True):
  7577. return thn;
  7578. case Constant(False):
  7579. return els;
  7580. case UnaryOp(Not(), operand):
  7581. ...
  7582. case IfExp(test, body, orelse):
  7583. ...
  7584. case Begin(body, result):
  7585. ...
  7586. case _:
  7587. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7588. [create_block(els, basic_blocks)],
  7589. [create_block(thn, basic_blocks)])]
  7590. def explicate_stmt(s, cont, basic_blocks):
  7591. match s:
  7592. case Assign([lhs], rhs):
  7593. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7594. case Expr(value):
  7595. return explicate_effect(value, cont, basic_blocks)
  7596. case If(test, body, orelse):
  7597. ...
  7598. def explicate_control(p):
  7599. match p:
  7600. case Module(body):
  7601. new_body = [Return(Constant(0))]
  7602. basic_blocks = {}
  7603. for s in reversed(body):
  7604. new_body = explicate_stmt(s, new_body, basic_blocks)
  7605. basic_blocks[label_name('start')] = new_body
  7606. return CProgram(basic_blocks)
  7607. \end{lstlisting}
  7608. \end{tcolorbox}
  7609. \caption{Skeleton for the \code{explicate\_control} pass.}
  7610. \label{fig:explicate-control-Lif}
  7611. \end{figure}
  7612. \fi}
  7613. {\if\edition\racketEd
  7614. \subsection{Explicate Tail and Assign}
  7615. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7616. additional cases for Boolean constants and \key{if}. The cases for
  7617. \code{if} should recursively compile the two branches using either
  7618. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7619. cases should then invoke \code{explicate\_pred} on the condition
  7620. expression, passing in the generated code for the two branches. For
  7621. example, consider the following program with an \code{if} in tail
  7622. position.
  7623. % cond_test_6.rkt
  7624. \begin{lstlisting}
  7625. (let ([x (read)])
  7626. (if (eq? x 0) 42 777))
  7627. \end{lstlisting}
  7628. The two branches are recursively compiled to return statements. We
  7629. then delegate to \code{explicate\_pred}, passing the condition
  7630. \code{(eq? x 0)} and the two return statements. We return to this
  7631. example shortly when we discuss \code{explicate\_pred}.
  7632. Next let us consider a program with an \code{if} on the right-hand
  7633. side of a \code{let}.
  7634. \begin{lstlisting}
  7635. (let ([y (read)])
  7636. (let ([x (if (eq? y 0) 40 777)])
  7637. (+ x 2)))
  7638. \end{lstlisting}
  7639. Note that the body of the inner \code{let} will have already been
  7640. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7641. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7642. to recursively process both branches of the \code{if}, and we do not
  7643. want to duplicate code, so we generate the following block using an
  7644. auxiliary function named \code{create\_block} that we discuss below.
  7645. \begin{lstlisting}
  7646. block_6:
  7647. return (+ x 2)
  7648. \end{lstlisting}
  7649. We then use \code{goto block\_6;} as the \code{cont} argument for
  7650. compiling the branches. So the two branches compile to
  7651. \begin{center}
  7652. \begin{minipage}{0.2\textwidth}
  7653. \begin{lstlisting}
  7654. x = 40;
  7655. goto block_6;
  7656. \end{lstlisting}
  7657. \end{minipage}
  7658. \hspace{0.5in} and \hspace{0.5in}
  7659. \begin{minipage}{0.2\textwidth}
  7660. \begin{lstlisting}
  7661. x = 777;
  7662. goto block_6;
  7663. \end{lstlisting}
  7664. \end{minipage}
  7665. \end{center}
  7666. Finally, we delegate to \code{explicate\_pred}, passing the condition
  7667. \code{(eq? y 0)} and the above code for the branches.
  7668. \subsection{Create Block}
  7669. We recommend implementing the \code{create\_block} auxiliary function
  7670. as follows, using a global variable \code{basic-blocks} to store a
  7671. dictionary that maps labels to $\Tail$ expressions. The main idea is
  7672. that \code{create\_block} generates a new label and then associates
  7673. the given \code{tail} with the new label in the \code{basic-blocks}
  7674. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  7675. new label. However, if the given \code{tail} is already a \code{Goto},
  7676. then there is no need to generate a new label and entry in
  7677. \code{basic-blocks}; we can simply return that \code{Goto}.
  7678. %
  7679. \begin{lstlisting}
  7680. (define (create_block tail)
  7681. (match tail
  7682. [(Goto label) (Goto label)]
  7683. [else
  7684. (let ([label (gensym 'block)])
  7685. (set! basic-blocks (cons (cons label tail) basic-blocks))
  7686. (Goto label))]))
  7687. \end{lstlisting}
  7688. \fi}
  7689. {\if\edition\racketEd
  7690. \subsection{Explicate Predicate}
  7691. \begin{figure}[tbp]
  7692. \begin{tcolorbox}[colback=white]
  7693. \begin{lstlisting}
  7694. (define (explicate_pred cnd thn els)
  7695. (match cnd
  7696. [(Var x) ___]
  7697. [(Let x rhs body) ___]
  7698. [(Prim 'not (list e)) ___]
  7699. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7700. (IfStmt (Prim op es) (create_block thn)
  7701. (create_block els))]
  7702. [(Bool b) (if b thn els)]
  7703. [(If cnd^ thn^ els^) ___]
  7704. [else (error "explicate_pred unhandled case" cnd)]))
  7705. \end{lstlisting}
  7706. \end{tcolorbox}
  7707. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7708. \label{fig:explicate-pred}
  7709. \end{figure}
  7710. \fi}
  7711. \racket{The skeleton for the \code{explicate\_pred} function is given
  7712. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7713. 1) \code{cnd}, the condition expression of the \code{if},
  7714. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7715. and 3) \code{els}, the code generated by
  7716. explicate for the ``else'' branch. The \code{explicate\_pred}
  7717. function should match on \code{cnd} with a case for
  7718. every kind of expression that can have type \BOOLTY{}.}
  7719. %
  7720. \python{The \code{explicate\_pred} function has four parameters: 1)
  7721. the condition expression, 2) the generated statements for the
  7722. ``then'' branch, 3) the generated statements for the ``else''
  7723. branch, and 4) the dictionary of basic blocks. The
  7724. \code{explicate\_pred} function returns a list of \LangCIf{}
  7725. statements and it may add to the dictionary of basic blocks.}
  7726. Consider the case for comparison operators. We translate the
  7727. comparison to an \code{if} statement whose branches are \code{goto}
  7728. statements created by applying \code{create\_block} to the code
  7729. generated for the \code{thn} and \code{els} branches. Let us
  7730. illustrate this translation by returning to the program with an
  7731. \code{if} expression in tail position, shown again below. We invoke
  7732. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  7733. \python{\code{x == 0}}.
  7734. %
  7735. {\if\edition\racketEd
  7736. \begin{lstlisting}
  7737. (let ([x (read)])
  7738. (if (eq? x 0) 42 777))
  7739. \end{lstlisting}
  7740. \fi}
  7741. %
  7742. {\if\edition\pythonEd
  7743. \begin{lstlisting}
  7744. x = input_int()
  7745. 42 if x == 0 else 777
  7746. \end{lstlisting}
  7747. \fi}
  7748. %
  7749. \noindent The two branches \code{42} and \code{777} were already
  7750. compiled to \code{return} statements, from which we now create the
  7751. following blocks.
  7752. %
  7753. \begin{center}
  7754. \begin{minipage}{\textwidth}
  7755. \begin{lstlisting}
  7756. block_1:
  7757. return 42;
  7758. block_2:
  7759. return 777;
  7760. \end{lstlisting}
  7761. \end{minipage}
  7762. \end{center}
  7763. %
  7764. After that, \code{explicate\_pred} compiles the comparison
  7765. \racket{\code{(eq? x 0)}}
  7766. \python{\code{x == 0}}
  7767. to the following \code{if} statement.
  7768. %
  7769. {\if\edition\racketEd
  7770. \begin{center}
  7771. \begin{minipage}{\textwidth}
  7772. \begin{lstlisting}
  7773. if (eq? x 0)
  7774. goto block_1;
  7775. else
  7776. goto block_2;
  7777. \end{lstlisting}
  7778. \end{minipage}
  7779. \end{center}
  7780. \fi}
  7781. {\if\edition\pythonEd
  7782. \begin{center}
  7783. \begin{minipage}{\textwidth}
  7784. \begin{lstlisting}
  7785. if x == 0:
  7786. goto block_1;
  7787. else
  7788. goto block_2;
  7789. \end{lstlisting}
  7790. \end{minipage}
  7791. \end{center}
  7792. \fi}
  7793. Next consider the case for Boolean constants. We perform a kind of
  7794. partial evaluation\index{subject}{partial evaluation} and output
  7795. either the \code{thn} or \code{els} branch depending on whether the
  7796. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7797. following program.
  7798. {\if\edition\racketEd
  7799. \begin{lstlisting}
  7800. (if #t 42 777)
  7801. \end{lstlisting}
  7802. \fi}
  7803. {\if\edition\pythonEd
  7804. \begin{lstlisting}
  7805. 42 if True else 777
  7806. \end{lstlisting}
  7807. \fi}
  7808. %
  7809. \noindent Again, the two branches \code{42} and \code{777} were
  7810. compiled to \code{return} statements, so \code{explicate\_pred}
  7811. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  7812. code for the ``then'' branch.
  7813. \begin{lstlisting}
  7814. return 42;
  7815. \end{lstlisting}
  7816. This case demonstrates that we sometimes discard the \code{thn} or
  7817. \code{els} blocks that are input to \code{explicate\_pred}.
  7818. The case for \key{if} expressions in \code{explicate\_pred} is
  7819. particularly illuminating because it deals with the challenges we
  7820. discussed above regarding nested \key{if} expressions
  7821. (Figure~\ref{fig:explicate-control-s1-38}). The
  7822. \racket{\lstinline{thn^}}\python{\code{body}} and
  7823. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7824. \key{if} inherit their context from the current one, that is,
  7825. predicate context. So you should recursively apply
  7826. \code{explicate\_pred} to the
  7827. \racket{\lstinline{thn^}}\python{\code{body}} and
  7828. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7829. those recursive calls, pass \code{thn} and \code{els} as the extra
  7830. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7831. inside each recursive call. As discussed above, to avoid duplicating
  7832. code, we need to add them to the dictionary of basic blocks so that we
  7833. can instead refer to them by name and execute them with a \key{goto}.
  7834. {\if\edition\pythonEd
  7835. %
  7836. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7837. three parameters: 1) the statement to be compiled, 2) the code for its
  7838. continuation, and 3) the dictionary of basic blocks. The
  7839. \code{explicate\_stmt} returns a list of statements and it may add to
  7840. the dictionary of basic blocks. The cases for assignment and an
  7841. expression-statement are given in full in the skeleton code: they
  7842. simply dispatch to \code{explicate\_assign} and
  7843. \code{explicate\_effect}, respectively. The case for \code{if}
  7844. statements is not given, and is similar to the case for \code{if}
  7845. expressions.
  7846. The \code{explicate\_control} function itself is given in
  7847. Figure~\ref{fig:explicate-control-Lif}. It applies
  7848. \code{explicate\_stmt} to each statement in the program, from back to
  7849. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7850. used as the continuation parameter in the next call to
  7851. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7852. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7853. the dictionary of basic blocks, labeling it as the ``start'' block.
  7854. %
  7855. \fi}
  7856. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7857. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7858. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7859. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7860. %% results from the two recursive calls. We complete the case for
  7861. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7862. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7863. %% the result $B_5$.
  7864. %% \[
  7865. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7866. %% \quad\Rightarrow\quad
  7867. %% B_5
  7868. %% \]
  7869. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7870. %% inherit the current context, so they are in tail position. Thus, the
  7871. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7872. %% \code{explicate\_tail}.
  7873. %% %
  7874. %% We need to pass $B_0$ as the accumulator argument for both of these
  7875. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7876. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7877. %% to the control-flow graph and obtain a promised goto $G_0$.
  7878. %% %
  7879. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7880. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7881. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7882. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7883. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7884. %% \[
  7885. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7886. %% \]
  7887. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7888. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7889. %% should not be confused with the labels for the blocks that appear in
  7890. %% the generated code. We initially construct unlabeled blocks; we only
  7891. %% attach labels to blocks when we add them to the control-flow graph, as
  7892. %% we see in the next case.
  7893. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7894. %% function. The context of the \key{if} is an assignment to some
  7895. %% variable $x$ and then the control continues to some promised block
  7896. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7897. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7898. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7899. %% branches of the \key{if} inherit the current context, so they are in
  7900. %% assignment positions. Let $B_2$ be the result of applying
  7901. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7902. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7903. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7904. %% the result of applying \code{explicate\_pred} to the predicate
  7905. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7906. %% translates to the promise $B_4$.
  7907. %% \[
  7908. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7909. %% \]
  7910. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7911. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7912. \code{remove\_complex\_operands} pass and then the
  7913. \code{explicate\_control} pass on the example program. We walk through
  7914. the output program.
  7915. %
  7916. Following the order of evaluation in the output of
  7917. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7918. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7919. in the predicate of the inner \key{if}. In the output of
  7920. \code{explicate\_control}, in the
  7921. block labeled \code{start}, are two assignment statements followed by a
  7922. \code{if} statement that branches to \code{block\_4} or
  7923. \code{block\_5}. The blocks associated with those labels contain the
  7924. translations of the code
  7925. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7926. and
  7927. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7928. respectively. In particular, we start \code{block\_4} with the
  7929. comparison
  7930. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7931. and then branch to \code{block\_2} or \code{block\_3},
  7932. which correspond to the two branches of the outer \key{if}, i.e.,
  7933. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7934. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7935. %
  7936. The story for \code{block\_5} is similar to that of \code{block\_4}.
  7937. %
  7938. \python{The \code{block\_1} corresponds to the \code{print} statement
  7939. at the end of the program.}
  7940. {\if\edition\racketEd
  7941. \subsection{Interactions between Explicate and Shrink}
  7942. The way in which the \code{shrink} pass transforms logical operations
  7943. such as \code{and} and \code{or} can impact the quality of code
  7944. generated by \code{explicate\_control}. For example, consider the
  7945. following program.
  7946. % cond_test_21.rkt, and_eq_input.py
  7947. \begin{lstlisting}
  7948. (if (and (eq? (read) 0) (eq? (read) 1))
  7949. 0
  7950. 42)
  7951. \end{lstlisting}
  7952. The \code{and} operation should transform into something that the
  7953. \code{explicate\_pred} function can still analyze and descend through to
  7954. reach the underlying \code{eq?} conditions. Ideally, your
  7955. \code{explicate\_control} pass should generate code similar to the
  7956. following for the above program.
  7957. \begin{center}
  7958. \begin{lstlisting}
  7959. start:
  7960. tmp1 = (read);
  7961. if (eq? tmp1 0) goto block40;
  7962. else goto block39;
  7963. block40:
  7964. tmp2 = (read);
  7965. if (eq? tmp2 1) goto block38;
  7966. else goto block39;
  7967. block38:
  7968. return 0;
  7969. block39:
  7970. return 42;
  7971. \end{lstlisting}
  7972. \end{center}
  7973. \fi}
  7974. \begin{exercise}\normalfont\normalsize
  7975. \racket{
  7976. Implement the pass \code{explicate\_control} by adding the cases for
  7977. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7978. \code{explicate\_assign} functions. Implement the auxiliary function
  7979. \code{explicate\_pred} for predicate contexts.}
  7980. \python{Implement \code{explicate\_control} pass with its
  7981. four auxiliary functions.}
  7982. %
  7983. Create test cases that exercise all of the new cases in the code for
  7984. this pass.
  7985. %
  7986. {\if\edition\racketEd
  7987. Add the following entry to the list of \code{passes} in
  7988. \code{run-tests.rkt} and then run this script to test your compiler.
  7989. \begin{lstlisting}
  7990. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7991. \end{lstlisting}
  7992. \fi}
  7993. \end{exercise}
  7994. \clearpage
  7995. \section{Select Instructions}
  7996. \label{sec:select-Lif}
  7997. \index{subject}{instruction selection}
  7998. The \code{select\_instructions} pass translates \LangCIf{} to
  7999. \LangXIfVar{}.
  8000. %
  8001. \racket{Recall that we implement this pass using three auxiliary
  8002. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  8003. $\Tail$ in \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  8004. %
  8005. \racket{For $\Atm$, we have new cases for the Booleans.}
  8006. %
  8007. \python{We begin with the Boolean constants.}
  8008. We take the usual approach of encoding them as integers.
  8009. \[
  8010. \TRUE{} \quad\Rightarrow\quad \key{1}
  8011. \qquad\qquad
  8012. \FALSE{} \quad\Rightarrow\quad \key{0}
  8013. \]
  8014. For translating statements, we discuss some of the cases. The
  8015. \code{not} operation can be implemented in terms of \code{xorq} as we
  8016. discussed at the beginning of this section. Given an assignment, if
  8017. the left-hand side variable is the same as the argument of \code{not},
  8018. then just the \code{xorq} instruction suffices.
  8019. \[
  8020. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8021. \quad\Rightarrow\quad
  8022. \key{xorq}~\key{\$}1\key{,}~\Var
  8023. \]
  8024. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8025. semantics of x86. In the following translation, let $\Arg$ be the
  8026. result of translating $\Atm$ to x86.
  8027. \[
  8028. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8029. \quad\Rightarrow\quad
  8030. \begin{array}{l}
  8031. \key{movq}~\Arg\key{,}~\Var\\
  8032. \key{xorq}~\key{\$}1\key{,}~\Var
  8033. \end{array}
  8034. \]
  8035. Next consider the cases for equality comparisons. Translating this
  8036. operation to x86 is slightly involved due to the unusual nature of the
  8037. \key{cmpq} instruction that we discussed in Section~\ref{sec:x86-if}.
  8038. We recommend translating an assignment with an equality on the
  8039. right-hand side into a sequence of three instructions. \\
  8040. \begin{tabular}{lll}
  8041. \begin{minipage}{0.4\textwidth}
  8042. \begin{lstlisting}
  8043. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  8044. \end{lstlisting}
  8045. \end{minipage}
  8046. &
  8047. $\Rightarrow$
  8048. &
  8049. \begin{minipage}{0.4\textwidth}
  8050. \begin{lstlisting}
  8051. cmpq |$\Arg_2$|, |$\Arg_1$|
  8052. sete %al
  8053. movzbq %al, |$\Var$|
  8054. \end{lstlisting}
  8055. \end{minipage}
  8056. \end{tabular} \\
  8057. The translations for the other comparison operators are similar to the
  8058. above but use different condition codes for the \code{set} instruction.
  8059. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  8060. \key{goto} and \key{if} statements. Both are straightforward to
  8061. translate to x86.}
  8062. %
  8063. A \key{goto} statement becomes a jump instruction.
  8064. \[
  8065. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8066. \]
  8067. %
  8068. An \key{if} statement becomes a compare instruction followed by a
  8069. conditional jump (for the ``then'' branch) and the fall-through is to
  8070. a regular jump (for the ``else'' branch).\\
  8071. \begin{tabular}{lll}
  8072. \begin{minipage}{0.4\textwidth}
  8073. \begin{lstlisting}
  8074. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8075. goto |$\ell_1$||$\racket{\key{;}}$|
  8076. else|$\python{\key{:}}$|
  8077. goto |$\ell_2$||$\racket{\key{;}}$|
  8078. \end{lstlisting}
  8079. \end{minipage}
  8080. &
  8081. $\Rightarrow$
  8082. &
  8083. \begin{minipage}{0.4\textwidth}
  8084. \begin{lstlisting}
  8085. cmpq |$\Arg_2$|, |$\Arg_1$|
  8086. je |$\ell_1$|
  8087. jmp |$\ell_2$|
  8088. \end{lstlisting}
  8089. \end{minipage}
  8090. \end{tabular} \\
  8091. Again, the translations for the other comparison operators are similar to the
  8092. above but use different condition codes for the conditional jump instruction.
  8093. \python{Regarding the \key{return} statement, we recommend treating it
  8094. as an assignment to the \key{rax} register followed by a jump to the
  8095. conclusion of the \code{main} function.}
  8096. \begin{exercise}\normalfont\normalsize
  8097. Expand your \code{select\_instructions} pass to handle the new
  8098. features of the \LangCIf{} language.
  8099. %
  8100. {\if\edition\racketEd
  8101. Add the following entry to the list of \code{passes} in
  8102. \code{run-tests.rkt}
  8103. \begin{lstlisting}
  8104. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8105. \end{lstlisting}
  8106. \fi}
  8107. %
  8108. Run the script to test your compiler on all the test programs.
  8109. \end{exercise}
  8110. \section{Register Allocation}
  8111. \label{sec:register-allocation-Lif}
  8112. \index{subject}{register allocation}
  8113. The changes required for compiling \LangIf{} affect liveness analysis,
  8114. building the interference graph, and assigning homes, but the graph
  8115. coloring algorithm itself does not change.
  8116. \subsection{Liveness Analysis}
  8117. \label{sec:liveness-analysis-Lif}
  8118. \index{subject}{liveness analysis}
  8119. Recall that for \LangVar{} we implemented liveness analysis for a
  8120. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  8121. the addition of \key{if} expressions to \LangIf{},
  8122. \code{explicate\_control} produces many basic blocks.
  8123. %% We recommend that you create a new auxiliary function named
  8124. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8125. %% control-flow graph.
  8126. The first question is: in what order should we process the basic blocks?
  8127. Recall that to perform liveness analysis on a basic block we need to
  8128. know the live-after set for the last instruction in the block. If a
  8129. basic block has no successors (i.e. contains no jumps to other
  8130. blocks), then it has an empty live-after set and we can immediately
  8131. apply liveness analysis to it. If a basic block has some successors,
  8132. then we need to complete liveness analysis on those blocks
  8133. first. These ordering constraints are the reverse of a
  8134. \emph{topological order}\index{subject}{topological order} on a graph
  8135. representation of the program. In particular, the \emph{control flow
  8136. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8137. of a program has a node for each basic block and an edge for each jump
  8138. from one block to another. It is straightforward to generate a CFG
  8139. from the dictionary of basic blocks. One then transposes the CFG and
  8140. applies the topological sort algorithm.
  8141. %
  8142. %
  8143. \racket{We recommend using the \code{tsort} and \code{transpose}
  8144. functions of the Racket \code{graph} package to accomplish this.}
  8145. %
  8146. \python{We provide implementations of \code{topological\_sort} and
  8147. \code{transpose} in the file \code{graph.py} of the support code.}
  8148. %
  8149. As an aside, a topological ordering is only guaranteed to exist if the
  8150. graph does not contain any cycles. This is the case for the
  8151. control-flow graphs that we generate from \LangIf{} programs.
  8152. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8153. and learn how to handle cycles in the control-flow graph.
  8154. \racket{You'll need to construct a directed graph to represent the
  8155. control-flow graph. Do not use the \code{directed-graph} of the
  8156. \code{graph} package because that only allows at most one edge
  8157. between each pair of vertices, but a control-flow graph may have
  8158. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8159. file in the support code implements a graph representation that
  8160. allows multiple edges between a pair of vertices.}
  8161. {\if\edition\racketEd
  8162. The next question is how to analyze jump instructions. Recall that in
  8163. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8164. \code{label->live} that maps each label to the set of live locations
  8165. at the beginning of its block. We use \code{label->live} to determine
  8166. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8167. that we have many basic blocks, \code{label->live} needs to be updated
  8168. as we process the blocks. In particular, after performing liveness
  8169. analysis on a block, we take the live-before set of its first
  8170. instruction and associate that with the block's label in the
  8171. \code{label->live} alist.
  8172. \fi}
  8173. %
  8174. {\if\edition\pythonEd
  8175. %
  8176. The next question is how to analyze jump instructions. The locations
  8177. that are live before a \code{jmp} should be the locations in
  8178. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8179. maintaining a dictionary named \code{live\_before\_block} that maps each
  8180. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8181. block. After performing liveness analysis on each block, we take the
  8182. live-before set of its first instruction and associate that with the
  8183. block's label in the \code{live\_before\_block} dictionary.
  8184. %
  8185. \fi}
  8186. In \LangXIfVar{} we also have the conditional jump
  8187. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8188. this instruction is particularly interesting because, during
  8189. compilation, we do not know which way a conditional jump will go. So
  8190. we do not know whether to use the live-before set for the block
  8191. associated with the $\itm{label}$ or the live-before set for the
  8192. following instruction. However, there is no harm to the correctness
  8193. of the generated code if we classify more locations as live than the
  8194. ones that are truly live during one particular execution of the
  8195. instruction. Thus, we can take the union of the live-before sets from
  8196. the following instruction and from the mapping for $\itm{label}$ in
  8197. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8198. The auxiliary functions for computing the variables in an
  8199. instruction's argument and for computing the variables read-from ($R$)
  8200. or written-to ($W$) by an instruction need to be updated to handle the
  8201. new kinds of arguments and instructions in \LangXIfVar{}.
  8202. \begin{exercise}\normalfont\normalsize
  8203. {\if\edition\racketEd
  8204. %
  8205. Update the \code{uncover\_live} pass to apply liveness analysis to
  8206. every basic block in the program.
  8207. %
  8208. Add the following entry to the list of \code{passes} in the
  8209. \code{run-tests.rkt} script.
  8210. \begin{lstlisting}
  8211. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8212. \end{lstlisting}
  8213. \fi}
  8214. {\if\edition\pythonEd
  8215. %
  8216. Update the \code{uncover\_live} function to perform liveness analysis,
  8217. in reverse topological order, on all of the basic blocks in the
  8218. program.
  8219. %
  8220. \fi}
  8221. % Check that the live-after sets that you generate for
  8222. % example X matches the following... -Jeremy
  8223. \end{exercise}
  8224. \subsection{Build the Interference Graph}
  8225. \label{sec:build-interference-Lif}
  8226. Many of the new instructions in \LangXIfVar{} can be handled in the
  8227. same way as the instructions in \LangXVar{}.
  8228. % Thus, if your code was
  8229. % already quite general, it will not need to be changed to handle the
  8230. % new instructions. If your code is not general enough, we recommend that
  8231. % you change your code to be more general. For example, you can factor
  8232. % out the computing of the the read and write sets for each kind of
  8233. % instruction into auxiliary functions.
  8234. %
  8235. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8236. similar to the \key{movq} instruction. See rule number 1 in
  8237. Section~\ref{sec:build-interference}.
  8238. \begin{exercise}\normalfont\normalsize
  8239. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8240. {\if\edition\racketEd
  8241. Add the following entries to the list of \code{passes} in the
  8242. \code{run-tests.rkt} script.
  8243. \begin{lstlisting}
  8244. (list "build_interference" build_interference interp-pseudo-x86-1)
  8245. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8246. \end{lstlisting}
  8247. \fi}
  8248. % Check that the interference graph that you generate for
  8249. % example X matches the following graph G... -Jeremy
  8250. \end{exercise}
  8251. \section{Patch Instructions}
  8252. The new instructions \key{cmpq} and \key{movzbq} have some special
  8253. restrictions that need to be handled in the \code{patch\_instructions}
  8254. pass.
  8255. %
  8256. The second argument of the \key{cmpq} instruction must not be an
  8257. immediate value (such as an integer). So if you are comparing two
  8258. immediates, we recommend inserting a \key{movq} instruction to put the
  8259. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8260. one memory reference.
  8261. %
  8262. The second argument of the \key{movzbq} must be a register.
  8263. \begin{exercise}\normalfont\normalsize
  8264. %
  8265. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8266. %
  8267. {\if\edition\racketEd
  8268. Add the following entry to the list of \code{passes} in
  8269. \code{run-tests.rkt} and then run this script to test your compiler.
  8270. \begin{lstlisting}
  8271. (list "patch_instructions" patch_instructions interp-x86-1)
  8272. \end{lstlisting}
  8273. \fi}
  8274. \end{exercise}
  8275. {\if\edition\pythonEd
  8276. \section{Prelude and Conclusion}
  8277. \label{sec:prelude-conclusion-cond}
  8278. The generation of the \code{main} function with its prelude and
  8279. conclusion must change to accommodate how the program now consists of
  8280. one or more basic blocks. After the prelude in \code{main}, jump to
  8281. the \code{start} block. Place the conclusion in a basic block labeled
  8282. with \code{conclusion}.
  8283. \fi}
  8284. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8285. \LangIf{} translated to x86, showing the results of
  8286. \code{explicate\_control}, \code{select\_instructions}, and the final
  8287. x86 assembly.
  8288. \begin{figure}[tbp]
  8289. \begin{tcolorbox}[colback=white]
  8290. {\if\edition\racketEd
  8291. \begin{tabular}{lll}
  8292. \begin{minipage}{0.4\textwidth}
  8293. % cond_test_20.rkt, eq_input.py
  8294. \begin{lstlisting}
  8295. (if (eq? (read) 1) 42 0)
  8296. \end{lstlisting}
  8297. $\Downarrow$
  8298. \begin{lstlisting}
  8299. start:
  8300. tmp7951 = (read);
  8301. if (eq? tmp7951 1)
  8302. goto block7952;
  8303. else
  8304. goto block7953;
  8305. block7952:
  8306. return 42;
  8307. block7953:
  8308. return 0;
  8309. \end{lstlisting}
  8310. $\Downarrow$
  8311. \begin{lstlisting}
  8312. start:
  8313. callq read_int
  8314. movq %rax, tmp7951
  8315. cmpq $1, tmp7951
  8316. je block7952
  8317. jmp block7953
  8318. block7953:
  8319. movq $0, %rax
  8320. jmp conclusion
  8321. block7952:
  8322. movq $42, %rax
  8323. jmp conclusion
  8324. \end{lstlisting}
  8325. \end{minipage}
  8326. &
  8327. $\Rightarrow\qquad$
  8328. \begin{minipage}{0.4\textwidth}
  8329. \begin{lstlisting}
  8330. start:
  8331. callq read_int
  8332. movq %rax, %rcx
  8333. cmpq $1, %rcx
  8334. je block7952
  8335. jmp block7953
  8336. block7953:
  8337. movq $0, %rax
  8338. jmp conclusion
  8339. block7952:
  8340. movq $42, %rax
  8341. jmp conclusion
  8342. .globl main
  8343. main:
  8344. pushq %rbp
  8345. movq %rsp, %rbp
  8346. pushq %r13
  8347. pushq %r12
  8348. pushq %rbx
  8349. pushq %r14
  8350. subq $0, %rsp
  8351. jmp start
  8352. conclusion:
  8353. addq $0, %rsp
  8354. popq %r14
  8355. popq %rbx
  8356. popq %r12
  8357. popq %r13
  8358. popq %rbp
  8359. retq
  8360. \end{lstlisting}
  8361. \end{minipage}
  8362. \end{tabular}
  8363. \fi}
  8364. {\if\edition\pythonEd
  8365. \begin{tabular}{lll}
  8366. \begin{minipage}{0.4\textwidth}
  8367. % cond_test_20.rkt, eq_input.py
  8368. \begin{lstlisting}
  8369. print(42 if input_int() == 1 else 0)
  8370. \end{lstlisting}
  8371. $\Downarrow$
  8372. \begin{lstlisting}
  8373. start:
  8374. tmp_0 = input_int()
  8375. if tmp_0 == 1:
  8376. goto block_3
  8377. else:
  8378. goto block_4
  8379. block_3:
  8380. tmp_1 = 42
  8381. goto block_2
  8382. block_4:
  8383. tmp_1 = 0
  8384. goto block_2
  8385. block_2:
  8386. print(tmp_1)
  8387. return 0
  8388. \end{lstlisting}
  8389. $\Downarrow$
  8390. \begin{lstlisting}
  8391. start:
  8392. callq read_int
  8393. movq %rax, tmp_0
  8394. cmpq 1, tmp_0
  8395. je block_3
  8396. jmp block_4
  8397. block_3:
  8398. movq 42, tmp_1
  8399. jmp block_2
  8400. block_4:
  8401. movq 0, tmp_1
  8402. jmp block_2
  8403. block_2:
  8404. movq tmp_1, %rdi
  8405. callq print_int
  8406. movq 0, %rax
  8407. jmp conclusion
  8408. \end{lstlisting}
  8409. \end{minipage}
  8410. &
  8411. $\Rightarrow\qquad$
  8412. \begin{minipage}{0.4\textwidth}
  8413. \begin{lstlisting}
  8414. .globl main
  8415. main:
  8416. pushq %rbp
  8417. movq %rsp, %rbp
  8418. subq $0, %rsp
  8419. jmp start
  8420. start:
  8421. callq read_int
  8422. movq %rax, %rcx
  8423. cmpq $1, %rcx
  8424. je block_3
  8425. jmp block_4
  8426. block_3:
  8427. movq $42, %rcx
  8428. jmp block_2
  8429. block_4:
  8430. movq $0, %rcx
  8431. jmp block_2
  8432. block_2:
  8433. movq %rcx, %rdi
  8434. callq print_int
  8435. movq $0, %rax
  8436. jmp conclusion
  8437. conclusion:
  8438. addq $0, %rsp
  8439. popq %rbp
  8440. retq
  8441. \end{lstlisting}
  8442. \end{minipage}
  8443. \end{tabular}
  8444. \fi}
  8445. \end{tcolorbox}
  8446. \caption{Example compilation of an \key{if} expression to x86, showing
  8447. the results of \code{explicate\_control},
  8448. \code{select\_instructions}, and the final x86 assembly code. }
  8449. \label{fig:if-example-x86}
  8450. \end{figure}
  8451. \begin{figure}[tbp]
  8452. \begin{tcolorbox}[colback=white]
  8453. {\if\edition\racketEd
  8454. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8455. \node (Lif) at (0,2) {\large \LangIf{}};
  8456. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8457. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8458. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8459. \node (Lif-5) at (9,0) {\large \LangIfANF{}};
  8460. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8461. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8462. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8463. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8464. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8465. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8466. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8467. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8468. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8469. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8470. \path[->,bend left=15] (Lif-4) edge [right] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8471. \path[->,bend right=15] (Lif-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8472. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  8473. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8474. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8475. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8476. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8477. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8478. \end{tikzpicture}
  8479. \fi}
  8480. {\if\edition\pythonEd
  8481. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8482. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8483. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8484. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8485. \node (C-1) at (3,0) {\large \LangCIf{}};
  8486. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8487. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8488. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8489. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8490. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8491. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8492. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8493. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8494. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8495. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8496. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8497. \end{tikzpicture}
  8498. \fi}
  8499. \end{tcolorbox}
  8500. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8501. \label{fig:Lif-passes}
  8502. \end{figure}
  8503. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8504. compilation of \LangIf{}.
  8505. \section{Challenge: Optimize Blocks and Remove Jumps}
  8506. \label{sec:opt-jumps}
  8507. We discuss two optional challenges that involve optimizing the
  8508. control-flow of the program.
  8509. \subsection{Optimize Blocks}
  8510. The algorithm for \code{explicate\_control} that we discussed in
  8511. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8512. blocks. It creates a basic block whenever a continuation \emph{might}
  8513. get used more than once (e.g., whenever the \code{cont} parameter is
  8514. passed into two or more recursive calls). However, some continuation
  8515. arguments may not be used at all. For example, consider the case for
  8516. the constant \TRUE{} in \code{explicate\_pred}, where we discard the
  8517. \code{els} continuation.
  8518. %
  8519. {\if\edition\racketEd
  8520. The following example program falls into this
  8521. case, and it creates two unused blocks.
  8522. \begin{center}
  8523. \begin{tabular}{lll}
  8524. \begin{minipage}{0.4\textwidth}
  8525. % cond_test_82.rkt
  8526. \begin{lstlisting}
  8527. (let ([y (if #t
  8528. (read)
  8529. (if (eq? (read) 0)
  8530. 777
  8531. (let ([x (read)])
  8532. (+ 1 x))))])
  8533. (+ y 2))
  8534. \end{lstlisting}
  8535. \end{minipage}
  8536. &
  8537. $\Rightarrow$
  8538. &
  8539. \begin{minipage}{0.55\textwidth}
  8540. \begin{lstlisting}
  8541. start:
  8542. y = (read);
  8543. goto block_5;
  8544. block_5:
  8545. return (+ y 2);
  8546. block_6:
  8547. y = 777;
  8548. goto block_5;
  8549. block_7:
  8550. x = (read);
  8551. y = (+ 1 x2);
  8552. goto block_5;
  8553. \end{lstlisting}
  8554. \end{minipage}
  8555. \end{tabular}
  8556. \end{center}
  8557. \fi}
  8558. So the question is how can we decide whether to create a basic block?
  8559. \emph{Lazy evaluation}\index{subject}{lazy
  8560. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  8561. delaying the creation of a basic block until the point in time where
  8562. we know it will be used.
  8563. %
  8564. {\if\edition\racketEd
  8565. %
  8566. Racket provides support for
  8567. lazy evaluation with the
  8568. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8569. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8570. \index{subject}{delay} creates a
  8571. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8572. expressions is postponed. When \key{(force}
  8573. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8574. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8575. result of $e_n$ is cached in the promise and returned. If \code{force}
  8576. is applied again to the same promise, then the cached result is
  8577. returned. If \code{force} is applied to an argument that is not a
  8578. promise, \code{force} simply returns the argument.
  8579. %
  8580. \fi}
  8581. %
  8582. {\if\edition\pythonEd
  8583. %
  8584. While Python does not provide direct support for lazy evaluation, it
  8585. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8586. by wrapping it inside a function with no parameters. We can
  8587. \emph{force} its evaluation by calling the function. However, in some
  8588. cases of \code{explicate\_pred}, etc., we will return a list of
  8589. statements and in other cases we will return a function that computes
  8590. a list of statements. We use the term \emph{promise} to refer to a
  8591. value that may be delayed. To uniformly deal with
  8592. promises, we define the following \code{force} function that checks
  8593. whether its input is delayed (i.e., whether it is a function) and then
  8594. either 1) calls the function, or 2) returns the input.
  8595. \begin{lstlisting}
  8596. def force(promise):
  8597. if isinstance(promise, types.FunctionType):
  8598. return promise()
  8599. else:
  8600. return promise
  8601. \end{lstlisting}
  8602. %
  8603. \fi}
  8604. We use promises for the input and output of the functions
  8605. \code{explicate\_pred}, \code{explicate\_assign},
  8606. %
  8607. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8608. %
  8609. So instead of taking and returning \racket{$\Tail$
  8610. expressions}\python{lists of statements}, they take and return
  8611. promises. Furthermore, when we come to a situation in which a
  8612. continuation might be used more than once, as in the case for
  8613. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8614. that creates a basic block for each continuation (if there is not
  8615. already one) and then returns a \code{goto} statement to that basic
  8616. block. When we come to a situation where we have a promise but need an
  8617. actual piece of code, e.g. to create a larger piece of code with a
  8618. constructor such as \code{Seq}, then insert a call to \code{force}.
  8619. %
  8620. {\if\edition\racketEd
  8621. %
  8622. Also we must modify the \code{create\_block} function to begin with
  8623. \code{delay} to create a promise. When forced, this promise forces the
  8624. original promise. If that returns a \code{Goto} (because the block was
  8625. already added to \code{basic-blocks}), then we return the
  8626. \code{Goto}. Otherwise we add the block to \code{basic-blocks} and
  8627. return a \code{Goto} to the new label.
  8628. \begin{center}
  8629. \begin{minipage}{\textwidth}
  8630. \begin{lstlisting}
  8631. (define (create_block tail)
  8632. (delay
  8633. (define t (force tail))
  8634. (match t
  8635. [(Goto label) (Goto label)]
  8636. [else
  8637. (let ([label (gensym 'block)])
  8638. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8639. (Goto label))]))
  8640. \end{lstlisting}
  8641. \end{minipage}
  8642. \end{center}
  8643. \fi}
  8644. {\if\edition\pythonEd
  8645. %
  8646. Here is the new version of the \code{create\_block} auxiliary function
  8647. that works on promises and that checks whether the block consists of a
  8648. solitary \code{goto} statement.\\
  8649. \begin{minipage}{\textwidth}
  8650. \begin{lstlisting}
  8651. def create_block(promise, basic_blocks):
  8652. stmts = force(promise)
  8653. match stmts:
  8654. case [Goto(l)]:
  8655. return Goto(l)
  8656. case _:
  8657. label = label_name(generate_name('block'))
  8658. basic_blocks[label] = stmts
  8659. return Goto(label)
  8660. \end{lstlisting}
  8661. \end{minipage}
  8662. \fi}
  8663. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8664. improved \code{explicate\_control} on the above example. As you can
  8665. see, the number of basic blocks has been reduced from 4 blocks (see
  8666. Figure~\ref{fig:explicate-control-s1-38}) down to 2 blocks.
  8667. \begin{figure}[tbp]
  8668. \begin{tcolorbox}[colback=white]
  8669. {\if\edition\racketEd
  8670. \begin{tabular}{lll}
  8671. \begin{minipage}{0.4\textwidth}
  8672. % cond_test_82.rkt
  8673. \begin{lstlisting}
  8674. (let ([y (if #t
  8675. (read)
  8676. (if (eq? (read) 0)
  8677. 777
  8678. (let ([x (read)])
  8679. (+ 1 x))))])
  8680. (+ y 2))
  8681. \end{lstlisting}
  8682. \end{minipage}
  8683. &
  8684. $\Rightarrow$
  8685. &
  8686. \begin{minipage}{0.55\textwidth}
  8687. \begin{lstlisting}
  8688. start:
  8689. y = (read);
  8690. goto block_5;
  8691. block_5:
  8692. return (+ y 2);
  8693. \end{lstlisting}
  8694. \end{minipage}
  8695. \end{tabular}
  8696. \fi}
  8697. {\if\edition\pythonEd
  8698. \begin{tabular}{lll}
  8699. \begin{minipage}{0.4\textwidth}
  8700. % cond_test_41.rkt
  8701. \begin{lstlisting}
  8702. x = input_int()
  8703. y = input_int()
  8704. print(y + 2 \
  8705. if (x == 0 \
  8706. if x < 1 \
  8707. else x == 2) \
  8708. else y + 10)
  8709. \end{lstlisting}
  8710. \end{minipage}
  8711. &
  8712. $\Rightarrow$
  8713. &
  8714. \begin{minipage}{0.55\textwidth}
  8715. \begin{lstlisting}
  8716. start:
  8717. x = input_int()
  8718. y = input_int()
  8719. if x < 1:
  8720. goto block_4
  8721. else:
  8722. goto block_5
  8723. block_4:
  8724. if x == 0:
  8725. goto block_2
  8726. else:
  8727. goto block_3
  8728. block_5:
  8729. if x == 2:
  8730. goto block_2
  8731. else:
  8732. goto block_3
  8733. block_2:
  8734. tmp_0 = y + 2
  8735. goto block_1
  8736. block_3:
  8737. tmp_0 = y + 10
  8738. goto block_1
  8739. block_1:
  8740. print(tmp_0)
  8741. return 0
  8742. \end{lstlisting}
  8743. \end{minipage}
  8744. \end{tabular}
  8745. \fi}
  8746. \end{tcolorbox}
  8747. \caption{Translation from \LangIf{} to \LangCIf{}
  8748. via the improved \code{explicate\_control}.}
  8749. \label{fig:explicate-control-challenge}
  8750. \end{figure}
  8751. %% Recall that in the example output of \code{explicate\_control} in
  8752. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8753. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8754. %% block. The first goal of this challenge assignment is to remove those
  8755. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8756. %% \code{explicate\_control} on the left and shows the result of bypassing
  8757. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8758. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8759. %% \code{block55}. The optimized code on the right of
  8760. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8761. %% \code{then} branch jumping directly to \code{block55}. The story is
  8762. %% similar for the \code{else} branch, as well as for the two branches in
  8763. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8764. %% have been optimized in this way, there are no longer any jumps to
  8765. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8766. %% \begin{figure}[tbp]
  8767. %% \begin{tabular}{lll}
  8768. %% \begin{minipage}{0.4\textwidth}
  8769. %% \begin{lstlisting}
  8770. %% block62:
  8771. %% tmp54 = (read);
  8772. %% if (eq? tmp54 2) then
  8773. %% goto block59;
  8774. %% else
  8775. %% goto block60;
  8776. %% block61:
  8777. %% tmp53 = (read);
  8778. %% if (eq? tmp53 0) then
  8779. %% goto block57;
  8780. %% else
  8781. %% goto block58;
  8782. %% block60:
  8783. %% goto block56;
  8784. %% block59:
  8785. %% goto block55;
  8786. %% block58:
  8787. %% goto block56;
  8788. %% block57:
  8789. %% goto block55;
  8790. %% block56:
  8791. %% return (+ 700 77);
  8792. %% block55:
  8793. %% return (+ 10 32);
  8794. %% start:
  8795. %% tmp52 = (read);
  8796. %% if (eq? tmp52 1) then
  8797. %% goto block61;
  8798. %% else
  8799. %% goto block62;
  8800. %% \end{lstlisting}
  8801. %% \end{minipage}
  8802. %% &
  8803. %% $\Rightarrow$
  8804. %% &
  8805. %% \begin{minipage}{0.55\textwidth}
  8806. %% \begin{lstlisting}
  8807. %% block62:
  8808. %% tmp54 = (read);
  8809. %% if (eq? tmp54 2) then
  8810. %% goto block55;
  8811. %% else
  8812. %% goto block56;
  8813. %% block61:
  8814. %% tmp53 = (read);
  8815. %% if (eq? tmp53 0) then
  8816. %% goto block55;
  8817. %% else
  8818. %% goto block56;
  8819. %% block56:
  8820. %% return (+ 700 77);
  8821. %% block55:
  8822. %% return (+ 10 32);
  8823. %% start:
  8824. %% tmp52 = (read);
  8825. %% if (eq? tmp52 1) then
  8826. %% goto block61;
  8827. %% else
  8828. %% goto block62;
  8829. %% \end{lstlisting}
  8830. %% \end{minipage}
  8831. %% \end{tabular}
  8832. %% \caption{Optimize jumps by removing trivial blocks.}
  8833. %% \label{fig:optimize-jumps}
  8834. %% \end{figure}
  8835. %% The name of this pass is \code{optimize-jumps}. We recommend
  8836. %% implementing this pass in two phases. The first phrase builds a hash
  8837. %% table that maps labels to possibly improved labels. The second phase
  8838. %% changes the target of each \code{goto} to use the improved label. If
  8839. %% the label is for a trivial block, then the hash table should map the
  8840. %% label to the first non-trivial block that can be reached from this
  8841. %% label by jumping through trivial blocks. If the label is for a
  8842. %% non-trivial block, then the hash table should map the label to itself;
  8843. %% we do not want to change jumps to non-trivial blocks.
  8844. %% The first phase can be accomplished by constructing an empty hash
  8845. %% table, call it \code{short-cut}, and then iterating over the control
  8846. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8847. %% then update the hash table, mapping the block's source to the target
  8848. %% of the \code{goto}. Also, the hash table may already have mapped some
  8849. %% labels to the block's source, to you must iterate through the hash
  8850. %% table and update all of those so that they instead map to the target
  8851. %% of the \code{goto}.
  8852. %% For the second phase, we recommend iterating through the $\Tail$ of
  8853. %% each block in the program, updating the target of every \code{goto}
  8854. %% according to the mapping in \code{short-cut}.
  8855. \begin{exercise}\normalfont\normalsize
  8856. Implement the improvements to the \code{explicate\_control} pass.
  8857. Check that it removes trivial blocks in a few example programs. Then
  8858. check that your compiler still passes all of your tests.
  8859. \end{exercise}
  8860. \subsection{Remove Jumps}
  8861. There is an opportunity for removing jumps that is apparent in the
  8862. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8863. ends with a jump to \code{block\_5} and there are no other jumps to
  8864. \code{block\_5} in the rest of the program. In this situation we can
  8865. avoid the runtime overhead of this jump by merging \code{block\_5}
  8866. into the preceding block, in this case the \code{start} block.
  8867. Figure~\ref{fig:remove-jumps} shows the output of
  8868. \code{allocate\_registers} on the left and the result of this
  8869. optimization on the right.
  8870. \begin{figure}[tbp]
  8871. \begin{tcolorbox}[colback=white]
  8872. {\if\edition\racketEd
  8873. \begin{tabular}{lll}
  8874. \begin{minipage}{0.5\textwidth}
  8875. % cond_test_82.rkt
  8876. \begin{lstlisting}
  8877. start:
  8878. callq read_int
  8879. movq %rax, %rcx
  8880. jmp block_5
  8881. block_5:
  8882. movq %rcx, %rax
  8883. addq $2, %rax
  8884. jmp conclusion
  8885. \end{lstlisting}
  8886. \end{minipage}
  8887. &
  8888. $\Rightarrow\qquad$
  8889. \begin{minipage}{0.4\textwidth}
  8890. \begin{lstlisting}
  8891. start:
  8892. callq read_int
  8893. movq %rax, %rcx
  8894. movq %rcx, %rax
  8895. addq $2, %rax
  8896. jmp conclusion
  8897. \end{lstlisting}
  8898. \end{minipage}
  8899. \end{tabular}
  8900. \fi}
  8901. {\if\edition\pythonEd
  8902. \begin{tabular}{lll}
  8903. \begin{minipage}{0.5\textwidth}
  8904. % cond_test_20.rkt
  8905. \begin{lstlisting}
  8906. start:
  8907. callq read_int
  8908. movq %rax, tmp_0
  8909. cmpq 1, tmp_0
  8910. je block_3
  8911. jmp block_4
  8912. block_3:
  8913. movq 42, tmp_1
  8914. jmp block_2
  8915. block_4:
  8916. movq 0, tmp_1
  8917. jmp block_2
  8918. block_2:
  8919. movq tmp_1, %rdi
  8920. callq print_int
  8921. movq 0, %rax
  8922. jmp conclusion
  8923. \end{lstlisting}
  8924. \end{minipage}
  8925. &
  8926. $\Rightarrow\qquad$
  8927. \begin{minipage}{0.4\textwidth}
  8928. \begin{lstlisting}
  8929. start:
  8930. callq read_int
  8931. movq %rax, tmp_0
  8932. cmpq 1, tmp_0
  8933. je block_3
  8934. movq 0, tmp_1
  8935. jmp block_2
  8936. block_3:
  8937. movq 42, tmp_1
  8938. jmp block_2
  8939. block_2:
  8940. movq tmp_1, %rdi
  8941. callq print_int
  8942. movq 0, %rax
  8943. jmp conclusion
  8944. \end{lstlisting}
  8945. \end{minipage}
  8946. \end{tabular}
  8947. \fi}
  8948. \end{tcolorbox}
  8949. \caption{Merging basic blocks by removing unnecessary jumps.}
  8950. \label{fig:remove-jumps}
  8951. \end{figure}
  8952. \begin{exercise}\normalfont\normalsize
  8953. %
  8954. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8955. into their preceding basic block, when there is only one preceding
  8956. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8957. %
  8958. {\if\edition\racketEd
  8959. In the \code{run-tests.rkt} script, add the following entry to the
  8960. list of \code{passes} between \code{allocate\_registers}
  8961. and \code{patch\_instructions}.
  8962. \begin{lstlisting}
  8963. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8964. \end{lstlisting}
  8965. \fi}
  8966. %
  8967. Run the script to test your compiler.
  8968. %
  8969. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8970. blocks on several test programs.
  8971. \end{exercise}
  8972. \section{Further Reading}
  8973. \label{sec:cond-further-reading}
  8974. The algorithm for the \code{explicate\_control} pass is based on the
  8975. \code{expose-basic-blocks} pass in the course notes of
  8976. \citet{Dybvig:2010aa}.
  8977. %
  8978. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8979. \citet{Appel:2003fk}, and is related to translations into continuation
  8980. passing
  8981. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8982. %
  8983. The treatment of conditionals in the \code{explicate\_control} pass is
  8984. similar to short-cut boolean
  8985. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8986. and the case-of-case transformation~\citep{PeytonJones:1998}.
  8987. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8988. \chapter{Loops and Dataflow Analysis}
  8989. \label{ch:Lwhile}
  8990. % TODO: define R'_8
  8991. % TODO: multi-graph
  8992. {\if\edition\racketEd
  8993. %
  8994. In this chapter we study two features that are the hallmarks of
  8995. imperative programming languages: loops and assignments to local
  8996. variables. The following example demonstrates these new features by
  8997. computing the sum of the first five positive integers.
  8998. % similar to loop_test_1.rkt
  8999. \begin{lstlisting}
  9000. (let ([sum 0])
  9001. (let ([i 5])
  9002. (begin
  9003. (while (> i 0)
  9004. (begin
  9005. (set! sum (+ sum i))
  9006. (set! i (- i 1))))
  9007. sum)))
  9008. \end{lstlisting}
  9009. The \code{while} loop consists of a condition and a
  9010. body\footnote{The \code{while} loop is not a built-in
  9011. feature of the Racket language, but Racket includes many looping
  9012. constructs and it is straightforward to define \code{while} as a
  9013. macro.}. The body is evaluated repeatedly so long as the condition
  9014. remains true.
  9015. %
  9016. The \code{set!} consists of a variable and a right-hand-side
  9017. expression. The \code{set!} updates value of the variable to the
  9018. value of the right-hand-side.
  9019. %
  9020. The primary purpose of both the \code{while} loop and \code{set!} is
  9021. to cause side effects, so they do not have a meaningful result
  9022. value. Instead their result is the \code{\#<void>} value. The
  9023. expression \code{(void)} is an explicit way to create the
  9024. \code{\#<void>} value and it has type \code{Void}. The
  9025. \code{\#<void>} value can be passed around just like other values
  9026. inside an \LangLoop{} program and it can be compared for equality with
  9027. another \code{\#<void>} value. However, there are no other operations
  9028. specific to the the \code{\#<void>} value in \LangLoop{}. In contrast,
  9029. Racket defines the \code{void?} predicate that returns \code{\#t}
  9030. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9031. %
  9032. \footnote{Racket's \code{Void} type corresponds to what is often
  9033. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9034. by a single value \code{\#<void>} which corresponds to \code{unit}
  9035. or \code{()} in the literature~\citep{Pierce:2002hj}.}.
  9036. %
  9037. With the addition of side-effecting features such as \code{while} loop
  9038. and \code{set!}, it is helpful to also include in a language feature
  9039. for sequencing side effects: the \code{begin} expression. It consists
  9040. of one or more subexpressions that are evaluated left-to-right.
  9041. %
  9042. \fi}
  9043. {\if\edition\pythonEd
  9044. %
  9045. In this chapter we study loops, one of the hallmarks of imperative
  9046. programming languages. The following example demonstrates the
  9047. \code{while} loop by computing the sum of the first five positive
  9048. integers.
  9049. \begin{lstlisting}
  9050. sum = 0
  9051. i = 5
  9052. while i > 0:
  9053. sum = sum + i
  9054. i = i - 1
  9055. print(sum)
  9056. \end{lstlisting}
  9057. The \code{while} loop consists of a condition expression and a body (a
  9058. sequence of statements). The body is evaluated repeatedly so long as
  9059. the condition remains true.
  9060. %
  9061. \fi}
  9062. \section{The \LangLoop{} Language}
  9063. \newcommand{\LwhileGrammarRacket}{
  9064. \begin{array}{lcl}
  9065. \Type &::=& \key{Void}\\
  9066. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9067. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9068. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9069. \end{array}
  9070. }
  9071. \newcommand{\LwhileASTRacket}{
  9072. \begin{array}{lcl}
  9073. \Type &::=& \key{Void}\\
  9074. \Exp &::=& \SETBANG{\Var}{\Exp}
  9075. \MID \BEGIN{\Exp^{*}}{\Exp}
  9076. \MID \WHILE{\Exp}{\Exp}
  9077. \MID \VOID{}
  9078. \end{array}
  9079. }
  9080. \newcommand{\LwhileGrammarPython}{
  9081. \begin{array}{rcl}
  9082. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9083. \end{array}
  9084. }
  9085. \newcommand{\LwhileASTPython}{
  9086. \begin{array}{lcl}
  9087. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9088. \end{array}
  9089. }
  9090. \begin{figure}[tp]
  9091. \centering
  9092. \begin{tcolorbox}[colback=white]
  9093. \small
  9094. {\if\edition\racketEd
  9095. \[
  9096. \begin{array}{l}
  9097. \gray{\LintGrammarRacket{}} \\ \hline
  9098. \gray{\LvarGrammarRacket{}} \\ \hline
  9099. \gray{\LifGrammarRacket{}} \\ \hline
  9100. \LwhileGrammarRacket \\
  9101. \begin{array}{lcl}
  9102. \LangLoopM{} &::=& \Exp
  9103. \end{array}
  9104. \end{array}
  9105. \]
  9106. \fi}
  9107. {\if\edition\pythonEd
  9108. \[
  9109. \begin{array}{l}
  9110. \gray{\LintGrammarPython} \\ \hline
  9111. \gray{\LvarGrammarPython} \\ \hline
  9112. \gray{\LifGrammarPython} \\ \hline
  9113. \LwhileGrammarPython \\
  9114. \begin{array}{rcl}
  9115. \LangLoopM{} &::=& \Stmt^{*}
  9116. \end{array}
  9117. \end{array}
  9118. \]
  9119. \fi}
  9120. \end{tcolorbox}
  9121. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  9122. \label{fig:Lwhile-concrete-syntax}
  9123. \end{figure}
  9124. \begin{figure}[tp]
  9125. \centering
  9126. \begin{tcolorbox}[colback=white]
  9127. \small
  9128. {\if\edition\racketEd
  9129. \[
  9130. \begin{array}{l}
  9131. \gray{\LintOpAST} \\ \hline
  9132. \gray{\LvarASTRacket{}} \\ \hline
  9133. \gray{\LifASTRacket{}} \\ \hline
  9134. \LwhileASTRacket{} \\
  9135. \begin{array}{lcl}
  9136. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9137. \end{array}
  9138. \end{array}
  9139. \]
  9140. \fi}
  9141. {\if\edition\pythonEd
  9142. \[
  9143. \begin{array}{l}
  9144. \gray{\LintASTPython} \\ \hline
  9145. \gray{\LvarASTPython} \\ \hline
  9146. \gray{\LifASTPython} \\ \hline
  9147. \LwhileASTPython \\
  9148. \begin{array}{lcl}
  9149. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9150. \end{array}
  9151. \end{array}
  9152. \]
  9153. \fi}
  9154. \end{tcolorbox}
  9155. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9156. \label{fig:Lwhile-syntax}
  9157. \end{figure}
  9158. The concrete syntax of \LangLoop{} is defined in
  9159. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9160. in Figure~\ref{fig:Lwhile-syntax}.
  9161. %
  9162. The definitional interpreter for \LangLoop{} is shown in
  9163. Figure~\ref{fig:interp-Lwhile}.
  9164. %
  9165. {\if\edition\racketEd
  9166. %
  9167. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9168. and \code{Void} and we make changes to the cases for \code{Var} and
  9169. \code{Let} regarding variables. To support assignment to variables and
  9170. to make their lifetimes indefinite (see the second example in
  9171. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9172. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9173. value.
  9174. %
  9175. Now to discuss the new cases. For \code{SetBang}, we find the
  9176. variable in the environment to obtain a boxed value and then we change
  9177. it using \code{set-box!} to the result of evaluating the right-hand
  9178. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9179. %
  9180. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9181. if the result is true, 2) evaluate the body.
  9182. The result value of a \code{while} loop is also \code{\#<void>}.
  9183. %
  9184. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9185. subexpressions \itm{es} for their effects and then evaluates
  9186. and returns the result from \itm{body}.
  9187. %
  9188. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9189. %
  9190. \fi}
  9191. {\if\edition\pythonEd
  9192. %
  9193. We add a new case for \code{While} in the \code{interp\_stmts}
  9194. function, where we repeatedly interpret the \code{body} so long as the
  9195. \code{test} expression remains true.
  9196. %
  9197. \fi}
  9198. \begin{figure}[tbp]
  9199. \begin{tcolorbox}[colback=white]
  9200. {\if\edition\racketEd
  9201. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9202. (define interp-Lwhile-class
  9203. (class interp-Lif-class
  9204. (super-new)
  9205. (define/override ((interp-exp env) e)
  9206. (define recur (interp-exp env))
  9207. (match e
  9208. [(Let x e body)
  9209. (define new-env (dict-set env x (box (recur e))))
  9210. ((interp-exp new-env) body)]
  9211. [(Var x) (unbox (dict-ref env x))]
  9212. [(SetBang x rhs)
  9213. (set-box! (dict-ref env x) (recur rhs))]
  9214. [(WhileLoop cnd body)
  9215. (define (loop)
  9216. (cond [(recur cnd) (recur body) (loop)]
  9217. [else (void)]))
  9218. (loop)]
  9219. [(Begin es body)
  9220. (for ([e es]) (recur e))
  9221. (recur body)]
  9222. [(Void) (void)]
  9223. [else ((super interp-exp env) e)]))
  9224. ))
  9225. (define (interp-Lwhile p)
  9226. (send (new interp-Lwhile-class) interp-program p))
  9227. \end{lstlisting}
  9228. \fi}
  9229. {\if\edition\pythonEd
  9230. \begin{lstlisting}
  9231. class InterpLwhile(InterpLif):
  9232. def interp_stmts(self, ss, env):
  9233. if len(ss) == 0:
  9234. return
  9235. match ss[0]:
  9236. case While(test, body, []):
  9237. while self.interp_exp(test, env):
  9238. self.interp_stmts(body, env)
  9239. return self.interp_stmts(ss[1:], env)
  9240. case _:
  9241. return super().interp_stmts(ss, env)
  9242. \end{lstlisting}
  9243. \fi}
  9244. \end{tcolorbox}
  9245. \caption{Interpreter for \LangLoop{}.}
  9246. \label{fig:interp-Lwhile}
  9247. \end{figure}
  9248. The type checker for \LangLoop{} is defined in
  9249. Figure~\ref{fig:type-check-Lwhile}.
  9250. %
  9251. {\if\edition\racketEd
  9252. %
  9253. The type checking of the \code{SetBang} expression requires the type
  9254. of the variable and the right-hand-side to agree. The result type is
  9255. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  9256. and the result type is \code{Void}. For \code{Begin}, the result type
  9257. is the type of its last subexpression.
  9258. %
  9259. \fi}
  9260. %
  9261. {\if\edition\pythonEd
  9262. %
  9263. A \code{while} loop is well typed if the type of the \code{test}
  9264. expression is \code{bool} and the statements in the \code{body} are
  9265. well typed.
  9266. %
  9267. \fi}
  9268. \begin{figure}[tbp]
  9269. \begin{tcolorbox}[colback=white]
  9270. {\if\edition\racketEd
  9271. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9272. (define type-check-Lwhile-class
  9273. (class type-check-Lif-class
  9274. (super-new)
  9275. (inherit check-type-equal?)
  9276. (define/override (type-check-exp env)
  9277. (lambda (e)
  9278. (define recur (type-check-exp env))
  9279. (match e
  9280. [(SetBang x rhs)
  9281. (define-values (rhs^ rhsT) (recur rhs))
  9282. (define varT (dict-ref env x))
  9283. (check-type-equal? rhsT varT e)
  9284. (values (SetBang x rhs^) 'Void)]
  9285. [(WhileLoop cnd body)
  9286. (define-values (cnd^ Tc) (recur cnd))
  9287. (check-type-equal? Tc 'Boolean e)
  9288. (define-values (body^ Tbody) ((type-check-exp env) body))
  9289. (values (WhileLoop cnd^ body^) 'Void)]
  9290. [(Begin es body)
  9291. (define-values (es^ ts)
  9292. (for/lists (l1 l2) ([e es]) (recur e)))
  9293. (define-values (body^ Tbody) (recur body))
  9294. (values (Begin es^ body^) Tbody)]
  9295. [else ((super type-check-exp env) e)])))
  9296. ))
  9297. (define (type-check-Lwhile p)
  9298. (send (new type-check-Lwhile-class) type-check-program p))
  9299. \end{lstlisting}
  9300. \fi}
  9301. {\if\edition\pythonEd
  9302. \begin{lstlisting}
  9303. class TypeCheckLwhile(TypeCheckLif):
  9304. def type_check_stmts(self, ss, env):
  9305. if len(ss) == 0:
  9306. return
  9307. match ss[0]:
  9308. case While(test, body, []):
  9309. test_t = self.type_check_exp(test, env)
  9310. check_type_equal(bool, test_t, test)
  9311. body_t = self.type_check_stmts(body, env)
  9312. return self.type_check_stmts(ss[1:], env)
  9313. case _:
  9314. return super().type_check_stmts(ss, env)
  9315. \end{lstlisting}
  9316. \fi}
  9317. \end{tcolorbox}
  9318. \caption{Type checker for the \LangLoop{} language.}
  9319. \label{fig:type-check-Lwhile}
  9320. \end{figure}
  9321. {\if\edition\racketEd
  9322. %
  9323. At first glance, the translation of these language features to x86
  9324. seems straightforward because the \LangCIf{} intermediate language
  9325. already supports all of the ingredients that we need: assignment,
  9326. \code{goto}, conditional branching, and sequencing. However, there are
  9327. complications that arise which we discuss in the next section. After
  9328. that we introduce the changes necessary to the existing passes.
  9329. %
  9330. \fi}
  9331. {\if\edition\pythonEd
  9332. %
  9333. At first glance, the translation of \code{while} loops to x86 seems
  9334. straightforward because the \LangCIf{} intermediate language already
  9335. supports \code{goto} and conditional branching. However, there are
  9336. complications that arise which we discuss in the next section. After
  9337. that we introduce the changes necessary to the existing passes.
  9338. %
  9339. \fi}
  9340. \section{Cyclic Control Flow and Dataflow Analysis}
  9341. \label{sec:dataflow-analysis}
  9342. Up until this point the programs generated in
  9343. \code{explicate\_control} were guaranteed to be acyclic. However, each
  9344. \code{while} loop introduces a cycle. But does that matter?
  9345. %
  9346. Indeed it does. Recall that for register allocation, the compiler
  9347. performs liveness analysis to determine which variables can share the
  9348. same register. To accomplish this we analyzed the control-flow graph
  9349. in reverse topological order
  9350. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9351. only well-defined for acyclic graphs.
  9352. Let us return to the example of computing the sum of the first five
  9353. positive integers. Here is the program after instruction selection but
  9354. before register allocation.
  9355. \begin{center}
  9356. {\if\edition\racketEd
  9357. \begin{minipage}{0.45\textwidth}
  9358. \begin{lstlisting}
  9359. (define (main) : Integer
  9360. mainstart:
  9361. movq $0, sum
  9362. movq $5, i
  9363. jmp block5
  9364. block5:
  9365. movq i, tmp3
  9366. cmpq tmp3, $0
  9367. jl block7
  9368. jmp block8
  9369. \end{lstlisting}
  9370. \end{minipage}
  9371. \begin{minipage}{0.45\textwidth}
  9372. \begin{lstlisting}
  9373. block7:
  9374. addq i, sum
  9375. movq $1, tmp4
  9376. negq tmp4
  9377. addq tmp4, i
  9378. jmp block5
  9379. block8:
  9380. movq $27, %rax
  9381. addq sum, %rax
  9382. jmp mainconclusion
  9383. )
  9384. \end{lstlisting}
  9385. \end{minipage}
  9386. \fi}
  9387. {\if\edition\pythonEd
  9388. \begin{minipage}{0.45\textwidth}
  9389. \begin{lstlisting}
  9390. mainstart:
  9391. movq $0, sum
  9392. movq $5, i
  9393. jmp block5
  9394. block5:
  9395. cmpq $0, i
  9396. jg block7
  9397. jmp block8
  9398. \end{lstlisting}
  9399. \end{minipage}
  9400. \begin{minipage}{0.45\textwidth}
  9401. \begin{lstlisting}
  9402. block7:
  9403. addq i, sum
  9404. subq $1, i
  9405. jmp block5
  9406. block8:
  9407. movq sum, %rdi
  9408. callq print_int
  9409. movq $0, %rax
  9410. jmp mainconclusion
  9411. \end{lstlisting}
  9412. \end{minipage}
  9413. \fi}
  9414. \end{center}
  9415. Recall that liveness analysis works backwards, starting at the end
  9416. of each function. For this example we could start with \code{block8}
  9417. because we know what is live at the beginning of the conclusion,
  9418. just \code{rax} and \code{rsp}. So the live-before set
  9419. for \code{block8} is \code{\{rsp,sum\}}.
  9420. %
  9421. Next we might try to analyze \code{block5} or \code{block7}, but
  9422. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9423. we are stuck.
  9424. The way out of this impasse is to realize that we can compute an
  9425. under-approximation of each live-before set by starting with empty
  9426. live-after sets. By \emph{under-approximation}, we mean that the set
  9427. only contains variables that are live for some execution of the
  9428. program, but the set may be missing some variables that are live.
  9429. Next, the under-approximations for each block can be improved by 1)
  9430. updating the live-after set for each block using the approximate
  9431. live-before sets from the other blocks and 2) perform liveness
  9432. analysis again on each block. In fact, by iterating this process, the
  9433. under-approximations eventually become the correct solutions!
  9434. %
  9435. This approach of iteratively analyzing a control-flow graph is
  9436. applicable to many static analysis problems and goes by the name
  9437. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9438. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9439. Washington.
  9440. Let us apply this approach to the above example. We use the empty set
  9441. for the initial live-before set for each block. Let $m_0$ be the
  9442. following mapping from label names to sets of locations (variables and
  9443. registers).
  9444. \begin{center}
  9445. \begin{lstlisting}
  9446. mainstart: {}, block5: {}, block7: {}, block8: {}
  9447. \end{lstlisting}
  9448. \end{center}
  9449. Using the above live-before approximations, we determine the
  9450. live-after for each block and then apply liveness analysis to each
  9451. block. This produces our next approximation $m_1$ of the live-before
  9452. sets.
  9453. \begin{center}
  9454. \begin{lstlisting}
  9455. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9456. \end{lstlisting}
  9457. \end{center}
  9458. For the second round, the live-after for \code{mainstart} is the
  9459. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9460. liveness analysis for \code{mainstart} computes the empty set. The
  9461. live-after for \code{block5} is the union of the live-before sets for
  9462. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9463. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9464. sum\}}. The live-after for \code{block7} is the live-before for
  9465. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9466. So the liveness analysis for \code{block7} remains \code{\{i,
  9467. sum\}}. Together these yield the following approximation $m_2$ of
  9468. the live-before sets.
  9469. \begin{center}
  9470. \begin{lstlisting}
  9471. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9472. \end{lstlisting}
  9473. \end{center}
  9474. In the preceding iteration, only \code{block5} changed, so we can
  9475. limit our attention to \code{mainstart} and \code{block7}, the two
  9476. blocks that jump to \code{block5}. As a result, the live-before sets
  9477. for \code{mainstart} and \code{block7} are updated to include
  9478. \code{rsp}, yielding the following approximation $m_3$.
  9479. \begin{center}
  9480. \begin{lstlisting}
  9481. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9482. \end{lstlisting}
  9483. \end{center}
  9484. Because \code{block7} changed, we analyze \code{block5} once more, but
  9485. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9486. our approximations have converged, so $m_3$ is the solution.
  9487. This iteration process is guaranteed to converge to a solution by the
  9488. Kleene Fixed-Point Theorem, a general theorem about functions on
  9489. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9490. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9491. elements, a least element $\bot$ (pronounced bottom), and a join
  9492. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9493. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9494. working with join semi-lattices.} When two elements are ordered $m_i
  9495. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9496. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9497. approximation than $m_i$. The bottom element $\bot$ represents the
  9498. complete lack of information, i.e., the worst approximation. The join
  9499. operator takes two lattice elements and combines their information,
  9500. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9501. bound}
  9502. A dataflow analysis typically involves two lattices: one lattice to
  9503. represent abstract states and another lattice that aggregates the
  9504. abstract states of all the blocks in the control-flow graph. For
  9505. liveness analysis, an abstract state is a set of locations. We form
  9506. the lattice $L$ by taking its elements to be sets of locations, the
  9507. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9508. set, and the join operator to be set union.
  9509. %
  9510. We form a second lattice $M$ by taking its elements to be mappings
  9511. from the block labels to sets of locations (elements of $L$). We
  9512. order the mappings point-wise, using the ordering of $L$. So given any
  9513. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9514. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9515. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9516. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9517. We can think of one iteration of liveness analysis applied to the
  9518. whole program as being a function $f$ on the lattice $M$. It takes a
  9519. mapping as input and computes a new mapping.
  9520. \[
  9521. f(m_i) = m_{i+1}
  9522. \]
  9523. Next let us think for a moment about what a final solution $m_s$
  9524. should look like. If we perform liveness analysis using the solution
  9525. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9526. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9527. \[
  9528. f(m_s) = m_s
  9529. \]
  9530. Furthermore, the solution should only include locations that are
  9531. forced to be there by performing liveness analysis on the program, so
  9532. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9533. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9534. monotone (better inputs produce better outputs), then the least fixed
  9535. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9536. chain} obtained by starting at $\bot$ and iterating $f$ as
  9537. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9538. \[
  9539. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9540. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9541. \]
  9542. When a lattice contains only finitely-long ascending chains, then
  9543. every Kleene chain tops out at some fixed point after some number of
  9544. iterations of $f$.
  9545. \[
  9546. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9547. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9548. \]
  9549. The liveness analysis is indeed a monotone function and the lattice
  9550. $M$ only has finitely-long ascending chains because there are only a
  9551. finite number of variables and blocks in the program. Thus we are
  9552. guaranteed that iteratively applying liveness analysis to all blocks
  9553. in the program will eventually produce the least fixed point solution.
  9554. Next let us consider dataflow analysis in general and discuss the
  9555. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9556. %
  9557. The algorithm has four parameters: the control-flow graph \code{G}, a
  9558. function \code{transfer} that applies the analysis to one block, the
  9559. \code{bottom} and \code{join} operator for the lattice of abstract
  9560. states. The \code{analyze\_dataflow} function is formulated as a
  9561. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9562. function come from the predecessor nodes in the control-flow
  9563. graph. However, liveness analysis is a \emph{backward} dataflow
  9564. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9565. function with the transpose of the control-flow graph.
  9566. The algorithm begins by creating the bottom mapping, represented by a
  9567. hash table. It then pushes all of the nodes in the control-flow graph
  9568. onto the work list (a queue). The algorithm repeats the \code{while}
  9569. loop as long as there are items in the work list. In each iteration, a
  9570. node is popped from the work list and processed. The \code{input} for
  9571. the node is computed by taking the join of the abstract states of all
  9572. the predecessor nodes. The \code{transfer} function is then applied to
  9573. obtain the \code{output} abstract state. If the output differs from
  9574. the previous state for this block, the mapping for this block is
  9575. updated and its successor nodes are pushed onto the work list.
  9576. \begin{figure}[tb]
  9577. \begin{tcolorbox}[colback=white]
  9578. {\if\edition\racketEd
  9579. \begin{lstlisting}
  9580. (define (analyze_dataflow G transfer bottom join)
  9581. (define mapping (make-hash))
  9582. (for ([v (in-vertices G)])
  9583. (dict-set! mapping v bottom))
  9584. (define worklist (make-queue))
  9585. (for ([v (in-vertices G)])
  9586. (enqueue! worklist v))
  9587. (define trans-G (transpose G))
  9588. (while (not (queue-empty? worklist))
  9589. (define node (dequeue! worklist))
  9590. (define input (for/fold ([state bottom])
  9591. ([pred (in-neighbors trans-G node)])
  9592. (join state (dict-ref mapping pred))))
  9593. (define output (transfer node input))
  9594. (cond [(not (equal? output (dict-ref mapping node)))
  9595. (dict-set! mapping node output)
  9596. (for ([v (in-neighbors G node)])
  9597. (enqueue! worklist v))]))
  9598. mapping)
  9599. \end{lstlisting}
  9600. \fi}
  9601. {\if\edition\pythonEd
  9602. \begin{lstlisting}
  9603. def analyze_dataflow(G, transfer, bottom, join):
  9604. trans_G = transpose(G)
  9605. mapping = dict((v, bottom) for v in G.vertices())
  9606. worklist = deque(G.vertices)
  9607. while worklist:
  9608. node = worklist.pop()
  9609. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9610. output = transfer(node, input)
  9611. if output != mapping[node]:
  9612. mapping[node] = output
  9613. worklist.extend(G.adjacent(node))
  9614. \end{lstlisting}
  9615. \fi}
  9616. \end{tcolorbox}
  9617. \caption{Generic work list algorithm for dataflow analysis}
  9618. \label{fig:generic-dataflow}
  9619. \end{figure}
  9620. {\if\edition\racketEd
  9621. \section{Mutable Variables \& Remove Complex Operands}
  9622. There is a subtle interaction between the
  9623. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  9624. and the left-to-right order of evaluation of Racket. Consider the
  9625. following example.
  9626. \begin{lstlisting}
  9627. (let ([x 2])
  9628. (+ x (begin (set! x 40) x)))
  9629. \end{lstlisting}
  9630. The result of this program is \code{42} because the first read from
  9631. \code{x} produces \code{2} and the second produces \code{40}. However,
  9632. if we naively apply the \code{remove\_complex\_operands} pass to this
  9633. example we obtain the following program whose result is \code{80}!
  9634. \begin{lstlisting}
  9635. (let ([x 2])
  9636. (let ([tmp (begin (set! x 40) x)])
  9637. (+ x tmp)))
  9638. \end{lstlisting}
  9639. The problem is that, with mutable variables, the ordering between
  9640. reads and writes is important, and the
  9641. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9642. before the first read of \code{x}.
  9643. We recommend solving this problem by giving special treatment to reads
  9644. from mutable variables, that is, variables that occur on the left-hand
  9645. side of a \code{set!}. We mark each read from a mutable variable with
  9646. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9647. that the read operation is effectful in that it can produce different
  9648. results at different points in time. Let's apply this idea to the
  9649. following variation that also involves a variable that is not mutated.
  9650. % loop_test_24.rkt
  9651. \begin{lstlisting}
  9652. (let ([x 2])
  9653. (let ([y 0])
  9654. (+ y (+ x (begin (set! x 40) x)))))
  9655. \end{lstlisting}
  9656. We first analyze the above program to discover that variable \code{x}
  9657. is mutable but \code{y} is not. We then transform the program as
  9658. follows, replacing each occurrence of \code{x} with \code{(get! x)}.
  9659. \begin{lstlisting}
  9660. (let ([x 2])
  9661. (let ([y 0])
  9662. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9663. \end{lstlisting}
  9664. Now that we have a clear distinction between reads from mutable and
  9665. immutable variables, we can apply the \code{remove\_complex\_operands}
  9666. pass, where reads from immutable variables are still classified as
  9667. atomic expressions but reads from mutable variables are classified as
  9668. complex. Thus, \code{remove\_complex\_operands} yields the following
  9669. program.\\
  9670. \begin{minipage}{\textwidth}
  9671. \begin{lstlisting}
  9672. (let ([x 2])
  9673. (let ([y 0])
  9674. (+ y (let ([t1 (get! x)])
  9675. (let ([t2 (begin (set! x 40) (get! x))])
  9676. (+ t1 t2))))))
  9677. \end{lstlisting}
  9678. \end{minipage}
  9679. The temporary variable \code{t1} gets the value of \code{x} before the
  9680. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9681. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9682. do not generate a temporary variable for the occurrence of \code{y}
  9683. because it's an immutable variable. We want to avoid such unnecessary
  9684. extra temporaries because they would needless increase the number of
  9685. variables, making it more likely for some of them to be spilled. The
  9686. result of this program is \code{42}, the same as the result prior to
  9687. \code{remove\_complex\_operands}.
  9688. The approach that we've sketched above requires only a small
  9689. modification to \code{remove\_complex\_operands} to handle
  9690. \code{get!}. However, it requires a new pass, called
  9691. \code{uncover-get!}, that we discuss in
  9692. Section~\ref{sec:uncover-get-bang}.
  9693. As an aside, this problematic interaction between \code{set!} and the
  9694. pass \code{remove\_complex\_operands} is particular to Racket and not
  9695. its predecessor, the Scheme language. The key difference is that
  9696. Scheme does not specify an order of evaluation for the arguments of an
  9697. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9698. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9699. would be correct results for the example program. Interestingly,
  9700. Racket is implemented on top of the Chez Scheme
  9701. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9702. presented in this section (using extra \code{let} bindings to control
  9703. the order of evaluation) is used in the translation from Racket to
  9704. Scheme~\citep{Flatt:2019tb}.
  9705. \fi} % racket
  9706. Having discussed the complications that arise from adding support for
  9707. assignment and loops, we turn to discussing the individual compilation
  9708. passes.
  9709. {\if\edition\racketEd
  9710. \section{Uncover \texttt{get!}}
  9711. \label{sec:uncover-get-bang}
  9712. The goal of this pass it to mark uses of mutable variables so that
  9713. \code{remove\_complex\_operands} can treat them as complex expressions
  9714. and thereby preserve their ordering relative to the side-effects in
  9715. other operands. So the first step is to collect all the mutable
  9716. variables. We recommend creating an auxiliary function for this,
  9717. named \code{collect-set!}, that recursively traverses expressions,
  9718. returning the set of all variables that occur on the left-hand side of a
  9719. \code{set!}. Here's an excerpt of its implementation.
  9720. \begin{center}
  9721. \begin{minipage}{\textwidth}
  9722. \begin{lstlisting}
  9723. (define (collect-set! e)
  9724. (match e
  9725. [(Var x) (set)]
  9726. [(Int n) (set)]
  9727. [(Let x rhs body)
  9728. (set-union (collect-set! rhs) (collect-set! body))]
  9729. [(SetBang var rhs)
  9730. (set-union (set var) (collect-set! rhs))]
  9731. ...))
  9732. \end{lstlisting}
  9733. \end{minipage}
  9734. \end{center}
  9735. By placing this pass after \code{uniquify}, we need not worry about
  9736. variable shadowing and our logic for \code{Let} can remain simple, as
  9737. in the excerpt above.
  9738. The second step is to mark the occurrences of the mutable variables
  9739. with the new \code{GetBang} AST node (\code{get!} in concrete
  9740. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  9741. function, which takes two parameters: the set of mutable variables
  9742. \code{set!-vars}, and the expression \code{e} to be processed. The
  9743. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9744. mutable variable or leaves it alone if not.
  9745. \begin{center}
  9746. \begin{minipage}{\textwidth}
  9747. \begin{lstlisting}
  9748. (define ((uncover-get!-exp set!-vars) e)
  9749. (match e
  9750. [(Var x)
  9751. (if (set-member? set!-vars x)
  9752. (GetBang x)
  9753. (Var x))]
  9754. ...))
  9755. \end{lstlisting}
  9756. \end{minipage}
  9757. \end{center}
  9758. To wrap things up, define the \code{uncover-get!} function for
  9759. processing a whole program, using \code{collect-set!} to obtain the
  9760. set of mutable variables and then \code{uncover-get!-exp} to replace
  9761. their occurrences with \code{GetBang}.
  9762. \fi}
  9763. \section{Remove Complex Operands}
  9764. \label{sec:rco-loop}
  9765. {\if\edition\racketEd
  9766. %
  9767. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9768. \code{while} are all complex expressions. The subexpressions of
  9769. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9770. %
  9771. \fi}
  9772. {\if\edition\pythonEd
  9773. %
  9774. The change needed for this pass is to add a case for the \code{while}
  9775. statement. The condition of a \code{while} loop is allowed to be a
  9776. complex expression, just like the condition of the \code{if}
  9777. statement.
  9778. %
  9779. \fi}
  9780. %
  9781. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  9782. \LangLoopANF{} of this pass.
  9783. \newcommand{\LwhileMonadASTRacket}{
  9784. \begin{array}{rcl}
  9785. \Atm &::=& \VOID{} \\
  9786. \Exp &::=& \GETBANG{\Var}
  9787. \MID \SETBANG{\Var}{\Exp}
  9788. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9789. &\MID& \WHILE{\Exp}{\Exp}
  9790. \end{array}
  9791. }
  9792. \newcommand{\LwhileMonadASTPython}{
  9793. \begin{array}{rcl}
  9794. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9795. \end{array}
  9796. }
  9797. \begin{figure}[tp]
  9798. \centering
  9799. \begin{tcolorbox}[colback=white]
  9800. \small
  9801. {\if\edition\racketEd
  9802. \[
  9803. \begin{array}{l}
  9804. \gray{\LvarMonadASTRacket} \\ \hline
  9805. \gray{\LifMonadASTRacket} \\ \hline
  9806. \LwhileMonadASTRacket \\
  9807. \begin{array}{rcl}
  9808. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  9809. \end{array}
  9810. \end{array}
  9811. \]
  9812. \fi}
  9813. {\if\edition\pythonEd
  9814. \[
  9815. \begin{array}{l}
  9816. \gray{\LvarMonadASTPython} \\ \hline
  9817. \gray{\LifMonadASTPython} \\ \hline
  9818. \LwhileMonadASTPython \\
  9819. \begin{array}{rcl}
  9820. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9821. \end{array}
  9822. \end{array}
  9823. %% \begin{array}{rcl}
  9824. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9825. %% \Exp &::=& \Atm \MID \READ{} \\
  9826. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9827. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9828. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9829. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9830. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9831. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9832. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9833. %% \end{array}
  9834. \]
  9835. \fi}
  9836. \end{tcolorbox}
  9837. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9838. \label{fig:Lwhile-anf-syntax}
  9839. \end{figure}
  9840. {\if\edition\racketEd
  9841. %
  9842. As usual, when a complex expression appears in a grammar position that
  9843. needs to be atomic, such as the argument of a primitive operator, we
  9844. must introduce a temporary variable and bind it to the complex
  9845. expression. This approach applies, unchanged, to handle the new
  9846. language forms. For example, in the following code there are two
  9847. \code{begin} expressions appearing as arguments to the \code{+}
  9848. operator. The output of \code{rco\_exp} is shown below, in which the
  9849. \code{begin} expressions have been bound to temporary
  9850. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  9851. allowed to have arbitrary expressions in their right-hand-side
  9852. expression, so it is fine to place \code{begin} there.
  9853. %
  9854. \begin{center}
  9855. \begin{tabular}{lcl}
  9856. \begin{minipage}{0.4\textwidth}
  9857. \begin{lstlisting}
  9858. (let ([x2 10])
  9859. (let ([y3 0])
  9860. (+ (+ (begin
  9861. (set! y3 (read))
  9862. (get! x2))
  9863. (begin
  9864. (set! x2 (read))
  9865. (get! y3)))
  9866. (get! x2))))
  9867. \end{lstlisting}
  9868. \end{minipage}
  9869. &
  9870. $\Rightarrow$
  9871. &
  9872. \begin{minipage}{0.4\textwidth}
  9873. \begin{lstlisting}
  9874. (let ([x2 10])
  9875. (let ([y3 0])
  9876. (let ([tmp4 (begin
  9877. (set! y3 (read))
  9878. x2)])
  9879. (let ([tmp5 (begin
  9880. (set! x2 (read))
  9881. y3)])
  9882. (let ([tmp6 (+ tmp4 tmp5)])
  9883. (let ([tmp7 x2])
  9884. (+ tmp6 tmp7)))))))
  9885. \end{lstlisting}
  9886. \end{minipage}
  9887. \end{tabular}
  9888. \end{center}
  9889. \fi}
  9890. \section{Explicate Control \racket{and \LangCLoop{}}}
  9891. \label{sec:explicate-loop}
  9892. \newcommand{\CloopASTRacket}{
  9893. \begin{array}{lcl}
  9894. \Atm &::=& \VOID \\
  9895. \Stmt &::=& \READ{}
  9896. \end{array}
  9897. }
  9898. {\if\edition\racketEd
  9899. Recall that in the \code{explicate\_control} pass we define one helper
  9900. function for each kind of position in the program. For the \LangVar{}
  9901. language of integers and variables we needed assignment and tail
  9902. positions. The \code{if} expressions of \LangIf{} introduced predicate
  9903. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  9904. another kind of position: effect position. Except for the last
  9905. subexpression, the subexpressions inside a \code{begin} are evaluated
  9906. only for their effect. Their result values are discarded. We can
  9907. generate better code by taking this fact into account.
  9908. The output language of \code{explicate\_control} is \LangCLoop{}
  9909. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9910. \LangCIf{}. The only syntactic difference is the addition of \VOID{}
  9911. and that \code{read} may appear as a statement. The most significant
  9912. difference between the programs generated by \code{explicate\_control}
  9913. in Chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  9914. chapter is that the control-flow graphs of the later may contain
  9915. cycles.
  9916. \begin{figure}[tp]
  9917. \begin{tcolorbox}[colback=white]
  9918. \small
  9919. \[
  9920. \begin{array}{l}
  9921. \gray{\CvarASTRacket} \\ \hline
  9922. \gray{\CifASTRacket} \\ \hline
  9923. \CloopASTRacket \\
  9924. \begin{array}{lcl}
  9925. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9926. \end{array}
  9927. \end{array}
  9928. \]
  9929. \end{tcolorbox}
  9930. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9931. \label{fig:c7-syntax}
  9932. \end{figure}
  9933. The new auxiliary function \code{explicate\_effect} takes an
  9934. expression (in an effect position) and the code for its
  9935. continuation. The function returns a $\Tail$ that includes the
  9936. generated code for the input expression followed by the
  9937. continuation. If the expression is obviously pure, that is, never
  9938. causes side effects, then the expression can be removed, so the result
  9939. is just the continuation.
  9940. %
  9941. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  9942. interesting; the generated code is depicted in the following diagram.
  9943. \begin{center}
  9944. \begin{minipage}{0.3\textwidth}
  9945. \xymatrix{
  9946. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  9947. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  9948. & *+[F]{\txt{\itm{cont}}} \\
  9949. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  9950. }
  9951. \end{minipage}
  9952. \end{center}
  9953. We start by creating a fresh label $\itm{loop}$ for the top of the
  9954. loop. Next, recursively process the \itm{body} (in effect position)
  9955. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  9956. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  9957. \itm{body'} as the then-branch and the continuation block as the
  9958. else-branch. The result should be added to the dictionary of
  9959. \code{basic-blocks} with the label \itm{loop}. The result for the
  9960. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  9961. The auxiliary functions for tail, assignment, and predicate positions
  9962. need to be updated. The three new language forms, \code{while},
  9963. \code{set!}, and \code{begin}, can appear in assignment and tail
  9964. positions. Only \code{begin} may appear in predicate positions; the
  9965. other two have result type \code{Void}.
  9966. \fi}
  9967. %
  9968. {\if\edition\pythonEd
  9969. %
  9970. The output of this pass is the language \LangCIf{}. No new language
  9971. features are needed in the output because a \code{while} loop can be
  9972. expressed in terms of \code{goto} and \code{if} statements, which are
  9973. already in \LangCIf{}.
  9974. %
  9975. Add a case for the \code{while} statement to the
  9976. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9977. the condition expression.
  9978. %
  9979. \fi}
  9980. {\if\edition\racketEd
  9981. \section{Select Instructions}
  9982. \label{sec:select-instructions-loop}
  9983. Only two small additions are needed in the \code{select\_instructions}
  9984. pass to handle the changes to \LangCLoop{}. First, to handle the
  9985. addition of \VOID{} we simply translate it to \code{0}. Second,
  9986. \code{read} may appear as a stand-alone statement instead of only
  9987. appearing on the right-hand side of an assignment statement. The code
  9988. generation is nearly identical to the one for assignment; just leave
  9989. off the instruction for moving the result into the left-hand side.
  9990. \fi}
  9991. \section{Register Allocation}
  9992. \label{sec:register-allocation-loop}
  9993. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9994. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9995. which complicates the liveness analysis needed for register
  9996. allocation.
  9997. %
  9998. We recommend using the generic \code{analyze\_dataflow} function that
  9999. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10000. perform liveness analysis, replacing the code in
  10001. \code{uncover\_live} that processed the basic blocks in topological
  10002. order (Section~\ref{sec:liveness-analysis-Lif}).
  10003. The \code{analyze\_dataflow} function has four parameters.
  10004. \begin{enumerate}
  10005. \item The first parameter \code{G} should be passed the transpose
  10006. of the control-flow graph.
  10007. \item The second parameter \code{transfer} should be passed a function
  10008. that applies liveness analysis to a basic block. It takes two
  10009. parameters: the label for the block to analyze and the live-after
  10010. set for that block. The transfer function should return the
  10011. live-before set for the block.
  10012. %
  10013. \racket{Also, as a side-effect, it should update the block's
  10014. $\itm{info}$ with the liveness information for each instruction.}
  10015. %
  10016. \python{Also, as a side-effect, it should update the live-before and
  10017. live-after sets for each instruction.}
  10018. %
  10019. To implement the \code{transfer} function, you should be able to
  10020. reuse the code you already have for analyzing basic blocks.
  10021. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10022. \code{bottom} and \code{join} for the lattice of abstract states,
  10023. i.e. sets of locations. For liveness analysis, the bottom of the
  10024. lattice is the empty set and the join operator is set union.
  10025. \end{enumerate}
  10026. \begin{figure}[p]
  10027. \begin{tcolorbox}[colback=white]
  10028. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10029. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10030. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10031. %\node (Lfun-3) at (6,2) {\large \LangLoop{}};
  10032. %\node (Lfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10033. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10034. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10035. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10036. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10037. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10038. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10039. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10040. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  10041. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  10042. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  10043. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  10044. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  10045. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  10046. %% \path[->,bend left=15] (Lfun) edge [above] node
  10047. %% {\ttfamily\footnotesize type-check} (Lfun-2);
  10048. \path[->,bend left=15] (Lfun) edge [above] node
  10049. {\ttfamily\footnotesize shrink} (Lfun-2);
  10050. \path[->,bend left=15] (Lfun-2) edge [above] node
  10051. {\ttfamily\footnotesize uniquify} (F1-4);
  10052. %% \path[->,bend left=15] (Lfun-3) edge [above] node
  10053. %% {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  10054. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10055. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  10056. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10057. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  10058. %% \path[->,bend right=15] (F1-2) edge [above] node
  10059. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  10060. %% \path[->,bend right=15] (F1-3) edge [above] node
  10061. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10062. \path[->,bend left=15] (F1-4) edge [above] node
  10063. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10064. \path[->,bend left=15] (F1-5) edge [right] node
  10065. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  10066. \path[->,bend right=15] (F1-6) edge [above] node
  10067. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10068. \path[->,bend left=15] (C3-2) edge [left] node
  10069. {\ttfamily\footnotesize select\_instr.} (x86-2);
  10070. \path[->,bend right=15] (x86-2) edge [left] node
  10071. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10072. \path[->,bend right=15] (x86-2-1) edge [below] node
  10073. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  10074. \path[->,bend right=15] (x86-2-2) edge [left] node
  10075. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  10076. \path[->,bend left=15] (x86-3) edge [above] node
  10077. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  10078. \path[->,bend left=15] (x86-4) edge [right] node
  10079. {\ttfamily\footnotesize pre.\_and\_concl.} (x86-5);
  10080. \end{tikzpicture}
  10081. \end{tcolorbox}
  10082. \caption{Diagram of the passes for \LangLoop{}.}
  10083. \label{fig:Lwhile-passes}
  10084. \end{figure}
  10085. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10086. for the compilation of \LangLoop{}.
  10087. % Further Reading: dataflow analysis
  10088. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10089. \chapter{Tuples and Garbage Collection}
  10090. \label{ch:Lvec}
  10091. \index{subject}{tuple}
  10092. \index{subject}{vector}
  10093. \index{subject}{allocate}
  10094. \index{subject}{heap allocate}
  10095. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10096. %% all the IR grammars are spelled out! \\ --Jeremy}
  10097. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10098. %% the root stack. \\ --Jeremy}
  10099. In this chapter we study the implementation of tuples\racket{, called
  10100. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10101. where each element may have a different type.
  10102. %
  10103. This language feature is the first to use the computer's
  10104. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  10105. indefinite, that is, a tuple lives forever from the programmer's
  10106. viewpoint. Of course, from an implementer's viewpoint, it is important
  10107. to reclaim the space associated with a tuple when it is no longer
  10108. needed, which is why we also study \emph{garbage collection}
  10109. \index{garbage collection} techniques in this chapter.
  10110. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  10111. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10112. language of Chapter~\ref{ch:Lwhile} with tuples.
  10113. %
  10114. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10115. copying live tuples back and forth between two halves of the heap. The
  10116. garbage collector requires coordination with the compiler so that it
  10117. can find all of the live tuples.
  10118. %
  10119. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10120. discuss the necessary changes and additions to the compiler passes,
  10121. including a new compiler pass named \code{expose\_allocation}.
  10122. \section{The \LangVec{} Language}
  10123. \label{sec:r3}
  10124. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  10125. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  10126. %
  10127. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10128. creating a tuple, \code{vector-ref} for reading an element of a
  10129. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10130. \code{vector-length} for obtaining the number of elements of a
  10131. tuple.}
  10132. %
  10133. \python{The \LangVec{} language adds 1) tuple creation via a
  10134. comma-separated list of expressions, 2) accessing an element of a
  10135. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10136. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10137. operator, and 4) obtaining the number of elements (the length) of a
  10138. tuple. In this chapter, we restrict access indices to constant
  10139. integers.}
  10140. %
  10141. The program below shows an example use of tuples. It creates a tuple
  10142. \code{t} containing the elements \code{40},
  10143. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10144. contains just \code{2}. The element at index $1$ of \code{t} is
  10145. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  10146. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10147. to which we add \code{2}, the element at index $0$ of the tuple. So
  10148. the result of the program is \code{42}.
  10149. %
  10150. {\if\edition\racketEd
  10151. \begin{lstlisting}
  10152. (let ([t (vector 40 #t (vector 2))])
  10153. (if (vector-ref t 1)
  10154. (+ (vector-ref t 0)
  10155. (vector-ref (vector-ref t 2) 0))
  10156. 44))
  10157. \end{lstlisting}
  10158. \fi}
  10159. {\if\edition\pythonEd
  10160. \begin{lstlisting}
  10161. t = 40, True, (2,)
  10162. print( t[0] + t[2][0] if t[1] else 44 )
  10163. \end{lstlisting}
  10164. \fi}
  10165. \newcommand{\LtupGrammarRacket}{
  10166. \begin{array}{lcl}
  10167. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10168. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  10169. \MID \LP\key{vector-length}\;\Exp\RP \\
  10170. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10171. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10172. \end{array}
  10173. }
  10174. \newcommand{\LtupASTRacket}{
  10175. \begin{array}{lcl}
  10176. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10177. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10178. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10179. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10180. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10181. \end{array}
  10182. }
  10183. \newcommand{\LtupGrammarPython}{
  10184. \begin{array}{rcl}
  10185. \itm{cmp} &::= & \key{is} \\
  10186. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10187. \end{array}
  10188. }
  10189. \newcommand{\LtupASTPython}{
  10190. \begin{array}{lcl}
  10191. \itm{cmp} &::= & \code{Is()} \\
  10192. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10193. &\MID& \LEN{\Exp}
  10194. \end{array}
  10195. }
  10196. \begin{figure}[tbp]
  10197. \centering
  10198. \begin{tcolorbox}[colback=white]
  10199. \small
  10200. {\if\edition\racketEd
  10201. \[
  10202. \begin{array}{l}
  10203. \gray{\LintGrammarRacket{}} \\ \hline
  10204. \gray{\LvarGrammarRacket{}} \\ \hline
  10205. \gray{\LifGrammarRacket{}} \\ \hline
  10206. \gray{\LwhileGrammarRacket} \\ \hline
  10207. \LtupGrammarRacket \\
  10208. \begin{array}{lcl}
  10209. \LangVecM{} &::=& \Exp
  10210. \end{array}
  10211. \end{array}
  10212. \]
  10213. \fi}
  10214. {\if\edition\pythonEd
  10215. \[
  10216. \begin{array}{l}
  10217. \gray{\LintGrammarPython{}} \\ \hline
  10218. \gray{\LvarGrammarPython{}} \\ \hline
  10219. \gray{\LifGrammarPython{}} \\ \hline
  10220. \gray{\LwhileGrammarPython} \\ \hline
  10221. \LtupGrammarPython \\
  10222. \begin{array}{rcl}
  10223. \LangVecM{} &::=& \Stmt^{*}
  10224. \end{array}
  10225. \end{array}
  10226. \]
  10227. \fi}
  10228. \end{tcolorbox}
  10229. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10230. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10231. \label{fig:Lvec-concrete-syntax}
  10232. \end{figure}
  10233. \begin{figure}[tp]
  10234. \centering
  10235. \begin{tcolorbox}[colback=white]
  10236. \small
  10237. {\if\edition\racketEd
  10238. \[
  10239. \begin{array}{l}
  10240. \gray{\LintOpAST} \\ \hline
  10241. \gray{\LvarASTRacket{}} \\ \hline
  10242. \gray{\LifASTRacket{}} \\ \hline
  10243. \gray{\LwhileASTRacket{}} \\ \hline
  10244. \LtupASTRacket{} \\
  10245. \begin{array}{lcl}
  10246. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10247. \end{array}
  10248. \end{array}
  10249. \]
  10250. \fi}
  10251. {\if\edition\pythonEd
  10252. \[
  10253. \begin{array}{l}
  10254. \gray{\LintASTPython} \\ \hline
  10255. \gray{\LvarASTPython} \\ \hline
  10256. \gray{\LifASTPython} \\ \hline
  10257. \gray{\LwhileASTPython} \\ \hline
  10258. \LtupASTPython \\
  10259. \begin{array}{lcl}
  10260. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10261. \end{array}
  10262. \end{array}
  10263. \]
  10264. \fi}
  10265. \end{tcolorbox}
  10266. \caption{The abstract syntax of \LangVec{}.}
  10267. \label{fig:Lvec-syntax}
  10268. \end{figure}
  10269. Tuples raise several interesting new issues. First, variable binding
  10270. performs a shallow-copy when dealing with tuples, which means that
  10271. different variables can refer to the same tuple, that is, two
  10272. variables can be \emph{aliases}\index{subject}{alias} for the same
  10273. entity. Consider the following example in which both \code{t1} and
  10274. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10275. different tuple value but with equal elements. The result of the
  10276. program is \code{42}.
  10277. \begin{center}
  10278. \begin{minipage}{0.96\textwidth}
  10279. {\if\edition\racketEd
  10280. \begin{lstlisting}
  10281. (let ([t1 (vector 3 7)])
  10282. (let ([t2 t1])
  10283. (let ([t3 (vector 3 7)])
  10284. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10285. 42
  10286. 0))))
  10287. \end{lstlisting}
  10288. \fi}
  10289. {\if\edition\pythonEd
  10290. \begin{lstlisting}
  10291. t1 = 3, 7
  10292. t2 = t1
  10293. t3 = 3, 7
  10294. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10295. \end{lstlisting}
  10296. \fi}
  10297. \end{minipage}
  10298. \end{center}
  10299. {\if\edition\racketEd
  10300. Whether two variables are aliased or not affects what happens
  10301. when the underlying tuple is mutated\index{subject}{mutation}.
  10302. Consider the following example in which \code{t1} and \code{t2}
  10303. again refer to the same tuple value.
  10304. \begin{center}
  10305. \begin{minipage}{0.96\textwidth}
  10306. \begin{lstlisting}
  10307. (let ([t1 (vector 3 7)])
  10308. (let ([t2 t1])
  10309. (let ([_ (vector-set! t2 0 42)])
  10310. (vector-ref t1 0))))
  10311. \end{lstlisting}
  10312. \end{minipage}
  10313. \end{center}
  10314. The mutation through \code{t2} is visible when referencing the tuple
  10315. from \code{t1}, so the result of this program is \code{42}.
  10316. \fi}
  10317. The next issue concerns the lifetime of tuples. When does their
  10318. lifetime end? Notice that \LangVec{} does not include an operation
  10319. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10320. to any notion of static scoping.
  10321. %
  10322. {\if\edition\racketEd
  10323. %
  10324. For example, the following program returns \code{42} even though the
  10325. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10326. that reads from the vector it was bound to.
  10327. \begin{center}
  10328. \begin{minipage}{0.96\textwidth}
  10329. \begin{lstlisting}
  10330. (let ([v (vector (vector 44))])
  10331. (let ([x (let ([w (vector 42)])
  10332. (let ([_ (vector-set! v 0 w)])
  10333. 0))])
  10334. (+ x (vector-ref (vector-ref v 0) 0))))
  10335. \end{lstlisting}
  10336. \end{minipage}
  10337. \end{center}
  10338. \fi}
  10339. %
  10340. {\if\edition\pythonEd
  10341. %
  10342. For example, the following program returns \code{42} even though the
  10343. variable \code{x} goes out of scope when the function returns, prior
  10344. to reading the tuple element at index zero. (We study the compilation
  10345. of functions in Chapter~\ref{ch:Lfun}.)
  10346. %
  10347. \begin{center}
  10348. \begin{minipage}{0.96\textwidth}
  10349. \begin{lstlisting}
  10350. def f():
  10351. x = 42, 43
  10352. return x
  10353. t = f()
  10354. print( t[0] )
  10355. \end{lstlisting}
  10356. \end{minipage}
  10357. \end{center}
  10358. \fi}
  10359. %
  10360. From the perspective of programmer-observable behavior, tuples live
  10361. forever. However, if they really lived forever then many long-running
  10362. programs would run out of memory. To solve this problem, the
  10363. language's runtime system performs automatic garbage collection.
  10364. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10365. \LangVec{} language.
  10366. %
  10367. \racket{We define the \code{vector}, \code{vector-ref},
  10368. \code{vector-set!}, and \code{vector-length} operations for
  10369. \LangVec{} in terms of the corresponding operations in Racket. One
  10370. subtle point is that the \code{vector-set!} operation returns the
  10371. \code{\#<void>} value.}
  10372. %
  10373. \python{We represent tuples with Python lists in the interpreter
  10374. because we need to write to them
  10375. (Section~\ref{sec:expose-allocation}). (Python tuples are
  10376. immutable.) We define element access, the \code{is} operator, and
  10377. the \code{len} operator for \LangVec{} in terms of the corresponding
  10378. operations in Python.}
  10379. \begin{figure}[tbp]
  10380. \begin{tcolorbox}[colback=white]
  10381. {\if\edition\racketEd
  10382. \begin{lstlisting}
  10383. (define interp-Lvec-class
  10384. (class interp-Lwhile-class
  10385. (super-new)
  10386. (define/override (interp-op op)
  10387. (match op
  10388. ['eq? (lambda (v1 v2)
  10389. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10390. (and (boolean? v1) (boolean? v2))
  10391. (and (vector? v1) (vector? v2))
  10392. (and (void? v1) (void? v2)))
  10393. (eq? v1 v2)]))]
  10394. ['vector vector]
  10395. ['vector-length vector-length]
  10396. ['vector-ref vector-ref]
  10397. ['vector-set! vector-set!]
  10398. [else (super interp-op op)]
  10399. ))
  10400. (define/override ((interp-exp env) e)
  10401. (match e
  10402. [(HasType e t) ((interp-exp env) e)]
  10403. [else ((super interp-exp env) e)]
  10404. ))
  10405. ))
  10406. (define (interp-Lvec p)
  10407. (send (new interp-Lvec-class) interp-program p))
  10408. \end{lstlisting}
  10409. \fi}
  10410. %
  10411. {\if\edition\pythonEd
  10412. \begin{lstlisting}
  10413. class InterpLtup(InterpLwhile):
  10414. def interp_cmp(self, cmp):
  10415. match cmp:
  10416. case Is():
  10417. return lambda x, y: x is y
  10418. case _:
  10419. return super().interp_cmp(cmp)
  10420. def interp_exp(self, e, env):
  10421. match e:
  10422. case Tuple(es, Load()):
  10423. return tuple([self.interp_exp(e, env) for e in es])
  10424. case Subscript(tup, index, Load()):
  10425. t = self.interp_exp(tup, env)
  10426. n = self.interp_exp(index, env)
  10427. return t[n]
  10428. case _:
  10429. return super().interp_exp(e, env)
  10430. \end{lstlisting}
  10431. \fi}
  10432. \end{tcolorbox}
  10433. \caption{Interpreter for the \LangVec{} language.}
  10434. \label{fig:interp-Lvec}
  10435. \end{figure}
  10436. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10437. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10438. we need to know which elements of the tuple are themselves tuples for
  10439. the purposes of garbage collection. We can obtain this information
  10440. during type checking. The type checker in
  10441. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10442. expression, it also
  10443. %
  10444. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10445. where $T$ is the tuple's type.
  10446. To create the s-expression for the \code{Vector} type in
  10447. Figure~\ref{fig:type-check-Lvec}, we use the
  10448. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10449. operator} \code{,@} to insert the list \code{t*} without its usual
  10450. start and end parentheses. \index{subject}{unquote-slicing}}
  10451. %
  10452. \python{records the type of each tuple expression in a new field
  10453. named \code{has\_type}. Because the type checker has to compute the type
  10454. of each tuple access, the index must be a constant.}
  10455. \begin{figure}[tp]
  10456. \begin{tcolorbox}[colback=white]
  10457. {\if\edition\racketEd
  10458. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10459. (define type-check-Lvec-class
  10460. (class type-check-Lif-class
  10461. (super-new)
  10462. (inherit check-type-equal?)
  10463. (define/override (type-check-exp env)
  10464. (lambda (e)
  10465. (define recur (type-check-exp env))
  10466. (match e
  10467. [(Prim 'vector es)
  10468. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10469. (define t `(Vector ,@t*))
  10470. (values (HasType (Prim 'vector e*) t) t)]
  10471. [(Prim 'vector-ref (list e1 (Int i)))
  10472. (define-values (e1^ t) (recur e1))
  10473. (match t
  10474. [`(Vector ,ts ...)
  10475. (unless (and (0 . <= . i) (i . < . (length ts)))
  10476. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10477. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10478. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10479. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10480. (define-values (e-vec t-vec) (recur e1))
  10481. (define-values (e-arg^ t-arg) (recur arg))
  10482. (match t-vec
  10483. [`(Vector ,ts ...)
  10484. (unless (and (0 . <= . i) (i . < . (length ts)))
  10485. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10486. (check-type-equal? (list-ref ts i) t-arg e)
  10487. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10488. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10489. [(Prim 'vector-length (list e))
  10490. (define-values (e^ t) (recur e))
  10491. (match t
  10492. [`(Vector ,ts ...)
  10493. (values (Prim 'vector-length (list e^)) 'Integer)]
  10494. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10495. [(Prim 'eq? (list arg1 arg2))
  10496. (define-values (e1 t1) (recur arg1))
  10497. (define-values (e2 t2) (recur arg2))
  10498. (match* (t1 t2)
  10499. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10500. [(other wise) (check-type-equal? t1 t2 e)])
  10501. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10502. [(HasType (Prim 'vector es) t)
  10503. ((type-check-exp env) (Prim 'vector es))]
  10504. [(HasType e1 t)
  10505. (define-values (e1^ t^) (recur e1))
  10506. (check-type-equal? t t^ e)
  10507. (values (HasType e1^ t) t)]
  10508. [else ((super type-check-exp env) e)]
  10509. )))
  10510. ))
  10511. (define (type-check-Lvec p)
  10512. (send (new type-check-Lvec-class) type-check-program p))
  10513. \end{lstlisting}
  10514. \fi}
  10515. {\if\edition\pythonEd
  10516. \begin{lstlisting}
  10517. class TypeCheckLtup(TypeCheckLwhile):
  10518. def type_check_exp(self, e, env):
  10519. match e:
  10520. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10521. l = self.type_check_exp(left, env)
  10522. r = self.type_check_exp(right, env)
  10523. check_type_equal(l, r, e)
  10524. return bool
  10525. case Tuple(es, Load()):
  10526. ts = [self.type_check_exp(e, env) for e in es]
  10527. e.has_type = tuple(ts)
  10528. return e.has_type
  10529. case Subscript(tup, Constant(index), Load()):
  10530. tup_ty = self.type_check_exp(tup, env)
  10531. index_ty = self.type_check_exp(Constant(index), env)
  10532. check_type_equal(index_ty, int, index)
  10533. match tup_ty:
  10534. case tuple(ts):
  10535. return ts[index]
  10536. case _:
  10537. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10538. case _:
  10539. return super().type_check_exp(e, env)
  10540. \end{lstlisting}
  10541. \fi}
  10542. \end{tcolorbox}
  10543. \caption{Type checker for the \LangVec{} language.}
  10544. \label{fig:type-check-Lvec}
  10545. \end{figure}
  10546. \section{Garbage Collection}
  10547. \label{sec:GC}
  10548. Garbage collection is a runtime technique for reclaiming space on the
  10549. heap that will not be used in the future of the running program. We
  10550. use the term \emph{object}\index{subject}{object} to refer to any
  10551. value that is stored in the heap, which for now only includes
  10552. tuples.%
  10553. %
  10554. \footnote{The term ``object'' as it is used in the context of
  10555. object-oriented programming has a more specific meaning than how we
  10556. are using the term here.}
  10557. %
  10558. Unfortunately, it is impossible to know precisely which objects will
  10559. be accessed in the future and which will not. Instead, garbage
  10560. collectors over approximate the set of objects that will be accessed by
  10561. identifying which objects can possibly be accessed. The running
  10562. program can directly access objects that are in registers and on the
  10563. procedure call stack. It can also transitively access the elements of
  10564. tuples, starting with a tuple whose address is in a register or on the
  10565. procedure call stack. We define the \emph{root
  10566. set}\index{subject}{root set} to be all the tuple addresses that are
  10567. in registers or on the procedure call stack. We define the \emph{live
  10568. objects}\index{subject}{live objects} to be the objects that are
  10569. reachable from the root set. Garbage collectors reclaim the space that
  10570. is allocated to objects that are no longer live. That means that some
  10571. objects may not get reclaimed as soon as they could be, but at least
  10572. garbage collectors do not reclaim the space dedicated to objects that
  10573. will be accessed in the future! The programmer can influence which
  10574. objects get reclaimed by causing them to become unreachable.
  10575. So the goal of the garbage collector is twofold:
  10576. \begin{enumerate}
  10577. \item preserve all the live objects, and
  10578. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10579. \end{enumerate}
  10580. \subsection{Two-Space Copying Collector}
  10581. Here we study a relatively simple algorithm for garbage collection
  10582. that is the basis of many state-of-the-art garbage
  10583. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10584. particular, we describe a two-space copying
  10585. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10586. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10587. collector} \index{subject}{two-space copying collector}
  10588. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10589. what happens in a two-space collector, showing two time steps, prior
  10590. to garbage collection (on the top) and after garbage collection (on
  10591. the bottom). In a two-space collector, the heap is divided into two
  10592. parts named the FromSpace\index{subject}{FromSpace} and the
  10593. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10594. FromSpace until there is not enough room for the next allocation
  10595. request. At that point, the garbage collector goes to work to make
  10596. room for the next allocation.
  10597. A copying collector makes more room by copying all of the live objects
  10598. from the FromSpace into the ToSpace and then performs a sleight of
  10599. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10600. as the new ToSpace. In the example of
  10601. Figure~\ref{fig:copying-collector}, the root set consists of three
  10602. pointers, one in a register and two on the stack. All of the live
  10603. objects have been copied to the ToSpace (the right-hand side of
  10604. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10605. pointer relationships. For example, the pointer in the register still
  10606. points to a tuple that in turn points to two other tuples. There are
  10607. four tuples that are not reachable from the root set and therefore do
  10608. not get copied into the ToSpace.
  10609. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10610. created by a well-typed program in \LangVec{} because it contains a
  10611. cycle. However, creating cycles will be possible once we get to
  10612. \LangDyn{} (Chapter~\ref{ch:Ldyn}). We design the garbage collector
  10613. to deal with cycles to begin with so we will not need to revisit this
  10614. issue.
  10615. \begin{figure}[tbp]
  10616. \centering
  10617. \begin{tcolorbox}[colback=white]
  10618. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10619. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10620. \\[5ex]
  10621. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10622. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10623. \end{tcolorbox}
  10624. \caption{A copying collector in action.}
  10625. \label{fig:copying-collector}
  10626. \end{figure}
  10627. \subsection{Graph Copying via Cheney's Algorithm}
  10628. \label{sec:cheney}
  10629. \index{subject}{Cheney's algorithm}
  10630. Let us take a closer look at the copying of the live objects. The
  10631. allocated objects and pointers can be viewed as a graph and we need to
  10632. copy the part of the graph that is reachable from the root set. To
  10633. make sure we copy all of the reachable vertices in the graph, we need
  10634. an exhaustive graph traversal algorithm, such as depth-first search or
  10635. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10636. such algorithms take into account the possibility of cycles by marking
  10637. which vertices have already been visited, so as to ensure termination
  10638. of the algorithm. These search algorithms also use a data structure
  10639. such as a stack or queue as a to-do list to keep track of the vertices
  10640. that need to be visited. We use breadth-first search and a trick
  10641. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10642. and copying tuples into the ToSpace.
  10643. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10644. copy progresses. The queue is represented by a chunk of contiguous
  10645. memory at the beginning of the ToSpace, using two pointers to track
  10646. the front and the back of the queue, called the \emph{free pointer}
  10647. and the \emph{scan pointer} respectively. The algorithm starts by
  10648. copying all tuples that are immediately reachable from the root set
  10649. into the ToSpace to form the initial queue. When we copy a tuple, we
  10650. mark the old tuple to indicate that it has been visited. We discuss
  10651. how this marking is accomplish in Section~\ref{sec:data-rep-gc}. Note
  10652. that any pointers inside the copied tuples in the queue still point
  10653. back to the FromSpace. Once the initial queue has been created, the
  10654. algorithm enters a loop in which it repeatedly processes the tuple at
  10655. the front of the queue and pops it off the queue. To process a tuple,
  10656. the algorithm copies all the objects that are directly reachable from it
  10657. to the ToSpace, placing them at the back of the queue. The algorithm
  10658. then updates the pointers in the popped tuple so they point to the
  10659. newly copied objects.
  10660. \begin{figure}[tbp]
  10661. \centering
  10662. \begin{tcolorbox}[colback=white]
  10663. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10664. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10665. \end{tcolorbox}
  10666. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10667. \label{fig:cheney}
  10668. \end{figure}
  10669. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10670. tuple whose second element is $42$ to the back of the queue. The other
  10671. pointer goes to a tuple that has already been copied, so we do not
  10672. need to copy it again, but we do need to update the pointer to the new
  10673. location. This can be accomplished by storing a \emph{forwarding
  10674. pointer}\index{subject}{forwarding pointer} to the new location in the
  10675. old tuple, back when we initially copied the tuple into the
  10676. ToSpace. This completes one step of the algorithm. The algorithm
  10677. continues in this way until the queue is empty, that is, when the scan
  10678. pointer catches up with the free pointer.
  10679. \subsection{Data Representation}
  10680. \label{sec:data-rep-gc}
  10681. The garbage collector places some requirements on the data
  10682. representations used by our compiler. First, the garbage collector
  10683. needs to distinguish between pointers and other kinds of data such as
  10684. integers. There are several ways to accomplish this.
  10685. \begin{enumerate}
  10686. \item Attached a tag to each object that identifies what type of
  10687. object it is~\citep{McCarthy:1960dz}.
  10688. \item Store different types of objects in different
  10689. regions~\citep{Steele:1977ab}.
  10690. \item Use type information from the program to either (a) generate
  10691. type-specific code for collecting or (b) generate tables that
  10692. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10693. \end{enumerate}
  10694. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10695. need to tag objects anyways, so option 1 is a natural choice for those
  10696. languages. However, \LangVec{} is a statically typed language, so it
  10697. would be unfortunate to require tags on every object, especially small
  10698. and pervasive objects like integers and Booleans. Option 3 is the
  10699. best-performing choice for statically typed languages, but comes with
  10700. a relatively high implementation complexity. To keep this chapter
  10701. within a reasonable time budget, we recommend a combination of options
  10702. 1 and 2, using separate strategies for the stack and the heap.
  10703. Regarding the stack, we recommend using a separate stack for pointers,
  10704. which we call the \emph{root stack}\index{subject}{root stack}
  10705. (a.k.a. ``shadow
  10706. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10707. is, when a local variable needs to be spilled and is of type
  10708. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10709. root stack instead of putting it on the procedure call
  10710. stack. Furthermore, we always spill tuple-typed variables if they are
  10711. live during a call to the collector, thereby ensuring that no pointers
  10712. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10713. reproduces the example from Figure~\ref{fig:copying-collector} and
  10714. contrasts it with the data layout using a root stack. The root stack
  10715. contains the two pointers from the regular stack and also the pointer
  10716. in the second register.
  10717. \begin{figure}[tbp]
  10718. \centering
  10719. \begin{tcolorbox}[colback=white]
  10720. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10721. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10722. \end{tcolorbox}
  10723. \caption{Maintaining a root stack to facilitate garbage collection.}
  10724. \label{fig:shadow-stack}
  10725. \end{figure}
  10726. The problem of distinguishing between pointers and other kinds of data
  10727. also arises inside of each tuple on the heap. We solve this problem by
  10728. attaching a tag, an extra 64-bits, to each
  10729. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10730. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10731. that we have drawn the bits in a big-endian way, from right-to-left,
  10732. with bit location 0 (the least significant bit) on the far right,
  10733. which corresponds to the direction of the x86 shifting instructions
  10734. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10735. is dedicated to specifying which elements of the tuple are pointers,
  10736. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10737. indicates there is a pointer and a 0 bit indicates some other kind of
  10738. data. The pointer mask starts at bit location 7. We limit tuples to a
  10739. maximum size of 50 elements, so we just need 50 bits for the pointer
  10740. mask.%
  10741. %
  10742. \footnote{A production-quality compiler would handle
  10743. arbitrary-sized tuples and use a more complex approach.}
  10744. %
  10745. The tag also contains two other pieces of information. The length of
  10746. the tuple (number of elements) is stored in bits location 1 through
  10747. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10748. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10749. has not yet been copied. If the bit has value 0 then the entire tag
  10750. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10751. zero anyways because our tuples are 8-byte aligned.)
  10752. \begin{figure}[tbp]
  10753. \centering
  10754. \begin{tcolorbox}[colback=white]
  10755. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10756. \end{tcolorbox}
  10757. \caption{Representation of tuples in the heap.}
  10758. \label{fig:tuple-rep}
  10759. \end{figure}
  10760. \subsection{Implementation of the Garbage Collector}
  10761. \label{sec:organize-gz}
  10762. \index{subject}{prelude}
  10763. An implementation of the copying collector is provided in the
  10764. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10765. interface to the garbage collector that is used by the compiler. The
  10766. \code{initialize} function creates the FromSpace, ToSpace, and root
  10767. stack and should be called in the prelude of the \code{main}
  10768. function. The arguments of \code{initialize} are the root stack size
  10769. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10770. good choice for both. The \code{initialize} function puts the address
  10771. of the beginning of the FromSpace into the global variable
  10772. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10773. the address that is 1-past the last element of the FromSpace. We use
  10774. half-open intervals to represent chunks of
  10775. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  10776. points to the first element of the root stack.
  10777. As long as there is room left in the FromSpace, your generated code
  10778. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10779. %
  10780. The amount of room left in the FromSpace is the difference between the
  10781. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10782. function should be called when there is not enough room left in the
  10783. FromSpace for the next allocation. The \code{collect} function takes
  10784. a pointer to the current top of the root stack (one past the last item
  10785. that was pushed) and the number of bytes that need to be
  10786. allocated. The \code{collect} function performs the copying collection
  10787. and leaves the heap in a state such that there is enough room for the
  10788. next allocation.
  10789. \begin{figure}[tbp]
  10790. \begin{tcolorbox}[colback=white]
  10791. \begin{lstlisting}
  10792. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10793. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10794. int64_t* free_ptr;
  10795. int64_t* fromspace_begin;
  10796. int64_t* fromspace_end;
  10797. int64_t** rootstack_begin;
  10798. \end{lstlisting}
  10799. \end{tcolorbox}
  10800. \caption{The compiler's interface to the garbage collector.}
  10801. \label{fig:gc-header}
  10802. \end{figure}
  10803. %% \begin{exercise}
  10804. %% In the file \code{runtime.c} you will find the implementation of
  10805. %% \code{initialize} and a partial implementation of \code{collect}.
  10806. %% The \code{collect} function calls another function, \code{cheney},
  10807. %% to perform the actual copy, and that function is left to the reader
  10808. %% to implement. The following is the prototype for \code{cheney}.
  10809. %% \begin{lstlisting}
  10810. %% static void cheney(int64_t** rootstack_ptr);
  10811. %% \end{lstlisting}
  10812. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10813. %% rootstack (which is an array of pointers). The \code{cheney} function
  10814. %% also communicates with \code{collect} through the global
  10815. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10816. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10817. %% the ToSpace:
  10818. %% \begin{lstlisting}
  10819. %% static int64_t* tospace_begin;
  10820. %% static int64_t* tospace_end;
  10821. %% \end{lstlisting}
  10822. %% The job of the \code{cheney} function is to copy all the live
  10823. %% objects (reachable from the root stack) into the ToSpace, update
  10824. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10825. %% update the root stack so that it points to the objects in the
  10826. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10827. %% and ToSpace.
  10828. %% \end{exercise}
  10829. The introduction of garbage collection has a non-trivial impact on our
  10830. compiler passes. We introduce a new compiler pass named
  10831. \code{expose\_allocation} that elaborates the code for allocating
  10832. tuples. We also make significant changes to
  10833. \code{select\_instructions}, \code{build\_interference},
  10834. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10835. make minor changes in several more passes.
  10836. The following program will serve as our running example. It creates
  10837. two tuples, one nested inside the other. Both tuples have length
  10838. one. The program accesses the element in the inner tuple.
  10839. % tests/vectors_test_17.rkt
  10840. {\if\edition\racketEd
  10841. \begin{lstlisting}
  10842. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10843. \end{lstlisting}
  10844. \fi}
  10845. {\if\edition\pythonEd
  10846. \begin{lstlisting}
  10847. print( ((42,),)[0][0] )
  10848. \end{lstlisting}
  10849. \fi}
  10850. {\if\edition\racketEd
  10851. \section{Shrink}
  10852. \label{sec:shrink-Lvec}
  10853. Recall that the \code{shrink} pass translates the primitives operators
  10854. into a smaller set of primitives.
  10855. %
  10856. This pass comes after type checking and the type checker adds a
  10857. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10858. need to add a case for \code{HasType} to the \code{shrink} pass.
  10859. \fi}
  10860. \section{Expose Allocation}
  10861. \label{sec:expose-allocation}
  10862. The pass \code{expose\_allocation} lowers tuple creation into a
  10863. conditional call to the collector followed by allocating the
  10864. appropriate amount of memory and initializing it. We choose to place
  10865. the \code{expose\_allocation} pass before
  10866. \code{remove\_complex\_operands} because it generates
  10867. code that contains complex operands.
  10868. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10869. replaces tuple creation with new lower-level forms that we use in the
  10870. translation of tuple creation.
  10871. %
  10872. {\if\edition\racketEd
  10873. \[
  10874. \begin{array}{lcl}
  10875. \Exp &::=& \cdots
  10876. \MID (\key{collect} \,\itm{int})
  10877. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10878. \MID (\key{global-value} \,\itm{name})
  10879. \end{array}
  10880. \]
  10881. \fi}
  10882. {\if\edition\pythonEd
  10883. \[
  10884. \begin{array}{lcl}
  10885. \Exp &::=& \cdots\\
  10886. &\MID& \key{collect}(\itm{int})
  10887. \MID \key{allocate}(\itm{int},\itm{type})
  10888. \MID \key{global\_value}(\itm{name}) \\
  10889. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10890. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10891. \end{array}
  10892. \]
  10893. \fi}
  10894. %
  10895. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10896. make sure that there are $n$ bytes ready to be allocated. During
  10897. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10898. the \code{collect} function in \code{runtime.c}.
  10899. %
  10900. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10901. space at the front for the 64 bit tag), but the elements are not
  10902. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10903. of the tuple:
  10904. %
  10905. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10906. %
  10907. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10908. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10909. as \code{free\_ptr}.
  10910. %
  10911. \python{The \code{begin} form is an expression that executes a
  10912. sequence of statements and then produces the value of the expression
  10913. at the end.}
  10914. The following shows the transformation of tuple creation into 1) a
  10915. sequence of temporary variable bindings for the initializing
  10916. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10917. \code{allocate}, and 4) the initialization of the tuple. The
  10918. \itm{len} placeholder refers to the length of the tuple and
  10919. \itm{bytes} is how many total bytes need to be allocated for the
  10920. tuple, which is 8 for the tag plus \itm{len} times 8.
  10921. %
  10922. \python{The \itm{type} needed for the second argument of the
  10923. \code{allocate} form can be obtained from the \code{has\_type} field
  10924. of the tuple AST node, which is stored there by running the type
  10925. checker for \LangVec{} immediately before this pass.}
  10926. %
  10927. \begin{center}
  10928. \begin{minipage}{\textwidth}
  10929. {\if\edition\racketEd
  10930. \begin{lstlisting}
  10931. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10932. |$\Longrightarrow$|
  10933. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10934. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10935. (global-value fromspace_end))
  10936. (void)
  10937. (collect |\itm{bytes}|))])
  10938. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10939. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10940. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10941. |$v$|) ... )))) ...)
  10942. \end{lstlisting}
  10943. \fi}
  10944. {\if\edition\pythonEd
  10945. \begin{lstlisting}
  10946. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10947. |$\Longrightarrow$|
  10948. begin:
  10949. |$x_0$| = |$e_0$|
  10950. |$\vdots$|
  10951. |$x_{n-1}$| = |$e_{n-1}$|
  10952. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10953. 0
  10954. else:
  10955. collect(|\itm{bytes}|)
  10956. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10957. |$v$|[0] = |$x_0$|
  10958. |$\vdots$|
  10959. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10960. |$v$|
  10961. \end{lstlisting}
  10962. \fi}
  10963. \end{minipage}
  10964. \end{center}
  10965. %
  10966. \noindent The sequencing of the initializing expressions
  10967. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10968. they may trigger garbage collection and we cannot have an allocated
  10969. but uninitialized tuple on the heap during a collection.
  10970. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10971. \code{expose\_allocation} pass on our running example.
  10972. \begin{figure}[tbp]
  10973. \begin{tcolorbox}[colback=white]
  10974. % tests/s2_17.rkt
  10975. {\if\edition\racketEd
  10976. \begin{lstlisting}
  10977. (vector-ref
  10978. (vector-ref
  10979. (let ([vecinit6
  10980. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  10981. (global-value fromspace_end))
  10982. (void)
  10983. (collect 16))])
  10984. (let ([alloc2 (allocate 1 (Vector Integer))])
  10985. (let ([_3 (vector-set! alloc2 0 42)])
  10986. alloc2)))])
  10987. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  10988. (global-value fromspace_end))
  10989. (void)
  10990. (collect 16))])
  10991. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  10992. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  10993. alloc5))))
  10994. 0)
  10995. 0)
  10996. \end{lstlisting}
  10997. \fi}
  10998. {\if\edition\pythonEd
  10999. \begin{lstlisting}
  11000. print( |$T_1$|[0][0] )
  11001. \end{lstlisting}
  11002. where $T_1$ is
  11003. \begin{lstlisting}
  11004. begin:
  11005. tmp.1 = |$T_2$|
  11006. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11007. 0
  11008. else:
  11009. collect(16)
  11010. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11011. tmp.2[0] = tmp.1
  11012. tmp.2
  11013. \end{lstlisting}
  11014. and $T_2$ is
  11015. \begin{lstlisting}
  11016. begin:
  11017. tmp.3 = 42
  11018. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11019. 0
  11020. else:
  11021. collect(16)
  11022. tmp.4 = allocate(1, TupleType([int]))
  11023. tmp.4[0] = tmp.3
  11024. tmp.4
  11025. \end{lstlisting}
  11026. \fi}
  11027. \end{tcolorbox}
  11028. \caption{Output of the \code{expose\_allocation} pass.}
  11029. \label{fig:expose-alloc-output}
  11030. \end{figure}
  11031. \section{Remove Complex Operands}
  11032. \label{sec:remove-complex-opera-Lvec}
  11033. {\if\edition\racketEd
  11034. %
  11035. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11036. should be treated as complex operands.
  11037. %
  11038. \fi}
  11039. %
  11040. {\if\edition\pythonEd
  11041. %
  11042. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11043. and tuple access should be treated as complex operands. The
  11044. sub-expressions of tuple access must be atomic.
  11045. %
  11046. \fi}
  11047. %% A new case for
  11048. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11049. %% handled carefully to prevent the \code{Prim} node from being separated
  11050. %% from its enclosing \code{HasType}.
  11051. Figure~\ref{fig:Lvec-anf-syntax}
  11052. shows the grammar for the output language \LangAllocANF{} of this
  11053. pass, which is \LangAlloc{} in monadic normal form.
  11054. \newcommand{\LtupMonadASTRacket}{
  11055. \begin{array}{rcl}
  11056. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11057. \MID \GLOBALVALUE{\Var}
  11058. \end{array}
  11059. }
  11060. \newcommand{\LtupMonadASTPython}{
  11061. \begin{array}{rcl}
  11062. \Exp &::=& \GET{\Atm}{\Atm} \\
  11063. &\MID& \LEN{\Atm}\\
  11064. &\MID& \ALLOCATE{\Int}{\Type}
  11065. \MID \GLOBALVALUE{\Var} \\
  11066. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11067. &\MID& \COLLECT{\Int}
  11068. \end{array}
  11069. }
  11070. \begin{figure}[tp]
  11071. \centering
  11072. \begin{tcolorbox}[colback=white]
  11073. \small
  11074. {\if\edition\racketEd
  11075. \[
  11076. \begin{array}{l}
  11077. \gray{\LvarMonadASTRacket} \\ \hline
  11078. \gray{\LifMonadASTRacket} \\ \hline
  11079. \gray{\LwhileMonadASTRacket} \\ \hline
  11080. \LtupMonadASTRacket \\
  11081. \begin{array}{rcl}
  11082. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11083. \end{array}
  11084. \end{array}
  11085. \]
  11086. \fi}
  11087. {\if\edition\pythonEd
  11088. \[
  11089. \begin{array}{l}
  11090. \gray{\LvarMonadASTPython} \\ \hline
  11091. \gray{\LifMonadASTPython} \\ \hline
  11092. \gray{\LwhileMonadASTPython} \\ \hline
  11093. \LtupMonadASTPython \\
  11094. \begin{array}{rcl}
  11095. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11096. \end{array}
  11097. \end{array}
  11098. %% \begin{array}{lcl}
  11099. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  11100. %% \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  11101. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  11102. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  11103. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  11104. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  11105. %% \Exp &::=& \Atm \MID \READ{} \MID \\
  11106. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  11107. %% \MID \UNIOP{\itm{unaryop}}{\Atm}\\
  11108. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  11109. %% % \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp} \\ % removed by RCO
  11110. %% &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  11111. %% &\MID& \GET{\Atm}{\Atm} \\
  11112. %% &\MID& \LEN{\Exp}\\
  11113. %% &\MID& \ALLOCATE{\Int}{\Type}
  11114. %% \MID \GLOBALVALUE{\Var}\RP\\
  11115. %% &\MID& \BEGIN{\Stmt^{*}}{\Atm} \\ % can use this in place of \LET;
  11116. %% % why have \LET?
  11117. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  11118. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  11119. %% &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  11120. %% &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  11121. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  11122. %% \MID \COLLECT{\Int} \\
  11123. %% \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11124. %% \end{array}
  11125. \]
  11126. \fi}
  11127. \end{tcolorbox}
  11128. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11129. \label{fig:Lvec-anf-syntax}
  11130. \end{figure}
  11131. \section{Explicate Control and the \LangCVec{} language}
  11132. \label{sec:explicate-control-r3}
  11133. \newcommand{\CtupASTRacket}{
  11134. \begin{array}{lcl}
  11135. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11136. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11137. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11138. &\MID& \VECLEN{\Atm} \\
  11139. &\MID& \GLOBALVALUE{\Var} \\
  11140. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11141. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11142. \end{array}
  11143. }
  11144. \newcommand{\CtupASTPython}{
  11145. \begin{array}{lcl}
  11146. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11147. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11148. \Stmt &::=& \COLLECT{\Int} \\
  11149. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11150. \end{array}
  11151. }
  11152. \begin{figure}[tp]
  11153. \begin{tcolorbox}[colback=white]
  11154. \small
  11155. {\if\edition\racketEd
  11156. \[
  11157. \begin{array}{l}
  11158. \gray{\CvarASTRacket} \\ \hline
  11159. \gray{\CifASTRacket} \\ \hline
  11160. \gray{\CloopASTRacket} \\ \hline
  11161. \CtupASTRacket \\
  11162. \begin{array}{lcl}
  11163. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11164. \end{array}
  11165. \end{array}
  11166. \]
  11167. \fi}
  11168. {\if\edition\pythonEd
  11169. \[
  11170. \begin{array}{l}
  11171. \gray{\CifASTPython} \\ \hline
  11172. \CtupASTPython \\
  11173. \begin{array}{lcl}
  11174. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11175. \end{array}
  11176. \end{array}
  11177. \]
  11178. \fi}
  11179. \end{tcolorbox}
  11180. \caption{The abstract syntax of \LangCVec{}, extending
  11181. \racket{\LangCLoop{} (Figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11182. (Figure~\ref{fig:c1-syntax})}.}
  11183. \label{fig:c2-syntax}
  11184. \end{figure}
  11185. The output of \code{explicate\_control} is a program in the
  11186. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11187. Figure~\ref{fig:c2-syntax}.
  11188. %
  11189. %% \racket{(The concrete syntax is defined in
  11190. %% Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11191. %
  11192. The new expressions of \LangCVec{} include \key{allocate},
  11193. %
  11194. \racket{\key{vector-ref}, and \key{vector-set!},}
  11195. %
  11196. \python{accessing tuple elements,}
  11197. %
  11198. and \key{global\_value}.
  11199. %
  11200. \python{\LangCVec{} also includes the \code{collect} statement and
  11201. assignment to a tuple element.}
  11202. %
  11203. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11204. %
  11205. The \code{explicate\_control} pass can treat these new forms much like
  11206. the other forms that we've already encountered. The output of the
  11207. \code{explicate\_control} pass on the running example is shown on the
  11208. left-side of Figure~\ref{fig:select-instr-output-gc} in the next
  11209. section.
  11210. \section{Select Instructions and the \LangXGlobal{} Language}
  11211. \label{sec:select-instructions-gc}
  11212. \index{subject}{instruction selection}
  11213. %% void (rep as zero)
  11214. %% allocate
  11215. %% collect (callq collect)
  11216. %% vector-ref
  11217. %% vector-set!
  11218. %% vector-length
  11219. %% global (postpone)
  11220. In this pass we generate x86 code for most of the new operations that
  11221. were needed to compile tuples, including \code{Allocate},
  11222. \code{Collect}, and accessing tuple elements.
  11223. %
  11224. We compile \code{GlobalValue} to \code{Global} because the later has a
  11225. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11226. \ref{fig:x86-2}). \index{subject}{x86}
  11227. The tuple read and write forms translate into \code{movq}
  11228. instructions. (The $+1$ in the offset is to move past the tag at the
  11229. beginning of the tuple representation.)
  11230. %
  11231. \begin{center}
  11232. \begin{minipage}{\textwidth}
  11233. {\if\edition\racketEd
  11234. \begin{lstlisting}
  11235. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11236. |$\Longrightarrow$|
  11237. movq |$\itm{tup}'$|, %r11
  11238. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11239. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11240. |$\Longrightarrow$|
  11241. movq |$\itm{tup}'$|, %r11
  11242. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11243. movq $0, |$\itm{lhs'}$|
  11244. \end{lstlisting}
  11245. \fi}
  11246. {\if\edition\pythonEd
  11247. \begin{lstlisting}
  11248. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11249. |$\Longrightarrow$|
  11250. movq |$\itm{tup}'$|, %r11
  11251. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11252. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11253. |$\Longrightarrow$|
  11254. movq |$\itm{tup}'$|, %r11
  11255. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11256. \end{lstlisting}
  11257. \fi}
  11258. \end{minipage}
  11259. \end{center}
  11260. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11261. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11262. are obtained by translating from \LangCVec{} to x86.
  11263. %
  11264. The move of $\itm{tup}'$ to
  11265. register \code{r11} ensures that offset expression
  11266. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  11267. removing \code{r11} from consideration by the register allocating.
  11268. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11269. \code{rax}. Then the generated code for tuple assignment would be
  11270. \begin{lstlisting}
  11271. movq |$\itm{tup}'$|, %rax
  11272. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11273. \end{lstlisting}
  11274. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11275. \code{patch\_instructions} would insert a move through \code{rax}
  11276. as follows.
  11277. \begin{lstlisting}
  11278. movq |$\itm{tup}'$|, %rax
  11279. movq |$\itm{rhs}'$|, %rax
  11280. movq %rax, |$8(n+1)$|(%rax)
  11281. \end{lstlisting}
  11282. But the above sequence of instructions does not work because we're
  11283. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11284. $\itm{rhs}'$) at the same time!
  11285. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11286. be translated into a sequence of instructions that read the tag of the
  11287. tuple and extract the six bits that represent the tuple length, which
  11288. are the bits starting at index 1 and going up to and including bit 6.
  11289. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11290. (shift right) can be used to accomplish this.
  11291. We compile the \code{allocate} form to operations on the
  11292. \code{free\_ptr}, as shown below. This approach is called
  11293. \emph{inline allocation} as it implements allocation without a
  11294. function call, by simply bumping the allocation pointer. It is much
  11295. more efficient than calling a function for each allocation. The
  11296. address in the \code{free\_ptr} is the next free address in the
  11297. FromSpace, so we copy it into \code{r11} and then move it forward by
  11298. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  11299. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  11300. the tag. We then initialize the \itm{tag} and finally copy the
  11301. address in \code{r11} to the left-hand-side. Refer to
  11302. Figure~\ref{fig:tuple-rep} to see how the tag is organized.
  11303. %
  11304. \racket{We recommend using the Racket operations
  11305. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11306. during compilation.}
  11307. %
  11308. \python{We recommend using the bitwise-or operator \code{|} and the
  11309. shift-left operator \code{<<} to compute the tag during
  11310. compilation.}
  11311. %
  11312. The type annotation in the \code{allocate} form is used to determine
  11313. the pointer mask region of the tag.
  11314. %
  11315. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11316. address of the \code{free\_ptr} global variable but uses a special
  11317. instruction-pointer relative addressing mode of the x86-64 processor.
  11318. In particular, the assembler computes the distance $d$ between the
  11319. address of \code{free\_ptr} and where the \code{rip} would be at that
  11320. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11321. \code{$d$(\%rip)}, which at runtime will compute the address of
  11322. \code{free\_ptr}.
  11323. %
  11324. {\if\edition\racketEd
  11325. \begin{lstlisting}
  11326. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11327. |$\Longrightarrow$|
  11328. movq free_ptr(%rip), %r11
  11329. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11330. movq $|$\itm{tag}$|, 0(%r11)
  11331. movq %r11, |$\itm{lhs}'$|
  11332. \end{lstlisting}
  11333. \fi}
  11334. {\if\edition\pythonEd
  11335. \begin{lstlisting}
  11336. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11337. |$\Longrightarrow$|
  11338. movq free_ptr(%rip), %r11
  11339. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11340. movq $|$\itm{tag}$|, 0(%r11)
  11341. movq %r11, |$\itm{lhs}'$|
  11342. \end{lstlisting}
  11343. \fi}
  11344. The \code{collect} form is compiled to a call to the \code{collect}
  11345. function in the runtime. The arguments to \code{collect} are 1) the
  11346. top of the root stack and 2) the number of bytes that need to be
  11347. allocated. We use another dedicated register, \code{r15}, to
  11348. store the pointer to the top of the root stack. So \code{r15} is not
  11349. available for use by the register allocator.
  11350. {\if\edition\racketEd
  11351. \begin{lstlisting}
  11352. (collect |$\itm{bytes}$|)
  11353. |$\Longrightarrow$|
  11354. movq %r15, %rdi
  11355. movq $|\itm{bytes}|, %rsi
  11356. callq collect
  11357. \end{lstlisting}
  11358. \fi}
  11359. {\if\edition\pythonEd
  11360. \begin{lstlisting}
  11361. collect(|$\itm{bytes}$|)
  11362. |$\Longrightarrow$|
  11363. movq %r15, %rdi
  11364. movq $|\itm{bytes}|, %rsi
  11365. callq collect
  11366. \end{lstlisting}
  11367. \fi}
  11368. \newcommand{\GrammarXGlobal}{
  11369. \begin{array}{lcl}
  11370. \Arg &::=& \itm{label} \key{(\%rip)}
  11371. \end{array}
  11372. }
  11373. \newcommand{\ASTXGlobalRacket}{
  11374. \begin{array}{lcl}
  11375. \Arg &::=& \GLOBAL{\itm{label}}
  11376. \end{array}
  11377. }
  11378. \begin{figure}[tp]
  11379. \begin{tcolorbox}[colback=white]
  11380. \[
  11381. \begin{array}{l}
  11382. \gray{\GrammarXInt} \\ \hline
  11383. \gray{\GrammarXIf} \\ \hline
  11384. \GrammarXGlobal \\
  11385. \begin{array}{lcl}
  11386. \LangXGlobalM{} &::= & \key{.globl main} \\
  11387. & & \key{main:} \; \Instr^{*}
  11388. \end{array}
  11389. \end{array}
  11390. \]
  11391. \end{tcolorbox}
  11392. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11393. \label{fig:x86-2-concrete}
  11394. \end{figure}
  11395. \begin{figure}[tp]
  11396. \begin{tcolorbox}[colback=white]
  11397. \small
  11398. \[
  11399. \begin{array}{l}
  11400. \gray{\ASTXIntRacket} \\ \hline
  11401. \gray{\ASTXIfRacket} \\ \hline
  11402. \ASTXGlobalRacket \\
  11403. \begin{array}{lcl}
  11404. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  11405. \end{array}
  11406. \end{array}
  11407. \]
  11408. \end{tcolorbox}
  11409. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11410. \label{fig:x86-2}
  11411. \end{figure}
  11412. The concrete and abstract syntax of the \LangXGlobal{} language is
  11413. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11414. differs from \LangXIf{} just in the addition of global variables.
  11415. %
  11416. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11417. \code{select\_instructions} pass on the running example.
  11418. \begin{figure}[tbp]
  11419. \centering
  11420. \begin{tcolorbox}[colback=white]
  11421. % tests/s2_17.rkt
  11422. \begin{tabular}{lll}
  11423. \begin{minipage}{0.5\textwidth}
  11424. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11425. start:
  11426. tmp9 = (global-value free_ptr);
  11427. tmp0 = (+ tmp9 16);
  11428. tmp1 = (global-value fromspace_end);
  11429. if (< tmp0 tmp1)
  11430. goto block0;
  11431. else
  11432. goto block1;
  11433. block0:
  11434. _4 = (void);
  11435. goto block9;
  11436. block1:
  11437. (collect 16)
  11438. goto block9;
  11439. block9:
  11440. alloc2 = (allocate 1 (Vector Integer));
  11441. _3 = (vector-set! alloc2 0 42);
  11442. vecinit6 = alloc2;
  11443. tmp2 = (global-value free_ptr);
  11444. tmp3 = (+ tmp2 16);
  11445. tmp4 = (global-value fromspace_end);
  11446. if (< tmp3 tmp4)
  11447. goto block7;
  11448. else
  11449. goto block8;
  11450. block7:
  11451. _8 = (void);
  11452. goto block6;
  11453. block8:
  11454. (collect 16)
  11455. goto block6;
  11456. block6:
  11457. alloc5 = (allocate 1 (Vector (Vector Integer)));
  11458. _7 = (vector-set! alloc5 0 vecinit6);
  11459. tmp5 = (vector-ref alloc5 0);
  11460. return (vector-ref tmp5 0);
  11461. \end{lstlisting}
  11462. \end{minipage}
  11463. &$\Rightarrow$&
  11464. \begin{minipage}{0.4\textwidth}
  11465. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11466. start:
  11467. movq free_ptr(%rip), tmp9
  11468. movq tmp9, tmp0
  11469. addq $16, tmp0
  11470. movq fromspace_end(%rip), tmp1
  11471. cmpq tmp1, tmp0
  11472. jl block0
  11473. jmp block1
  11474. block0:
  11475. movq $0, _4
  11476. jmp block9
  11477. block1:
  11478. movq %r15, %rdi
  11479. movq $16, %rsi
  11480. callq collect
  11481. jmp block9
  11482. block9:
  11483. movq free_ptr(%rip), %r11
  11484. addq $16, free_ptr(%rip)
  11485. movq $3, 0(%r11)
  11486. movq %r11, alloc2
  11487. movq alloc2, %r11
  11488. movq $42, 8(%r11)
  11489. movq $0, _3
  11490. movq alloc2, vecinit6
  11491. movq free_ptr(%rip), tmp2
  11492. movq tmp2, tmp3
  11493. addq $16, tmp3
  11494. movq fromspace_end(%rip), tmp4
  11495. cmpq tmp4, tmp3
  11496. jl block7
  11497. jmp block8
  11498. block7:
  11499. movq $0, _8
  11500. jmp block6
  11501. block8:
  11502. movq %r15, %rdi
  11503. movq $16, %rsi
  11504. callq collect
  11505. jmp block6
  11506. block6:
  11507. movq free_ptr(%rip), %r11
  11508. addq $16, free_ptr(%rip)
  11509. movq $131, 0(%r11)
  11510. movq %r11, alloc5
  11511. movq alloc5, %r11
  11512. movq vecinit6, 8(%r11)
  11513. movq $0, _7
  11514. movq alloc5, %r11
  11515. movq 8(%r11), tmp5
  11516. movq tmp5, %r11
  11517. movq 8(%r11), %rax
  11518. jmp conclusion
  11519. \end{lstlisting}
  11520. \end{minipage}
  11521. \end{tabular}
  11522. \end{tcolorbox}
  11523. \caption{Output of the \code{explicate\_control} (left)
  11524. and \code{select\_instructions} (right) passes on the running example.}
  11525. \label{fig:select-instr-output-gc}
  11526. \end{figure}
  11527. \clearpage
  11528. \section{Register Allocation}
  11529. \label{sec:reg-alloc-gc}
  11530. \index{subject}{register allocation}
  11531. As discussed earlier in this chapter, the garbage collector needs to
  11532. access all the pointers in the root set, that is, all variables that
  11533. are tuples. It will be the responsibility of the register allocator
  11534. to make sure that:
  11535. \begin{enumerate}
  11536. \item the root stack is used for spilling tuple-typed variables, and
  11537. \item if a tuple-typed variable is live during a call to the
  11538. collector, it must be spilled to ensure it is visible to the
  11539. collector.
  11540. \end{enumerate}
  11541. The later responsibility can be handled during construction of the
  11542. interference graph, by adding interference edges between the call-live
  11543. tuple-typed variables and all the callee-saved registers. (They
  11544. already interfere with the caller-saved registers.)
  11545. %
  11546. \racket{The type information for variables is in the \code{Program}
  11547. form, so we recommend adding another parameter to the
  11548. \code{build\_interference} function to communicate this alist.}
  11549. %
  11550. \python{The type information for variables is generated by the type
  11551. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11552. the \code{CProgram} AST mode. You'll need to propagate that
  11553. information so that it is available in this pass.}
  11554. The spilling of tuple-typed variables to the root stack can be handled
  11555. after graph coloring, when choosing how to assign the colors
  11556. (integers) to registers and stack locations. The
  11557. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11558. changes to also record the number of spills to the root stack.
  11559. % build-interference
  11560. %
  11561. % callq
  11562. % extra parameter for var->type assoc. list
  11563. % update 'program' and 'if'
  11564. % allocate-registers
  11565. % allocate spilled vectors to the rootstack
  11566. % don't change color-graph
  11567. % TODO:
  11568. %\section{Patch Instructions}
  11569. %[mention that global variables are memory references]
  11570. \section{Prelude and Conclusion}
  11571. \label{sec:print-x86-gc}
  11572. \label{sec:prelude-conclusion-x86-gc}
  11573. \index{subject}{prelude}\index{subject}{conclusion}
  11574. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11575. \code{prelude\_and\_conclusion} pass on the running example. In the
  11576. prelude and conclusion of the \code{main} function, we allocate space
  11577. on the root stack to make room for the spills of tuple-typed
  11578. variables. We do so by bumping the root stack pointer (\code{r15})
  11579. taking care that the root stack grows up instead of down. For the
  11580. running example, there was just one spill so we increment \code{r15}
  11581. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  11582. One issue that deserves special care is that there may be a call to
  11583. \code{collect} prior to the initializing assignments for all the
  11584. variables in the root stack. We do not want the garbage collector to
  11585. accidentally think that some uninitialized variable is a pointer that
  11586. needs to be followed. Thus, we zero-out all locations on the root
  11587. stack in the prelude of \code{main}. In
  11588. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11589. %
  11590. \lstinline{movq $0, 0(%r15)}
  11591. %
  11592. is sufficient to accomplish this task because there is only one spill.
  11593. In general, we have to clear as many words as there are spills of
  11594. tuple-typed variables. The garbage collector tests each root to see
  11595. if it is null prior to dereferencing it.
  11596. \begin{figure}[htbp]
  11597. % TODO: Python Version -Jeremy
  11598. \begin{tcolorbox}[colback=white]
  11599. \begin{minipage}[t]{0.5\textwidth}
  11600. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11601. .globl main
  11602. main:
  11603. pushq %rbp
  11604. movq %rsp, %rbp
  11605. subq $0, %rsp
  11606. movq $65536, %rdi
  11607. movq $65536, %rsi
  11608. callq initialize
  11609. movq rootstack_begin(%rip), %r15
  11610. movq $0, 0(%r15)
  11611. addq $8, %r15
  11612. jmp start
  11613. conclusion:
  11614. subq $8, %r15
  11615. addq $0, %rsp
  11616. popq %rbp
  11617. retq
  11618. \end{lstlisting}
  11619. \end{minipage}
  11620. \end{tcolorbox}
  11621. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  11622. \label{fig:print-x86-output-gc}
  11623. \end{figure}
  11624. \begin{figure}[tbp]
  11625. \begin{tcolorbox}[colback=white]
  11626. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11627. \node (Lvec) at (0,2) {\large \LangVec{}};
  11628. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11629. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11630. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11631. \node (Lvec-5) at (9,0) {\large \LangAlloc{}};
  11632. \node (Lvec-6) at (6,0) {\large \LangAllocANF{}};
  11633. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11634. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11635. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11636. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11637. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11638. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11639. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11640. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11641. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11642. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11643. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11644. \path[->,bend left=15] (Lvec-4) edge [right] node
  11645. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  11646. \path[->,bend left=15] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex.} (Lvec-6);
  11647. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11648. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11649. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11650. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11651. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11652. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11653. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  11654. \end{tikzpicture}
  11655. \end{tcolorbox}
  11656. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11657. \label{fig:Lvec-passes}
  11658. \end{figure}
  11659. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11660. for the compilation of \LangVec{}.
  11661. \clearpage
  11662. {\if\edition\racketEd
  11663. \section{Challenge: Simple Structures}
  11664. \label{sec:simple-structures}
  11665. \index{subject}{struct}
  11666. \index{subject}{structure}
  11667. The language \LangStruct{} extends \LangVec{} with support for simple
  11668. structures. Its concrete syntax is defined in
  11669. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11670. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11671. Racket is a user-defined data type that contains named fields and that
  11672. is heap allocated, similar to a vector. The following is an example of
  11673. a structure definition, in this case the definition of a \code{point}
  11674. type.
  11675. \begin{lstlisting}
  11676. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11677. \end{lstlisting}
  11678. \newcommand{\LstructGrammarRacket}{
  11679. \begin{array}{lcl}
  11680. \Type &::=& \Var \\
  11681. \Exp &::=& (\Var\;\Exp \ldots)\\
  11682. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11683. \end{array}
  11684. }
  11685. \newcommand{\LstructASTRacket}{
  11686. \begin{array}{lcl}
  11687. \Type &::=& \VAR{\Var} \\
  11688. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11689. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11690. \end{array}
  11691. }
  11692. \begin{figure}[tbp]
  11693. \centering
  11694. \begin{tcolorbox}[colback=white]
  11695. \[
  11696. \begin{array}{l}
  11697. \gray{\LintGrammarRacket{}} \\ \hline
  11698. \gray{\LvarGrammarRacket{}} \\ \hline
  11699. \gray{\LifGrammarRacket{}} \\ \hline
  11700. \gray{\LwhileGrammarRacket} \\ \hline
  11701. \gray{\LtupGrammarRacket} \\ \hline
  11702. \LstructGrammarRacket \\
  11703. \begin{array}{lcl}
  11704. \LangStruct{} &::=& \Def \ldots \; \Exp
  11705. \end{array}
  11706. \end{array}
  11707. \]
  11708. \end{tcolorbox}
  11709. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11710. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11711. \label{fig:Lstruct-concrete-syntax}
  11712. \end{figure}
  11713. \begin{figure}[tbp]
  11714. \centering
  11715. \begin{tcolorbox}[colback=white]
  11716. \small
  11717. \[
  11718. \begin{array}{l}
  11719. \gray{\LintASTRacket{}} \\ \hline
  11720. \gray{\LvarASTRacket{}} \\ \hline
  11721. \gray{\LifASTRacket{}} \\ \hline
  11722. \gray{\LwhileASTRacket} \\ \hline
  11723. \gray{\LtupASTRacket} \\ \hline
  11724. \LstructASTRacket \\
  11725. \begin{array}{lcl}
  11726. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11727. \end{array}
  11728. \end{array}
  11729. \]
  11730. \end{tcolorbox}
  11731. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11732. (Figure~\ref{fig:Lvec-syntax}).}
  11733. \label{fig:Lstruct-syntax}
  11734. \end{figure}
  11735. An instance of a structure is created using function call syntax, with
  11736. the name of the structure in the function position:
  11737. \begin{lstlisting}
  11738. (point 7 12)
  11739. \end{lstlisting}
  11740. Function-call syntax is also used to read a field of a structure. The
  11741. function name is formed by the structure name, a dash, and the field
  11742. name. The following example uses \code{point-x} and \code{point-y} to
  11743. access the \code{x} and \code{y} fields of two point instances.
  11744. \begin{center}
  11745. \begin{lstlisting}
  11746. (let ([pt1 (point 7 12)])
  11747. (let ([pt2 (point 4 3)])
  11748. (+ (- (point-x pt1) (point-x pt2))
  11749. (- (point-y pt1) (point-y pt2)))))
  11750. \end{lstlisting}
  11751. \end{center}
  11752. Similarly, to write to a field of a structure, use its set function,
  11753. whose name starts with \code{set-}, followed by the structure name,
  11754. then a dash, then the field name, and concluded with an exclamation
  11755. mark. The following example uses \code{set-point-x!} to change the
  11756. \code{x} field from \code{7} to \code{42}.
  11757. \begin{center}
  11758. \begin{lstlisting}
  11759. (let ([pt (point 7 12)])
  11760. (let ([_ (set-point-x! pt 42)])
  11761. (point-x pt)))
  11762. \end{lstlisting}
  11763. \end{center}
  11764. \begin{exercise}\normalfont\normalsize
  11765. Create a type checker for \LangStruct{} by extending the type
  11766. checker for \LangVec{}. Extend your compiler with support for simple
  11767. structures, compiling \LangStruct{} to x86 assembly code. Create
  11768. five new test cases that use structures and test your compiler.
  11769. \end{exercise}
  11770. % TODO: create an interpreter for L_struct
  11771. \clearpage
  11772. \section{Challenge: Arrays}
  11773. \label{sec:arrays}
  11774. In Chapter~\ref{ch:Lvec} we studied tuples, that is, a heterogeneous
  11775. sequences of elements whose length is determined at compile-time. This
  11776. challenge is also about sequences, but this time the length is
  11777. determined at run-time and all the elements have the same type (they
  11778. are homogeneous). We use the term ``array'' for this later kind of
  11779. sequence.
  11780. The Racket language does not distinguish between tuples and arrays,
  11781. they are both represented by vectors. However, Typed Racket
  11782. distinguishes between tuples and arrays: the \code{Vector} type is for
  11783. tuples and the \code{Vectorof} type is for arrays.
  11784. %
  11785. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11786. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11787. and the \code{make-vector} primitive operator for creating an array,
  11788. whose arguments are the length of the array and an initial value for
  11789. all the elements in the array. The \code{vector-length},
  11790. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11791. for tuples become overloaded for use with arrays.
  11792. %
  11793. We also include integer multiplication in \LangArray{}, as it is
  11794. useful in many examples involving arrays such as computing the
  11795. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11796. \newcommand{\LarrayGrammarRacket}{
  11797. \begin{array}{lcl}
  11798. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11799. \Exp &::=& \CMUL{\Exp}{\Exp}
  11800. \MID \CMAKEVEC{\Exp}{\Exp} \\
  11801. \end{array}
  11802. }
  11803. \begin{figure}[tp]
  11804. \centering
  11805. \begin{tcolorbox}[colback=white]
  11806. \small
  11807. {\if\edition\racketEd
  11808. \[
  11809. \begin{array}{l}
  11810. \gray{\LintGrammarRacket{}} \\ \hline
  11811. \gray{\LvarGrammarRacket{}} \\ \hline
  11812. \gray{\LifGrammarRacket{}} \\ \hline
  11813. \gray{\LwhileGrammarRacket} \\ \hline
  11814. \gray{\LtupGrammarRacket} \\ \hline
  11815. \LarrayGrammarRacket \\
  11816. \begin{array}{lcl}
  11817. \LangArray{} &::=& \Exp
  11818. \end{array}
  11819. \end{array}
  11820. \]
  11821. \fi}
  11822. {\if\edition\pythonEd
  11823. UNDER CONSTRUCTION
  11824. \fi}
  11825. \end{tcolorbox}
  11826. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11827. \label{fig:Lvecof-concrete-syntax}
  11828. \end{figure}
  11829. \begin{figure}[tp]
  11830. \begin{tcolorbox}[colback=white]
  11831. \begin{lstlisting}
  11832. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11833. [n : Integer]) : Integer
  11834. (let ([i 0])
  11835. (let ([prod 0])
  11836. (begin
  11837. (while (< i n)
  11838. (begin
  11839. (set! prod (+ prod (* (vector-ref A i)
  11840. (vector-ref B i))))
  11841. (set! i (+ i 1))
  11842. ))
  11843. prod))))
  11844. (let ([A (make-vector 2 2)])
  11845. (let ([B (make-vector 2 3)])
  11846. (+ (inner-product A B 2)
  11847. 30)))
  11848. \end{lstlisting}
  11849. \end{tcolorbox}
  11850. \caption{Example program that computes the inner-product.}
  11851. \label{fig:inner-product}
  11852. \end{figure}
  11853. The type checker for \LangArray{} is defined in
  11854. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11855. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11856. of the initializing expression. The length expression is required to
  11857. have type \code{Integer}. The type checking of the operators
  11858. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11859. updated to handle the situation where the vector has type
  11860. \code{Vectorof}. In these cases we translate the operators to their
  11861. \code{vectorof} form so that later passes can easily distinguish
  11862. between operations on tuples versus arrays. We override the
  11863. \code{operator-types} method to provide the type signature for
  11864. multiplication: it takes two integers and returns an integer.
  11865. \begin{figure}[tbp]
  11866. \begin{tcolorbox}[colback=white]
  11867. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11868. (define type-check-Lvecof-class
  11869. (class type-check-Lvec-class
  11870. (super-new)
  11871. (inherit check-type-equal?)
  11872. (define/override (operator-types)
  11873. (append '((* . ((Integer Integer) . Integer)))
  11874. (super operator-types)))
  11875. (define/override (type-check-exp env)
  11876. (lambda (e)
  11877. (define recur (type-check-exp env))
  11878. (match e
  11879. [(Prim 'make-vector (list e1 e2))
  11880. (define-values (e1^ t1) (recur e1))
  11881. (define-values (e2^ elt-type) (recur e2))
  11882. (define vec-type `(Vectorof ,elt-type))
  11883. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11884. vec-type)]
  11885. [(Prim 'vector-ref (list e1 e2))
  11886. (define-values (e1^ t1) (recur e1))
  11887. (define-values (e2^ t2) (recur e2))
  11888. (match* (t1 t2)
  11889. [(`(Vectorof ,elt-type) 'Integer)
  11890. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11891. [(other wise) ((super type-check-exp env) e)])]
  11892. [(Prim 'vector-set! (list e1 e2 e3) )
  11893. (define-values (e-vec t-vec) (recur e1))
  11894. (define-values (e2^ t2) (recur e2))
  11895. (define-values (e-arg^ t-arg) (recur e3))
  11896. (match t-vec
  11897. [`(Vectorof ,elt-type)
  11898. (check-type-equal? elt-type t-arg e)
  11899. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11900. [else ((super type-check-exp env) e)])]
  11901. [(Prim 'vector-length (list e1))
  11902. (define-values (e1^ t1) (recur e1))
  11903. (match t1
  11904. [`(Vectorof ,t)
  11905. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11906. [else ((super type-check-exp env) e)])]
  11907. [else ((super type-check-exp env) e)])))
  11908. ))
  11909. (define (type-check-Lvecof p)
  11910. (send (new type-check-Lvecof-class) type-check-program p))
  11911. \end{lstlisting}
  11912. \end{tcolorbox}
  11913. \caption{Type checker for the \LangArray{} language.}
  11914. \label{fig:type-check-Lvecof}
  11915. \end{figure}
  11916. The interpreter for \LangArray{} is defined in
  11917. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11918. implemented with Racket's \code{make-vector} function and
  11919. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11920. integers.
  11921. \begin{figure}[tbp]
  11922. \begin{tcolorbox}[colback=white]
  11923. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11924. (define interp-Lvecof-class
  11925. (class interp-Lvec-class
  11926. (super-new)
  11927. (define/override (interp-op op)
  11928. (match op
  11929. ['make-vector make-vector]
  11930. ['* fx*]
  11931. [else (super interp-op op)]))
  11932. ))
  11933. (define (interp-Lvecof p)
  11934. (send (new interp-Lvecof-class) interp-program p))
  11935. \end{lstlisting}
  11936. \end{tcolorbox}
  11937. \caption{Interpreter for \LangArray{}.}
  11938. \label{fig:interp-Lvecof}
  11939. \end{figure}
  11940. \subsection{Data Representation}
  11941. \label{sec:array-rep}
  11942. Just like tuples, we store arrays on the heap which means that the
  11943. garbage collector will need to inspect arrays. An immediate thought is
  11944. to use the same representation for arrays that we use for tuples.
  11945. However, we limit tuples to a length of $50$ so that their length and
  11946. pointer mask can fit into the 64-bit tag at the beginning of each
  11947. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11948. millions of elements, so we need more bits to store the length.
  11949. However, because arrays are homogeneous, we only need $1$ bit for the
  11950. pointer mask instead of one bit per array elements. Finally, the
  11951. garbage collector will need to be able to distinguish between tuples
  11952. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11953. arrive at the following layout for the 64-bit tag at the beginning of
  11954. an array:
  11955. \begin{itemize}
  11956. \item The right-most bit is the forwarding bit, just like in a tuple.
  11957. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11958. it is not.
  11959. \item The next bit to the left is the pointer mask. A $0$ indicates
  11960. that none of the elements are pointers to the heap and a $1$
  11961. indicates that all of the elements are pointers.
  11962. \item The next $61$ bits store the length of the array.
  11963. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11964. array ($1$).
  11965. \end{itemize}
  11966. %% Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  11967. %% differentiate the kinds of values that have been injected into the
  11968. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11969. %% to indicate that the value is an array.
  11970. In the following subsections we provide hints regarding how to update
  11971. the passes to handle arrays.
  11972. \subsection{Bounds Checking}
  11973. We recommend inserting a new pass named \code{check\_bounds} that
  11974. inserts code around each the \code{vector-ref} and \code{vector-set!}
  11975. operation to ensure that the index is greater than or equal to zero
  11976. and less than the \code{vector-length}.
  11977. %% \subsection{Reveal Casts}
  11978. %% The array-access operators \code{vectorof-ref} and
  11979. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11980. %% \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  11981. %% that the type checker cannot tell whether the index will be in bounds,
  11982. %% so the bounds check must be performed at run time. Recall that the
  11983. %% \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11984. %% an \code{If} arround a vector reference for update to check whether
  11985. %% the index is less than the length. You should do the same for
  11986. %% \code{vectorof-ref} and \code{vectorof-set!} .
  11987. %% In addition, the handling of the \code{any-vector} operators in
  11988. %% \code{reveal-casts} needs to be updated to account for arrays that are
  11989. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  11990. %% generated code should test whether the tag is for tuples (\code{010})
  11991. %% or arrays (\code{110}) and then dispatch to either
  11992. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11993. %% we add a case in \code{select\_instructions} to generate the
  11994. %% appropriate instructions for accessing the array length from the
  11995. %% header of an array.
  11996. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11997. %% the generated code needs to check that the index is less than the
  11998. %% vector length, so like the code for \code{any-vector-length}, check
  11999. %% the tag to determine whether to use \code{any-vector-length} or
  12000. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  12001. %% is complete, the generated code can use \code{any-vector-ref} and
  12002. %% \code{any-vector-set!} for both tuples and arrays because the
  12003. %% instructions used for those operators do not look at the tag at the
  12004. %% front of the tuple or array.
  12005. \subsection{Expose Allocation}
  12006. This pass should translate the \code{make-vector} operator into
  12007. lower-level operations. In particular, the new AST node
  12008. $\LP\key{AllocateArray}~\Exp~\Type\RP$ is analogous to the
  12009. \code{Allocate} AST node for tuples. It allocates an array of the
  12010. length specified by the $\Exp$, but does not initialize the elements
  12011. of the array. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$
  12012. where $T$ is the element type for the array. Regarding the
  12013. initialization of the array, we recommend generated a \code{while}
  12014. loop that uses \code{vector-set!} to put the initializing value into
  12015. every element of the array.
  12016. \subsection{Remove Complex Operands}
  12017. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  12018. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12019. complex and its subexpression must be atomic.
  12020. \subsection{Explicate Control}
  12021. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  12022. \code{explicate\_assign}.
  12023. \subsection{Select Instructions}
  12024. Generate instructions for \code{AllocateArray} similar to those for
  12025. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  12026. that the tag at the front of the array should instead use the
  12027. representation discussed in Section~\ref{sec:array-rep}.
  12028. Regarding \code{vectorof-length}, extract the length from the tag
  12029. according to the representation discussed in
  12030. Section~\ref{sec:array-rep}.
  12031. The instructions generated for \code{vectorof-ref} differ from those
  12032. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  12033. that the index is not a constant so the offset must be computed at
  12034. runtime. The same is true for \code{vectorof-set!}. Also, the
  12035. \code{vectorof-set!} may appear in an assignment and as a stand-alone
  12036. statement, so make sure to handle both situations in this pass.
  12037. %% Finally, the instructions for \code{any-vectorof-length} should be
  12038. %% similar to those for \code{vectorof-length}, except that one must
  12039. %% first project the array by writing zeroes into the $3$-bit tag
  12040. \begin{exercise}\normalfont\normalsize
  12041. Implement a compiler for the \LangArray{} language by extending your
  12042. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12043. programs, including the one in Figure~\ref{fig:inner-product} and also
  12044. a program that multiplies two matrices. Note that although matrices
  12045. are 2-dimensional arrays, they can be encoded into 1-dimensional
  12046. arrays by laying out each row in the array, one after the next.
  12047. \end{exercise}
  12048. \section{Challenge: Generational Collection}
  12049. The copying collector described in Section~\ref{sec:GC} can incur
  12050. significant runtime overhead because the call to \code{collect} takes
  12051. time proportional to all of the live data. One way to reduce this
  12052. overhead is to reduce how much data is inspected in each call to
  12053. \code{collect}. In particular, researchers have observed that recently
  12054. allocated data is more likely to become garbage then data that has
  12055. survived one or more previous calls to \code{collect}. This insight
  12056. motivated the creation of \emph{generational garbage collectors}
  12057. \index{subject}{generational garbage collector} that
  12058. 1) segregates data according to its age into two or more generations,
  12059. 2) allocates less space for younger generations, so collecting them is
  12060. faster, and more space for the older generations, and 3) performs
  12061. collection on the younger generations more frequently then for older
  12062. generations~\citep{Wilson:1992fk}.
  12063. For this challenge assignment, the goal is to adapt the copying
  12064. collector implemented in \code{runtime.c} to use two generations, one
  12065. for young data and one for old data. Each generation consists of a
  12066. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  12067. \code{collect} function to use the two generations.
  12068. \begin{enumerate}
  12069. \item Copy the young generation's FromSpace to its ToSpace then switch
  12070. the role of the ToSpace and FromSpace
  12071. \item If there is enough space for the requested number of bytes in
  12072. the young FromSpace, then return from \code{collect}.
  12073. \item If there is not enough space in the young FromSpace for the
  12074. requested bytes, then move the data from the young generation to the
  12075. old one with the following steps:
  12076. \begin{enumerate}
  12077. \item If there is enough room in the old FromSpace, copy the young
  12078. FromSpace to the old FromSpace and then return.
  12079. \item If there is not enough room in the old FromSpace, then collect
  12080. the old generation by copying the old FromSpace to the old ToSpace
  12081. and swap the roles of the old FromSpace and ToSpace.
  12082. \item If there is enough room now, copy the young FromSpace to the
  12083. old FromSpace and return. Otherwise, allocate a larger FromSpace
  12084. and ToSpace for the old generation. Copy the young FromSpace and
  12085. the old FromSpace into the larger FromSpace for the old
  12086. generation and then return.
  12087. \end{enumerate}
  12088. \end{enumerate}
  12089. We recommend that you generalize the \code{cheney} function so that it
  12090. can be used for all the copies mentioned above: between the young
  12091. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  12092. between the young FromSpace and old FromSpace. This can be
  12093. accomplished by adding parameters to \code{cheney} that replace its
  12094. use of the global variables \code{fromspace\_begin},
  12095. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  12096. Note that the collection of the young generation does not traverse the
  12097. old generation. This introduces a potential problem: there may be
  12098. young data that is only reachable through pointers in the old
  12099. generation. If these pointers are not taken into account, the
  12100. collector could throw away young data that is live! One solution,
  12101. called \emph{pointer recording}, is to maintain a set of all the
  12102. pointers from the old generation into the new generation and consider
  12103. this set as part of the root set. To maintain this set, the compiler
  12104. must insert extra instructions around every \code{vector-set!}. If the
  12105. vector being modified is in the old generation, and if the value being
  12106. written is a pointer into the new generation, than that pointer must
  12107. be added to the set. Also, if the value being overwritten was a
  12108. pointer into the new generation, then that pointer should be removed
  12109. from the set.
  12110. \begin{exercise}\normalfont\normalsize
  12111. Adapt the \code{collect} function in \code{runtime.c} to implement
  12112. generational garbage collection, as outlined in this section.
  12113. Update the code generation for \code{vector-set!} to implement
  12114. pointer recording. Make sure that your new compiler and runtime
  12115. passes your test suite.
  12116. \end{exercise}
  12117. \fi}
  12118. \section{Further Reading}
  12119. \citet{Appel90} describes many data representation approaches,
  12120. including the ones used in the compilation of Standard ML.
  12121. There are many alternatives to copying collectors (and their bigger
  12122. siblings, the generational collectors) when its comes to garbage
  12123. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12124. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12125. collectors are that allocation is fast (just a comparison and pointer
  12126. increment), there is no fragmentation, cyclic garbage is collected,
  12127. and the time complexity of collection only depends on the amount of
  12128. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12129. main disadvantages of a two-space copying collector is that it uses a
  12130. lot of extra space and takes a long time to perform the copy, though
  12131. these problems are ameliorated in generational collectors.
  12132. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12133. small objects and generate a lot of garbage, so copying and
  12134. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12135. Garbage collection is an active research topic, especially concurrent
  12136. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12137. developing new techniques and revisiting old
  12138. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12139. meet every year at the International Symposium on Memory Management to
  12140. present these findings.
  12141. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12142. \chapter{Functions}
  12143. \label{ch:Lfun}
  12144. \index{subject}{function}
  12145. This chapter studies the compilation of a subset of \racket{Typed
  12146. Racket}\python{Python} in which only top-level function definitions
  12147. are allowed. This kind of function appears in the C programming
  12148. language and it serves as an important stepping stone to implementing
  12149. lexically-scoped functions in the form of \key{lambda} abstractions,
  12150. which is the topic of Chapter~\ref{ch:Llambda}.
  12151. \section{The \LangFun{} Language}
  12152. The concrete and abstract syntax for function definitions and function
  12153. application is shown in Figures~\ref{fig:Lfun-concrete-syntax} and
  12154. \ref{fig:Lfun-syntax}, where we define the \LangFun{} language.
  12155. Programs in \LangFun{} begin with zero or more function definitions.
  12156. The function names from these definitions are in-scope for the entire
  12157. program, including all of the function definitions (so the ordering of
  12158. function definitions does not matter).
  12159. %
  12160. \python{The abstract syntax for function parameters in
  12161. Figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  12162. consists of a parameter name and its type. This design differs from
  12163. Python's \code{ast} module, which has a more complex structure for
  12164. function parameters to handle keyword parameters,
  12165. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12166. complex Python abstract syntax into the simpler syntax of
  12167. Figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  12168. \code{FunctionDef} constructor are for decorators and a type
  12169. comment, neither of which are used by our compiler. We recommend
  12170. replacing them with \code{None} in the \code{shrink} pass.
  12171. }
  12172. %
  12173. The concrete syntax for function application\index{subject}{function
  12174. application} is
  12175. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12176. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12177. where the first expression
  12178. must evaluate to a function and the remaining expressions are the arguments. The
  12179. abstract syntax for function application is
  12180. $\APPLY{\Exp}{\Exp^*}$.
  12181. %% The syntax for function application does not include an explicit
  12182. %% keyword, which is error prone when using \code{match}. To alleviate
  12183. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12184. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12185. Functions are first-class in the sense that a function pointer
  12186. \index{subject}{function pointer} is data and can be stored in memory or passed
  12187. as a parameter to another function. Thus, there is a function
  12188. type, written
  12189. {\if\edition\racketEd
  12190. \begin{lstlisting}
  12191. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12192. \end{lstlisting}
  12193. \fi}
  12194. {\if\edition\pythonEd
  12195. \begin{lstlisting}
  12196. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12197. \end{lstlisting}
  12198. \fi}
  12199. %
  12200. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12201. through $\Type_n$ and whose return type is $\Type_R$. The main
  12202. limitation of these functions (with respect to
  12203. \racket{Racket}\python{Python} functions) is that they are not
  12204. lexically scoped. That is, the only external entities that can be
  12205. referenced from inside a function body are other globally-defined
  12206. functions. The syntax of \LangFun{} prevents function definitions from being
  12207. nested inside each other.
  12208. \newcommand{\LfunGrammarRacket}{
  12209. \begin{array}{lcl}
  12210. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12211. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12212. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12213. \end{array}
  12214. }
  12215. \newcommand{\LfunASTRacket}{
  12216. \begin{array}{lcl}
  12217. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12218. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12219. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12220. \end{array}
  12221. }
  12222. \newcommand{\LfunGrammarPython}{
  12223. \begin{array}{lcl}
  12224. \Type &::=& \key{int}
  12225. \MID \key{bool}
  12226. \MID \key{tuple}\LS \Type^+ \RS
  12227. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12228. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12229. \Stmt &::=& \CRETURN{\Exp} \\
  12230. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12231. \end{array}
  12232. }
  12233. \newcommand{\LfunASTPython}{
  12234. \begin{array}{lcl}
  12235. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  12236. \MID \key{TupleType}\LS\Type^+\RS\\
  12237. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12238. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12239. \Stmt &::=& \RETURN{\Exp} \\
  12240. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  12241. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12242. \end{array}
  12243. }
  12244. \begin{figure}[tp]
  12245. \centering
  12246. \begin{tcolorbox}[colback=white]
  12247. \small
  12248. {\if\edition\racketEd
  12249. \[
  12250. \begin{array}{l}
  12251. \gray{\LintGrammarRacket{}} \\ \hline
  12252. \gray{\LvarGrammarRacket{}} \\ \hline
  12253. \gray{\LifGrammarRacket{}} \\ \hline
  12254. \gray{\LwhileGrammarRacket} \\ \hline
  12255. \gray{\LtupGrammarRacket} \\ \hline
  12256. \LfunGrammarRacket \\
  12257. \begin{array}{lcl}
  12258. \LangFunM{} &::=& \Def \ldots \; \Exp
  12259. \end{array}
  12260. \end{array}
  12261. \]
  12262. \fi}
  12263. {\if\edition\pythonEd
  12264. \[
  12265. \begin{array}{l}
  12266. \gray{\LintGrammarPython{}} \\ \hline
  12267. \gray{\LvarGrammarPython{}} \\ \hline
  12268. \gray{\LifGrammarPython{}} \\ \hline
  12269. \gray{\LwhileGrammarPython} \\ \hline
  12270. \gray{\LtupGrammarPython} \\ \hline
  12271. \LfunGrammarPython \\
  12272. \begin{array}{rcl}
  12273. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12274. \end{array}
  12275. \end{array}
  12276. \]
  12277. \fi}
  12278. \end{tcolorbox}
  12279. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  12280. \label{fig:Lfun-concrete-syntax}
  12281. \end{figure}
  12282. \begin{figure}[tp]
  12283. \centering
  12284. \begin{tcolorbox}[colback=white]
  12285. \small
  12286. {\if\edition\racketEd
  12287. \[
  12288. \begin{array}{l}
  12289. \gray{\LintOpAST} \\ \hline
  12290. \gray{\LvarASTRacket{}} \\ \hline
  12291. \gray{\LifASTRacket{}} \\ \hline
  12292. \gray{\LwhileASTRacket{}} \\ \hline
  12293. \gray{\LtupASTRacket{}} \\ \hline
  12294. \LfunASTRacket \\
  12295. \begin{array}{lcl}
  12296. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12297. \end{array}
  12298. \end{array}
  12299. \]
  12300. \fi}
  12301. {\if\edition\pythonEd
  12302. \[
  12303. \begin{array}{l}
  12304. \gray{\LintASTPython{}} \\ \hline
  12305. \gray{\LvarASTPython{}} \\ \hline
  12306. \gray{\LifASTPython{}} \\ \hline
  12307. \gray{\LwhileASTPython} \\ \hline
  12308. \gray{\LtupASTPython} \\ \hline
  12309. \LfunASTPython \\
  12310. \begin{array}{rcl}
  12311. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12312. \end{array}
  12313. \end{array}
  12314. \]
  12315. \fi}
  12316. \end{tcolorbox}
  12317. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12318. \label{fig:Lfun-syntax}
  12319. \end{figure}
  12320. The program in Figure~\ref{fig:Lfun-function-example} is a
  12321. representative example of defining and using functions in \LangFun{}.
  12322. We define a function \code{map} that applies some other function
  12323. \code{f} to both elements of a tuple and returns a new tuple
  12324. containing the results. We also define a function \code{inc}. The
  12325. program applies \code{map} to \code{inc} and
  12326. %
  12327. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12328. %
  12329. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12330. %
  12331. from which we return \code{42}.
  12332. \begin{figure}[tbp]
  12333. \begin{tcolorbox}[colback=white]
  12334. {\if\edition\racketEd
  12335. \begin{lstlisting}
  12336. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12337. : (Vector Integer Integer)
  12338. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12339. (define (inc [x : Integer]) : Integer
  12340. (+ x 1))
  12341. (vector-ref (map inc (vector 0 41)) 1)
  12342. \end{lstlisting}
  12343. \fi}
  12344. {\if\edition\pythonEd
  12345. \begin{lstlisting}
  12346. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12347. return f(v[0]), f(v[1])
  12348. def inc(x : int) -> int:
  12349. return x + 1
  12350. print( map(inc, (0, 41))[1] )
  12351. \end{lstlisting}
  12352. \fi}
  12353. \end{tcolorbox}
  12354. \caption{Example of using functions in \LangFun{}.}
  12355. \label{fig:Lfun-function-example}
  12356. \end{figure}
  12357. The definitional interpreter for \LangFun{} is in
  12358. Figure~\ref{fig:interp-Lfun}. The case for the
  12359. %
  12360. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12361. %
  12362. AST is responsible for setting up the mutual recursion between the
  12363. top-level function definitions.
  12364. %
  12365. \racket{We use the classic back-patching
  12366. \index{subject}{back-patching} approach that uses mutable variables
  12367. and makes two passes over the function
  12368. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12369. top-level environment using a mutable cons cell for each function
  12370. definition. Note that the \code{lambda} value for each function is
  12371. incomplete; it does not yet include the environment. Once the
  12372. top-level environment is constructed, we then iterate over it and
  12373. update the \code{lambda} values to use the top-level environment.}
  12374. %
  12375. \python{We create a dictionary named \code{env} and fill it in
  12376. by mapping each function name to a new \code{Function} value,
  12377. each of which stores a reference to the \code{env}.
  12378. (We define the class \code{Function} for this purpose.)}
  12379. %
  12380. To interpret a function \racket{application}\python{call}, we match
  12381. the result of the function expression to obtain a function value. We
  12382. then extend the function's environment with the mapping of parameters to
  12383. argument values. Finally, we interpret the body of the function in
  12384. this extended environment.
  12385. \begin{figure}[tp]
  12386. \begin{tcolorbox}[colback=white]
  12387. {\if\edition\racketEd
  12388. \begin{lstlisting}
  12389. (define interp-Lfun-class
  12390. (class interp-Lvec-class
  12391. (super-new)
  12392. (define/override ((interp-exp env) e)
  12393. (define recur (interp-exp env))
  12394. (match e
  12395. [(Apply fun args)
  12396. (define fun-val (recur fun))
  12397. (define arg-vals (for/list ([e args]) (recur e)))
  12398. (match fun-val
  12399. [`(function (,xs ...) ,body ,fun-env)
  12400. (define params-args (for/list ([x xs] [arg arg-vals])
  12401. (cons x (box arg))))
  12402. (define new-env (append params-args fun-env))
  12403. ((interp-exp new-env) body)]
  12404. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12405. [else ((super interp-exp env) e)]
  12406. ))
  12407. (define/public (interp-def d)
  12408. (match d
  12409. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12410. (cons f (box `(function ,xs ,body ())))]))
  12411. (define/override (interp-program p)
  12412. (match p
  12413. [(ProgramDefsExp info ds body)
  12414. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12415. (for/list ([f (in-dict-values top-level)])
  12416. (set-box! f (match (unbox f)
  12417. [`(function ,xs ,body ())
  12418. `(function ,xs ,body ,top-level)])))
  12419. ((interp-exp top-level) body))]))
  12420. ))
  12421. (define (interp-Lfun p)
  12422. (send (new interp-Lfun-class) interp-program p))
  12423. \end{lstlisting}
  12424. \fi}
  12425. {\if\edition\pythonEd
  12426. \begin{lstlisting}
  12427. class InterpLfun(InterpLtup):
  12428. def apply_fun(self, fun, args, e):
  12429. match fun:
  12430. case Function(name, xs, body, env):
  12431. new_env = env.copy().update(zip(xs, args))
  12432. return self.interp_stmts(body, new_env)
  12433. case _:
  12434. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12435. def interp_exp(self, e, env):
  12436. match e:
  12437. case Call(Name('input_int'), []):
  12438. return super().interp_exp(e, env)
  12439. case Call(func, args):
  12440. f = self.interp_exp(func, env)
  12441. vs = [self.interp_exp(arg, env) for arg in args]
  12442. return self.apply_fun(f, vs, e)
  12443. case _:
  12444. return super().interp_exp(e, env)
  12445. def interp_stmts(self, ss, env):
  12446. if len(ss) == 0:
  12447. return
  12448. match ss[0]:
  12449. case Return(value):
  12450. return self.interp_exp(value, env)
  12451. case FunctionDef(name, params, bod, dl, returns, comment):
  12452. ps = [x for (x,t) in params]
  12453. env[name] = Function(name, ps, bod, env)
  12454. return self.interp_stmts(ss[1:], env)
  12455. case _:
  12456. return super().interp_stmts(ss, env)
  12457. def interp(self, p):
  12458. match p:
  12459. case Module(ss):
  12460. env = {}
  12461. self.interp_stmts(ss, env)
  12462. if 'main' in env.keys():
  12463. self.apply_fun(env['main'], [], None)
  12464. case _:
  12465. raise Exception('interp: unexpected ' + repr(p))
  12466. \end{lstlisting}
  12467. \fi}
  12468. \end{tcolorbox}
  12469. \caption{Interpreter for the \LangFun{} language.}
  12470. \label{fig:interp-Lfun}
  12471. \end{figure}
  12472. %\margincomment{TODO: explain type checker}
  12473. The type checker for \LangFun{} is in
  12474. Figure~\ref{fig:type-check-Lfun}.
  12475. %
  12476. \python{(We omit the code that parses function parameters into the
  12477. simpler abstract syntax.)}
  12478. %
  12479. Similar to the interpreter, the case for the
  12480. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12481. %
  12482. AST is responsible for setting up the mutual recursion between the
  12483. top-level function definitions. We begin by create a mapping
  12484. \code{env} from every function name to its type. We then type check
  12485. the program using this mapping.
  12486. %
  12487. In the case for function \racket{application}\python{call}, we match
  12488. the type of the function expression to a function type and check that
  12489. the types of the argument expressions are equal to the function's
  12490. parameter types. The type of the \racket{application}\python{call} as
  12491. a whole is the return type from the function type.
  12492. \begin{figure}[tp]
  12493. \begin{tcolorbox}[colback=white]
  12494. {\if\edition\racketEd
  12495. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12496. (define type-check-Lfun-class
  12497. (class type-check-Lvec-class
  12498. (super-new)
  12499. (inherit check-type-equal?)
  12500. (define/public (type-check-apply env e es)
  12501. (define-values (e^ ty) ((type-check-exp env) e))
  12502. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12503. ((type-check-exp env) e)))
  12504. (match ty
  12505. [`(,ty^* ... -> ,rt)
  12506. (for ([arg-ty ty*] [param-ty ty^*])
  12507. (check-type-equal? arg-ty param-ty (Apply e es)))
  12508. (values e^ e* rt)]))
  12509. (define/override (type-check-exp env)
  12510. (lambda (e)
  12511. (match e
  12512. [(FunRef f n)
  12513. (values (FunRef f n) (dict-ref env f))]
  12514. [(Apply e es)
  12515. (define-values (e^ es^ rt) (type-check-apply env e es))
  12516. (values (Apply e^ es^) rt)]
  12517. [(Call e es)
  12518. (define-values (e^ es^ rt) (type-check-apply env e es))
  12519. (values (Call e^ es^) rt)]
  12520. [else ((super type-check-exp env) e)])))
  12521. (define/public (type-check-def env)
  12522. (lambda (e)
  12523. (match e
  12524. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12525. (define new-env (append (map cons xs ps) env))
  12526. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12527. (check-type-equal? ty^ rt body)
  12528. (Def f p:t* rt info body^)])))
  12529. (define/public (fun-def-type d)
  12530. (match d
  12531. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12532. (define/override (type-check-program e)
  12533. (match e
  12534. [(ProgramDefsExp info ds body)
  12535. (define env (for/list ([d ds])
  12536. (cons (Def-name d) (fun-def-type d))))
  12537. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12538. (define-values (body^ ty) ((type-check-exp env) body))
  12539. (check-type-equal? ty 'Integer body)
  12540. (ProgramDefsExp info ds^ body^)]))))
  12541. (define (type-check-Lfun p)
  12542. (send (new type-check-Lfun-class) type-check-program p))
  12543. \end{lstlisting}
  12544. \fi}
  12545. {\if\edition\pythonEd
  12546. \begin{lstlisting}
  12547. class TypeCheckLfun(TypeCheckLtup):
  12548. def type_check_exp(self, e, env):
  12549. match e:
  12550. case Call(Name('input_int'), []):
  12551. return super().type_check_exp(e, env)
  12552. case Call(func, args):
  12553. func_t = self.type_check_exp(func, env)
  12554. args_t = [self.type_check_exp(arg, env) for arg in args]
  12555. match func_t:
  12556. case FunctionType(params_t, return_t):
  12557. for (arg_t, param_t) in zip(args_t, params_t):
  12558. check_type_equal(param_t, arg_t, e)
  12559. return return_t
  12560. case _:
  12561. raise Exception('type_check_exp: in call, unexpected ' +
  12562. repr(func_t))
  12563. case _:
  12564. return super().type_check_exp(e, env)
  12565. def type_check_stmts(self, ss, env):
  12566. if len(ss) == 0:
  12567. return
  12568. match ss[0]:
  12569. case FunctionDef(name, params, body, dl, returns, comment):
  12570. new_env = env.copy().update(params)
  12571. rt = self.type_check_stmts(body, new_env)
  12572. check_type_equal(returns, rt, ss[0])
  12573. return self.type_check_stmts(ss[1:], env)
  12574. case Return(value):
  12575. return self.type_check_exp(value, env)
  12576. case _:
  12577. return super().type_check_stmts(ss, env)
  12578. def type_check(self, p):
  12579. match p:
  12580. case Module(body):
  12581. env = {}
  12582. for s in body:
  12583. match s:
  12584. case FunctionDef(name, params, bod, dl, returns, comment):
  12585. if name in env:
  12586. raise Exception('type_check: function ' +
  12587. repr(name) + ' defined twice')
  12588. params_t = [t for (x,t) in params]
  12589. env[name] = FunctionType(params_t, returns)
  12590. self.type_check_stmts(body, env)
  12591. case _:
  12592. raise Exception('type_check: unexpected ' + repr(p))
  12593. \end{lstlisting}
  12594. \fi}
  12595. \end{tcolorbox}
  12596. \caption{Type checker for the \LangFun{} language.}
  12597. \label{fig:type-check-Lfun}
  12598. \end{figure}
  12599. \clearpage
  12600. \section{Functions in x86}
  12601. \label{sec:fun-x86}
  12602. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12603. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12604. %% \margincomment{\tiny Talk about the return address on the
  12605. %% stack and what callq and retq does.\\ --Jeremy }
  12606. The x86 architecture provides a few features to support the
  12607. implementation of functions. We have already seen that there are
  12608. labels in x86 so that one can refer to the location of an instruction,
  12609. as is needed for jump instructions. Labels can also be used to mark
  12610. the beginning of the instructions for a function. Going further, we
  12611. can obtain the address of a label by using the \key{leaq}
  12612. instruction. For example, the following puts the address of the
  12613. \code{inc} label into the \code{rbx} register.
  12614. \begin{lstlisting}
  12615. leaq inc(%rip), %rbx
  12616. \end{lstlisting}
  12617. Recall from Section~\ref{sec:select-instructions-gc} that
  12618. \verb!inc(%rip)! is an example of instruction-pointer relative
  12619. addressing. It computes the address of \code{inc}.
  12620. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12621. to functions whose locations were given by a label, such as
  12622. \code{read\_int}. To support function calls in this chapter we instead
  12623. will be jumping to functions whose location are given by an address in
  12624. a register, that is, we shall use \emph{indirect function calls}. The
  12625. x86 syntax for this is a \code{callq} instruction but with an asterisk
  12626. before the register name.\index{subject}{indirect function call}
  12627. \begin{lstlisting}
  12628. callq *%rbx
  12629. \end{lstlisting}
  12630. \subsection{Calling Conventions}
  12631. \label{sec:calling-conventions-fun}
  12632. \index{subject}{calling conventions}
  12633. The \code{callq} instruction provides partial support for implementing
  12634. functions: it pushes the return address on the stack and it jumps to
  12635. the target. However, \code{callq} does not handle
  12636. \begin{enumerate}
  12637. \item parameter passing,
  12638. \item pushing frames on the procedure call stack and popping them off,
  12639. or
  12640. \item determining how registers are shared by different functions.
  12641. \end{enumerate}
  12642. Regarding (1) parameter passing, recall that the x86-64 calling
  12643. convention for Unix-based system uses the following six registers to
  12644. pass arguments to a function, in this order.
  12645. \begin{lstlisting}
  12646. rdi rsi rdx rcx r8 r9
  12647. \end{lstlisting}
  12648. If there are more than six arguments, then the calling convention
  12649. mandates to use space on the frame of the caller for the rest of the
  12650. arguments. However, to ease the implementation of efficient tail calls
  12651. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12652. arguments.
  12653. %
  12654. The return value of the function is stored in register \code{rax}.
  12655. \index{subject}{prelude}\index{subject}{conclusion}
  12656. Regarding (2) frames \index{subject}{frame} and the procedure call
  12657. stack, \index{subject}{procedure call stack} recall from
  12658. Section~\ref{sec:x86} that the stack grows down and each function call
  12659. uses a chunk of space on the stack called a frame. The caller sets the
  12660. stack pointer, register \code{rsp}, to the last data item in its
  12661. frame. The callee must not change anything in the caller's frame, that
  12662. is, anything that is at or above the stack pointer. The callee is free
  12663. to use locations that are below the stack pointer.
  12664. Recall that we store variables of tuple type on the root stack. So
  12665. the prelude of a function needs to move the root stack pointer
  12666. \code{r15} up according to the number of variables of tuple type and
  12667. the conclusion needs to move the root stack pointer back down. Also,
  12668. the prelude must initialize to \code{0} this frame's slots in the root
  12669. stack to signal to the garbage collector that those slots do not yet
  12670. contain a valid pointer. Otherwise the garbage collector will
  12671. interpret the garbage bits in those slots as memory addresses and try
  12672. to traverse them, causing serious mayhem!
  12673. Regarding (3) the sharing of registers between different functions,
  12674. recall from Section~\ref{sec:calling-conventions} that the registers
  12675. are divided into two groups, the caller-saved registers and the
  12676. callee-saved registers. The caller should assume that all the
  12677. caller-saved registers get overwritten with arbitrary values by the
  12678. callee. For that reason we recommend in
  12679. Section~\ref{sec:calling-conventions} that variables that are live
  12680. during a function call should not be assigned to caller-saved
  12681. registers.
  12682. On the flip side, if the callee wants to use a callee-saved register,
  12683. the callee must save the contents of those registers on their stack
  12684. frame and then put them back prior to returning to the caller. For
  12685. that reason we recommend in Section~\ref{sec:calling-conventions} that if
  12686. the register allocator assigns a variable to a callee-saved register,
  12687. then the prelude of the \code{main} function must save that register
  12688. to the stack and the conclusion of \code{main} must restore it. This
  12689. recommendation now generalizes to all functions.
  12690. Recall that the base pointer, register \code{rbp}, is used as a
  12691. point-of-reference within a frame, so that each local variable can be
  12692. accessed at a fixed offset from the base pointer
  12693. (Section~\ref{sec:x86}).
  12694. %
  12695. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12696. and callee frames.
  12697. \begin{figure}[tbp]
  12698. \centering
  12699. \begin{tcolorbox}[colback=white]
  12700. \begin{tabular}{r|r|l|l} \hline
  12701. Caller View & Callee View & Contents & Frame \\ \hline
  12702. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12703. 0(\key{\%rbp}) & & old \key{rbp} \\
  12704. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12705. \ldots & & \ldots \\
  12706. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12707. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12708. \ldots & & \ldots \\
  12709. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12710. %% & & \\
  12711. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12712. %% & \ldots & \ldots \\
  12713. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12714. \hline
  12715. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12716. & 0(\key{\%rbp}) & old \key{rbp} \\
  12717. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12718. & \ldots & \ldots \\
  12719. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12720. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12721. & \ldots & \ldots \\
  12722. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12723. \end{tabular}
  12724. \end{tcolorbox}
  12725. \caption{Memory layout of caller and callee frames.}
  12726. \label{fig:call-frames}
  12727. \end{figure}
  12728. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12729. %% local variables and for storing the values of callee-saved registers
  12730. %% (we shall refer to all of these collectively as ``locals''), and that
  12731. %% at the beginning of a function we move the stack pointer \code{rsp}
  12732. %% down to make room for them.
  12733. %% We recommend storing the local variables
  12734. %% first and then the callee-saved registers, so that the local variables
  12735. %% can be accessed using \code{rbp} the same as before the addition of
  12736. %% functions.
  12737. %% To make additional room for passing arguments, we shall
  12738. %% move the stack pointer even further down. We count how many stack
  12739. %% arguments are needed for each function call that occurs inside the
  12740. %% body of the function and find their maximum. Adding this number to the
  12741. %% number of locals gives us how much the \code{rsp} should be moved at
  12742. %% the beginning of the function. In preparation for a function call, we
  12743. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12744. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12745. %% so on.
  12746. %% Upon calling the function, the stack arguments are retrieved by the
  12747. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12748. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12749. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12750. %% the layout of the caller and callee frames. Notice how important it is
  12751. %% that we correctly compute the maximum number of arguments needed for
  12752. %% function calls; if that number is too small then the arguments and
  12753. %% local variables will smash into each other!
  12754. \subsection{Efficient Tail Calls}
  12755. \label{sec:tail-call}
  12756. In general, the amount of stack space used by a program is determined
  12757. by the longest chain of nested function calls. That is, if function
  12758. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  12759. amount of stack space is linear in $n$. The depth $n$ can grow quite
  12760. large if functions are recursive. However, in some cases we can
  12761. arrange to use only a constant amount of space for a long chain of
  12762. nested function calls.
  12763. A \emph{tail call}\index{subject}{tail call} is a function call that
  12764. happens as the last action in a function body.
  12765. For example, in the following
  12766. program, the recursive call to \code{tail\_sum} is a tail call.
  12767. \begin{center}
  12768. {\if\edition\racketEd
  12769. \begin{lstlisting}
  12770. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12771. (if (eq? n 0)
  12772. r
  12773. (tail_sum (- n 1) (+ n r))))
  12774. (+ (tail_sum 3 0) 36)
  12775. \end{lstlisting}
  12776. \fi}
  12777. {\if\edition\pythonEd
  12778. \begin{lstlisting}
  12779. def tail_sum(n : int, r : int) -> int:
  12780. if n == 0:
  12781. return r
  12782. else:
  12783. return tail_sum(n - 1, n + r)
  12784. print( tail_sum(3, 0) + 36)
  12785. \end{lstlisting}
  12786. \fi}
  12787. \end{center}
  12788. At a tail call, the frame of the caller is no longer needed, so we can
  12789. pop the caller's frame before making the tail call. With this
  12790. approach, a recursive function that only makes tail calls ends up
  12791. using a constant amount of stack space. Functional languages like
  12792. Racket rely heavily on recursive functions, so the definition of
  12793. Racket \emph{requires} that all tail calls be optimized in this way.
  12794. \index{subject}{frame}
  12795. Some care is needed with regards to argument passing in tail calls.
  12796. As mentioned above, for arguments beyond the sixth, the convention is
  12797. to use space in the caller's frame for passing arguments. But for a
  12798. tail call we pop the caller's frame and can no longer use it. An
  12799. alternative is to use space in the callee's frame for passing
  12800. arguments. However, this option is also problematic because the caller
  12801. and callee's frames overlap in memory. As we begin to copy the
  12802. arguments from their sources in the caller's frame, the target
  12803. locations in the callee's frame might collide with the sources for
  12804. later arguments! We solve this problem by using the heap instead of
  12805. the stack for passing more than six arguments
  12806. (Section~\ref{sec:limit-functions-r4}).
  12807. As mentioned above, for a tail call we pop the caller's frame prior to
  12808. making the tail call. The instructions for popping a frame are the
  12809. instructions that we usually place in the conclusion of a
  12810. function. Thus, we also need to place such code immediately before
  12811. each tail call. These instructions include restoring the callee-saved
  12812. registers, so it is fortunate that the argument passing registers are
  12813. all caller-saved registers!
  12814. One last note regarding which instruction to use to make the tail
  12815. call. When the callee is finished, it should not return to the current
  12816. function, but it should return to the function that called the current
  12817. one. Thus, the return address that is already on the stack is the
  12818. right one and we should not use \key{callq} to make the tail call, as
  12819. that would overwrite the return address. Instead we simply use the
  12820. \key{jmp} instruction. Like the indirect function call, we write an
  12821. \emph{indirect jump}\index{subject}{indirect jump} with a register
  12822. prefixed with an asterisk. We recommend using \code{rax} to hold the
  12823. jump target because the conclusion can overwrite just about everything
  12824. else.
  12825. \begin{lstlisting}
  12826. jmp *%rax
  12827. \end{lstlisting}
  12828. \section{Shrink \LangFun{}}
  12829. \label{sec:shrink-r4}
  12830. The \code{shrink} pass performs a minor modification to ease the
  12831. later passes. This pass introduces an explicit \code{main} function
  12832. that gobbles up all the top-level statements of the module.
  12833. %
  12834. \racket{It also changes the top \code{ProgramDefsExp} form to
  12835. \code{ProgramDefs}.}
  12836. {\if\edition\racketEd
  12837. \begin{lstlisting}
  12838. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12839. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12840. \end{lstlisting}
  12841. where $\itm{mainDef}$ is
  12842. \begin{lstlisting}
  12843. (Def 'main '() 'Integer '() |$\Exp'$|)
  12844. \end{lstlisting}
  12845. \fi}
  12846. {\if\edition\pythonEd
  12847. \begin{lstlisting}
  12848. Module(|$\Def\ldots\Stmt\ldots$|)
  12849. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12850. \end{lstlisting}
  12851. where $\itm{mainDef}$ is
  12852. \begin{lstlisting}
  12853. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  12854. \end{lstlisting}
  12855. \fi}
  12856. \section{Reveal Functions and the \LangFunRef{} language}
  12857. \label{sec:reveal-functions-r4}
  12858. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12859. in that it conflates the use of function names and local
  12860. variables. This is a problem because we need to compile the use of a
  12861. function name differently than the use of a local variable. In
  12862. particular, we use \code{leaq} to convert the function name (a label
  12863. in x86) to an address in a register. Thus, we create a new pass that
  12864. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  12865. $n$ is the arity of the function.\python{\footnote{The arity is not
  12866. needed in this chapter but is used in Chapter~\ref{ch:Ldyn}.}}
  12867. This pass is named \code{reveal\_functions} and the output language
  12868. is \LangFunRef{}.
  12869. %is defined in Figure~\ref{fig:f1-syntax}.
  12870. %% The concrete syntax for a
  12871. %% function reference is $\CFUNREF{f}$.
  12872. %% \begin{figure}[tp]
  12873. %% \centering
  12874. %% \fbox{
  12875. %% \begin{minipage}{0.96\textwidth}
  12876. %% {\if\edition\racketEd
  12877. %% \[
  12878. %% \begin{array}{lcl}
  12879. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  12880. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12881. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12882. %% \end{array}
  12883. %% \]
  12884. %% \fi}
  12885. %% {\if\edition\pythonEd
  12886. %% \[
  12887. %% \begin{array}{lcl}
  12888. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  12889. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12890. %% \end{array}
  12891. %% \]
  12892. %% \fi}
  12893. %% \end{minipage}
  12894. %% }
  12895. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12896. %% (Figure~\ref{fig:Lfun-syntax}).}
  12897. %% \label{fig:f1-syntax}
  12898. %% \end{figure}
  12899. %% Distinguishing between calls in tail position and non-tail position
  12900. %% requires the pass to have some notion of context. We recommend using
  12901. %% two mutually recursive functions, one for processing expressions in
  12902. %% tail position and another for the rest.
  12903. \racket{Placing this pass after \code{uniquify} will make sure that
  12904. there are no local variables and functions that share the same
  12905. name.}
  12906. %
  12907. The \code{reveal\_functions} pass should come before the
  12908. \code{remove\_complex\_operands} pass because function references
  12909. should be categorized as complex expressions.
  12910. \section{Limit Functions}
  12911. \label{sec:limit-functions-r4}
  12912. Recall that we wish to limit the number of function parameters to six
  12913. so that we do not need to use the stack for argument passing, which
  12914. makes it easier to implement efficient tail calls. However, because
  12915. the input language \LangFun{} supports arbitrary numbers of function
  12916. arguments, we have some work to do!
  12917. This pass transforms functions and function calls that involve more
  12918. than six arguments to pass the first five arguments as usual, but it
  12919. packs the rest of the arguments into a tuple and passes it as the
  12920. sixth argument.
  12921. Each function definition with seven or more parameters is transformed as
  12922. follows.
  12923. {\if\edition\racketEd
  12924. \begin{lstlisting}
  12925. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12926. |$\Rightarrow$|
  12927. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12928. \end{lstlisting}
  12929. \fi}
  12930. {\if\edition\pythonEd
  12931. \begin{lstlisting}
  12932. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  12933. |$\Rightarrow$|
  12934. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  12935. |$T_r$|, None, |$\itm{body}'$|, None)
  12936. \end{lstlisting}
  12937. \fi}
  12938. %
  12939. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12940. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12941. the $k$th element of the tuple, where $k = i - 6$.
  12942. %
  12943. {\if\edition\racketEd
  12944. \begin{lstlisting}
  12945. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12946. \end{lstlisting}
  12947. \fi}
  12948. {\if\edition\pythonEd
  12949. \begin{lstlisting}
  12950. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  12951. \end{lstlisting}
  12952. \fi}
  12953. For function calls with too many arguments, the \code{limit\_functions}
  12954. pass transforms them in the following way.
  12955. \begin{tabular}{lll}
  12956. \begin{minipage}{0.3\textwidth}
  12957. {\if\edition\racketEd
  12958. \begin{lstlisting}
  12959. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12960. \end{lstlisting}
  12961. \fi}
  12962. {\if\edition\pythonEd
  12963. \begin{lstlisting}
  12964. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12965. \end{lstlisting}
  12966. \fi}
  12967. \end{minipage}
  12968. &
  12969. $\Rightarrow$
  12970. &
  12971. \begin{minipage}{0.5\textwidth}
  12972. {\if\edition\racketEd
  12973. \begin{lstlisting}
  12974. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12975. \end{lstlisting}
  12976. \fi}
  12977. {\if\edition\pythonEd
  12978. \begin{lstlisting}
  12979. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12980. \end{lstlisting}
  12981. \fi}
  12982. \end{minipage}
  12983. \end{tabular}
  12984. \section{Remove Complex Operands}
  12985. \label{sec:rco-r4}
  12986. The primary decisions to make for this pass are whether to classify
  12987. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12988. atomic or complex expressions. Recall that an atomic expression will
  12989. end up as an immediate argument of an x86 instruction. Function
  12990. application will be translated to a sequence of instructions, so
  12991. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  12992. complex expression. On the other hand, the arguments of
  12993. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  12994. expressions.
  12995. %
  12996. Regarding \code{FunRef}, as discussed above, the function label needs
  12997. to be converted to an address using the \code{leaq} instruction. Thus,
  12998. even though \code{FunRef} seems rather simple, it needs to be
  12999. classified as a complex expression so that we generate an assignment
  13000. statement with a left-hand side that can serve as the target of the
  13001. \code{leaq}.
  13002. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  13003. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  13004. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  13005. %
  13006. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  13007. % TODO: Return?
  13008. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  13009. %% \LangFunANF{} of this pass.
  13010. %% \begin{figure}[tp]
  13011. %% \centering
  13012. %% \fbox{
  13013. %% \begin{minipage}{0.96\textwidth}
  13014. %% \small
  13015. %% \[
  13016. %% \begin{array}{rcl}
  13017. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  13018. %% \MID \VOID{} } \\
  13019. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  13020. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  13021. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  13022. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  13023. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  13024. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  13025. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  13026. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13027. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13028. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  13029. %% \end{array}
  13030. %% \]
  13031. %% \end{minipage}
  13032. %% }
  13033. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  13034. %% \label{fig:Lfun-anf-syntax}
  13035. %% \end{figure}
  13036. \section{Explicate Control and the \LangCFun{} language}
  13037. \label{sec:explicate-control-r4}
  13038. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  13039. output of \code{explicate\_control}.
  13040. %
  13041. %% \racket{(The concrete syntax is given in
  13042. %% Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  13043. %
  13044. The auxiliary functions for assignment\racket{ and tail contexts} should
  13045. be updated with cases for
  13046. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  13047. function for predicate context should be updated for
  13048. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  13049. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  13050. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  13051. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  13052. auxiliary function for processing function definitions. This code is
  13053. similar to the case for \code{Program} in \LangVec{}. The top-level
  13054. \code{explicate\_control} function that handles the \code{ProgramDefs}
  13055. form of \LangFun{} can then apply this new function to all the
  13056. function definitions.
  13057. {\if\edition\pythonEd
  13058. The translation of \code{Return} statements requires a new auxiliary
  13059. function to handle expressions in tail context, called
  13060. \code{explicate\_tail}. The function should take an expression and the
  13061. dictionary of basic blocks and produce a list of statements in the
  13062. \LangCFun{} language. The \code{explicate\_tail} function should
  13063. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  13064. and a default case for other kinds of expressions. The default case
  13065. should produce a \code{Return} statement. The case for \code{Call}
  13066. should change it into \code{TailCall}. The other cases should
  13067. recursively process their subexpressions and statements, choosing the
  13068. appropriate explicate functions for the various contexts.
  13069. \fi}
  13070. \newcommand{\CfunASTRacket}{
  13071. \begin{array}{lcl}
  13072. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  13073. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  13074. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  13075. \end{array}
  13076. }
  13077. \newcommand{\CfunASTPython}{
  13078. \begin{array}{lcl}
  13079. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  13080. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  13081. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  13082. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  13083. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  13084. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  13085. \end{array}
  13086. }
  13087. \begin{figure}[tp]
  13088. \begin{tcolorbox}[colback=white]
  13089. \small
  13090. {\if\edition\racketEd
  13091. \[
  13092. \begin{array}{l}
  13093. \gray{\CvarASTRacket} \\ \hline
  13094. \gray{\CifASTRacket} \\ \hline
  13095. \gray{\CloopASTRacket} \\ \hline
  13096. \gray{\CtupASTRacket} \\ \hline
  13097. \CfunASTRacket \\
  13098. \begin{array}{lcl}
  13099. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13100. \end{array}
  13101. \end{array}
  13102. \]
  13103. \fi}
  13104. {\if\edition\pythonEd
  13105. \[
  13106. \begin{array}{l}
  13107. \gray{\CifASTPython} \\ \hline
  13108. \gray{\CtupASTPython} \\ \hline
  13109. \CfunASTPython \\
  13110. \begin{array}{lcl}
  13111. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13112. \end{array}
  13113. \end{array}
  13114. \]
  13115. \fi}
  13116. \end{tcolorbox}
  13117. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  13118. \label{fig:c3-syntax}
  13119. \end{figure}
  13120. \clearpage
  13121. \section{Select Instructions and the \LangXIndCall{} Language}
  13122. \label{sec:select-r4}
  13123. \index{subject}{instruction selection}
  13124. The output of select instructions is a program in the \LangXIndCall{}
  13125. language, whose concrete syntax is defined in
  13126. Figure~\ref{fig:x86-3-concrete} and abstract syntax is defined in
  13127. Figure~\ref{fig:x86-3}. We use the \code{align} directive on the
  13128. labels of function definitions to make sure the bottom three bits are
  13129. zero, which we make use of in Chapter~\ref{ch:Ldyn}. We discuss the
  13130. new instructions as needed in this section. \index{subject}{x86}
  13131. \newcommand{\GrammarXIndCall}{
  13132. \begin{array}{lcl}
  13133. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13134. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13135. \Block &::= & \Instr^{+} \\
  13136. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  13137. \end{array}
  13138. }
  13139. \newcommand{\ASTXIndCallRacket}{
  13140. \begin{array}{lcl}
  13141. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  13142. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13143. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13144. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13145. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  13146. \end{array}
  13147. }
  13148. \begin{figure}[tp]
  13149. \begin{tcolorbox}[colback=white]
  13150. \small
  13151. \[
  13152. \begin{array}{l}
  13153. \gray{\GrammarXInt} \\ \hline
  13154. \gray{\GrammarXIf} \\ \hline
  13155. \gray{\GrammarXGlobal} \\ \hline
  13156. \GrammarXIndCall \\
  13157. \begin{array}{lcl}
  13158. \LangXIndCallM{} &::= & \Def^{*}
  13159. \end{array}
  13160. \end{array}
  13161. \]
  13162. \end{tcolorbox}
  13163. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  13164. \label{fig:x86-3-concrete}
  13165. \end{figure}
  13166. \begin{figure}[tp]
  13167. \begin{tcolorbox}[colback=white]
  13168. \small
  13169. {\if\edition\racketEd
  13170. \[\arraycolsep=3pt
  13171. \begin{array}{l}
  13172. \gray{\ASTXIntRacket} \\ \hline
  13173. \gray{\ASTXIfRacket} \\ \hline
  13174. \gray{\ASTXGlobalRacket} \\ \hline
  13175. \ASTXIndCallRacket \\
  13176. \begin{array}{lcl}
  13177. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13178. \end{array}
  13179. \end{array}
  13180. \]
  13181. \fi}
  13182. {\if\edition\pythonEd
  13183. \[
  13184. \begin{array}{lcl}
  13185. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13186. \MID \BYTEREG{\Reg} } \\
  13187. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  13188. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13189. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13190. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13191. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13192. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13193. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13194. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13195. \end{array}
  13196. \]
  13197. \fi}
  13198. \end{tcolorbox}
  13199. \caption{The abstract syntax of \LangXIndCall{} (extends
  13200. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  13201. \label{fig:x86-3}
  13202. \end{figure}
  13203. An assignment of a function reference to a variable becomes a
  13204. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  13205. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  13206. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  13207. node, whose concrete syntax is instruction-pointer relative
  13208. addressing.
  13209. \begin{center}
  13210. \begin{tabular}{lcl}
  13211. \begin{minipage}{0.35\textwidth}
  13212. {\if\edition\racketEd
  13213. \begin{lstlisting}
  13214. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13215. \end{lstlisting}
  13216. \fi}
  13217. {\if\edition\pythonEd
  13218. \begin{lstlisting}
  13219. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  13220. \end{lstlisting}
  13221. \fi}
  13222. \end{minipage}
  13223. &
  13224. $\Rightarrow$\qquad\qquad
  13225. &
  13226. \begin{minipage}{0.3\textwidth}
  13227. \begin{lstlisting}
  13228. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13229. \end{lstlisting}
  13230. \end{minipage}
  13231. \end{tabular}
  13232. \end{center}
  13233. Regarding function definitions, we need to remove the parameters and
  13234. instead perform parameter passing using the conventions discussed in
  13235. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13236. registers. We recommend turning the parameters into local variables
  13237. and generating instructions at the beginning of the function to move
  13238. from the argument passing registers
  13239. (Section~\ref{sec:calling-conventions-fun}) to these local variables.
  13240. {\if\edition\racketEd
  13241. \begin{lstlisting}
  13242. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13243. |$\Rightarrow$|
  13244. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13245. \end{lstlisting}
  13246. \fi}
  13247. {\if\edition\pythonEd
  13248. \begin{lstlisting}
  13249. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13250. |$\Rightarrow$|
  13251. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13252. \end{lstlisting}
  13253. \fi}
  13254. The basic blocks $B'$ are the same as $B$ except that the
  13255. \code{start} block is modified to add the instructions for moving from
  13256. the argument registers to the parameter variables. So the \code{start}
  13257. block of $B$ shown on the left is changed to the code on the right.
  13258. \begin{center}
  13259. \begin{minipage}{0.3\textwidth}
  13260. \begin{lstlisting}
  13261. start:
  13262. |$\itm{instr}_1$|
  13263. |$\cdots$|
  13264. |$\itm{instr}_n$|
  13265. \end{lstlisting}
  13266. \end{minipage}
  13267. $\Rightarrow$
  13268. \begin{minipage}{0.3\textwidth}
  13269. \begin{lstlisting}
  13270. start:
  13271. movq %rdi, |$x_1$|
  13272. movq %rsi, |$x_2$|
  13273. |$\cdots$|
  13274. |$\itm{instr}_1$|
  13275. |$\cdots$|
  13276. |$\itm{instr}_n$|
  13277. \end{lstlisting}
  13278. \end{minipage}
  13279. \end{center}
  13280. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13281. parameters the function expects, but the parameters are no longer in
  13282. the syntax of function definitions. Instead, add an entry to
  13283. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13284. to construct $\itm{info}'$.}
  13285. By changing the parameters to local variables, we are giving the
  13286. register allocator control over which registers or stack locations to
  13287. use for them. If you implemented the move-biasing challenge
  13288. (Section~\ref{sec:move-biasing}), the register allocator will try to
  13289. assign the parameter variables to the corresponding argument register,
  13290. in which case the \code{patch\_instructions} pass will remove the
  13291. \code{movq} instruction. This happens in the example translation in
  13292. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  13293. the \code{add} function.
  13294. %
  13295. Also, note that the register allocator will perform liveness analysis
  13296. on this sequence of move instructions and build the interference
  13297. graph. So, for example, $x_1$ will be marked as interfering with
  13298. \code{rsi} and that will prevent the assignment of $x_1$ to
  13299. \code{rsi}, which is good, because that would overwrite the argument
  13300. that needs to move into $x_2$.
  13301. Next, consider the compilation of function calls. In the mirror image
  13302. of the handling of parameters in function definitions, the arguments
  13303. are moved to the argument passing registers. Note that the function
  13304. is not given as a label, but its address is produced by the argument
  13305. $\itm{arg}_0$. So we translate the call into an indirect function
  13306. call. The return value from the function is stored in \code{rax}, so
  13307. it needs to be moved into the \itm{lhs}.
  13308. \begin{lstlisting}
  13309. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  13310. |$\Rightarrow$|
  13311. movq |$\itm{arg}_1$|, %rdi
  13312. movq |$\itm{arg}_2$|, %rsi
  13313. |$\vdots$|
  13314. callq *|$\itm{arg}_0$|
  13315. movq %rax, |$\itm{lhs}$|
  13316. \end{lstlisting}
  13317. The \code{IndirectCallq} AST node includes an integer for the arity of
  13318. the function, i.e., the number of parameters. That information is
  13319. useful in the \code{uncover\_live} pass for determining which
  13320. argument-passing registers are potentially read during the call.
  13321. For tail calls, the parameter passing is the same as non-tail calls:
  13322. generate instructions to move the arguments into the argument
  13323. passing registers. After that we need to pop the frame from the
  13324. procedure call stack. However, we do not yet know how big the frame
  13325. is; that gets determined during register allocation. So instead of
  13326. generating those instructions here, we invent a new instruction that
  13327. means ``pop the frame and then do an indirect jump'', which we name
  13328. \code{TailJmp}. The abstract syntax for this instruction includes an
  13329. argument that specifies where to jump and an integer that represents
  13330. the arity of the function being called.
  13331. Recall that we use the label \code{start} for the initial block of a
  13332. program, and in Section~\ref{sec:select-Lvar} we recommend labeling
  13333. the conclusion of the program with \code{conclusion}, so that
  13334. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13335. by a jump to \code{conclusion}. With the addition of function
  13336. definitions, there is a start block and conclusion for each function,
  13337. but their labels need to be unique. We recommend prepending the
  13338. function's name to \code{start} and \code{conclusion}, respectively,
  13339. to obtain unique labels.
  13340. \section{Register Allocation}
  13341. \label{sec:register-allocation-r4}
  13342. The addition of functions requires some changes to all three aspects
  13343. of register allocation, which we discuss in the following subsections.
  13344. \subsection{Liveness Analysis}
  13345. \label{sec:liveness-analysis-r4}
  13346. \index{subject}{liveness analysis}
  13347. %% The rest of the passes need only minor modifications to handle the new
  13348. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13349. %% \code{leaq}.
  13350. The \code{IndirectCallq} instruction should be treated like
  13351. \code{Callq} regarding its written locations $W$, in that they should
  13352. include all the caller-saved registers. Recall that the reason for
  13353. that is to force variables that are live across a function call to be assigned to callee-saved
  13354. registers or to be spilled to the stack.
  13355. Regarding the set of read locations $R$, the arity field of
  13356. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13357. argument-passing registers should be considered as read by those
  13358. instructions. Also, the target field of \code{TailJmp} and
  13359. \code{IndirectCallq} should be included in the set of read locations
  13360. $R$.
  13361. \subsection{Build Interference Graph}
  13362. \label{sec:build-interference-r4}
  13363. With the addition of function definitions, we compute a separate interference
  13364. graph for each function (not just one for the whole program).
  13365. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13366. spill tuple-typed variables that are live during a call to
  13367. \code{collect}, the garbage collector. With the addition of functions
  13368. to our language, we need to revisit this issue. Functions that perform
  13369. allocation contain calls to the collector. Thus, we should not only
  13370. spill a tuple-typed variable when it is live during a call to
  13371. \code{collect}, but we should spill the variable if it is live during
  13372. call to any user-defined function. Thus, in the
  13373. \code{build\_interference} pass, we recommend adding interference
  13374. edges between call-live tuple-typed variables and the callee-saved
  13375. registers (in addition to the usual addition of edges between
  13376. call-live variables and the caller-saved registers).
  13377. \subsection{Allocate Registers}
  13378. The primary change to the \code{allocate\_registers} pass is adding an
  13379. auxiliary function for handling definitions (the \Def{} non-terminal
  13380. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13381. logic is the same as described in
  13382. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13383. allocation is performed many times, once for each function definition,
  13384. instead of just once for the whole program.
  13385. \section{Patch Instructions}
  13386. In \code{patch\_instructions}, you should deal with the x86
  13387. idiosyncrasy that the destination argument of \code{leaq} must be a
  13388. register. Additionally, you should ensure that the argument of
  13389. \code{TailJmp} is \itm{rax}, our reserved register---because we
  13390. trample many other registers before the tail call (as explained in the
  13391. next section).
  13392. \section{Prelude and Conclusion}
  13393. Now that register allocation is complete, we can translate the
  13394. \code{TailJmp} into a sequence of instructions. A naive translation of
  13395. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  13396. before the jump we need to pop the current frame to achieve efficient
  13397. tail calls. This sequence of instructions is the same as the code for
  13398. the conclusion of a function, except the \code{retq} is replaced with
  13399. \code{jmp *$\itm{arg}$}.
  13400. Regarding function definitions, we generate a prelude and conclusion
  13401. for each one. This code is similar to the prelude and conclusion
  13402. generated for the \code{main} function in Chapter~\ref{ch:Lvec}. To
  13403. review, the prelude of every function should carry out the following
  13404. steps.
  13405. % TODO: .align the functions!
  13406. \begin{enumerate}
  13407. %% \item Start with \code{.global} and \code{.align} directives followed
  13408. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13409. %% example.)
  13410. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13411. pointer.
  13412. \item Push to the stack all of the callee-saved registers that were
  13413. used for register allocation.
  13414. \item Move the stack pointer \code{rsp} down to make room for the
  13415. regular spills. (Aligned to 16 bytes.)
  13416. \item Move the root stack pointer \code{r15} up by the size of the
  13417. root-stack frame for this function, which depends on the number of
  13418. spilled tuple-typed variables. \label{root-stack-init}
  13419. \item Initialize to zero all new entries in the root-stack frame.
  13420. \item Jump to the start block.
  13421. \end{enumerate}
  13422. The prelude of the \code{main} function has an additional task: call
  13423. the \code{initialize} function to set up the garbage collector and
  13424. then move the value of the global \code{rootstack\_begin} in
  13425. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13426. above, which depends on \code{r15}.
  13427. The conclusion of every function should do the following.
  13428. \begin{enumerate}
  13429. \item Move the stack pointer back up past the regular spills.
  13430. \item Restore the callee-saved registers by popping them from the
  13431. stack.
  13432. \item Move the root stack pointer back down by the size of the
  13433. root-stack frame for this function.
  13434. \item Restore \code{rbp} by popping it from the stack.
  13435. \item Return to the caller with the \code{retq} instruction.
  13436. \end{enumerate}
  13437. \begin{exercise}\normalfont\normalsize
  13438. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13439. Create 8 new programs that use functions, including examples that pass
  13440. functions and return functions from other functions, recursive
  13441. functions, functions that create vectors, and functions that make tail
  13442. calls. Test your compiler on these new programs and all of your
  13443. previously created test programs.
  13444. \end{exercise}
  13445. \begin{figure}[tbp]
  13446. \begin{tcolorbox}[colback=white]
  13447. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13448. \node (Lfun) at (0,2) {\large \LangFun{}};
  13449. \node (Lfun-1) at (3,2) {\large \LangFun{}};
  13450. \node (Lfun-2) at (6,2) {\large \LangFun{}};
  13451. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13452. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13453. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13454. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13455. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13456. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13457. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13458. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13459. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13460. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13461. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13462. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13463. \path[->,bend left=15] (Lfun) edge [above] node
  13464. {\ttfamily\footnotesize shrink} (Lfun-1);
  13465. \path[->,bend left=15] (Lfun-1) edge [above] node
  13466. {\ttfamily\footnotesize uniquify} (Lfun-2);
  13467. \path[->,bend left=15] (Lfun-2) edge [above] node
  13468. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13469. \path[->,bend left=15] (F1-1) edge [left] node
  13470. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13471. \path[->,bend left=15] (F1-2) edge [below] node
  13472. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13473. \path[->,bend left=15] (F1-3) edge [below] node
  13474. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  13475. \path[->,bend right=15] (F1-4) edge [above] node
  13476. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13477. \path[->,bend right=15] (F1-5) edge [left] node
  13478. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13479. \path[->,bend right=15] (C3-2) edge [left] node
  13480. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13481. \path[->,bend left=15] (x86-2) edge [left] node
  13482. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13483. \path[->,bend right=15] (x86-2-1) edge [below] node
  13484. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13485. \path[->,bend right=15] (x86-2-2) edge [left] node
  13486. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13487. \path[->,bend left=15] (x86-3) edge [above] node
  13488. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13489. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize prelude.} (x86-5);
  13490. \end{tikzpicture}
  13491. \end{tcolorbox}
  13492. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13493. \label{fig:Lfun-passes}
  13494. \end{figure}
  13495. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  13496. compiling \LangFun{} to x86.
  13497. \section{An Example Translation}
  13498. \label{sec:functions-example}
  13499. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13500. function in \LangFun{} to x86. The figure also includes the results of the
  13501. \code{explicate\_control} and \code{select\_instructions} passes.
  13502. \begin{figure}[htbp]
  13503. \begin{tcolorbox}[colback=white]
  13504. \begin{tabular}{ll}
  13505. \begin{minipage}{0.4\textwidth}
  13506. % s3_2.rkt
  13507. {\if\edition\racketEd
  13508. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13509. (define (add [x : Integer]
  13510. [y : Integer])
  13511. : Integer
  13512. (+ x y))
  13513. (add 40 2)
  13514. \end{lstlisting}
  13515. \fi}
  13516. {\if\edition\pythonEd
  13517. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13518. def add(x:int, y:int) -> int:
  13519. return x + y
  13520. print(add(40, 2))
  13521. \end{lstlisting}
  13522. \fi}
  13523. $\Downarrow$
  13524. {\if\edition\racketEd
  13525. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13526. (define (add86 [x87 : Integer]
  13527. [y88 : Integer])
  13528. : Integer
  13529. add86start:
  13530. return (+ x87 y88);
  13531. )
  13532. (define (main) : Integer ()
  13533. mainstart:
  13534. tmp89 = (fun-ref add86 2);
  13535. (tail-call tmp89 40 2)
  13536. )
  13537. \end{lstlisting}
  13538. \fi}
  13539. {\if\edition\pythonEd
  13540. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13541. def add(x:int, y:int) -> int:
  13542. addstart:
  13543. return x + y
  13544. def main() -> int:
  13545. mainstart:
  13546. fun.0 = add
  13547. tmp.1 = fun.0(40, 2)
  13548. print(tmp.1)
  13549. return 0
  13550. \end{lstlisting}
  13551. \fi}
  13552. \end{minipage}
  13553. &
  13554. $\Rightarrow$
  13555. \begin{minipage}{0.5\textwidth}
  13556. {\if\edition\racketEd
  13557. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13558. (define (add86) : Integer
  13559. add86start:
  13560. movq %rdi, x87
  13561. movq %rsi, y88
  13562. movq x87, %rax
  13563. addq y88, %rax
  13564. jmp inc1389conclusion
  13565. )
  13566. (define (main) : Integer
  13567. mainstart:
  13568. leaq (fun-ref add86 2), tmp89
  13569. movq $40, %rdi
  13570. movq $2, %rsi
  13571. tail-jmp tmp89
  13572. )
  13573. \end{lstlisting}
  13574. \fi}
  13575. {\if\edition\pythonEd
  13576. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13577. def add() -> int:
  13578. addstart:
  13579. movq %rdi, x
  13580. movq %rsi, y
  13581. movq x, %rax
  13582. addq y, %rax
  13583. jmp addconclusion
  13584. def main() -> int:
  13585. mainstart:
  13586. leaq add, fun.0
  13587. movq $40, %rdi
  13588. movq $2, %rsi
  13589. callq *fun.0
  13590. movq %rax, tmp.1
  13591. movq tmp.1, %rdi
  13592. callq print_int
  13593. movq $0, %rax
  13594. jmp mainconclusion
  13595. \end{lstlisting}
  13596. \fi}
  13597. $\Downarrow$
  13598. \end{minipage}
  13599. \end{tabular}
  13600. \begin{tabular}{ll}
  13601. \begin{minipage}{0.3\textwidth}
  13602. {\if\edition\racketEd
  13603. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13604. .globl add86
  13605. .align 8
  13606. add86:
  13607. pushq %rbp
  13608. movq %rsp, %rbp
  13609. jmp add86start
  13610. add86start:
  13611. movq %rdi, %rax
  13612. addq %rsi, %rax
  13613. jmp add86conclusion
  13614. add86conclusion:
  13615. popq %rbp
  13616. retq
  13617. \end{lstlisting}
  13618. \fi}
  13619. {\if\edition\pythonEd
  13620. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13621. .align 8
  13622. add:
  13623. pushq %rbp
  13624. movq %rsp, %rbp
  13625. subq $0, %rsp
  13626. jmp addstart
  13627. addstart:
  13628. movq %rdi, %rdx
  13629. movq %rsi, %rcx
  13630. movq %rdx, %rax
  13631. addq %rcx, %rax
  13632. jmp addconclusion
  13633. addconclusion:
  13634. subq $0, %r15
  13635. addq $0, %rsp
  13636. popq %rbp
  13637. retq
  13638. \end{lstlisting}
  13639. \fi}
  13640. \end{minipage}
  13641. &
  13642. \begin{minipage}{0.5\textwidth}
  13643. {\if\edition\racketEd
  13644. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13645. .globl main
  13646. .align 8
  13647. main:
  13648. pushq %rbp
  13649. movq %rsp, %rbp
  13650. movq $16384, %rdi
  13651. movq $16384, %rsi
  13652. callq initialize
  13653. movq rootstack_begin(%rip), %r15
  13654. jmp mainstart
  13655. mainstart:
  13656. leaq add86(%rip), %rcx
  13657. movq $40, %rdi
  13658. movq $2, %rsi
  13659. movq %rcx, %rax
  13660. popq %rbp
  13661. jmp *%rax
  13662. mainconclusion:
  13663. popq %rbp
  13664. retq
  13665. \end{lstlisting}
  13666. \fi}
  13667. {\if\edition\pythonEd
  13668. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13669. .globl main
  13670. .align 8
  13671. main:
  13672. pushq %rbp
  13673. movq %rsp, %rbp
  13674. subq $0, %rsp
  13675. movq $65536, %rdi
  13676. movq $65536, %rsi
  13677. callq initialize
  13678. movq rootstack_begin(%rip), %r15
  13679. jmp mainstart
  13680. mainstart:
  13681. leaq add(%rip), %rcx
  13682. movq $40, %rdi
  13683. movq $2, %rsi
  13684. callq *%rcx
  13685. movq %rax, %rcx
  13686. movq %rcx, %rdi
  13687. callq print_int
  13688. movq $0, %rax
  13689. jmp mainconclusion
  13690. mainconclusion:
  13691. subq $0, %r15
  13692. addq $0, %rsp
  13693. popq %rbp
  13694. retq
  13695. \end{lstlisting}
  13696. \fi}
  13697. \end{minipage}
  13698. \end{tabular}
  13699. \end{tcolorbox}
  13700. \caption{Example compilation of a simple function to x86.}
  13701. \label{fig:add-fun}
  13702. \end{figure}
  13703. % Challenge idea: inlining! (simple version)
  13704. % Further Reading
  13705. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13706. \chapter{Lexically Scoped Functions}
  13707. \label{ch:Llambda}
  13708. \index{subject}{lambda}
  13709. \index{subject}{lexical scoping}
  13710. This chapter studies lexically scoped functions. Lexical scoping means
  13711. that a function's body may refer to variables whose binding site is
  13712. outside of the function, in an enclosing scope.
  13713. %
  13714. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13715. \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  13716. creating lexically scoped functions. The body of the \key{lambda}
  13717. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  13718. binding sites for \code{x} and \code{y} are outside of the
  13719. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  13720. \key{let}}\python{a local variable of function \code{f}} and
  13721. \code{x} is a parameter of function \code{f}. Note that function
  13722. \code{f} returns the \key{lambda} as its result value. The main
  13723. expression of the program includes two calls to \code{f} with
  13724. different arguments for \code{x}, first \code{5} then \code{3}. The
  13725. functions returned from \code{f} are bound to variables \code{g} and
  13726. \code{h}. Even though these two functions were created by the same
  13727. \code{lambda}, they are really different functions because they use
  13728. different values for \code{x}. Applying \code{g} to \code{11} produces
  13729. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  13730. so the result of the program is \code{42}.
  13731. \begin{figure}[btp]
  13732. \begin{tcolorbox}[colback=white]
  13733. {\if\edition\racketEd
  13734. % lambda_test_21.rkt
  13735. \begin{lstlisting}
  13736. (define (f [x : Integer]) : (Integer -> Integer)
  13737. (let ([y 4])
  13738. (lambda: ([z : Integer]) : Integer
  13739. (+ x (+ y z)))))
  13740. (let ([g (f 5)])
  13741. (let ([h (f 3)])
  13742. (+ (g 11) (h 15))))
  13743. \end{lstlisting}
  13744. \fi}
  13745. {\if\edition\pythonEd
  13746. \begin{lstlisting}
  13747. def f(x : int) -> Callable[[int], int]:
  13748. y = 4
  13749. return lambda z: x + y + z
  13750. g = f(5)
  13751. h = f(3)
  13752. print( g(11) + h(15) )
  13753. \end{lstlisting}
  13754. \fi}
  13755. \end{tcolorbox}
  13756. \caption{Example of a lexically scoped function.}
  13757. \label{fig:lexical-scoping}
  13758. \end{figure}
  13759. The approach that we take for implementing lexically scoped functions
  13760. is to compile them into top-level function definitions, translating
  13761. from \LangLam{} into \LangFun{}. However, the compiler must give
  13762. special treatment to variable occurrences such as \code{x} and
  13763. \code{y} in the body of the \code{lambda} of
  13764. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13765. may not refer to variables defined outside of it. To identify such
  13766. variable occurrences, we review the standard notion of free variable.
  13767. \begin{definition}
  13768. A variable is \textbf{free in expression} $e$ if the variable occurs
  13769. inside $e$ but does not have an enclosing definition that is also in
  13770. $e$.\index{subject}{free variable}
  13771. \end{definition}
  13772. For example, in the expression
  13773. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  13774. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13775. only \code{x} and \code{y} are free in the following expression
  13776. because \code{z} is defined by the \code{lambda}.
  13777. {\if\edition\racketEd
  13778. \begin{lstlisting}
  13779. (lambda: ([z : Integer]) : Integer
  13780. (+ x (+ y z)))
  13781. \end{lstlisting}
  13782. \fi}
  13783. {\if\edition\pythonEd
  13784. \begin{lstlisting}
  13785. lambda z: x + y + z
  13786. \end{lstlisting}
  13787. \fi}
  13788. %
  13789. So the free variables of a \code{lambda} are the ones that need
  13790. special treatment. We need to transport, at runtime, the values of
  13791. those variables from the point where the \code{lambda} was created to
  13792. the point where the \code{lambda} is applied. An efficient solution to
  13793. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  13794. of the free variables together with a function pointer into a tuple,
  13795. an arrangement called a \emph{flat closure} (which we shorten to just
  13796. ``closure'').\index{subject}{closure}\index{subject}{flat closure}
  13797. %
  13798. By design, we have all the ingredients to make closures:
  13799. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  13800. function pointers. The function pointer resides at index $0$ and the
  13801. values for the free variables fill in the rest of the tuple.
  13802. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13803. how closures work. It is a three-step dance. The program calls
  13804. function \code{f}, which creates a closure for the \code{lambda}. The
  13805. closure is a tuple whose first element is a pointer to the top-level
  13806. function that we will generate for the \code{lambda}, the second
  13807. element is the value of \code{x}, which is \code{5}, and the third
  13808. element is \code{4}, the value of \code{y}. The closure does not
  13809. contain an element for \code{z} because \code{z} is not a free
  13810. variable of the \code{lambda}. Creating the closure is step 1 of the
  13811. dance. The closure is returned from \code{f} and bound to \code{g}, as
  13812. shown in Figure~\ref{fig:closures}.
  13813. %
  13814. The second call to \code{f} creates another closure, this time with
  13815. \code{3} in the second slot (for \code{x}). This closure is also
  13816. returned from \code{f} but bound to \code{h}, which is also shown in
  13817. Figure~\ref{fig:closures}.
  13818. \begin{figure}[tbp]
  13819. \centering
  13820. \begin{minipage}{0.65\textwidth}
  13821. \begin{tcolorbox}[colback=white]
  13822. \includegraphics[width=\textwidth]{figs/closures}
  13823. \end{tcolorbox}
  13824. \end{minipage}
  13825. \caption{Flat closure representations for the two functions
  13826. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  13827. \label{fig:closures}
  13828. \end{figure}
  13829. Continuing with the example, consider the application of \code{g} to
  13830. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13831. obtain the function pointer from the first element of the closure and
  13832. call it, passing in the closure itself and then the regular arguments,
  13833. in this case \code{11}. This technique for applying a closure is step
  13834. 2 of the dance.
  13835. %
  13836. But doesn't this \code{lambda} only take 1 argument, for parameter
  13837. \code{z}? The third and final step of the dance is generating a
  13838. top-level function for a \code{lambda}. We add an additional
  13839. parameter for the closure and we insert an initialization at the beginning
  13840. of the function for each free variable, to bind those variables to the
  13841. appropriate elements from the closure parameter.
  13842. %
  13843. This three-step dance is known as \emph{closure conversion}. We
  13844. discuss the details of closure conversion in
  13845. Section~\ref{sec:closure-conversion} and show the code generated from
  13846. the example in Section~\ref{sec:example-lambda}. But first we define
  13847. the syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13848. \section{The \LangLam{} Language}
  13849. \label{sec:r5}
  13850. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13851. functions and lexical scoping, is defined in
  13852. Figures~\ref{fig:Llam-concrete-syntax} and \ref{fig:Llam-syntax}. It adds
  13853. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13854. syntax for function application.
  13855. %
  13856. \python{The syntax also includes an assignment statement that includes
  13857. a type annotation for the variable on the left-hand side, which
  13858. facilitates the type checking of \code{lambda} expressions that we
  13859. discuss later in this section.}
  13860. %
  13861. \racket{The \code{procedure-arity} operation returns the number of parameters
  13862. of a given function, an operation that we need for the translation
  13863. of dynamic typing in Chapter~\ref{ch:Ldyn}.}
  13864. %
  13865. \python{The \code{arity} operation returns the number of parameters of
  13866. a given function, an operation that we need for the translation
  13867. of dynamic typing in Chapter~\ref{ch:Ldyn}.
  13868. The \code{arity} operation is not in Python, but the same functionality
  13869. is available in a more complex form. We include \code{arity} in the
  13870. \LangLam{} source language to enable testing.}
  13871. \newcommand{\LlambdaGrammarRacket}{
  13872. \begin{array}{lcl}
  13873. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  13874. &\MID& \LP \key{procedure-arity}~\Exp\RP
  13875. \end{array}
  13876. }
  13877. \newcommand{\LlambdaASTRacket}{
  13878. \begin{array}{lcl}
  13879. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  13880. \itm{op} &::=& \code{procedure-arity}
  13881. \end{array}
  13882. }
  13883. \newcommand{\LlambdaGrammarPython}{
  13884. \begin{array}{lcl}
  13885. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  13886. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  13887. \end{array}
  13888. }
  13889. \newcommand{\LlambdaASTPython}{
  13890. \begin{array}{lcl}
  13891. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  13892. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  13893. \end{array}
  13894. }
  13895. % include AnnAssign in ASTPython
  13896. \begin{figure}[tp]
  13897. \centering
  13898. \begin{tcolorbox}[colback=white]
  13899. \small
  13900. {\if\edition\racketEd
  13901. \[
  13902. \begin{array}{l}
  13903. \gray{\LintGrammarRacket{}} \\ \hline
  13904. \gray{\LvarGrammarRacket{}} \\ \hline
  13905. \gray{\LifGrammarRacket{}} \\ \hline
  13906. \gray{\LwhileGrammarRacket} \\ \hline
  13907. \gray{\LtupGrammarRacket} \\ \hline
  13908. \gray{\LfunGrammarRacket} \\ \hline
  13909. \LlambdaGrammarRacket \\
  13910. \begin{array}{lcl}
  13911. \LangLamM{} &::=& \Def\ldots \; \Exp
  13912. \end{array}
  13913. \end{array}
  13914. \]
  13915. \fi}
  13916. {\if\edition\pythonEd
  13917. \[
  13918. \begin{array}{l}
  13919. \gray{\LintGrammarPython{}} \\ \hline
  13920. \gray{\LvarGrammarPython{}} \\ \hline
  13921. \gray{\LifGrammarPython{}} \\ \hline
  13922. \gray{\LwhileGrammarPython} \\ \hline
  13923. \gray{\LtupGrammarPython} \\ \hline
  13924. \gray{\LfunGrammarPython} \\ \hline
  13925. \LlambdaGrammarPython \\
  13926. \begin{array}{lcl}
  13927. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13928. \end{array}
  13929. \end{array}
  13930. \]
  13931. \fi}
  13932. \end{tcolorbox}
  13933. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Lfun-concrete-syntax})
  13934. with \key{lambda}.}
  13935. \label{fig:Llam-concrete-syntax}
  13936. \end{figure}
  13937. \begin{figure}[tp]
  13938. \centering
  13939. \begin{tcolorbox}[colback=white]
  13940. \small
  13941. {\if\edition\racketEd
  13942. \[\arraycolsep=3pt
  13943. \begin{array}{l}
  13944. \gray{\LintOpAST} \\ \hline
  13945. \gray{\LvarASTRacket{}} \\ \hline
  13946. \gray{\LifASTRacket{}} \\ \hline
  13947. \gray{\LwhileASTRacket{}} \\ \hline
  13948. \gray{\LtupASTRacket{}} \\ \hline
  13949. \gray{\LfunASTRacket} \\ \hline
  13950. \LlambdaASTRacket \\
  13951. \begin{array}{lcl}
  13952. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13953. \end{array}
  13954. \end{array}
  13955. \]
  13956. \fi}
  13957. {\if\edition\pythonEd
  13958. \[
  13959. \begin{array}{l}
  13960. \gray{\LintASTPython} \\ \hline
  13961. \gray{\LvarASTPython{}} \\ \hline
  13962. \gray{\LifASTPython{}} \\ \hline
  13963. \gray{\LwhileASTPython{}} \\ \hline
  13964. \gray{\LtupASTPython{}} \\ \hline
  13965. \gray{\LfunASTPython} \\ \hline
  13966. \LlambdaASTPython \\
  13967. \begin{array}{lcl}
  13968. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13969. \end{array}
  13970. \end{array}
  13971. \]
  13972. \fi}
  13973. \end{tcolorbox}
  13974. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Lfun-syntax}).}
  13975. \label{fig:Llam-syntax}
  13976. \end{figure}
  13977. \index{subject}{interpreter}
  13978. \label{sec:interp-Llambda}
  13979. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  13980. \LangLam{}. The case for \key{Lambda} saves the current environment
  13981. inside the returned function value. Recall that during function
  13982. application, the environment stored in the function value, extended
  13983. with the mapping of parameters to argument values, is used to
  13984. interpret the body of the function.
  13985. \begin{figure}[tbp]
  13986. \begin{tcolorbox}[colback=white]
  13987. {\if\edition\racketEd
  13988. \begin{lstlisting}
  13989. (define interp-Llambda-class
  13990. (class interp-Lfun-class
  13991. (super-new)
  13992. (define/override (interp-op op)
  13993. (match op
  13994. ['procedure-arity
  13995. (lambda (v)
  13996. (match v
  13997. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13998. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13999. [else (super interp-op op)]))
  14000. (define/override ((interp-exp env) e)
  14001. (define recur (interp-exp env))
  14002. (match e
  14003. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  14004. `(function ,xs ,body ,env)]
  14005. [else ((super interp-exp env) e)]))
  14006. ))
  14007. (define (interp-Llambda p)
  14008. (send (new interp-Llambda-class) interp-program p))
  14009. \end{lstlisting}
  14010. \fi}
  14011. {\if\edition\pythonEd
  14012. \begin{lstlisting}
  14013. class InterpLlambda(InterpLfun):
  14014. def arity(self, v):
  14015. match v:
  14016. case Function(name, params, body, env):
  14017. return len(params)
  14018. case _:
  14019. raise Exception('Llambda arity unexpected ' + repr(v))
  14020. def interp_exp(self, e, env):
  14021. match e:
  14022. case Call(Name('arity'), [fun]):
  14023. f = self.interp_exp(fun, env)
  14024. return self.arity(f)
  14025. case Lambda(params, body):
  14026. return Function('lambda', params, [Return(body)], env)
  14027. case _:
  14028. return super().interp_exp(e, env)
  14029. def interp_stmts(self, ss, env):
  14030. if len(ss) == 0:
  14031. return
  14032. match ss[0]:
  14033. case AnnAssign(lhs, typ, value, simple):
  14034. env[lhs.id] = self.interp_exp(value, env)
  14035. return self.interp_stmts(ss[1:], env)
  14036. case _:
  14037. return super().interp_stmts(ss, env)
  14038. \end{lstlisting}
  14039. \fi}
  14040. \end{tcolorbox}
  14041. \caption{Interpreter for \LangLam{}.}
  14042. \label{fig:interp-Llambda}
  14043. \end{figure}
  14044. \label{sec:type-check-r5}
  14045. \index{subject}{type checking}
  14046. {\if\edition\racketEd
  14047. %
  14048. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  14049. \key{lambda} form. The body of the \key{lambda} is checked in an
  14050. environment that includes the current environment (because it is
  14051. lexically scoped) and also includes the \key{lambda}'s parameters. We
  14052. require the body's type to match the declared return type.
  14053. %
  14054. \fi}
  14055. {\if\edition\pythonEd
  14056. %
  14057. Figures~\ref{fig:type-check-Llambda} and
  14058. \ref{fig:type-check-Llambda-part2} define the type checker for
  14059. \LangLam{}, which is more complex than one might expect. The reason
  14060. for the added complexity is that the syntax of \key{lambda} does not
  14061. include type annotations for the parameters or return type. Instead
  14062. they must be inferred. There are many approaches of type inference to
  14063. choose from of varying degrees of complexity. We choose one of the
  14064. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  14065. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  14066. this book is compilation, not type inference.
  14067. The main idea of bidirectional type inference is to add an auxiliary
  14068. function, here named \code{check\_exp}, that takes an expected type
  14069. and checks whether the given expression is of that type. Thus, in
  14070. \code{check\_exp}, type information flows in a top-down manner with
  14071. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  14072. function, where type information flows in a primarily bottom-up
  14073. manner.
  14074. %
  14075. The idea then is to use \code{check\_exp} in all the places where we
  14076. already know what the type of an expression should be, such as in the
  14077. \code{return} statement of a top-level function definition, or on the
  14078. right-hand side of an annotated assignment statement.
  14079. Getting back to \code{lambda}, it is straightforward to check a
  14080. \code{lambda} inside \code{check\_exp} because the expected type
  14081. provides the parameter types and the return type. On the other hand,
  14082. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  14083. that we do not allow \code{lambda} in contexts where we don't already
  14084. know its type. This restriction does not incur a loss of
  14085. expressiveness for \LangLam{} because it is straightforward to modify
  14086. a program to sidestep the restriction, for example, by using an
  14087. annotated assignment statement to assign the \code{lambda} to a
  14088. temporary variable.
  14089. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  14090. checker records their type in a \code{has\_type} field. This type
  14091. information is used later in this chapter.
  14092. %
  14093. \fi}
  14094. \begin{figure}[tbp]
  14095. \begin{tcolorbox}[colback=white]
  14096. {\if\edition\racketEd
  14097. \begin{lstlisting}
  14098. (define (type-check-Llambda env)
  14099. (lambda (e)
  14100. (match e
  14101. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  14102. (define-values (new-body bodyT)
  14103. ((type-check-exp (append (map cons xs Ts) env)) body))
  14104. (define ty `(,@Ts -> ,rT))
  14105. (cond
  14106. [(equal? rT bodyT)
  14107. (values (HasType (Lambda params rT new-body) ty) ty)]
  14108. [else
  14109. (error "mismatch in return type" bodyT rT)])]
  14110. ...
  14111. )))
  14112. \end{lstlisting}
  14113. \fi}
  14114. {\if\edition\pythonEd
  14115. \begin{lstlisting}
  14116. class TypeCheckLlambda(TypeCheckLfun):
  14117. def type_check_exp(self, e, env):
  14118. match e:
  14119. case Name(id):
  14120. e.has_type = env[id]
  14121. return env[id]
  14122. case Lambda(params, body):
  14123. raise Exception('cannot synthesize a type for a lambda')
  14124. case Call(Name('arity'), [func]):
  14125. func_t = self.type_check_exp(func, env)
  14126. match func_t:
  14127. case FunctionType(params_t, return_t):
  14128. return IntType()
  14129. case _:
  14130. raise Exception('in arity, unexpected ' + repr(func_t))
  14131. case _:
  14132. return super().type_check_exp(e, env)
  14133. def check_exp(self, e, ty, env):
  14134. match e:
  14135. case Lambda(params, body):
  14136. e.has_type = ty
  14137. match ty:
  14138. case FunctionType(params_t, return_t):
  14139. new_env = env.copy().update(zip(params, params_t))
  14140. self.check_exp(body, return_t, new_env)
  14141. case _:
  14142. raise Exception('lambda does not have type ' + str(ty))
  14143. case Call(func, args):
  14144. func_t = self.type_check_exp(func, env)
  14145. match func_t:
  14146. case FunctionType(params_t, return_t):
  14147. for (arg, param_t) in zip(args, params_t):
  14148. self.check_exp(arg, param_t, env)
  14149. self.check_type_equal(return_t, ty, e)
  14150. case _:
  14151. raise Exception('type_check_exp: in call, unexpected ' + \
  14152. repr(func_t))
  14153. case _:
  14154. t = self.type_check_exp(e, env)
  14155. self.check_type_equal(t, ty, e)
  14156. \end{lstlisting}
  14157. \fi}
  14158. \end{tcolorbox}
  14159. \caption{Type checking \LangLam{}\python{, part 1}.}
  14160. \label{fig:type-check-Llambda}
  14161. \end{figure}
  14162. {\if\edition\pythonEd
  14163. \begin{figure}[tbp]
  14164. \begin{tcolorbox}[colback=white]
  14165. \begin{lstlisting}
  14166. def check_stmts(self, ss, return_ty, env):
  14167. if len(ss) == 0:
  14168. return
  14169. match ss[0]:
  14170. case FunctionDef(name, params, body, dl, returns, comment):
  14171. new_env = env.copy().update(params)
  14172. rt = self.check_stmts(body, returns, new_env)
  14173. self.check_stmts(ss[1:], return_ty, env)
  14174. case Return(value):
  14175. self.check_exp(value, return_ty, env)
  14176. case Assign([Name(id)], value):
  14177. if id in env:
  14178. self.check_exp(value, env[id], env)
  14179. else:
  14180. env[id] = self.type_check_exp(value, env)
  14181. self.check_stmts(ss[1:], return_ty, env)
  14182. case Assign([Subscript(tup, Constant(index), Store())], value):
  14183. tup_t = self.type_check_exp(tup, env)
  14184. match tup_t:
  14185. case TupleType(ts):
  14186. self.check_exp(value, ts[index], env)
  14187. case _:
  14188. raise Exception('expected a tuple, not ' + repr(tup_t))
  14189. self.check_stmts(ss[1:], return_ty, env)
  14190. case AnnAssign(Name(id), ty_annot, value, simple):
  14191. ss[0].annotation = ty_annot
  14192. if id in env:
  14193. self.check_type_equal(env[id], ty_annot)
  14194. else:
  14195. env[id] = ty_annot
  14196. self.check_exp(value, ty_annot, env)
  14197. self.check_stmts(ss[1:], return_ty, env)
  14198. case _:
  14199. self.type_check_stmts(ss, env)
  14200. def type_check(self, p):
  14201. match p:
  14202. case Module(body):
  14203. env = {}
  14204. for s in body:
  14205. match s:
  14206. case FunctionDef(name, params, bod, dl, returns, comment):
  14207. params_t = [t for (x,t) in params]
  14208. env[name] = FunctionType(params_t, returns)
  14209. self.check_stmts(body, int, env)
  14210. \end{lstlisting}
  14211. \end{tcolorbox}
  14212. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14213. \label{fig:type-check-Llambda-part2}
  14214. \end{figure}
  14215. \fi}
  14216. \clearpage
  14217. \section{Assignment and Lexically Scoped Functions}
  14218. \label{sec:assignment-scoping}
  14219. The combination of lexically-scoped functions and assignment to
  14220. variables raises a challenge with the flat-closure approach to
  14221. implementing lexically-scoped functions. Consider the following
  14222. example in which function \code{f} has a free variable \code{x} that
  14223. is changed after \code{f} is created but before the call to \code{f}.
  14224. % loop_test_11.rkt
  14225. {\if\edition\racketEd
  14226. \begin{lstlisting}
  14227. (let ([x 0])
  14228. (let ([y 0])
  14229. (let ([z 20])
  14230. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14231. (begin
  14232. (set! x 10)
  14233. (set! y 12)
  14234. (f y))))))
  14235. \end{lstlisting}
  14236. \fi}
  14237. {\if\edition\pythonEd
  14238. % box_free_assign.py
  14239. \begin{lstlisting}
  14240. def g(z : int) -> int:
  14241. x = 0
  14242. y = 0
  14243. f : Callable[[int],int] = lambda a: a + x + z
  14244. x = 10
  14245. y = 12
  14246. return f(y)
  14247. print( g(20) )
  14248. \end{lstlisting}
  14249. \fi} The correct output for this example is \code{42} because the call
  14250. to \code{f} is required to use the current value of \code{x} (which is
  14251. \code{10}). Unfortunately, the closure conversion pass
  14252. (Section~\ref{sec:closure-conversion}) generates code for the
  14253. \code{lambda} that copies the old value of \code{x} into a
  14254. closure. Thus, if we naively apply closure conversion, the output of
  14255. this program would be \code{32}.
  14256. A first attempt at solving this problem would be to save a pointer to
  14257. \code{x} in the closure and change the occurrences of \code{x} inside
  14258. the lambda to dereference the pointer. Of course, this would require
  14259. assigning \code{x} to the stack and not to a register. However, the
  14260. problem goes a bit deeper.
  14261. Consider the following example that returns a function that refers to
  14262. a local variable of the enclosing function.
  14263. \begin{center}
  14264. \begin{minipage}{\textwidth}
  14265. {\if\edition\racketEd
  14266. \begin{lstlisting}
  14267. (define (f []) : Integer
  14268. (let ([x 0])
  14269. (let ([g (lambda: () : Integer x)])
  14270. (begin
  14271. (set! x 42)
  14272. g))))
  14273. ((f))
  14274. \end{lstlisting}
  14275. \fi}
  14276. {\if\edition\pythonEd
  14277. % counter.py
  14278. \begin{lstlisting}
  14279. def f():
  14280. x = 0
  14281. g = lambda: x
  14282. x = 42
  14283. return g
  14284. print( f()() )
  14285. \end{lstlisting}
  14286. \fi}
  14287. \end{minipage}
  14288. \end{center}
  14289. In this example, the lifetime of \code{x} extends beyond the lifetime
  14290. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14291. stack frame for the call to \code{f}, it would be gone by the time we
  14292. call \code{g}, leaving us with dangling pointers for
  14293. \code{x}. This example demonstrates that when a variable occurs free
  14294. inside a function, its lifetime becomes indefinite. Thus, the value of
  14295. the variable needs to live on the heap. The verb
  14296. \emph{box}\index{subject}{box} is often used for allocating a single
  14297. value on the heap, producing a pointer, and
  14298. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14299. %
  14300. We introduce a new pass named \code{convert\_assignments} to address
  14301. this challenge.
  14302. %
  14303. \python{But before diving into that, we have one more
  14304. problem to discuss.}
  14305. \if\edition\pythonEd
  14306. \section{Uniquify Variables}
  14307. \label{sec:uniquify-lambda}
  14308. With the addition of \code{lambda} we have a complication to deal
  14309. with: name shadowing. Consider the following program with a function
  14310. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14311. \code{lambda} expressions. The first \code{lambda} has a parameter
  14312. that is also named \code{x}.
  14313. \begin{lstlisting}
  14314. def f(x:int, y:int) -> Callable[[int], int]:
  14315. g : Callable[[int],int] = (lambda x: x + y)
  14316. h : Callable[[int],int] = (lambda y: x + y)
  14317. x = input_int()
  14318. return g
  14319. print(f(0, 10)(32))
  14320. \end{lstlisting}
  14321. Many of our compiler passes rely on being able to connect variable
  14322. uses with their definitions using just the name of the variable,
  14323. including new passes in this chapter. However, in the above example
  14324. the name of the variable does not uniquely determine its
  14325. definition. To solve this problem we recommend implementing a pass
  14326. named \code{uniquify} that renames every variable in the program to
  14327. make sure they are all unique.
  14328. The following shows the result of \code{uniquify} for the above
  14329. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14330. and the \code{x} parameter of the \code{lambda} is renamed to
  14331. \code{x\_4}.
  14332. \begin{lstlisting}
  14333. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14334. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14335. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14336. x_0 = input_int()
  14337. return g_2
  14338. def main() -> int :
  14339. print(f(0, 10)(32))
  14340. return 0
  14341. \end{lstlisting}
  14342. \fi
  14343. %% \section{Reveal Functions}
  14344. %% \label{sec:reveal-functions-r5}
  14345. %% \racket{To support the \code{procedure-arity} operator we need to
  14346. %% communicate the arity of a function to the point of closure
  14347. %% creation.}
  14348. %% %
  14349. %% \python{In Chapter~\ref{ch:Ldyn} we need to access the arity of a
  14350. %% function at runtime. Thus, we need to communicate the arity of a
  14351. %% function to the point of closure creation.}
  14352. %% %
  14353. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14354. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14355. %% \[
  14356. %% \begin{array}{lcl}
  14357. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14358. %% \end{array}
  14359. %% \]
  14360. \section{Assignment Conversion}
  14361. \label{sec:convert-assignments}
  14362. The purpose of the \code{convert\_assignments} pass is to address the
  14363. challenge regarding the interaction between variable assignments and
  14364. closure conversion. First we identify which variables need to be
  14365. boxed, then we transform the program to box those variables. In
  14366. general, boxing introduces runtime overhead that we would like to
  14367. avoid, so we should box as few variables as possible. We recommend
  14368. boxing the variables in the intersection of the following two sets of
  14369. variables:
  14370. \begin{enumerate}
  14371. \item The variables that are free in a \code{lambda}.
  14372. \item The variables that appear on the left-hand side of an
  14373. assignment.
  14374. \end{enumerate}
  14375. The first condition is a must but the second condition is
  14376. conservative. It is possible to develop a more liberal condition using
  14377. static program analysis.
  14378. Consider again the first example from
  14379. Section~\ref{sec:assignment-scoping}:
  14380. %
  14381. {\if\edition\racketEd
  14382. \begin{lstlisting}
  14383. (let ([x 0])
  14384. (let ([y 0])
  14385. (let ([z 20])
  14386. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14387. (begin
  14388. (set! x 10)
  14389. (set! y 12)
  14390. (f y))))))
  14391. \end{lstlisting}
  14392. \fi}
  14393. {\if\edition\pythonEd
  14394. \begin{lstlisting}
  14395. def g(z : int) -> int:
  14396. x = 0
  14397. y = 0
  14398. f : Callable[[int],int] = lambda a: a + x + z
  14399. x = 10
  14400. y = 12
  14401. return f(y)
  14402. print( g(20) )
  14403. \end{lstlisting}
  14404. \fi}
  14405. %
  14406. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14407. variables \code{x} and \code{z} occur free inside the
  14408. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14409. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14410. transformations: initialize \code{x} with a tuple whose elements are uninitialized,
  14411. replace reads from \code{x} with tuple reads, and replace each assignment to \code{x}
  14412. with a tuple write. The output of \code{convert\_assignments} for
  14413. this example is as follows.
  14414. %
  14415. {\if\edition\racketEd
  14416. \begin{lstlisting}
  14417. (define (main) : Integer
  14418. (let ([x0 (vector 0)])
  14419. (let ([y1 0])
  14420. (let ([z2 20])
  14421. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14422. (+ a3 (+ (vector-ref x0 0) z2)))])
  14423. (begin
  14424. (vector-set! x0 0 10)
  14425. (set! y1 12)
  14426. (f4 y1)))))))
  14427. \end{lstlisting}
  14428. \fi}
  14429. %
  14430. {\if\edition\pythonEd
  14431. \begin{lstlisting}
  14432. def g(z : int)-> int:
  14433. x = (uninitialized(int),)
  14434. x[0] = 0
  14435. y = 0
  14436. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14437. x[0] = 10
  14438. y = 12
  14439. return f(y)
  14440. def main() -> int:
  14441. print(g(20))
  14442. return 0
  14443. \end{lstlisting}
  14444. \fi}
  14445. To compute the free variables of all the \code{lambda} expressions, we
  14446. recommend defining two auxiliary functions:
  14447. \begin{enumerate}
  14448. \item \code{free\_variables} computes the free variables of an expression, and
  14449. \item \code{free\_in\_lambda} collects all of the variables that are
  14450. free in any of the \code{lambda} expressions, using
  14451. \code{free\_variables} in the case for each \code{lambda}.
  14452. \end{enumerate}
  14453. {\if\edition\racketEd
  14454. %
  14455. To compute the variables that are assigned-to, we recommend using the
  14456. \code{collect-set!} function that we introduced in
  14457. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14458. forms such as \code{Lambda}.
  14459. %
  14460. \fi}
  14461. {\if\edition\pythonEd
  14462. %
  14463. To compute the variables that are assigned-to, we recommend defining
  14464. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14465. the set of variables that occur in the left-hand side of an assignment
  14466. statement, and otherwise returns the empty set.
  14467. %
  14468. \fi}
  14469. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14470. free in a \code{lambda} and that are assigned-to in the enclosing
  14471. function definition.
  14472. Next we discuss the \code{convert\_assignments} pass. In the case for
  14473. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14474. $\VAR{x}$ to a tuple read.
  14475. %
  14476. {\if\edition\racketEd
  14477. \begin{lstlisting}
  14478. (Var |$x$|)
  14479. |$\Rightarrow$|
  14480. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14481. \end{lstlisting}
  14482. \fi}
  14483. %
  14484. {\if\edition\pythonEd
  14485. \begin{lstlisting}
  14486. Name(|$x$|)
  14487. |$\Rightarrow$|
  14488. Subscript(Name(|$x$|), Constant(0), Load())
  14489. \end{lstlisting}
  14490. \fi}
  14491. %
  14492. \noindent In the case for assignment, recursively process the
  14493. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  14494. $x$ is in $\mathit{AF}$, translate the assignment into a tuple-write
  14495. as follows.
  14496. %
  14497. {\if\edition\racketEd
  14498. \begin{lstlisting}
  14499. (SetBang |$x$| |$\itm{rhs}$|)
  14500. |$\Rightarrow$|
  14501. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14502. \end{lstlisting}
  14503. \fi}
  14504. {\if\edition\pythonEd
  14505. \begin{lstlisting}
  14506. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14507. |$\Rightarrow$|
  14508. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14509. \end{lstlisting}
  14510. \fi}
  14511. %
  14512. {\if\edition\racketEd
  14513. The case for \code{Lambda} is non-trivial, but it is similar to the
  14514. case for function definitions, which we discuss next.
  14515. \fi}
  14516. %
  14517. To translate a function definition, we first compute $\mathit{AF}$,
  14518. the intersection of the variables that are free in a \code{lambda} and
  14519. that are assigned-to. We then apply assignment conversion to the body
  14520. of the function definition. Finally, we box the parameters of this
  14521. function definition that are in $\mathit{AF}$. For example,
  14522. the parameter \code{x} of the following function \code{g}
  14523. needs to be boxed.
  14524. {\if\edition\racketEd
  14525. \begin{lstlisting}
  14526. (define (g [x : Integer]) : Integer
  14527. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14528. (begin
  14529. (set! x 10)
  14530. (f 32))))
  14531. \end{lstlisting}
  14532. \fi}
  14533. %
  14534. {\if\edition\pythonEd
  14535. \begin{lstlisting}
  14536. def g(x : int) -> int:
  14537. f : Callable[[int],int] = lambda a: a + x
  14538. x = 10
  14539. return f(32)
  14540. \end{lstlisting}
  14541. \fi}
  14542. %
  14543. \noindent We box parameter \code{x} by creating a local variable named
  14544. \code{x} that is initialized to a tuple whose contents is the value of
  14545. the parameter, which has been renamed to \code{x\_0}.
  14546. %
  14547. {\if\edition\racketEd
  14548. \begin{lstlisting}
  14549. (define (g [x_0 : Integer]) : Integer
  14550. (let ([x (vector x_0)])
  14551. (let ([f (lambda: ([a : Integer]) : Integer
  14552. (+ a (vector-ref x 0)))])
  14553. (begin
  14554. (vector-set! x 0 10)
  14555. (f 32)))))
  14556. \end{lstlisting}
  14557. \fi}
  14558. %
  14559. {\if\edition\pythonEd
  14560. \begin{lstlisting}
  14561. def g(x_0 : int)-> int:
  14562. x = (x_0,)
  14563. f : Callable[[int], int] = (lambda a: a + x[0])
  14564. x[0] = 10
  14565. return f(32)
  14566. \end{lstlisting}
  14567. \fi}
  14568. \section{Closure Conversion}
  14569. \label{sec:closure-conversion}
  14570. \index{subject}{closure conversion}
  14571. The compiling of lexically-scoped functions into top-level function
  14572. definitions and flat closures is accomplished in the pass
  14573. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  14574. and before \code{limit\_functions}.
  14575. As usual, we implement the pass as a recursive function over the
  14576. AST. The interesting cases are the ones for \key{lambda} and function
  14577. application. We transform a \key{lambda} expression into an expression
  14578. that creates a closure, that is, a tuple whose first element is a
  14579. function pointer and the rest of the elements are the values of the
  14580. free variables of the \key{lambda}.
  14581. %
  14582. However, we use the \code{Closure} AST node instead of using a tuple
  14583. so that we can record the arity.
  14584. %
  14585. In the generated code below, \itm{fvs} is the free variables of the
  14586. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14587. %
  14588. \racket{The \itm{arity} is the number of parameters (the length of
  14589. \itm{ps}).}
  14590. %
  14591. {\if\edition\racketEd
  14592. \begin{lstlisting}
  14593. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14594. |$\Rightarrow$|
  14595. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  14596. \end{lstlisting}
  14597. \fi}
  14598. %
  14599. {\if\edition\pythonEd
  14600. \begin{lstlisting}
  14601. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  14602. |$\Rightarrow$|
  14603. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  14604. \end{lstlisting}
  14605. \fi}
  14606. %
  14607. In addition to transforming each \key{Lambda} AST node into a
  14608. tuple, we create a top-level function definition for each
  14609. \key{Lambda}, as shown below.\\
  14610. \begin{minipage}{0.8\textwidth}
  14611. {\if\edition\racketEd
  14612. \begin{lstlisting}
  14613. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14614. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14615. ...
  14616. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14617. |\itm{body'}|)...))
  14618. \end{lstlisting}
  14619. \fi}
  14620. {\if\edition\pythonEd
  14621. \begin{lstlisting}
  14622. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14623. |$\itm{fvs}_1$| = clos[1]
  14624. |$\ldots$|
  14625. |$\itm{fvs}_n$| = clos[|$n$|]
  14626. |\itm{body'}|
  14627. \end{lstlisting}
  14628. \fi}
  14629. \end{minipage}\\
  14630. The \code{clos} parameter refers to the closure. Translate the type
  14631. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14632. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14633. \itm{closTy} is a tuple type whose first element type is
  14634. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14635. the element types are the types of the free variables in the
  14636. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14637. is non-trivial to give a type to the function in the closure's type.%
  14638. %
  14639. \footnote{To give an accurate type to a closure, we would need to add
  14640. existential types to the type checker~\citep{Minamide:1996ys}.}
  14641. %
  14642. %% The dummy type is considered to be equal to any other type during type
  14643. %% checking.
  14644. The free variables become local variables that are initialized with
  14645. their values in the closure.
  14646. Closure conversion turns every function into a tuple, so the type
  14647. annotations in the program must also be translated. We recommend
  14648. defining an auxiliary recursive function for this purpose. Function
  14649. types should be translated as follows.
  14650. %
  14651. {\if\edition\racketEd
  14652. \begin{lstlisting}
  14653. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14654. |$\Rightarrow$|
  14655. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14656. \end{lstlisting}
  14657. \fi}
  14658. {\if\edition\pythonEd
  14659. \begin{lstlisting}
  14660. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14661. |$\Rightarrow$|
  14662. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14663. \end{lstlisting}
  14664. \fi}
  14665. %
  14666. The above type says that the first thing in the tuple is a
  14667. function. The first parameter of the function is a tuple (a closure)
  14668. and the rest of the parameters are the ones from the original
  14669. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14670. omits the types of the free variables because 1) those types are not
  14671. available in this context and 2) we do not need them in the code that
  14672. is generated for function application. So this type only describes the
  14673. first component of the closure tuple. At runtime the tuple may have
  14674. more components, but we ignore them at this point.
  14675. We transform function application into code that retrieves the
  14676. function from the closure and then calls the function, passing the
  14677. closure as the first argument. We place $e'$ in a temporary variable
  14678. to avoid code duplication.
  14679. \begin{center}
  14680. \begin{minipage}{\textwidth}
  14681. {\if\edition\racketEd
  14682. \begin{lstlisting}
  14683. (Apply |$e$| |$\itm{es}$|)
  14684. |$\Rightarrow$|
  14685. (Let |$\itm{tmp}$| |$e'$|
  14686. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  14687. \end{lstlisting}
  14688. \fi}
  14689. %
  14690. {\if\edition\pythonEd
  14691. \begin{lstlisting}
  14692. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14693. |$\Rightarrow$|
  14694. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  14695. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14696. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14697. \end{lstlisting}
  14698. \fi}
  14699. \end{minipage}
  14700. \end{center}
  14701. There is also the question of what to do with references to top-level
  14702. function definitions. To maintain a uniform translation of function
  14703. application, we turn function references into closures.
  14704. \begin{tabular}{lll}
  14705. \begin{minipage}{0.3\textwidth}
  14706. {\if\edition\racketEd
  14707. \begin{lstlisting}
  14708. (FunRef |$f$| |$n$|)
  14709. \end{lstlisting}
  14710. \fi}
  14711. {\if\edition\pythonEd
  14712. \begin{lstlisting}
  14713. FunRef(|$f$|, |$n$|)
  14714. \end{lstlisting}
  14715. \fi}
  14716. \end{minipage}
  14717. &
  14718. $\Rightarrow$
  14719. &
  14720. \begin{minipage}{0.5\textwidth}
  14721. {\if\edition\racketEd
  14722. \begin{lstlisting}
  14723. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  14724. \end{lstlisting}
  14725. \fi}
  14726. {\if\edition\pythonEd
  14727. \begin{lstlisting}
  14728. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  14729. \end{lstlisting}
  14730. \fi}
  14731. \end{minipage}
  14732. \end{tabular} \\
  14733. We no longer need the annotated assignment statement \code{AnnAssign}
  14734. to support the type checking of \code{lambda} expressions, so we
  14735. translate it to a regular \code{Assign} statement.
  14736. The top-level function definitions need to be updated to take an extra
  14737. closure parameter but that parameter is ignored in the body of those
  14738. functions.
  14739. \section{An Example Translation}
  14740. \label{sec:example-lambda}
  14741. Figure~\ref{fig:lexical-functions-example} shows the result of
  14742. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14743. program demonstrating lexical scoping that we discussed at the
  14744. beginning of this chapter.
  14745. \begin{figure}[tbp]
  14746. \begin{tcolorbox}[colback=white]
  14747. \begin{minipage}{0.8\textwidth}
  14748. {\if\edition\racketEd
  14749. % tests/lambda_test_6.rkt
  14750. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14751. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14752. (let ([y8 4])
  14753. (lambda: ([z9 : Integer]) : Integer
  14754. (+ x7 (+ y8 z9)))))
  14755. (define (main) : Integer
  14756. (let ([g0 ((fun-ref f6 1) 5)])
  14757. (let ([h1 ((fun-ref f6 1) 3)])
  14758. (+ (g0 11) (h1 15)))))
  14759. \end{lstlisting}
  14760. $\Rightarrow$
  14761. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14762. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14763. (let ([y8 4])
  14764. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  14765. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14766. (let ([x7 (vector-ref fvs3 1)])
  14767. (let ([y8 (vector-ref fvs3 2)])
  14768. (+ x7 (+ y8 z9)))))
  14769. (define (main) : Integer
  14770. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  14771. ((vector-ref clos5 0) clos5 5))])
  14772. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  14773. ((vector-ref clos6 0) clos6 3))])
  14774. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14775. \end{lstlisting}
  14776. \fi}
  14777. %
  14778. {\if\edition\pythonEd
  14779. % free_var.py
  14780. \begin{lstlisting}
  14781. def f(x : int) -> Callable[[int], int]:
  14782. y = 4
  14783. return lambda z: x + y + z
  14784. g = f(5)
  14785. h = f(3)
  14786. print( g(11) + h(15) )
  14787. \end{lstlisting}
  14788. $\Rightarrow$
  14789. \begin{lstlisting}
  14790. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  14791. x = fvs_1[1]
  14792. y = fvs_1[2]
  14793. return x + y[0] + z
  14794. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  14795. y = (777,)
  14796. y[0] = 4
  14797. return (lambda_0, x, y)
  14798. def main() -> int:
  14799. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  14800. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  14801. print((let clos_5 = g in clos_5[0](clos_5, 11))
  14802. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  14803. return 0
  14804. \end{lstlisting}
  14805. \fi}
  14806. \end{minipage}
  14807. \end{tcolorbox}
  14808. \caption{Example of closure conversion.}
  14809. \label{fig:lexical-functions-example}
  14810. \end{figure}
  14811. \begin{exercise}\normalfont\normalsize
  14812. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14813. Create 5 new programs that use \key{lambda} functions and make use of
  14814. lexical scoping. Test your compiler on these new programs and all of
  14815. your previously created test programs.
  14816. \end{exercise}
  14817. \section{Expose Allocation}
  14818. \label{sec:expose-allocation-r5}
  14819. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  14820. that allocates and initializes a tuple, similar to the translation of
  14821. the tuple creation in Section~\ref{sec:expose-allocation}.
  14822. The only difference is replacing the use of
  14823. \ALLOC{\itm{len}}{\itm{type}} with
  14824. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14825. \section{Explicate Control and \LangCLam{}}
  14826. \label{sec:explicate-r5}
  14827. The output language of \code{explicate\_control} is \LangCLam{} whose
  14828. abstract syntax is defined in Figure~\ref{fig:Clam-syntax}.
  14829. %
  14830. \racket{The only differences with respect to \LangCFun{} is the
  14831. addition of the \code{AllocateClosure} form to the grammar for
  14832. $\Exp$ and the \code{procedure-arity} operator. The handling of
  14833. \code{AllocateClosure} in the \code{explicate\_control} pass is
  14834. similar to the handling of other expressions such as primitive
  14835. operators.}
  14836. %
  14837. \python{The differences with respect to \LangCFun{} are the
  14838. additions of \code{Uninitialized}, \code{AllocateClosure},
  14839. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  14840. \code{explicate\_control} pass is similar to the handling of other
  14841. expressions such as primitive operators.}
  14842. \newcommand{\ClambdaASTRacket}{
  14843. \begin{array}{lcl}
  14844. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14845. \itm{op} &::= & \code{procedure-arity}
  14846. \end{array}
  14847. }
  14848. \newcommand{\ClambdaASTPython}{
  14849. \begin{array}{lcl}
  14850. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  14851. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  14852. &\MID& \ARITY{\Atm}
  14853. \end{array}
  14854. }
  14855. \begin{figure}[tp]
  14856. \begin{tcolorbox}[colback=white]
  14857. \small
  14858. {\if\edition\racketEd
  14859. \[
  14860. \begin{array}{l}
  14861. \gray{\CvarASTRacket} \\ \hline
  14862. \gray{\CifASTRacket} \\ \hline
  14863. \gray{\CloopASTRacket} \\ \hline
  14864. \gray{\CtupASTRacket} \\ \hline
  14865. \gray{\CfunASTRacket} \\ \hline
  14866. \ClambdaASTRacket \\
  14867. \begin{array}{lcl}
  14868. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  14869. \end{array}
  14870. \end{array}
  14871. \]
  14872. \fi}
  14873. {\if\edition\pythonEd
  14874. \[
  14875. \begin{array}{l}
  14876. \gray{\CifASTPython} \\ \hline
  14877. \gray{\CtupASTPython} \\ \hline
  14878. \gray{\CfunASTPython} \\ \hline
  14879. \ClambdaASTPython \\
  14880. \begin{array}{lcl}
  14881. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14882. \end{array}
  14883. \end{array}
  14884. \]
  14885. \fi}
  14886. \end{tcolorbox}
  14887. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14888. \label{fig:Clam-syntax}
  14889. \end{figure}
  14890. \section{Select Instructions}
  14891. \label{sec:select-instructions-Llambda}
  14892. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14893. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14894. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14895. that you should place the \itm{arity} in the tag that is stored at
  14896. position $0$ of the vector. Recall that in
  14897. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14898. was not used. We store the arity in the $5$ bits starting at position
  14899. $58$.
  14900. \racket{Compile the \code{procedure-arity} operator into a sequence of
  14901. instructions that access the tag from position $0$ of the vector and
  14902. extract the $5$-bits starting at position $58$ from the tag.}
  14903. %
  14904. \python{Compile a call to the \code{arity} operator to a sequence of
  14905. instructions that access the tag from position $0$ of the tuple
  14906. (representing a closure) and extract the $5$-bits starting at position
  14907. $58$ from the tag.}
  14908. \begin{figure}[p]
  14909. \begin{tcolorbox}[colback=white]
  14910. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  14911. \node (Lfun) at (0,2) {\large \LangLam{}};
  14912. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  14913. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  14914. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14915. \node (F1-1) at (12,2) {\large \LangLamFunRef{}};
  14916. \node (F1-2) at (12,0) {\large \LangFunRef{}};
  14917. \node (F1-3) at (9,0) {\large \LangFunRef{}};
  14918. \node (F1-4) at (6,0) {\large \LangFunRefAlloc{}};
  14919. \node (F1-5) at (3,0) {\large \LangFunRefAlloc{}};
  14920. \node (F1-6) at (0,0) {\large \LangFunANF{}};
  14921. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14922. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14923. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14924. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14925. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14926. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14927. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14928. \path[->,bend left=15] (Lfun) edge [above] node
  14929. {\ttfamily\footnotesize shrink} (Lfun-2);
  14930. \path[->,bend left=15] (Lfun-2) edge [above] node
  14931. {\ttfamily\footnotesize uniquify} (Lfun-3);
  14932. \path[->,bend left=15] (Lfun-3) edge [above] node
  14933. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14934. \path[->,bend left=15] (F1-0) edge [above] node
  14935. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  14936. \path[->,bend left=15] (F1-1) edge [left] node
  14937. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14938. \path[->,bend left=15] (F1-2) edge [below] node
  14939. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14940. \path[->,bend right=15] (F1-3) edge [above] node
  14941. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14942. \path[->,bend left=15] (F1-4) edge [below] node
  14943. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  14944. \path[->,bend right=15] (F1-5) edge [above] node
  14945. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  14946. \path[->,bend right=15] (F1-6) edge [right] node
  14947. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14948. \path[->,bend left=15] (C3-2) edge [left] node
  14949. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14950. \path[->,bend right=15] (x86-2) edge [left] node
  14951. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14952. \path[->,bend right=15] (x86-2-1) edge [below] node
  14953. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14954. \path[->,bend right=15] (x86-2-2) edge [left] node
  14955. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14956. \path[->,bend left=15] (x86-3) edge [above] node
  14957. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14958. \path[->,bend left=15] (x86-4) edge [right] node
  14959. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  14960. \end{tikzpicture}
  14961. \end{tcolorbox}
  14962. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14963. functions.}
  14964. \label{fig:Llambda-passes}
  14965. \end{figure}
  14966. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  14967. needed for the compilation of \LangLam{}.
  14968. \clearpage
  14969. \section{Challenge: Optimize Closures}
  14970. \label{sec:optimize-closures}
  14971. In this chapter we compiled lexically-scoped functions into a
  14972. relatively efficient representation: flat closures. However, even this
  14973. representation comes with some overhead. For example, consider the
  14974. following program with a function \code{tail\_sum} that does not have
  14975. any free variables and where all the uses of \code{tail\_sum} are in
  14976. applications where we know that only \code{tail\_sum} is being applied
  14977. (and not any other functions).
  14978. \begin{center}
  14979. \begin{minipage}{0.95\textwidth}
  14980. {\if\edition\racketEd
  14981. \begin{lstlisting}
  14982. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  14983. (if (eq? n 0)
  14984. s
  14985. (tail_sum (- n 1) (+ n s))))
  14986. (+ (tail_sum 3 0) 36)
  14987. \end{lstlisting}
  14988. \fi}
  14989. {\if\edition\pythonEd
  14990. \begin{lstlisting}
  14991. def tail_sum(n : int, s : int) -> int:
  14992. if n == 0:
  14993. return s
  14994. else:
  14995. return tail_sum(n - 1, n + s)
  14996. print( tail_sum(3, 0) + 36)
  14997. \end{lstlisting}
  14998. \fi}
  14999. \end{minipage}
  15000. \end{center}
  15001. As described in this chapter, we uniformly apply closure conversion to
  15002. all functions, obtaining the following output for this program.
  15003. \begin{center}
  15004. \begin{minipage}{0.95\textwidth}
  15005. {\if\edition\racketEd
  15006. \begin{lstlisting}
  15007. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  15008. (if (eq? n2 0)
  15009. s3
  15010. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  15011. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  15012. (define (main) : Integer
  15013. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  15014. ((vector-ref clos6 0) clos6 3 0)) 27))
  15015. \end{lstlisting}
  15016. \fi}
  15017. {\if\edition\pythonEd
  15018. \begin{lstlisting}
  15019. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  15020. if n_0 == 0:
  15021. return s_1
  15022. else:
  15023. return (let clos_2 = (tail_sum,)
  15024. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  15025. def main() -> int :
  15026. print((let clos_4 = (tail_sum,)
  15027. in clos_4[0](clos_4, 3, 0)) + 36)
  15028. return 0
  15029. \end{lstlisting}
  15030. \fi}
  15031. \end{minipage}
  15032. \end{center}
  15033. In the previous chapter, there would be no allocation in the program
  15034. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  15035. the above program allocates memory for each closure and the calls to
  15036. \code{tail\_sum} are indirect. These two differences incur
  15037. considerable overhead in a program such as this one, where the
  15038. allocations and indirect calls occur inside a tight loop.
  15039. One might think that this problem is trivial to solve: can't we just
  15040. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  15041. and compile them to direct calls instead of treating it like a call to
  15042. a closure? We would also drop the new \code{fvs} parameter of
  15043. \code{tail\_sum}.
  15044. %
  15045. However, this problem is not so trivial because a global function may
  15046. ``escape'' and become involved in applications that also involve
  15047. closures. Consider the following example in which the application
  15048. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  15049. application, because the \code{lambda} may flow into \code{f}, but the
  15050. \code{inc} function might also flow into \code{f}.
  15051. \begin{center}
  15052. \begin{minipage}{\textwidth}
  15053. % lambda_test_30.rkt
  15054. {\if\edition\racketEd
  15055. \begin{lstlisting}
  15056. (define (inc [x : Integer]) : Integer
  15057. (+ x 1))
  15058. (let ([y (read)])
  15059. (let ([f (if (eq? (read) 0)
  15060. inc
  15061. (lambda: ([x : Integer]) : Integer (- x y)))])
  15062. (f 41)))
  15063. \end{lstlisting}
  15064. \fi}
  15065. {\if\edition\pythonEd
  15066. \begin{lstlisting}
  15067. def add1(x : int) -> int:
  15068. return x + 1
  15069. y = input_int()
  15070. g : Callable[[int], int] = lambda x: x - y
  15071. f = add1 if input_int() == 0 else g
  15072. print( f(41) )
  15073. \end{lstlisting}
  15074. \fi}
  15075. \end{minipage}
  15076. \end{center}
  15077. If a global function name is used in any way other than as the
  15078. operator in a direct call, then we say that the function
  15079. \emph{escapes}. If a global function does not escape, then we do not
  15080. need to perform closure conversion on the function.
  15081. \begin{exercise}\normalfont\normalsize
  15082. Implement an auxiliary function for detecting which global
  15083. functions escape. Using that function, implement an improved version
  15084. of closure conversion that does not apply closure conversion to
  15085. global functions that do not escape but instead compiles them as
  15086. regular functions. Create several new test cases that check whether
  15087. you properly detect whether global functions escape or not.
  15088. \end{exercise}
  15089. So far we have reduced the overhead of calling global functions, but
  15090. it would also be nice to reduce the overhead of calling a
  15091. \code{lambda} when we can determine at compile time which
  15092. \code{lambda} will be called. We refer to such calls as \emph{known
  15093. calls}. Consider the following example in which a \code{lambda} is
  15094. bound to \code{f} and then applied.
  15095. {\if\edition\racketEd
  15096. % lambda_test_9.rkt
  15097. \begin{lstlisting}
  15098. (let ([y (read)])
  15099. (let ([f (lambda: ([x : Integer]) : Integer
  15100. (+ x y))])
  15101. (f 21)))
  15102. \end{lstlisting}
  15103. \fi}
  15104. {\if\edition\pythonEd
  15105. \begin{lstlisting}
  15106. y = input_int()
  15107. f : Callable[[int],int] = lambda x: x + y
  15108. print( f(21) )
  15109. \end{lstlisting}
  15110. \fi}
  15111. %
  15112. \noindent Closure conversion compiles the application
  15113. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  15114. %
  15115. {\if\edition\racketEd
  15116. \begin{lstlisting}
  15117. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15118. (let ([y2 (vector-ref fvs6 1)])
  15119. (+ x3 y2)))
  15120. (define (main) : Integer
  15121. (let ([y2 (read)])
  15122. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15123. ((vector-ref f4 0) f4 21))))
  15124. \end{lstlisting}
  15125. \fi}
  15126. {\if\edition\pythonEd
  15127. \begin{lstlisting}
  15128. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15129. y_1 = fvs_4[1]
  15130. return x_2 + y_1[0]
  15131. def main() -> int:
  15132. y_1 = (777,)
  15133. y_1[0] = input_int()
  15134. f_0 = (lambda_3, y_1)
  15135. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15136. return 0
  15137. \end{lstlisting}
  15138. \fi}
  15139. %
  15140. \noindent but we can instead compile the application
  15141. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  15142. %
  15143. {\if\edition\racketEd
  15144. \begin{lstlisting}
  15145. (define (main) : Integer
  15146. (let ([y2 (read)])
  15147. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15148. ((fun-ref lambda5 1) f4 21))))
  15149. \end{lstlisting}
  15150. \fi}
  15151. {\if\edition\pythonEd
  15152. \begin{lstlisting}
  15153. def main() -> int:
  15154. y_1 = (777,)
  15155. y_1[0] = input_int()
  15156. f_0 = (lambda_3, y_1)
  15157. print(lambda_3(f_0, 21))
  15158. return 0
  15159. \end{lstlisting}
  15160. \fi}
  15161. The problem of determining which \code{lambda} will be called from a
  15162. particular application is quite challenging in general and the topic
  15163. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15164. following exercise we recommend that you compile an application to a
  15165. direct call when the operator is a variable and \racket{the variable
  15166. is \code{let}-bound to a closure}\python{the previous assignment to
  15167. the variable is a closure}. This can be accomplished by maintaining
  15168. an environment mapping variables to function names. Extend the
  15169. environment whenever you encounter a closure on the right-hand side of
  15170. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15171. name of the global function for the closure. This pass should come
  15172. after closure conversion.
  15173. \begin{exercise}\normalfont\normalsize
  15174. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15175. compiles known calls into direct calls. Verify that your compiler is
  15176. successful in this regard on several example programs.
  15177. \end{exercise}
  15178. These exercises only scratches the surface of optimizing of
  15179. closures. A good next step for the interested reader is to look at the
  15180. work of \citet{Keep:2012ab}.
  15181. \section{Further Reading}
  15182. The notion of lexically scoped functions predates modern computers by
  15183. about a decade. They were invented by \citet{Church:1932aa}, who
  15184. proposed the lambda calculus as a foundation for logic. Anonymous
  15185. functions were included in the LISP~\citep{McCarthy:1960dz}
  15186. programming language but were initially dynamically scoped. The Scheme
  15187. dialect of LISP adopted lexical scoping and
  15188. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15189. Scheme programs. However, environments were represented as linked
  15190. lists, so variable look-up was linear in the size of the
  15191. environment. \citet{Appel91} gives a detailed description of several
  15192. closure representations. In this chapter we represent environments
  15193. using flat closures, which were invented by
  15194. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15195. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15196. closures, variable look-up is constant time but the time to create a
  15197. closure is proportional to the number of its free variables. Flat
  15198. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  15199. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15200. % todo: related work on assignment conversion (e.g. orbit and rabbit
  15201. % compilers)
  15202. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15203. \chapter{Dynamic Typing}
  15204. \label{ch:Ldyn}
  15205. \index{subject}{dynamic typing}
  15206. In this chapter we learn how to compile \LangDyn{}, a dynamically
  15207. typed language that is a subset of \racket{Racket}\python{Python}. The
  15208. focus on dynamic typing is in contrast to the previous chapters, which
  15209. have studied the compilation of statically typed languages. In
  15210. dynamically typed languages such as \LangDyn{}, a particular
  15211. expression may produce a value of a different type each time it is
  15212. executed. Consider the following example with a conditional \code{if}
  15213. expression that may return a Boolean or an integer depending on the
  15214. input to the program.
  15215. % part of dynamic_test_25.rkt
  15216. {\if\edition\racketEd
  15217. \begin{lstlisting}
  15218. (not (if (eq? (read) 1) #f 0))
  15219. \end{lstlisting}
  15220. \fi}
  15221. {\if\edition\pythonEd
  15222. \begin{lstlisting}
  15223. not (False if input_int() == 1 else 0)
  15224. \end{lstlisting}
  15225. \fi}
  15226. Languages that allow expressions to produce different kinds of values
  15227. are called \emph{polymorphic}, a word composed of the Greek roots
  15228. ``poly'', meaning ``many'', and ``morph'', meaning ``form''. There
  15229. are several kinds of polymorphism in programming languages, such as
  15230. subtype polymorphism and parametric
  15231. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  15232. study in this chapter does not have a special name but it is the kind
  15233. that arises in dynamically typed languages.
  15234. Another characteristic of dynamically typed languages is that
  15235. primitive operations, such as \code{not}, are often defined to operate
  15236. on many different types of values. In fact, in
  15237. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15238. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15239. given anything else it returns \FALSE{}.
  15240. Furthermore, even when primitive operations restrict their inputs to
  15241. values of a certain type, this restriction is enforced at runtime
  15242. instead of during compilation. For example, the tuple read
  15243. operation
  15244. \racket{\code{(vector-ref \#t 0)}}
  15245. \python{\code{True[0]}}
  15246. results in a run-time error because the first argument must
  15247. be a tuple, not a Boolean.
  15248. \section{The \LangDyn{} Language}
  15249. \newcommand{\LdynGrammarRacket}{
  15250. \begin{array}{rcl}
  15251. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  15252. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15253. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15254. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15255. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  15256. \end{array}
  15257. }
  15258. \newcommand{\LdynASTRacket}{
  15259. \begin{array}{lcl}
  15260. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  15261. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15262. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  15263. \end{array}
  15264. }
  15265. \begin{figure}[tp]
  15266. \centering
  15267. \begin{tcolorbox}[colback=white]
  15268. \small
  15269. {\if\edition\racketEd
  15270. \[
  15271. \begin{array}{l}
  15272. \gray{\LintGrammarRacket{}} \\ \hline
  15273. \gray{\LvarGrammarRacket{}} \\ \hline
  15274. \gray{\LifGrammarRacket{}} \\ \hline
  15275. \gray{\LwhileGrammarRacket} \\ \hline
  15276. \gray{\LtupGrammarRacket} \\ \hline
  15277. \LdynGrammarRacket \\
  15278. \begin{array}{rcl}
  15279. \LangDynM{} &::=& \Def\ldots\; \Exp
  15280. \end{array}
  15281. \end{array}
  15282. \]
  15283. \fi}
  15284. {\if\edition\pythonEd
  15285. \[
  15286. \begin{array}{rcl}
  15287. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15288. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15289. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15290. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15291. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15292. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15293. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15294. \MID \CLEN{\Exp} \\
  15295. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15296. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15297. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15298. \MID \Var\mathop{\key{=}}\Exp \\
  15299. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15300. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15301. &\MID& \CRETURN{\Exp} \\
  15302. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15303. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15304. \end{array}
  15305. \]
  15306. \fi}
  15307. \end{tcolorbox}
  15308. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15309. \label{fig:r7-concrete-syntax}
  15310. \end{figure}
  15311. \begin{figure}[tp]
  15312. \centering
  15313. \begin{tcolorbox}[colback=white]
  15314. \small
  15315. {\if\edition\racketEd
  15316. \[
  15317. \begin{array}{l}
  15318. \gray{\LintASTRacket{}} \\ \hline
  15319. \gray{\LvarASTRacket{}} \\ \hline
  15320. \gray{\LifASTRacket{}} \\ \hline
  15321. \gray{\LwhileASTRacket} \\ \hline
  15322. \gray{\LtupASTRacket} \\ \hline
  15323. \LdynASTRacket \\
  15324. \begin{array}{lcl}
  15325. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15326. \end{array}
  15327. \end{array}
  15328. \]
  15329. \fi}
  15330. {\if\edition\pythonEd
  15331. \[
  15332. \begin{array}{rcl}
  15333. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15334. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15335. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15336. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15337. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15338. &\MID & \code{Is()} \\
  15339. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15340. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15341. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15342. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  15343. \MID \VAR{\Var{}} \\
  15344. &\MID& \BOOL{\itm{bool}}
  15345. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15346. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15347. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15348. &\MID& \LEN{\Exp} \\
  15349. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15350. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15351. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15352. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15353. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15354. &\MID& \RETURN{\Exp} \\
  15355. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15356. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  15357. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15358. \end{array}
  15359. \]
  15360. \fi}
  15361. \end{tcolorbox}
  15362. \caption{The abstract syntax of \LangDyn{}.}
  15363. \label{fig:r7-syntax}
  15364. \end{figure}
  15365. The concrete and abstract syntax of \LangDyn{} is defined in
  15366. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15367. %
  15368. There is no type checker for \LangDyn{} because it only checks types
  15369. at runtime.
  15370. The definitional interpreter for \LangDyn{} is presented in
  15371. \racket{Figure~\ref{fig:interp-Ldyn}}
  15372. \python{Figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}
  15373. and its auxiliary functions are defined in
  15374. Figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15375. \INT{n}. Instead of simply returning the integer \code{n} (as
  15376. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  15377. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15378. value} that combines an underlying value with a tag that identifies
  15379. what kind of value it is. We define the following \racket{struct}\python{class}
  15380. to represented tagged values.
  15381. %
  15382. {\if\edition\racketEd
  15383. \begin{lstlisting}
  15384. (struct Tagged (value tag) #:transparent)
  15385. \end{lstlisting}
  15386. \fi}
  15387. {\if\edition\pythonEd
  15388. \begin{minipage}{\textwidth}
  15389. \begin{lstlisting}
  15390. @dataclass(eq=True)
  15391. class Tagged(Value):
  15392. value : Value
  15393. tag : str
  15394. def __str__(self):
  15395. return str(self.value)
  15396. \end{lstlisting}
  15397. \end{minipage}
  15398. \fi}
  15399. %
  15400. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  15401. \code{Vector}, and \code{Procedure}.}
  15402. %
  15403. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15404. \code{'tuple'}, and \code{'function'}.}
  15405. %
  15406. Tags are closely related to types but don't always capture all the
  15407. information that a type does.
  15408. %
  15409. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15410. tagged with \code{Vector} and a procedure of type \code{(Any Any ->
  15411. Any)} is tagged with \code{Procedure}.}
  15412. %
  15413. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15414. is tagged with \code{'tuple'} and a function of type
  15415. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15416. is tagged with \code{'function'}.}
  15417. Next consider the match case for accessing the element of a tuple.
  15418. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15419. (Figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15420. argument is a tuple and the second is an integer.
  15421. \racket{
  15422. If they are not, a \code{trapped-error} is raised. Recall from
  15423. Section~\ref{sec:interp_Lint} that when a definition interpreter
  15424. raises a \code{trapped-error} error, the compiled code must also
  15425. signal an error by exiting with return code \code{255}. A
  15426. \code{trapped-error} is also raised if the index is not less than the
  15427. length of the vector.
  15428. }
  15429. %
  15430. \python{If they are not, an exception is raised. The compiled code
  15431. must also signal an error by exiting with return code \code{255}. A
  15432. exception is also raised if the index is not less than the length of the
  15433. tuple or if it is negative.}
  15434. \begin{figure}[tbp]
  15435. \begin{tcolorbox}[colback=white]
  15436. {\if\edition\racketEd
  15437. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15438. (define ((interp-Ldyn-exp env) ast)
  15439. (define recur (interp-Ldyn-exp env))
  15440. (match ast
  15441. [(Var x) (dict-ref env x)]
  15442. [(Int n) (Tagged n 'Integer)]
  15443. [(Bool b) (Tagged b 'Boolean)]
  15444. [(Lambda xs rt body)
  15445. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15446. [(Prim 'vector es)
  15447. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15448. [(Prim 'vector-ref (list e1 e2))
  15449. (define vec (recur e1)) (define i (recur e2))
  15450. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15451. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15452. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15453. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15454. [(Prim 'vector-set! (list e1 e2 e3))
  15455. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15456. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15457. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15458. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15459. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15460. (Tagged (void) 'Void)]
  15461. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  15462. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15463. [(Prim 'or (list e1 e2))
  15464. (define v1 (recur e1))
  15465. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15466. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15467. [(Prim op (list e1))
  15468. #:when (set-member? type-predicates op)
  15469. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15470. [(Prim op es)
  15471. (define args (map recur es))
  15472. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15473. (unless (for/or ([expected-tags (op-tags op)])
  15474. (equal? expected-tags tags))
  15475. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15476. (tag-value
  15477. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15478. [(If q t f)
  15479. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15480. [(Apply f es)
  15481. (define new-f (recur f)) (define args (map recur es))
  15482. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15483. (match f-val
  15484. [`(function ,xs ,body ,lam-env)
  15485. (unless (eq? (length xs) (length args))
  15486. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15487. (define new-env (append (map cons xs args) lam-env))
  15488. ((interp-Ldyn-exp new-env) body)]
  15489. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  15490. \end{lstlisting}
  15491. \fi}
  15492. {\if\edition\pythonEd
  15493. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15494. class InterpLdyn(InterpLlambda):
  15495. def interp_exp(self, e, env):
  15496. match e:
  15497. case Constant(n):
  15498. return self.tag(super().interp_exp(e, env))
  15499. case Tuple(es, Load()):
  15500. return self.tag(super().interp_exp(e, env))
  15501. case Lambda(params, body):
  15502. return self.tag(super().interp_exp(e, env))
  15503. case Call(Name('input_int'), []):
  15504. return self.tag(super().interp_exp(e, env))
  15505. case BinOp(left, Add(), right):
  15506. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15507. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  15508. case BinOp(left, Sub(), right):
  15509. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15510. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  15511. case UnaryOp(USub(), e1):
  15512. v = self.interp_exp(e1, env)
  15513. return self.tag(- self.untag(v, 'int', e))
  15514. case IfExp(test, body, orelse):
  15515. v = self.interp_exp(test, env)
  15516. if self.untag(v, 'bool', e):
  15517. return self.interp_exp(body, env)
  15518. else:
  15519. return self.interp_exp(orelse, env)
  15520. case UnaryOp(Not(), e1):
  15521. v = self.interp_exp(e1, env)
  15522. return self.tag(not self.untag(v, 'bool', e))
  15523. case BoolOp(And(), values):
  15524. left = values[0]; right = values[1]
  15525. l = self.interp_exp(left, env)
  15526. if self.untag(l, 'bool', e):
  15527. return self.interp_exp(right, env)
  15528. else:
  15529. return self.tag(False)
  15530. case BoolOp(Or(), values):
  15531. left = values[0]; right = values[1]
  15532. l = self.interp_exp(left, env)
  15533. if self.untag(l, 'bool', e):
  15534. return self.tag(True)
  15535. else:
  15536. return self.interp_exp(right, env)
  15537. case Compare(left, [cmp], [right]):
  15538. l = self.interp_exp(left, env)
  15539. r = self.interp_exp(right, env)
  15540. if l.tag == r.tag:
  15541. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  15542. else:
  15543. raise Exception('interp Compare unexpected ' \
  15544. + repr(l) + ' ' + repr(r))
  15545. case Subscript(tup, index, Load()):
  15546. t = self.interp_exp(tup, env)
  15547. n = self.interp_exp(index, env)
  15548. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  15549. case Call(Name('len'), [tup]):
  15550. t = self.interp_exp(tup, env)
  15551. return self.tag(len(self.untag(t, 'tuple', e)))
  15552. case _:
  15553. return self.tag(super().interp_exp(e, env))
  15554. \end{lstlisting}
  15555. \fi}
  15556. \end{tcolorbox}
  15557. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  15558. \label{fig:interp-Ldyn}
  15559. \end{figure}
  15560. {\if\edition\pythonEd
  15561. \begin{figure}[tbp]
  15562. \begin{tcolorbox}[colback=white]
  15563. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15564. class InterpLdyn(InterpLlambda):
  15565. def interp_stmts(self, ss, env):
  15566. if len(ss) == 0:
  15567. return
  15568. match ss[0]:
  15569. case If(test, body, orelse):
  15570. v = self.interp_exp(test, env)
  15571. if self.untag(v, 'bool', ss[0]):
  15572. return self.interp_stmts(body + ss[1:], env)
  15573. else:
  15574. return self.interp_stmts(orelse + ss[1:], env)
  15575. case While(test, body, []):
  15576. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  15577. self.interp_stmts(body, env)
  15578. return self.interp_stmts(ss[1:], env)
  15579. case Assign([Subscript(tup, index)], value):
  15580. tup = self.interp_exp(tup, env)
  15581. index = self.interp_exp(index, env)
  15582. tup_v = self.untag(tup, 'tuple', ss[0])
  15583. index_v = self.untag(index, 'int', ss[0])
  15584. tup_v[index_v] = self.interp_exp(value, env)
  15585. return self.interp_stmts(ss[1:], env)
  15586. case FunctionDef(name, params, bod, dl, returns, comment):
  15587. ps = [x for (x,t) in params]
  15588. env[name] = self.tag(Function(name, ps, bod, env))
  15589. return self.interp_stmts(ss[1:], env)
  15590. case _:
  15591. return super().interp_stmts(ss, env)
  15592. \end{lstlisting}
  15593. \end{tcolorbox}
  15594. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  15595. \label{fig:interp-Ldyn-2}
  15596. \end{figure}
  15597. \fi}
  15598. \begin{figure}[tbp]
  15599. \begin{tcolorbox}[colback=white]
  15600. {\if\edition\racketEd
  15601. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15602. (define (interp-op op)
  15603. (match op
  15604. ['+ fx+]
  15605. ['- fx-]
  15606. ['read read-fixnum]
  15607. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  15608. ['< (lambda (v1 v2)
  15609. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  15610. ['<= (lambda (v1 v2)
  15611. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  15612. ['> (lambda (v1 v2)
  15613. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  15614. ['>= (lambda (v1 v2)
  15615. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  15616. ['boolean? boolean?]
  15617. ['integer? fixnum?]
  15618. ['void? void?]
  15619. ['vector? vector?]
  15620. ['vector-length vector-length]
  15621. ['procedure? (match-lambda
  15622. [`(functions ,xs ,body ,env) #t] [else #f])]
  15623. [else (error 'interp-op "unknown operator" op)]))
  15624. (define (op-tags op)
  15625. (match op
  15626. ['+ '((Integer Integer))]
  15627. ['- '((Integer Integer) (Integer))]
  15628. ['read '(())]
  15629. ['not '((Boolean))]
  15630. ['< '((Integer Integer))]
  15631. ['<= '((Integer Integer))]
  15632. ['> '((Integer Integer))]
  15633. ['>= '((Integer Integer))]
  15634. ['vector-length '((Vector))]))
  15635. (define type-predicates
  15636. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15637. (define (tag-value v)
  15638. (cond [(boolean? v) (Tagged v 'Boolean)]
  15639. [(fixnum? v) (Tagged v 'Integer)]
  15640. [(procedure? v) (Tagged v 'Procedure)]
  15641. [(vector? v) (Tagged v 'Vector)]
  15642. [(void? v) (Tagged v 'Void)]
  15643. [else (error 'tag-value "unidentified value ~a" v)]))
  15644. (define (check-tag val expected ast)
  15645. (define tag (Tagged-tag val))
  15646. (unless (eq? tag expected)
  15647. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  15648. \end{lstlisting}
  15649. \fi}
  15650. {\if\edition\pythonEd
  15651. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15652. class InterpLdyn(InterpLlambda):
  15653. def tag(self, v):
  15654. if v is True or v is False:
  15655. return Tagged(v, 'bool')
  15656. elif isinstance(v, int):
  15657. return Tagged(v, 'int')
  15658. elif isinstance(v, Function):
  15659. return Tagged(v, 'function')
  15660. elif isinstance(v, tuple):
  15661. return Tagged(v, 'tuple')
  15662. elif isinstance(v, type(None)):
  15663. return Tagged(v, 'none')
  15664. else:
  15665. raise Exception('tag: unexpected ' + repr(v))
  15666. def untag(self, v, expected_tag, ast):
  15667. match v:
  15668. case Tagged(val, tag) if tag == expected_tag:
  15669. return val
  15670. case _:
  15671. raise Exception('expected Tagged value with ' + expected_tag + ', not ' + ' ' + repr(v))
  15672. def apply_fun(self, fun, args, e):
  15673. f = self.untag(fun, 'function', e)
  15674. return super().apply_fun(f, args, e)
  15675. \end{lstlisting}
  15676. \fi}
  15677. \end{tcolorbox}
  15678. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  15679. \label{fig:interp-Ldyn-aux}
  15680. \end{figure}
  15681. \clearpage
  15682. \section{Representation of Tagged Values}
  15683. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  15684. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  15685. values at the bit level. Because almost every operation in \LangDyn{}
  15686. involves manipulating tagged values, the representation must be
  15687. efficient. Recall that all of our values are 64 bits. We shall steal
  15688. the 3 right-most bits to encode the tag. We use $001$ to identify
  15689. integers, $100$ for Booleans, $010$ for tuples, $011$ for procedures,
  15690. and $101$ for the void value\python{, \key{None}}. We define the following auxiliary
  15691. function for mapping types to tag codes.
  15692. {\if\edition\racketEd
  15693. \begin{align*}
  15694. \itm{tagof}(\key{Integer}) &= 001 \\
  15695. \itm{tagof}(\key{Boolean}) &= 100 \\
  15696. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  15697. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  15698. \itm{tagof}(\key{Void}) &= 101
  15699. \end{align*}
  15700. \fi}
  15701. {\if\edition\pythonEd
  15702. \begin{align*}
  15703. \itm{tagof}(\key{IntType()}) &= 001 \\
  15704. \itm{tagof}(\key{BoolType()}) &= 100 \\
  15705. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  15706. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  15707. \itm{tagof}(\key{type(None)}) &= 101
  15708. \end{align*}
  15709. \fi}
  15710. This stealing of 3 bits comes at some price: integers are now restricted
  15711. to the range from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  15712. affect tuples and procedures because those values are addresses, and
  15713. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  15714. they are always $000$. Thus, we do not lose information by overwriting
  15715. the rightmost 3 bits with the tag and we can simply zero-out the tag
  15716. to recover the original address.
  15717. To make tagged values into first-class entities, we can give them a
  15718. type, called \racket{\code{Any}}\python{\code{AnyType()}}, and define
  15719. operations such as \code{Inject} and \code{Project} for creating and
  15720. using them, yielding the statically typed \LangAny{} intermediate
  15721. language. We describe how to compile \LangDyn{} to \LangAny{} in
  15722. Section~\ref{sec:compile-r7} but first we describe the \LangAny{}
  15723. language in greater detail.
  15724. \section{The \LangAny{} Language}
  15725. \label{sec:Rany-lang}
  15726. \newcommand{\LanyASTRacket}{
  15727. \begin{array}{lcl}
  15728. \Type &::= & \ANYTY \\
  15729. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  15730. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  15731. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  15732. \itm{op} &::= & \code{any-vector-length}
  15733. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15734. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15735. \MID \code{procedure?} \MID \code{void?} \\
  15736. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  15737. \end{array}
  15738. }
  15739. \newcommand{\LanyASTPython}{
  15740. \begin{array}{lcl}
  15741. \Type &::= & \key{AnyType()} \\
  15742. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  15743. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  15744. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  15745. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15746. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\INT{n}\RS}\\
  15747. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS}
  15748. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  15749. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  15750. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  15751. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  15752. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  15753. \end{array}
  15754. }
  15755. \begin{figure}[tp]
  15756. \centering
  15757. \begin{tcolorbox}[colback=white]
  15758. \small
  15759. {\if\edition\racketEd
  15760. \[
  15761. \begin{array}{l}
  15762. \gray{\LintOpAST} \\ \hline
  15763. \gray{\LvarASTRacket{}} \\ \hline
  15764. \gray{\LifASTRacket{}} \\ \hline
  15765. \gray{\LwhileASTRacket{}} \\ \hline
  15766. \gray{\LtupASTRacket{}} \\ \hline
  15767. \gray{\LfunASTRacket} \\ \hline
  15768. \gray{\LlambdaASTRacket} \\ \hline
  15769. \LanyASTRacket \\
  15770. \begin{array}{lcl}
  15771. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15772. \end{array}
  15773. \end{array}
  15774. \]
  15775. \fi}
  15776. {\if\edition\pythonEd
  15777. \[
  15778. \begin{array}{l}
  15779. \gray{\LintASTPython} \\ \hline
  15780. \gray{\LvarASTPython{}} \\ \hline
  15781. \gray{\LifASTPython{}} \\ \hline
  15782. \gray{\LwhileASTPython{}} \\ \hline
  15783. \gray{\LtupASTPython{}} \\ \hline
  15784. \gray{\LfunASTPython} \\ \hline
  15785. \gray{\LlambdaASTPython} \\ \hline
  15786. \LanyASTPython \\
  15787. \begin{array}{lcl}
  15788. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15789. \end{array}
  15790. \end{array}
  15791. \]
  15792. \fi}
  15793. \end{tcolorbox}
  15794. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Llam-syntax}).}
  15795. \label{fig:Lany-syntax}
  15796. \end{figure}
  15797. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Lany-syntax}.
  15798. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  15799. %% Figure~\ref{fig:Lany-concrete-syntax}.)}
  15800. The $\INJECT{e}{T}$ form
  15801. converts the value produced by expression $e$ of type $T$ into a
  15802. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  15803. produced by expression $e$ into a value of type $T$ or halts the
  15804. program if the type tag does not match $T$.
  15805. %
  15806. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  15807. restricted to a flat type $\FType$, which simplifies the
  15808. implementation and corresponds with the needs for compiling \LangDyn{}.
  15809. The \racket{\code{any-vector}} operators
  15810. \python{\code{any\_tuple\_load} and \code{any\_len}}
  15811. adapt the tuple operations so that they can be applied to a value of
  15812. type \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  15813. tuple operations in that the index is not restricted to be a literal
  15814. integer in the grammar but is allowed to be any expression.
  15815. \racket{The type predicates such as
  15816. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  15817. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  15818. the predicate and they return {\FALSE} otherwise.}
  15819. The type checker for \LangAny{} is shown in
  15820. Figure~\ref{fig:type-check-Lany}
  15821. %
  15822. \racket{ and uses the auxiliary functions in
  15823. Figure~\ref{fig:type-check-Lany-aux}}.
  15824. %
  15825. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Lany} and
  15826. its auxiliary functions are in Figure~\ref{fig:interp-Lany-aux}.
  15827. \begin{figure}[btp]
  15828. \begin{tcolorbox}[colback=white]
  15829. {\if\edition\racketEd
  15830. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15831. (define type-check-Lany-class
  15832. (class type-check-Llambda-class
  15833. (super-new)
  15834. (inherit check-type-equal?)
  15835. (define/override (type-check-exp env)
  15836. (lambda (e)
  15837. (define recur (type-check-exp env))
  15838. (match e
  15839. [(Inject e1 ty)
  15840. (unless (flat-ty? ty)
  15841. (error 'type-check "may only inject from flat type, not ~a" ty))
  15842. (define-values (new-e1 e-ty) (recur e1))
  15843. (check-type-equal? e-ty ty e)
  15844. (values (Inject new-e1 ty) 'Any)]
  15845. [(Project e1 ty)
  15846. (unless (flat-ty? ty)
  15847. (error 'type-check "may only project to flat type, not ~a" ty))
  15848. (define-values (new-e1 e-ty) (recur e1))
  15849. (check-type-equal? e-ty 'Any e)
  15850. (values (Project new-e1 ty) ty)]
  15851. [(Prim 'any-vector-length (list e1))
  15852. (define-values (e1^ t1) (recur e1))
  15853. (check-type-equal? t1 'Any e)
  15854. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  15855. [(Prim 'any-vector-ref (list e1 e2))
  15856. (define-values (e1^ t1) (recur e1))
  15857. (define-values (e2^ t2) (recur e2))
  15858. (check-type-equal? t1 'Any e)
  15859. (check-type-equal? t2 'Integer e)
  15860. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  15861. [(Prim 'any-vector-set! (list e1 e2 e3))
  15862. (define-values (e1^ t1) (recur e1))
  15863. (define-values (e2^ t2) (recur e2))
  15864. (define-values (e3^ t3) (recur e3))
  15865. (check-type-equal? t1 'Any e)
  15866. (check-type-equal? t2 'Integer e)
  15867. (check-type-equal? t3 'Any e)
  15868. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  15869. [(Prim pred (list e1))
  15870. #:when (set-member? (type-predicates) pred)
  15871. (define-values (new-e1 e-ty) (recur e1))
  15872. (check-type-equal? e-ty 'Any e)
  15873. (values (Prim pred (list new-e1)) 'Boolean)]
  15874. [(Prim 'eq? (list arg1 arg2))
  15875. (define-values (e1 t1) (recur arg1))
  15876. (define-values (e2 t2) (recur arg2))
  15877. (match* (t1 t2)
  15878. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  15879. [(other wise) (check-type-equal? t1 t2 e)])
  15880. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  15881. [else ((super type-check-exp env) e)])))
  15882. ))
  15883. \end{lstlisting}
  15884. \fi}
  15885. {\if\edition\pythonEd
  15886. \begin{lstlisting}
  15887. class TypeCheckLany(TypeCheckLlambda):
  15888. def type_check_exp(self, e, env):
  15889. match e:
  15890. case Inject(value, typ):
  15891. self.check_exp(value, typ, env)
  15892. return AnyType()
  15893. case Project(value, typ):
  15894. self.check_exp(value, AnyType(), env)
  15895. return typ
  15896. case Call(Name('any_tuple_load'), [tup, index]):
  15897. self.check_exp(tup, AnyType(), env)
  15898. self.check_exp(index, IntType(), env)
  15899. return AnyType()
  15900. case Call(Name('any_len'), [tup]):
  15901. self.check_exp(tup, AnyType(), env)
  15902. return IntType()
  15903. case Call(Name('arity'), [fun]):
  15904. ty = self.type_check_exp(fun, env)
  15905. match ty:
  15906. case FunctionType(ps, rt):
  15907. return IntType()
  15908. case TupleType([FunctionType(ps,rs)]):
  15909. return IntType()
  15910. case _:
  15911. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  15912. case Call(Name('make_any'), [value, tag]):
  15913. self.type_check_exp(value, env)
  15914. self.check_exp(tag, IntType(), env)
  15915. return AnyType()
  15916. case AnnLambda(params, returns, body):
  15917. new_env = {x:t for (x,t) in env.items()}
  15918. for (x,t) in params:
  15919. new_env[x] = t
  15920. return_t = self.type_check_exp(body, new_env)
  15921. self.check_type_equal(returns, return_t, e)
  15922. return FunctionType([t for (x,t) in params], return_t)
  15923. case _:
  15924. return super().type_check_exp(e, env)
  15925. \end{lstlisting}
  15926. \fi}
  15927. \end{tcolorbox}
  15928. \caption{Type checker for the \LangAny{} language.}
  15929. \label{fig:type-check-Lany}
  15930. \end{figure}
  15931. {\if\edition\racketEd
  15932. \begin{figure}[tbp]
  15933. \begin{tcolorbox}[colback=white]
  15934. \begin{lstlisting}
  15935. (define/override (operator-types)
  15936. (append
  15937. '((integer? . ((Any) . Boolean))
  15938. (vector? . ((Any) . Boolean))
  15939. (procedure? . ((Any) . Boolean))
  15940. (void? . ((Any) . Boolean)))
  15941. (super operator-types)))
  15942. (define/public (type-predicates)
  15943. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15944. (define/public (flat-ty? ty)
  15945. (match ty
  15946. [(or `Integer `Boolean `Void) #t]
  15947. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  15948. ['(Vectorof Any) #t]
  15949. [`(,ts ... -> ,rt)
  15950. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  15951. [else #f]))
  15952. \end{lstlisting}
  15953. \end{tcolorbox}
  15954. \caption{Auxiliary methods for type checking \LangAny{}.}
  15955. \label{fig:type-check-Lany-aux}
  15956. \end{figure}
  15957. \fi}
  15958. \begin{figure}[btp]
  15959. \begin{tcolorbox}[colback=white]
  15960. {\if\edition\racketEd
  15961. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15962. (define interp-Lany-class
  15963. (class interp-Llambda-class
  15964. (super-new)
  15965. (define/override (interp-op op)
  15966. (match op
  15967. ['boolean? (match-lambda
  15968. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  15969. [else #f])]
  15970. ['integer? (match-lambda
  15971. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  15972. [else #f])]
  15973. ['vector? (match-lambda
  15974. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  15975. [else #f])]
  15976. ['procedure? (match-lambda
  15977. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  15978. [else #f])]
  15979. ['eq? (match-lambda*
  15980. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  15981. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  15982. [ls (apply (super interp-op op) ls)])]
  15983. ['any-vector-ref (lambda (v i)
  15984. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  15985. ['any-vector-set! (lambda (v i a)
  15986. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  15987. ['any-vector-length (lambda (v)
  15988. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  15989. [else (super interp-op op)]))
  15990. (define/override ((interp-exp env) e)
  15991. (define recur (interp-exp env))
  15992. (match e
  15993. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  15994. [(Project e ty2) (apply-project (recur e) ty2)]
  15995. [else ((super interp-exp env) e)]))
  15996. ))
  15997. (define (interp-Lany p)
  15998. (send (new interp-Lany-class) interp-program p))
  15999. \end{lstlisting}
  16000. \fi}
  16001. {\if\edition\pythonEd
  16002. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16003. class InterpLany(InterpLlambda):
  16004. def interp_exp(self, e, env):
  16005. match e:
  16006. case Inject(value, typ):
  16007. v = self.interp_exp(value, env)
  16008. return Tagged(v, self.type_to_tag(typ))
  16009. case Project(value, typ):
  16010. v = self.interp_exp(value, env)
  16011. match v:
  16012. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  16013. return val
  16014. case _:
  16015. raise Exception('interp project to ' + repr(typ) \
  16016. + ' unexpected ' + repr(v))
  16017. case Call(Name('any_tuple_load'), [tup, index]):
  16018. tv = self.interp_exp(tup, env)
  16019. n = self.interp_exp(index, env)
  16020. match tv:
  16021. case Tagged(v, tag):
  16022. return v[n]
  16023. case _:
  16024. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  16025. case Call(Name('any_len'), [value]):
  16026. v = self.interp_exp(value, env)
  16027. match v:
  16028. case Tagged(value, tag):
  16029. return len(value)
  16030. case _:
  16031. raise Exception('interp any_len unexpected ' + repr(v))
  16032. case Call(Name('arity'), [fun]):
  16033. f = self.interp_exp(fun, env)
  16034. return self.arity(f)
  16035. case _:
  16036. return super().interp_exp(e, env)
  16037. \end{lstlisting}
  16038. \fi}
  16039. \end{tcolorbox}
  16040. \caption{Interpreter for \LangAny{}.}
  16041. \label{fig:interp-Lany}
  16042. \end{figure}
  16043. \begin{figure}[tbp]
  16044. \begin{tcolorbox}[colback=white]
  16045. {\if\edition\racketEd
  16046. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16047. (define/public (apply-inject v tg) (Tagged v tg))
  16048. (define/public (apply-project v ty2)
  16049. (define tag2 (any-tag ty2))
  16050. (match v
  16051. [(Tagged v1 tag1)
  16052. (cond
  16053. [(eq? tag1 tag2)
  16054. (match ty2
  16055. [`(Vector ,ts ...)
  16056. (define l1 ((interp-op 'vector-length) v1))
  16057. (cond
  16058. [(eq? l1 (length ts)) v1]
  16059. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  16060. l1 (length ts))])]
  16061. [`(,ts ... -> ,rt)
  16062. (match v1
  16063. [`(function ,xs ,body ,env)
  16064. (cond [(eq? (length xs) (length ts)) v1]
  16065. [else
  16066. (error 'apply-project "arity mismatch ~a != ~a"
  16067. (length xs) (length ts))])]
  16068. [else (error 'apply-project "expected function not ~a" v1)])]
  16069. [else v1])]
  16070. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16071. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16072. \end{lstlisting}
  16073. \fi}
  16074. {\if\edition\pythonEd
  16075. \begin{lstlisting}
  16076. class InterpLany(InterpLlambda):
  16077. def type_to_tag(self, typ):
  16078. match typ:
  16079. case FunctionType(params, rt):
  16080. return 'function'
  16081. case TupleType(fields):
  16082. return 'tuple'
  16083. case t if t == int:
  16084. return 'int'
  16085. case t if t == bool:
  16086. return 'bool'
  16087. case IntType():
  16088. return 'int'
  16089. case BoolType():
  16090. return 'int'
  16091. case _:
  16092. raise Exception('type_to_tag unexpected ' + repr(typ))
  16093. def arity(self, v):
  16094. match v:
  16095. case Function(name, params, body, env):
  16096. return len(params)
  16097. case ClosureTuple(args, arity):
  16098. return arity
  16099. case _:
  16100. raise Exception('Lany arity unexpected ' + repr(v))
  16101. \end{lstlisting}
  16102. \fi}
  16103. \end{tcolorbox}
  16104. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16105. \label{fig:interp-Lany-aux}
  16106. \end{figure}
  16107. \clearpage
  16108. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16109. \label{sec:compile-r7}
  16110. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16111. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  16112. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  16113. is that given any subexpression $e$ in the \LangDyn{} program, the
  16114. pass will produce an expression $e'$ in \LangAny{} that has type
  16115. \ANYTY{}. For example, the first row in
  16116. Figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  16117. \TRUE{}, which must be injected to produce an expression of type
  16118. \ANYTY{}.
  16119. %
  16120. The second row of Figure~\ref{fig:compile-r7-Lany}, the compilation of
  16121. addition, is representative of compilation for many primitive
  16122. operations: the arguments have type \ANYTY{} and must be projected to
  16123. \INTTYPE{} before the addition can be performed.
  16124. The compilation of \key{lambda} (third row of
  16125. Figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  16126. produce type annotations: we simply use \ANYTY{}.
  16127. %
  16128. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16129. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16130. this pass has to account for some differences in behavior between
  16131. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16132. permissive than \LangAny{} regarding what kind of values can be used
  16133. in various places. For example, the condition of an \key{if} does
  16134. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16135. of the same type (in that case the result is \code{\#f}).}
  16136. \begin{figure}[btp]
  16137. \centering
  16138. \begin{tcolorbox}[colback=white]
  16139. {\if\edition\racketEd
  16140. \begin{tabular}{lll}
  16141. \begin{minipage}{0.27\textwidth}
  16142. \begin{lstlisting}
  16143. #t
  16144. \end{lstlisting}
  16145. \end{minipage}
  16146. &
  16147. $\Rightarrow$
  16148. &
  16149. \begin{minipage}{0.65\textwidth}
  16150. \begin{lstlisting}
  16151. (inject #t Boolean)
  16152. \end{lstlisting}
  16153. \end{minipage}
  16154. \\[2ex]\hline
  16155. \begin{minipage}{0.27\textwidth}
  16156. \begin{lstlisting}
  16157. (+ |$e_1$| |$e_2$|)
  16158. \end{lstlisting}
  16159. \end{minipage}
  16160. &
  16161. $\Rightarrow$
  16162. &
  16163. \begin{minipage}{0.65\textwidth}
  16164. \begin{lstlisting}
  16165. (inject
  16166. (+ (project |$e'_1$| Integer)
  16167. (project |$e'_2$| Integer))
  16168. Integer)
  16169. \end{lstlisting}
  16170. \end{minipage}
  16171. \\[2ex]\hline
  16172. \begin{minipage}{0.27\textwidth}
  16173. \begin{lstlisting}
  16174. (lambda (|$x_1 \ldots$|) |$e$|)
  16175. \end{lstlisting}
  16176. \end{minipage}
  16177. &
  16178. $\Rightarrow$
  16179. &
  16180. \begin{minipage}{0.65\textwidth}
  16181. \begin{lstlisting}
  16182. (inject
  16183. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  16184. (Any|$\ldots$|Any -> Any))
  16185. \end{lstlisting}
  16186. \end{minipage}
  16187. \\[2ex]\hline
  16188. \begin{minipage}{0.27\textwidth}
  16189. \begin{lstlisting}
  16190. (|$e_0$| |$e_1 \ldots e_n$|)
  16191. \end{lstlisting}
  16192. \end{minipage}
  16193. &
  16194. $\Rightarrow$
  16195. &
  16196. \begin{minipage}{0.65\textwidth}
  16197. \begin{lstlisting}
  16198. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16199. \end{lstlisting}
  16200. \end{minipage}
  16201. \\[2ex]\hline
  16202. \begin{minipage}{0.27\textwidth}
  16203. \begin{lstlisting}
  16204. (vector-ref |$e_1$| |$e_2$|)
  16205. \end{lstlisting}
  16206. \end{minipage}
  16207. &
  16208. $\Rightarrow$
  16209. &
  16210. \begin{minipage}{0.65\textwidth}
  16211. \begin{lstlisting}
  16212. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  16213. \end{lstlisting}
  16214. \end{minipage}
  16215. \\[2ex]\hline
  16216. \begin{minipage}{0.27\textwidth}
  16217. \begin{lstlisting}
  16218. (if |$e_1$| |$e_2$| |$e_3$|)
  16219. \end{lstlisting}
  16220. \end{minipage}
  16221. &
  16222. $\Rightarrow$
  16223. &
  16224. \begin{minipage}{0.65\textwidth}
  16225. \begin{lstlisting}
  16226. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16227. \end{lstlisting}
  16228. \end{minipage}
  16229. \\[2ex]\hline
  16230. \begin{minipage}{0.27\textwidth}
  16231. \begin{lstlisting}
  16232. (eq? |$e_1$| |$e_2$|)
  16233. \end{lstlisting}
  16234. \end{minipage}
  16235. &
  16236. $\Rightarrow$
  16237. &
  16238. \begin{minipage}{0.65\textwidth}
  16239. \begin{lstlisting}
  16240. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16241. \end{lstlisting}
  16242. \end{minipage}
  16243. \\[2ex]\hline
  16244. \begin{minipage}{0.27\textwidth}
  16245. \begin{lstlisting}
  16246. (not |$e_1$|)
  16247. \end{lstlisting}
  16248. \end{minipage}
  16249. &
  16250. $\Rightarrow$
  16251. &
  16252. \begin{minipage}{0.65\textwidth}
  16253. \begin{lstlisting}
  16254. (if (eq? |$e'_1$| (inject #f Boolean))
  16255. (inject #t Boolean) (inject #f Boolean))
  16256. \end{lstlisting}
  16257. \end{minipage}
  16258. \end{tabular}
  16259. \fi}
  16260. {\if\edition\pythonEd
  16261. \begin{tabular}{lll}
  16262. \begin{minipage}{0.22\textwidth}
  16263. \begin{lstlisting}
  16264. True
  16265. \end{lstlisting}
  16266. \end{minipage}
  16267. &
  16268. $\Rightarrow$
  16269. &
  16270. \begin{minipage}{0.7\textwidth}
  16271. \begin{lstlisting}
  16272. Inject(True, BoolType())
  16273. \end{lstlisting}
  16274. \end{minipage}
  16275. \\[2ex]\hline
  16276. \begin{minipage}{0.22\textwidth}
  16277. \begin{lstlisting}
  16278. |$e_1$| + |$e_2$|
  16279. \end{lstlisting}
  16280. \end{minipage}
  16281. &
  16282. $\Rightarrow$
  16283. &
  16284. \begin{minipage}{0.7\textwidth}
  16285. \begin{lstlisting}
  16286. Inject(Project(|$e'_1$|, IntType())
  16287. + Project(|$e'_2$|, IntType()),
  16288. IntType())
  16289. \end{lstlisting}
  16290. \end{minipage}
  16291. \\[2ex]\hline
  16292. \begin{minipage}{0.22\textwidth}
  16293. \begin{lstlisting}
  16294. lambda |$x_1 \ldots$|: |$e$|
  16295. \end{lstlisting}
  16296. \end{minipage}
  16297. &
  16298. $\Rightarrow$
  16299. &
  16300. \begin{minipage}{0.7\textwidth}
  16301. \begin{lstlisting}
  16302. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  16303. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16304. \end{lstlisting}
  16305. \end{minipage}
  16306. \\[2ex]\hline
  16307. \begin{minipage}{0.22\textwidth}
  16308. \begin{lstlisting}
  16309. |$e_0$|(|$e_1 \ldots e_n$|)
  16310. \end{lstlisting}
  16311. \end{minipage}
  16312. &
  16313. $\Rightarrow$
  16314. &
  16315. \begin{minipage}{0.7\textwidth}
  16316. \begin{lstlisting}
  16317. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16318. AnyType())), |$e'_1, \ldots, e'_n$|)
  16319. \end{lstlisting}
  16320. \end{minipage}
  16321. \\[2ex]\hline
  16322. \begin{minipage}{0.22\textwidth}
  16323. \begin{lstlisting}
  16324. |$e_1$|[|$e_2$|]
  16325. \end{lstlisting}
  16326. \end{minipage}
  16327. &
  16328. $\Rightarrow$
  16329. &
  16330. \begin{minipage}{0.7\textwidth}
  16331. \begin{lstlisting}
  16332. Call(Name('any_tuple_load'),
  16333. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  16334. \end{lstlisting}
  16335. \end{minipage}
  16336. %% \begin{minipage}{0.22\textwidth}
  16337. %% \begin{lstlisting}
  16338. %% |$e_2$| if |$e_1$| else |$e_3$|
  16339. %% \end{lstlisting}
  16340. %% \end{minipage}
  16341. %% &
  16342. %% $\Rightarrow$
  16343. %% &
  16344. %% \begin{minipage}{0.7\textwidth}
  16345. %% \begin{lstlisting}
  16346. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16347. %% \end{lstlisting}
  16348. %% \end{minipage}
  16349. %% \\[2ex]\hline
  16350. %% \begin{minipage}{0.22\textwidth}
  16351. %% \begin{lstlisting}
  16352. %% (eq? |$e_1$| |$e_2$|)
  16353. %% \end{lstlisting}
  16354. %% \end{minipage}
  16355. %% &
  16356. %% $\Rightarrow$
  16357. %% &
  16358. %% \begin{minipage}{0.7\textwidth}
  16359. %% \begin{lstlisting}
  16360. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16361. %% \end{lstlisting}
  16362. %% \end{minipage}
  16363. %% \\[2ex]\hline
  16364. %% \begin{minipage}{0.22\textwidth}
  16365. %% \begin{lstlisting}
  16366. %% (not |$e_1$|)
  16367. %% \end{lstlisting}
  16368. %% \end{minipage}
  16369. %% &
  16370. %% $\Rightarrow$
  16371. %% &
  16372. %% \begin{minipage}{0.7\textwidth}
  16373. %% \begin{lstlisting}
  16374. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16375. %% (inject #t Boolean) (inject #f Boolean))
  16376. %% \end{lstlisting}
  16377. %% \end{minipage}
  16378. %% \\[2ex]\hline
  16379. \end{tabular}
  16380. \fi}
  16381. \end{tcolorbox}
  16382. \caption{Cast Insertion}
  16383. \label{fig:compile-r7-Lany}
  16384. \end{figure}
  16385. \section{Reveal Casts}
  16386. \label{sec:reveal-casts-Lany}
  16387. % TODO: define R'_6
  16388. In the \code{reveal\_casts} pass we recommend compiling \code{Project}
  16389. into a conditional expression that checks whether the value's tag
  16390. matches the target type; if it does, the value is converted to a value
  16391. of the target type by removing the tag; if it does not, the program
  16392. exits.
  16393. %
  16394. {\if\edition\racketEd
  16395. %
  16396. To perform these actions we need a new primitive operation,
  16397. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16398. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16399. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16400. underlying value from a tagged value. The \code{ValueOf} form
  16401. includes the type for the underlying value which is used by the type
  16402. checker. Finally, the \code{Exit} form ends the execution of the
  16403. program.
  16404. %
  16405. \fi}
  16406. %
  16407. {\if\edition\pythonEd
  16408. %
  16409. To perform these actions we need the \code{exit} function (from the C
  16410. standard library) and two new AST classes: \code{TagOf} and
  16411. \code{ValueOf}. The \code{exit} function ends the execution of the
  16412. program. The \code{TagOf} operation retrieves the type tag from a
  16413. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16414. the underlying value from a tagged value. The \code{ValueOf}
  16415. operation includes the type for the underlying value which is used by
  16416. the type checker.
  16417. %
  16418. \fi}
  16419. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16420. \code{Project} can be translated as follows.
  16421. \begin{center}
  16422. \begin{minipage}{1.0\textwidth}
  16423. {\if\edition\racketEd
  16424. \begin{lstlisting}
  16425. (Project |$e$| |$\FType$|)
  16426. |$\Rightarrow$|
  16427. (Let |$\itm{tmp}$| |$e'$|
  16428. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16429. (Int |$\itm{tagof}(\FType)$|)))
  16430. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16431. (Exit)))
  16432. \end{lstlisting}
  16433. \fi}
  16434. {\if\edition\pythonEd
  16435. \begin{lstlisting}
  16436. Project(|$e$|, |$\FType$|)
  16437. |$\Rightarrow$|
  16438. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16439. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16440. [Constant(|$\itm{tagof}(\FType)$|)]),
  16441. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16442. Call(Name('exit'), [])))
  16443. \end{lstlisting}
  16444. \fi}
  16445. \end{minipage}
  16446. \end{center}
  16447. If the target type of the projection is a tuple or function type, then
  16448. there is a bit more work to do. For tuples, check that the length of
  16449. the tuple type matches the length of the tuple. For functions, check
  16450. that the number of parameters in the function type matches the
  16451. function's arity.
  16452. Regarding \code{Inject}, we recommend compiling it to a slightly
  16453. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  16454. takes a tag instead of a type.
  16455. \begin{center}
  16456. \begin{minipage}{1.0\textwidth}
  16457. {\if\edition\racketEd
  16458. \begin{lstlisting}
  16459. (Inject |$e$| |$\FType$|)
  16460. |$\Rightarrow$|
  16461. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16462. \end{lstlisting}
  16463. \fi}
  16464. {\if\edition\pythonEd
  16465. \begin{lstlisting}
  16466. Inject(|$e$|, |$\FType$|)
  16467. |$\Rightarrow$|
  16468. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16469. \end{lstlisting}
  16470. \fi}
  16471. \end{minipage}
  16472. \end{center}
  16473. {\if\edition\pythonEd
  16474. %
  16475. The introduction of \code{make\_any} makes it difficult to use
  16476. bidirectional type checking because we no longer have an expected type
  16477. to use for type checking the expression $e'$. Thus, we run into
  16478. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16479. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16480. annotated lambda) whose parameters have type annotations and that
  16481. records the return type.
  16482. %
  16483. \fi}
  16484. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16485. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16486. translation of \code{Project}.}
  16487. {\if\edition\racketEd
  16488. The \code{any-vector-ref} and \code{any-vector-set!} operations
  16489. combine the projection action with the vector operation. Also, the
  16490. read and write operations allow arbitrary expressions for the index so
  16491. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Lany})
  16492. cannot guarantee that the index is within bounds. Thus, we insert code
  16493. to perform bounds checking at runtime. The translation for
  16494. \code{any-vector-ref} is as follows and the other two operations are
  16495. translated in a similar way.
  16496. \begin{center}
  16497. \begin{minipage}{0.95\textwidth}
  16498. \begin{lstlisting}
  16499. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  16500. |$\Rightarrow$|
  16501. (Let |$v$| |$e'_1$|
  16502. (Let |$i$| |$e'_2$|
  16503. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  16504. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  16505. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  16506. (Exit))
  16507. (Exit))))
  16508. \end{lstlisting}
  16509. \end{minipage}
  16510. \end{center}
  16511. \fi}
  16512. %
  16513. {\if\edition\pythonEd
  16514. %
  16515. The \code{any\_tuple\_load} operation combines the projection action
  16516. with the load operation. Also, the load operation allows arbitrary
  16517. expressions for the index so the type checker for \LangAny{}
  16518. (Figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  16519. within bounds. Thus, we insert code to perform bounds checking at
  16520. runtime. The translation for \code{any\_tuple\_load} is as follows.
  16521. \begin{lstlisting}
  16522. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  16523. |$\Rightarrow$|
  16524. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  16525. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  16526. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  16527. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  16528. Call(Name('exit'), [])),
  16529. Call(Name('exit'), [])))
  16530. \end{lstlisting}
  16531. \fi}
  16532. {\if\edition\pythonEd
  16533. \section{Assignment Conversion}
  16534. \label{sec:convert-assignments-Lany}
  16535. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16536. \code{AnnLambda} AST classes.
  16537. \section{Closure Conversion}
  16538. \label{sec:closure-conversion-Lany}
  16539. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16540. \code{AnnLambda} AST classes.
  16541. \fi}
  16542. \section{Remove Complex Operands}
  16543. \label{sec:rco-Lany}
  16544. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  16545. expressions. The subexpression of \code{ValueOf} must be atomic.}
  16546. %
  16547. \python{The \code{ValueOf} and \code{TagOf} operations are both
  16548. complex expressions. Their subexpressions must be atomic.}
  16549. \section{Explicate Control and \LangCAny{}}
  16550. \label{sec:explicate-Lany}
  16551. The output of \code{explicate\_control} is the \LangCAny{} language
  16552. whose syntax is defined in Figure~\ref{fig:c5-syntax}.
  16553. %
  16554. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  16555. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  16556. note that the index argument of \code{vector-ref} and
  16557. \code{vector-set!} is an $\Atm$ instead of an integer, as it was in
  16558. \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  16559. %
  16560. \python{
  16561. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  16562. and \code{explicate\_pred} as appropriately to handle the new expressions
  16563. in \LangCAny{}.
  16564. }
  16565. \newcommand{\CanyASTPython}{
  16566. \begin{array}{lcl}
  16567. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  16568. &\MID& \key{TagOf}\LP \Atm \RP
  16569. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  16570. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  16571. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  16572. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  16573. \end{array}
  16574. }
  16575. \newcommand{\CanyASTRacket}{
  16576. \begin{array}{lcl}
  16577. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  16578. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  16579. &\MID& \VALUEOF{\Atm}{\FType} \\
  16580. \Tail &::= & \LP\key{Exit}\RP
  16581. \end{array}
  16582. }
  16583. \begin{figure}[tp]
  16584. \begin{tcolorbox}[colback=white]
  16585. \small
  16586. {\if\edition\racketEd
  16587. \[
  16588. \begin{array}{l}
  16589. \gray{\CvarASTRacket} \\ \hline
  16590. \gray{\CifASTRacket} \\ \hline
  16591. \gray{\CloopASTRacket} \\ \hline
  16592. \gray{\CtupASTRacket} \\ \hline
  16593. \gray{\CfunASTRacket} \\ \hline
  16594. \gray{\ClambdaASTRacket} \\ \hline
  16595. \CanyASTRacket \\
  16596. \begin{array}{lcl}
  16597. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  16598. \end{array}
  16599. \end{array}
  16600. \]
  16601. \fi}
  16602. {\if\edition\pythonEd
  16603. \[
  16604. \begin{array}{l}
  16605. \gray{\CifASTPython} \\ \hline
  16606. \gray{\CtupASTPython} \\ \hline
  16607. \gray{\CfunASTPython} \\ \hline
  16608. \gray{\ClambdaASTPython} \\ \hline
  16609. \CanyASTPython \\
  16610. \begin{array}{lcl}
  16611. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16612. \end{array}
  16613. \end{array}
  16614. \]
  16615. \fi}
  16616. \end{tcolorbox}
  16617. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:Clam-syntax}).}
  16618. \label{fig:c5-syntax}
  16619. \end{figure}
  16620. \section{Select Instructions}
  16621. \label{sec:select-Lany}
  16622. In the \code{select\_instructions} pass we translate the primitive
  16623. operations on the \ANYTY{} type to x86 instructions that manipulate
  16624. the 3 tag bits of the tagged value. In the following descriptions,
  16625. given an atom $e$ we use a primed variable $e'$ to refer to the result
  16626. of translating $e$ into an x86 argument.
  16627. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  16628. We recommend compiling the
  16629. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  16630. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  16631. shifts the destination to the left by the number of bits specified its
  16632. source argument (in this case $3$, the length of the tag) and it
  16633. preserves the sign of the integer. We use the \key{orq} instruction to
  16634. combine the tag and the value to form the tagged value. \\
  16635. %
  16636. {\if\edition\racketEd
  16637. \begin{lstlisting}
  16638. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16639. |$\Rightarrow$|
  16640. movq |$e'$|, |\itm{lhs'}|
  16641. salq $3, |\itm{lhs'}|
  16642. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16643. \end{lstlisting}
  16644. \fi}
  16645. %
  16646. {\if\edition\pythonEd
  16647. \begin{lstlisting}
  16648. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16649. |$\Rightarrow$|
  16650. movq |$e'$|, |\itm{lhs'}|
  16651. salq $3, |\itm{lhs'}|
  16652. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16653. \end{lstlisting}
  16654. \fi}
  16655. %
  16656. The instruction selection for tuples and procedures is different
  16657. because their is no need to shift them to the left. The rightmost 3
  16658. bits are already zeros so we simply combine the value and the tag
  16659. using \key{orq}. \\
  16660. %
  16661. {\if\edition\racketEd
  16662. \begin{center}
  16663. \begin{minipage}{\textwidth}
  16664. \begin{lstlisting}
  16665. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16666. |$\Rightarrow$|
  16667. movq |$e'$|, |\itm{lhs'}|
  16668. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16669. \end{lstlisting}
  16670. \end{minipage}
  16671. \end{center}
  16672. \fi}
  16673. %
  16674. {\if\edition\pythonEd
  16675. \begin{lstlisting}
  16676. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16677. |$\Rightarrow$|
  16678. movq |$e'$|, |\itm{lhs'}|
  16679. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16680. \end{lstlisting}
  16681. \fi}
  16682. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  16683. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  16684. operation extracts the type tag from a value of type \ANYTY{}. The
  16685. type tag is the bottom three bits, so we obtain the tag by taking the
  16686. bitwise-and of the value with $111$ ($7$ in decimal).
  16687. %
  16688. {\if\edition\racketEd
  16689. \begin{lstlisting}
  16690. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  16691. |$\Rightarrow$|
  16692. movq |$e'$|, |\itm{lhs'}|
  16693. andq $7, |\itm{lhs'}|
  16694. \end{lstlisting}
  16695. \fi}
  16696. %
  16697. {\if\edition\pythonEd
  16698. \begin{lstlisting}
  16699. Assign([|\itm{lhs}|], TagOf(|$e$|))
  16700. |$\Rightarrow$|
  16701. movq |$e'$|, |\itm{lhs'}|
  16702. andq $7, |\itm{lhs'}|
  16703. \end{lstlisting}
  16704. \fi}
  16705. \paragraph{\code{ValueOf}}
  16706. The instructions for \key{ValueOf} also differ depending on whether
  16707. the type $T$ is a pointer (tuple or function) or not (integer or
  16708. Boolean). The following shows the instruction selection for integers
  16709. and Booleans. We produce an untagged value by shifting it to the
  16710. right by 3 bits.
  16711. %
  16712. {\if\edition\racketEd
  16713. \begin{lstlisting}
  16714. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16715. |$\Rightarrow$|
  16716. movq |$e'$|, |\itm{lhs'}|
  16717. sarq $3, |\itm{lhs'}|
  16718. \end{lstlisting}
  16719. \fi}
  16720. %
  16721. {\if\edition\pythonEd
  16722. \begin{lstlisting}
  16723. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16724. |$\Rightarrow$|
  16725. movq |$e'$|, |\itm{lhs'}|
  16726. sarq $3, |\itm{lhs'}|
  16727. \end{lstlisting}
  16728. \fi}
  16729. %
  16730. In the case for tuples and procedures, we zero-out the rightmost 3
  16731. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  16732. ($7$ in decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  16733. in decimal) which we \code{movq} into the destination $\itm{lhs'}$.
  16734. Finally, we apply \code{andq} with the tagged value to get the desired
  16735. result.
  16736. %
  16737. {\if\edition\racketEd
  16738. \begin{lstlisting}
  16739. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16740. |$\Rightarrow$|
  16741. movq $|$-8$|, |\itm{lhs'}|
  16742. andq |$e'$|, |\itm{lhs'}|
  16743. \end{lstlisting}
  16744. \fi}
  16745. %
  16746. {\if\edition\pythonEd
  16747. \begin{lstlisting}
  16748. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16749. |$\Rightarrow$|
  16750. movq $|$-8$|, |\itm{lhs'}|
  16751. andq |$e'$|, |\itm{lhs'}|
  16752. \end{lstlisting}
  16753. \fi}
  16754. %% \paragraph{Type Predicates} We leave it to the reader to
  16755. %% devise a sequence of instructions to implement the type predicates
  16756. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  16757. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  16758. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  16759. operation combines the effect of \code{ValueOf} with accessing the
  16760. length of a tuple from the tag stored at the zero index of the tuple.
  16761. {\if\edition\racketEd
  16762. \begin{lstlisting}
  16763. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  16764. |$\Longrightarrow$|
  16765. movq $|$-8$|, %r11
  16766. andq |$e_1'$|, %r11
  16767. movq 0(%r11), %r11
  16768. andq $126, %r11
  16769. sarq $1, %r11
  16770. movq %r11, |$\itm{lhs'}$|
  16771. \end{lstlisting}
  16772. \fi}
  16773. {\if\edition\pythonEd
  16774. \begin{lstlisting}
  16775. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  16776. |$\Longrightarrow$|
  16777. movq $|$-8$|, %r11
  16778. andq |$e_1'$|, %r11
  16779. movq 0(%r11), %r11
  16780. andq $126, %r11
  16781. sarq $1, %r11
  16782. movq %r11, |$\itm{lhs'}$|
  16783. \end{lstlisting}
  16784. \fi}
  16785. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  16786. This operation combines the effect of \code{ValueOf} with reading an
  16787. element of the tuple (see
  16788. Section~\ref{sec:select-instructions-gc}). However, the index may be
  16789. an arbitrary atom so instead of computing the offset at compile time,
  16790. we must generate instructions to compute the offset at runtime as
  16791. follows. Note the use of the new instruction \code{imulq}.
  16792. \begin{center}
  16793. \begin{minipage}{0.96\textwidth}
  16794. {\if\edition\racketEd
  16795. \begin{lstlisting}
  16796. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16797. |$\Longrightarrow$|
  16798. movq |$\neg 111$|, %r11
  16799. andq |$e_1'$|, %r11
  16800. movq |$e_2'$|, %rax
  16801. addq $1, %rax
  16802. imulq $8, %rax
  16803. addq %rax, %r11
  16804. movq 0(%r11) |$\itm{lhs'}$|
  16805. \end{lstlisting}
  16806. \fi}
  16807. %
  16808. {\if\edition\pythonEd
  16809. \begin{lstlisting}
  16810. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  16811. |$\Longrightarrow$|
  16812. movq $|$-8$|, %r11
  16813. andq |$e_1'$|, %r11
  16814. movq |$e_2'$|, %rax
  16815. addq $1, %rax
  16816. imulq $8, %rax
  16817. addq %rax, %r11
  16818. movq 0(%r11) |$\itm{lhs'}$|
  16819. \end{lstlisting}
  16820. \fi}
  16821. \end{minipage}
  16822. \end{center}
  16823. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  16824. %% The code generation for
  16825. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  16826. %% analogous to the above translation for reading from a tuple.
  16827. \section{Register Allocation for \LangAny{}}
  16828. \label{sec:register-allocation-Lany}
  16829. \index{subject}{register allocation}
  16830. There is an interesting interaction between tagged values and garbage
  16831. collection that has an impact on register allocation. A variable of
  16832. type \ANYTY{} might refer to a tuple and therefore it might be a root
  16833. that needs to be inspected and copied during garbage collection. Thus,
  16834. we need to treat variables of type \ANYTY{} in a similar way to
  16835. variables of tuple type for purposes of register allocation. In
  16836. particular,
  16837. \begin{itemize}
  16838. \item If a variable of type \ANYTY{} is live during a function call,
  16839. then it must be spilled. This can be accomplished by changing
  16840. \code{build\_interference} to mark all variables of type \ANYTY{}
  16841. that are live after a \code{callq} as interfering with all the
  16842. registers.
  16843. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  16844. the root stack instead of the normal procedure call stack.
  16845. \end{itemize}
  16846. Another concern regarding the root stack is that the garbage collector
  16847. needs to differentiate between (1) plain old pointers to tuples, (2) a
  16848. tagged value that points to a tuple, and (3) a tagged value that is
  16849. not a tuple. We enable this differentiation by choosing not to use the
  16850. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  16851. reserved for identifying plain old pointers to tuples. That way, if
  16852. one of the first three bits is set, then we have a tagged value and
  16853. inspecting the tag can differentiate between tuples ($010$) and the
  16854. other kinds of values.
  16855. %% \begin{exercise}\normalfont
  16856. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  16857. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  16858. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  16859. %% compiler on these new programs and all of your previously created test
  16860. %% programs.
  16861. %% \end{exercise}
  16862. \begin{exercise}\normalfont\normalsize
  16863. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  16864. Create tests for \LangDyn{} by adapting ten of your previous test programs
  16865. by removing type annotations. Add 5 more tests programs that
  16866. specifically rely on the language being dynamically typed. That is,
  16867. they should not be legal programs in a statically typed language, but
  16868. nevertheless, they should be valid \LangDyn{} programs that run to
  16869. completion without error.
  16870. \end{exercise}
  16871. \begin{figure}[p]
  16872. \begin{tcolorbox}[colback=white]
  16873. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16874. \node (Lfun) at (0,4) {\large \LangDyn{}};
  16875. \node (Lfun-2) at (3,4) {\large \LangDyn{}};
  16876. \node (Lfun-3) at (6,4) {\large \LangDyn{}};
  16877. \node (Lfun-4) at (9,4) {\large \LangDynFunRef{}};
  16878. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  16879. \node (Lfun-6) at (9,2) {\large \LangAnyFunRef{}};
  16880. \node (Lfun-7) at (6,2) {\large \LangAnyFunRef{}};
  16881. \node (F1-2) at (3,2) {\large \LangAnyFunRef{}};
  16882. \node (F1-3) at (0,2) {\large \LangAnyFunRef{}};
  16883. \node (F1-4) at (0,0) {\large \LangAnyAlloc{}};
  16884. \node (F1-5) at (3,0) {\large \LangAnyAlloc{}};
  16885. \node (F1-6) at (6,0) {\large \LangAnyAlloc{}};
  16886. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  16887. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16888. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16889. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16890. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16891. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16892. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16893. \path[->,bend left=15] (Lfun) edge [above] node
  16894. {\ttfamily\footnotesize shrink} (Lfun-2);
  16895. \path[->,bend left=15] (Lfun-2) edge [above] node
  16896. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16897. \path[->,bend left=15] (Lfun-3) edge [above] node
  16898. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  16899. \path[->,bend left=15] (Lfun-4) edge [left] node
  16900. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  16901. \path[->,bend left=15] (Lfun-5) edge [below] node
  16902. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  16903. \path[->,bend left=15] (Lfun-6) edge [below] node
  16904. {\ttfamily\footnotesize convert\_assign.} (Lfun-7);
  16905. \path[->,bend right=15] (Lfun-7) edge [above] node
  16906. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16907. \path[->,bend right=15] (F1-2) edge [above] node
  16908. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16909. \path[->,bend right=15] (F1-3) edge [right] node
  16910. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16911. \path[->,bend right=15] (F1-4) edge [below] node
  16912. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16913. \path[->,bend left=15] (F1-5) edge [above] node
  16914. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  16915. \path[->,bend left=15] (F1-6) edge [right] node
  16916. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16917. \path[->,bend left=15] (C3-2) edge [left] node
  16918. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16919. \path[->,bend right=15] (x86-2) edge [left] node
  16920. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16921. \path[->,bend right=15] (x86-2-1) edge [below] node
  16922. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16923. \path[->,bend right=15] (x86-2-2) edge [left] node
  16924. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16925. \path[->,bend left=15] (x86-3) edge [above] node
  16926. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16927. \path[->,bend left=15] (x86-4) edge [right] node
  16928. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  16929. \end{tikzpicture}
  16930. \end{tcolorbox}
  16931. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  16932. \label{fig:Ldyn-passes}
  16933. \end{figure}
  16934. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  16935. for the compilation of \LangDyn{}.
  16936. % Further Reading
  16937. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16938. %% {\if\edition\pythonEd
  16939. %% \chapter{Objects}
  16940. %% \label{ch:Lobject}
  16941. %% \index{subject}{objects}
  16942. %% \index{subject}{classes}
  16943. %% \fi}
  16944. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16945. \chapter{Gradual Typing}
  16946. \label{ch:Lgrad}
  16947. \index{subject}{gradual typing}
  16948. This chapter studies a language, \LangGrad{}, in which the programmer
  16949. can choose between static and dynamic type checking in different parts
  16950. of a program, thereby mixing the statically typed \LangLam{} language
  16951. with the dynamically typed \LangDyn{}. There are several approaches to
  16952. mixing static and dynamic typing, including multi-language
  16953. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  16954. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  16955. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  16956. programmer controls the amount of static versus dynamic checking by
  16957. adding or removing type annotations on parameters and
  16958. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  16959. %
  16960. The concrete syntax of \LangGrad{} is defined in
  16961. Figure~\ref{fig:Lgrad-concrete-syntax} and its abstract syntax is
  16962. defined in Figure~\ref{fig:Lgrad-syntax}. The main syntactic
  16963. difference between \LangLam{} and \LangGrad{} is the additional
  16964. \Param{} and \itm{ret} non-terminals that make type annotations
  16965. optional. The type annotations are not optional in the abstract
  16966. syntax; the parser fills in the \ANYTY{} type when a type annotation
  16967. is absent.
  16968. \newcommand{\LgradGrammarRacket}{
  16969. \begin{array}{lcl}
  16970. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  16971. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16972. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  16973. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  16974. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  16975. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  16976. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  16977. \end{array}
  16978. }
  16979. \newcommand{\LgradASTRacket}{
  16980. \begin{array}{lcl}
  16981. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  16982. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16983. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16984. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  16985. \itm{op} &::=& \code{procedure-arity} \\
  16986. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  16987. \end{array}
  16988. }
  16989. \newcommand{\LgradGrammarPython}{
  16990. \begin{array}{lcl}
  16991. \Type &::=& \key{Any}
  16992. \MID \key{int}
  16993. \MID \key{bool}
  16994. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  16995. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  16996. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16997. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  16998. \MID \CARITY{\Exp} \\
  16999. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  17000. \Param &::=& \Var \MID \Var \key{:} \Type \\
  17001. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  17002. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  17003. \end{array}
  17004. }
  17005. \newcommand{\LgradASTPython}{
  17006. \begin{array}{lcl}
  17007. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  17008. &\MID& \key{TupleType}\LP\Type^{*}\RP
  17009. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  17010. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  17011. &\MID& \ARITY{\Exp} \\
  17012. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  17013. \MID \RETURN{\Exp} \\
  17014. \Param &::=& \LP\Var\key{,}\Type\RP \\
  17015. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  17016. \end{array}
  17017. }
  17018. \begin{figure}[tp]
  17019. \centering
  17020. \begin{tcolorbox}[colback=white]
  17021. \small
  17022. {\if\edition\racketEd
  17023. \[
  17024. \begin{array}{l}
  17025. \gray{\LintGrammarRacket{}} \\ \hline
  17026. \gray{\LvarGrammarRacket{}} \\ \hline
  17027. \gray{\LifGrammarRacket{}} \\ \hline
  17028. \gray{\LwhileGrammarRacket} \\ \hline
  17029. \gray{\LtupGrammarRacket} \\ \hline
  17030. \LgradGrammarRacket \\
  17031. \begin{array}{lcl}
  17032. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  17033. \end{array}
  17034. \end{array}
  17035. \]
  17036. \fi}
  17037. {\if\edition\pythonEd
  17038. \[
  17039. \begin{array}{l}
  17040. \gray{\LintGrammarPython{}} \\ \hline
  17041. \gray{\LvarGrammarPython{}} \\ \hline
  17042. \gray{\LifGrammarPython{}} \\ \hline
  17043. \gray{\LwhileGrammarPython} \\ \hline
  17044. \gray{\LtupGrammarPython} \\ \hline
  17045. \LgradGrammarPython \\
  17046. \begin{array}{lcl}
  17047. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  17048. \end{array}
  17049. \end{array}
  17050. \]
  17051. \fi}
  17052. \end{tcolorbox}
  17053. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  17054. \label{fig:Lgrad-concrete-syntax}
  17055. \end{figure}
  17056. \begin{figure}[tp]
  17057. \centering
  17058. \begin{tcolorbox}[colback=white]
  17059. \small
  17060. {\if\edition\racketEd
  17061. \[
  17062. \begin{array}{l}
  17063. \gray{\LintOpAST} \\ \hline
  17064. \gray{\LvarASTRacket{}} \\ \hline
  17065. \gray{\LifASTRacket{}} \\ \hline
  17066. \gray{\LwhileASTRacket{}} \\ \hline
  17067. \gray{\LtupASTRacket{}} \\ \hline
  17068. \LgradASTRacket \\
  17069. \begin{array}{lcl}
  17070. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17071. \end{array}
  17072. \end{array}
  17073. \]
  17074. \fi}
  17075. {\if\edition\pythonEd
  17076. \[
  17077. \begin{array}{l}
  17078. \gray{\LintASTPython{}} \\ \hline
  17079. \gray{\LvarASTPython{}} \\ \hline
  17080. \gray{\LifASTPython{}} \\ \hline
  17081. \gray{\LwhileASTPython} \\ \hline
  17082. \gray{\LtupASTPython} \\ \hline
  17083. \LgradASTPython \\
  17084. \begin{array}{lcl}
  17085. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17086. \end{array}
  17087. \end{array}
  17088. \]
  17089. \fi}
  17090. \end{tcolorbox}
  17091. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  17092. \label{fig:Lgrad-syntax}
  17093. \end{figure}
  17094. Both the type checker and the interpreter for \LangGrad{} require some
  17095. interesting changes to enable gradual typing, which we discuss in the
  17096. next two sections in the context of the \code{map} example from
  17097. Chapter~\ref{ch:Lfun}. In Figure~\ref{fig:gradual-map} we revisit the
  17098. \code{map} example, omitting the type annotations from the \code{inc}
  17099. function.
  17100. \begin{figure}[btp]
  17101. % gradual_test_9.rkt
  17102. \begin{tcolorbox}[colback=white]
  17103. {\if\edition\racketEd
  17104. \begin{lstlisting}
  17105. (define (map [f : (Integer -> Integer)]
  17106. [v : (Vector Integer Integer)])
  17107. : (Vector Integer Integer)
  17108. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17109. (define (inc x) (+ x 1))
  17110. (vector-ref (map inc (vector 0 41)) 1)
  17111. \end{lstlisting}
  17112. \fi}
  17113. {\if\edition\pythonEd
  17114. \begin{lstlisting}
  17115. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17116. return f(v[0]), f(v[1])
  17117. def inc(x):
  17118. return x + 1
  17119. t = map(inc, (0, 41))
  17120. print(t[1])
  17121. \end{lstlisting}
  17122. \fi}
  17123. \end{tcolorbox}
  17124. \caption{A partially-typed version of the \code{map} example.}
  17125. \label{fig:gradual-map}
  17126. \end{figure}
  17127. \section{Type Checking \LangGrad{}}
  17128. \label{sec:gradual-type-check}
  17129. The type checker for \LangGrad{} uses the \code{Any} type for missing
  17130. parameter and return types. For example, the \code{x} parameter of
  17131. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  17132. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  17133. consider the \code{+} operator inside \code{inc}. It expects both
  17134. arguments to have type \code{Integer}, but its first argument \code{x}
  17135. has type \code{Any}. In a gradually typed language, such differences
  17136. are allowed so long as the types are \emph{consistent}, that is, they
  17137. are equal except in places where there is an \code{Any} type. The type
  17138. \code{Any} is consistent with every other type.
  17139. Figure~\ref{fig:consistent} defines the
  17140. \racket{\code{consistent?}}\python{\code{consistent}} predicate.
  17141. Returning to the \code{map} example of
  17142. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  17143. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17144. but parameter \code{f} of \code{map} has type
  17145. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17146. The type checker for \LangGrad{} allows this
  17147. because the two types are consistent.
  17148. \begin{figure}[tbp]
  17149. \begin{tcolorbox}[colback=white]
  17150. {\if\edition\racketEd
  17151. \begin{lstlisting}
  17152. (define/public (consistent? t1 t2)
  17153. (match* (t1 t2)
  17154. [('Integer 'Integer) #t]
  17155. [('Boolean 'Boolean) #t]
  17156. [('Void 'Void) #t]
  17157. [('Any t2) #t]
  17158. [(t1 'Any) #t]
  17159. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17160. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  17161. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17162. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  17163. (consistent? rt1 rt2))]
  17164. [(other wise) #f]))
  17165. \end{lstlisting}
  17166. \fi}
  17167. {\if\edition\pythonEd
  17168. \begin{lstlisting}
  17169. def consistent(self, t1, t2):
  17170. match (t1, t2):
  17171. case (AnyType(), _):
  17172. return True
  17173. case (_, AnyType()):
  17174. return True
  17175. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17176. return all([consistent(p1, p2) for (p1,p2) in zip(ps1,ps2)]) \
  17177. and consistent(rt1, rt2)
  17178. case (TupleType(ts1), TupleType(ts2)):
  17179. return all([consistent(ty1, ty2) for (ty1,ty2) in zip(ts1,ts2)])
  17180. case (_, _):
  17181. return t1 == t2
  17182. \end{lstlisting}
  17183. \fi}
  17184. \end{tcolorbox}
  17185. \caption{The consistency predicate on types.}
  17186. \label{fig:consistent}
  17187. \end{figure}
  17188. Next consider a program with an error, such as applying \code{map} to
  17189. a function that sometimes returns a Boolean, as shown in
  17190. Figure~\ref{fig:map-maybe_inc}. The type checker for \LangGrad{}
  17191. accepts this program because the type of \code{maybe\_inc} is
  17192. consistent with the type of parameter \code{f} of \code{map}, that is,
  17193. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}} is consistent
  17194. with \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17195. One might say that a gradual type checker is optimistic
  17196. in that it accepts programs that might execute without a runtime type
  17197. error.
  17198. %
  17199. The type checker for \LangGrad{} is defined in
  17200. Figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  17201. and \ref{fig:type-check-Lgradual-3}.
  17202. %% \begin{figure}[tp]
  17203. %% \centering
  17204. %% \fbox{
  17205. %% \begin{minipage}{0.96\textwidth}
  17206. %% \small
  17207. %% \[
  17208. %% \begin{array}{lcl}
  17209. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17210. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17211. %% \end{array}
  17212. %% \]
  17213. %% \end{minipage}
  17214. %% }
  17215. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (Figure~\ref{fig:Lwhile-syntax}).}
  17216. %% \label{fig:Lgrad-prime-syntax}
  17217. %% \end{figure}
  17218. \begin{figure}[tbp]
  17219. \begin{tcolorbox}[colback=white]
  17220. {\if\edition\racketEd
  17221. \begin{lstlisting}
  17222. (define (map [f : (Integer -> Integer)]
  17223. [v : (Vector Integer Integer)])
  17224. : (Vector Integer Integer)
  17225. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17226. (define (inc x) (+ x 1))
  17227. (define (true) #t)
  17228. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  17229. (vector-ref (map maybe_inc (vector 0 41)) 0)
  17230. \end{lstlisting}
  17231. \fi}
  17232. {\if\edition\pythonEd
  17233. \begin{lstlisting}
  17234. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17235. return f(v[0]), f(v[1])
  17236. def inc(x):
  17237. return x + 1
  17238. def true():
  17239. return True
  17240. def maybe_inc(x):
  17241. return inc(x) if input_int() == 0 else true()
  17242. t = map(maybe_inc, (0, 41))
  17243. print( t[1] )
  17244. \end{lstlisting}
  17245. \fi}
  17246. \end{tcolorbox}
  17247. \caption{A variant of the \code{map} example with an error.}
  17248. \label{fig:map-maybe_inc}
  17249. \end{figure}
  17250. Running this program with input \code{1} triggers an
  17251. error when the \code{maybe\_inc} function returns
  17252. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  17253. performs checking at runtime to ensure the integrity of the static
  17254. types, such as the
  17255. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  17256. annotation on
  17257. parameter \code{f} of \code{map}. This runtime checking is carried
  17258. out by a new \code{Cast} AST node that is generate in the
  17259. new \code{cast\_insert} pass. The output of the \code{cast\_insert}
  17260. pass is a program in the \LangCast{} language, which adds \code{Cast}
  17261. and \ANYTY{} to \LangLam{}.
  17262. %
  17263. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  17264. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  17265. inserted every time the type checker sees two types that are
  17266. consistent but not equal. In the \code{inc} function, \code{x} is
  17267. cast to \INTTY{} and the result of the \code{+} is cast to
  17268. \ANYTY{}. In the call to \code{map}, the \code{inc} argument
  17269. is cast from
  17270. \racket{\code{(Any -> Any)}}
  17271. \python{\code{Callable[[Any], Any]}}
  17272. to
  17273. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17274. \begin{figure}[btp]
  17275. \begin{tcolorbox}[colback=white]
  17276. {\if\edition\racketEd
  17277. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17278. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17279. : (Vector Integer Integer)
  17280. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17281. (define (inc [x : Any]) : Any
  17282. (cast (+ (cast x Any Integer) 1) Integer Any))
  17283. (define (true) : Any (cast #t Boolean Any))
  17284. (define (maybe_inc [x : Any]) : Any
  17285. (if (eq? 0 (read)) (inc x) (true)))
  17286. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  17287. (vector 0 41)) 0)
  17288. \end{lstlisting}
  17289. \fi}
  17290. {\if\edition\pythonEd
  17291. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17292. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17293. return f(v[0]), f(v[1])
  17294. def inc(x : Any) -> Any:
  17295. return Cast(Cast(x, Any, int) + 1, int, Any)
  17296. def true() -> Any:
  17297. return Cast(True, bool, Any)
  17298. def maybe_inc(x : Any) -> Any:
  17299. return inc(x) if input_int() == 0 else true()
  17300. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  17301. (0, 41))
  17302. print(t[1])
  17303. \end{lstlisting}
  17304. \fi}
  17305. \end{tcolorbox}
  17306. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  17307. and \code{maybe\_inc} example.}
  17308. \label{fig:map-cast}
  17309. \end{figure}
  17310. \begin{figure}[tbp]
  17311. \begin{tcolorbox}[colback=white]
  17312. {\if\edition\racketEd
  17313. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17314. (define type-check-gradual-class
  17315. (class type-check-Llambda-class
  17316. (super-new)
  17317. (inherit operator-types type-predicates)
  17318. (define/override (type-check-exp env)
  17319. (lambda (e)
  17320. (define recur (type-check-exp env))
  17321. (match e
  17322. [(Prim 'vector-length (list e1))
  17323. (define-values (e1^ t) (recur e1))
  17324. (match t
  17325. [`(Vector ,ts ...)
  17326. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17327. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17328. [(Prim 'vector-ref (list e1 e2))
  17329. (define-values (e1^ t1) (recur e1))
  17330. (define-values (e2^ t2) (recur e2))
  17331. (check-consistent? t2 'Integer e)
  17332. (match t1
  17333. [`(Vector ,ts ...)
  17334. (match e2^
  17335. [(Int i)
  17336. (unless (and (0 . <= . i) (i . < . (length ts)))
  17337. (error 'type-check "invalid index ~a in ~a" i e))
  17338. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17339. [else (define e1^^ (make-cast e1^ t1 'Any))
  17340. (define e2^^ (make-cast e2^ t2 'Integer))
  17341. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17342. ['Any
  17343. (define e2^^ (make-cast e2^ t2 'Integer))
  17344. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17345. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17346. [(Prim 'vector-set! (list e1 e2 e3) )
  17347. (define-values (e1^ t1) (recur e1))
  17348. (define-values (e2^ t2) (recur e2))
  17349. (define-values (e3^ t3) (recur e3))
  17350. (check-consistent? t2 'Integer e)
  17351. (match t1
  17352. [`(Vector ,ts ...)
  17353. (match e2^
  17354. [(Int i)
  17355. (unless (and (0 . <= . i) (i . < . (length ts)))
  17356. (error 'type-check "invalid index ~a in ~a" i e))
  17357. (check-consistent? (list-ref ts i) t3 e)
  17358. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  17359. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  17360. [else
  17361. (define e1^^ (make-cast e1^ t1 'Any))
  17362. (define e2^^ (make-cast e2^ t2 'Integer))
  17363. (define e3^^ (make-cast e3^ t3 'Any))
  17364. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  17365. ['Any
  17366. (define e2^^ (make-cast e2^ t2 'Integer))
  17367. (define e3^^ (make-cast e3^ t3 'Any))
  17368. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  17369. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17370. \end{lstlisting}
  17371. \fi}
  17372. {\if\edition\pythonEd
  17373. UNDER CONSTRUCTION
  17374. \fi}
  17375. \end{tcolorbox}
  17376. \caption{Type checker for the \LangGrad{} language, part 1.}
  17377. \label{fig:type-check-Lgradual-1}
  17378. \end{figure}
  17379. \begin{figure}[tbp]
  17380. \begin{tcolorbox}[colback=white]
  17381. {\if\edition\racketEd
  17382. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17383. [(Prim 'eq? (list e1 e2))
  17384. (define-values (e1^ t1) (recur e1))
  17385. (define-values (e2^ t2) (recur e2))
  17386. (check-consistent? t1 t2 e)
  17387. (define T (meet t1 t2))
  17388. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  17389. 'Boolean)]
  17390. [(Prim 'not (list e1))
  17391. (define-values (e1^ t1) (recur e1))
  17392. (match t1
  17393. ['Any
  17394. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  17395. (Bool #t) (Bool #f)))]
  17396. [else
  17397. (define-values (t-ret new-es^)
  17398. (type-check-op 'not (list t1) (list e1^) e))
  17399. (values (Prim 'not new-es^) t-ret)])]
  17400. [(Prim 'and (list e1 e2))
  17401. (recur (If e1 e2 (Bool #f)))]
  17402. [(Prim 'or (list e1 e2))
  17403. (define tmp (gensym 'tmp))
  17404. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  17405. [(Prim op es)
  17406. #:when (not (set-member? explicit-prim-ops op))
  17407. (define-values (new-es ts)
  17408. (for/lists (exprs types) ([e es])
  17409. (recur e)))
  17410. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  17411. (values (Prim op new-es^) t-ret)]
  17412. [(If e1 e2 e3)
  17413. (define-values (e1^ T1) (recur e1))
  17414. (define-values (e2^ T2) (recur e2))
  17415. (define-values (e3^ T3) (recur e3))
  17416. (check-consistent? T2 T3 e)
  17417. (match T1
  17418. ['Boolean
  17419. (define Tif (join T2 T3))
  17420. (values (If e1^ (make-cast e2^ T2 Tif)
  17421. (make-cast e3^ T3 Tif)) Tif)]
  17422. ['Any
  17423. (define Tif (meet T2 T3))
  17424. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  17425. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  17426. Tif)]
  17427. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  17428. [(HasType e1 T)
  17429. (define-values (e1^ T1) (recur e1))
  17430. (check-consistent? T1 T)
  17431. (values (make-cast e1^ T1 T) T)]
  17432. [(SetBang x e1)
  17433. (define-values (e1^ T1) (recur e1))
  17434. (define varT (dict-ref env x))
  17435. (check-consistent? T1 varT e)
  17436. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  17437. [(WhileLoop e1 e2)
  17438. (define-values (e1^ T1) (recur e1))
  17439. (check-consistent? T1 'Boolean e)
  17440. (define-values (e2^ T2) ((type-check-exp env) e2))
  17441. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  17442. \end{lstlisting}
  17443. \fi}
  17444. {\if\edition\pythonEd
  17445. UNDER CONSTRUCTION
  17446. \fi}
  17447. \end{tcolorbox}
  17448. \caption{Type checker for the \LangGrad{} language, part 2.}
  17449. \label{fig:type-check-Lgradual-2}
  17450. \end{figure}
  17451. \begin{figure}[tbp]
  17452. \begin{tcolorbox}[colback=white]
  17453. {\if\edition\racketEd
  17454. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17455. [(Apply e1 e2s)
  17456. (define-values (e1^ T1) (recur e1))
  17457. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  17458. (match T1
  17459. [`(,T1ps ... -> ,T1rt)
  17460. (for ([T2 T2s] [Tp T1ps])
  17461. (check-consistent? T2 Tp e))
  17462. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  17463. (make-cast e2 src tgt)))
  17464. (values (Apply e1^ e2s^^) T1rt)]
  17465. [`Any
  17466. (define e1^^ (make-cast e1^ 'Any
  17467. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  17468. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  17469. (make-cast e2 src 'Any)))
  17470. (values (Apply e1^^ e2s^^) 'Any)]
  17471. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  17472. [(Lambda params Tr e1)
  17473. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  17474. (match p
  17475. [`[,x : ,T] (values x T)]
  17476. [(? symbol? x) (values x 'Any)])))
  17477. (define-values (e1^ T1)
  17478. ((type-check-exp (append (map cons xs Ts) env)) e1))
  17479. (check-consistent? Tr T1 e)
  17480. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  17481. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  17482. [else ((super type-check-exp env) e)]
  17483. )))
  17484. \end{lstlisting}
  17485. \fi}
  17486. {\if\edition\pythonEd
  17487. UNDER CONSTRUCTION
  17488. \fi}
  17489. \end{tcolorbox}
  17490. \caption{Type checker for the \LangGrad{} language, part 3.}
  17491. \label{fig:type-check-Lgradual-3}
  17492. \end{figure}
  17493. \begin{figure}[tbp]
  17494. \begin{tcolorbox}[colback=white]
  17495. {\if\edition\racketEd
  17496. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17497. (define/public (join t1 t2)
  17498. (match* (t1 t2)
  17499. [('Integer 'Integer) 'Integer]
  17500. [('Boolean 'Boolean) 'Boolean]
  17501. [('Void 'Void) 'Void]
  17502. [('Any t2) t2]
  17503. [(t1 'Any) t1]
  17504. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17505. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  17506. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17507. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  17508. -> ,(join rt1 rt2))]))
  17509. (define/public (meet t1 t2)
  17510. (match* (t1 t2)
  17511. [('Integer 'Integer) 'Integer]
  17512. [('Boolean 'Boolean) 'Boolean]
  17513. [('Void 'Void) 'Void]
  17514. [('Any t2) 'Any]
  17515. [(t1 'Any) 'Any]
  17516. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17517. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  17518. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17519. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  17520. -> ,(meet rt1 rt2))]))
  17521. (define/public (make-cast e src tgt)
  17522. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  17523. (define/public (check-consistent? t1 t2 e)
  17524. (unless (consistent? t1 t2)
  17525. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  17526. (define/override (type-check-op op arg-types args e)
  17527. (match (dict-ref (operator-types) op)
  17528. [`(,param-types . ,return-type)
  17529. (for ([at arg-types] [pt param-types])
  17530. (check-consistent? at pt e))
  17531. (values return-type
  17532. (for/list ([e args] [s arg-types] [t param-types])
  17533. (make-cast e s t)))]
  17534. [else (error 'type-check-op "unrecognized ~a" op)]))
  17535. (define explicit-prim-ops
  17536. (set-union
  17537. (type-predicates)
  17538. (set 'procedure-arity 'eq?
  17539. 'vector 'vector-length 'vector-ref 'vector-set!
  17540. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  17541. (define/override (fun-def-type d)
  17542. (match d
  17543. [(Def f params rt info body)
  17544. (define ps
  17545. (for/list ([p params])
  17546. (match p
  17547. [`[,x : ,T] T]
  17548. [(? symbol?) 'Any]
  17549. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  17550. `(,@ps -> ,rt)]
  17551. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  17552. \end{lstlisting}
  17553. \fi}
  17554. {\if\edition\pythonEd
  17555. UNDER CONSTRUCTION
  17556. \fi}
  17557. \end{tcolorbox}
  17558. \caption{Auxiliary functions for type checking \LangGrad{}.}
  17559. \label{fig:type-check-Lgradual-aux}
  17560. \end{figure}
  17561. \clearpage
  17562. \section{Interpreting \LangCast{}}
  17563. \label{sec:interp-casts}
  17564. The runtime behavior of casts involving simple types such as
  17565. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  17566. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  17567. \code{Inject} operator of \LangAny{}, which puts the integer into a
  17568. tagged value (Figure~\ref{fig:interp-Lany}). Similarly, a cast from
  17569. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  17570. operator, that is, by checking the value's tag and either retrieving
  17571. the underlying integer or signaling an error if it the tag is not the
  17572. one for integers (Figure~\ref{fig:interp-Lany-aux}).
  17573. %
  17574. Things get more interesting casts involving function or tuple types,
  17575. that is, casts involving higher-order types.
  17576. Consider the cast of the function \code{maybe\_inc} from
  17577. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  17578. to
  17579. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}.
  17580. When a function flows through
  17581. this cast at runtime, we can't know in general whether the function
  17582. will always return an integer. After all, predicting the return value of
  17583. a function is equivalent to the halting problem, which is
  17584. undecidable. The \LangCast{} interpreter therefore delays the checking
  17585. of the cast until the function is applied. This is accomplished by
  17586. wrapping \code{maybe\_inc} in a new function that casts its parameter
  17587. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  17588. casts the return value from \CANYTY{} to \code{Integer}.
  17589. UNDER CONSTRUCTION
  17590. Turning our attention to casts involving tuple types, we consider the
  17591. example in Figure~\ref{fig:map-bang} that defines a
  17592. partially-typed version of \code{map} whose parameter \code{v} has
  17593. type \code{(Vector Any Any)} and that updates \code{v} in place
  17594. instead of returning a new tuple. So we name this function
  17595. \code{map!}. We apply \code{map!} to a tuple of integers, so
  17596. the type checker inserts a cast from \code{(Vector Integer Integer)}
  17597. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  17598. cast between tuple types would be a build a new tuple whose elements
  17599. are the result of casting each of the original elements to the
  17600. appropriate target type. However, this approach is only valid for
  17601. immutable tuples; and our tuples are mutable. In the example of
  17602. Figure~\ref{fig:map-bang}, if the cast created a new tuple, then
  17603. the updates inside of \code{map!} would happen to the new tuple
  17604. and not the original one.
  17605. \begin{figure}[tbp]
  17606. \begin{tcolorbox}[colback=white]
  17607. % gradual_test_11.rkt
  17608. \begin{lstlisting}
  17609. (define (map! [f : (Any -> Any)]
  17610. [v : (Vector Any Any)]) : Void
  17611. (begin
  17612. (vector-set! v 0 (f (vector-ref v 0)))
  17613. (vector-set! v 1 (f (vector-ref v 1)))))
  17614. (define (inc x) (+ x 1))
  17615. (let ([v (vector 0 41)])
  17616. (begin (map! inc v) (vector-ref v 1)))
  17617. \end{lstlisting}
  17618. \end{tcolorbox}
  17619. \caption{An example involving casts on vectors.}
  17620. \label{fig:map-bang}
  17621. \end{figure}
  17622. Instead the interpreter needs to create a new kind of value, a
  17623. \emph{tuple proxy}, that intercepts every tuple operation. On a
  17624. read, the proxy reads from the underlying tuple and then applies a
  17625. cast to the resulting value. On a write, the proxy casts the argument
  17626. value and then performs the write to the underlying tuple. For the
  17627. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  17628. \code{0} from \code{Integer} to \CANYTY{}. For the first
  17629. \code{vector-set!}, the proxy casts a tagged \code{1} from \CANYTY{}
  17630. to \code{Integer}.
  17631. The final category of cast that we need to consider are casts between
  17632. the \CANYTY{} type and either a function or a tuple
  17633. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  17634. in which parameter \code{v} does not have a type annotation, so it is
  17635. given type \CANYTY{}. In the call to \code{map!}, the tuple has
  17636. type \code{(Vector Integer Integer)} so the type checker inserts a
  17637. cast from \code{(Vector Integer Integer)} to \CANYTY{}. A first
  17638. thought is to use \code{Inject}, but that doesn't work because
  17639. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  17640. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  17641. to \CANYTY{}.
  17642. \begin{figure}[tbp]
  17643. \begin{tcolorbox}[colback=white]
  17644. \begin{lstlisting}
  17645. (define (map! [f : (Any -> Any)] v) : Void
  17646. (begin
  17647. (vector-set! v 0 (f (vector-ref v 0)))
  17648. (vector-set! v 1 (f (vector-ref v 1)))))
  17649. (define (inc x) (+ x 1))
  17650. (let ([v (vector 0 41)])
  17651. (begin (map! inc v) (vector-ref v 1)))
  17652. \end{lstlisting}
  17653. \end{tcolorbox}
  17654. \caption{Casting a tuple to \CANYTY{}.}
  17655. \label{fig:map-any}
  17656. \end{figure}
  17657. The \LangCast{} interpreter uses an auxiliary function named
  17658. \code{apply-cast} to cast a value from a source type to a target type,
  17659. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  17660. of the kinds of casts that we've discussed in this section.
  17661. \begin{figure}[tbp]
  17662. \begin{tcolorbox}[colback=white]
  17663. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17664. (define/public (apply-cast v s t)
  17665. (match* (s t)
  17666. [(t1 t2) #:when (equal? t1 t2) v]
  17667. [('Any t2)
  17668. (match t2
  17669. [`(,ts ... -> ,rt)
  17670. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17671. (define v^ (apply-project v any->any))
  17672. (apply-cast v^ any->any `(,@ts -> ,rt))]
  17673. [`(Vector ,ts ...)
  17674. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17675. (define v^ (apply-project v vec-any))
  17676. (apply-cast v^ vec-any `(Vector ,@ts))]
  17677. [else (apply-project v t2)])]
  17678. [(t1 'Any)
  17679. (match t1
  17680. [`(,ts ... -> ,rt)
  17681. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17682. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  17683. (apply-inject v^ (any-tag any->any))]
  17684. [`(Vector ,ts ...)
  17685. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17686. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  17687. (apply-inject v^ (any-tag vec-any))]
  17688. [else (apply-inject v (any-tag t1))])]
  17689. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17690. (define x (gensym 'x))
  17691. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  17692. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  17693. (define cast-writes
  17694. (for/list ([t1 ts1] [t2 ts2])
  17695. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  17696. `(vector-proxy ,(vector v (apply vector cast-reads)
  17697. (apply vector cast-writes)))]
  17698. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17699. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  17700. `(function ,xs ,(Cast
  17701. (Apply (Value v)
  17702. (for/list ([x xs][t1 ts1][t2 ts2])
  17703. (Cast (Var x) t2 t1)))
  17704. rt1 rt2) ())]
  17705. ))
  17706. \end{lstlisting}
  17707. \end{tcolorbox}
  17708. \caption{The \code{apply-cast} auxiliary method.}
  17709. \label{fig:apply-cast}
  17710. \end{figure}
  17711. The interpreter for \LangCast{} is defined in
  17712. Figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  17713. dispatching to \code{apply-cast}. To handle the addition of tuple
  17714. proxies, we update the tuple primitives in \code{interp-op} using the
  17715. functions in Figure~\ref{fig:guarded-tuple}.
  17716. \begin{figure}[tbp]
  17717. \begin{tcolorbox}[colback=white]
  17718. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17719. (define interp-Lcast-class
  17720. (class interp-Llambda-class
  17721. (super-new)
  17722. (inherit apply-fun apply-inject apply-project)
  17723. (define/override (interp-op op)
  17724. (match op
  17725. ['vector-length guarded-vector-length]
  17726. ['vector-ref guarded-vector-ref]
  17727. ['vector-set! guarded-vector-set!]
  17728. ['any-vector-ref (lambda (v i)
  17729. (match v [`(tagged ,v^ ,tg)
  17730. (guarded-vector-ref v^ i)]))]
  17731. ['any-vector-set! (lambda (v i a)
  17732. (match v [`(tagged ,v^ ,tg)
  17733. (guarded-vector-set! v^ i a)]))]
  17734. ['any-vector-length (lambda (v)
  17735. (match v [`(tagged ,v^ ,tg)
  17736. (guarded-vector-length v^)]))]
  17737. [else (super interp-op op)]
  17738. ))
  17739. (define/override ((interp-exp env) e)
  17740. (define (recur e) ((interp-exp env) e))
  17741. (match e
  17742. [(Value v) v]
  17743. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  17744. [else ((super interp-exp env) e)]))
  17745. ))
  17746. (define (interp-Lcast p)
  17747. (send (new interp-Lcast-class) interp-program p))
  17748. \end{lstlisting}
  17749. \end{tcolorbox}
  17750. \caption{The interpreter for \LangCast{}.}
  17751. \label{fig:interp-Lcast}
  17752. \end{figure}
  17753. \begin{figure}[tbp]
  17754. \begin{tcolorbox}[colback=white]
  17755. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17756. (define (guarded-vector-ref vec i)
  17757. (match vec
  17758. [`(vector-proxy ,proxy)
  17759. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  17760. (define rd (vector-ref (vector-ref proxy 1) i))
  17761. (apply-fun rd (list val) 'guarded-vector-ref)]
  17762. [else (vector-ref vec i)]))
  17763. (define (guarded-vector-set! vec i arg)
  17764. (match vec
  17765. [`(vector-proxy ,proxy)
  17766. (define wr (vector-ref (vector-ref proxy 2) i))
  17767. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  17768. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  17769. [else (vector-set! vec i arg)]))
  17770. (define (guarded-vector-length vec)
  17771. (match vec
  17772. [`(vector-proxy ,proxy)
  17773. (guarded-vector-length (vector-ref proxy 0))]
  17774. [else (vector-length vec)]))
  17775. \end{lstlisting}
  17776. \end{tcolorbox}
  17777. \caption{The \code{guarded-vector} auxiliary functions.}
  17778. \label{fig:guarded-tuple}
  17779. \end{figure}
  17780. \section{Lower Casts}
  17781. \label{sec:lower-casts}
  17782. The next step in the journey towards x86 is the \code{lower-casts}
  17783. pass that translates the casts in \LangCast{} to the lower-level
  17784. \code{Inject} and \code{Project} operators and a new operator for
  17785. creating tuple proxies, extending the \LangLam{} language to create
  17786. \LangProxy{}. We recommend creating an auxiliary function named
  17787. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  17788. and a target type, and translates it to expression in \LangProxy{} that has
  17789. the same behavior as casting the expression from the source to the
  17790. target type in the interpreter.
  17791. The \code{lower-cast} function can follow a code structure similar to
  17792. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  17793. the interpreter for \LangCast{} because it must handle the same cases as
  17794. \code{apply-cast} and it needs to mimic the behavior of
  17795. \code{apply-cast}. The most interesting cases are those concerning the
  17796. casts between two tuple types and between two function types.
  17797. As mentioned in Section~\ref{sec:interp-casts}, a cast from one tuple
  17798. type to another tuple type is accomplished by creating a proxy that
  17799. intercepts the operations on the underlying tuple. Here we make the
  17800. creation of the proxy explicit with the \code{vector-proxy} primitive
  17801. operation. It takes three arguments, the first is an expression for
  17802. the tuple, the second is a tuple of functions for casting an element
  17803. that is being read from the tuple, and the third is a tuple of
  17804. functions for casting an element that is being written to the tuple.
  17805. You can create the functions using \code{Lambda}. Also, as we shall
  17806. see in the next section, we need to differentiate these tuples from
  17807. the user-created ones, so we recommend using a new primitive operator
  17808. named \code{raw-vector} instead of \code{vector} to create these
  17809. tuples of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  17810. the output of \code{lower-casts} on the example in
  17811. Figure~\ref{fig:map-bang} that involved casting a tuple of
  17812. integers to a tuple of \CANYTY{}.
  17813. \begin{figure}[tbp]
  17814. \begin{tcolorbox}[colback=white]
  17815. \begin{lstlisting}
  17816. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  17817. (begin
  17818. (vector-set! v 0 (f (vector-ref v 0)))
  17819. (vector-set! v 1 (f (vector-ref v 1)))))
  17820. (define (inc [x : Any]) : Any
  17821. (inject (+ (project x Integer) 1) Integer))
  17822. (let ([v (vector 0 41)])
  17823. (begin
  17824. (map! inc (vector-proxy v
  17825. (raw-vector (lambda: ([x9 : Integer]) : Any
  17826. (inject x9 Integer))
  17827. (lambda: ([x9 : Integer]) : Any
  17828. (inject x9 Integer)))
  17829. (raw-vector (lambda: ([x9 : Any]) : Integer
  17830. (project x9 Integer))
  17831. (lambda: ([x9 : Any]) : Integer
  17832. (project x9 Integer)))))
  17833. (vector-ref v 1)))
  17834. \end{lstlisting}
  17835. \end{tcolorbox}
  17836. \caption{Output of \code{lower-casts} on the example in
  17837. Figure~\ref{fig:map-bang}.}
  17838. \label{fig:map-bang-lower-cast}
  17839. \end{figure}
  17840. A cast from one function type to another function type is accomplished
  17841. by generating a \code{Lambda} whose parameter and return types match
  17842. the target function type. The body of the \code{Lambda} should cast
  17843. the parameters from the target type to the source type. (Yes,
  17844. backwards! Functions are contravariant\index{subject}{contravariant}
  17845. in the parameters.). Afterwards, call the underlying function and then
  17846. cast the result from the source return type to the target return type.
  17847. Figure~\ref{fig:map-lower-cast} shows the output of the
  17848. \code{lower-casts} pass on the \code{map} example in
  17849. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  17850. call to \code{map} is wrapped in a \code{lambda}.
  17851. \begin{figure}[tbp]
  17852. \begin{tcolorbox}[colback=white]
  17853. \begin{lstlisting}
  17854. (define (map [f : (Integer -> Integer)]
  17855. [v : (Vector Integer Integer)])
  17856. : (Vector Integer Integer)
  17857. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17858. (define (inc [x : Any]) : Any
  17859. (inject (+ (project x Integer) 1) Integer))
  17860. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  17861. (project (inc (inject x9 Integer)) Integer))
  17862. (vector 0 41)) 1)
  17863. \end{lstlisting}
  17864. \end{tcolorbox}
  17865. \caption{Output of \code{lower-casts} on the example in
  17866. Figure~\ref{fig:gradual-map}.}
  17867. \label{fig:map-lower-cast}
  17868. \end{figure}
  17869. \section{Differentiate Proxies}
  17870. \label{sec:differentiate-proxies}
  17871. So far the job of differentiating tuples and tuple proxies has been
  17872. the job of the interpreter. For example, the interpreter for \LangCast{}
  17873. implements \code{vector-ref} using the \code{guarded-vector-ref}
  17874. function in Figure~\ref{fig:guarded-tuple}. In the
  17875. \code{differentiate-proxies} pass we shift this responsibility to the
  17876. generated code.
  17877. We begin by designing the output language \LangPVec. In
  17878. \LangGrad{} we used the type \code{Vector} for both real tuples and tuple
  17879. proxies. In \LangPVec we return the \code{Vector} type to
  17880. its original meaning, as the type of real tuples, and we introduce a
  17881. new type, \code{PVector}, whose values can be either real tuples or
  17882. tuple proxies. This new type comes with a suite of new primitive
  17883. operations for creating and using values of type \code{PVector}.
  17884. %We don't need to introduce a new type to represent tuple proxies.
  17885. A proxy is represented by a tuple containing three things: 1) the
  17886. underlying tuple, 2) a tuple of functions for casting elements that
  17887. are read from the tuple, and 3) a tuple of functions for casting
  17888. values to be written to the tuple. So we define the following
  17889. abbreviation for the type of a tuple proxy:
  17890. \[
  17891. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  17892. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  17893. \to (\key{PVector}~ T' \ldots)
  17894. \]
  17895. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  17896. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  17897. %
  17898. Next we describe each of the new primitive operations.
  17899. \begin{description}
  17900. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  17901. (\key{PVector} $T \ldots$)]\ \\
  17902. %
  17903. This operation brands a vector as a value of the \code{PVector} type.
  17904. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  17905. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  17906. %
  17907. This operation brands a vector proxy as value of the \code{PVector} type.
  17908. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  17909. \BOOLTY{}] \ \\
  17910. %
  17911. This returns true if the value is a tuple proxy and false if it is a
  17912. real tuple.
  17913. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  17914. (\key{Vector} $T \ldots$)]\ \\
  17915. %
  17916. Assuming that the input is a tuple, this operation returns the
  17917. tuple.
  17918. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  17919. $\to$ \BOOLTY{}]\ \\
  17920. %
  17921. Given a tuple proxy, this operation returns the length of the tuple.
  17922. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  17923. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  17924. %
  17925. Given a tuple proxy, this operation returns the $i$th element of the
  17926. tuple.
  17927. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  17928. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  17929. Given a tuple proxy, this operation writes a value to the $i$th element
  17930. of the tuple.
  17931. \end{description}
  17932. Now to discuss the translation that differentiates tuples from
  17933. proxies. First, every type annotation in the program is translated
  17934. (recursively) to replace \code{Vector} with \code{PVector}. Next, we
  17935. insert uses of \code{PVector} operations in the appropriate
  17936. places. For example, we wrap every tuple creation with an
  17937. \code{inject-vector}.
  17938. \begin{lstlisting}
  17939. (vector |$e_1 \ldots e_n$|)
  17940. |$\Rightarrow$|
  17941. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  17942. \end{lstlisting}
  17943. The \code{raw-vector} operator that we introduced in the previous
  17944. section does not get injected.
  17945. \begin{lstlisting}
  17946. (raw-vector |$e_1 \ldots e_n$|)
  17947. |$\Rightarrow$|
  17948. (vector |$e'_1 \ldots e'_n$|)
  17949. \end{lstlisting}
  17950. The \code{vector-proxy} primitive translates as follows.
  17951. \begin{lstlisting}
  17952. (vector-proxy |$e_1~e_2~e_3$|)
  17953. |$\Rightarrow$|
  17954. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  17955. \end{lstlisting}
  17956. We translate the tuple operations into conditional expressions that
  17957. check whether the value is a proxy and then dispatch to either the
  17958. appropriate proxy tuple operation or the regular tuple operation.
  17959. For example, the following is the translation for \code{vector-ref}.
  17960. \begin{lstlisting}
  17961. (vector-ref |$e_1$| |$i$|)
  17962. |$\Rightarrow$|
  17963. (let ([|$v~e_1$|])
  17964. (if (proxy? |$v$|)
  17965. (proxy-vector-ref |$v$| |$i$|)
  17966. (vector-ref (project-vector |$v$|) |$i$|)
  17967. \end{lstlisting}
  17968. Note in the case of a real tuple, we must apply \code{project-vector}
  17969. before the \code{vector-ref}.
  17970. \section{Reveal Casts}
  17971. \label{sec:reveal-casts-gradual}
  17972. Recall that the \code{reveal-casts} pass
  17973. (Section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  17974. \code{Inject} and \code{Project} into lower-level operations. In
  17975. particular, \code{Project} turns into a conditional expression that
  17976. inspects the tag and retrieves the underlying value. Here we need to
  17977. augment the translation of \code{Project} to handle the situation when
  17978. the target type is \code{PVector}. Instead of using
  17979. \code{vector-length} we need to use \code{proxy-vector-length}.
  17980. \begin{lstlisting}
  17981. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  17982. |$\Rightarrow$|
  17983. (let |$\itm{tmp}$| |$e'$|
  17984. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  17985. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  17986. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  17987. (exit)))
  17988. \end{lstlisting}
  17989. \section{Closure Conversion}
  17990. \label{sec:closure-conversion-gradual}
  17991. The closure conversion pass only requires one minor adjustment. The
  17992. auxiliary function that translates type annotations needs to be
  17993. updated to handle the \code{PVector} type.
  17994. \section{Explicate Control}
  17995. \label{sec:explicate-control-gradual}
  17996. Update the \code{explicate\_control} pass to handle the new primitive
  17997. operations on the \code{PVector} type.
  17998. \section{Select Instructions}
  17999. \label{sec:select-instructions-gradual}
  18000. Recall that the \code{select\_instructions} pass is responsible for
  18001. lowering the primitive operations into x86 instructions. So we need
  18002. to translate the new \code{PVector} operations to x86. To do so, the
  18003. first question we need to answer is how to differentiate the two
  18004. kinds of values (tuples and proxies) that can inhabit \code{PVector}.
  18005. We need just one bit to accomplish this, and use the bit in position
  18006. $57$ of the 64-bit tag at the front of every tuple (see
  18007. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  18008. for \code{inject-vector} we leave it that way.
  18009. \begin{lstlisting}
  18010. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  18011. |$\Rightarrow$|
  18012. movq |$e'_1$|, |$\itm{lhs'}$|
  18013. \end{lstlisting}
  18014. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  18015. \begin{lstlisting}
  18016. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  18017. |$\Rightarrow$|
  18018. movq |$e'_1$|, %r11
  18019. movq |$(1 << 57)$|, %rax
  18020. orq 0(%r11), %rax
  18021. movq %rax, 0(%r11)
  18022. movq %r11, |$\itm{lhs'}$|
  18023. \end{lstlisting}
  18024. The \code{proxy?} operation consumes the information so carefully
  18025. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  18026. isolates the $57$th bit to tell whether the value is a real tuple or
  18027. a proxy.
  18028. \begin{lstlisting}
  18029. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  18030. |$\Rightarrow$|
  18031. movq |$e_1'$|, %r11
  18032. movq 0(%r11), %rax
  18033. sarq $57, %rax
  18034. andq $1, %rax
  18035. movq %rax, |$\itm{lhs'}$|
  18036. \end{lstlisting}
  18037. The \code{project-vector} operation is straightforward to translate,
  18038. so we leave it up to the reader.
  18039. Regarding the \code{proxy-vector} operations, the runtime provides
  18040. procedures that implement them (they are recursive functions!) so
  18041. here we simply need to translate these tuple operations into the
  18042. appropriate function call. For example, here is the translation for
  18043. \code{proxy-vector-ref}.
  18044. \begin{lstlisting}
  18045. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  18046. |$\Rightarrow$|
  18047. movq |$e_1'$|, %rdi
  18048. movq |$e_2'$|, %rsi
  18049. callq proxy_vector_ref
  18050. movq %rax, |$\itm{lhs'}$|
  18051. \end{lstlisting}
  18052. We have another batch of tuple operations to deal with, those for the
  18053. \CANYTY{} type. Recall that the type checker for \LangGrad{}
  18054. generates an \code{any-vector-ref} when there is a \code{vector-ref}
  18055. on something of type \CANYTY{}, and similarly for
  18056. \code{any-vector-set!} and \code{any-vector-length}
  18057. (Figure~\ref{fig:type-check-Lgradual-1}). In
  18058. Section~\ref{sec:select-Lany} we selected instructions for these
  18059. operations based on the idea that the underlying value was a real
  18060. tuple. But in the current setting, the underlying value is of type
  18061. \code{PVector}. So \code{any-vector-ref} can be translated follows. We
  18062. begin by projecting the underlying value out of the tagged value and
  18063. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  18064. \begin{lstlisting}
  18065. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18066. movq |$\neg 111$|, %rdi
  18067. andq |$e_1'$|, %rdi
  18068. movq |$e_2'$|, %rsi
  18069. callq proxy_vector_ref
  18070. movq %rax, |$\itm{lhs'}$|
  18071. \end{lstlisting}
  18072. The \code{any-vector-set!} and \code{any-vector-length} operators can
  18073. be translated in a similar way.
  18074. \begin{exercise}\normalfont\normalsize
  18075. Implement a compiler for the gradually-typed \LangGrad{} language by
  18076. extending and adapting your compiler for \LangLam{}. Create 10 new
  18077. partially-typed test programs. In addition to testing with these
  18078. new programs, also test your compiler on all the tests for \LangLam{}
  18079. and tests for \LangDyn{}. Sometimes you may get a type checking error
  18080. on the \LangDyn{} programs but you can adapt them by inserting
  18081. a cast to the \CANYTY{} type around each subexpression
  18082. causing a type error. While \LangDyn{} does not have explicit casts,
  18083. you can induce one by wrapping the subexpression \code{e}
  18084. with a call to an un-annotated identity function, like this:
  18085. \code{((lambda (x) x) e)}.
  18086. \end{exercise}
  18087. \begin{figure}[p]
  18088. \begin{tcolorbox}[colback=white]
  18089. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18090. \node (Lgradual) at (9,4) {\large \LangGrad{}};
  18091. \node (Lgradualp) at (6,4) {\large \LangCast{}};
  18092. \node (Llambdapp) at (3,4) {\large \LangProxy{}};
  18093. \node (Llambdaproxy) at (0,4) {\large \LangPVec{}};
  18094. \node (Llambdaproxy-2) at (0,2) {\large \LangPVec{}};
  18095. \node (Llambdaproxy-3) at (3,2) {\large \LangPVec{}};
  18096. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  18097. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  18098. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  18099. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  18100. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  18101. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  18102. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  18103. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  18104. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  18105. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  18106. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  18107. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  18108. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  18109. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  18110. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  18111. \path[->,bend right=15] (Lgradual) edge [above] node
  18112. {\ttfamily\footnotesize type\_check} (Lgradualp);
  18113. \path[->,bend right=15] (Lgradualp) edge [above] node
  18114. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  18115. \path[->,bend right=15] (Llambdapp) edge [above] node
  18116. {\ttfamily\footnotesize differentiate.} (Llambdaproxy);
  18117. \path[->,bend left=15] (Llambdaproxy) edge [right] node
  18118. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  18119. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  18120. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  18121. \path[->,bend left=15] (Llambdaproxy-3) edge [above] node
  18122. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  18123. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  18124. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  18125. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  18126. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  18127. \path[->,bend left=15] (F1-1) edge [left] node
  18128. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  18129. \path[->,bend left=15] (F1-2) edge [below] node
  18130. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  18131. \path[->,bend right=15] (F1-3) edge [above] node
  18132. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  18133. \path[->,bend right=15] (F1-4) edge [above] node
  18134. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18135. \path[->,bend right=15] (F1-5) edge [above] node
  18136. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  18137. \path[->,bend right=15] (F1-6) edge [right] node
  18138. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18139. \path[->,bend left=15] (C3-2) edge [left] node
  18140. {\ttfamily\footnotesize select\_instr.} (x86-2);
  18141. \path[->,bend right=15] (x86-2) edge [left] node
  18142. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18143. \path[->,bend right=15] (x86-2-1) edge [below] node
  18144. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  18145. \path[->,bend right=15] (x86-2-2) edge [left] node
  18146. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  18147. \path[->,bend left=15] (x86-3) edge [above] node
  18148. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  18149. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  18150. \end{tikzpicture}
  18151. \end{tcolorbox}
  18152. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  18153. \label{fig:Lgradual-passes}
  18154. \end{figure}
  18155. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  18156. needed for the compilation of \LangGrad{}.
  18157. \section{Further Reading}
  18158. This chapter just scratches the surface of gradual typing. The basic
  18159. approach described here is missing two key ingredients that one would
  18160. want in a implementation of gradual typing: blame
  18161. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  18162. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  18163. problem addressed by blame tracking is that when a cast on a
  18164. higher-order value fails, it often does so at a point in the program
  18165. that is far removed from the original cast. Blame tracking is a
  18166. technique for propagating extra information through casts and proxies
  18167. so that when a cast fails, the error message can point back to the
  18168. original location of the cast in the source program.
  18169. The problem addressed by space-efficient casts also relates to
  18170. higher-order casts. It turns out that in partially typed programs, a
  18171. function or tuple can flow through very-many casts at runtime. With
  18172. the approach described in this chapter, each cast adds another
  18173. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  18174. considerable space, but it also makes the function calls and tuple
  18175. operations slow. For example, a partially-typed version of quicksort
  18176. could, in the worst case, build a chain of proxies of length $O(n)$
  18177. around the tuple, changing the overall time complexity of the
  18178. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  18179. solution to this problem by representing casts using the coercion
  18180. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  18181. long chains of proxies by compressing them into a concise normal
  18182. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  18183. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  18184. the Grift compiler.
  18185. \begin{center}
  18186. \url{https://github.com/Gradual-Typing/Grift}
  18187. \end{center}
  18188. There are also interesting interactions between gradual typing and
  18189. other language features, such as parametetric polymorphism,
  18190. information-flow types, and type inference, to name a few. We
  18191. recommend the reader to the online gradual typing bibliography:
  18192. \begin{center}
  18193. \url{http://samth.github.io/gradual-typing-bib/}
  18194. \end{center}
  18195. % TODO: challenge problem:
  18196. % type analysis and type specialization?
  18197. % coercions?
  18198. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18199. \chapter{Parametric Polymorphism}
  18200. \label{ch:Lpoly}
  18201. \index{subject}{parametric polymorphism}
  18202. \index{subject}{generics}
  18203. \if\edition\pythonEd
  18204. UNDER CONSTRUCTION
  18205. \fi
  18206. \if\edition\racketEd
  18207. This chapter studies the compilation of parametric
  18208. polymorphism\index{subject}{parametric polymorphism}
  18209. (aka. generics\index{subject}{generics}), compiling the \LangPoly{}
  18210. subset of Typed Racket. Parametric polymorphism enables programmers to
  18211. make code more reusable by parameterizing functions and data
  18212. structures with respect to the types that they operate on. For
  18213. example, Figure~\ref{fig:map-poly} revisits the \code{map} example but
  18214. this time gives it a more fitting type. This \code{map} function is
  18215. parameterized with respect to the element type of the tuple. The type
  18216. of \code{map} is the following polymorphic type as specified by the
  18217. \code{All} and the type parameter \code{a}.
  18218. \begin{lstlisting}
  18219. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18220. \end{lstlisting}
  18221. The idea is that \code{map} can be used at \emph{all} choices of a
  18222. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  18223. \code{map} to a tuple of integers, a choice of \code{Integer} for
  18224. \code{a}, but we could have just as well applied \code{map} to a tuple
  18225. of Booleans.
  18226. \begin{figure}[tbp]
  18227. % poly_test_2.rkt
  18228. \begin{tcolorbox}[colback=white]
  18229. \begin{lstlisting}
  18230. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  18231. (define (map f v)
  18232. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18233. (define (inc [x : Integer]) : Integer (+ x 1))
  18234. (vector-ref (map inc (vector 0 41)) 1)
  18235. \end{lstlisting}
  18236. \end{tcolorbox}
  18237. \caption{The \code{map} example using parametric polymorphism.}
  18238. \label{fig:map-poly}
  18239. \end{figure}
  18240. Figure~\ref{fig:Lpoly-concrete-syntax} defines the concrete syntax of
  18241. \LangPoly{} and Figure~\ref{fig:Lpoly-syntax} defines the abstract
  18242. syntax. We add a second form for function definitions in which a type
  18243. declaration comes before the \code{define}. In the abstract syntax,
  18244. the return type in the \code{Def} is \CANYTY{}, but that should be
  18245. ignored in favor of the return type in the type declaration. (The
  18246. \CANYTY{} comes from using the same parser as in
  18247. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  18248. enables the use of an \code{All} type for a function, thereby making
  18249. it polymorphic. The grammar for types is extended to include
  18250. polymorphic types and type variables.
  18251. \newcommand{\LpolyGrammarRacket}{
  18252. \begin{array}{lcl}
  18253. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18254. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  18255. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  18256. \end{array}
  18257. }
  18258. \newcommand{\LpolyASTRacket}{
  18259. \begin{array}{lcl}
  18260. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18261. \Def &::=& \DECL{\Var}{\Type} \\
  18262. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  18263. \end{array}
  18264. }
  18265. \begin{figure}[tp]
  18266. \centering
  18267. \begin{tcolorbox}[colback=white]
  18268. \footnotesize
  18269. \[
  18270. \begin{array}{l}
  18271. \gray{\LintGrammarRacket{}} \\ \hline
  18272. \gray{\LvarGrammarRacket{}} \\ \hline
  18273. \gray{\LifGrammarRacket{}} \\ \hline
  18274. \gray{\LwhileGrammarRacket} \\ \hline
  18275. \gray{\LtupGrammarRacket} \\ \hline
  18276. \gray{\LfunGrammarRacket} \\ \hline
  18277. \gray{\LlambdaGrammarRacket} \\ \hline
  18278. \LpolyGrammarRacket \\
  18279. \begin{array}{lcl}
  18280. \LangPoly{} &::=& \Def \ldots ~ \Exp
  18281. \end{array}
  18282. \end{array}
  18283. \]
  18284. \end{tcolorbox}
  18285. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  18286. (Figure~\ref{fig:Llam-concrete-syntax}).}
  18287. \label{fig:Lpoly-concrete-syntax}
  18288. \end{figure}
  18289. \begin{figure}[tp]
  18290. \centering
  18291. \begin{tcolorbox}[colback=white]
  18292. \footnotesize
  18293. \[
  18294. \begin{array}{l}
  18295. \gray{\LintOpAST} \\ \hline
  18296. \gray{\LvarASTRacket{}} \\ \hline
  18297. \gray{\LifASTRacket{}} \\ \hline
  18298. \gray{\LwhileASTRacket{}} \\ \hline
  18299. \gray{\LtupASTRacket{}} \\ \hline
  18300. \gray{\LfunASTRacket} \\ \hline
  18301. \gray{\LlambdaASTRacket} \\ \hline
  18302. \LpolyASTRacket \\
  18303. \begin{array}{lcl}
  18304. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18305. \end{array}
  18306. \end{array}
  18307. \]
  18308. \end{tcolorbox}
  18309. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  18310. (Figure~\ref{fig:Llam-syntax}).}
  18311. \label{fig:Lpoly-syntax}
  18312. \end{figure}
  18313. By including polymorphic types in the $\Type$ non-terminal we choose
  18314. to make them first-class which has interesting repercussions on the
  18315. compiler. Many languages with polymorphism, such as
  18316. C++~\citep{stroustrup88:_param_types} and Standard
  18317. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  18318. it may be helpful to see an example of first-class polymorphism in
  18319. action. In Figure~\ref{fig:apply-twice} we define a function
  18320. \code{apply-twice} whose parameter is a polymorphic function. The
  18321. occurrence of a polymorphic type underneath a function type is enabled
  18322. by the normal recursive structure of the grammar for $\Type$ and the
  18323. categorization of the \code{All} type as a $\Type$. The body of
  18324. \code{apply-twice} applies the polymorphic function to a Boolean and
  18325. to an integer.
  18326. \begin{figure}[tbp]
  18327. \begin{tcolorbox}[colback=white]
  18328. \begin{lstlisting}
  18329. (: apply-twice ((All (b) (b -> b)) -> Integer))
  18330. (define (apply-twice f)
  18331. (if (f #t) (f 42) (f 777)))
  18332. (: id (All (a) (a -> a)))
  18333. (define (id x) x)
  18334. (apply-twice id)
  18335. \end{lstlisting}
  18336. \end{tcolorbox}
  18337. \caption{An example illustrating first-class polymorphism.}
  18338. \label{fig:apply-twice}
  18339. \end{figure}
  18340. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  18341. three new responsibilities (compared to \LangLam{}). The type checking of
  18342. function application is extended to handle the case where the operator
  18343. expression is a polymorphic function. In that case the type arguments
  18344. are deduced by matching the type of the parameters with the types of
  18345. the arguments.
  18346. %
  18347. The \code{match-types} auxiliary function carries out this deduction
  18348. by recursively descending through a parameter type \code{pt} and the
  18349. corresponding argument type \code{at}, making sure that they are equal
  18350. except when there is a type parameter on the left (in the parameter
  18351. type). If it is the first time that the type parameter has been
  18352. encountered, then the algorithm deduces an association of the type
  18353. parameter to the corresponding type on the right (in the argument
  18354. type). If it is not the first time that the type parameter has been
  18355. encountered, the algorithm looks up its deduced type and makes sure
  18356. that it is equal to the type on the right.
  18357. %
  18358. Once the type arguments are deduced, the operator expression is
  18359. wrapped in an \code{Inst} AST node (for instantiate) that records the
  18360. type of the operator, but more importantly, records the deduced type
  18361. arguments. The return type of the application is the return type of
  18362. the polymorphic function, but with the type parameters replaced by the
  18363. deduced type arguments, using the \code{subst-type} function.
  18364. The second responsibility of the type checker to extend the
  18365. \code{type-equal?} function to handle the \code{All} type. This is
  18366. not quite as simple as for other types, such as function and tuple
  18367. types, because two polymorphic types can be syntactically different
  18368. even though they are equivalent types. For example, \code{(All (a) (a
  18369. -> a))} is equivalent to \code{(All (b) (b -> b))}. Two polymorphic
  18370. types should be considered equal if they differ only in the choice of
  18371. the names of the type parameters. The \code{type-equal?} function in
  18372. Figure~\ref{fig:type-check-Lvar0-aux} renames the type parameters of
  18373. the first type to match the type parameters of the second type.
  18374. The third responsibility of the type checker is to make sure that only
  18375. defined type variables appear in type annotations. The
  18376. \code{check-well-formed} function defined in
  18377. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  18378. sure that each type variable has been defined.
  18379. The output language of the type checker is \LangInst{}, defined in
  18380. Figure~\ref{fig:Lpoly-prime-syntax}. The type checker combines the type
  18381. declaration and polymorphic function into a single definition, using
  18382. the \code{Poly} form, to make polymorphic functions more convenient to
  18383. process in next pass of the compiler.
  18384. \begin{figure}[tp]
  18385. \centering
  18386. \begin{tcolorbox}[colback=white]
  18387. \small
  18388. \[
  18389. \begin{array}{lcl}
  18390. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18391. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  18392. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  18393. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  18394. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18395. \end{array}
  18396. \]
  18397. \end{tcolorbox}
  18398. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  18399. (Figure~\ref{fig:Llam-syntax}).}
  18400. \label{fig:Lpoly-prime-syntax}
  18401. \end{figure}
  18402. The output of the type checker on the polymorphic \code{map}
  18403. example is listed in Figure~\ref{fig:map-type-check}.
  18404. \begin{figure}[tbp]
  18405. % poly_test_2.rkt
  18406. \begin{tcolorbox}[colback=white]
  18407. \begin{lstlisting}
  18408. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  18409. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  18410. (define (inc [x : Integer]) : Integer (+ x 1))
  18411. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18412. (Integer))
  18413. inc (vector 0 41)) 1)
  18414. \end{lstlisting}
  18415. \end{tcolorbox}
  18416. \caption{Output of the type checker on the \code{map} example.}
  18417. \label{fig:map-type-check}
  18418. \end{figure}
  18419. \begin{figure}[tbp]
  18420. \begin{tcolorbox}[colback=white]
  18421. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18422. (define type-check-poly-class
  18423. (class type-check-Llambda-class
  18424. (super-new)
  18425. (inherit check-type-equal?)
  18426. (define/override (type-check-apply env e1 es)
  18427. (define-values (e^ ty) ((type-check-exp env) e1))
  18428. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  18429. ((type-check-exp env) e)))
  18430. (match ty
  18431. [`(,ty^* ... -> ,rt)
  18432. (for ([arg-ty ty*] [param-ty ty^*])
  18433. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  18434. (values e^ es^ rt)]
  18435. [`(All ,xs (,tys ... -> ,rt))
  18436. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18437. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  18438. (match-types env^^ param-ty arg-ty)))
  18439. (define targs
  18440. (for/list ([x xs])
  18441. (match (dict-ref env^^ x (lambda () #f))
  18442. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  18443. x (Apply e1 es))]
  18444. [ty ty])))
  18445. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  18446. [else (error 'type-check "expected a function, not ~a" ty)]))
  18447. (define/override ((type-check-exp env) e)
  18448. (match e
  18449. [(Lambda `([,xs : ,Ts] ...) rT body)
  18450. (for ([T Ts]) ((check-well-formed env) T))
  18451. ((check-well-formed env) rT)
  18452. ((super type-check-exp env) e)]
  18453. [(HasType e1 ty)
  18454. ((check-well-formed env) ty)
  18455. ((super type-check-exp env) e)]
  18456. [else ((super type-check-exp env) e)]))
  18457. (define/override ((type-check-def env) d)
  18458. (verbose 'type-check "poly/def" d)
  18459. (match d
  18460. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  18461. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  18462. (for ([p ps]) ((check-well-formed ts-env) p))
  18463. ((check-well-formed ts-env) rt)
  18464. (define new-env (append ts-env (map cons xs ps) env))
  18465. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18466. (check-type-equal? ty^ rt body)
  18467. (Generic ts (Def f p:t* rt info body^))]
  18468. [else ((super type-check-def env) d)]))
  18469. (define/override (type-check-program p)
  18470. (match p
  18471. [(Program info body)
  18472. (type-check-program (ProgramDefsExp info '() body))]
  18473. [(ProgramDefsExp info ds body)
  18474. (define ds^ (combine-decls-defs ds))
  18475. (define new-env (for/list ([d ds^])
  18476. (cons (def-name d) (fun-def-type d))))
  18477. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  18478. (define-values (body^ ty) ((type-check-exp new-env) body))
  18479. (check-type-equal? ty 'Integer body)
  18480. (ProgramDefsExp info ds^^ body^)]))
  18481. ))
  18482. \end{lstlisting}
  18483. \end{tcolorbox}
  18484. \caption{Type checker for the \LangPoly{} language.}
  18485. \label{fig:type-check-Lvar0}
  18486. \end{figure}
  18487. \begin{figure}[tbp]
  18488. \begin{tcolorbox}[colback=white]
  18489. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18490. (define/override (type-equal? t1 t2)
  18491. (match* (t1 t2)
  18492. [(`(All ,xs ,T1) `(All ,ys ,T2))
  18493. (define env (map cons xs ys))
  18494. (type-equal? (subst-type env T1) T2)]
  18495. [(other wise)
  18496. (super type-equal? t1 t2)]))
  18497. (define/public (match-types env pt at)
  18498. (match* (pt at)
  18499. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  18500. [('Void 'Void) env] [('Any 'Any) env]
  18501. [(`(Vector ,pts ...) `(Vector ,ats ...))
  18502. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  18503. (match-types env^ pt1 at1))]
  18504. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  18505. (define env^ (match-types env prt art))
  18506. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  18507. (match-types env^^ pt1 at1))]
  18508. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  18509. (define env^ (append (map cons pxs axs) env))
  18510. (match-types env^ pt1 at1)]
  18511. [((? symbol? x) at)
  18512. (match (dict-ref env x (lambda () #f))
  18513. [#f (error 'type-check "undefined type variable ~a" x)]
  18514. ['Type (cons (cons x at) env)]
  18515. [t^ (check-type-equal? at t^ 'matching) env])]
  18516. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  18517. (define/public (subst-type env pt)
  18518. (match pt
  18519. ['Integer 'Integer] ['Boolean 'Boolean]
  18520. ['Void 'Void] ['Any 'Any]
  18521. [`(Vector ,ts ...)
  18522. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  18523. [`(,ts ... -> ,rt)
  18524. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  18525. [`(All ,xs ,t)
  18526. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  18527. [(? symbol? x) (dict-ref env x)]
  18528. [else (error 'type-check "expected a type not ~a" pt)]))
  18529. (define/public (combine-decls-defs ds)
  18530. (match ds
  18531. ['() '()]
  18532. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  18533. (unless (equal? name f)
  18534. (error 'type-check "name mismatch, ~a != ~a" name f))
  18535. (match type
  18536. [`(All ,xs (,ps ... -> ,rt))
  18537. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18538. (cons (Generic xs (Def name params^ rt info body))
  18539. (combine-decls-defs ds^))]
  18540. [`(,ps ... -> ,rt)
  18541. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18542. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  18543. [else (error 'type-check "expected a function type, not ~a" type) ])]
  18544. [`(,(Def f params rt info body) . ,ds^)
  18545. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  18546. \end{lstlisting}
  18547. \end{tcolorbox}
  18548. \caption{Auxiliary functions for type checking \LangPoly{}.}
  18549. \label{fig:type-check-Lvar0-aux}
  18550. \end{figure}
  18551. \begin{figure}[tbp]
  18552. \begin{tcolorbox}[colback=white]
  18553. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  18554. (define/public ((check-well-formed env) ty)
  18555. (match ty
  18556. ['Integer (void)]
  18557. ['Boolean (void)]
  18558. ['Void (void)]
  18559. [(? symbol? a)
  18560. (match (dict-ref env a (lambda () #f))
  18561. ['Type (void)]
  18562. [else (error 'type-check "undefined type variable ~a" a)])]
  18563. [`(Vector ,ts ...)
  18564. (for ([t ts]) ((check-well-formed env) t))]
  18565. [`(,ts ... -> ,t)
  18566. (for ([t ts]) ((check-well-formed env) t))
  18567. ((check-well-formed env) t)]
  18568. [`(All ,xs ,t)
  18569. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18570. ((check-well-formed env^) t)]
  18571. [else (error 'type-check "unrecognized type ~a" ty)]))
  18572. \end{lstlisting}
  18573. \end{tcolorbox}
  18574. \caption{Well-formed types.}
  18575. \label{fig:well-formed-types}
  18576. \end{figure}
  18577. % TODO: interpreter for R'_10
  18578. \clearpage
  18579. \section{Compiling Polymorphism}
  18580. \label{sec:compiling-poly}
  18581. Broadly speaking, there are four approaches to compiling parametric
  18582. polymorphism, which we describe below.
  18583. \begin{description}
  18584. \item[Monomorphization] generates a different version of a polymorphic
  18585. function for each set of type arguments that it is used with,
  18586. producing type-specialized code. This approach results in the most
  18587. efficient code but requires whole-program compilation (no separate
  18588. compilation) and increases code size. For our current purposes
  18589. monomorphization is a non-starter because, with first-class
  18590. polymorphism, it is sometimes not possible to determine which
  18591. generic functions are used with which type arguments during
  18592. compilation. (It can be done at runtime, with just-in-time
  18593. compilation.) Monomorphization is used to compile C++
  18594. templates~\citep{stroustrup88:_param_types} and polymorphic
  18595. functions in NESL~\citep{Blelloch:1993aa} and
  18596. ML~\citep{Weeks:2006aa}.
  18597. \item[Uniform representation] generates one version of each
  18598. polymorphic function but requires all values to have a common
  18599. ``boxed'' format, such as the tagged values of type \CANYTY{} in
  18600. \LangAny{}. Both polymorphic and non-polymorphic (i.e. monomorphic)
  18601. code is compiled similarly to code in a dynamically typed language
  18602. (like \LangDyn{}), in which primitive operators require their
  18603. arguments to be projected from \CANYTY{} and their results are
  18604. injected into \CANYTY{}. (In object-oriented languages, the
  18605. projection is accomplished via virtual method dispatch.) The uniform
  18606. representation approach is compatible with separate compilation and
  18607. with first-class polymorphism. However, it produces the
  18608. least-efficient code because it introduces overhead in the entire
  18609. program. This approach is used in implementations of
  18610. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  18611. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  18612. Java~\citep{Bracha:1998fk}.
  18613. \item[Mixed representation] generates one version of each polymorphic
  18614. function, using a boxed representation for type
  18615. variables. Monomorphic code is compiled as usual (as in \LangLam{})
  18616. and conversions are performed at the boundaries between monomorphic
  18617. and polymorphic (e.g. when a polymorphic function is instantiated
  18618. and called). This approach is compatible with separate compilation
  18619. and first-class polymorphism and maintains efficiency in monomorphic
  18620. code. The trade off is increased overhead at the boundary between
  18621. monomorphic and polymorphic code. This approach is used in
  18622. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  18623. Java 5 with the addition of autoboxing.
  18624. \item[Type passing] uses the unboxed representation in both
  18625. monomorphic and polymorphic code. Each polymorphic function is
  18626. compiled to a single function with extra parameters that describe
  18627. the type arguments. The type information is used by the generated
  18628. code to know how to access the unboxed values at runtime. This
  18629. approach is used in implementation of the Napier88
  18630. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  18631. passing is compatible with separate compilation and first-class
  18632. polymorphism and maintains the efficiency for monomorphic
  18633. code. There is runtime overhead in polymorphic code from dispatching
  18634. on type information.
  18635. \end{description}
  18636. In this chapter we use the mixed representation approach, partly
  18637. because of its favorable attributes, and partly because it is
  18638. straightforward to implement using the tools that we have already
  18639. built to support gradual typing. To compile polymorphic functions, we
  18640. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  18641. \LangCast{}.
  18642. \section{Erase Types}
  18643. \label{sec:erase-types}
  18644. We use the \CANYTY{} type from Chapter~\ref{ch:Ldyn} to
  18645. represent type variables. For example, Figure~\ref{fig:map-erase}
  18646. shows the output of the \code{erase-types} pass on the polymorphic
  18647. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  18648. type parameter \code{a} are replaced by \CANYTY{} and the polymorphic
  18649. \code{All} types are removed from the type of \code{map}.
  18650. \begin{figure}[tbp]
  18651. \begin{tcolorbox}[colback=white]
  18652. \begin{lstlisting}
  18653. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  18654. : (Vector Any Any)
  18655. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18656. (define (inc [x : Integer]) : Integer (+ x 1))
  18657. (vector-ref ((cast map
  18658. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18659. ((Integer -> Integer) (Vector Integer Integer)
  18660. -> (Vector Integer Integer)))
  18661. inc (vector 0 41)) 1)
  18662. \end{lstlisting}
  18663. \end{tcolorbox}
  18664. \caption{The polymorphic \code{map} example after type erasure.}
  18665. \label{fig:map-erase}
  18666. \end{figure}
  18667. This process of type erasure creates a challenge at points of
  18668. instantiation. For example, consider the instantiation of
  18669. \code{map} in Figure~\ref{fig:map-type-check}.
  18670. The type of \code{map} is
  18671. \begin{lstlisting}
  18672. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18673. \end{lstlisting}
  18674. and it is instantiated to
  18675. \begin{lstlisting}
  18676. ((Integer -> Integer) (Vector Integer Integer)
  18677. -> (Vector Integer Integer))
  18678. \end{lstlisting}
  18679. After erasure, the type of \code{map} is
  18680. \begin{lstlisting}
  18681. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18682. \end{lstlisting}
  18683. but we need to convert it to the instantiated type. This is easy to
  18684. do in the language \LangCast{} with a single \code{cast}. In
  18685. Figure~\ref{fig:map-erase}, the instantiation of \code{map} has been
  18686. compiled to a \code{cast} from the type of \code{map} to the
  18687. instantiated type. The source and target type of a cast must be
  18688. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  18689. because both the source and target are obtained from the same
  18690. polymorphic type of \code{map}, replacing the type parameters with
  18691. \CANYTY{} in the former and with the deduced type arguments in the
  18692. later. (Recall that the \CANYTY{} type is consistent with any type.)
  18693. To implement the \code{erase-types} pass, we recommend defining a
  18694. recursive auxiliary function named \code{erase-type} that applies the
  18695. following two transformations. It replaces type variables with
  18696. \CANYTY{}
  18697. \begin{lstlisting}
  18698. |$x$|
  18699. |$\Rightarrow$|
  18700. Any
  18701. \end{lstlisting}
  18702. and it removes the polymorphic \code{All} types.
  18703. \begin{lstlisting}
  18704. (All |$xs$| |$T_1$|)
  18705. |$\Rightarrow$|
  18706. |$T'_1$|
  18707. \end{lstlisting}
  18708. Apply the \code{erase-type} function to all of the type annotations in
  18709. the program.
  18710. Regarding the translation of expressions, the case for \code{Inst} is
  18711. the interesting one. We translate it into a \code{Cast}, as shown
  18712. below. The type of the subexpression $e$ is the polymorphic type
  18713. $\LP\key{All}~\itm{xs}~T\RP$. The source type of the cast is the erasure of
  18714. $T$, the type $T'$. The target type $T''$ is the result of
  18715. substituting the argument types $ts$ for the type parameters $xs$ in
  18716. $T$ followed by doing type erasure.
  18717. \begin{lstlisting}
  18718. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  18719. |$\Rightarrow$|
  18720. (Cast |$e'$| |$T'$| |$T''$|)
  18721. \end{lstlisting}
  18722. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  18723. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  18724. Finally, each polymorphic function is translated to a regular
  18725. function in which type erasure has been applied to all the type
  18726. annotations and the body.
  18727. \begin{lstlisting}
  18728. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  18729. |$\Rightarrow$|
  18730. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  18731. \end{lstlisting}
  18732. \begin{exercise}\normalfont\normalsize
  18733. Implement a compiler for the polymorphic language \LangPoly{} by
  18734. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  18735. programs that use polymorphic functions. Some of them should make
  18736. use of first-class polymorphism.
  18737. \end{exercise}
  18738. \begin{figure}[p]
  18739. \begin{tcolorbox}[colback=white]
  18740. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18741. \node (Lpoly) at (12,4) {\large \LangPoly{}};
  18742. \node (Lpolyp) at (9,4) {\large \LangInst{}};
  18743. \node (Lgradualp) at (6,4) {\large \LangCast{}};
  18744. \node (Llambdapp) at (3,4) {\large \LangProxy{}};
  18745. \node (Llambdaproxy) at (0,4) {\large \LangPVec{}};
  18746. \node (Llambdaproxy-2) at (0,2) {\large \LangPVec{}};
  18747. \node (Llambdaproxy-3) at (3,2) {\large \LangPVec{}};
  18748. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  18749. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  18750. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  18751. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  18752. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  18753. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  18754. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  18755. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  18756. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  18757. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  18758. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  18759. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  18760. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  18761. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  18762. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  18763. \path[->,bend right=15] (Lpoly) edge [above] node
  18764. {\ttfamily\footnotesize type\_check} (Lpolyp);
  18765. \path[->,bend right=15] (Lpolyp) edge [above] node
  18766. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  18767. \path[->,bend right=15] (Lgradualp) edge [above] node
  18768. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  18769. \path[->,bend right=15] (Llambdapp) edge [above] node
  18770. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  18771. \path[->,bend right=15] (Llambdaproxy) edge [right] node
  18772. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  18773. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  18774. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  18775. \path[->,bend left=15] (Llambdaproxy-3) edge [above] node
  18776. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  18777. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  18778. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  18779. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  18780. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  18781. \path[->,bend left=15] (F1-1) edge [left] node
  18782. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  18783. \path[->,bend left=15] (F1-2) edge [below] node
  18784. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  18785. \path[->,bend right=15] (F1-3) edge [above] node
  18786. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  18787. \path[->,bend right=15] (F1-4) edge [above] node
  18788. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18789. \path[->,bend right=15] (F1-5) edge [above] node
  18790. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  18791. \path[->,bend right=15] (F1-6) edge [right] node
  18792. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18793. \path[->,bend left=15] (C3-2) edge [left] node
  18794. {\ttfamily\footnotesize select\_instr.} (x86-2);
  18795. \path[->,bend right=15] (x86-2) edge [left] node
  18796. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18797. \path[->,bend right=15] (x86-2-1) edge [below] node
  18798. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  18799. \path[->,bend right=15] (x86-2-2) edge [left] node
  18800. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  18801. \path[->,bend left=15] (x86-3) edge [above] node
  18802. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  18803. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  18804. \end{tikzpicture}
  18805. \end{tcolorbox}
  18806. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  18807. \label{fig:Lpoly-passes}
  18808. \end{figure}
  18809. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  18810. needed to compile \LangPoly{}.
  18811. % TODO: challenge problem: specialization of instantiations
  18812. % Further Reading
  18813. \fi
  18814. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18815. \clearpage
  18816. \appendix
  18817. \chapter{Appendix}
  18818. \if\edition\racketEd
  18819. \section{Interpreters}
  18820. \label{appendix:interp}
  18821. \index{subject}{interpreter}
  18822. We provide interpreters for each of the source languages \LangInt{},
  18823. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  18824. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  18825. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  18826. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  18827. and x86 are in the \key{interp.rkt} file.
  18828. \section{Utility Functions}
  18829. \label{appendix:utilities}
  18830. The utility functions described in this section are in the
  18831. \key{utilities.rkt} file of the support code.
  18832. \paragraph{\code{interp-tests}}
  18833. The \key{interp-tests} function runs the compiler passes and the
  18834. interpreters on each of the specified tests to check whether each pass
  18835. is correct. The \key{interp-tests} function has the following
  18836. parameters:
  18837. \begin{description}
  18838. \item[name (a string)] a name to identify the compiler,
  18839. \item[typechecker] a function of exactly one argument that either
  18840. raises an error using the \code{error} function when it encounters a
  18841. type error, or returns \code{\#f} when it encounters a type
  18842. error. If there is no type error, the type checker returns the
  18843. program.
  18844. \item[passes] a list with one entry per pass. An entry is a list with
  18845. four things:
  18846. \begin{enumerate}
  18847. \item a string giving the name of the pass,
  18848. \item the function that implements the pass (a translator from AST
  18849. to AST),
  18850. \item a function that implements the interpreter (a function from
  18851. AST to result value) for the output language,
  18852. \item and a type checker for the output language. Type checkers for
  18853. the $R$ and $C$ languages are provided in the support code. For
  18854. example, the type checkers for \LangVar{} and \LangCVar{} are in
  18855. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  18856. type checker entry is optional. The support code does not provide
  18857. type checkers for the x86 languages.
  18858. \end{enumerate}
  18859. \item[source-interp] an interpreter for the source language. The
  18860. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  18861. \item[test-family (a string)] for example, \code{"var"}, \code{"cond"}, etc.
  18862. \item[tests] a list of test numbers that specifies which tests to
  18863. run. (see below)
  18864. \end{description}
  18865. %
  18866. The \key{interp-tests} function assumes that the subdirectory
  18867. \key{tests} has a collection of Racket programs whose names all start
  18868. with the family name, followed by an underscore and then the test
  18869. number, ending with the file extension \key{.rkt}. Also, for each test
  18870. program that calls \code{read} one or more times, there is a file with
  18871. the same name except that the file extension is \key{.in} that
  18872. provides the input for the Racket program. If the test program is
  18873. expected to fail type checking, then there should be an empty file of
  18874. the same name but with extension \key{.tyerr}.
  18875. \paragraph{\code{compiler-tests}}
  18876. runs the compiler passes to generate x86 (a \key{.s} file) and then
  18877. runs the GNU C compiler (gcc) to generate machine code. It runs the
  18878. machine code and checks that the output is $42$. The parameters to the
  18879. \code{compiler-tests} function are similar to those of the
  18880. \code{interp-tests} function, and consist of
  18881. \begin{itemize}
  18882. \item a compiler name (a string),
  18883. \item a type checker,
  18884. \item description of the passes,
  18885. \item name of a test-family, and
  18886. \item a list of test numbers.
  18887. \end{itemize}
  18888. \paragraph{\code{compile-file}}
  18889. takes a description of the compiler passes (see the comment for
  18890. \key{interp-tests}) and returns a function that, given a program file
  18891. name (a string ending in \key{.rkt}), applies all of the passes and
  18892. writes the output to a file whose name is the same as the program file
  18893. name but with \key{.rkt} replaced with \key{.s}.
  18894. \paragraph{\code{read-program}}
  18895. takes a file path and parses that file (it must be a Racket program)
  18896. into an abstract syntax tree.
  18897. \paragraph{\code{parse-program}}
  18898. takes an S-expression representation of an abstract syntax tree and converts it into
  18899. the struct-based representation.
  18900. \paragraph{\code{assert}}
  18901. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  18902. and displays the message \key{msg} if the Boolean \key{bool} is false.
  18903. \paragraph{\code{lookup}}
  18904. % remove discussion of lookup? -Jeremy
  18905. takes a key and an alist, and returns the first value that is
  18906. associated with the given key, if there is one. If not, an error is
  18907. triggered. The alist may contain both immutable pairs (built with
  18908. \key{cons}) and mutable pairs (built with \key{mcons}).
  18909. %The \key{map2} function ...
  18910. \fi %\racketEd
  18911. \section{x86 Instruction Set Quick-Reference}
  18912. \label{sec:x86-quick-reference}
  18913. \index{subject}{x86}
  18914. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  18915. do. We write $A \to B$ to mean that the value of $A$ is written into
  18916. location $B$. Address offsets are given in bytes. The instruction
  18917. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  18918. registers (such as \code{\%rax}), or memory references (such as
  18919. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  18920. reference per instruction. Other operands must be immediates or
  18921. registers.
  18922. \begin{table}[tbp]
  18923. \centering
  18924. \begin{tabular}{l|l}
  18925. \textbf{Instruction} & \textbf{Operation} \\ \hline
  18926. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  18927. \texttt{negq} $A$ & $- A \to A$ \\
  18928. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  18929. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  18930. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  18931. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  18932. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  18933. \texttt{retq} & Pops the return address and jumps to it \\
  18934. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  18935. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  18936. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  18937. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  18938. be an immediate) \\
  18939. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  18940. matches the condition code of the instruction, otherwise go to the
  18941. next instructions. The condition codes are \key{e} for ``equal'',
  18942. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  18943. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  18944. \texttt{jl} $L$ & \\
  18945. \texttt{jle} $L$ & \\
  18946. \texttt{jg} $L$ & \\
  18947. \texttt{jge} $L$ & \\
  18948. \texttt{jmp} $L$ & Jump to label $L$ \\
  18949. \texttt{movq} $A$, $B$ & $A \to B$ \\
  18950. \texttt{movzbq} $A$, $B$ &
  18951. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  18952. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  18953. and the extra bytes of $B$ are set to zero.} \\
  18954. & \\
  18955. & \\
  18956. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  18957. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  18958. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  18959. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  18960. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  18961. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  18962. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  18963. description of the condition codes. $A$ must be a single byte register
  18964. (e.g., \texttt{al} or \texttt{cl}).} \\
  18965. \texttt{setl} $A$ & \\
  18966. \texttt{setle} $A$ & \\
  18967. \texttt{setg} $A$ & \\
  18968. \texttt{setge} $A$ &
  18969. \end{tabular}
  18970. \vspace{5pt}
  18971. \caption{Quick-reference for the x86 instructions used in this book.}
  18972. \label{tab:x86-instr}
  18973. \end{table}
  18974. %% \if\edition\racketEd
  18975. %% \cleardoublepage
  18976. %% \section{Concrete Syntax for Intermediate Languages}
  18977. %% The concrete syntax of \LangAny{} is defined in
  18978. %% Figure~\ref{fig:Lany-concrete-syntax}.
  18979. %% \begin{figure}[tp]
  18980. %% \centering
  18981. %% \fbox{
  18982. %% \begin{minipage}{0.97\textwidth}\small
  18983. %% \[
  18984. %% \begin{array}{lcl}
  18985. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  18986. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  18987. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  18988. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  18989. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  18990. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  18991. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  18992. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  18993. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  18994. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  18995. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  18996. %% \MID \LP\key{void?}\;\Exp\RP \\
  18997. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  18998. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  18999. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  19000. %% \end{array}
  19001. %% \]
  19002. %% \end{minipage}
  19003. %% }
  19004. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  19005. %% (Figure~\ref{fig:Llam-syntax}).}
  19006. %% \label{fig:Lany-concrete-syntax}
  19007. %% \end{figure}
  19008. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  19009. %% \LangCFun{} is defined in Figures~\ref{fig:c0-concrete-syntax},
  19010. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  19011. %% \ref{fig:c3-concrete-syntax}, respectively.
  19012. %% \begin{figure}[tbp]
  19013. %% \fbox{
  19014. %% \begin{minipage}{0.96\textwidth}
  19015. %% \small
  19016. %% \[
  19017. %% \begin{array}{lcl}
  19018. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  19019. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  19020. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  19021. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  19022. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  19023. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  19024. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  19025. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  19026. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  19027. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  19028. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  19029. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  19030. %% \end{array}
  19031. %% \]
  19032. %% \end{minipage}
  19033. %% }
  19034. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  19035. %% \label{fig:c2-concrete-syntax}
  19036. %% \end{figure}
  19037. %% \begin{figure}[tp]
  19038. %% \fbox{
  19039. %% \begin{minipage}{0.96\textwidth}
  19040. %% \small
  19041. %% \[
  19042. %% \begin{array}{lcl}
  19043. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  19044. %% \\
  19045. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  19046. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  19047. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  19048. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  19049. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  19050. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  19051. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  19052. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  19053. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  19054. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  19055. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  19056. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  19057. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  19058. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  19059. %% \LangCFunM{} & ::= & \Def\ldots
  19060. %% \end{array}
  19061. %% \]
  19062. %% \end{minipage}
  19063. %% }
  19064. %% \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  19065. %% \label{fig:c3-concrete-syntax}
  19066. %% \end{figure}
  19067. %% \fi % racketEd
  19068. \backmatter
  19069. \addtocontents{toc}{\vspace{11pt}}
  19070. %% \addtocontents{toc}{\vspace{11pt}}
  19071. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  19072. \nocite{*}\let\bibname\refname
  19073. \addcontentsline{toc}{fmbm}{\refname}
  19074. \printbibliography
  19075. %\printindex{authors}{Author Index}
  19076. \printindex{subject}{Subject Index}
  19077. \end{document}
  19078. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  19079. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  19080. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  19081. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  19082. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  19083. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  19084. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  19085. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  19086. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  19087. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  19088. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  19089. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  19090. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  19091. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  19092. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  19093. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  19094. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  19095. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  19096. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  19097. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  19098. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  19099. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  19100. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  19101. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  19102. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  19103. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  19104. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  19105. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  19106. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  19107. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  19108. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  19109. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  19110. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  19111. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  19112. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  19113. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  19114. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  19115. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  19116. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  19117. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  19118. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  19119. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  19120. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  19121. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  19122. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  19123. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  19124. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  19125. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  19126. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  19127. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  19128. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  19129. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  19130. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  19131. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  19132. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  19133. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  19134. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  19135. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  19136. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  19137. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  19138. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  19139. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  19140. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  19141. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  19142. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  19143. % LocalWords: notq setle setg setge