book.tex 735 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360
  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{0}
  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 Massachusetts Institute of Technology Press \\[2ex]
  96. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  97. Subject to such license, all rights are reserved. \\[2ex]
  98. \includegraphics{CCBY-logo}
  99. The MIT Press would like to thank the anonymous peer reviewers who
  100. provided comments on drafts of this book. The generous work of
  101. academic experts is essential for establishing the authority and
  102. quality of our publications. We acknowledge with gratitude the
  103. contributions of these otherwise uncredited readers.
  104. This book was set in Times LT Std Roman by the author. Printed and
  105. bound in the United States of America.
  106. Library of Congress Cataloging-in-Publication Data is available.
  107. ISBN:
  108. 10 9 8 7 6 5 4 3 2 1
  109. %% Jeremy G. Siek. Available for free viewing
  110. %% or personal downloading under the
  111. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  112. %% license.
  113. %% Copyright in this monograph has been licensed exclusively to The MIT
  114. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  115. %% version to the public in 2022. All inquiries regarding rights should
  116. %% be addressed to The MIT Press, Rights and Permissions Department.
  117. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  118. %% All rights reserved. No part of this book may be reproduced in any
  119. %% form by any electronic or mechanical means (including photocopying,
  120. %% recording, or information storage and retrieval) without permission in
  121. %% writing from the publisher.
  122. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  123. %% United States of America.
  124. %% Library of Congress Cataloging-in-Publication Data is available.
  125. %% ISBN:
  126. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  127. \end{copyrightpage}
  128. \dedication{This book is dedicated to the programming language wonks
  129. at Indiana University.}
  130. %% \begin{epigraphpage}
  131. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  132. %% \textit{Book Name if any}}
  133. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  134. %% \end{epigraphpage}
  135. \tableofcontents
  136. %\listoffigures
  137. %\listoftables
  138. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  139. \chapter*{Preface}
  140. \addcontentsline{toc}{fmbm}{Preface}
  141. There is a magical moment when a programmer presses the ``run'' button
  142. and the software begins to execute. Somehow a program written in a
  143. high-level language is running on a computer that is only capable of
  144. shuffling bits. Here we reveal the wizardry that makes that moment
  145. possible. Beginning with the groundbreaking work of Backus and
  146. colleagues in the 1950s, computer scientists discovered techniques for
  147. constructing programs, called \emph{compilers}, that automatically
  148. translate high-level programs into machine code.
  149. We take you on a journey of constructing your own compiler for a small
  150. but powerful language. Along the way we explain the essential
  151. concepts, algorithms, and data structures that underlie compilers. We
  152. develop your understanding of how programs are mapped onto computer
  153. hardware, which is helpful when reasoning about properties at the
  154. junction between hardware and software such as execution time,
  155. software errors, and security vulnerabilities. For those interested
  156. in pursuing compiler construction as a career, our goal is to provide a
  157. stepping-stone to advanced topics such as just-in-time compilation,
  158. program analysis, and program optimization. For those interested in
  159. designing and implementing programming languages, we connect
  160. language design choices to their impact on the compiler and the generated
  161. code.
  162. A compiler is typically organized as a sequence of stages that
  163. progressively translate a program to the code that runs on
  164. hardware. We take this approach to the extreme by partitioning our
  165. compiler into a large number of \emph{nanopasses}, each of which
  166. performs a single task. This enables the testing of each pass in
  167. isolation and focuses our attention, making the compiler far easier to
  168. understand.
  169. The most familiar approach to describing compilers is with each
  170. chapter dedicated to one pass. The problem with that approach is it
  171. obfuscates how language features motivate design choices in a
  172. compiler. We instead take an \emph{incremental} approach in which we
  173. build a complete compiler in each chapter, starting with a small input
  174. language that includes only arithmetic and variables. We add new
  175. language features in subsequent chapters, extending the compiler as
  176. necessary.
  177. Our choice of language features is designed to elicit fundamental
  178. concepts and algorithms used in compilers.
  179. \begin{itemize}
  180. \item We begin with integer arithmetic and local variables in
  181. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  182. the fundamental tools of compiler construction: \emph{abstract
  183. syntax trees} and \emph{recursive functions}.
  184. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  185. \emph{graph coloring} to assign variables to machine registers.
  186. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  187. motivates an elegant recursive algorithm for translating them into
  188. conditional \code{goto}'s.
  189. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  190. variables}. This elicits the need for \emph{dataflow
  191. analysis} in the register allocator.
  192. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  193. \emph{garbage collection}.
  194. \item Chapter~\ref{ch:Lfun} adds functions as first-class values but
  195. without lexical scoping, similar to functions in the C programming
  196. language~\citep{Kernighan:1988nx}. The reader learns about the
  197. procedure call stack and \emph{calling conventions} and how they interact
  198. with register allocation and garbage collection. The chapter also
  199. describes how to generate efficient tail calls.
  200. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  201. scoping, i.e., \emph{lambda} expressions. The reader learns about
  202. \emph{closure conversion}, in which lambdas are translated into a
  203. combination of functions and tuples.
  204. % Chapter about classes and objects?
  205. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  206. point the input languages are statically typed. The reader extends
  207. the statically typed language with an \code{Any} type which serves
  208. as a target for compiling the dynamically typed language.
  209. {\if\edition\pythonEd
  210. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  211. \emph{classes}.
  212. \fi}
  213. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type of
  214. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  215. in which different regions of a program may be static or dynamically
  216. typed. The reader implements runtime support for \emph{proxies} that
  217. allow values to safely move between regions.
  218. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  219. leveraging the \code{Any} type and type casts developed in Chapters
  220. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  221. \end{itemize}
  222. There are many language features that we do not include. Our choices
  223. balance the incidental complexity of a feature versus the fundamental
  224. concepts that it exposes. For example, we include tuples and not
  225. records because they both elicit the study of heap allocation and
  226. garbage collection but records come with more incidental complexity.
  227. Since 2009 drafts of this book have served as the textbook for 16-week
  228. compiler courses for upper-level undergraduates and first-year
  229. graduate students at the University of Colorado and Indiana
  230. University.
  231. %
  232. Students come into the course having learned the basics of
  233. programming, data structures and algorithms, and discrete
  234. mathematics.
  235. %
  236. At the beginning of the course, students form groups of 2-4 people.
  237. The groups complete one chapter every two weeks, starting with
  238. Chapter~\ref{ch:Lvar} and finishing with
  239. Chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  240. that we assign to the graduate students. The last two weeks of the
  241. course involve a final project in which students design and implement
  242. a compiler extension of their choosing. The later chapters can be
  243. used in support of these projects. For compiler courses at
  244. universities on the quarter system (about 10 weeks in length), we
  245. recommend completing up through Chapter~\ref{ch:Lvec} or
  246. Chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  247. students for each compiler pass.
  248. %
  249. The course can be adapted to emphasize functional languages by
  250. skipping Chapter~\ref{ch:Lwhile} (loops) and including
  251. Chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  252. dynamically typed languages by including Chapter~\ref{ch:Ldyn}.
  253. %
  254. \python{A course that emphasizes object-oriented languages would
  255. include Chapter~\ref{ch:Lobject}.}
  256. %
  257. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  258. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  259. Chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  260. tail calls.
  261. This book has been used in compiler courses at California Polytechnic
  262. State University, Portland State University, Rose–Hulman Institute of
  263. Technology, University of Freiburg, University of Massachusetts
  264. Lowell, and the University of Vermont.
  265. \begin{figure}[tp]
  266. \begin{tcolorbox}[colback=white]
  267. {\if\edition\racketEd
  268. \begin{tikzpicture}[baseline=(current bounding box.center)]
  269. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  270. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  271. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  272. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  273. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  274. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  275. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  276. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  277. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  278. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  279. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  280. \path[->] (C1) edge [above] node {} (C2);
  281. \path[->] (C2) edge [above] node {} (C3);
  282. \path[->] (C3) edge [above] node {} (C4);
  283. \path[->] (C4) edge [above] node {} (C5);
  284. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  285. \path[->] (C5) edge [above] node {} (C7);
  286. \path[->] (C6) edge [above] node {} (C7);
  287. \path[->] (C4) edge [above] node {} (C8);
  288. \path[->] (C4) edge [above] node {} (C9);
  289. \path[->] (C7) edge [above] node {} (C10);
  290. \path[->] (C8) edge [above] node {} (C10);
  291. \path[->] (C10) edge [above] node {} (C11);
  292. \end{tikzpicture}
  293. \fi}
  294. {\if\edition\pythonEd
  295. \begin{tikzpicture}[baseline=(current bounding box.center)]
  296. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  297. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  298. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  299. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  300. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  301. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  302. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  303. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  304. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  305. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  306. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  307. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  308. \path[->] (C1) edge [above] node {} (C2);
  309. \path[->] (C2) edge [above] node {} (C3);
  310. \path[->] (C3) edge [above] node {} (C4);
  311. \path[->] (C4) edge [above] node {} (C5);
  312. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  313. \path[->] (C5) edge [above] node {} (C7);
  314. \path[->] (C6) edge [above] node {} (C7);
  315. \path[->] (C4) edge [above] node {} (C8);
  316. \path[->] (C4) edge [above] node {} (C9);
  317. \path[->] (C7) edge [above] node {} (C10);
  318. \path[->] (C8) edge [above] node {} (C10);
  319. \path[->] (C8) edge [above] node {} (CO);
  320. \path[->] (C10) edge [above] node {} (C11);
  321. \end{tikzpicture}
  322. \fi}
  323. \end{tcolorbox}
  324. \caption{Diagram of chapter dependencies.}
  325. \label{fig:chapter-dependences}
  326. \end{figure}
  327. \racket{
  328. We use the \href{https://racket-lang.org/}{Racket} language both for
  329. the implementation of the compiler and for the input language, so the
  330. reader should be proficient with Racket or Scheme. There are many
  331. excellent resources for learning Scheme and
  332. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  333. }
  334. \python{
  335. This edition of the book uses \href{https://www.python.org/}{Python}
  336. both for the implementation of the compiler and for the input language, so the
  337. reader should be proficient with Python. There are many
  338. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  339. }
  340. The support code for this book is in the github repository at
  341. the following location:
  342. \if\edition\racketEd
  343. \begin{center}\small
  344. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  345. \end{center}
  346. \fi
  347. \if\edition\pythonEd
  348. \begin{center}\small
  349. \url{https://github.com/IUCompilerCourse/}
  350. \end{center}
  351. \fi
  352. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  353. is helpful but not necessary for the reader to have taken a computer
  354. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  355. assembly language that are needed in the compiler.
  356. %
  357. We follow the System V calling
  358. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  359. that we generate works with the runtime system (written in C) when it
  360. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  361. operating systems on Intel hardware.
  362. %
  363. On the Windows operating system, \code{gcc} uses the Microsoft x64
  364. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  365. assembly code that we generate does \emph{not} work with the runtime
  366. system on Windows. One workaround is to use a virtual machine with
  367. Linux as the guest operating system.
  368. \section*{Acknowledgments}
  369. The tradition of compiler construction at Indiana University goes back
  370. to research and courses on programming languages by Daniel Friedman in
  371. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  372. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  373. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  374. the compiler course and continued the development of Chez Scheme.
  375. %
  376. The compiler course evolved to incorporate novel pedagogical ideas
  377. while also including elements of real-world compilers. One of
  378. Friedman's ideas was to split the compiler into many small
  379. passes. Another idea, called ``the game'', was to test the code
  380. generated by each pass using interpreters.
  381. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  382. developed infrastructure to support this approach and evolved the
  383. course to use even smaller
  384. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  385. design decisions in this book are inspired by the assignment
  386. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  387. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  388. organization of the course made it difficult for students to
  389. understand the rationale for the compiler design. Ghuloum proposed the
  390. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  391. on.
  392. We thank the many students who served as teaching assistants for the
  393. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  394. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  395. garbage collector and x86 interpreter, Michael Vollmer for work on
  396. efficient tail calls, and Michael Vitousek for help with the first
  397. offering of the incremental compiler course at IU.
  398. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  399. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  400. Michael Wollowski for teaching courses based on drafts of this book
  401. and for their feedback.
  402. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  403. course in the early 2000's and especially for finding the bug that
  404. sent our garbage collector on a wild goose chase!
  405. \mbox{}\\
  406. \noindent Jeremy G. Siek \\
  407. Bloomington, Indiana
  408. \mainmatter
  409. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  410. \chapter{Preliminaries}
  411. \label{ch:trees-recur}
  412. In this chapter we review the basic tools that are needed to implement
  413. a compiler. Programs are typically input by a programmer as text,
  414. i.e., a sequence of characters. The program-as-text representation is
  415. called \emph{concrete syntax}. We use concrete syntax to concisely
  416. write down and talk about programs. Inside the compiler, we use
  417. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  418. that efficiently supports the operations that the compiler needs to
  419. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  420. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  421. from concrete syntax to abstract syntax is a process called
  422. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  423. implementation of parsing in this book.
  424. %
  425. \racket{A parser is provided in the support code for translating from
  426. concrete to abstract syntax.}
  427. %
  428. \python{We use Python's \code{ast} module to translate from concrete
  429. to abstract syntax.}
  430. ASTs can be represented in many different ways inside the compiler,
  431. depending on the programming language used to write the compiler.
  432. %
  433. \racket{We use Racket's
  434. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  435. feature to represent ASTs (Section~\ref{sec:ast}).}
  436. %
  437. \python{We use Python classes and objects to represent ASTs, especially the
  438. classes defined in the standard \code{ast} module for the Python
  439. source language.}
  440. %
  441. We use grammars to define the abstract syntax of programming languages
  442. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  443. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  444. recursive functions to construct and deconstruct ASTs
  445. (Section~\ref{sec:recursion}). This chapter provides an brief
  446. introduction to these ideas.
  447. \racket{\index{subject}{struct}}
  448. \python{\index{subject}{class}\index{subject}{object}}
  449. \section{Abstract Syntax Trees}
  450. \label{sec:ast}
  451. Compilers use abstract syntax trees to represent programs because they
  452. often need to ask questions like: for a given part of a program, what
  453. kind of language feature is it? What are its sub-parts? Consider the
  454. program on the left and its AST on the right. This program is an
  455. addition operation and it has two sub-parts, a
  456. \racket{read}\python{input} operation and a negation. The negation has
  457. another sub-part, the integer constant \code{8}. By using a tree to
  458. represent the program, we can easily follow the links to go from one
  459. part of a program to its sub-parts.
  460. \begin{center}
  461. \begin{minipage}{0.4\textwidth}
  462. \if\edition\racketEd
  463. \begin{lstlisting}
  464. (+ (read) (- 8))
  465. \end{lstlisting}
  466. \fi
  467. \if\edition\pythonEd
  468. \begin{lstlisting}
  469. input_int() + -8
  470. \end{lstlisting}
  471. \fi
  472. \end{minipage}
  473. \begin{minipage}{0.4\textwidth}
  474. \begin{equation}
  475. \begin{tikzpicture}
  476. \node[draw] (plus) at (0 , 0) {\key{+}};
  477. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  478. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  479. \node[draw] (8) at (1 , -3) {\key{8}};
  480. \draw[->] (plus) to (read);
  481. \draw[->] (plus) to (minus);
  482. \draw[->] (minus) to (8);
  483. \end{tikzpicture}
  484. \label{eq:arith-prog}
  485. \end{equation}
  486. \end{minipage}
  487. \end{center}
  488. We use the standard terminology for trees to describe ASTs: each
  489. rectangle above is called a \emph{node}. The arrows connect a node to its
  490. \emph{children} (which are also nodes). The top-most node is the
  491. \emph{root}. Every node except for the root has a \emph{parent} (the
  492. node it is the child of). If a node has no children, it is a
  493. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  494. \index{subject}{node}
  495. \index{subject}{children}
  496. \index{subject}{root}
  497. \index{subject}{parent}
  498. \index{subject}{leaf}
  499. \index{subject}{internal node}
  500. %% Recall that an \emph{symbolic expression} (S-expression) is either
  501. %% \begin{enumerate}
  502. %% \item an atom, or
  503. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  504. %% where $e_1$ and $e_2$ are each an S-expression.
  505. %% \end{enumerate}
  506. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  507. %% null value \code{'()}, etc. We can create an S-expression in Racket
  508. %% simply by writing a backquote (called a quasi-quote in Racket)
  509. %% followed by the textual representation of the S-expression. It is
  510. %% quite common to use S-expressions to represent a list, such as $a, b
  511. %% ,c$ in the following way:
  512. %% \begin{lstlisting}
  513. %% `(a . (b . (c . ())))
  514. %% \end{lstlisting}
  515. %% Each element of the list is in the first slot of a pair, and the
  516. %% second slot is either the rest of the list or the null value, to mark
  517. %% the end of the list. Such lists are so common that Racket provides
  518. %% special notation for them that removes the need for the periods
  519. %% and so many parenthesis:
  520. %% \begin{lstlisting}
  521. %% `(a b c)
  522. %% \end{lstlisting}
  523. %% The following expression creates an S-expression that represents AST
  524. %% \eqref{eq:arith-prog}.
  525. %% \begin{lstlisting}
  526. %% `(+ (read) (- 8))
  527. %% \end{lstlisting}
  528. %% When using S-expressions to represent ASTs, the convention is to
  529. %% represent each AST node as a list and to put the operation symbol at
  530. %% the front of the list. The rest of the list contains the children. So
  531. %% in the above case, the root AST node has operation \code{`+} and its
  532. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  533. %% diagram \eqref{eq:arith-prog}.
  534. %% To build larger S-expressions one often needs to splice together
  535. %% several smaller S-expressions. Racket provides the comma operator to
  536. %% splice an S-expression into a larger one. For example, instead of
  537. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  538. %% we could have first created an S-expression for AST
  539. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  540. %% S-expression.
  541. %% \begin{lstlisting}
  542. %% (define ast1.4 `(- 8))
  543. %% (define ast1_1 `(+ (read) ,ast1.4))
  544. %% \end{lstlisting}
  545. %% In general, the Racket expression that follows the comma (splice)
  546. %% can be any expression that produces an S-expression.
  547. {\if\edition\racketEd
  548. We define a Racket \code{struct} for each kind of node. For this
  549. chapter we require just two kinds of nodes: one for integer constants
  550. and one for primitive operations. The following is the \code{struct}
  551. definition for integer constants.\footnote{All of the AST structures are
  552. defined in the file \code{utilities.rkt} in the support code.}
  553. \begin{lstlisting}
  554. (struct Int (value))
  555. \end{lstlisting}
  556. An integer node includes just one thing: the integer value.
  557. To create an AST node for the integer $8$, we write \INT{8}.
  558. \begin{lstlisting}
  559. (define eight (Int 8))
  560. \end{lstlisting}
  561. We say that the value created by \INT{8} is an
  562. \emph{instance} of the
  563. \code{Int} structure.
  564. The following is the \code{struct} definition for primitive operations.
  565. \begin{lstlisting}
  566. (struct Prim (op args))
  567. \end{lstlisting}
  568. A primitive operation node includes an operator symbol \code{op} and a
  569. list of child \code{args}. For example, to create an AST that negates
  570. the number $8$, we write the following.
  571. \begin{lstlisting}
  572. (define neg-eight (Prim '- (list eight)))
  573. \end{lstlisting}
  574. Primitive operations may have zero or more children. The \code{read}
  575. operator has zero:
  576. \begin{lstlisting}
  577. (define rd (Prim 'read '()))
  578. \end{lstlisting}
  579. The addition operator has two children:
  580. \begin{lstlisting}
  581. (define ast1_1 (Prim '+ (list rd neg-eight)))
  582. \end{lstlisting}
  583. We have made a design choice regarding the \code{Prim} structure.
  584. Instead of using one structure for many different operations
  585. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  586. structure for each operation, as follows.
  587. \begin{lstlisting}
  588. (struct Read ())
  589. (struct Add (left right))
  590. (struct Neg (value))
  591. \end{lstlisting}
  592. The reason we choose to use just one structure is that in many parts
  593. of the compiler the code for the different primitive operators is the
  594. same, so we might as well just write that code once, which is enabled
  595. by using a single structure.
  596. \fi}
  597. {\if\edition\pythonEd
  598. We use a Python \code{class} for each kind of node.
  599. The following is the class definition for constants.
  600. \begin{lstlisting}
  601. class Constant:
  602. def __init__(self, value):
  603. self.value = value
  604. \end{lstlisting}
  605. An integer constant node includes just one thing: the integer value.
  606. To create an AST node for the integer $8$, we write \INT{8}.
  607. \begin{lstlisting}
  608. eight = Constant(8)
  609. \end{lstlisting}
  610. We say that the value created by \INT{8} is an
  611. \emph{instance} of the \code{Constant} class.
  612. The following is the class definition for unary operators.
  613. \begin{lstlisting}
  614. class UnaryOp:
  615. def __init__(self, op, operand):
  616. self.op = op
  617. self.operand = operand
  618. \end{lstlisting}
  619. The specific operation is specified by the \code{op} parameter. For
  620. example, the class \code{USub} is for unary subtraction. (More unary
  621. operators are introduced in later chapters.) To create an AST that
  622. negates the number $8$, we write the following.
  623. \begin{lstlisting}
  624. neg_eight = UnaryOp(USub(), eight)
  625. \end{lstlisting}
  626. The call to the \code{input\_int} function is represented by the
  627. \code{Call} and \code{Name} classes.
  628. \begin{lstlisting}
  629. class Call:
  630. def __init__(self, func, args):
  631. self.func = func
  632. self.args = args
  633. class Name:
  634. def __init__(self, id):
  635. self.id = id
  636. \end{lstlisting}
  637. To create an AST node that calls \code{input\_int}, we write
  638. \begin{lstlisting}
  639. read = Call(Name('input_int'), [])
  640. \end{lstlisting}
  641. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  642. the \code{BinOp} class for binary operators.
  643. \begin{lstlisting}
  644. class BinOp:
  645. def __init__(self, left, op, right):
  646. self.op = op
  647. self.left = left
  648. self.right = right
  649. \end{lstlisting}
  650. Similar to \code{UnaryOp}, the specific operation is specified by the
  651. \code{op} parameter, which for now is just an instance of the
  652. \code{Add} class. So to create the AST node that adds negative eight
  653. to some user input, we write the following.
  654. \begin{lstlisting}
  655. ast1_1 = BinOp(read, Add(), neg_eight)
  656. \end{lstlisting}
  657. \fi}
  658. When compiling a program such as \eqref{eq:arith-prog}, we need to
  659. know that the operation associated with the root node is addition and
  660. we need to be able to access its two children. \racket{Racket}\python{Python}
  661. provides pattern matching to support these kinds of queries, as we see in
  662. Section~\ref{sec:pattern-matching}.
  663. We often write down the concrete syntax of a program even when we
  664. really have in mind the AST because the concrete syntax is more
  665. concise. We recommend that, in your mind, you always think of
  666. programs as abstract syntax trees.
  667. \section{Grammars}
  668. \label{sec:grammar}
  669. \index{subject}{integer}
  670. \index{subject}{literal}
  671. \index{subject}{constant}
  672. A programming language can be thought of as a \emph{set} of programs.
  673. The set is typically infinite (one can always create larger and larger
  674. programs) so one cannot simply describe a language by listing all of
  675. the programs in the language. Instead we write down a set of rules, a
  676. \emph{grammar}, for building programs. Grammars are often used to
  677. define the concrete syntax of a language but they can also be used to
  678. describe the abstract syntax. We write our rules in a variant of
  679. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  680. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  681. As an example, we describe a small language, named \LangInt{}, that consists of
  682. integers and arithmetic operations.
  683. \index{subject}{grammar}
  684. The first grammar rule for the abstract syntax of \LangInt{} says that an
  685. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  686. \begin{equation}
  687. \Exp ::= \INT{\Int} \label{eq:arith-int}
  688. \end{equation}
  689. %
  690. Each rule has a left-hand-side and a right-hand-side.
  691. If you have an AST node that matches the
  692. right-hand-side, then you can categorize it according to the
  693. left-hand-side.
  694. %
  695. Symbols in typewriter font are \emph{terminal} symbols and must
  696. literally appear in the program for the rule to be applicable.
  697. \index{subject}{terminal}
  698. %
  699. Our grammars do not mention \emph{white-space}, that is, separating characters
  700. like spaces, tabulators, and newlines. White-space may be inserted
  701. between symbols for disambiguation and to improve readability.
  702. \index{subject}{white-space}
  703. %
  704. A name such as $\Exp$ that is defined by the grammar rules is a
  705. \emph{non-terminal}. \index{subject}{non-terminal}
  706. %
  707. The name $\Int$ is also a non-terminal, but instead of defining it
  708. with a grammar rule, we define it with the following explanation. An
  709. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  710. $-$ (for negative integers), such that the sequence of decimals
  711. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  712. the representation of integers using 63 bits, which simplifies several
  713. aspects of compilation. \racket{Thus, these integers correspond to
  714. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  715. \python{In contrast, integers in Python have unlimited precision, but
  716. the techniques needed to handle unlimited precision fall outside the
  717. scope of this book.}
  718. The second grammar rule is the \READOP{} operation that receives an
  719. input integer from the user of the program.
  720. \begin{equation}
  721. \Exp ::= \READ{} \label{eq:arith-read}
  722. \end{equation}
  723. The third rule categorizes the negation of an $\Exp$ node as an
  724. $\Exp$.
  725. \begin{equation}
  726. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  727. \end{equation}
  728. We can apply these rules to categorize the ASTs that are in the
  729. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  730. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  731. following AST is an $\Exp$.
  732. \begin{center}
  733. \begin{minipage}{0.5\textwidth}
  734. \NEG{\INT{\code{8}}}
  735. \end{minipage}
  736. \begin{minipage}{0.25\textwidth}
  737. \begin{equation}
  738. \begin{tikzpicture}
  739. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  740. \node[draw, circle] (8) at (0, -1.2) {$8$};
  741. \draw[->] (minus) to (8);
  742. \end{tikzpicture}
  743. \label{eq:arith-neg8}
  744. \end{equation}
  745. \end{minipage}
  746. \end{center}
  747. The next grammar rules are for addition and subtraction expressions:
  748. \begin{align}
  749. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  750. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  751. \end{align}
  752. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  753. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  754. \eqref{eq:arith-read} and we have already categorized
  755. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  756. to show that
  757. \[
  758. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  759. \]
  760. is an $\Exp$ in the \LangInt{} language.
  761. If you have an AST for which the above rules do not apply, then the
  762. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  763. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  764. because there is no rule for the \key{*} operator. Whenever we
  765. define a language with a grammar, the language only includes those
  766. programs that are justified by the grammar rules.
  767. {\if\edition\pythonEd
  768. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  769. There is a statement for printing the value of an expression
  770. \[
  771. \Stmt{} ::= \PRINT{\Exp}
  772. \]
  773. and a statement that evaluates an expression but ignores the result.
  774. \[
  775. \Stmt{} ::= \EXPR{\Exp}
  776. \]
  777. \fi}
  778. {\if\edition\racketEd
  779. The last grammar rule for \LangInt{} states that there is a
  780. \code{Program} node to mark the top of the whole program:
  781. \[
  782. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  783. \]
  784. The \code{Program} structure is defined as follows
  785. \begin{lstlisting}
  786. (struct Program (info body))
  787. \end{lstlisting}
  788. where \code{body} is an expression. In later chapters, the \code{info}
  789. part will be used to store auxiliary information but for now it is
  790. just the empty list.
  791. \fi}
  792. {\if\edition\pythonEd
  793. The last grammar rule for \LangInt{} states that there is a
  794. \code{Module} node to mark the top of the whole program:
  795. \[
  796. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  797. \]
  798. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  799. this case, a list of statements.
  800. %
  801. The \code{Module} class is defined as follows
  802. \begin{lstlisting}
  803. class Module:
  804. def __init__(self, body):
  805. self.body = body
  806. \end{lstlisting}
  807. where \code{body} is a list of statements.
  808. \fi}
  809. It is common to have many grammar rules with the same left-hand side
  810. but different right-hand sides, such as the rules for $\Exp$ in the
  811. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  812. combine several right-hand-sides into a single rule.
  813. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  814. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  815. defined in Figure~\ref{fig:r0-concrete-syntax}.
  816. \racket{The \code{read-program} function provided in
  817. \code{utilities.rkt} of the support code reads a program in from a
  818. file (the sequence of characters in the concrete syntax of Racket)
  819. and parses it into an abstract syntax tree. See the description of
  820. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  821. details.}
  822. \python{The \code{parse} function in Python's \code{ast} module
  823. converts the concrete syntax (represented as a string) into an
  824. abstract syntax tree.}
  825. \newcommand{\LintGrammarRacket}{
  826. \begin{array}{rcl}
  827. \Type &::=& \key{Integer} \\
  828. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  829. \MID \CSUB{\Exp}{\Exp}
  830. \end{array}
  831. }
  832. \newcommand{\LintASTRacket}{
  833. \begin{array}{rcl}
  834. \Type &::=& \key{Integer} \\
  835. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  836. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  837. \end{array}
  838. }
  839. \newcommand{\LintGrammarPython}{
  840. \begin{array}{rcl}
  841. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  842. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  843. \end{array}
  844. }
  845. \newcommand{\LintASTPython}{
  846. \begin{array}{rcl}
  847. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  848. \itm{unaryop} &::= & \code{USub()} \\
  849. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  850. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  851. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  852. \end{array}
  853. }
  854. \begin{figure}[tp]
  855. \begin{tcolorbox}[colback=white]
  856. {\if\edition\racketEd
  857. \[
  858. \begin{array}{l}
  859. \LintGrammarRacket \\
  860. \begin{array}{rcl}
  861. \LangInt{} &::=& \Exp
  862. \end{array}
  863. \end{array}
  864. \]
  865. \fi}
  866. {\if\edition\pythonEd
  867. \[
  868. \begin{array}{l}
  869. \LintGrammarPython \\
  870. \begin{array}{rcl}
  871. \LangInt{} &::=& \Stmt^{*}
  872. \end{array}
  873. \end{array}
  874. \]
  875. \fi}
  876. \end{tcolorbox}
  877. \caption{The concrete syntax of \LangInt{}.}
  878. \label{fig:r0-concrete-syntax}
  879. \end{figure}
  880. \begin{figure}[tp]
  881. \begin{tcolorbox}[colback=white]
  882. {\if\edition\racketEd
  883. \[
  884. \begin{array}{l}
  885. \LintASTRacket{} \\
  886. \begin{array}{rcl}
  887. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  888. \end{array}
  889. \end{array}
  890. \]
  891. \fi}
  892. {\if\edition\pythonEd
  893. \[
  894. \begin{array}{l}
  895. \LintASTPython\\
  896. \begin{array}{rcl}
  897. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  898. \end{array}
  899. \end{array}
  900. \]
  901. \fi}
  902. \end{tcolorbox}
  903. \caption{The abstract syntax of \LangInt{}.}
  904. \label{fig:r0-syntax}
  905. \end{figure}
  906. \section{Pattern Matching}
  907. \label{sec:pattern-matching}
  908. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  909. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  910. \texttt{match} feature to access the parts of a value.
  911. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  912. \begin{center}
  913. \begin{minipage}{0.5\textwidth}
  914. {\if\edition\racketEd
  915. \begin{lstlisting}
  916. (match ast1_1
  917. [(Prim op (list child1 child2))
  918. (print op)])
  919. \end{lstlisting}
  920. \fi}
  921. {\if\edition\pythonEd
  922. \begin{lstlisting}
  923. match ast1_1:
  924. case BinOp(child1, op, child2):
  925. print(op)
  926. \end{lstlisting}
  927. \fi}
  928. \end{minipage}
  929. \end{center}
  930. {\if\edition\racketEd
  931. %
  932. In the above example, the \texttt{match} form checks whether the AST
  933. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  934. three pattern variables \texttt{op}, \texttt{child1}, and
  935. \texttt{child2}. In general, a match clause consists of a
  936. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  937. recursively defined to be either a pattern variable, a structure name
  938. followed by a pattern for each of the structure's arguments, or an
  939. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  940. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  941. and Chapter 9 of The Racket
  942. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  943. for complete descriptions of \code{match}.)
  944. %
  945. The body of a match clause may contain arbitrary Racket code. The
  946. pattern variables can be used in the scope of the body, such as
  947. \code{op} in \code{(print op)}.
  948. %
  949. \fi}
  950. %
  951. %
  952. {\if\edition\pythonEd
  953. %
  954. In the above example, the \texttt{match} form checks whether the AST
  955. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  956. three pattern variables \texttt{child1}, \texttt{op}, and
  957. \texttt{child2}, and then prints out the operator. In general, each
  958. \code{case} consists of a \emph{pattern} and a
  959. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  960. to be either a pattern variable, a class name followed by a pattern
  961. for each of its constructor's arguments, or other literals such as
  962. strings, lists, etc.
  963. %
  964. The body of each \code{case} may contain arbitrary Python code. The
  965. pattern variables can be used in the body, such as \code{op} in
  966. \code{print(op)}.
  967. %
  968. \fi}
  969. A \code{match} form may contain several clauses, as in the following
  970. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  971. the AST. The \code{match} proceeds through the clauses in order,
  972. checking whether the pattern can match the input AST. The body of the
  973. first clause that matches is executed. The output of \code{leaf} for
  974. several ASTs is shown on the right.
  975. \begin{center}
  976. \begin{minipage}{0.6\textwidth}
  977. {\if\edition\racketEd
  978. \begin{lstlisting}
  979. (define (leaf arith)
  980. (match arith
  981. [(Int n) #t]
  982. [(Prim 'read '()) #t]
  983. [(Prim '- (list e1)) #f]
  984. [(Prim '+ (list e1 e2)) #f]
  985. [(Prim '- (list e1 e2)) #f]))
  986. (leaf (Prim 'read '()))
  987. (leaf (Prim '- (list (Int 8))))
  988. (leaf (Int 8))
  989. \end{lstlisting}
  990. \fi}
  991. {\if\edition\pythonEd
  992. \begin{lstlisting}
  993. def leaf(arith):
  994. match arith:
  995. case Constant(n):
  996. return True
  997. case Call(Name('input_int'), []):
  998. return True
  999. case UnaryOp(USub(), e1):
  1000. return False
  1001. case BinOp(e1, Add(), e2):
  1002. return False
  1003. case BinOp(e1, Sub(), e2):
  1004. return False
  1005. print(leaf(Call(Name('input_int'), [])))
  1006. print(leaf(UnaryOp(USub(), eight)))
  1007. print(leaf(Constant(8)))
  1008. \end{lstlisting}
  1009. \fi}
  1010. \end{minipage}
  1011. \vrule
  1012. \begin{minipage}{0.25\textwidth}
  1013. {\if\edition\racketEd
  1014. \begin{lstlisting}
  1015. #t
  1016. #f
  1017. #t
  1018. \end{lstlisting}
  1019. \fi}
  1020. {\if\edition\pythonEd
  1021. \begin{lstlisting}
  1022. True
  1023. False
  1024. True
  1025. \end{lstlisting}
  1026. \fi}
  1027. \end{minipage}
  1028. \end{center}
  1029. When constructing a \code{match} expression, we refer to the grammar
  1030. definition to identify which non-terminal we are expecting to match
  1031. against, then we make sure that 1) we have one
  1032. \racket{clause}\python{case} for each alternative of that non-terminal
  1033. and 2) that the pattern in each \racket{clause}\python{case}
  1034. corresponds to the corresponding right-hand side of a grammar
  1035. rule. For the \code{match} in the \code{leaf} function, we refer to
  1036. the grammar for \LangInt{} in Figure~\ref{fig:r0-syntax}. The $\Exp$
  1037. non-terminal has 4 alternatives, so the \code{match} has 4
  1038. \racket{clauses}\python{cases}. The pattern in each
  1039. \racket{clause}\python{case} corresponds to the right-hand side of a
  1040. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1041. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1042. translating from grammars to patterns, replace non-terminals such as
  1043. $\Exp$ with pattern variables of your choice (e.g. \code{e1} and
  1044. \code{e2}).
  1045. \section{Recursive Functions}
  1046. \label{sec:recursion}
  1047. \index{subject}{recursive function}
  1048. Programs are inherently recursive. For example, an expression is often
  1049. made of smaller expressions. Thus, the natural way to process an
  1050. entire program is with a recursive function. As a first example of
  1051. such a recursive function, we define the function \code{is\_exp} in
  1052. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1053. determines whether or not it is an expression in \LangInt{}.
  1054. %
  1055. We say that a function is defined by \emph{structural recursion} when
  1056. it is defined using a sequence of match \racket{clauses}\python{cases}
  1057. that correspond to a grammar, and the body of each
  1058. \racket{clause}\python{case} makes a recursive call on each child
  1059. node.\footnote{This principle of structuring code according to the
  1060. data definition is advocated in the book \emph{How to Design
  1061. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1062. second function, named \code{stmt}, that recognizes whether a value
  1063. is a \LangInt{} statement.} \python{Finally, }
  1064. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{is\_Lint},
  1065. which determines whether an AST is a program in \LangInt{}. In
  1066. general we can write one recursive function to handle each
  1067. non-terminal in a grammar.\index{subject}{structural recursion} Of the
  1068. two examples at the bottom of the figure, the first is in
  1069. \LangInt{} and the second is not.
  1070. \begin{figure}[tp]
  1071. \begin{tcolorbox}[colback=white]
  1072. {\if\edition\racketEd
  1073. \begin{lstlisting}
  1074. (define (is_exp ast)
  1075. (match ast
  1076. [(Int n) #t]
  1077. [(Prim 'read '()) #t]
  1078. [(Prim '- (list e)) (is_exp e)]
  1079. [(Prim '+ (list e1 e2))
  1080. (and (is_exp e1) (is_exp e2))]
  1081. [(Prim '- (list e1 e2))
  1082. (and (is_exp e1) (is_exp e2))]
  1083. [else #f]))
  1084. (define (is_Lint ast)
  1085. (match ast
  1086. [(Program '() e) (is_exp e)]
  1087. [else #f]))
  1088. (is_Lint (Program '() ast1_1)
  1089. (is_Lint (Program '()
  1090. (Prim '* (list (Prim 'read '())
  1091. (Prim '+ (list (Int 8)))))))
  1092. \end{lstlisting}
  1093. \fi}
  1094. {\if\edition\pythonEd
  1095. \begin{lstlisting}
  1096. def is_exp(e):
  1097. match e:
  1098. case Constant(n):
  1099. return True
  1100. case Call(Name('input_int'), []):
  1101. return True
  1102. case UnaryOp(USub(), e1):
  1103. return is_exp(e1)
  1104. case BinOp(e1, Add(), e2):
  1105. return is_exp(e1) and is_exp(e2)
  1106. case BinOp(e1, Sub(), e2):
  1107. return is_exp(e1) and is_exp(e2)
  1108. case _:
  1109. return False
  1110. def stmt(s):
  1111. match s:
  1112. case Expr(Call(Name('print'), [e])):
  1113. return is_exp(e)
  1114. case Expr(e):
  1115. return is_exp(e)
  1116. case _:
  1117. return False
  1118. def is_Lint(p):
  1119. match p:
  1120. case Module(body):
  1121. return all([stmt(s) for s in body])
  1122. case _:
  1123. return False
  1124. print(is_Lint(Module([Expr(ast1_1)])))
  1125. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1126. UnaryOp(Add(), Constant(8))))])))
  1127. \end{lstlisting}
  1128. \fi}
  1129. \end{tcolorbox}
  1130. \caption{Example of recursive functions for \LangInt{}. These functions
  1131. recognize whether an AST is in \LangInt{}.}
  1132. \label{fig:exp-predicate}
  1133. \end{figure}
  1134. %% You may be tempted to merge the two functions into one, like this:
  1135. %% \begin{center}
  1136. %% \begin{minipage}{0.5\textwidth}
  1137. %% \begin{lstlisting}
  1138. %% (define (Lint ast)
  1139. %% (match ast
  1140. %% [(Int n) #t]
  1141. %% [(Prim 'read '()) #t]
  1142. %% [(Prim '- (list e)) (Lint e)]
  1143. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1144. %% [(Program '() e) (Lint e)]
  1145. %% [else #f]))
  1146. %% \end{lstlisting}
  1147. %% \end{minipage}
  1148. %% \end{center}
  1149. %% %
  1150. %% Sometimes such a trick will save a few lines of code, especially when
  1151. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1152. %% \emph{not} recommended because it can get you into trouble.
  1153. %% %
  1154. %% For example, the above function is subtly wrong:
  1155. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1156. %% returns true when it should return false.
  1157. \section{Interpreters}
  1158. \label{sec:interp_Lint}
  1159. \index{subject}{interpreter}
  1160. The behavior of a program is defined by the specification of the
  1161. programming language.
  1162. %
  1163. \racket{For example, the Scheme language is defined in the report by
  1164. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1165. reference manual~\citep{plt-tr}.}
  1166. %
  1167. \python{For example, the Python language is defined in the Python
  1168. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1169. %
  1170. In this book we use interpreters to specify each language that we
  1171. consider. An interpreter that is designated as the definition of a
  1172. language is called a \emph{definitional
  1173. interpreter}~\citep{reynolds72:_def_interp}.
  1174. \index{subject}{definitional interpreter} We warm up by creating a
  1175. definitional interpreter for the \LangInt{} language. This interpreter
  1176. serves as a second example of structural recursion. The
  1177. \code{interp\_Lint} function is defined in
  1178. Figure~\ref{fig:interp_Lint}.
  1179. %
  1180. \racket{The body of the function is a match on the input program
  1181. followed by a call to the \lstinline{interp_exp} helper function,
  1182. which in turn has one match clause per grammar rule for \LangInt{}
  1183. expressions.}
  1184. %
  1185. \python{The body of the function matches on the \code{Module} AST node
  1186. and then invokes \code{interp\_stmt} on each statement in the
  1187. module. The \code{interp\_stmt} function includes a case for each
  1188. grammar rule of the \Stmt{} non-terminal and it calls
  1189. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1190. function includes a case for each grammar rule of the \Exp{}
  1191. non-terminal.}
  1192. \begin{figure}[tp]
  1193. \begin{tcolorbox}[colback=white]
  1194. {\if\edition\racketEd
  1195. \begin{lstlisting}
  1196. (define (interp_exp e)
  1197. (match e
  1198. [(Int n) n]
  1199. [(Prim 'read '())
  1200. (define r (read))
  1201. (cond [(fixnum? r) r]
  1202. [else (error 'interp_exp "read expected an integer" r)])]
  1203. [(Prim '- (list e))
  1204. (define v (interp_exp e))
  1205. (fx- 0 v)]
  1206. [(Prim '+ (list e1 e2))
  1207. (define v1 (interp_exp e1))
  1208. (define v2 (interp_exp e2))
  1209. (fx+ v1 v2)]
  1210. [(Prim '- (list e1 e2))
  1211. (define v1 ((interp-exp env) e1))
  1212. (define v2 ((interp-exp env) e2))
  1213. (fx- v1 v2)]))
  1214. (define (interp_Lint p)
  1215. (match p
  1216. [(Program '() e) (interp_exp e)]))
  1217. \end{lstlisting}
  1218. \fi}
  1219. {\if\edition\pythonEd
  1220. \begin{lstlisting}
  1221. def interp_exp(e):
  1222. match e:
  1223. case BinOp(left, Add(), right):
  1224. l = interp_exp(left); r = interp_exp(right)
  1225. return l + r
  1226. case BinOp(left, Sub(), right):
  1227. l = interp_exp(left); r = interp_exp(right)
  1228. return l - r
  1229. case UnaryOp(USub(), v):
  1230. return - interp_exp(v)
  1231. case Constant(value):
  1232. return value
  1233. case Call(Name('input_int'), []):
  1234. return int(input())
  1235. def interp_stmt(s):
  1236. match s:
  1237. case Expr(Call(Name('print'), [arg])):
  1238. print(interp_exp(arg))
  1239. case Expr(value):
  1240. interp_exp(value)
  1241. def interp_Lint(p):
  1242. match p:
  1243. case Module(body):
  1244. for s in body:
  1245. interp_stmt(s)
  1246. \end{lstlisting}
  1247. \fi}
  1248. \end{tcolorbox}
  1249. \caption{Interpreter for the \LangInt{} language.}
  1250. \label{fig:interp_Lint}
  1251. \end{figure}
  1252. Let us consider the result of interpreting a few \LangInt{} programs. The
  1253. following program adds two integers.
  1254. {\if\edition\racketEd
  1255. \begin{lstlisting}
  1256. (+ 10 32)
  1257. \end{lstlisting}
  1258. \fi}
  1259. {\if\edition\pythonEd
  1260. \begin{lstlisting}
  1261. print(10 + 32)
  1262. \end{lstlisting}
  1263. \fi}
  1264. %
  1265. \noindent The result is \key{42}, the answer to life, the universe,
  1266. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1267. the Galaxy} by Douglas Adams.}
  1268. %
  1269. We wrote the above program in concrete syntax whereas the parsed
  1270. abstract syntax is:
  1271. {\if\edition\racketEd
  1272. \begin{lstlisting}
  1273. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1274. \end{lstlisting}
  1275. \fi}
  1276. {\if\edition\pythonEd
  1277. \begin{lstlisting}
  1278. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1279. \end{lstlisting}
  1280. \fi}
  1281. The next example demonstrates that expressions may be nested within
  1282. each other, in this case nesting several additions and negations.
  1283. {\if\edition\racketEd
  1284. \begin{lstlisting}
  1285. (+ 10 (- (+ 12 20)))
  1286. \end{lstlisting}
  1287. \fi}
  1288. {\if\edition\pythonEd
  1289. \begin{lstlisting}
  1290. print(10 + -(12 + 20))
  1291. \end{lstlisting}
  1292. \fi}
  1293. %
  1294. \noindent What is the result of the above program?
  1295. {\if\edition\racketEd
  1296. As mentioned previously, the \LangInt{} language does not support
  1297. arbitrarily-large integers, but only $63$-bit integers, so we
  1298. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1299. in Racket.
  1300. Suppose
  1301. \[
  1302. n = 999999999999999999
  1303. \]
  1304. which indeed fits in $63$-bits. What happens when we run the
  1305. following program in our interpreter?
  1306. \begin{lstlisting}
  1307. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1308. \end{lstlisting}
  1309. It produces an error:
  1310. \begin{lstlisting}
  1311. fx+: result is not a fixnum
  1312. \end{lstlisting}
  1313. We establish the convention that if running the definitional
  1314. interpreter on a program produces an error then the meaning of that
  1315. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1316. error is a \code{trapped-error}. A compiler for the language is under
  1317. no obligations regarding programs with unspecified behavior; it does
  1318. not have to produce an executable, and if it does, that executable can
  1319. do anything. On the other hand, if the error is a
  1320. \code{trapped-error}, then the compiler must produce an executable and
  1321. it is required to report that an error occurred. To signal an error,
  1322. exit with a return code of \code{255}. The interpreters in chapters
  1323. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1324. \code{trapped-error}.
  1325. \fi}
  1326. % TODO: how to deal with too-large integers in the Python interpreter?
  1327. %% This convention applies to the languages defined in this
  1328. %% book, as a way to simplify the student's task of implementing them,
  1329. %% but this convention is not applicable to all programming languages.
  1330. %%
  1331. Moving on to the last feature of the \LangInt{} language, the
  1332. \READOP{} operation prompts the user of the program for an integer.
  1333. Recall that program \eqref{eq:arith-prog} requests an integer input
  1334. and then subtracts \code{8}. So if we run
  1335. {\if\edition\racketEd
  1336. \begin{lstlisting}
  1337. (interp_Lint (Program '() ast1_1))
  1338. \end{lstlisting}
  1339. \fi}
  1340. {\if\edition\pythonEd
  1341. \begin{lstlisting}
  1342. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1343. \end{lstlisting}
  1344. \fi}
  1345. \noindent and if the input is \code{50}, the result is \code{42}.
  1346. We include the \READOP{} operation in \LangInt{} so a clever student
  1347. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1348. during compilation to obtain the output and then generates the trivial
  1349. code to produce the output.\footnote{Yes, a clever student did this in the
  1350. first instance of this course!}
  1351. The job of a compiler is to translate a program in one language into a
  1352. program in another language so that the output program behaves the
  1353. same way as the input program. This idea is depicted in the
  1354. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1355. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1356. Given a compiler that translates from language $\mathcal{L}_1$ to
  1357. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1358. compiler must translate it into some program $P_2$ such that
  1359. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1360. same input $i$ yields the same output $o$.
  1361. \begin{equation} \label{eq:compile-correct}
  1362. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1363. \node (p1) at (0, 0) {$P_1$};
  1364. \node (p2) at (3, 0) {$P_2$};
  1365. \node (o) at (3, -2.5) {$o$};
  1366. \path[->] (p1) edge [above] node {compile} (p2);
  1367. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1368. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1369. \end{tikzpicture}
  1370. \end{equation}
  1371. In the next section we see our first example of a compiler.
  1372. \section{Example Compiler: a Partial Evaluator}
  1373. \label{sec:partial-evaluation}
  1374. In this section we consider a compiler that translates \LangInt{}
  1375. programs into \LangInt{} programs that may be more efficient. The
  1376. compiler eagerly computes the parts of the program that do not depend
  1377. on any inputs, a process known as \emph{partial
  1378. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1379. For example, given the following program
  1380. {\if\edition\racketEd
  1381. \begin{lstlisting}
  1382. (+ (read) (- (+ 5 3)))
  1383. \end{lstlisting}
  1384. \fi}
  1385. {\if\edition\pythonEd
  1386. \begin{lstlisting}
  1387. print(input_int() + -(5 + 3) )
  1388. \end{lstlisting}
  1389. \fi}
  1390. \noindent our compiler translates it into the program
  1391. {\if\edition\racketEd
  1392. \begin{lstlisting}
  1393. (+ (read) -8)
  1394. \end{lstlisting}
  1395. \fi}
  1396. {\if\edition\pythonEd
  1397. \begin{lstlisting}
  1398. print(input_int() + -8)
  1399. \end{lstlisting}
  1400. \fi}
  1401. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1402. evaluator for the \LangInt{} language. The output of the partial evaluator
  1403. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1404. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1405. whereas the code for partially evaluating the negation and addition
  1406. operations is factored into three auxiliary functions:
  1407. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1408. functions is the output of partially evaluating the children.
  1409. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1410. arguments are integers and if they are, perform the appropriate
  1411. arithmetic. Otherwise, they create an AST node for the arithmetic
  1412. operation.
  1413. \begin{figure}[tp]
  1414. \begin{tcolorbox}[colback=white]
  1415. {\if\edition\racketEd
  1416. \begin{lstlisting}
  1417. (define (pe_neg r)
  1418. (match r
  1419. [(Int n) (Int (fx- 0 n))]
  1420. [else (Prim '- (list r))]))
  1421. (define (pe_add r1 r2)
  1422. (match* (r1 r2)
  1423. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1424. [(_ _) (Prim '+ (list r1 r2))]))
  1425. (define (pe_sub r1 r2)
  1426. (match* (r1 r2)
  1427. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1428. [(_ _) (Prim '- (list r1 r2))]))
  1429. (define (pe_exp e)
  1430. (match e
  1431. [(Int n) (Int n)]
  1432. [(Prim 'read '()) (Prim 'read '())]
  1433. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1434. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1435. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1436. (define (pe_Lint p)
  1437. (match p
  1438. [(Program '() e) (Program '() (pe_exp e))]))
  1439. \end{lstlisting}
  1440. \fi}
  1441. {\if\edition\pythonEd
  1442. \begin{lstlisting}
  1443. def pe_neg(r):
  1444. match r:
  1445. case Constant(n):
  1446. return Constant(-n)
  1447. case _:
  1448. return UnaryOp(USub(), r)
  1449. def pe_add(r1, r2):
  1450. match (r1, r2):
  1451. case (Constant(n1), Constant(n2)):
  1452. return Constant(n1 + n2)
  1453. case _:
  1454. return BinOp(r1, Add(), r2)
  1455. def pe_sub(r1, r2):
  1456. match (r1, r2):
  1457. case (Constant(n1), Constant(n2)):
  1458. return Constant(n1 - n2)
  1459. case _:
  1460. return BinOp(r1, Sub(), r2)
  1461. def pe_exp(e):
  1462. match e:
  1463. case BinOp(left, Add(), right):
  1464. return pe_add(pe_exp(left), pe_exp(right))
  1465. case BinOp(left, Sub(), right):
  1466. return pe_sub(pe_exp(left), pe_exp(right))
  1467. case UnaryOp(USub(), v):
  1468. return pe_neg(pe_exp(v))
  1469. case Constant(value):
  1470. return e
  1471. case Call(Name('input_int'), []):
  1472. return e
  1473. def pe_stmt(s):
  1474. match s:
  1475. case Expr(Call(Name('print'), [arg])):
  1476. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1477. case Expr(value):
  1478. return Expr(pe_exp(value))
  1479. def pe_P_int(p):
  1480. match p:
  1481. case Module(body):
  1482. new_body = [pe_stmt(s) for s in body]
  1483. return Module(new_body)
  1484. \end{lstlisting}
  1485. \fi}
  1486. \end{tcolorbox}
  1487. \caption{A partial evaluator for \LangInt{}.}
  1488. \label{fig:pe-arith}
  1489. \end{figure}
  1490. To gain some confidence that the partial evaluator is correct, we can
  1491. test whether it produces programs that produce the same result as the
  1492. input programs. That is, we can test whether it satisfies Diagram
  1493. \ref{eq:compile-correct}.
  1494. %
  1495. {\if\edition\racketEd
  1496. The following code runs the partial evaluator on several examples and
  1497. tests the output program. The \texttt{parse-program} and
  1498. \texttt{assert} functions are defined in
  1499. Appendix~\ref{appendix:utilities}.\\
  1500. \begin{minipage}{1.0\textwidth}
  1501. \begin{lstlisting}
  1502. (define (test_pe p)
  1503. (assert "testing pe_Lint"
  1504. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1505. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1506. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1507. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1508. \end{lstlisting}
  1509. \end{minipage}
  1510. \fi}
  1511. % TODO: python version of testing the PE
  1512. \begin{exercise}\normalfont\normalsize
  1513. Create three programs in the \LangInt{} language and test whether
  1514. partially evaluating them with \code{pe\_Lint} and then
  1515. interpreting them with \code{interp\_Lint} gives the same result
  1516. as directly interpreting them with \code{interp\_Lint}.
  1517. \end{exercise}
  1518. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1519. \chapter{Integers and Variables}
  1520. \label{ch:Lvar}
  1521. This chapter is about compiling a subset of
  1522. \racket{Racket}\python{Python} to x86-64 assembly
  1523. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1524. integer arithmetic and local variables. We often refer to x86-64
  1525. simply as x86. The chapter begins with a description of the
  1526. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1527. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1528. large so we discuss only the instructions needed for compiling
  1529. \LangVar{}. We introduce more x86 instructions in later chapters.
  1530. After introducing \LangVar{} and x86, we reflect on their differences
  1531. and come up with a plan to break down the translation from \LangVar{}
  1532. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1533. rest of the sections in this chapter give detailed hints regarding
  1534. each step. We hope to give enough hints that the well-prepared
  1535. reader, together with a few friends, can implement a compiler from
  1536. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1537. the scale of this first compiler, the instructor solution for the
  1538. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1539. code.
  1540. \section{The \LangVar{} Language}
  1541. \label{sec:s0}
  1542. \index{subject}{variable}
  1543. The \LangVar{} language extends the \LangInt{} language with
  1544. variables. The concrete syntax of the \LangVar{} language is defined
  1545. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1546. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1547. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1548. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1549. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1550. syntax of \LangVar{} includes the \racket{\key{Program}
  1551. struct}\python{\key{Module} instance} to mark the top of the
  1552. program.
  1553. %% The $\itm{info}$
  1554. %% field of the \key{Program} structure contains an \emph{association
  1555. %% list} (a list of key-value pairs) that is used to communicate
  1556. %% auxiliary data from one compiler pass the next.
  1557. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1558. exhibit several compilation techniques.
  1559. \newcommand{\LvarGrammarRacket}{
  1560. \begin{array}{rcl}
  1561. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1562. \end{array}
  1563. }
  1564. \newcommand{\LvarASTRacket}{
  1565. \begin{array}{rcl}
  1566. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1567. \end{array}
  1568. }
  1569. \newcommand{\LvarGrammarPython}{
  1570. \begin{array}{rcl}
  1571. \Exp &::=& \Var{} \\
  1572. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1573. \end{array}
  1574. }
  1575. \newcommand{\LvarASTPython}{
  1576. \begin{array}{rcl}
  1577. \Exp{} &::=& \VAR{\Var{}} \\
  1578. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1579. \end{array}
  1580. }
  1581. \begin{figure}[tp]
  1582. \centering
  1583. \begin{tcolorbox}[colback=white]
  1584. {\if\edition\racketEd
  1585. \[
  1586. \begin{array}{l}
  1587. \gray{\LintGrammarRacket{}} \\ \hline
  1588. \LvarGrammarRacket{} \\
  1589. \begin{array}{rcl}
  1590. \LangVarM{} &::=& \Exp
  1591. \end{array}
  1592. \end{array}
  1593. \]
  1594. \fi}
  1595. {\if\edition\pythonEd
  1596. \[
  1597. \begin{array}{l}
  1598. \gray{\LintGrammarPython} \\ \hline
  1599. \LvarGrammarPython \\
  1600. \begin{array}{rcl}
  1601. \LangVarM{} &::=& \Stmt^{*}
  1602. \end{array}
  1603. \end{array}
  1604. \]
  1605. \fi}
  1606. \end{tcolorbox}
  1607. \caption{The concrete syntax of \LangVar{}.}
  1608. \label{fig:Lvar-concrete-syntax}
  1609. \end{figure}
  1610. \begin{figure}[tp]
  1611. \centering
  1612. \begin{tcolorbox}[colback=white]
  1613. {\if\edition\racketEd
  1614. \[
  1615. \begin{array}{l}
  1616. \gray{\LintASTRacket{}} \\ \hline
  1617. \LvarASTRacket \\
  1618. \begin{array}{rcl}
  1619. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1620. \end{array}
  1621. \end{array}
  1622. \]
  1623. \fi}
  1624. {\if\edition\pythonEd
  1625. \[
  1626. \begin{array}{l}
  1627. \gray{\LintASTPython}\\ \hline
  1628. \LvarASTPython \\
  1629. \begin{array}{rcl}
  1630. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1631. \end{array}
  1632. \end{array}
  1633. \]
  1634. \fi}
  1635. \end{tcolorbox}
  1636. \caption{The abstract syntax of \LangVar{}.}
  1637. \label{fig:Lvar-syntax}
  1638. \end{figure}
  1639. {\if\edition\racketEd
  1640. Let us dive further into the syntax and semantics of the \LangVar{}
  1641. language. The \key{let} feature defines a variable for use within its
  1642. body and initializes the variable with the value of an expression.
  1643. The abstract syntax for \key{let} is defined in
  1644. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1645. \begin{lstlisting}
  1646. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1647. \end{lstlisting}
  1648. For example, the following program initializes \code{x} to $32$ and then
  1649. evaluates the body \code{(+ 10 x)}, producing $42$.
  1650. \begin{lstlisting}
  1651. (let ([x (+ 12 20)]) (+ 10 x))
  1652. \end{lstlisting}
  1653. \fi}
  1654. %
  1655. {\if\edition\pythonEd
  1656. %
  1657. The \LangVar{} language includes assignment statements, which define a
  1658. variable for use in later statements and initializes the variable with
  1659. the value of an expression. The abstract syntax for assignment is
  1660. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1661. assignment is
  1662. \begin{lstlisting}
  1663. |$\itm{var}$| = |$\itm{exp}$|
  1664. \end{lstlisting}
  1665. For example, the following program initializes the variable \code{x}
  1666. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1667. \begin{lstlisting}
  1668. x = 12 + 20
  1669. print(10 + x)
  1670. \end{lstlisting}
  1671. \fi}
  1672. {\if\edition\racketEd
  1673. %
  1674. When there are multiple \key{let}'s for the same variable, the closest
  1675. enclosing \key{let} is used. That is, variable definitions overshadow
  1676. prior definitions. Consider the following program with two \key{let}'s
  1677. that define two variables named \code{x}. Can you figure out the
  1678. result?
  1679. \begin{lstlisting}
  1680. (let ([x 32]) (+ (let ([x 10]) x) x))
  1681. \end{lstlisting}
  1682. For the purposes of depicting which variable occurrences correspond to
  1683. which definitions, the following shows the \code{x}'s annotated with
  1684. subscripts to distinguish them. Double check that your answer for the
  1685. above is the same as your answer for this annotated version of the
  1686. program.
  1687. \begin{lstlisting}
  1688. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1689. \end{lstlisting}
  1690. The initializing expression is always evaluated before the body of the
  1691. \key{let}, so in the following, the \key{read} for \code{x} is
  1692. performed before the \key{read} for \code{y}. Given the input
  1693. $52$ then $10$, the following produces $42$ (not $-42$).
  1694. \begin{lstlisting}
  1695. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1696. \end{lstlisting}
  1697. \fi}
  1698. \subsection{Extensible Interpreters via Method Overriding}
  1699. \label{sec:extensible-interp}
  1700. To prepare for discussing the interpreter of \LangVar{}, we explain
  1701. why we implement it in an object-oriented style. Throughout this book
  1702. we define many interpreters, one for each of language that we
  1703. study. Because each language builds on the prior one, there is a lot
  1704. of commonality between these interpreters. We want to write down the
  1705. common parts just once instead of many times. A naive
  1706. interpreter for \LangVar{} would handle the
  1707. \racket{cases for variables and \code{let}}
  1708. \python{case for variables}
  1709. but dispatch to an interpreter for \LangInt{}
  1710. in the rest of the cases. The following code sketches this idea. (We
  1711. explain the \code{env} parameter soon, in
  1712. Section~\ref{sec:interp-Lvar}.)
  1713. \begin{center}
  1714. {\if\edition\racketEd
  1715. \begin{minipage}{0.45\textwidth}
  1716. \begin{lstlisting}
  1717. (define ((interp_Lint env) e)
  1718. (match e
  1719. [(Prim '- (list e1))
  1720. (fx- 0 ((interp_Lint env) e1))]
  1721. ...))
  1722. \end{lstlisting}
  1723. \end{minipage}
  1724. \begin{minipage}{0.45\textwidth}
  1725. \begin{lstlisting}
  1726. (define ((interp_Lvar env) e)
  1727. (match e
  1728. [(Var x)
  1729. (dict-ref env x)]
  1730. [(Let x e body)
  1731. (define v ((interp_exp env) e))
  1732. (define env^ (dict-set env x v))
  1733. ((interp_exp env^) body)]
  1734. [else ((interp_Lint env) e)]))
  1735. \end{lstlisting}
  1736. \end{minipage}
  1737. \fi}
  1738. {\if\edition\pythonEd
  1739. \begin{minipage}{0.45\textwidth}
  1740. \begin{lstlisting}
  1741. def interp_Lint(e, env):
  1742. match e:
  1743. case UnaryOp(USub(), e1):
  1744. return - interp_Lint(e1, env)
  1745. ...
  1746. \end{lstlisting}
  1747. \end{minipage}
  1748. \begin{minipage}{0.45\textwidth}
  1749. \begin{lstlisting}
  1750. def interp_Lvar(e, env):
  1751. match e:
  1752. case Name(id):
  1753. return env[id]
  1754. case _:
  1755. return interp_Lint(e, env)
  1756. \end{lstlisting}
  1757. \end{minipage}
  1758. \fi}
  1759. \end{center}
  1760. The problem with this naive approach is that it does not handle
  1761. situations in which an \LangVar{} feature, such as a variable, is
  1762. nested inside an \LangInt{} feature, like the \code{-} operator, as in
  1763. the following program.
  1764. %
  1765. {\if\edition\racketEd
  1766. \begin{lstlisting}
  1767. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1768. \end{lstlisting}
  1769. \fi}
  1770. {\if\edition\pythonEd
  1771. \begin{lstlisting}
  1772. y = 10
  1773. print(-y)
  1774. \end{lstlisting}
  1775. \fi}
  1776. %
  1777. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1778. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1779. then it recursively calls \code{interp\_Lint} again on its argument.
  1780. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1781. an error!
  1782. To make our interpreters extensible we need something called
  1783. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1784. recursive knot is delayed to when the functions are
  1785. composed. Object-oriented languages provide open recursion via
  1786. method overriding\index{subject}{method overriding}. The
  1787. following code uses method overriding to interpret \LangInt{} and
  1788. \LangVar{} using
  1789. %
  1790. \racket{the
  1791. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1792. \index{subject}{class} feature of Racket.}
  1793. %
  1794. \python{a Python \code{class} definition.}
  1795. %
  1796. We define one class for each language and define a method for
  1797. interpreting expressions inside each class. The class for \LangVar{}
  1798. inherits from the class for \LangInt{} and the method
  1799. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1800. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1801. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1802. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1803. \code{interp\_exp} in \LangInt{}.
  1804. \begin{center}
  1805. \hspace{-20pt}
  1806. {\if\edition\racketEd
  1807. \begin{minipage}{0.45\textwidth}
  1808. \begin{lstlisting}
  1809. (define interp-Lint-class
  1810. (class object%
  1811. (define/public ((interp_exp env) e)
  1812. (match e
  1813. [(Prim '- (list e))
  1814. (fx- 0 ((interp_exp env) e))]
  1815. ...))
  1816. ...))
  1817. \end{lstlisting}
  1818. \end{minipage}
  1819. \begin{minipage}{0.45\textwidth}
  1820. \begin{lstlisting}
  1821. (define interp-Lvar-class
  1822. (class interp-Lint-class
  1823. (define/override ((interp_exp env) e)
  1824. (match e
  1825. [(Var x)
  1826. (dict-ref env x)]
  1827. [(Let x e body)
  1828. (define v ((interp_exp env) e))
  1829. (define env^ (dict-set env x v))
  1830. ((interp_exp env^) body)]
  1831. [else
  1832. (super (interp_exp env) e)]))
  1833. ...
  1834. ))
  1835. \end{lstlisting}
  1836. \end{minipage}
  1837. \fi}
  1838. {\if\edition\pythonEd
  1839. \begin{minipage}{0.45\textwidth}
  1840. \begin{lstlisting}
  1841. class InterpLint:
  1842. def interp_exp(e):
  1843. match e:
  1844. case UnaryOp(USub(), e1):
  1845. return -self.interp_exp(e1)
  1846. ...
  1847. ...
  1848. \end{lstlisting}
  1849. \end{minipage}
  1850. \begin{minipage}{0.45\textwidth}
  1851. \begin{lstlisting}
  1852. def InterpLvar(InterpLint):
  1853. def interp_exp(e):
  1854. match e:
  1855. case Name(id):
  1856. return env[id]
  1857. case _:
  1858. return super().interp_exp(e)
  1859. ...
  1860. \end{lstlisting}
  1861. \end{minipage}
  1862. \fi}
  1863. \end{center}
  1864. Getting back to the troublesome example, repeated here:
  1865. {\if\edition\racketEd
  1866. \begin{lstlisting}
  1867. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1868. \end{lstlisting}
  1869. \fi}
  1870. {\if\edition\pythonEd
  1871. \begin{lstlisting}
  1872. y = 10
  1873. print(-y)
  1874. \end{lstlisting}
  1875. \fi}
  1876. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1877. \racket{on this expression,}
  1878. \python{on the \code{-y} expression,}
  1879. %
  1880. call it \code{e0}, by creating an object of the \LangVar{} class
  1881. and calling the \code{interp\_exp} method.
  1882. {\if\edition\racketEd
  1883. \begin{lstlisting}
  1884. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1885. \end{lstlisting}
  1886. \fi}
  1887. {\if\edition\pythonEd
  1888. \begin{lstlisting}
  1889. InterpLvar().interp_exp(e0)
  1890. \end{lstlisting}
  1891. \fi}
  1892. \noindent To process the \code{-} operator, the default case of
  1893. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1894. method in \LangInt{}. But then for the recursive method call, it
  1895. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1896. \code{Var} node is handled correctly. Thus, method overriding gives us
  1897. the open recursion that we need to implement our interpreters in an
  1898. extensible way.
  1899. \subsection{Definitional Interpreter for \LangVar{}}
  1900. \label{sec:interp-Lvar}
  1901. {\if\edition\racketEd
  1902. \begin{figure}[tp]
  1903. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1904. \small
  1905. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1906. An \emph{association list} (alist) is a list of key-value pairs.
  1907. For example, we can map people to their ages with an alist.
  1908. \index{subject}{alist}\index{subject}{association list}
  1909. \begin{lstlisting}[basicstyle=\ttfamily]
  1910. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1911. \end{lstlisting}
  1912. The \emph{dictionary} interface is for mapping keys to values.
  1913. Every alist implements this interface. \index{subject}{dictionary} The package
  1914. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1915. provides many functions for working with dictionaries. Here
  1916. are a few of them:
  1917. \begin{description}
  1918. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1919. returns the value associated with the given $\itm{key}$.
  1920. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1921. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1922. but otherwise is the same as $\itm{dict}$.
  1923. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1924. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1925. of keys and values in $\itm{dict}$. For example, the following
  1926. creates a new alist in which the ages are incremented.
  1927. \end{description}
  1928. \vspace{-10pt}
  1929. \begin{lstlisting}[basicstyle=\ttfamily]
  1930. (for/list ([(k v) (in-dict ages)])
  1931. (cons k (add1 v)))
  1932. \end{lstlisting}
  1933. \end{tcolorbox}
  1934. %\end{wrapfigure}
  1935. \caption{Association lists implement the dictionary interface.}
  1936. \label{fig:alist}
  1937. \end{figure}
  1938. \fi}
  1939. Having justified the use of classes and methods to implement
  1940. interpreters, we revisit the definitional interpreter for \LangInt{}
  1941. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1942. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1943. interpreter for \LangVar{} adds two new \key{match} cases for
  1944. variables and \racket{\key{let}}\python{assignment}. For
  1945. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1946. value bound to a variable to all the uses of the variable. To
  1947. accomplish this, we maintain a mapping from variables to values
  1948. called an \emph{environment}\index{subject}{environment}.
  1949. %
  1950. We use
  1951. %
  1952. \racket{an association list (alist) }%
  1953. %
  1954. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1955. %
  1956. to represent the environment.
  1957. %
  1958. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1959. and the \code{racket/dict} package.}
  1960. %
  1961. The \code{interp\_exp} function takes the current environment,
  1962. \code{env}, as an extra parameter. When the interpreter encounters a
  1963. variable, it looks up the corresponding value in the dictionary.
  1964. %
  1965. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1966. initializing expression, extends the environment with the result
  1967. value bound to the variable, using \code{dict-set}, then evaluates
  1968. the body of the \key{Let}.}
  1969. %
  1970. \python{When the interpreter encounters an assignment, it evaluates
  1971. the initializing expression and then associates the resulting value
  1972. with the variable in the environment.}
  1973. \begin{figure}[tp]
  1974. \begin{tcolorbox}[colback=white]
  1975. {\if\edition\racketEd
  1976. \begin{lstlisting}
  1977. (define interp-Lint-class
  1978. (class object%
  1979. (super-new)
  1980. (define/public ((interp_exp env) e)
  1981. (match e
  1982. [(Int n) n]
  1983. [(Prim 'read '())
  1984. (define r (read))
  1985. (cond [(fixnum? r) r]
  1986. [else (error 'interp_exp "expected an integer" r)])]
  1987. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1988. [(Prim '+ (list e1 e2))
  1989. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1990. [(Prim '- (list e1 e2))
  1991. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1992. (define/public (interp_program p)
  1993. (match p
  1994. [(Program '() e) ((interp_exp '()) e)]))
  1995. ))
  1996. \end{lstlisting}
  1997. \fi}
  1998. {\if\edition\pythonEd
  1999. \begin{lstlisting}
  2000. class InterpLint:
  2001. def interp_exp(self, e, env):
  2002. match e:
  2003. case BinOp(left, Add(), right):
  2004. return self.interp_exp(left, env) + self.interp_exp(right, env)
  2005. case BinOp(left, Sub(), right):
  2006. return self.interp_exp(left, env) - self.interp_exp(right, env)
  2007. case UnaryOp(USub(), v):
  2008. return - self.interp_exp(v, env)
  2009. case Constant(value):
  2010. return value
  2011. case Call(Name('input_int'), []):
  2012. return int(input())
  2013. def interp_stmts(self, ss, env):
  2014. if len(ss) == 0:
  2015. return
  2016. match ss[0]:
  2017. case Expr(Call(Name('print'), [arg])):
  2018. print(self.interp_exp(arg, env), end='')
  2019. return self.interp_stmts(ss[1:], env)
  2020. case Expr(value):
  2021. self.interp_exp(value, env)
  2022. return self.interp_stmts(ss[1:], env)
  2023. def interp(self, p):
  2024. match p:
  2025. case Module(body):
  2026. self.interp_stmts(body, {})
  2027. def interp_Lint(p):
  2028. return InterpLint().interp(p)
  2029. \end{lstlisting}
  2030. \fi}
  2031. \end{tcolorbox}
  2032. \caption{Interpreter for \LangInt{} as a class.}
  2033. \label{fig:interp-Lint-class}
  2034. \end{figure}
  2035. \begin{figure}[tp]
  2036. \begin{tcolorbox}[colback=white]
  2037. {\if\edition\racketEd
  2038. \begin{lstlisting}
  2039. (define interp-Lvar-class
  2040. (class interp-Lint-class
  2041. (super-new)
  2042. (define/override ((interp_exp env) e)
  2043. (match e
  2044. [(Var x) (dict-ref env x)]
  2045. [(Let x e body)
  2046. (define new-env (dict-set env x ((interp_exp env) e)))
  2047. ((interp_exp new-env) body)]
  2048. [else ((super interp-exp env) e)]))
  2049. ))
  2050. (define (interp_Lvar p)
  2051. (send (new interp-Lvar-class) interp_program p))
  2052. \end{lstlisting}
  2053. \fi}
  2054. {\if\edition\pythonEd
  2055. \begin{lstlisting}
  2056. class InterpLvar(InterpLint):
  2057. def interp_exp(self, e, env):
  2058. match e:
  2059. case Name(id):
  2060. return env[id]
  2061. case _:
  2062. return super().interp_exp(e, env)
  2063. def interp_stmts(self, ss, env):
  2064. if len(ss) == 0:
  2065. return
  2066. match ss[0]:
  2067. case Assign([lhs], value):
  2068. env[lhs.id] = self.interp_exp(value, env)
  2069. return self.interp_stmts(ss[1:], env)
  2070. case _:
  2071. return super().interp_stmts(ss, env)
  2072. def interp_Lvar(p):
  2073. return InterpLvar().interp(p)
  2074. \end{lstlisting}
  2075. \fi}
  2076. \end{tcolorbox}
  2077. \caption{Interpreter for the \LangVar{} language.}
  2078. \label{fig:interp-Lvar}
  2079. \end{figure}
  2080. The goal for this chapter is to implement a compiler that translates
  2081. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2082. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2083. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2084. That is, they output the same integer $n$. We depict this correctness
  2085. criteria in the following diagram.
  2086. \[
  2087. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2088. \node (p1) at (0, 0) {$P_1$};
  2089. \node (p2) at (4, 0) {$P_2$};
  2090. \node (o) at (4, -2) {$n$};
  2091. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2092. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2093. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2094. \end{tikzpicture}
  2095. \]
  2096. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2097. compiling \LangVar{}.
  2098. \section{The \LangXInt{} Assembly Language}
  2099. \label{sec:x86}
  2100. \index{subject}{x86}
  2101. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2102. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2103. assembler.
  2104. %
  2105. A program begins with a \code{main} label followed by a sequence of
  2106. instructions. The \key{globl} directive says that the \key{main}
  2107. procedure is externally visible, which is necessary so that the
  2108. operating system can call it.
  2109. %
  2110. An x86 program is stored in the computer's memory. For our purposes,
  2111. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2112. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2113. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2114. the address of the next instruction to be executed. For most
  2115. instructions, the program counter is incremented after the instruction
  2116. is executed, so it points to the next instruction in memory. Most x86
  2117. instructions take two operands, where each operand is either an
  2118. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2119. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2120. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2121. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2122. && \key{r8} \MID \key{r9} \MID \key{r10}
  2123. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2124. \MID \key{r14} \MID \key{r15}}
  2125. \newcommand{\GrammarXInt}{
  2126. \begin{array}{rcl}
  2127. \Reg &::=& \allregisters{} \\
  2128. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2129. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2130. \key{subq} \; \Arg\key{,} \Arg \MID
  2131. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2132. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2133. \key{callq} \; \mathit{label} \MID
  2134. \key{retq} \MID
  2135. \key{jmp}\,\itm{label} \MID \\
  2136. && \itm{label}\key{:}\; \Instr
  2137. \end{array}
  2138. }
  2139. \begin{figure}[tp]
  2140. \begin{tcolorbox}[colback=white]
  2141. {\if\edition\racketEd
  2142. \[
  2143. \begin{array}{l}
  2144. \GrammarXInt \\
  2145. \begin{array}{lcl}
  2146. \LangXIntM{} &::= & \key{.globl main}\\
  2147. & & \key{main:} \; \Instr\ldots
  2148. \end{array}
  2149. \end{array}
  2150. \]
  2151. \fi}
  2152. {\if\edition\pythonEd
  2153. \[
  2154. \begin{array}{lcl}
  2155. \Reg &::=& \allregisters{} \\
  2156. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2157. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2158. \key{subq} \; \Arg\key{,} \Arg \MID
  2159. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2160. && \key{callq} \; \mathit{label} \MID
  2161. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2162. \LangXIntM{} &::= & \key{.globl main}\\
  2163. & & \key{main:} \; \Instr^{*}
  2164. \end{array}
  2165. \]
  2166. \fi}
  2167. \end{tcolorbox}
  2168. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2169. \label{fig:x86-int-concrete}
  2170. \end{figure}
  2171. A register is a special kind of variable that holds a 64-bit
  2172. value. There are 16 general-purpose registers in the computer and
  2173. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2174. is written with a \key{\%} followed by the register name, such as
  2175. \key{\%rax}.
  2176. An immediate value is written using the notation \key{\$}$n$ where $n$
  2177. is an integer.
  2178. %
  2179. %
  2180. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2181. which obtains the address stored in register $r$ and then adds $n$
  2182. bytes to the address. The resulting address is used to load or store
  2183. to memory depending on whether it occurs as a source or destination
  2184. argument of an instruction.
  2185. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2186. source $s$ and destination $d$, applies the arithmetic operation, then
  2187. writes the result back to the destination $d$. \index{subject}{instruction}
  2188. %
  2189. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2190. stores the result in $d$.
  2191. %
  2192. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2193. specified by the label and $\key{retq}$ returns from a procedure to
  2194. its caller.
  2195. %
  2196. We discuss procedure calls in more detail later in this chapter and in
  2197. Chapter~\ref{ch:Lfun}.
  2198. %
  2199. The last letter \key{q} indicates that these instructions operate on
  2200. quadwords, i.e., 64-bit values.
  2201. %
  2202. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2203. counter to the address of the instruction after the specified
  2204. label.}
  2205. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2206. all of the x86 instructions used in this book.
  2207. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2208. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2209. \lstinline{movq $10, %rax}
  2210. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2211. adds $32$ to the $10$ in \key{rax} and
  2212. puts the result, $42$, back into \key{rax}.
  2213. %
  2214. The last instruction \key{retq} finishes the \key{main} function by
  2215. returning the integer in \key{rax} to the operating system. The
  2216. operating system interprets this integer as the program's exit
  2217. code. By convention, an exit code of 0 indicates that a program
  2218. completed successfully, and all other exit codes indicate various
  2219. errors.
  2220. %
  2221. \racket{Nevertheless, in this book we return the result of the program
  2222. as the exit code.}
  2223. \begin{figure}[tbp]
  2224. \begin{minipage}{0.45\textwidth}
  2225. \begin{tcolorbox}[colback=white]
  2226. \begin{lstlisting}
  2227. .globl main
  2228. main:
  2229. movq $10, %rax
  2230. addq $32, %rax
  2231. retq
  2232. \end{lstlisting}
  2233. \end{tcolorbox}
  2234. \end{minipage}
  2235. \caption{An x86 program that computes
  2236. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2237. \label{fig:p0-x86}
  2238. \end{figure}
  2239. We exhibit the use of memory for storing intermediate results in the
  2240. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2241. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2242. uses a region of memory called the \emph{procedure call stack} (or
  2243. \emph{stack} for
  2244. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2245. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2246. for each procedure call. The memory layout for an individual frame is
  2247. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2248. \emph{stack pointer}\index{subject}{stack pointer} and it contains the
  2249. address of the item at the top of the stack. In general, we use the
  2250. term \emph{pointer}\index{subject}{pointer} for something that
  2251. contains an address. The stack grows downward in memory, so we
  2252. increase the size of the stack by subtracting from the stack pointer.
  2253. In the context of a procedure call, the \emph{return
  2254. address}\index{subject}{return address} is the instruction after the
  2255. call instruction on the caller side. The function call instruction,
  2256. \code{callq}, pushes the return address onto the stack prior to
  2257. jumping to the procedure. The register \key{rbp} is the \emph{base
  2258. pointer}\index{subject}{base pointer} and is used to access
  2259. variables that are stored in the frame of the current procedure call.
  2260. The base pointer of the caller is stored after the return address. In
  2261. Figure~\ref{fig:frame} we number the variables from $1$ to
  2262. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2263. at $-16\key{(\%rbp)}$, etc.
  2264. \begin{figure}[tbp]
  2265. \begin{minipage}{0.66\textwidth}
  2266. \begin{tcolorbox}[colback=white]
  2267. {\if\edition\racketEd
  2268. \begin{lstlisting}
  2269. start:
  2270. movq $10, -8(%rbp)
  2271. negq -8(%rbp)
  2272. movq -8(%rbp), %rax
  2273. addq $52, %rax
  2274. jmp conclusion
  2275. .globl main
  2276. main:
  2277. pushq %rbp
  2278. movq %rsp, %rbp
  2279. subq $16, %rsp
  2280. jmp start
  2281. conclusion:
  2282. addq $16, %rsp
  2283. popq %rbp
  2284. retq
  2285. \end{lstlisting}
  2286. \fi}
  2287. {\if\edition\pythonEd
  2288. \begin{lstlisting}
  2289. .globl main
  2290. main:
  2291. pushq %rbp
  2292. movq %rsp, %rbp
  2293. subq $16, %rsp
  2294. movq $10, -8(%rbp)
  2295. negq -8(%rbp)
  2296. movq -8(%rbp), %rax
  2297. addq $52, %rax
  2298. addq $16, %rsp
  2299. popq %rbp
  2300. retq
  2301. \end{lstlisting}
  2302. \fi}
  2303. \end{tcolorbox}
  2304. \end{minipage}
  2305. \caption{An x86 program that computes
  2306. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2307. \label{fig:p1-x86}
  2308. \end{figure}
  2309. \begin{figure}[tbp]
  2310. \centering
  2311. \begin{tabular}{|r|l|} \hline
  2312. Position & Contents \\ \hline
  2313. 8(\key{\%rbp}) & return address \\
  2314. 0(\key{\%rbp}) & old \key{rbp} \\
  2315. -8(\key{\%rbp}) & variable $1$ \\
  2316. -16(\key{\%rbp}) & variable $2$ \\
  2317. \ldots & \ldots \\
  2318. 0(\key{\%rsp}) & variable $n$\\ \hline
  2319. \end{tabular}
  2320. \caption{Memory layout of a frame.}
  2321. \label{fig:frame}
  2322. \end{figure}
  2323. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2324. control is transferred from the operating system to the \code{main}
  2325. function. The operating system issues a \code{callq main} instruction
  2326. which pushes its return address on the stack and then jumps to
  2327. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2328. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2329. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2330. alignment (because the \code{callq} pushed the return address). The
  2331. first three instructions are the typical
  2332. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2333. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2334. pointer \code{rsp} and then saves the base pointer of the caller at
  2335. address \code{rsp} on the stack. The next instruction \code{movq
  2336. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2337. which is pointing at the location of the old base pointer. The
  2338. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2339. make enough room for storing variables. This program needs one
  2340. variable ($8$ bytes) but we round up to 16 bytes so that \code{rsp} is
  2341. 16-byte aligned and we're ready to make calls to other functions.
  2342. \racket{The last instruction of the prelude is \code{jmp start}, which
  2343. transfers control to the instructions that were generated from the
  2344. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2345. \racket{The first instruction under the \code{start} label is}
  2346. %
  2347. \python{The first instruction after the prelude is}
  2348. %
  2349. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2350. %
  2351. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2352. $1$ to $-10$.
  2353. %
  2354. The next instruction moves the $-10$ from variable $1$ into the
  2355. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2356. the value in \code{rax}, updating its contents to $42$.
  2357. \racket{The three instructions under the label \code{conclusion} are the
  2358. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2359. %
  2360. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2361. \code{main} function consists of the last three instructions.}
  2362. %
  2363. The first two restore the \code{rsp} and \code{rbp} registers to the
  2364. state they were in at the beginning of the procedure. In particular,
  2365. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2366. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2367. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2368. \key{retq}, jumps back to the procedure that called this one and adds
  2369. $8$ to the stack pointer.
  2370. Our compiler needs a convenient representation for manipulating x86
  2371. programs, so we define an abstract syntax for x86 in
  2372. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2373. \LangXInt{}.
  2374. %
  2375. {\if\edition\pythonEd%
  2376. The main difference compared to the concrete syntax of \LangXInt{}
  2377. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2378. names, and register names are explicitly represented by strings.
  2379. \fi} %
  2380. {\if\edition\racketEd
  2381. The main difference compared to the concrete syntax of \LangXInt{}
  2382. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2383. front of every instruction. Instead instructions are grouped into
  2384. \emph{basic blocks}\index{subject}{basic block} with a
  2385. label associated with every basic block, which is why the \key{X86Program}
  2386. struct includes an alist mapping labels to basic blocks. The reason for this
  2387. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2388. introduce conditional branching. The \code{Block} structure includes
  2389. an $\itm{info}$ field that is not needed for this chapter but becomes
  2390. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2391. $\itm{info}$ field should contain an empty list.
  2392. \fi}
  2393. %
  2394. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2395. node includes an integer for representing the arity of the function,
  2396. i.e., the number of arguments, which is helpful to know during
  2397. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2398. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2399. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2400. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2401. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2402. \MID \skey{r14} \MID \skey{r15}}
  2403. \newcommand{\ASTXIntRacket}{
  2404. \begin{array}{lcl}
  2405. \Reg &::=& \allregisters{} \\
  2406. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2407. \MID \DEREF{\Reg}{\Int} \\
  2408. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2409. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}
  2410. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2411. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2412. \MID \PUSHQ{\Arg}
  2413. \MID \POPQ{\Arg} \\
  2414. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2415. \MID \RETQ{}
  2416. \MID \JMP{\itm{label}} \\
  2417. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2418. \end{array}
  2419. }
  2420. \begin{figure}[tp]
  2421. \begin{tcolorbox}[colback=white]
  2422. \small
  2423. {\if\edition\racketEd
  2424. \[\arraycolsep=3pt
  2425. \begin{array}{l}
  2426. \ASTXIntRacket \\
  2427. \begin{array}{lcl}
  2428. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2429. \end{array}
  2430. \end{array}
  2431. \]
  2432. \fi}
  2433. {\if\edition\pythonEd
  2434. \[
  2435. \begin{array}{lcl}
  2436. \Reg &::=& \allastregisters{} \\
  2437. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2438. \MID \DEREF{\Reg}{\Int} \\
  2439. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2440. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2441. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2442. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2443. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2444. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2445. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2446. \end{array}
  2447. \]
  2448. \fi}
  2449. \end{tcolorbox}
  2450. \caption{The abstract syntax of \LangXInt{} assembly.}
  2451. \label{fig:x86-int-ast}
  2452. \end{figure}
  2453. \section{Planning the trip to x86}
  2454. \label{sec:plan-s0-x86}
  2455. To compile one language to another it helps to focus on the
  2456. differences between the two languages because the compiler will need
  2457. to bridge those differences. What are the differences between \LangVar{}
  2458. and x86 assembly? Here are some of the most important ones:
  2459. \begin{enumerate}
  2460. \item x86 arithmetic instructions typically have two arguments and
  2461. update the second argument in place. In contrast, \LangVar{}
  2462. arithmetic operations take two arguments and produce a new value.
  2463. An x86 instruction may have at most one memory-accessing argument.
  2464. Furthermore, some x86 instructions place special restrictions on
  2465. their arguments.
  2466. \item An argument of an \LangVar{} operator can be a deeply-nested
  2467. expression, whereas x86 instructions restrict their arguments to be
  2468. integer constants, registers, and memory locations.
  2469. {\if\edition\racketEd
  2470. \item The order of execution in x86 is explicit in the syntax: a
  2471. sequence of instructions and jumps to labeled positions, whereas in
  2472. \LangVar{} the order of evaluation is a left-to-right depth-first
  2473. traversal of the abstract syntax tree.
  2474. \fi}
  2475. \item A program in \LangVar{} can have any number of variables
  2476. whereas x86 has 16 registers and the procedure call stack.
  2477. {\if\edition\racketEd
  2478. \item Variables in \LangVar{} can shadow other variables with the
  2479. same name. In x86, registers have unique names and memory locations
  2480. have unique addresses.
  2481. \fi}
  2482. \end{enumerate}
  2483. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2484. down the problem into several steps, dealing with the above
  2485. differences one at a time. Each of these steps is called a \emph{pass}
  2486. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2487. %
  2488. This terminology comes from the way each step passes over, or
  2489. traverses, the AST of the program.
  2490. %
  2491. Furthermore, we follow the nanopass approach, which means we strive
  2492. for each pass to accomplish one clear objective (not two or three at
  2493. the same time).
  2494. %
  2495. We begin by sketching how we might implement each pass, and give them
  2496. names. We then figure out an ordering of the passes and the
  2497. input/output language for each pass. The very first pass has
  2498. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2499. its output language. In between we can choose whichever language is
  2500. most convenient for expressing the output of each pass, whether that
  2501. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2502. our own design. Finally, to implement each pass we write one
  2503. recursive function per non-terminal in the grammar of the input
  2504. language of the pass. \index{subject}{intermediate language}
  2505. Our compiler for \LangVar{} consists of the following passes.
  2506. %
  2507. \begin{description}
  2508. {\if\edition\racketEd
  2509. \item[\key{uniquify}] deals with the shadowing of variables by
  2510. renaming every variable to a unique name.
  2511. \fi}
  2512. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2513. of a primitive operation or function call is a variable or integer,
  2514. that is, an \emph{atomic} expression. We refer to non-atomic
  2515. expressions as \emph{complex}. This pass introduces temporary
  2516. variables to hold the results of complex
  2517. subexpressions.\index{subject}{atomic
  2518. expression}\index{subject}{complex expression}%
  2519. {\if\edition\racketEd
  2520. \item[\key{explicate\_control}] makes the execution order of the
  2521. program explicit. It converts the abstract syntax tree
  2522. representation into a graph in which each node is a labeled sequence
  2523. of statements and the edges are \code{goto} statements.
  2524. \fi}
  2525. \item[\key{select\_instructions}] handles the difference between
  2526. \LangVar{} operations and x86 instructions. This pass converts each
  2527. \LangVar{} operation to a short sequence of instructions that
  2528. accomplishes the same task.
  2529. \item[\key{assign\_homes}] replaces variables with registers or stack
  2530. locations.
  2531. \end{description}
  2532. %
  2533. {\if\edition\racketEd
  2534. %
  2535. Our treatment of \code{remove\_complex\_operands} and
  2536. \code{explicate\_control} as separate passes is an example of the
  2537. nanopass approach\footnote{For analogous decompositions of the
  2538. translation into continuation passing style, see the work of
  2539. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2540. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2541. %
  2542. \fi}
  2543. The next question is: in what order should we apply these passes? This
  2544. question can be challenging because it is difficult to know ahead of
  2545. time which orderings will be better (easier to implement, produce more
  2546. efficient code, etc.) so oftentimes trial-and-error is
  2547. involved. Nevertheless, we can plan ahead and make educated choices
  2548. regarding the ordering.
  2549. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2550. \key{uniquify}? The \key{uniquify} pass should come first because
  2551. \key{explicate\_control} changes all the \key{let}-bound variables to
  2552. become local variables whose scope is the entire program, which would
  2553. confuse variables with the same name.}
  2554. %
  2555. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2556. because the later removes the \key{let} form, but it is convenient to
  2557. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2558. %
  2559. \racket{The ordering of \key{uniquify} with respect to
  2560. \key{remove\_complex\_operands} does not matter so we arbitrarily choose
  2561. \key{uniquify} to come first.}
  2562. The \key{select\_instructions} and \key{assign\_homes} passes are
  2563. intertwined.
  2564. %
  2565. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2566. passing arguments to functions and it is preferable to assign
  2567. parameters to their corresponding registers. This suggests that it
  2568. would be better to start with the \key{select\_instructions} pass,
  2569. which generates the instructions for argument passing, before
  2570. performing register allocation.
  2571. %
  2572. On the other hand, by selecting instructions first we may run into a
  2573. dead end in \key{assign\_homes}. Recall that only one argument of an
  2574. x86 instruction may be a memory access but \key{assign\_homes} might
  2575. be forced to assign both arguments to memory locations.
  2576. %
  2577. A sophisticated approach is to repeat the two passes until a solution
  2578. is found. However, to reduce implementation complexity we recommend
  2579. placing \key{select\_instructions} first, followed by the
  2580. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2581. that uses a reserved register to fix outstanding problems.
  2582. \begin{figure}[tbp]
  2583. \begin{tcolorbox}[colback=white]
  2584. {\if\edition\racketEd
  2585. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2586. \node (Lvar) at (0,2) {\large \LangVar{}};
  2587. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2588. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2589. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2590. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2591. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2592. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2593. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2594. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2595. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2596. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2597. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2598. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2599. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2600. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2601. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2602. \end{tikzpicture}
  2603. \fi}
  2604. {\if\edition\pythonEd
  2605. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2606. \node (Lvar) at (0,2) {\large \LangVar{}};
  2607. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2608. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2609. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2610. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2611. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2612. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2613. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2614. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2615. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2616. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2617. \end{tikzpicture}
  2618. \fi}
  2619. \end{tcolorbox}
  2620. \caption{Diagram of the passes for compiling \LangVar{}. }
  2621. \label{fig:Lvar-passes}
  2622. \end{figure}
  2623. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2624. passes and identifies the input and output language of each pass.
  2625. %
  2626. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2627. language, which extends \LangXInt{} with an unbounded number of
  2628. program-scope variables and removes the restrictions regarding
  2629. instruction arguments.
  2630. %
  2631. The last pass, \key{prelude\_and\_conclusion}, places the program
  2632. instructions inside a \code{main} function with instructions for the
  2633. prelude and conclusion.
  2634. %
  2635. \racket{In the next section we discuss the \LangCVar{} intermediate
  2636. language that serves as the output of \code{explicate\_control}.}
  2637. %
  2638. The remainder of this chapter provides guidance on the implementation
  2639. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2640. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2641. %% are programs that are still in the \LangVar{} language, though the
  2642. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2643. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2644. %% %
  2645. %% The output of \code{explicate\_control} is in an intermediate language
  2646. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2647. %% syntax, which we introduce in the next section. The
  2648. %% \key{select-instruction} pass translates from \LangCVar{} to
  2649. %% \LangXVar{}. The \key{assign-homes} and
  2650. %% \key{patch-instructions}
  2651. %% passes input and output variants of x86 assembly.
  2652. \newcommand{\CvarGrammarRacket}{
  2653. \begin{array}{lcl}
  2654. \Atm &::=& \Int \MID \Var \\
  2655. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2656. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2657. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2658. \end{array}
  2659. }
  2660. \newcommand{\CvarASTRacket}{
  2661. \begin{array}{lcl}
  2662. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2663. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2664. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2665. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2666. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2667. \end{array}
  2668. }
  2669. {\if\edition\racketEd
  2670. \subsection{The \LangCVar{} Intermediate Language}
  2671. The output of \code{explicate\_control} is similar to the $C$
  2672. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2673. categories for expressions and statements, so we name it \LangCVar{}.
  2674. This style of intermediate language is also known as
  2675. \emph{three-address code}, to emphasize that the typical form of a
  2676. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2677. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2678. The concrete syntax for \LangCVar{} is defined in
  2679. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2680. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2681. %
  2682. The \LangCVar{} language supports the same operators as \LangVar{} but
  2683. the arguments of operators are restricted to atomic
  2684. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2685. assignment statements which can be executed in sequence using the
  2686. \key{Seq} form. A sequence of statements always ends with
  2687. \key{Return}, a guarantee that is baked into the grammar rules for
  2688. \itm{tail}. The naming of this non-terminal comes from the term
  2689. \emph{tail position}\index{subject}{tail position}, which refers to an
  2690. expression that is the last one to execute within a function or
  2691. program.
  2692. A \LangCVar{} program consists of an alist mapping labels to
  2693. tails. This is more general than necessary for the present chapter, as
  2694. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2695. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2696. there will be just one label, \key{start}, and the whole program is
  2697. its tail.
  2698. %
  2699. The $\itm{info}$ field of the \key{CProgram} form, after the
  2700. \code{explicate\_control} pass, contains a mapping from the symbol
  2701. \key{locals} to a list of variables, that is, a list of all the
  2702. variables used in the program. At the start of the program, these
  2703. variables are uninitialized; they become initialized on their first
  2704. assignment.
  2705. \begin{figure}[tbp]
  2706. \begin{tcolorbox}[colback=white]
  2707. \[
  2708. \begin{array}{l}
  2709. \CvarGrammarRacket \\
  2710. \begin{array}{lcl}
  2711. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2712. \end{array}
  2713. \end{array}
  2714. \]
  2715. \end{tcolorbox}
  2716. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2717. \label{fig:c0-concrete-syntax}
  2718. \end{figure}
  2719. \begin{figure}[tbp]
  2720. \begin{tcolorbox}[colback=white]
  2721. \[
  2722. \begin{array}{l}
  2723. \CvarASTRacket \\
  2724. \begin{array}{lcl}
  2725. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2726. \end{array}
  2727. \end{array}
  2728. \]
  2729. \end{tcolorbox}
  2730. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2731. \label{fig:c0-syntax}
  2732. \end{figure}
  2733. The definitional interpreter for \LangCVar{} is in the support code,
  2734. in the file \code{interp-Cvar.rkt}.
  2735. \fi}
  2736. {\if\edition\racketEd
  2737. \section{Uniquify Variables}
  2738. \label{sec:uniquify-Lvar}
  2739. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2740. programs in which every \key{let} binds a unique variable name. For
  2741. example, the \code{uniquify} pass should translate the program on the
  2742. left into the program on the right.
  2743. \begin{transformation}
  2744. \begin{lstlisting}
  2745. (let ([x 32])
  2746. (+ (let ([x 10]) x) x))
  2747. \end{lstlisting}
  2748. \compilesto
  2749. \begin{lstlisting}
  2750. (let ([x.1 32])
  2751. (+ (let ([x.2 10]) x.2) x.1))
  2752. \end{lstlisting}
  2753. \end{transformation}
  2754. The following is another example translation, this time of a program
  2755. with a \key{let} nested inside the initializing expression of another
  2756. \key{let}.
  2757. \begin{transformation}
  2758. \begin{lstlisting}
  2759. (let ([x (let ([x 4])
  2760. (+ x 1))])
  2761. (+ x 2))
  2762. \end{lstlisting}
  2763. \compilesto
  2764. \begin{lstlisting}
  2765. (let ([x.2 (let ([x.1 4])
  2766. (+ x.1 1))])
  2767. (+ x.2 2))
  2768. \end{lstlisting}
  2769. \end{transformation}
  2770. We recommend implementing \code{uniquify} by creating a structurally
  2771. recursive function named \code{uniquify\_exp} that mostly just copies
  2772. an expression. However, when encountering a \key{let}, it should
  2773. generate a unique name for the variable and associate the old name
  2774. with the new name in an alist.\footnote{The Racket function
  2775. \code{gensym} is handy for generating unique variable names.} The
  2776. \code{uniquify\_exp} function needs to access this alist when it gets
  2777. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2778. for the alist.
  2779. The skeleton of the \code{uniquify\_exp} function is shown in
  2780. Figure~\ref{fig:uniquify-Lvar}.
  2781. %% The function is curried so that it is
  2782. %% convenient to partially apply it to an alist and then apply it to
  2783. %% different expressions, as in the last case for primitive operations in
  2784. %% Figure~\ref{fig:uniquify-Lvar}.
  2785. The
  2786. %
  2787. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2788. %
  2789. form of Racket is useful for transforming the element of a list to
  2790. produce a new list.\index{subject}{for/list}
  2791. \begin{figure}[tbp]
  2792. \begin{tcolorbox}[colback=white]
  2793. \begin{lstlisting}
  2794. (define (uniquify_exp env)
  2795. (lambda (e)
  2796. (match e
  2797. [(Var x) ___]
  2798. [(Int n) (Int n)]
  2799. [(Let x e body) ___]
  2800. [(Prim op es)
  2801. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2802. (define (uniquify p)
  2803. (match p
  2804. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2805. \end{lstlisting}
  2806. \end{tcolorbox}
  2807. \caption{Skeleton for the \key{uniquify} pass.}
  2808. \label{fig:uniquify-Lvar}
  2809. \end{figure}
  2810. \begin{exercise}
  2811. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2812. Complete the \code{uniquify} pass by filling in the blanks in
  2813. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2814. variables and for the \key{let} form in the file \code{compiler.rkt}
  2815. in the support code.
  2816. \end{exercise}
  2817. \begin{exercise}
  2818. \normalfont\normalsize
  2819. \label{ex:Lvar}
  2820. Create five \LangVar{} programs that exercise the most interesting
  2821. parts of the \key{uniquify} pass, that is, the programs should include
  2822. \key{let} forms, variables, and variables that shadow each other.
  2823. The five programs should be placed in the subdirectory named
  2824. \key{tests} and the file names should start with \code{var\_test\_}
  2825. followed by a unique integer and end with the file extension
  2826. \key{.rkt}.
  2827. %
  2828. The \key{run-tests.rkt} script in the support code checks whether the
  2829. output programs produce the same result as the input programs. The
  2830. script uses the \key{interp-tests} function
  2831. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2832. your \key{uniquify} pass on the example programs. The \code{passes}
  2833. parameter of \key{interp-tests} is a list that should have one entry
  2834. for each pass in your compiler. For now, define \code{passes} to
  2835. contain just one entry for \code{uniquify} as shown below.
  2836. \begin{lstlisting}
  2837. (define passes
  2838. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2839. \end{lstlisting}
  2840. Run the \key{run-tests.rkt} script in the support code to check
  2841. whether the output programs produce the same result as the input
  2842. programs.
  2843. \end{exercise}
  2844. \fi}
  2845. \section{Remove Complex Operands}
  2846. \label{sec:remove-complex-opera-Lvar}
  2847. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2848. into a restricted form in which the arguments of operations are atomic
  2849. expressions. Put another way, this pass removes complex
  2850. operands\index{subject}{complex operand}, such as the expression
  2851. \racket{\code{(- 10)}}\python{\code{-10}}
  2852. in the program below. This is accomplished by introducing a new
  2853. temporary variable, assigning the complex operand to the new
  2854. variable, and then using the new variable in place of the complex
  2855. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2856. right.
  2857. {\if\edition\racketEd
  2858. \begin{transformation}
  2859. % var_test_19.rkt
  2860. \begin{lstlisting}
  2861. (let ([x (+ 42 (- 10))])
  2862. (+ x 10))
  2863. \end{lstlisting}
  2864. \compilesto
  2865. \begin{lstlisting}
  2866. (let ([x (let ([tmp.1 (- 10)])
  2867. (+ 42 tmp.1))])
  2868. (+ x 10))
  2869. \end{lstlisting}
  2870. \end{transformation}
  2871. \fi}
  2872. {\if\edition\pythonEd
  2873. \begin{transformation}
  2874. \begin{lstlisting}
  2875. x = 42 + -10
  2876. print(x + 10)
  2877. \end{lstlisting}
  2878. \compilesto
  2879. \begin{lstlisting}
  2880. tmp_0 = -10
  2881. x = 42 + tmp_0
  2882. tmp_1 = x + 10
  2883. print(tmp_1)
  2884. \end{lstlisting}
  2885. \end{transformation}
  2886. \fi}
  2887. \newcommand{\LvarMonadASTRacket}{
  2888. \begin{array}{rcl}
  2889. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2890. \Exp &::=& \Atm \MID \READ{} \\
  2891. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2892. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2893. \end{array}
  2894. }
  2895. \newcommand{\LvarMonadASTPython}{
  2896. \begin{array}{rcl}
  2897. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2898. \Exp{} &::=& \Atm \MID \READ{} \\
  2899. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2900. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2901. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2902. \end{array}
  2903. }
  2904. \begin{figure}[tp]
  2905. \centering
  2906. \begin{tcolorbox}[colback=white]
  2907. {\if\edition\racketEd
  2908. \[
  2909. \begin{array}{l}
  2910. \LvarMonadASTRacket \\
  2911. \begin{array}{rcl}
  2912. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2913. \end{array}
  2914. \end{array}
  2915. \]
  2916. \fi}
  2917. {\if\edition\pythonEd
  2918. \[
  2919. \begin{array}{l}
  2920. \LvarMonadASTPython \\
  2921. \begin{array}{rcl}
  2922. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2923. \end{array}
  2924. \end{array}
  2925. \]
  2926. \fi}
  2927. \end{tcolorbox}
  2928. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2929. atomic expressions.}
  2930. \label{fig:Lvar-anf-syntax}
  2931. \end{figure}
  2932. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2933. of this pass, the language \LangVarANF{}. The only difference is that
  2934. operator arguments are restricted to be atomic expressions that are
  2935. defined by the \Atm{} non-terminal. In particular, integer constants
  2936. and variables are atomic.
  2937. The atomic expressions are pure (they do not cause or depend on
  2938. side-effects) whereas complex expressions may have side effects, such
  2939. as \READ{}. A language with this separation between pure versus
  2940. side-effecting expressions is said to be in monadic normal
  2941. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2942. in the name \LangVarANF{}. An important invariant of the
  2943. \code{remove\_complex\_operands} pass is that the relative ordering
  2944. among complex expressions is not changed, but the relative ordering
  2945. between atomic expressions and complex expressions can change and
  2946. often does. The reason that these changes are behavior preserving is
  2947. that the atomic expressions are pure.
  2948. Another well-known form for intermediate languages is the
  2949. \emph{administrative normal form}
  2950. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2951. \index{subject}{administrative normal form} \index{subject}{ANF}
  2952. %
  2953. The \LangVarANF{} language is not quite in ANF because we allow the
  2954. right-hand side of a \code{let} to be a complex expression.
  2955. {\if\edition\racketEd
  2956. We recommend implementing this pass with two mutually recursive
  2957. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2958. \code{rco\_atom} to subexpressions that need to become atomic and to
  2959. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2960. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2961. returns an expression. The \code{rco\_atom} function returns two
  2962. things: an atomic expression and an alist mapping temporary variables to
  2963. complex subexpressions. You can return multiple things from a function
  2964. using Racket's \key{values} form and you can receive multiple things
  2965. from a function call using the \key{define-values} form.
  2966. \fi}
  2967. %
  2968. {\if\edition\pythonEd
  2969. %
  2970. We recommend implementing this pass with an auxiliary method named
  2971. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2972. Boolean that specifies whether the expression needs to become atomic
  2973. or not. The \code{rco\_exp} method should return a pair consisting of
  2974. the new expression and a list of pairs, associating new temporary
  2975. variables with their initializing expressions.
  2976. %
  2977. \fi}
  2978. {\if\edition\racketEd
  2979. %
  2980. Returning to the example program with the expression \code{(+ 42 (-
  2981. 10))}, the subexpression \code{(- 10)} should be processed using the
  2982. \code{rco\_atom} function because it is an argument of the \code{+}
  2983. operator and therefore needs to become atomic. The output of
  2984. \code{rco\_atom} applied to \code{(- 10)} is as follows.
  2985. \begin{transformation}
  2986. \begin{lstlisting}
  2987. (- 10)
  2988. \end{lstlisting}
  2989. \compilesto
  2990. \begin{lstlisting}
  2991. tmp.1
  2992. ((tmp.1 . (- 10)))
  2993. \end{lstlisting}
  2994. \end{transformation}
  2995. \fi}
  2996. %
  2997. {\if\edition\pythonEd
  2998. %
  2999. Returning to the example program with the expression \code{42 + -10},
  3000. the subexpression \code{-10} should be processed using the
  3001. \code{rco\_exp} function with \code{True} as the second argument
  3002. because \code{-10} is an argument of the \code{+} operator and
  3003. therefore needs to become atomic. The output of \code{rco\_exp}
  3004. applied to \code{-10} is as follows.
  3005. \begin{transformation}
  3006. \begin{lstlisting}
  3007. -10
  3008. \end{lstlisting}
  3009. \compilesto
  3010. \begin{lstlisting}
  3011. tmp_1
  3012. [(tmp_1, -10)]
  3013. \end{lstlisting}
  3014. \end{transformation}
  3015. %
  3016. \fi}
  3017. Take special care of programs such as the following that
  3018. %
  3019. \racket{bind a variable to an atomic expression.}
  3020. %
  3021. \python{assign an atomic expression to a variable.}
  3022. %
  3023. You should leave such \racket{variable bindings}\python{assignments}
  3024. unchanged, as shown in the program on the right\\
  3025. %
  3026. {\if\edition\racketEd
  3027. \begin{transformation}
  3028. % var_test_20.rkt
  3029. \begin{lstlisting}
  3030. (let ([a 42])
  3031. (let ([b a])
  3032. b))
  3033. \end{lstlisting}
  3034. \compilesto
  3035. \begin{lstlisting}
  3036. (let ([a 42])
  3037. (let ([b a])
  3038. b))
  3039. \end{lstlisting}
  3040. \end{transformation}
  3041. \fi}
  3042. {\if\edition\pythonEd
  3043. \begin{transformation}
  3044. \begin{lstlisting}
  3045. a = 42
  3046. b = a
  3047. print(b)
  3048. \end{lstlisting}
  3049. \compilesto
  3050. \begin{lstlisting}
  3051. a = 42
  3052. b = a
  3053. print(b)
  3054. \end{lstlisting}
  3055. \end{transformation}
  3056. \fi}
  3057. %
  3058. \noindent A careless implementation might produce the following output with
  3059. unnecessary temporary variables.
  3060. \begin{center}
  3061. \begin{minipage}{0.4\textwidth}
  3062. {\if\edition\racketEd
  3063. \begin{lstlisting}
  3064. (let ([tmp.1 42])
  3065. (let ([a tmp.1])
  3066. (let ([tmp.2 a])
  3067. (let ([b tmp.2])
  3068. b))))
  3069. \end{lstlisting}
  3070. \fi}
  3071. {\if\edition\pythonEd
  3072. \begin{lstlisting}
  3073. tmp_1 = 42
  3074. a = tmp_1
  3075. tmp_2 = a
  3076. b = tmp_2
  3077. print(b)
  3078. \end{lstlisting}
  3079. \fi}
  3080. \end{minipage}
  3081. \end{center}
  3082. \begin{exercise}
  3083. \normalfont\normalsize
  3084. {\if\edition\racketEd
  3085. Implement the \code{remove\_complex\_operands} function in
  3086. \code{compiler.rkt}.
  3087. %
  3088. Create three new \LangVar{} programs that exercise the interesting
  3089. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3090. regarding file names described in Exercise~\ref{ex:Lvar}.
  3091. %
  3092. In the \code{run-tests.rkt} script, add the following entry to the
  3093. list of \code{passes} and then run the script to test your compiler.
  3094. \begin{lstlisting}
  3095. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3096. \end{lstlisting}
  3097. While debugging your compiler, it is often useful to see the
  3098. intermediate programs that are output from each pass. To print the
  3099. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3100. \code{interp-tests} in \code{run-tests.rkt}.
  3101. \fi}
  3102. %
  3103. {\if\edition\pythonEd
  3104. Implement the \code{remove\_complex\_operands} pass in
  3105. \code{compiler.py}, creating auxiliary functions for each
  3106. non-terminal in the grammar, i.e., \code{rco\_exp}
  3107. and \code{rco\_stmt}. We recommend you use the function
  3108. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3109. \fi}
  3110. \end{exercise}
  3111. {\if\edition\pythonEd
  3112. \begin{exercise}
  3113. \normalfont\normalsize
  3114. \label{ex:Lvar}
  3115. Create five \LangVar{} programs that exercise the most interesting
  3116. parts of the \code{remove\_complex\_operands} pass. The five programs
  3117. should be placed in the subdirectory named \key{tests} and the file
  3118. names should start with \code{var\_test\_} followed by a unique
  3119. integer and end with the file extension \key{.py}.
  3120. %% The \key{run-tests.rkt} script in the support code checks whether the
  3121. %% output programs produce the same result as the input programs. The
  3122. %% script uses the \key{interp-tests} function
  3123. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3124. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3125. %% parameter of \key{interp-tests} is a list that should have one entry
  3126. %% for each pass in your compiler. For now, define \code{passes} to
  3127. %% contain just one entry for \code{uniquify} as shown below.
  3128. %% \begin{lstlisting}
  3129. %% (define passes
  3130. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3131. %% \end{lstlisting}
  3132. Run the \key{run-tests.py} script in the support code to check
  3133. whether the output programs produce the same result as the input
  3134. programs.
  3135. \end{exercise}
  3136. \fi}
  3137. {\if\edition\racketEd
  3138. \section{Explicate Control}
  3139. \label{sec:explicate-control-Lvar}
  3140. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3141. programs that make the order of execution explicit in their
  3142. syntax. For now this amounts to flattening \key{let} constructs into a
  3143. sequence of assignment statements. For example, consider the following
  3144. \LangVar{} program.\\
  3145. % var_test_11.rkt
  3146. \begin{minipage}{0.96\textwidth}
  3147. \begin{lstlisting}
  3148. (let ([y (let ([x 20])
  3149. (+ x (let ([x 22]) x)))])
  3150. y)
  3151. \end{lstlisting}
  3152. \end{minipage}\\
  3153. %
  3154. The output of the previous pass is shown below, on the left, and the
  3155. output of \code{explicate\_control} is on the right. Recall that the
  3156. right-hand-side of a \key{let} executes before its body, so the order
  3157. of evaluation for this program is to assign \code{20} to \code{x.1},
  3158. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, then
  3159. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3160. this ordering explicit.
  3161. \begin{transformation}
  3162. \begin{lstlisting}
  3163. (let ([y (let ([x.1 20])
  3164. (let ([x.2 22])
  3165. (+ x.1 x.2)))])
  3166. y)
  3167. \end{lstlisting}
  3168. \compilesto
  3169. \begin{lstlisting}[language=C]
  3170. start:
  3171. x.1 = 20;
  3172. x.2 = 22;
  3173. y = (+ x.1 x.2);
  3174. return y;
  3175. \end{lstlisting}
  3176. \end{transformation}
  3177. \begin{figure}[tbp]
  3178. \begin{tcolorbox}[colback=white]
  3179. \begin{lstlisting}
  3180. (define (explicate_tail e)
  3181. (match e
  3182. [(Var x) ___]
  3183. [(Int n) (Return (Int n))]
  3184. [(Let x rhs body) ___]
  3185. [(Prim op es) ___]
  3186. [else (error "explicate_tail unhandled case" e)]))
  3187. (define (explicate_assign e x cont)
  3188. (match e
  3189. [(Var x) ___]
  3190. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3191. [(Let y rhs body) ___]
  3192. [(Prim op es) ___]
  3193. [else (error "explicate_assign unhandled case" e)]))
  3194. (define (explicate_control p)
  3195. (match p
  3196. [(Program info body) ___]))
  3197. \end{lstlisting}
  3198. \end{tcolorbox}
  3199. \caption{Skeleton for the \code{explicate\_control} pass.}
  3200. \label{fig:explicate-control-Lvar}
  3201. \end{figure}
  3202. The organization of this pass depends on the notion of tail position
  3203. that we have alluded to earlier. Here is the definition.
  3204. \begin{definition}
  3205. The following rules define when an expression is in \textbf{\emph{tail
  3206. position}}\index{subject}{tail position} for the language \LangVar{}.
  3207. \begin{enumerate}
  3208. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3209. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3210. \end{enumerate}
  3211. \end{definition}
  3212. We recommend implementing \code{explicate\_control} using two
  3213. recursive functions, \code{explicate\_tail} and
  3214. \code{explicate\_assign}, as suggested in the skeleton code in
  3215. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3216. function should be applied to expressions in tail position whereas the
  3217. \code{explicate\_assign} should be applied to expressions that occur on
  3218. the right-hand-side of a \key{let}.
  3219. %
  3220. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3221. input and produces a \Tail{} in \LangCVar{} (see
  3222. Figure~\ref{fig:c0-syntax}).
  3223. %
  3224. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3225. the variable that it is to be assigned to, and a \Tail{} in
  3226. \LangCVar{} for the code that comes after the assignment. The
  3227. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3228. The \code{explicate\_assign} function is in accumulator-passing style:
  3229. the \code{cont} parameter is used for accumulating the output. This
  3230. accumulator-passing style plays an important role in how we generate
  3231. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3232. The abbreviation \code{cont} is for continuation because it contains
  3233. the generated code that should come after the current assignment.
  3234. This code organization is also related to continuation-passing style,
  3235. except that \code{cont} is not what happens next during compilation,
  3236. but what happens next in the generated code.
  3237. \begin{exercise}\normalfont\normalsize
  3238. %
  3239. Implement the \code{explicate\_control} function in
  3240. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3241. exercise the code in \code{explicate\_control}.
  3242. %
  3243. In the \code{run-tests.rkt} script, add the following entry to the
  3244. list of \code{passes} and then run the script to test your compiler.
  3245. \begin{lstlisting}
  3246. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3247. \end{lstlisting}
  3248. \end{exercise}
  3249. \fi}
  3250. \section{Select Instructions}
  3251. \label{sec:select-Lvar}
  3252. \index{subject}{instruction selection}
  3253. In the \code{select\_instructions} pass we begin the work of
  3254. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3255. language of this pass is a variant of x86 that still uses variables,
  3256. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3257. non-terminal of the \LangXInt{} abstract syntax
  3258. (Figure~\ref{fig:x86-int-ast}).
  3259. \racket{We recommend implementing the
  3260. \code{select\_instructions} with three auxiliary functions, one for
  3261. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3262. $\Tail$.}
  3263. \python{We recommend implementing an auxiliary function
  3264. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3265. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3266. same and integer constants change to immediates, that is, $\INT{n}$
  3267. changes to $\IMM{n}$.}
  3268. Next consider the cases for the $\Stmt$ non-terminal, starting with
  3269. arithmetic operations. For example, consider the addition operation
  3270. below, on the left side. There is an \key{addq} instruction in x86,
  3271. but it performs an in-place update. So we could move $\Arg_1$
  3272. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3273. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3274. $\Atm_1$ and $\Atm_2$ respectively.
  3275. \begin{transformation}
  3276. {\if\edition\racketEd
  3277. \begin{lstlisting}
  3278. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3279. \end{lstlisting}
  3280. \fi}
  3281. {\if\edition\pythonEd
  3282. \begin{lstlisting}
  3283. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3284. \end{lstlisting}
  3285. \fi}
  3286. \compilesto
  3287. \begin{lstlisting}
  3288. movq |$\Arg_1$|, |$\itm{var}$|
  3289. addq |$\Arg_2$|, |$\itm{var}$|
  3290. \end{lstlisting}
  3291. \end{transformation}
  3292. There are also cases that require special care to avoid generating
  3293. needlessly complicated code. For example, if one of the arguments of
  3294. the addition is the same variable as the left-hand side of the
  3295. assignment, as shown below, then there is no need for the extra move
  3296. instruction. The assignment statement can be translated into a single
  3297. \key{addq} instruction as follows.
  3298. \begin{transformation}
  3299. {\if\edition\racketEd
  3300. \begin{lstlisting}
  3301. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3302. \end{lstlisting}
  3303. \fi}
  3304. {\if\edition\pythonEd
  3305. \begin{lstlisting}
  3306. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3307. \end{lstlisting}
  3308. \fi}
  3309. \compilesto
  3310. \begin{lstlisting}
  3311. addq |$\Arg_1$|, |$\itm{var}$|
  3312. \end{lstlisting}
  3313. \end{transformation}
  3314. The \READOP{} operation does not have a direct counterpart in x86
  3315. assembly, so we provide this functionality with the function
  3316. \code{read\_int} in the file \code{runtime.c}, written in
  3317. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3318. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3319. system}, or simply the \emph{runtime} for short. When compiling your
  3320. generated x86 assembly code, you need to compile \code{runtime.c} to
  3321. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3322. \code{-c}) and link it into the executable. For our purposes of code
  3323. generation, all you need to do is translate an assignment of
  3324. \READOP{} into a call to the \code{read\_int} function followed by a
  3325. move from \code{rax} to the left-hand-side variable. (Recall that the
  3326. return value of a function goes into \code{rax}.)
  3327. \begin{transformation}
  3328. {\if\edition\racketEd
  3329. \begin{lstlisting}
  3330. |$\itm{var}$| = (read);
  3331. \end{lstlisting}
  3332. \fi}
  3333. {\if\edition\pythonEd
  3334. \begin{lstlisting}
  3335. |$\itm{var}$| = input_int();
  3336. \end{lstlisting}
  3337. \fi}
  3338. \compilesto
  3339. \begin{lstlisting}
  3340. callq read_int
  3341. movq %rax, |$\itm{var}$|
  3342. \end{lstlisting}
  3343. \end{transformation}
  3344. {\if\edition\pythonEd
  3345. %
  3346. Similarly, we translate the \code{print} operation, shown below, into
  3347. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3348. In x86, the first six arguments to functions are passed in registers,
  3349. with the first argument passed in register \code{rdi}. So we move the
  3350. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3351. \code{callq} instruction.
  3352. \begin{transformation}
  3353. \begin{lstlisting}
  3354. print(|$\Atm$|)
  3355. \end{lstlisting}
  3356. \compilesto
  3357. \begin{lstlisting}
  3358. movq |$\Arg$|, %rdi
  3359. callq print_int
  3360. \end{lstlisting}
  3361. \end{transformation}
  3362. %
  3363. \fi}
  3364. {\if\edition\racketEd
  3365. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3366. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3367. assignment to the \key{rax} register followed by a jump to the
  3368. conclusion of the program (so the conclusion needs to be labeled).
  3369. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3370. recursively and then append the resulting instructions.
  3371. \fi}
  3372. {\if\edition\pythonEd
  3373. We recommend that you use the function \code{utils.label\_name()} to
  3374. transform a string into an label argument suitably suitable for, e.g.,
  3375. the target of the \code{callq} instruction. This practice makes your
  3376. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3377. all labels.
  3378. \fi}
  3379. \begin{exercise}
  3380. \normalfont\normalsize
  3381. {\if\edition\racketEd
  3382. Implement the \code{select\_instructions} pass in
  3383. \code{compiler.rkt}. Create three new example programs that are
  3384. designed to exercise all of the interesting cases in this pass.
  3385. %
  3386. In the \code{run-tests.rkt} script, add the following entry to the
  3387. list of \code{passes} and then run the script to test your compiler.
  3388. \begin{lstlisting}
  3389. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3390. \end{lstlisting}
  3391. \fi}
  3392. {\if\edition\pythonEd
  3393. Implement the \key{select\_instructions} pass in
  3394. \code{compiler.py}. Create three new example programs that are
  3395. designed to exercise all of the interesting cases in this pass.
  3396. Run the \code{run-tests.py} script to to check
  3397. whether the output programs produce the same result as the input
  3398. programs.
  3399. \fi}
  3400. \end{exercise}
  3401. \section{Assign Homes}
  3402. \label{sec:assign-Lvar}
  3403. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3404. \LangXVar{} programs that no longer use program variables.
  3405. Thus, the \code{assign\_homes} pass is responsible for placing all of
  3406. the program variables in registers or on the stack. For runtime
  3407. efficiency, it is better to place variables in registers, but as there
  3408. are only 16 registers, some programs must necessarily resort to
  3409. placing some variables on the stack. In this chapter we focus on the
  3410. mechanics of placing variables on the stack. We study an algorithm for
  3411. placing variables in registers in
  3412. Chapter~\ref{ch:register-allocation-Lvar}.
  3413. Consider again the following \LangVar{} program from
  3414. Section~\ref{sec:remove-complex-opera-Lvar}.
  3415. % var_test_20.rkt
  3416. {\if\edition\racketEd
  3417. \begin{lstlisting}
  3418. (let ([a 42])
  3419. (let ([b a])
  3420. b))
  3421. \end{lstlisting}
  3422. \fi}
  3423. {\if\edition\pythonEd
  3424. \begin{lstlisting}
  3425. a = 42
  3426. b = a
  3427. print(b)
  3428. \end{lstlisting}
  3429. \fi}
  3430. %
  3431. The output of \code{select\_instructions} is shown below, on the left,
  3432. and the output of \code{assign\_homes} is on the right. In this
  3433. example, we assign variable \code{a} to stack location
  3434. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3435. \begin{transformation}
  3436. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3437. movq $42, a
  3438. movq a, b
  3439. movq b, %rax
  3440. \end{lstlisting}
  3441. \compilesto
  3442. %stack-space: 16
  3443. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3444. movq $42, -8(%rbp)
  3445. movq -8(%rbp), -16(%rbp)
  3446. movq -16(%rbp), %rax
  3447. \end{lstlisting}
  3448. \end{transformation}
  3449. \racket{
  3450. The \code{assign\_homes} pass should replace all variables
  3451. with stack locations.
  3452. The list of variables can be obtain from
  3453. the \code{locals-types} entry in the $\itm{info}$ of the
  3454. \code{X86Program} node. The \code{locals-types} entry is an alist
  3455. mapping all the variables in the program to their types
  3456. (for now just \code{Integer}).
  3457. As an aside, the \code{locals-types} entry is
  3458. computed by \code{type-check-Cvar} in the support code, which
  3459. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3460. which you should propagate to the \code{X86Program} node.}
  3461. %
  3462. \python{The \code{assign\_homes} pass should replace all uses of
  3463. variables with stack locations.}
  3464. %
  3465. In the process of assigning variables to stack locations, it is
  3466. convenient for you to compute and store the size of the frame (in
  3467. bytes) in
  3468. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3469. %
  3470. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3471. %
  3472. which is needed later to generate the conclusion of the \code{main}
  3473. procedure. The x86-64 standard requires the frame size to be a
  3474. multiple of 16 bytes.\index{subject}{frame}
  3475. % TODO: store the number of variables instead? -Jeremy
  3476. \begin{exercise}\normalfont\normalsize
  3477. Implement the \code{assign\_homes} pass in
  3478. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3479. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3480. grammar. We recommend that the auxiliary functions take an extra
  3481. parameter that maps variable names to homes (stack locations for now).
  3482. %
  3483. {\if\edition\racketEd
  3484. In the \code{run-tests.rkt} script, add the following entry to the
  3485. list of \code{passes} and then run the script to test your compiler.
  3486. \begin{lstlisting}
  3487. (list "assign homes" assign-homes interp_x86-0)
  3488. \end{lstlisting}
  3489. \fi}
  3490. {\if\edition\pythonEd
  3491. Run the \code{run-tests.py} script to to check
  3492. whether the output programs produce the same result as the input
  3493. programs.
  3494. \fi}
  3495. \end{exercise}
  3496. \section{Patch Instructions}
  3497. \label{sec:patch-s0}
  3498. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3499. \LangXInt{} by making sure that each instruction adheres to the
  3500. restriction that at most one argument of an instruction may be a
  3501. memory reference.
  3502. We return to the following example.\\
  3503. \begin{minipage}{0.5\textwidth}
  3504. % var_test_20.rkt
  3505. {\if\edition\racketEd
  3506. \begin{lstlisting}
  3507. (let ([a 42])
  3508. (let ([b a])
  3509. b))
  3510. \end{lstlisting}
  3511. \fi}
  3512. {\if\edition\pythonEd
  3513. \begin{lstlisting}
  3514. a = 42
  3515. b = a
  3516. print(b)
  3517. \end{lstlisting}
  3518. \fi}
  3519. \end{minipage}\\
  3520. The \code{assign\_homes} pass produces the following translation. \\
  3521. \begin{minipage}{0.5\textwidth}
  3522. {\if\edition\racketEd
  3523. \begin{lstlisting}
  3524. movq $42, -8(%rbp)
  3525. movq -8(%rbp), -16(%rbp)
  3526. movq -16(%rbp), %rax
  3527. \end{lstlisting}
  3528. \fi}
  3529. {\if\edition\pythonEd
  3530. \begin{lstlisting}
  3531. movq 42, -8(%rbp)
  3532. movq -8(%rbp), -16(%rbp)
  3533. movq -16(%rbp), %rdi
  3534. callq print_int
  3535. \end{lstlisting}
  3536. \fi}
  3537. \end{minipage}\\
  3538. The second \key{movq} instruction is problematic because both
  3539. arguments are stack locations. We suggest fixing this problem by
  3540. moving from the source location to the register \key{rax} and then
  3541. from \key{rax} to the destination location, as follows.
  3542. \begin{lstlisting}
  3543. movq -8(%rbp), %rax
  3544. movq %rax, -16(%rbp)
  3545. \end{lstlisting}
  3546. \begin{exercise}
  3547. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3548. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3549. Create three new example programs that are
  3550. designed to exercise all of the interesting cases in this pass.
  3551. %
  3552. {\if\edition\racketEd
  3553. In the \code{run-tests.rkt} script, add the following entry to the
  3554. list of \code{passes} and then run the script to test your compiler.
  3555. \begin{lstlisting}
  3556. (list "patch instructions" patch_instructions interp_x86-0)
  3557. \end{lstlisting}
  3558. \fi}
  3559. {\if\edition\pythonEd
  3560. Run the \code{run-tests.py} script to to check
  3561. whether the output programs produce the same result as the input
  3562. programs.
  3563. \fi}
  3564. \end{exercise}
  3565. \section{Generate Prelude and Conclusion}
  3566. \label{sec:print-x86}
  3567. \index{subject}{prelude}\index{subject}{conclusion}
  3568. The last step of the compiler from \LangVar{} to x86 is to generate
  3569. the \code{main} function with a prelude and conclusion wrapped around
  3570. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3571. discussed in Section~\ref{sec:x86}.
  3572. When running on Mac OS X, your compiler should prefix an underscore to
  3573. all labels, e.g., changing \key{main} to \key{\_main}.
  3574. %
  3575. \racket{The Racket call \code{(system-type 'os)} is useful for
  3576. determining which operating system the compiler is running on. It
  3577. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3578. %
  3579. \python{The Python \code{platform} library includes a \code{system()}
  3580. function that returns \code{'Linux'}, \code{'Windows'}, or
  3581. \code{'Darwin'} (for Mac).}
  3582. \begin{exercise}\normalfont\normalsize
  3583. %
  3584. Implement the \key{prelude\_and\_conclusion} pass in
  3585. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3586. %
  3587. {\if\edition\racketEd
  3588. In the \code{run-tests.rkt} script, add the following entry to the
  3589. list of \code{passes} and then run the script to test your compiler.
  3590. \begin{lstlisting}
  3591. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3592. \end{lstlisting}
  3593. %
  3594. Uncomment the call to the \key{compiler-tests} function
  3595. (Appendix~\ref{appendix:utilities}), which tests your complete
  3596. compiler by executing the generated x86 code. It translates the x86
  3597. AST that you produce into a string by invoking the \code{print-x86}
  3598. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3599. the provided \key{runtime.c} file to \key{runtime.o} using
  3600. \key{gcc}. Run the script to test your compiler.
  3601. %
  3602. \fi}
  3603. {\if\edition\pythonEd
  3604. %
  3605. Run the \code{run-tests.py} script to to check whether the output
  3606. programs produce the same result as the input programs. That script
  3607. translates the x86 AST that you produce into a string by invoking the
  3608. \code{repr} method that is implemented by the x86 AST classes in
  3609. \code{x86\_ast.py}.
  3610. %
  3611. \fi}
  3612. \end{exercise}
  3613. \section{Challenge: Partial Evaluator for \LangVar{}}
  3614. \label{sec:pe-Lvar}
  3615. \index{subject}{partial evaluation}
  3616. This section describes two optional challenge exercises that involve
  3617. adapting and improving the partial evaluator for \LangInt{} that was
  3618. introduced in Section~\ref{sec:partial-evaluation}.
  3619. \begin{exercise}\label{ex:pe-Lvar}
  3620. \normalfont\normalsize
  3621. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3622. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3623. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3624. %
  3625. \racket{\key{let} binding}\python{assignment}
  3626. %
  3627. to the \LangInt{} language, so you will need to add cases for them in
  3628. the \code{pe\_exp}
  3629. %
  3630. \racket{function.}
  3631. %
  3632. \python{and \code{pe\_stmt} functions.}
  3633. %
  3634. Once complete, add the partial evaluation pass to the front of your
  3635. compiler and make sure that your compiler still passes all of the
  3636. tests.
  3637. \end{exercise}
  3638. \begin{exercise}
  3639. \normalfont\normalsize
  3640. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3641. \code{pe\_add} auxiliary functions with functions that know more about
  3642. arithmetic. For example, your partial evaluator should translate
  3643. {\if\edition\racketEd
  3644. \[
  3645. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3646. \code{(+ 2 (read))}
  3647. \]
  3648. \fi}
  3649. {\if\edition\pythonEd
  3650. \[
  3651. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3652. \code{2 + input\_int()}
  3653. \]
  3654. \fi}
  3655. To accomplish this, the \code{pe\_exp} function should produce output
  3656. in the form of the $\itm{residual}$ non-terminal of the following
  3657. grammar. The idea is that when processing an addition expression, we
  3658. can always produce either 1) an integer constant, 2) an addition
  3659. expression with an integer constant on the left-hand side but not the
  3660. right-hand side, or 3) or an addition expression in which neither
  3661. subexpression is a constant.
  3662. {\if\edition\racketEd
  3663. \[
  3664. \begin{array}{lcl}
  3665. \itm{inert} &::=& \Var
  3666. \MID \LP\key{read}\RP
  3667. \MID \LP\key{-} ~\Var\RP
  3668. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3669. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3670. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3671. \itm{residual} &::=& \Int
  3672. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3673. \MID \itm{inert}
  3674. \end{array}
  3675. \]
  3676. \fi}
  3677. {\if\edition\pythonEd
  3678. \[
  3679. \begin{array}{lcl}
  3680. \itm{inert} &::=& \Var
  3681. \MID \key{input\_int}\LP\RP
  3682. \MID \key{-} \Var
  3683. \MID \key{-} \key{input\_int}\LP\RP
  3684. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3685. \itm{residual} &::=& \Int
  3686. \MID \Int ~ \key{+} ~ \itm{inert}
  3687. \MID \itm{inert}
  3688. \end{array}
  3689. \]
  3690. \fi}
  3691. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3692. inputs are $\itm{residual}$ expressions and they should return
  3693. $\itm{residual}$ expressions. Once the improvements are complete,
  3694. make sure that your compiler still passes all of the tests. After
  3695. all, fast code is useless if it produces incorrect results!
  3696. \end{exercise}
  3697. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3698. \chapter{Register Allocation}
  3699. \label{ch:register-allocation-Lvar}
  3700. \index{subject}{register allocation}
  3701. In Chapter~\ref{ch:Lvar} we compiled \LangVar{} to x86, storing
  3702. variables on the procedure call stack. It can take 10s to 100s of
  3703. cycles for the CPU to access locations on the stack whereas accessing
  3704. a register takes only a single cycle. In this chapter we improve the
  3705. efficiency of our generated code by storing some variables in
  3706. registers. The goal of register allocation is to fit as many variables
  3707. into registers as possible. Some programs have more variables than
  3708. registers so we cannot always map each variable to a different
  3709. register. Fortunately, it is common for different variables to be
  3710. in-use during different periods of time during program execution, and
  3711. in those cases we can map multiple variables to the same register.
  3712. The program in Figure~\ref{fig:reg-eg} serves as a running
  3713. example. The source program is on the left and the output of
  3714. instruction selection is on the right. The program is almost in the
  3715. x86 assembly language but it still uses variables. Consider variables
  3716. \code{x} and \code{z}. After the variable \code{x} is moved to
  3717. \code{z} it is no longer in-use. Variable \code{z}, on the other
  3718. hand, is used only after this point, so \code{x} and \code{z} could
  3719. share the same register.
  3720. \begin{figure}
  3721. \begin{tcolorbox}[colback=white]
  3722. \begin{minipage}{0.45\textwidth}
  3723. Example \LangVar{} program:
  3724. % var_test_28.rkt
  3725. {\if\edition\racketEd
  3726. \begin{lstlisting}
  3727. (let ([v 1])
  3728. (let ([w 42])
  3729. (let ([x (+ v 7)])
  3730. (let ([y x])
  3731. (let ([z (+ x w)])
  3732. (+ z (- y)))))))
  3733. \end{lstlisting}
  3734. \fi}
  3735. {\if\edition\pythonEd
  3736. \begin{lstlisting}
  3737. v = 1
  3738. w = 42
  3739. x = v + 7
  3740. y = x
  3741. z = x + w
  3742. print(z + (- y))
  3743. \end{lstlisting}
  3744. \fi}
  3745. \end{minipage}
  3746. \begin{minipage}{0.45\textwidth}
  3747. After instruction selection:
  3748. {\if\edition\racketEd
  3749. \begin{lstlisting}
  3750. locals-types:
  3751. x : Integer, y : Integer,
  3752. z : Integer, t : Integer,
  3753. v : Integer, w : Integer
  3754. start:
  3755. movq $1, v
  3756. movq $42, w
  3757. movq v, x
  3758. addq $7, x
  3759. movq x, y
  3760. movq x, z
  3761. addq w, z
  3762. movq y, t
  3763. negq t
  3764. movq z, %rax
  3765. addq t, %rax
  3766. jmp conclusion
  3767. \end{lstlisting}
  3768. \fi}
  3769. {\if\edition\pythonEd
  3770. \begin{lstlisting}
  3771. movq $1, v
  3772. movq $42, w
  3773. movq v, x
  3774. addq $7, x
  3775. movq x, y
  3776. movq x, z
  3777. addq w, z
  3778. movq y, tmp_0
  3779. negq tmp_0
  3780. movq z, tmp_1
  3781. addq tmp_0, tmp_1
  3782. movq tmp_1, %rdi
  3783. callq print_int
  3784. \end{lstlisting}
  3785. \fi}
  3786. \end{minipage}
  3787. \end{tcolorbox}
  3788. \caption{A running example for register allocation.}
  3789. \label{fig:reg-eg}
  3790. \end{figure}
  3791. The topic of Section~\ref{sec:liveness-analysis-Lvar} is how to
  3792. compute where a variable is in-use. Once we have that information, we
  3793. compute which variables are in-use at the same time, i.e., which ones
  3794. \emph{interfere}\index{subject}{interfere} with each other, and
  3795. represent this relation as an undirected graph whose vertices are
  3796. variables and edges indicate when two variables interfere
  3797. (Section~\ref{sec:build-interference}). We then model register
  3798. allocation as a graph coloring problem
  3799. (Section~\ref{sec:graph-coloring}).
  3800. If we run out of registers despite these efforts, we place the
  3801. remaining variables on the stack, similar to what we did in
  3802. Chapter~\ref{ch:Lvar}. It is common to use the verb
  3803. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3804. location. The decision to spill a variable is handled as part of the
  3805. graph coloring process.
  3806. We make the simplifying assumption that each variable is assigned to
  3807. one location (a register or stack address). A more sophisticated
  3808. approach is to assign a variable to one or more locations in different
  3809. regions of the program. For example, if a variable is used many times
  3810. in short sequence and then only used again after many other
  3811. instructions, it could be more efficient to assign the variable to a
  3812. register during the initial sequence and then move it to the stack for
  3813. the rest of its lifetime. We refer the interested reader to
  3814. \citet{Cooper:2011aa} (Chapter 13) for more information about that
  3815. approach.
  3816. % discuss prioritizing variables based on how much they are used.
  3817. \section{Registers and Calling Conventions}
  3818. \label{sec:calling-conventions}
  3819. \index{subject}{calling conventions}
  3820. As we perform register allocation, we must be aware of the
  3821. \emph{calling conventions} \index{subject}{calling conventions} that
  3822. govern how functions calls are performed in x86.
  3823. %
  3824. Even though \LangVar{} does not include programmer-defined functions,
  3825. our generated code includes a \code{main} function that is called by
  3826. the operating system and our generated code contains calls to the
  3827. \code{read\_int} function.
  3828. Function calls require coordination between two pieces of code that
  3829. may be written by different programmers or generated by different
  3830. compilers. Here we follow the System V calling conventions that are
  3831. used by the GNU C compiler on Linux and
  3832. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3833. %
  3834. The calling conventions include rules about how functions share the
  3835. use of registers. In particular, the caller is responsible for freeing
  3836. up some registers prior to the function call for use by the callee.
  3837. These are called the \emph{caller-saved registers}
  3838. \index{subject}{caller-saved registers}
  3839. and they are
  3840. \begin{lstlisting}
  3841. rax rcx rdx rsi rdi r8 r9 r10 r11
  3842. \end{lstlisting}
  3843. On the other hand, the callee is responsible for preserving the values
  3844. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3845. which are
  3846. \begin{lstlisting}
  3847. rsp rbp rbx r12 r13 r14 r15
  3848. \end{lstlisting}
  3849. We can think about this caller/callee convention from two points of
  3850. view, the caller view and the callee view:
  3851. \begin{itemize}
  3852. \item The caller should assume that all the caller-saved registers get
  3853. overwritten with arbitrary values by the callee. On the other hand,
  3854. the caller can safely assume that all the callee-saved registers
  3855. retain their original values.
  3856. \item The callee can freely use any of the caller-saved registers.
  3857. However, if the callee wants to use a callee-saved register, the
  3858. callee must arrange to put the original value back in the register
  3859. prior to returning to the caller. This can be accomplished by saving
  3860. the value to the stack in the prelude of the function and restoring
  3861. the value in the conclusion of the function.
  3862. \end{itemize}
  3863. In x86, registers are also used for passing arguments to a function
  3864. and for the return value. In particular, the first six arguments of a
  3865. function are passed in the following six registers, in this order.
  3866. \index{subject}{argument-passing registers}
  3867. \index{subject}{parameter-passing registers}
  3868. \begin{lstlisting}
  3869. rdi rsi rdx rcx r8 r9
  3870. \end{lstlisting}
  3871. If there are more than six arguments, then the convention is to use
  3872. space on the frame of the caller for the rest of the
  3873. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3874. need more than six arguments.
  3875. %
  3876. \racket{For now, the only function we care about is \code{read\_int}
  3877. and it takes zero arguments.}
  3878. %
  3879. \python{For now, the only functions we care about are \code{read\_int}
  3880. and \code{print\_int}, which take zero and one argument, respectively.}
  3881. %
  3882. The register \code{rax} is used for the return value of a function.
  3883. The next question is how these calling conventions impact register
  3884. allocation. Consider the \LangVar{} program in
  3885. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3886. example from the caller point of view and then from the callee point
  3887. of view. We refer to a variable that is in-use during a function call
  3888. as being a \emph{call-live variable}\index{subject}{call-live
  3889. variable}.
  3890. The program makes two calls to \READOP{}. The variable \code{x} is
  3891. call-live because it is in-use during the second call to \READOP{}; we
  3892. must ensure that the value in \code{x} does not get overwritten during
  3893. the call to \READOP{}. One obvious approach is to save all the values
  3894. that reside in caller-saved registers to the stack prior to each
  3895. function call, and restore them after each call. That way, if the
  3896. register allocator chooses to assign \code{x} to a caller-saved
  3897. register, its value will be preserved across the call to \READOP{}.
  3898. However, saving and restoring to the stack is relatively slow. If
  3899. \code{x} is not used many times, it may be better to assign \code{x}
  3900. to a stack location in the first place. Or better yet, if we can
  3901. arrange for \code{x} to be placed in a callee-saved register, then it
  3902. won't need to be saved and restored during function calls.
  3903. The approach that we recommend for call-live variables is to either
  3904. assign them to callee-saved registers or to spill them to the
  3905. stack. On the other hand, for variables that are not call-live, we try
  3906. the following alternatives in order 1) look for an available
  3907. caller-saved register (to leave room for other variables in the
  3908. callee-saved register), 2) look for a callee-saved register, and 3)
  3909. spill the variable to the stack.
  3910. It is straightforward to implement this approach in a graph coloring
  3911. register allocator. First, we know which variables are call-live
  3912. because we already need to compute which variables are in-use at every
  3913. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3914. we build the interference graph
  3915. (Section~\ref{sec:build-interference}), we can place an edge between
  3916. each of the call-live variables and the caller-saved registers in the
  3917. interference graph. This will prevent the graph coloring algorithm
  3918. from assigning them to caller-saved registers.
  3919. Returning to the example in
  3920. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3921. generated x86 code on the right-hand side. Notice that variable
  3922. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3923. is already in a safe place during the second call to
  3924. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3925. \code{rcx}, a caller-saved register, because \code{y} is not a
  3926. call-live variable.
  3927. Next we analyze the example from the callee point of view, focusing on
  3928. the prelude and conclusion of the \code{main} function. As usual the
  3929. prelude begins with saving the \code{rbp} register to the stack and
  3930. setting the \code{rbp} to the current stack pointer. We now know why
  3931. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3932. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3933. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3934. (\code{x}). The other callee-saved registers are not saved in the
  3935. prelude because they are not used. The prelude subtracts 8 bytes from
  3936. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3937. conclusion, we see that \code{rbx} is restored from the stack with a
  3938. \code{popq} instruction.
  3939. \index{subject}{prelude}\index{subject}{conclusion}
  3940. \begin{figure}[tp]
  3941. \begin{tcolorbox}[colback=white]
  3942. \begin{minipage}{0.45\textwidth}
  3943. Example \LangVar{} program:
  3944. %var_test_14.rkt
  3945. {\if\edition\racketEd
  3946. \begin{lstlisting}
  3947. (let ([x (read)])
  3948. (let ([y (read)])
  3949. (+ (+ x y) 42)))
  3950. \end{lstlisting}
  3951. \fi}
  3952. {\if\edition\pythonEd
  3953. \begin{lstlisting}
  3954. x = input_int()
  3955. y = input_int()
  3956. print((x + y) + 42)
  3957. \end{lstlisting}
  3958. \fi}
  3959. \end{minipage}
  3960. \begin{minipage}{0.45\textwidth}
  3961. Generated x86 assembly:
  3962. {\if\edition\racketEd
  3963. \begin{lstlisting}
  3964. start:
  3965. callq read_int
  3966. movq %rax, %rbx
  3967. callq read_int
  3968. movq %rax, %rcx
  3969. addq %rcx, %rbx
  3970. movq %rbx, %rax
  3971. addq $42, %rax
  3972. jmp _conclusion
  3973. .globl main
  3974. main:
  3975. pushq %rbp
  3976. movq %rsp, %rbp
  3977. pushq %rbx
  3978. subq $8, %rsp
  3979. jmp start
  3980. conclusion:
  3981. addq $8, %rsp
  3982. popq %rbx
  3983. popq %rbp
  3984. retq
  3985. \end{lstlisting}
  3986. \fi}
  3987. {\if\edition\pythonEd
  3988. \begin{lstlisting}
  3989. .globl main
  3990. main:
  3991. pushq %rbp
  3992. movq %rsp, %rbp
  3993. pushq %rbx
  3994. subq $8, %rsp
  3995. callq read_int
  3996. movq %rax, %rbx
  3997. callq read_int
  3998. movq %rax, %rcx
  3999. movq %rbx, %rdx
  4000. addq %rcx, %rdx
  4001. movq %rdx, %rcx
  4002. addq $42, %rcx
  4003. movq %rcx, %rdi
  4004. callq print_int
  4005. addq $8, %rsp
  4006. popq %rbx
  4007. popq %rbp
  4008. retq
  4009. \end{lstlisting}
  4010. \fi}
  4011. \end{minipage}
  4012. \end{tcolorbox}
  4013. \caption{An example with function calls.}
  4014. \label{fig:example-calling-conventions}
  4015. \end{figure}
  4016. %\clearpage
  4017. \section{Liveness Analysis}
  4018. \label{sec:liveness-analysis-Lvar}
  4019. \index{subject}{liveness analysis}
  4020. The \code{uncover\_live} \racket{pass}\python{function} performs
  4021. \emph{liveness analysis}, that is, it discovers which variables are
  4022. in-use in different regions of a program.
  4023. %
  4024. A variable or register is \emph{live} at a program point if its
  4025. current value is used at some later point in the program. We refer to
  4026. variables, stack locations, and registers collectively as
  4027. \emph{locations}.
  4028. %
  4029. Consider the following code fragment in which there are two writes to
  4030. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4031. time?
  4032. \begin{center}
  4033. \begin{minipage}{0.96\textwidth}
  4034. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4035. movq $5, a
  4036. movq $30, b
  4037. movq a, c
  4038. movq $10, b
  4039. addq b, c
  4040. \end{lstlisting}
  4041. \end{minipage}
  4042. \end{center}
  4043. The answer is no because \code{a} is live from line 1 to 3 and
  4044. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4045. line 2 is never used because it is overwritten (line 4) before the
  4046. next read (line 5).
  4047. The live locations for each instruction can be computed by traversing
  4048. the instruction sequence back to front (i.e., backwards in execution
  4049. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4050. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4051. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  4052. locations before instruction $I_k$. \racket{We recommend representing
  4053. these sets with the Racket \code{set} data structure described in
  4054. Figure~\ref{fig:set}.} \python{We recommend representing these sets
  4055. with the Python
  4056. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4057. data structure.}
  4058. {\if\edition\racketEd
  4059. \begin{figure}[tp]
  4060. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4061. \small
  4062. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4063. A \emph{set} is an unordered collection of elements without duplicates.
  4064. Here are some of the operations defined on sets.
  4065. \index{subject}{set}
  4066. \begin{description}
  4067. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4068. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4069. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4070. difference of the two sets.
  4071. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4072. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4073. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4074. \end{description}
  4075. \end{tcolorbox}
  4076. %\end{wrapfigure}
  4077. \caption{The \code{set} data structure.}
  4078. \label{fig:set}
  4079. \end{figure}
  4080. \fi}
  4081. The live locations after an instruction are always the same as the
  4082. live locations before the next instruction.
  4083. \index{subject}{live-after} \index{subject}{live-before}
  4084. \begin{equation} \label{eq:live-after-before-next}
  4085. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4086. \end{equation}
  4087. To start things off, there are no live locations after the last
  4088. instruction, so
  4089. \begin{equation}\label{eq:live-last-empty}
  4090. L_{\mathsf{after}}(n) = \emptyset
  4091. \end{equation}
  4092. We then apply the following rule repeatedly, traversing the
  4093. instruction sequence back to front.
  4094. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4095. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4096. \end{equation}
  4097. where $W(k)$ are the locations written to by instruction $I_k$ and
  4098. $R(k)$ are the locations read by instruction $I_k$.
  4099. {\if\edition\racketEd
  4100. %
  4101. There is a special case for \code{jmp} instructions. The locations
  4102. that are live before a \code{jmp} should be the locations in
  4103. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  4104. maintaining an alist named \code{label->live} that maps each label to
  4105. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  4106. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4107. conclusion. (For example, see Figure~\ref{fig:reg-eg}.) The
  4108. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4109. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4110. %
  4111. \fi}
  4112. Let us walk through the above example, applying these formulas
  4113. starting with the instruction on line 5. We collect the answers in
  4114. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  4115. \code{addq b, c} instruction is $\emptyset$ because it is the last
  4116. instruction (formula~\ref{eq:live-last-empty}). The
  4117. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4118. because it reads from variables \code{b} and \code{c}
  4119. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4120. \[
  4121. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4122. \]
  4123. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4124. the live-before set from line 5 to be the live-after set for this
  4125. instruction (formula~\ref{eq:live-after-before-next}).
  4126. \[
  4127. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4128. \]
  4129. This move instruction writes to \code{b} and does not read from any
  4130. variables, so we have the following live-before set
  4131. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4132. \[
  4133. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4134. \]
  4135. The live-before for instruction \code{movq a, c}
  4136. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4137. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4138. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4139. variable that is not live and does not read from a variable.
  4140. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4141. because it writes to variable \code{a}.
  4142. \begin{figure}[tbp]
  4143. \centering
  4144. \begin{tcolorbox}[colback=white]
  4145. \hspace{10pt}
  4146. \begin{minipage}{0.4\textwidth}
  4147. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4148. movq $5, a
  4149. movq $30, b
  4150. movq a, c
  4151. movq $10, b
  4152. addq b, c
  4153. \end{lstlisting}
  4154. \end{minipage}
  4155. \vrule\hspace{10pt}
  4156. \begin{minipage}{0.45\textwidth}
  4157. \begin{align*}
  4158. L_{\mathsf{before}}(1)= \emptyset,
  4159. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4160. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4161. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4162. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4163. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4164. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4165. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4166. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4167. L_{\mathsf{after}}(5)= \emptyset
  4168. \end{align*}
  4169. \end{minipage}
  4170. \end{tcolorbox}
  4171. \caption{Example output of liveness analysis on a short example.}
  4172. \label{fig:liveness-example-0}
  4173. \end{figure}
  4174. \begin{exercise}\normalfont\normalsize
  4175. Perform liveness analysis by hand on the running example in
  4176. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4177. sets for each instruction. Compare your answers to the solution
  4178. shown in Figure~\ref{fig:live-eg}.
  4179. \end{exercise}
  4180. \begin{figure}[tp]
  4181. \hspace{20pt}
  4182. \begin{minipage}{0.55\textwidth}
  4183. \begin{tcolorbox}[colback=white]
  4184. {\if\edition\racketEd
  4185. \begin{lstlisting}
  4186. |$\{\ttm{rsp}\}$|
  4187. movq $1, v
  4188. |$\{\ttm{v},\ttm{rsp}\}$|
  4189. movq $42, w
  4190. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4191. movq v, x
  4192. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4193. addq $7, x
  4194. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4195. movq x, y
  4196. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4197. movq x, z
  4198. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4199. addq w, z
  4200. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4201. movq y, t
  4202. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4203. negq t
  4204. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4205. movq z, %rax
  4206. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4207. addq t, %rax
  4208. |$\{\ttm{rax},\ttm{rsp}\}$|
  4209. jmp conclusion
  4210. \end{lstlisting}
  4211. \fi}
  4212. {\if\edition\pythonEd
  4213. \begin{lstlisting}
  4214. movq $1, v
  4215. |$\{\ttm{v}\}$|
  4216. movq $42, w
  4217. |$\{\ttm{w}, \ttm{v}\}$|
  4218. movq v, x
  4219. |$\{\ttm{w}, \ttm{x}\}$|
  4220. addq $7, x
  4221. |$\{\ttm{w}, \ttm{x}\}$|
  4222. movq x, y
  4223. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4224. movq x, z
  4225. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4226. addq w, z
  4227. |$\{\ttm{y}, \ttm{z}\}$|
  4228. movq y, tmp_0
  4229. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4230. negq tmp_0
  4231. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4232. movq z, tmp_1
  4233. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4234. addq tmp_0, tmp_1
  4235. |$\{\ttm{tmp\_1}\}$|
  4236. movq tmp_1, %rdi
  4237. |$\{\ttm{rdi}\}$|
  4238. callq print_int
  4239. |$\{\}$|
  4240. \end{lstlisting}
  4241. \fi}
  4242. \end{tcolorbox}
  4243. \end{minipage}
  4244. \caption{The running example annotated with live-after sets.}
  4245. \label{fig:live-eg}
  4246. \end{figure}
  4247. \begin{exercise}\normalfont\normalsize
  4248. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4249. %
  4250. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4251. field of the \code{Block} structure.}
  4252. %
  4253. \python{Return a dictionary that maps each instruction to its
  4254. live-after set.}
  4255. %
  4256. \racket{We recommend creating an auxiliary function that takes a list
  4257. of instructions and an initial live-after set (typically empty) and
  4258. returns the list of live-after sets.}
  4259. %
  4260. We recommend creating auxiliary functions to 1) compute the set
  4261. of locations that appear in an \Arg{}, 2) compute the locations read
  4262. by an instruction (the $R$ function), and 3) the locations written by
  4263. an instruction (the $W$ function). The \code{callq} instruction should
  4264. include all of the caller-saved registers in its write-set $W$ because
  4265. the calling convention says that those registers may be written to
  4266. during the function call. Likewise, the \code{callq} instruction
  4267. should include the appropriate argument-passing registers in its
  4268. read-set $R$, depending on the arity of the function being
  4269. called. (This is why the abstract syntax for \code{callq} includes the
  4270. arity.)
  4271. \end{exercise}
  4272. %\clearpage
  4273. \section{Build the Interference Graph}
  4274. \label{sec:build-interference}
  4275. {\if\edition\racketEd
  4276. \begin{figure}[tp]
  4277. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4278. \small
  4279. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4280. A \emph{graph} is a collection of vertices and edges where each
  4281. edge connects two vertices. A graph is \emph{directed} if each
  4282. edge points from a source to a target. Otherwise the graph is
  4283. \emph{undirected}.
  4284. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4285. \begin{description}
  4286. %% We currently don't use directed graphs. We instead use
  4287. %% directed multi-graphs. -Jeremy
  4288. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4289. directed graph from a list of edges. Each edge is a list
  4290. containing the source and target vertex.
  4291. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4292. undirected graph from a list of edges. Each edge is represented by
  4293. a list containing two vertices.
  4294. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4295. inserts a vertex into the graph.
  4296. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4297. inserts an edge between the two vertices.
  4298. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4299. returns a sequence of vertices adjacent to the vertex.
  4300. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4301. returns a sequence of all vertices in the graph.
  4302. \end{description}
  4303. \end{tcolorbox}
  4304. %\end{wrapfigure}
  4305. \caption{The Racket \code{graph} package.}
  4306. \label{fig:graph}
  4307. \end{figure}
  4308. \fi}
  4309. Based on the liveness analysis, we know where each location is live.
  4310. However, during register allocation, we need to answer questions of
  4311. the specific form: are locations $u$ and $v$ live at the same time?
  4312. (And therefore cannot be assigned to the same register.) To make this
  4313. question more efficient to answer, we create an explicit data
  4314. structure, an \emph{interference graph}\index{subject}{interference
  4315. graph}. An interference graph is an undirected graph that has an
  4316. edge between two locations if they are live at the same time, that is,
  4317. if they interfere with each other.
  4318. %
  4319. \racket{We recommend using the Racket \code{graph} package
  4320. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4321. %
  4322. \python{We provide implementations of directed and undirected graph
  4323. data structures in the file \code{graph.py} of the support code.}
  4324. A straightforward way to compute the interference graph is to look at
  4325. the set of live locations between each instruction and add an edge to
  4326. the graph for every pair of variables in the same set. This approach
  4327. is less than ideal for two reasons. First, it can be expensive because
  4328. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4329. locations. Second, in the special case where two locations hold the
  4330. same value (because one was assigned to the other), they can be live
  4331. at the same time without interfering with each other.
  4332. A better way to compute the interference graph is to focus on
  4333. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4334. must not overwrite something in a live location. So for each
  4335. instruction, we create an edge between the locations being written to
  4336. and the live locations. (Except that a location never interferes with
  4337. itself.) For the \key{callq} instruction, we consider all of the
  4338. caller-saved registers as being written to, so an edge is added
  4339. between every live variable and every caller-saved register. Also, for
  4340. \key{movq} there is the special case of two variables holding the same
  4341. value. If a live variable $v$ is the same as the source of the
  4342. \key{movq}, then there is no need to add an edge between $v$ and the
  4343. destination, because they both hold the same value.
  4344. %
  4345. So we have the following two rules.
  4346. \begin{enumerate}
  4347. \item If instruction $I_k$ is a move instruction of the form
  4348. \key{movq} $s$\key{,} $d$, then for every $v \in
  4349. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4350. $(d,v)$.
  4351. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4352. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4353. $(d,v)$.
  4354. \end{enumerate}
  4355. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4356. the above rules to each instruction. We highlight a few of the
  4357. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4358. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4359. so \code{v} interferes with \code{rsp}.}
  4360. %
  4361. \python{The first instruction is \lstinline{movq $1, v} and the
  4362. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4363. no interference because $\ttm{v}$ is the destination of the move.}
  4364. %
  4365. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4366. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4367. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4368. %
  4369. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4370. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4371. $\ttm{x}$ interferes with \ttm{w}.}
  4372. %
  4373. \racket{The next instruction is \lstinline{movq x, y} and the
  4374. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4375. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4376. \ttm{x} because \ttm{x} is the source of the move and therefore
  4377. \ttm{x} and \ttm{y} hold the same value.}
  4378. %
  4379. \python{The next instruction is \lstinline{movq x, y} and the
  4380. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4381. applies, so \ttm{y} interferes with \ttm{w} but not
  4382. \ttm{x} because \ttm{x} is the source of the move and therefore
  4383. \ttm{x} and \ttm{y} hold the same value.}
  4384. %
  4385. Figure~\ref{fig:interference-results} lists the interference results
  4386. for all of the instructions and the resulting interference graph is
  4387. shown in Figure~\ref{fig:interfere}.
  4388. \begin{figure}[tbp]
  4389. \begin{tcolorbox}[colback=white]
  4390. \begin{quote}
  4391. {\if\edition\racketEd
  4392. \begin{tabular}{ll}
  4393. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4394. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4395. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4396. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4397. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4398. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4399. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4400. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4401. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4402. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4403. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4404. \lstinline!jmp conclusion!& no interference.
  4405. \end{tabular}
  4406. \fi}
  4407. {\if\edition\pythonEd
  4408. \begin{tabular}{ll}
  4409. \lstinline!movq $1, v!& no interference\\
  4410. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4411. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4412. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4413. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4414. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4415. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4416. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4417. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4418. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4419. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4420. \lstinline!movq tmp_1, %rdi! & no interference \\
  4421. \lstinline!callq print_int!& no interference.
  4422. \end{tabular}
  4423. \fi}
  4424. \end{quote}
  4425. \end{tcolorbox}
  4426. \caption{Interference results for the running example.}
  4427. \label{fig:interference-results}
  4428. \end{figure}
  4429. \begin{figure}[tbp]
  4430. \begin{tcolorbox}[colback=white]
  4431. \large
  4432. {\if\edition\racketEd
  4433. \[
  4434. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4435. \node (rax) at (0,0) {$\ttm{rax}$};
  4436. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4437. \node (t1) at (0,2) {$\ttm{t}$};
  4438. \node (z) at (3,2) {$\ttm{z}$};
  4439. \node (x) at (6,2) {$\ttm{x}$};
  4440. \node (y) at (3,0) {$\ttm{y}$};
  4441. \node (w) at (6,0) {$\ttm{w}$};
  4442. \node (v) at (9,0) {$\ttm{v}$};
  4443. \draw (t1) to (rax);
  4444. \draw (t1) to (z);
  4445. \draw (z) to (y);
  4446. \draw (z) to (w);
  4447. \draw (x) to (w);
  4448. \draw (y) to (w);
  4449. \draw (v) to (w);
  4450. \draw (v) to (rsp);
  4451. \draw (w) to (rsp);
  4452. \draw (x) to (rsp);
  4453. \draw (y) to (rsp);
  4454. \path[-.,bend left=15] (z) edge node {} (rsp);
  4455. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4456. \draw (rax) to (rsp);
  4457. \end{tikzpicture}
  4458. \]
  4459. \fi}
  4460. {\if\edition\pythonEd
  4461. \[
  4462. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4463. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4464. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4465. \node (z) at (3,2) {$\ttm{z}$};
  4466. \node (x) at (6,2) {$\ttm{x}$};
  4467. \node (y) at (3,0) {$\ttm{y}$};
  4468. \node (w) at (6,0) {$\ttm{w}$};
  4469. \node (v) at (9,0) {$\ttm{v}$};
  4470. \draw (t0) to (t1);
  4471. \draw (t0) to (z);
  4472. \draw (z) to (y);
  4473. \draw (z) to (w);
  4474. \draw (x) to (w);
  4475. \draw (y) to (w);
  4476. \draw (v) to (w);
  4477. \end{tikzpicture}
  4478. \]
  4479. \fi}
  4480. \end{tcolorbox}
  4481. \caption{The interference graph of the example program.}
  4482. \label{fig:interfere}
  4483. \end{figure}
  4484. %% Our next concern is to choose a data structure for representing the
  4485. %% interference graph. There are many choices for how to represent a
  4486. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4487. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4488. %% data structure is to study the algorithm that uses the data structure,
  4489. %% determine what operations need to be performed, and then choose the
  4490. %% data structure that provide the most efficient implementations of
  4491. %% those operations. Often times the choice of data structure can have an
  4492. %% effect on the time complexity of the algorithm, as it does here. If
  4493. %% you skim the next section, you will see that the register allocation
  4494. %% algorithm needs to ask the graph for all of its vertices and, given a
  4495. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4496. %% correct choice of graph representation is that of an adjacency
  4497. %% list. There are helper functions in \code{utilities.rkt} for
  4498. %% representing graphs using the adjacency list representation:
  4499. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4500. %% (Appendix~\ref{appendix:utilities}).
  4501. %% %
  4502. %% \margincomment{\footnotesize To do: change to use the
  4503. %% Racket graph library. \\ --Jeremy}
  4504. %% %
  4505. %% In particular, those functions use a hash table to map each vertex to
  4506. %% the set of adjacent vertices, and the sets are represented using
  4507. %% Racket's \key{set}, which is also a hash table.
  4508. \begin{exercise}\normalfont\normalsize
  4509. \racket{Implement the compiler pass named \code{build\_interference} according
  4510. to the algorithm suggested above. We recommend using the Racket
  4511. \code{graph} package to create and inspect the interference graph.
  4512. The output graph of this pass should be stored in the $\itm{info}$ field of
  4513. the program, under the key \code{conflicts}.}
  4514. %
  4515. \python{Implement a function named \code{build\_interference}
  4516. according to the algorithm suggested above that
  4517. returns the interference graph.}
  4518. \end{exercise}
  4519. \section{Graph Coloring via Sudoku}
  4520. \label{sec:graph-coloring}
  4521. \index{subject}{graph coloring}
  4522. \index{subject}{Sudoku}
  4523. \index{subject}{color}
  4524. We come to the main event of this chapter, mapping variables to
  4525. registers and stack locations. Variables that interfere with each
  4526. other must be mapped to different locations. In terms of the
  4527. interference graph, this means that adjacent vertices must be mapped
  4528. to different locations. If we think of locations as colors, the
  4529. register allocation problem becomes the graph coloring
  4530. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4531. The reader may be more familiar with the graph coloring problem than he
  4532. or she realizes; the popular game of Sudoku is an instance of the
  4533. graph coloring problem. The following describes how to build a graph
  4534. out of an initial Sudoku board.
  4535. \begin{itemize}
  4536. \item There is one vertex in the graph for each Sudoku square.
  4537. \item There is an edge between two vertices if the corresponding squares
  4538. are in the same row, in the same column, or if the squares are in
  4539. the same $3\times 3$ region.
  4540. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4541. \item Based on the initial assignment of numbers to squares in the
  4542. Sudoku board, assign the corresponding colors to the corresponding
  4543. vertices in the graph.
  4544. \end{itemize}
  4545. If you can color the remaining vertices in the graph with the nine
  4546. colors, then you have also solved the corresponding game of Sudoku.
  4547. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4548. the corresponding graph with colored vertices. We map the Sudoku
  4549. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4550. sampling of the vertices (the colored ones) because showing edges for
  4551. all of the vertices would make the graph unreadable.
  4552. \begin{figure}[tbp]
  4553. \begin{tcolorbox}[colback=white]
  4554. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  4555. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4556. \end{tcolorbox}
  4557. \caption{A Sudoku game board and the corresponding colored graph.}
  4558. \label{fig:sudoku-graph}
  4559. \end{figure}
  4560. Some techniques for playing Sudoku correspond to heuristics used in
  4561. graph coloring algorithms. For example, one of the basic techniques
  4562. for Sudoku is called Pencil Marks. The idea is to use a process of
  4563. elimination to determine what numbers are no longer available for a
  4564. square and write down those numbers in the square (writing very
  4565. small). For example, if the number $1$ is assigned to a square, then
  4566. write the pencil mark $1$ in all the squares in the same row, column,
  4567. and region to indicate that $1$ is no longer an option for those other
  4568. squares.
  4569. %
  4570. The Pencil Marks technique corresponds to the notion of
  4571. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4572. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4573. are no longer available. In graph terminology, we have the following
  4574. definition:
  4575. \begin{equation*}
  4576. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4577. \text{ and } \mathrm{color}(v) = c \}
  4578. \end{equation*}
  4579. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4580. edge with $u$.
  4581. The Pencil Marks technique leads to a simple strategy for filling in
  4582. numbers: if there is a square with only one possible number left, then
  4583. choose that number! But what if there are no squares with only one
  4584. possibility left? One brute-force approach is to try them all: choose
  4585. the first one and if that ultimately leads to a solution, great. If
  4586. not, backtrack and choose the next possibility. One good thing about
  4587. Pencil Marks is that it reduces the degree of branching in the search
  4588. tree. Nevertheless, backtracking can be terribly time consuming. One
  4589. way to reduce the amount of backtracking is to use the
  4590. most-constrained-first heuristic (aka. minimum remaining
  4591. values)~\citep{Russell2003}. That is, when choosing a square, always
  4592. choose one with the fewest possibilities left (the vertex with the
  4593. highest saturation). The idea is that choosing highly constrained
  4594. squares earlier rather than later is better because later on there may
  4595. not be any possibilities left in the highly saturated squares.
  4596. However, register allocation is easier than Sudoku because the
  4597. register allocator can fall back to assigning variables to stack
  4598. locations when the registers run out. Thus, it makes sense to replace
  4599. backtracking with greedy search: make the best choice at the time and
  4600. keep going. We still wish to minimize the number of colors needed, so
  4601. we use the most-constrained-first heuristic in the greedy search.
  4602. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4603. algorithm for register allocation based on saturation and the
  4604. most-constrained-first heuristic. It is roughly equivalent to the
  4605. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4606. %,Gebremedhin:1999fk,Omari:2006uq
  4607. Just as in Sudoku, the algorithm represents colors with integers. The
  4608. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4609. for register allocation. The integers $k$ and larger correspond to
  4610. stack locations. The registers that are not used for register
  4611. allocation, such as \code{rax}, are assigned to negative integers. In
  4612. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4613. %% One might wonder why we include registers at all in the liveness
  4614. %% analysis and interference graph. For example, we never allocate a
  4615. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4616. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4617. %% to use register for passing arguments to functions, it will be
  4618. %% necessary for those registers to appear in the interference graph
  4619. %% because those registers will also be assigned to variables, and we
  4620. %% don't want those two uses to encroach on each other. Regarding
  4621. %% registers such as \code{rax} and \code{rsp} that are not used for
  4622. %% variables, we could omit them from the interference graph but that
  4623. %% would require adding special cases to our algorithm, which would
  4624. %% complicate the logic for little gain.
  4625. \begin{figure}[btp]
  4626. \begin{tcolorbox}[colback=white]
  4627. \centering
  4628. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4629. Algorithm: DSATUR
  4630. Input: a graph |$G$|
  4631. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4632. |$W \gets \mathrm{vertices}(G)$|
  4633. while |$W \neq \emptyset$| do
  4634. pick a vertex |$u$| from |$W$| with the highest saturation,
  4635. breaking ties randomly
  4636. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4637. |$\mathrm{color}[u] \gets c$|
  4638. |$W \gets W - \{u\}$|
  4639. \end{lstlisting}
  4640. \end{tcolorbox}
  4641. \caption{The saturation-based greedy graph coloring algorithm.}
  4642. \label{fig:satur-algo}
  4643. \end{figure}
  4644. {\if\edition\racketEd
  4645. With the DSATUR algorithm in hand, let us return to the running
  4646. example and consider how to color the interference graph in
  4647. Figure~\ref{fig:interfere}.
  4648. %
  4649. We start by assigning the register nodes to their own color. For
  4650. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4651. assigned $-2$. The variables are not yet colored, so they are
  4652. annotated with a dash. We then update the saturation for vertices that
  4653. are adjacent to a register, obtaining the following annotated
  4654. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4655. it interferes with both \code{rax} and \code{rsp}.
  4656. \[
  4657. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4658. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4659. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4660. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4661. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4662. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4663. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4664. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4665. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4666. \draw (t1) to (rax);
  4667. \draw (t1) to (z);
  4668. \draw (z) to (y);
  4669. \draw (z) to (w);
  4670. \draw (x) to (w);
  4671. \draw (y) to (w);
  4672. \draw (v) to (w);
  4673. \draw (v) to (rsp);
  4674. \draw (w) to (rsp);
  4675. \draw (x) to (rsp);
  4676. \draw (y) to (rsp);
  4677. \path[-.,bend left=15] (z) edge node {} (rsp);
  4678. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4679. \draw (rax) to (rsp);
  4680. \end{tikzpicture}
  4681. \]
  4682. The algorithm says to select a maximally saturated vertex. So we pick
  4683. $\ttm{t}$ and color it with the first available integer, which is
  4684. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4685. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4686. \[
  4687. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4688. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4689. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4690. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4691. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4692. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4693. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4694. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4695. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4696. \draw (t1) to (rax);
  4697. \draw (t1) to (z);
  4698. \draw (z) to (y);
  4699. \draw (z) to (w);
  4700. \draw (x) to (w);
  4701. \draw (y) to (w);
  4702. \draw (v) to (w);
  4703. \draw (v) to (rsp);
  4704. \draw (w) to (rsp);
  4705. \draw (x) to (rsp);
  4706. \draw (y) to (rsp);
  4707. \path[-.,bend left=15] (z) edge node {} (rsp);
  4708. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4709. \draw (rax) to (rsp);
  4710. \end{tikzpicture}
  4711. \]
  4712. We repeat the process, selecting a maximally saturated vertex,
  4713. choosing is \code{z}, and color it with the first available number, which
  4714. is $1$. We add $1$ to the saturation for the neighboring vertices
  4715. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4716. \[
  4717. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4718. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4719. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4720. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4721. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4722. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4723. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4724. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4725. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4726. \draw (t1) to (rax);
  4727. \draw (t1) to (z);
  4728. \draw (z) to (y);
  4729. \draw (z) to (w);
  4730. \draw (x) to (w);
  4731. \draw (y) to (w);
  4732. \draw (v) to (w);
  4733. \draw (v) to (rsp);
  4734. \draw (w) to (rsp);
  4735. \draw (x) to (rsp);
  4736. \draw (y) to (rsp);
  4737. \path[-.,bend left=15] (z) edge node {} (rsp);
  4738. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4739. \draw (rax) to (rsp);
  4740. \end{tikzpicture}
  4741. \]
  4742. The most saturated vertices are now \code{w} and \code{y}. We color
  4743. \code{w} with the first available color, which is $0$.
  4744. \[
  4745. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4746. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4747. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4748. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4749. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4750. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4751. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4752. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4753. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4754. \draw (t1) to (rax);
  4755. \draw (t1) to (z);
  4756. \draw (z) to (y);
  4757. \draw (z) to (w);
  4758. \draw (x) to (w);
  4759. \draw (y) to (w);
  4760. \draw (v) to (w);
  4761. \draw (v) to (rsp);
  4762. \draw (w) to (rsp);
  4763. \draw (x) to (rsp);
  4764. \draw (y) to (rsp);
  4765. \path[-.,bend left=15] (z) edge node {} (rsp);
  4766. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4767. \draw (rax) to (rsp);
  4768. \end{tikzpicture}
  4769. \]
  4770. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4771. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4772. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4773. and \code{z}, whose colors are $0$ and $1$ respectively.
  4774. \[
  4775. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4776. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4777. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4778. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4779. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4780. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4781. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4782. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4783. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4784. \draw (t1) to (rax);
  4785. \draw (t1) to (z);
  4786. \draw (z) to (y);
  4787. \draw (z) to (w);
  4788. \draw (x) to (w);
  4789. \draw (y) to (w);
  4790. \draw (v) to (w);
  4791. \draw (v) to (rsp);
  4792. \draw (w) to (rsp);
  4793. \draw (x) to (rsp);
  4794. \draw (y) to (rsp);
  4795. \path[-.,bend left=15] (z) edge node {} (rsp);
  4796. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4797. \draw (rax) to (rsp);
  4798. \end{tikzpicture}
  4799. \]
  4800. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4801. \[
  4802. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4803. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4804. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4805. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4806. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4807. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4808. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4809. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4810. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4811. \draw (t1) to (rax);
  4812. \draw (t1) to (z);
  4813. \draw (z) to (y);
  4814. \draw (z) to (w);
  4815. \draw (x) to (w);
  4816. \draw (y) to (w);
  4817. \draw (v) to (w);
  4818. \draw (v) to (rsp);
  4819. \draw (w) to (rsp);
  4820. \draw (x) to (rsp);
  4821. \draw (y) to (rsp);
  4822. \path[-.,bend left=15] (z) edge node {} (rsp);
  4823. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4824. \draw (rax) to (rsp);
  4825. \end{tikzpicture}
  4826. \]
  4827. In the last step of the algorithm, we color \code{x} with $1$.
  4828. \[
  4829. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4830. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4831. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4832. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4833. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4834. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4835. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4836. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4837. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4838. \draw (t1) to (rax);
  4839. \draw (t1) to (z);
  4840. \draw (z) to (y);
  4841. \draw (z) to (w);
  4842. \draw (x) to (w);
  4843. \draw (y) to (w);
  4844. \draw (v) to (w);
  4845. \draw (v) to (rsp);
  4846. \draw (w) to (rsp);
  4847. \draw (x) to (rsp);
  4848. \draw (y) to (rsp);
  4849. \path[-.,bend left=15] (z) edge node {} (rsp);
  4850. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4851. \draw (rax) to (rsp);
  4852. \end{tikzpicture}
  4853. \]
  4854. So we obtain the following coloring:
  4855. \[
  4856. \{
  4857. \ttm{rax} \mapsto -1,
  4858. \ttm{rsp} \mapsto -2,
  4859. \ttm{t} \mapsto 0,
  4860. \ttm{z} \mapsto 1,
  4861. \ttm{x} \mapsto 1,
  4862. \ttm{y} \mapsto 2,
  4863. \ttm{w} \mapsto 0,
  4864. \ttm{v} \mapsto 1
  4865. \}
  4866. \]
  4867. \fi}
  4868. %
  4869. {\if\edition\pythonEd
  4870. %
  4871. With the DSATUR algorithm in hand, let us return to the running
  4872. example and consider how to color the interference graph in
  4873. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4874. to indicate that it has not yet been assigned a color. The saturation
  4875. sets are also shown for each node; all of them start as the empty set.
  4876. (We do not include the register nodes in the graph below because there
  4877. were no interference edges involving registers in this program, but in
  4878. general there can be.)
  4879. %
  4880. \[
  4881. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4882. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4883. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4884. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4885. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4886. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4887. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4888. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4889. \draw (t0) to (t1);
  4890. \draw (t0) to (z);
  4891. \draw (z) to (y);
  4892. \draw (z) to (w);
  4893. \draw (x) to (w);
  4894. \draw (y) to (w);
  4895. \draw (v) to (w);
  4896. \end{tikzpicture}
  4897. \]
  4898. The algorithm says to select a maximally saturated vertex, but they
  4899. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4900. then color it with the first available integer, which is $0$. We mark
  4901. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4902. they interfere with $\ttm{tmp\_0}$.
  4903. \[
  4904. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4905. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4906. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4907. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4908. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4909. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4910. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4911. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4912. \draw (t0) to (t1);
  4913. \draw (t0) to (z);
  4914. \draw (z) to (y);
  4915. \draw (z) to (w);
  4916. \draw (x) to (w);
  4917. \draw (y) to (w);
  4918. \draw (v) to (w);
  4919. \end{tikzpicture}
  4920. \]
  4921. We repeat the process. The most saturated vertices are \code{z} and
  4922. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4923. available number, which is $1$. We add $1$ to the saturation for the
  4924. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4925. \[
  4926. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4927. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4928. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4929. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4930. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4931. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4932. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4933. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4934. \draw (t0) to (t1);
  4935. \draw (t0) to (z);
  4936. \draw (z) to (y);
  4937. \draw (z) to (w);
  4938. \draw (x) to (w);
  4939. \draw (y) to (w);
  4940. \draw (v) to (w);
  4941. \end{tikzpicture}
  4942. \]
  4943. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4944. \code{y}. We color \code{w} with the first available color, which
  4945. is $0$.
  4946. \[
  4947. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4948. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4949. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4950. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4951. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4952. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4953. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4954. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4955. \draw (t0) to (t1);
  4956. \draw (t0) to (z);
  4957. \draw (z) to (y);
  4958. \draw (z) to (w);
  4959. \draw (x) to (w);
  4960. \draw (y) to (w);
  4961. \draw (v) to (w);
  4962. \end{tikzpicture}
  4963. \]
  4964. Now \code{y} is the most saturated, so we color it with $2$.
  4965. \[
  4966. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4967. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4968. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4969. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4970. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4971. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4972. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4973. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4974. \draw (t0) to (t1);
  4975. \draw (t0) to (z);
  4976. \draw (z) to (y);
  4977. \draw (z) to (w);
  4978. \draw (x) to (w);
  4979. \draw (y) to (w);
  4980. \draw (v) to (w);
  4981. \end{tikzpicture}
  4982. \]
  4983. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4984. We choose to color \code{v} with $1$.
  4985. \[
  4986. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4987. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4988. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4989. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4990. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4991. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4992. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4993. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4994. \draw (t0) to (t1);
  4995. \draw (t0) to (z);
  4996. \draw (z) to (y);
  4997. \draw (z) to (w);
  4998. \draw (x) to (w);
  4999. \draw (y) to (w);
  5000. \draw (v) to (w);
  5001. \end{tikzpicture}
  5002. \]
  5003. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5004. \[
  5005. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5006. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5007. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5008. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5009. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5010. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5011. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5012. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5013. \draw (t0) to (t1);
  5014. \draw (t0) to (z);
  5015. \draw (z) to (y);
  5016. \draw (z) to (w);
  5017. \draw (x) to (w);
  5018. \draw (y) to (w);
  5019. \draw (v) to (w);
  5020. \end{tikzpicture}
  5021. \]
  5022. So we obtain the following coloring:
  5023. \[
  5024. \{ \ttm{tmp\_0} \mapsto 0,
  5025. \ttm{tmp\_1} \mapsto 1,
  5026. \ttm{z} \mapsto 1,
  5027. \ttm{x} \mapsto 1,
  5028. \ttm{y} \mapsto 2,
  5029. \ttm{w} \mapsto 0,
  5030. \ttm{v} \mapsto 1 \}
  5031. \]
  5032. \fi}
  5033. We recommend creating an auxiliary function named \code{color\_graph}
  5034. that takes an interference graph and a list of all the variables in
  5035. the program. This function should return a mapping of variables to
  5036. their colors (represented as natural numbers). By creating this helper
  5037. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  5038. when we add support for functions.
  5039. To prioritize the processing of highly saturated nodes inside the
  5040. \code{color\_graph} function, we recommend using the priority queue
  5041. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5042. addition, you will need to maintain a mapping from variables to their
  5043. ``handles'' in the priority queue so that you can notify the priority
  5044. queue when their saturation changes.}
  5045. {\if\edition\racketEd
  5046. \begin{figure}[tp]
  5047. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5048. \small
  5049. \begin{tcolorbox}[title=Priority Queue]
  5050. A \emph{priority queue} is a collection of items in which the
  5051. removal of items is governed by priority. In a ``min'' queue,
  5052. lower priority items are removed first. An implementation is in
  5053. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5054. queue} \index{subject}{minimum priority queue}
  5055. \begin{description}
  5056. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5057. priority queue that uses the $\itm{cmp}$ predicate to determine
  5058. whether its first argument has lower or equal priority to its
  5059. second argument.
  5060. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5061. items in the queue.
  5062. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5063. the item into the queue and returns a handle for the item in the
  5064. queue.
  5065. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5066. the lowest priority.
  5067. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5068. notifies the queue that the priority has decreased for the item
  5069. associated with the given handle.
  5070. \end{description}
  5071. \end{tcolorbox}
  5072. %\end{wrapfigure}
  5073. \caption{The priority queue data structure.}
  5074. \label{fig:priority-queue}
  5075. \end{figure}
  5076. \fi}
  5077. With the coloring complete, we finalize the assignment of variables to
  5078. registers and stack locations. We map the first $k$ colors to the $k$
  5079. registers and the rest of the colors to stack locations. Suppose for
  5080. the moment that we have just one register to use for register
  5081. allocation, \key{rcx}. Then we have the following map from colors to
  5082. locations.
  5083. \[
  5084. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5085. \]
  5086. Composing this mapping with the coloring, we arrive at the following
  5087. assignment of variables to locations.
  5088. {\if\edition\racketEd
  5089. \begin{gather*}
  5090. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5091. \ttm{w} \mapsto \key{\%rcx}, \,
  5092. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5093. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5094. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5095. \ttm{t} \mapsto \key{\%rcx} \}
  5096. \end{gather*}
  5097. \fi}
  5098. {\if\edition\pythonEd
  5099. \begin{gather*}
  5100. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5101. \ttm{w} \mapsto \key{\%rcx}, \,
  5102. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5103. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5104. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5105. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5106. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5107. \end{gather*}
  5108. \fi}
  5109. Adapt the code from the \code{assign\_homes} pass
  5110. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  5111. assigned location. Applying the above assignment to our running
  5112. example, on the left, yields the program on the right.
  5113. % why frame size of 32? -JGS
  5114. \begin{center}
  5115. {\if\edition\racketEd
  5116. \begin{minipage}{0.3\textwidth}
  5117. \begin{lstlisting}
  5118. movq $1, v
  5119. movq $42, w
  5120. movq v, x
  5121. addq $7, x
  5122. movq x, y
  5123. movq x, z
  5124. addq w, z
  5125. movq y, t
  5126. negq t
  5127. movq z, %rax
  5128. addq t, %rax
  5129. jmp conclusion
  5130. \end{lstlisting}
  5131. \end{minipage}
  5132. $\Rightarrow\qquad$
  5133. \begin{minipage}{0.45\textwidth}
  5134. \begin{lstlisting}
  5135. movq $1, -8(%rbp)
  5136. movq $42, %rcx
  5137. movq -8(%rbp), -8(%rbp)
  5138. addq $7, -8(%rbp)
  5139. movq -8(%rbp), -16(%rbp)
  5140. movq -8(%rbp), -8(%rbp)
  5141. addq %rcx, -8(%rbp)
  5142. movq -16(%rbp), %rcx
  5143. negq %rcx
  5144. movq -8(%rbp), %rax
  5145. addq %rcx, %rax
  5146. jmp conclusion
  5147. \end{lstlisting}
  5148. \end{minipage}
  5149. \fi}
  5150. {\if\edition\pythonEd
  5151. \begin{minipage}{0.3\textwidth}
  5152. \begin{lstlisting}
  5153. movq $1, v
  5154. movq $42, w
  5155. movq v, x
  5156. addq $7, x
  5157. movq x, y
  5158. movq x, z
  5159. addq w, z
  5160. movq y, tmp_0
  5161. negq tmp_0
  5162. movq z, tmp_1
  5163. addq tmp_0, tmp_1
  5164. movq tmp_1, %rdi
  5165. callq print_int
  5166. \end{lstlisting}
  5167. \end{minipage}
  5168. $\Rightarrow\qquad$
  5169. \begin{minipage}{0.45\textwidth}
  5170. \begin{lstlisting}
  5171. movq $1, -8(%rbp)
  5172. movq $42, %rcx
  5173. movq -8(%rbp), -8(%rbp)
  5174. addq $7, -8(%rbp)
  5175. movq -8(%rbp), -16(%rbp)
  5176. movq -8(%rbp), -8(%rbp)
  5177. addq %rcx, -8(%rbp)
  5178. movq -16(%rbp), %rcx
  5179. negq %rcx
  5180. movq -8(%rbp), -8(%rbp)
  5181. addq %rcx, -8(%rbp)
  5182. movq -8(%rbp), %rdi
  5183. callq print_int
  5184. \end{lstlisting}
  5185. \end{minipage}
  5186. \fi}
  5187. \end{center}
  5188. \begin{exercise}\normalfont\normalsize
  5189. Implement the \code{allocate\_registers} pass.
  5190. Create five programs that exercise all aspects of the register
  5191. allocation algorithm, including spilling variables to the stack.
  5192. %
  5193. {\if\edition\racketEd
  5194. Replace \code{assign\_homes} in the list of \code{passes} in the
  5195. \code{run-tests.rkt} script with the three new passes:
  5196. \code{uncover\_live}, \code{build\_interference}, and
  5197. \code{allocate\_registers}.
  5198. Temporarily remove the call to \code{compiler-tests}.
  5199. Run the script to test the register allocator.
  5200. \fi}
  5201. %
  5202. {\if\edition\pythonEd
  5203. Run the \code{run-tests.py} script to to check whether the
  5204. output programs produce the same result as the input programs.
  5205. \fi}
  5206. \end{exercise}
  5207. \section{Patch Instructions}
  5208. \label{sec:patch-instructions}
  5209. The remaining step in the compilation to x86 is to ensure that the
  5210. instructions have at most one argument that is a memory access.
  5211. %
  5212. In the running example, the instruction \code{movq -8(\%rbp),
  5213. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5214. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5215. then move \code{rax} into \code{-16(\%rbp)}.
  5216. %
  5217. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5218. problematic, but they can simply be deleted. In general, we recommend
  5219. deleting all the trivial moves whose source and destination are the
  5220. same location.
  5221. %
  5222. The following is the output of \code{patch\_instructions} on the
  5223. running example.
  5224. \begin{center}
  5225. {\if\edition\racketEd
  5226. \begin{minipage}{0.4\textwidth}
  5227. \begin{lstlisting}
  5228. movq $1, -8(%rbp)
  5229. movq $42, %rcx
  5230. movq -8(%rbp), -8(%rbp)
  5231. addq $7, -8(%rbp)
  5232. movq -8(%rbp), -16(%rbp)
  5233. movq -8(%rbp), -8(%rbp)
  5234. addq %rcx, -8(%rbp)
  5235. movq -16(%rbp), %rcx
  5236. negq %rcx
  5237. movq -8(%rbp), %rax
  5238. addq %rcx, %rax
  5239. jmp conclusion
  5240. \end{lstlisting}
  5241. \end{minipage}
  5242. $\Rightarrow\qquad$
  5243. \begin{minipage}{0.45\textwidth}
  5244. \begin{lstlisting}
  5245. movq $1, -8(%rbp)
  5246. movq $42, %rcx
  5247. addq $7, -8(%rbp)
  5248. movq -8(%rbp), %rax
  5249. movq %rax, -16(%rbp)
  5250. addq %rcx, -8(%rbp)
  5251. movq -16(%rbp), %rcx
  5252. negq %rcx
  5253. movq -8(%rbp), %rax
  5254. addq %rcx, %rax
  5255. jmp conclusion
  5256. \end{lstlisting}
  5257. \end{minipage}
  5258. \fi}
  5259. {\if\edition\pythonEd
  5260. \begin{minipage}{0.4\textwidth}
  5261. \begin{lstlisting}
  5262. movq $1, -8(%rbp)
  5263. movq $42, %rcx
  5264. movq -8(%rbp), -8(%rbp)
  5265. addq $7, -8(%rbp)
  5266. movq -8(%rbp), -16(%rbp)
  5267. movq -8(%rbp), -8(%rbp)
  5268. addq %rcx, -8(%rbp)
  5269. movq -16(%rbp), %rcx
  5270. negq %rcx
  5271. movq -8(%rbp), -8(%rbp)
  5272. addq %rcx, -8(%rbp)
  5273. movq -8(%rbp), %rdi
  5274. callq print_int
  5275. \end{lstlisting}
  5276. \end{minipage}
  5277. $\Rightarrow\qquad$
  5278. \begin{minipage}{0.45\textwidth}
  5279. \begin{lstlisting}
  5280. movq $1, -8(%rbp)
  5281. movq $42, %rcx
  5282. addq $7, -8(%rbp)
  5283. movq -8(%rbp), %rax
  5284. movq %rax, -16(%rbp)
  5285. addq %rcx, -8(%rbp)
  5286. movq -16(%rbp), %rcx
  5287. negq %rcx
  5288. addq %rcx, -8(%rbp)
  5289. movq -8(%rbp), %rdi
  5290. callq print_int
  5291. \end{lstlisting}
  5292. \end{minipage}
  5293. \fi}
  5294. \end{center}
  5295. \begin{exercise}\normalfont\normalsize
  5296. %
  5297. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5298. %
  5299. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5300. %in the \code{run-tests.rkt} script.
  5301. %
  5302. Run the script to test the \code{patch\_instructions} pass.
  5303. \end{exercise}
  5304. \section{Prelude and Conclusion}
  5305. \label{sec:print-x86-reg-alloc}
  5306. \index{subject}{calling conventions}
  5307. \index{subject}{prelude}\index{subject}{conclusion}
  5308. Recall that this pass generates the prelude and conclusion
  5309. instructions to satisfy the x86 calling conventions
  5310. (Section~\ref{sec:calling-conventions}). With the addition of the
  5311. register allocator, the callee-saved registers used by the register
  5312. allocator must be saved in the prelude and restored in the conclusion.
  5313. In the \code{allocate\_registers} pass,
  5314. %
  5315. \racket{add an entry to the \itm{info}
  5316. of \code{X86Program} named \code{used\_callee}}
  5317. %
  5318. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5319. %
  5320. that stores the set of callee-saved registers that were assigned to
  5321. variables. The \code{prelude\_and\_conclusion} pass can then access
  5322. this information to decide which callee-saved registers need to be
  5323. saved and restored.
  5324. %
  5325. When calculating the amount to adjust the \code{rsp} in the prelude,
  5326. make sure to take into account the space used for saving the
  5327. callee-saved registers. Also, don't forget that the frame needs to be
  5328. a multiple of 16 bytes! We recommend using the following equation for
  5329. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5330. of spilled variables and $C$ be the number of callee-saved registers
  5331. that were allocated to variables. The $\itm{align}$ function rounds a
  5332. number up to the nearest 16 bytes.
  5333. \[
  5334. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5335. \]
  5336. The reason we subtract $8\itm{C}$ in the above equation is because the
  5337. prelude uses \code{pushq} to save each of the callee-saved registers,
  5338. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5339. \racket{An overview of all of the passes involved in register
  5340. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5341. {\if\edition\racketEd
  5342. \begin{figure}[tbp]
  5343. \begin{tcolorbox}[colback=white]
  5344. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5345. \node (Lvar) at (0,2) {\large \LangVar{}};
  5346. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5347. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5348. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5349. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5350. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5351. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5352. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5353. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5354. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5355. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5356. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5357. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5358. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5359. \path[->,bend left=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5360. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5361. \path[->,bend right=15] (x86-2-2) edge [left] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5362. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5363. \path[->,bend left=15] (x86-4) edge [left] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5364. \end{tikzpicture}
  5365. \end{tcolorbox}
  5366. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5367. \label{fig:reg-alloc-passes}
  5368. \end{figure}
  5369. \fi}
  5370. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5371. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5372. use of registers and the stack, we limit the register allocator for
  5373. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5374. the prelude\index{subject}{prelude} of the \code{main} function, we
  5375. push \code{rbx} onto the stack because it is a callee-saved register
  5376. and it was assigned to a variable by the register allocator. We
  5377. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5378. reserve space for the one spilled variable. After that subtraction,
  5379. the \code{rsp} is aligned to 16 bytes.
  5380. Moving on to the program proper, we see how the registers were
  5381. allocated.
  5382. %
  5383. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5384. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5385. %
  5386. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5387. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5388. were assigned to \code{rbx}.}
  5389. %
  5390. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5391. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5392. callee-save register \code{rbx} onto the stack. The spilled variables
  5393. must be placed lower on the stack than the saved callee-save
  5394. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5395. \code{-16(\%rbp)}.
  5396. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5397. done in the prelude. We move the stack pointer up by \code{8} bytes
  5398. (the room for spilled variables), then we pop the old values of
  5399. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5400. \code{retq} to return control to the operating system.
  5401. \begin{figure}[tbp]
  5402. \begin{minipage}{0.55\textwidth}
  5403. \begin{tcolorbox}[colback=white]
  5404. % var_test_28.rkt
  5405. % (use-minimal-set-of-registers! #t)
  5406. % and only rbx rcx
  5407. % tmp 0 rbx
  5408. % z 1 rcx
  5409. % y 0 rbx
  5410. % w 2 16(%rbp)
  5411. % v 0 rbx
  5412. % x 0 rbx
  5413. {\if\edition\racketEd
  5414. \begin{lstlisting}
  5415. start:
  5416. movq $1, %rbx
  5417. movq $42, -16(%rbp)
  5418. addq $7, %rbx
  5419. movq %rbx, %rcx
  5420. addq -16(%rbp), %rcx
  5421. negq %rbx
  5422. movq %rcx, %rax
  5423. addq %rbx, %rax
  5424. jmp conclusion
  5425. .globl main
  5426. main:
  5427. pushq %rbp
  5428. movq %rsp, %rbp
  5429. pushq %rbx
  5430. subq $8, %rsp
  5431. jmp start
  5432. conclusion:
  5433. addq $8, %rsp
  5434. popq %rbx
  5435. popq %rbp
  5436. retq
  5437. \end{lstlisting}
  5438. \fi}
  5439. {\if\edition\pythonEd
  5440. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5441. \begin{lstlisting}
  5442. .globl main
  5443. main:
  5444. pushq %rbp
  5445. movq %rsp, %rbp
  5446. pushq %rbx
  5447. subq $8, %rsp
  5448. movq $1, %rcx
  5449. movq $42, %rbx
  5450. addq $7, %rcx
  5451. movq %rcx, -16(%rbp)
  5452. addq %rbx, -16(%rbp)
  5453. negq %rcx
  5454. movq -16(%rbp), %rbx
  5455. addq %rcx, %rbx
  5456. movq %rbx, %rdi
  5457. callq print_int
  5458. addq $8, %rsp
  5459. popq %rbx
  5460. popq %rbp
  5461. retq
  5462. \end{lstlisting}
  5463. \fi}
  5464. \end{tcolorbox}
  5465. \end{minipage}
  5466. \caption{The x86 output from the running example
  5467. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5468. and \code{rcx}.}
  5469. \label{fig:running-example-x86}
  5470. \end{figure}
  5471. \begin{exercise}\normalfont\normalsize
  5472. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5473. %
  5474. \racket{
  5475. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5476. list of passes and the call to \code{compiler-tests}.}
  5477. %
  5478. Run the script to test the complete compiler for \LangVar{} that
  5479. performs register allocation.
  5480. \end{exercise}
  5481. \section{Challenge: Move Biasing}
  5482. \label{sec:move-biasing}
  5483. \index{subject}{move biasing}
  5484. This section describes an enhancement to the register allocator,
  5485. called move biasing, for students who are looking for an extra
  5486. challenge.
  5487. {\if\edition\racketEd
  5488. To motivate the need for move biasing we return to the running example
  5489. but this time we use all of the general purpose registers. So we have
  5490. the following mapping of color numbers to registers.
  5491. \[
  5492. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5493. \]
  5494. Using the same assignment of variables to color numbers that was
  5495. produced by the register allocator described in the last section, we
  5496. get the following program.
  5497. \begin{center}
  5498. \begin{minipage}{0.3\textwidth}
  5499. \begin{lstlisting}
  5500. movq $1, v
  5501. movq $42, w
  5502. movq v, x
  5503. addq $7, x
  5504. movq x, y
  5505. movq x, z
  5506. addq w, z
  5507. movq y, t
  5508. negq t
  5509. movq z, %rax
  5510. addq t, %rax
  5511. jmp conclusion
  5512. \end{lstlisting}
  5513. \end{minipage}
  5514. $\Rightarrow\qquad$
  5515. \begin{minipage}{0.45\textwidth}
  5516. \begin{lstlisting}
  5517. movq $1, %rdx
  5518. movq $42, %rcx
  5519. movq %rdx, %rdx
  5520. addq $7, %rdx
  5521. movq %rdx, %rsi
  5522. movq %rdx, %rdx
  5523. addq %rcx, %rdx
  5524. movq %rsi, %rcx
  5525. negq %rcx
  5526. movq %rdx, %rax
  5527. addq %rcx, %rax
  5528. jmp conclusion
  5529. \end{lstlisting}
  5530. \end{minipage}
  5531. \end{center}
  5532. In the above output code there are two \key{movq} instructions that
  5533. can be removed because their source and target are the same. However,
  5534. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5535. register, we could instead remove three \key{movq} instructions. We
  5536. can accomplish this by taking into account which variables appear in
  5537. \key{movq} instructions with which other variables.
  5538. \fi}
  5539. {\if\edition\pythonEd
  5540. %
  5541. To motivate the need for move biasing we return to the running example
  5542. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5543. remove three trivial move instructions from the running
  5544. example. However, we could remove another trivial move if we were able
  5545. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5546. We say that two variables $p$ and $q$ are \emph{move
  5547. related}\index{subject}{move related} if they participate together in
  5548. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5549. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5550. when there are multiple variables with the same saturation, prefer
  5551. variables that can be assigned to a color that is the same as the
  5552. color of a move related variable. Furthermore, when the register
  5553. allocator chooses a color for a variable, it should prefer a color
  5554. that has already been used for a move-related variable (assuming that
  5555. they do not interfere). Of course, this preference should not override
  5556. the preference for registers over stack locations. So this preference
  5557. should be used as a tie breaker when choosing between registers or
  5558. when choosing between stack locations.
  5559. We recommend representing the move relationships in a graph, similar
  5560. to how we represented interference. The following is the \emph{move
  5561. graph} for our running example.
  5562. {\if\edition\racketEd
  5563. \[
  5564. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5565. \node (rax) at (0,0) {$\ttm{rax}$};
  5566. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5567. \node (t) at (0,2) {$\ttm{t}$};
  5568. \node (z) at (3,2) {$\ttm{z}$};
  5569. \node (x) at (6,2) {$\ttm{x}$};
  5570. \node (y) at (3,0) {$\ttm{y}$};
  5571. \node (w) at (6,0) {$\ttm{w}$};
  5572. \node (v) at (9,0) {$\ttm{v}$};
  5573. \draw (v) to (x);
  5574. \draw (x) to (y);
  5575. \draw (x) to (z);
  5576. \draw (y) to (t);
  5577. \end{tikzpicture}
  5578. \]
  5579. \fi}
  5580. %
  5581. {\if\edition\pythonEd
  5582. \[
  5583. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5584. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5585. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5586. \node (z) at (3,2) {$\ttm{z}$};
  5587. \node (x) at (6,2) {$\ttm{x}$};
  5588. \node (y) at (3,0) {$\ttm{y}$};
  5589. \node (w) at (6,0) {$\ttm{w}$};
  5590. \node (v) at (9,0) {$\ttm{v}$};
  5591. \draw (y) to (t0);
  5592. \draw (z) to (x);
  5593. \draw (z) to (t1);
  5594. \draw (x) to (y);
  5595. \draw (x) to (v);
  5596. \end{tikzpicture}
  5597. \]
  5598. \fi}
  5599. {\if\edition\racketEd
  5600. Now we replay the graph coloring, pausing to see the coloring of
  5601. \code{y}. Recall the following configuration. The most saturated vertices
  5602. were \code{w} and \code{y}.
  5603. \[
  5604. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5605. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5606. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5607. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5608. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5609. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5610. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5611. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5612. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5613. \draw (t1) to (rax);
  5614. \draw (t1) to (z);
  5615. \draw (z) to (y);
  5616. \draw (z) to (w);
  5617. \draw (x) to (w);
  5618. \draw (y) to (w);
  5619. \draw (v) to (w);
  5620. \draw (v) to (rsp);
  5621. \draw (w) to (rsp);
  5622. \draw (x) to (rsp);
  5623. \draw (y) to (rsp);
  5624. \path[-.,bend left=15] (z) edge node {} (rsp);
  5625. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5626. \draw (rax) to (rsp);
  5627. \end{tikzpicture}
  5628. \]
  5629. %
  5630. Last time we chose to color \code{w} with $0$. But this time we see
  5631. that \code{w} is not move related to any vertex, but \code{y} is move
  5632. related to \code{t}. So we choose to color \code{y} with $0$, the
  5633. same color as \code{t}.
  5634. \[
  5635. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5636. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5637. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5638. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5639. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5640. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5641. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5642. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5643. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5644. \draw (t1) to (rax);
  5645. \draw (t1) to (z);
  5646. \draw (z) to (y);
  5647. \draw (z) to (w);
  5648. \draw (x) to (w);
  5649. \draw (y) to (w);
  5650. \draw (v) to (w);
  5651. \draw (v) to (rsp);
  5652. \draw (w) to (rsp);
  5653. \draw (x) to (rsp);
  5654. \draw (y) to (rsp);
  5655. \path[-.,bend left=15] (z) edge node {} (rsp);
  5656. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5657. \draw (rax) to (rsp);
  5658. \end{tikzpicture}
  5659. \]
  5660. Now \code{w} is the most saturated, so we color it $2$.
  5661. \[
  5662. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5663. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5664. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5665. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5666. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5667. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5668. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5669. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5670. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5671. \draw (t1) to (rax);
  5672. \draw (t1) to (z);
  5673. \draw (z) to (y);
  5674. \draw (z) to (w);
  5675. \draw (x) to (w);
  5676. \draw (y) to (w);
  5677. \draw (v) to (w);
  5678. \draw (v) to (rsp);
  5679. \draw (w) to (rsp);
  5680. \draw (x) to (rsp);
  5681. \draw (y) to (rsp);
  5682. \path[-.,bend left=15] (z) edge node {} (rsp);
  5683. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5684. \draw (rax) to (rsp);
  5685. \end{tikzpicture}
  5686. \]
  5687. At this point, vertices \code{x} and \code{v} are most saturated, but
  5688. \code{x} is move related to \code{y} and \code{z}, so we color
  5689. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5690. \[
  5691. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5692. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5693. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5694. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5695. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5696. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5697. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5698. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5699. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5700. \draw (t1) to (rax);
  5701. \draw (t) to (z);
  5702. \draw (z) to (y);
  5703. \draw (z) to (w);
  5704. \draw (x) to (w);
  5705. \draw (y) to (w);
  5706. \draw (v) to (w);
  5707. \draw (v) to (rsp);
  5708. \draw (w) to (rsp);
  5709. \draw (x) to (rsp);
  5710. \draw (y) to (rsp);
  5711. \path[-.,bend left=15] (z) edge node {} (rsp);
  5712. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5713. \draw (rax) to (rsp);
  5714. \end{tikzpicture}
  5715. \]
  5716. \fi}
  5717. %
  5718. {\if\edition\pythonEd
  5719. Now we replay the graph coloring, pausing before the coloring of
  5720. \code{w}. Recall the following configuration. The most saturated vertices
  5721. were \code{tmp\_1}, \code{w}, and \code{y}.
  5722. \[
  5723. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5724. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5725. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5726. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5727. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5728. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5729. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5730. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5731. \draw (t0) to (t1);
  5732. \draw (t0) to (z);
  5733. \draw (z) to (y);
  5734. \draw (z) to (w);
  5735. \draw (x) to (w);
  5736. \draw (y) to (w);
  5737. \draw (v) to (w);
  5738. \end{tikzpicture}
  5739. \]
  5740. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5741. or \code{y}, but note that \code{w} is not move related to any
  5742. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5743. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5744. \code{y} and color it $0$, we can delete another move instruction.
  5745. \[
  5746. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5747. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5748. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5749. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5750. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5751. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5752. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5753. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5754. \draw (t0) to (t1);
  5755. \draw (t0) to (z);
  5756. \draw (z) to (y);
  5757. \draw (z) to (w);
  5758. \draw (x) to (w);
  5759. \draw (y) to (w);
  5760. \draw (v) to (w);
  5761. \end{tikzpicture}
  5762. \]
  5763. Now \code{w} is the most saturated, so we color it $2$.
  5764. \[
  5765. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5766. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5767. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5768. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5769. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5770. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5771. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5772. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5773. \draw (t0) to (t1);
  5774. \draw (t0) to (z);
  5775. \draw (z) to (y);
  5776. \draw (z) to (w);
  5777. \draw (x) to (w);
  5778. \draw (y) to (w);
  5779. \draw (v) to (w);
  5780. \end{tikzpicture}
  5781. \]
  5782. To finish the coloring, \code{x} and \code{v} get $0$ and
  5783. \code{tmp\_1} gets $1$.
  5784. \[
  5785. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5786. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5787. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5788. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5789. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5790. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5791. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5792. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5793. \draw (t0) to (t1);
  5794. \draw (t0) to (z);
  5795. \draw (z) to (y);
  5796. \draw (z) to (w);
  5797. \draw (x) to (w);
  5798. \draw (y) to (w);
  5799. \draw (v) to (w);
  5800. \end{tikzpicture}
  5801. \]
  5802. \fi}
  5803. So we have the following assignment of variables to registers.
  5804. {\if\edition\racketEd
  5805. \begin{gather*}
  5806. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5807. \ttm{w} \mapsto \key{\%rsi}, \,
  5808. \ttm{x} \mapsto \key{\%rcx}, \,
  5809. \ttm{y} \mapsto \key{\%rcx}, \,
  5810. \ttm{z} \mapsto \key{\%rdx}, \,
  5811. \ttm{t} \mapsto \key{\%rcx} \}
  5812. \end{gather*}
  5813. \fi}
  5814. {\if\edition\pythonEd
  5815. \begin{gather*}
  5816. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5817. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5818. \ttm{x} \mapsto \key{\%rcx}, \,
  5819. \ttm{y} \mapsto \key{\%rcx}, \\
  5820. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5821. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5822. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5823. \end{gather*}
  5824. \fi}
  5825. We apply this register assignment to the running example, on the left,
  5826. to obtain the code in the middle. The \code{patch\_instructions} then
  5827. deletes the trivial moves to obtain the code on the right.
  5828. {\if\edition\racketEd
  5829. \begin{minipage}{0.25\textwidth}
  5830. \begin{lstlisting}
  5831. movq $1, v
  5832. movq $42, w
  5833. movq v, x
  5834. addq $7, x
  5835. movq x, y
  5836. movq x, z
  5837. addq w, z
  5838. movq y, t
  5839. negq t
  5840. movq z, %rax
  5841. addq t, %rax
  5842. jmp conclusion
  5843. \end{lstlisting}
  5844. \end{minipage}
  5845. $\Rightarrow\qquad$
  5846. \begin{minipage}{0.25\textwidth}
  5847. \begin{lstlisting}
  5848. movq $1, %rcx
  5849. movq $42, %rsi
  5850. movq %rcx, %rcx
  5851. addq $7, %rcx
  5852. movq %rcx, %rcx
  5853. movq %rcx, %rdx
  5854. addq %rsi, %rdx
  5855. movq %rcx, %rcx
  5856. negq %rcx
  5857. movq %rdx, %rax
  5858. addq %rcx, %rax
  5859. jmp conclusion
  5860. \end{lstlisting}
  5861. \end{minipage}
  5862. $\Rightarrow\qquad$
  5863. \begin{minipage}{0.25\textwidth}
  5864. \begin{lstlisting}
  5865. movq $1, %rcx
  5866. movq $42, %rsi
  5867. addq $7, %rcx
  5868. movq %rcx, %rdx
  5869. addq %rsi, %rdx
  5870. negq %rcx
  5871. movq %rdx, %rax
  5872. addq %rcx, %rax
  5873. jmp conclusion
  5874. \end{lstlisting}
  5875. \end{minipage}
  5876. \fi}
  5877. {\if\edition\pythonEd
  5878. \begin{minipage}{0.20\textwidth}
  5879. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5880. movq $1, v
  5881. movq $42, w
  5882. movq v, x
  5883. addq $7, x
  5884. movq x, y
  5885. movq x, z
  5886. addq w, z
  5887. movq y, tmp_0
  5888. negq tmp_0
  5889. movq z, tmp_1
  5890. addq tmp_0, tmp_1
  5891. movq tmp_1, %rdi
  5892. callq _print_int
  5893. \end{lstlisting}
  5894. \end{minipage}
  5895. ${\Rightarrow\qquad}$
  5896. \begin{minipage}{0.30\textwidth}
  5897. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5898. movq $1, %rcx
  5899. movq $42, -16(%rbp)
  5900. movq %rcx, %rcx
  5901. addq $7, %rcx
  5902. movq %rcx, %rcx
  5903. movq %rcx, -8(%rbp)
  5904. addq -16(%rbp), -8(%rbp)
  5905. movq %rcx, %rcx
  5906. negq %rcx
  5907. movq -8(%rbp), -8(%rbp)
  5908. addq %rcx, -8(%rbp)
  5909. movq -8(%rbp), %rdi
  5910. callq _print_int
  5911. \end{lstlisting}
  5912. \end{minipage}
  5913. ${\Rightarrow\qquad}$
  5914. \begin{minipage}{0.20\textwidth}
  5915. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5916. movq $1, %rcx
  5917. movq $42, -16(%rbp)
  5918. addq $7, %rcx
  5919. movq %rcx, -8(%rbp)
  5920. movq -16(%rbp), %rax
  5921. addq %rax, -8(%rbp)
  5922. negq %rcx
  5923. addq %rcx, -8(%rbp)
  5924. movq -8(%rbp), %rdi
  5925. callq print_int
  5926. \end{lstlisting}
  5927. \end{minipage}
  5928. \fi}
  5929. \begin{exercise}\normalfont\normalsize
  5930. Change your implementation of \code{allocate\_registers} to take move
  5931. biasing into account. Create two new tests that include at least one
  5932. opportunity for move biasing and visually inspect the output x86
  5933. programs to make sure that your move biasing is working properly. Make
  5934. sure that your compiler still passes all of the tests.
  5935. \end{exercise}
  5936. %To do: another neat challenge would be to do
  5937. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5938. %% \subsection{Output of the Running Example}
  5939. %% \label{sec:reg-alloc-output}
  5940. % challenge: prioritize variables based on execution frequencies
  5941. % and the number of uses of a variable
  5942. % challenge: enhance the coloring algorithm using Chaitin's
  5943. % approach of prioritizing high-degree variables
  5944. % by removing low-degree variables (coloring them later)
  5945. % from the interference graph
  5946. \section{Further Reading}
  5947. \label{sec:register-allocation-further-reading}
  5948. Early register allocation algorithms were developed for Fortran
  5949. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5950. of graph coloring began in the late 1970s and early 1980s with the
  5951. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5952. algorithm is based on the following observation of
  5953. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5954. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5955. $v$ removed is also $k$ colorable. To see why, suppose that the
  5956. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5957. different colors, but since there are less than $k$ neighbors, there
  5958. will be one or more colors left over to use for coloring $v$ in $G$.
  5959. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5960. less than $k$ from the graph and recursively colors the rest of the
  5961. graph. Upon returning from the recursion, it colors $v$ with one of
  5962. the available colors and returns. \citet{Chaitin:1982vn} augments
  5963. this algorithm to handle spilling as follows. If there are no vertices
  5964. of degree lower than $k$ then pick a vertex at random, spill it,
  5965. remove it from the graph, and proceed recursively to color the rest of
  5966. the graph.
  5967. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5968. move-related and that don't interfere with each other, a process
  5969. called \emph{coalescing}. While coalescing decreases the number of
  5970. moves, it can make the graph more difficult to
  5971. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5972. which two variables are merged only if they have fewer than $k$
  5973. neighbors of high degree. \citet{George:1996aa} observe that
  5974. conservative coalescing is sometimes too conservative and make it more
  5975. aggressive by iterating the coalescing with the removal of low-degree
  5976. vertices.
  5977. %
  5978. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5979. also propose \emph{biased coloring} in which a variable is assigned to
  5980. the same color as another move-related variable if possible, as
  5981. discussed in Section~\ref{sec:move-biasing}.
  5982. %
  5983. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5984. performs coalescing, graph coloring, and spill code insertion until
  5985. all variables have been assigned a location.
  5986. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5987. spills variables that don't have to be: a high-degree variable can be
  5988. colorable if many of its neighbors are assigned the same color.
  5989. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5990. high-degree vertex is not immediately spilled. Instead the decision is
  5991. deferred until after the recursive call, at which point it is apparent
  5992. whether there is actually an available color or not. We observe that
  5993. this algorithm is equivalent to the smallest-last ordering
  5994. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5995. be registers and the rest to be stack locations.
  5996. %% biased coloring
  5997. Earlier editions of the compiler course at Indiana University
  5998. \citep{Dybvig:2010aa} were based on the algorithm of
  5999. \citet{Briggs:1994kx}.
  6000. The smallest-last ordering algorithm is one of many \emph{greedy}
  6001. coloring algorithms. A greedy coloring algorithm visits all the
  6002. vertices in a particular order and assigns each one the first
  6003. available color. An \emph{offline} greedy algorithm chooses the
  6004. ordering up-front, prior to assigning colors. The algorithm of
  6005. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6006. ordering does not depend on the colors assigned. Other orderings are
  6007. possible. For example, \citet{Chow:1984ys} order variables according
  6008. to an estimate of runtime cost.
  6009. An \emph{online} greedy coloring algorithm uses information about the
  6010. current assignment of colors to influence the order in which the
  6011. remaining vertices are colored. The saturation-based algorithm
  6012. described in this chapter is one such algorithm. We choose to use
  6013. saturation-based coloring because it is fun to introduce graph
  6014. coloring via Sudoku!
  6015. A register allocator may choose to map each variable to just one
  6016. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6017. variable to one or more locations. The later can be achieved by
  6018. \emph{live range splitting}, where a variable is replaced by several
  6019. variables that each handle part of its live
  6020. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6021. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6022. %% replacement algorithm, bottom-up local
  6023. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6024. %% Cooper: top-down (priority bassed), bottom-up
  6025. %% top-down
  6026. %% order variables by priority (estimated cost)
  6027. %% caveat: split variables into two groups:
  6028. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6029. %% color the constrained ones first
  6030. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6031. %% cite J. Cocke for an algorithm that colors variables
  6032. %% in a high-degree first ordering
  6033. %Register Allocation via Usage Counts, Freiburghouse CACM
  6034. \citet{Palsberg:2007si} observe that many of the interference graphs
  6035. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  6036. that is, every cycle with four or more edges has an edge which is not
  6037. part of the cycle but which connects two vertices on the cycle. Such
  6038. graphs can be optimally colored by the greedy algorithm with a vertex
  6039. ordering determined by maximum cardinality search.
  6040. In situations where compile time is of utmost importance, such as in
  6041. just-in-time compilers, graph coloring algorithms can be too expensive
  6042. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  6043. appropriate.
  6044. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6045. \chapter{Booleans and Conditionals}
  6046. \label{ch:Lif}
  6047. \index{subject}{Boolean}
  6048. \index{subject}{control flow}
  6049. \index{subject}{conditional expression}
  6050. The \LangVar{} language only has a single kind of value, the
  6051. integers. In this chapter we add a second kind of value, the Booleans,
  6052. to create the \LangIf{} language. The Boolean values \emph{true} and
  6053. \emph{false} are written \TRUE{} and \FALSE{} respectively in
  6054. \racket{Racket}\python{Python}. The \LangIf{} language includes
  6055. several operations that involve Booleans (\key{and}, \key{not},
  6056. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6057. expression \python{and statement}. With the addition of \key{if},
  6058. programs can have non-trivial control flow which
  6059. %
  6060. \racket{impacts \code{explicate\_control} and liveness analysis}
  6061. %
  6062. \python{impacts liveness analysis and motivates a new pass named
  6063. \code{explicate\_control}}.
  6064. %
  6065. Also, because we now have two kinds of values, we need to handle
  6066. programs that apply an operation to the wrong kind of value, such as
  6067. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6068. There are two language design options for such situations. One option
  6069. is to signal an error and the other is to provide a wider
  6070. interpretation of the operation. \racket{The Racket
  6071. language}\python{Python} uses a mixture of these two options,
  6072. depending on the operation and the kind of value. For example, the
  6073. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6074. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6075. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6076. %
  6077. \racket{On the other hand, \code{(car 1)} results in a run-time error
  6078. in Racket because \code{car} expects a pair.}
  6079. %
  6080. \python{On the other hand, \code{1[0]} results in a run-time error
  6081. in Python because an ``\code{int} object is not subscriptable''.}
  6082. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6083. design choices as \racket{Racket}\python{Python}, except much of the
  6084. error detection happens at compile time instead of run
  6085. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6086. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6087. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  6088. Racket}\python{MyPy} reports a compile-time error
  6089. %
  6090. \racket{because Racket expects the type of the argument to be of the form
  6091. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6092. %
  6093. \python{stating that a ``value of type \code{int} is not indexable''.}
  6094. The \LangIf{} language performs type checking during compilation like
  6095. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study
  6096. the alternative choice, that is, a dynamically typed language like
  6097. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6098. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6099. restrictive, for example, rejecting \racket{\code{(not
  6100. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6101. fairly simple because the focus of this book is on compilation, not
  6102. type systems, about which there are already several excellent
  6103. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6104. This chapter is organized as follows. We begin by defining the syntax
  6105. and interpreter for the \LangIf{} language
  6106. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  6107. checking and define a type checker for \LangIf{}
  6108. (Section~\ref{sec:type-check-Lif}).
  6109. %
  6110. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6111. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  6112. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  6113. %
  6114. The remaining sections of this chapter discuss how Booleans and
  6115. conditional control flow require changes to the existing compiler
  6116. passes and the addition of new ones. We introduce the \code{shrink}
  6117. pass to translates some operators into others, thereby reducing the
  6118. number of operators that need to be handled in later passes.
  6119. %
  6120. The main event of this chapter is the \code{explicate\_control} pass
  6121. that is responsible for translating \code{if}'s into conditional
  6122. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  6123. %
  6124. Regarding register allocation, there is the interesting question of
  6125. how to handle conditional \code{goto}'s during liveness analysis.
  6126. \section{The \LangIf{} Language}
  6127. \label{sec:lang-if}
  6128. The concrete and abstract syntax of the \LangIf{} language are defined in
  6129. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6130. respectively. The \LangIf{} language includes all of
  6131. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6132. \FALSE{},\racket{ and} the \code{if} expression\python{, and the
  6133. \code{if} statement}. We expand the set of operators to include
  6134. \begin{enumerate}
  6135. \item the logical operators \key{and}, \key{or}, and \key{not},
  6136. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6137. for comparing integers or Booleans for equality, and
  6138. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6139. comparing integers.
  6140. \end{enumerate}
  6141. \racket{We reorganize the abstract syntax for the primitive
  6142. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  6143. rule for all of them. This means that the grammar no longer checks
  6144. whether the arity of an operators matches the number of
  6145. arguments. That responsibility is moved to the type checker for
  6146. \LangIf{} (Section~\ref{sec:type-check-Lif}).}
  6147. \newcommand{\LifGrammarRacket}{
  6148. \begin{array}{lcl}
  6149. \Type &::=& \key{Boolean} \\
  6150. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6151. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6152. \Exp &::=& \itm{bool}
  6153. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6154. \MID (\key{not}\;\Exp) \\
  6155. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6156. \end{array}
  6157. }
  6158. \newcommand{\LifASTRacket}{
  6159. \begin{array}{lcl}
  6160. \Type &::=& \key{Boolean} \\
  6161. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6162. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6163. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6164. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6165. \end{array}
  6166. }
  6167. \newcommand{\LintOpAST}{
  6168. \begin{array}{rcl}
  6169. \Type &::=& \key{Integer} \\
  6170. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6171. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6172. \end{array}
  6173. }
  6174. \newcommand{\LifGrammarPython}{
  6175. \begin{array}{rcl}
  6176. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6177. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6178. \MID \key{not}~\Exp \\
  6179. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6180. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6181. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6182. \end{array}
  6183. }
  6184. \newcommand{\LifASTPython}{
  6185. \begin{array}{lcl}
  6186. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6187. \itm{unaryop} &::=& \code{Not()} \\
  6188. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6189. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6190. \Exp &::=& \BOOL{\itm{bool}}
  6191. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6192. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6193. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6194. \end{array}
  6195. }
  6196. \begin{figure}[tp]
  6197. \centering
  6198. \begin{tcolorbox}[colback=white]
  6199. {\if\edition\racketEd
  6200. \[
  6201. \begin{array}{l}
  6202. \gray{\LintGrammarRacket{}} \\ \hline
  6203. \gray{\LvarGrammarRacket{}} \\ \hline
  6204. \LifGrammarRacket{} \\
  6205. \begin{array}{lcl}
  6206. \LangIfM{} &::=& \Exp
  6207. \end{array}
  6208. \end{array}
  6209. \]
  6210. \fi}
  6211. {\if\edition\pythonEd
  6212. \[
  6213. \begin{array}{l}
  6214. \gray{\LintGrammarPython} \\ \hline
  6215. \gray{\LvarGrammarPython} \\ \hline
  6216. \LifGrammarPython \\
  6217. \begin{array}{rcl}
  6218. \LangIfM{} &::=& \Stmt^{*}
  6219. \end{array}
  6220. \end{array}
  6221. \]
  6222. \fi}
  6223. \end{tcolorbox}
  6224. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6225. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6226. \label{fig:Lif-concrete-syntax}
  6227. \end{figure}
  6228. \begin{figure}[tp]
  6229. \begin{minipage}{0.66\textwidth}
  6230. \begin{tcolorbox}[colback=white]
  6231. \centering
  6232. {\if\edition\racketEd
  6233. \[
  6234. \begin{array}{l}
  6235. \gray{\LintOpAST} \\ \hline
  6236. \gray{\LvarASTRacket{}} \\ \hline
  6237. \LifASTRacket{} \\
  6238. \begin{array}{lcl}
  6239. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6240. \end{array}
  6241. \end{array}
  6242. \]
  6243. \fi}
  6244. {\if\edition\pythonEd
  6245. \[
  6246. \begin{array}{l}
  6247. \gray{\LintASTPython} \\ \hline
  6248. \gray{\LvarASTPython} \\ \hline
  6249. \LifASTPython \\
  6250. \begin{array}{lcl}
  6251. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6252. \end{array}
  6253. \end{array}
  6254. \]
  6255. \fi}
  6256. \end{tcolorbox}
  6257. \end{minipage}
  6258. \caption{The abstract syntax of \LangIf{}.}
  6259. \label{fig:Lif-syntax}
  6260. \end{figure}
  6261. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6262. which inherits from the interpreter for \LangVar{}
  6263. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6264. evaluate to the corresponding Boolean values. The conditional
  6265. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6266. and then either evaluates $e_2$ or $e_3$ depending on whether
  6267. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6268. \code{and}, \code{or}, and \code{not} behave according to
  6269. propositional logic. In addition, the \code{and} and \code{or}
  6270. operations perform \emph{short-circuit evaluation}.
  6271. %
  6272. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6273. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6274. %
  6275. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6276. evaluated if $e_1$ evaluates to \TRUE{}.
  6277. \racket{With the increase in the number of primitive operations, the
  6278. interpreter would become repetitive without some care. We refactor
  6279. the case for \code{Prim}, moving the code that differs with each
  6280. operation into the \code{interp\_op} method shown in in
  6281. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6282. \code{or} operations separately because of their short-circuiting
  6283. behavior.}
  6284. \begin{figure}[tbp]
  6285. \begin{tcolorbox}[colback=white]
  6286. {\if\edition\racketEd
  6287. \begin{lstlisting}
  6288. (define interp-Lif-class
  6289. (class interp-Lvar-class
  6290. (super-new)
  6291. (define/public (interp_op op) ...)
  6292. (define/override ((interp_exp env) e)
  6293. (define recur (interp_exp env))
  6294. (match e
  6295. [(Bool b) b]
  6296. [(If cnd thn els)
  6297. (match (recur cnd)
  6298. [#t (recur thn)]
  6299. [#f (recur els)])]
  6300. [(Prim 'and (list e1 e2))
  6301. (match (recur e1)
  6302. [#t (match (recur e2) [#t #t] [#f #f])]
  6303. [#f #f])]
  6304. [(Prim 'or (list e1 e2))
  6305. (define v1 (recur e1))
  6306. (match v1
  6307. [#t #t]
  6308. [#f (match (recur e2) [#t #t] [#f #f])])]
  6309. [(Prim op args)
  6310. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6311. [else ((super interp_exp env) e)]))
  6312. ))
  6313. (define (interp_Lif p)
  6314. (send (new interp-Lif-class) interp_program p))
  6315. \end{lstlisting}
  6316. \fi}
  6317. {\if\edition\pythonEd
  6318. \begin{lstlisting}
  6319. class InterpLif(InterpLvar):
  6320. def interp_exp(self, e, env):
  6321. match e:
  6322. case IfExp(test, body, orelse):
  6323. if self.interp_exp(test, env):
  6324. return self.interp_exp(body, env)
  6325. else:
  6326. return self.interp_exp(orelse, env)
  6327. case UnaryOp(Not(), v):
  6328. return not self.interp_exp(v, env)
  6329. case BoolOp(And(), values):
  6330. if self.interp_exp(values[0], env):
  6331. return self.interp_exp(values[1], env)
  6332. else:
  6333. return False
  6334. case BoolOp(Or(), values):
  6335. if self.interp_exp(values[0], env):
  6336. return True
  6337. else:
  6338. return self.interp_exp(values[1], env)
  6339. case Compare(left, [cmp], [right]):
  6340. l = self.interp_exp(left, env)
  6341. r = self.interp_exp(right, env)
  6342. return self.interp_cmp(cmp)(l, r)
  6343. case _:
  6344. return super().interp_exp(e, env)
  6345. def interp_stmts(self, ss, env):
  6346. if len(ss) == 0:
  6347. return
  6348. match ss[0]:
  6349. case If(test, body, orelse):
  6350. if self.interp_exp(test, env):
  6351. return self.interp_stmts(body + ss[1:], env)
  6352. else:
  6353. return self.interp_stmts(orelse + ss[1:], env)
  6354. case _:
  6355. return super().interp_stmts(ss, env)
  6356. ...
  6357. \end{lstlisting}
  6358. \fi}
  6359. \end{tcolorbox}
  6360. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6361. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6362. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6363. \label{fig:interp-Lif}
  6364. \end{figure}
  6365. {\if\edition\racketEd
  6366. \begin{figure}[tbp]
  6367. \begin{tcolorbox}[colback=white]
  6368. \begin{lstlisting}
  6369. (define/public (interp_op op)
  6370. (match op
  6371. ['+ fx+]
  6372. ['- fx-]
  6373. ['read read-fixnum]
  6374. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6375. ['eq? (lambda (v1 v2)
  6376. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6377. (and (boolean? v1) (boolean? v2))
  6378. (and (vector? v1) (vector? v2)))
  6379. (eq? v1 v2)]))]
  6380. ['< (lambda (v1 v2)
  6381. (cond [(and (fixnum? v1) (fixnum? v2))
  6382. (< v1 v2)]))]
  6383. ['<= (lambda (v1 v2)
  6384. (cond [(and (fixnum? v1) (fixnum? v2))
  6385. (<= v1 v2)]))]
  6386. ['> (lambda (v1 v2)
  6387. (cond [(and (fixnum? v1) (fixnum? v2))
  6388. (> v1 v2)]))]
  6389. ['>= (lambda (v1 v2)
  6390. (cond [(and (fixnum? v1) (fixnum? v2))
  6391. (>= v1 v2)]))]
  6392. [else (error 'interp_op "unknown operator")]))
  6393. \end{lstlisting}
  6394. \end{tcolorbox}
  6395. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6396. \label{fig:interp-op-Lif}
  6397. \end{figure}
  6398. \fi}
  6399. {\if\edition\pythonEd
  6400. \begin{figure}
  6401. \begin{tcolorbox}[colback=white]
  6402. \begin{lstlisting}
  6403. class InterpLif(InterpLvar):
  6404. ...
  6405. def interp_cmp(self, cmp):
  6406. match cmp:
  6407. case Lt():
  6408. return lambda x, y: x < y
  6409. case LtE():
  6410. return lambda x, y: x <= y
  6411. case Gt():
  6412. return lambda x, y: x > y
  6413. case GtE():
  6414. return lambda x, y: x >= y
  6415. case Eq():
  6416. return lambda x, y: x == y
  6417. case NotEq():
  6418. return lambda x, y: x != y
  6419. \end{lstlisting}
  6420. \end{tcolorbox}
  6421. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6422. \label{fig:interp-cmp-Lif}
  6423. \end{figure}
  6424. \fi}
  6425. \section{Type Checking \LangIf{} Programs}
  6426. \label{sec:type-check-Lif}
  6427. \index{subject}{type checking}
  6428. \index{subject}{semantic analysis}
  6429. It is helpful to think about type checking in two complementary
  6430. ways. A type checker predicts the type of value that will be produced
  6431. by each expression in the program. For \LangIf{}, we have just two types,
  6432. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6433. {\if\edition\racketEd
  6434. \begin{lstlisting}
  6435. (+ 10 (- (+ 12 20)))
  6436. \end{lstlisting}
  6437. \fi}
  6438. {\if\edition\pythonEd
  6439. \begin{lstlisting}
  6440. 10 + -(12 + 20)
  6441. \end{lstlisting}
  6442. \fi}
  6443. \noindent produces a value of type \INTTY{} while
  6444. {\if\edition\racketEd
  6445. \begin{lstlisting}
  6446. (and (not #f) #t)
  6447. \end{lstlisting}
  6448. \fi}
  6449. {\if\edition\pythonEd
  6450. \begin{lstlisting}
  6451. (not False) and True
  6452. \end{lstlisting}
  6453. \fi}
  6454. \noindent produces a value of type \BOOLTY{}.
  6455. A second way to think about type checking is that it enforces a set of
  6456. rules about which operators can be applied to which kinds of
  6457. values. For example, our type checker for \LangIf{} signals an error
  6458. for the below expression {\if\edition\racketEd
  6459. \begin{lstlisting}
  6460. (not (+ 10 (- (+ 12 20))))
  6461. \end{lstlisting}
  6462. \fi}
  6463. {\if\edition\pythonEd
  6464. \begin{lstlisting}
  6465. not (10 + -(12 + 20))
  6466. \end{lstlisting}
  6467. \fi}
  6468. \noindent The subexpression
  6469. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6470. \python{\code{(10 + -(12 + 20))}}
  6471. has type \INTTY{} but the type checker enforces the rule that the
  6472. argument of \code{not} must be an expression of type \BOOLTY{}.
  6473. We implement type checking using classes and methods because they
  6474. provide the open recursion needed to reuse code as we extend the type
  6475. checker in later chapters, analogous to the use of classes and methods
  6476. for the interpreters (Section~\ref{sec:extensible-interp}).
  6477. We separate the type checker for the \LangVar{} subset into its own
  6478. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6479. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6480. from the type checker for \LangVar{}. These type checkers are in the
  6481. files
  6482. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6483. and
  6484. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6485. of the support code.
  6486. %
  6487. Each type checker is a structurally recursive function over the AST.
  6488. Given an input expression \code{e}, the type checker either signals an
  6489. error or returns \racket{an expression and} its type.
  6490. %
  6491. \racket{It returns an expression because there are situations in which
  6492. we want to change or update the expression.}
  6493. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6494. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6495. \INTTY{}. To handle variables, the type checker uses the environment
  6496. \code{env} to map variables to types.
  6497. %
  6498. \racket{Consider the case for \key{let}. We type check the
  6499. initializing expression to obtain its type \key{T} and then
  6500. associate type \code{T} with the variable \code{x} in the
  6501. environment used to type check the body of the \key{let}. Thus,
  6502. when the type checker encounters a use of variable \code{x}, it can
  6503. find its type in the environment.}
  6504. %
  6505. \python{Consider the case for assignment. We type check the
  6506. initializing expression to obtain its type \key{t}. If the variable
  6507. \code{lhs.id} is already in the environment because there was a
  6508. prior assignment, we check that this initializer has the same type
  6509. as the prior one. If this is the first assignment to the variable,
  6510. we associate type \code{t} with the variable \code{lhs.id} in the
  6511. environment. Thus, when the type checker encounters a use of
  6512. variable \code{x}, it can find its type in the environment.}
  6513. %
  6514. \racket{Regarding primitive operators, we recursively analyze the
  6515. arguments and then invoke \code{type\_check\_op} to check whether
  6516. the argument types are allowed.}
  6517. %
  6518. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6519. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6520. \racket{Several auxiliary methods are used in the type checker. The
  6521. method \code{operator-types} defines a dictionary that maps the
  6522. operator names to their parameter and return types. The
  6523. \code{type-equal?} method determines whether two types are equal,
  6524. which for now simply dispatches to \code{equal?} (deep
  6525. equality). The \code{check-type-equal?} method triggers an error if
  6526. the two types are not equal. The \code{type-check-op} method looks
  6527. up the operator in the \code{operator-types} dictionary and then
  6528. checks whether the argument types are equal to the parameter types.
  6529. The result is the return type of the operator.}
  6530. %
  6531. \python{The auxiliary method \code{check\_type\_equal} triggers
  6532. an error if the two types are not equal.}
  6533. \begin{figure}[tbp]
  6534. \begin{tcolorbox}[colback=white]
  6535. {\if\edition\racketEd
  6536. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6537. (define type-check-Lvar-class
  6538. (class object%
  6539. (super-new)
  6540. (define/public (operator-types)
  6541. '((+ . ((Integer Integer) . Integer))
  6542. (- . ((Integer Integer) . Integer))
  6543. (read . (() . Integer))))
  6544. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6545. (define/public (check-type-equal? t1 t2 e)
  6546. (unless (type-equal? t1 t2)
  6547. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6548. (define/public (type-check-op op arg-types e)
  6549. (match (dict-ref (operator-types) op)
  6550. [`(,param-types . ,return-type)
  6551. (for ([at arg-types] [pt param-types])
  6552. (check-type-equal? at pt e))
  6553. return-type]
  6554. [else (error 'type-check-op "unrecognized ~a" op)]))
  6555. (define/public (type-check-exp env)
  6556. (lambda (e)
  6557. (match e
  6558. [(Int n) (values (Int n) 'Integer)]
  6559. [(Var x) (values (Var x) (dict-ref env x))]
  6560. [(Let x e body)
  6561. (define-values (e^ Te) ((type-check-exp env) e))
  6562. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6563. (values (Let x e^ b) Tb)]
  6564. [(Prim op es)
  6565. (define-values (new-es ts)
  6566. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6567. (values (Prim op new-es) (type-check-op op ts e))]
  6568. [else (error 'type-check-exp "couldn't match" e)])))
  6569. (define/public (type-check-program e)
  6570. (match e
  6571. [(Program info body)
  6572. (define-values (body^ Tb) ((type-check-exp '()) body))
  6573. (check-type-equal? Tb 'Integer body)
  6574. (Program info body^)]
  6575. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6576. ))
  6577. (define (type-check-Lvar p)
  6578. (send (new type-check-Lvar-class) type-check-program p))
  6579. \end{lstlisting}
  6580. \fi}
  6581. {\if\edition\pythonEd
  6582. \begin{lstlisting}[escapechar=`]
  6583. class TypeCheckLvar:
  6584. def check_type_equal(self, t1, t2, e):
  6585. if t1 != t2:
  6586. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6587. raise Exception(msg)
  6588. def type_check_exp(self, e, env):
  6589. match e:
  6590. case BinOp(left, (Add() | Sub()), right):
  6591. l = self.type_check_exp(left, env)
  6592. check_type_equal(l, int, left)
  6593. r = self.type_check_exp(right, env)
  6594. check_type_equal(r, int, right)
  6595. return int
  6596. case UnaryOp(USub(), v):
  6597. t = self.type_check_exp(v, env)
  6598. check_type_equal(t, int, v)
  6599. return int
  6600. case Name(id):
  6601. return env[id]
  6602. case Constant(value) if isinstance(value, int):
  6603. return int
  6604. case Call(Name('input_int'), []):
  6605. return int
  6606. def type_check_stmts(self, ss, env):
  6607. if len(ss) == 0:
  6608. return
  6609. match ss[0]:
  6610. case Assign([lhs], value):
  6611. t = self.type_check_exp(value, env)
  6612. if lhs.id in env:
  6613. check_type_equal(env[lhs.id], t, value)
  6614. else:
  6615. env[lhs.id] = t
  6616. return self.type_check_stmts(ss[1:], env)
  6617. case Expr(Call(Name('print'), [arg])):
  6618. t = self.type_check_exp(arg, env)
  6619. check_type_equal(t, int, arg)
  6620. return self.type_check_stmts(ss[1:], env)
  6621. case Expr(value):
  6622. self.type_check_exp(value, env)
  6623. return self.type_check_stmts(ss[1:], env)
  6624. def type_check_P(self, p):
  6625. match p:
  6626. case Module(body):
  6627. self.type_check_stmts(body, {})
  6628. \end{lstlisting}
  6629. \fi}
  6630. \end{tcolorbox}
  6631. \caption{Type checker for the \LangVar{} language.}
  6632. \label{fig:type-check-Lvar}
  6633. \end{figure}
  6634. \begin{figure}[tbp]
  6635. \begin{tcolorbox}[colback=white]
  6636. {\if\edition\racketEd
  6637. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6638. (define type-check-Lif-class
  6639. (class type-check-Lvar-class
  6640. (super-new)
  6641. (inherit check-type-equal?)
  6642. (define/override (operator-types)
  6643. (append '((and . ((Boolean Boolean) . Boolean))
  6644. (or . ((Boolean Boolean) . Boolean))
  6645. (< . ((Integer Integer) . Boolean))
  6646. (<= . ((Integer Integer) . Boolean))
  6647. (> . ((Integer Integer) . Boolean))
  6648. (>= . ((Integer Integer) . Boolean))
  6649. (not . ((Boolean) . Boolean)))
  6650. (super operator-types)))
  6651. (define/override (type-check-exp env)
  6652. (lambda (e)
  6653. (match e
  6654. [(Bool b) (values (Bool b) 'Boolean)]
  6655. [(Prim 'eq? (list e1 e2))
  6656. (define-values (e1^ T1) ((type-check-exp env) e1))
  6657. (define-values (e2^ T2) ((type-check-exp env) e2))
  6658. (check-type-equal? T1 T2 e)
  6659. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6660. [(If cnd thn els)
  6661. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6662. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6663. (define-values (els^ Te) ((type-check-exp env) els))
  6664. (check-type-equal? Tc 'Boolean e)
  6665. (check-type-equal? Tt Te e)
  6666. (values (If cnd^ thn^ els^) Te)]
  6667. [else ((super type-check-exp env) e)])))
  6668. ))
  6669. (define (type-check-Lif p)
  6670. (send (new type-check-Lif-class) type-check-program p))
  6671. \end{lstlisting}
  6672. \fi}
  6673. {\if\edition\pythonEd
  6674. \begin{lstlisting}
  6675. class TypeCheckLif(TypeCheckLvar):
  6676. def type_check_exp(self, e, env):
  6677. match e:
  6678. case Constant(value) if isinstance(value, bool):
  6679. return bool
  6680. case BinOp(left, Sub(), right):
  6681. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6682. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6683. return int
  6684. case UnaryOp(Not(), v):
  6685. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6686. return bool
  6687. case BoolOp(op, values):
  6688. left = values[0] ; right = values[1]
  6689. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6690. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6691. return bool
  6692. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6693. or isinstance(cmp, NotEq):
  6694. l = self.type_check_exp(left, env)
  6695. r = self.type_check_exp(right, env)
  6696. check_type_equal(l, r, e)
  6697. return bool
  6698. case Compare(left, [cmp], [right]):
  6699. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6700. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6701. return bool
  6702. case IfExp(test, body, orelse):
  6703. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6704. b = self.type_check_exp(body, env)
  6705. o = self.type_check_exp(orelse, env)
  6706. check_type_equal(b, o, e)
  6707. return b
  6708. case _:
  6709. return super().type_check_exp(e, env)
  6710. def type_check_stmts(self, ss, env):
  6711. if len(ss) == 0:
  6712. return
  6713. match ss[0]:
  6714. case If(test, body, orelse):
  6715. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6716. b = self.type_check_stmts(body, env)
  6717. o = self.type_check_stmts(orelse, env)
  6718. check_type_equal(b, o, ss[0])
  6719. return self.type_check_stmts(ss[1:], env)
  6720. case _:
  6721. return super().type_check_stmts(ss, env)
  6722. \end{lstlisting}
  6723. \fi}
  6724. \end{tcolorbox}
  6725. \caption{Type checker for the \LangIf{} language.}
  6726. \label{fig:type-check-Lif}
  6727. \end{figure}
  6728. The type checker for \LangIf{} is defined in
  6729. Figure~\ref{fig:type-check-Lif}.
  6730. %
  6731. The type of a Boolean constant is \BOOLTY{}.
  6732. %
  6733. \racket{The \code{operator-types} function adds dictionary entries for
  6734. the new operators.}
  6735. %
  6736. \python{Logical not requires its argument to be a \BOOLTY{} and
  6737. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6738. %
  6739. The equality operator requires the two arguments to have the same type
  6740. and therefore we handle it separately from the other operators.
  6741. %
  6742. \python{The other comparisons (less-than, etc.) require their
  6743. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6744. %
  6745. The condition of an \code{if} must
  6746. be of \BOOLTY{} type and the two branches must have the same type.
  6747. \begin{exercise}\normalfont\normalsize
  6748. Create 10 new test programs in \LangIf{}. Half of the programs should
  6749. have a type error. For those programs, create an empty file with the
  6750. same base name but with file extension \code{.tyerr}. For example, if
  6751. the test
  6752. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6753. is expected to error, then create
  6754. an empty file named \code{cond\_test\_14.tyerr}.
  6755. %
  6756. \racket{This indicates to \code{interp-tests} and
  6757. \code{compiler-tests} that a type error is expected. }
  6758. %
  6759. The other half of the test programs should not have type errors.
  6760. %
  6761. \racket{In the \code{run-tests.rkt} script, change the second argument
  6762. of \code{interp-tests} and \code{compiler-tests} to
  6763. \code{type-check-Lif}, which causes the type checker to run prior to
  6764. the compiler passes. Temporarily change the \code{passes} to an
  6765. empty list and run the script, thereby checking that the new test
  6766. programs either type check or not as intended.}
  6767. %
  6768. Run the test script to check that these test programs type check as
  6769. expected.
  6770. \end{exercise}
  6771. \clearpage
  6772. \section{The \LangCIf{} Intermediate Language}
  6773. \label{sec:Cif}
  6774. {\if\edition\racketEd
  6775. %
  6776. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  6777. comparison operators to the \Exp{} non-terminal and the literals
  6778. \TRUE{} and \FALSE{} to the \Arg{} non-terminal. Regarding control
  6779. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  6780. \Tail{} non-terminal. The condition of an \code{if} statement is a
  6781. comparison operation and the branches are \code{goto} statements,
  6782. making it straightforward to compile \code{if} statements to x86. The
  6783. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  6784. expressions. A \code{goto} statement transfers control to the $\Tail$
  6785. expression corresponding to its label.
  6786. %
  6787. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6788. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6789. defines its abstract syntax.
  6790. %
  6791. \fi}
  6792. %
  6793. {\if\edition\pythonEd
  6794. %
  6795. The output of \key{explicate\_control} is a language similar to the
  6796. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6797. \code{goto} statements, so we name it \LangCIf{}.
  6798. %
  6799. The \LangCIf{} language supports the same operators as \LangIf{} but
  6800. the arguments of operators are restricted to atomic expressions. The
  6801. \LangCIf{} language does not include \code{if} expressions but it does
  6802. include a restricted form of \code{if} statement. The condition must be
  6803. a comparison and the two branches may only contain \code{goto}
  6804. statements. These restrictions make it easier to translate \code{if}
  6805. statements to x86. The \LangCIf{} language also adds a \code{return}
  6806. statement to finish the program with a specified value.
  6807. %
  6808. The \key{CProgram} construct contains a dictionary mapping labels to
  6809. lists of statements that end with a \code{return} statement, a
  6810. \code{goto}, or a conditional \code{goto}.
  6811. %% Statement lists of this
  6812. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  6813. %% is a control transfer at the end and control only enters at the
  6814. %% beginning of the list, which is marked by the label.
  6815. %
  6816. A \code{goto} statement transfers control to the sequence of statements
  6817. associated with its label.
  6818. %
  6819. The concrete syntax for \LangCIf{} is defined in
  6820. Figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  6821. in Figure~\ref{fig:c1-syntax}.
  6822. %
  6823. \fi}
  6824. %
  6825. \newcommand{\CifGrammarRacket}{
  6826. \begin{array}{lcl}
  6827. \Atm &::=& \itm{bool} \\
  6828. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6829. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6830. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6831. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6832. \end{array}
  6833. }
  6834. \newcommand{\CifASTRacket}{
  6835. \begin{array}{lcl}
  6836. \Atm &::=& \BOOL{\itm{bool}} \\
  6837. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6838. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6839. \Tail &::= & \GOTO{\itm{label}} \\
  6840. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6841. \end{array}
  6842. }
  6843. \newcommand{\CifGrammarPython}{
  6844. \begin{array}{lcl}
  6845. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6846. \Exp &::= & \Atm \MID \CREAD{}
  6847. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6848. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6849. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6850. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  6851. &\MID& \CASSIGN{\Var}{\Exp}
  6852. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6853. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6854. \end{array}
  6855. }
  6856. \newcommand{\CifASTPython}{
  6857. \begin{array}{lcl}
  6858. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6859. \Exp &::= & \Atm \MID \READ{} \\
  6860. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6861. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6862. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6863. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6864. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6865. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6866. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6867. \end{array}
  6868. }
  6869. \begin{figure}[tbp]
  6870. \begin{tcolorbox}[colback=white]
  6871. \small
  6872. {\if\edition\racketEd
  6873. \[
  6874. \begin{array}{l}
  6875. \gray{\CvarGrammarRacket} \\ \hline
  6876. \CifGrammarRacket \\
  6877. \begin{array}{lcl}
  6878. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6879. \end{array}
  6880. \end{array}
  6881. \]
  6882. \fi}
  6883. {\if\edition\pythonEd
  6884. \[
  6885. \begin{array}{l}
  6886. \CifGrammarPython \\
  6887. \begin{array}{lcl}
  6888. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6889. \end{array}
  6890. \end{array}
  6891. \]
  6892. \fi}
  6893. \end{tcolorbox}
  6894. \caption{The concrete syntax of the \LangCIf{} intermediate language,
  6895. an extension of \LangCVar{} (Figure~\ref{fig:c0-concrete-syntax}).}
  6896. \label{fig:c1-concrete-syntax}
  6897. \end{figure}
  6898. \begin{figure}[tp]
  6899. \begin{tcolorbox}[colback=white]
  6900. \small
  6901. {\if\edition\racketEd
  6902. \[
  6903. \begin{array}{l}
  6904. \gray{\CvarASTRacket} \\ \hline
  6905. \CifASTRacket \\
  6906. \begin{array}{lcl}
  6907. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6908. \end{array}
  6909. \end{array}
  6910. \]
  6911. \fi}
  6912. {\if\edition\pythonEd
  6913. \[
  6914. \begin{array}{l}
  6915. \CifASTPython \\
  6916. \begin{array}{lcl}
  6917. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6918. \end{array}
  6919. \end{array}
  6920. \]
  6921. \fi}
  6922. \end{tcolorbox}
  6923. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6924. (Figure~\ref{fig:c0-syntax})}.}
  6925. \label{fig:c1-syntax}
  6926. \end{figure}
  6927. \section{The \LangXIf{} Language}
  6928. \label{sec:x86-if}
  6929. \index{subject}{x86} To implement the new logical operations, the
  6930. comparison operations, and the \key{if} expression\python{ and
  6931. statement}, we delve further into the x86
  6932. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  6933. the concrete and abstract syntax for the \LangXIf{} subset of x86,
  6934. which includes instructions for logical operations, comparisons, and
  6935. \racket{conditional} jumps.
  6936. %
  6937. \python{The abstract syntax for an \LangXIf{} program contains a
  6938. dictionary mapping labels to sequences of instructions, each of
  6939. which we refer to as a \emph{basic block}\index{subject}{basic
  6940. block}.}
  6941. One challenge is that x86 does not provide an instruction that
  6942. directly implements logical negation (\code{not} in \LangIf{} and
  6943. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6944. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6945. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6946. bit of its arguments, and writes the results into its second argument.
  6947. Recall the truth table for exclusive-or:
  6948. \begin{center}
  6949. \begin{tabular}{l|cc}
  6950. & 0 & 1 \\ \hline
  6951. 0 & 0 & 1 \\
  6952. 1 & 1 & 0
  6953. \end{tabular}
  6954. \end{center}
  6955. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6956. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6957. for the bit $1$, the result is the opposite of the second bit. Thus,
  6958. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6959. the first argument as follows, where $\Arg$ is the translation of
  6960. $\Atm$ to x86.
  6961. \[
  6962. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6963. \qquad\Rightarrow\qquad
  6964. \begin{array}{l}
  6965. \key{movq}~ \Arg\key{,} \Var\\
  6966. \key{xorq}~ \key{\$1,} \Var
  6967. \end{array}
  6968. \]
  6969. \newcommand{\GrammarXIf}{
  6970. \begin{array}{lcl}
  6971. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6972. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6973. \Arg &::=& \key{\%}\itm{bytereg}\\
  6974. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6975. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  6976. \MID \key{cmpq}~\Arg\key{,}~\Arg
  6977. \MID \key{set}cc~\Arg
  6978. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  6979. &\MID& \key{j}cc~\itm{label} \\
  6980. \end{array}
  6981. }
  6982. \begin{figure}[tp]
  6983. \begin{tcolorbox}[colback=white]
  6984. \[
  6985. \begin{array}{l}
  6986. \gray{\GrammarXInt} \\ \hline
  6987. \GrammarXIf \\
  6988. \begin{array}{lcl}
  6989. \LangXIfM{} &::= & \key{.globl main} \\
  6990. & & \key{main:} \; \Instr\ldots
  6991. \end{array}
  6992. \end{array}
  6993. \]
  6994. \end{tcolorbox}
  6995. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6996. \label{fig:x86-1-concrete}
  6997. \end{figure}
  6998. \newcommand{\ASTXIfRacket}{
  6999. \begin{array}{lcl}
  7000. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7001. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7002. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7003. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7004. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7005. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7006. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7007. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7008. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7009. \end{array}
  7010. }
  7011. \begin{figure}[tp]
  7012. \begin{tcolorbox}[colback=white]
  7013. \small
  7014. {\if\edition\racketEd
  7015. \[\arraycolsep=3pt
  7016. \begin{array}{l}
  7017. \gray{\ASTXIntRacket} \\ \hline
  7018. \ASTXIfRacket \\
  7019. \begin{array}{lcl}
  7020. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7021. \end{array}
  7022. \end{array}
  7023. \]
  7024. \fi}
  7025. %
  7026. {\if\edition\pythonEd
  7027. \[
  7028. \begin{array}{lcl}
  7029. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7030. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7031. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7032. \MID \BYTEREG{\itm{bytereg}} \\
  7033. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7034. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7035. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7036. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7037. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7038. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7039. \MID \PUSHQ{\Arg}} \\
  7040. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7041. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7042. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7043. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7044. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7045. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7046. \Block &::= & \Instr^{+} \\
  7047. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7048. \end{array}
  7049. \]
  7050. \fi}
  7051. \end{tcolorbox}
  7052. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  7053. \label{fig:x86-1}
  7054. \end{figure}
  7055. Next we consider the x86 instructions that are relevant for compiling
  7056. the comparison operations. The \key{cmpq} instruction compares its two
  7057. arguments to determine whether one argument is less than, equal, or
  7058. greater than the other argument. The \key{cmpq} instruction is unusual
  7059. regarding the order of its arguments and where the result is
  7060. placed. The argument order is backwards: if you want to test whether
  7061. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7062. \key{cmpq} is placed in the special EFLAGS register. This register
  7063. cannot be accessed directly but it can be queried by a number of
  7064. instructions, including the \key{set} instruction. The instruction
  7065. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  7066. depending on whether the contents of the EFLAGS register matches the
  7067. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7068. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7069. The \key{set} instruction has a quirk in that its destination argument
  7070. must be single byte register, such as \code{al} (L for lower bits) or
  7071. \code{ah} (H for higher bits), which are part of the \code{rax}
  7072. register. Thankfully, the \key{movzbq} instruction can be used to
  7073. move from a single byte register to a normal 64-bit register. The
  7074. abstract syntax for the \code{set} instruction differs from the
  7075. concrete syntax in that it separates the instruction name from the
  7076. condition code.
  7077. \python{The x86 instructions for jumping are relevant to the
  7078. compilation of \key{if} expressions.}
  7079. %
  7080. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7081. counter to the address of the instruction after the specified
  7082. label.}
  7083. %
  7084. \racket{The x86 instruction for conditional jump is relevant to the
  7085. compilation of \key{if} expressions.}
  7086. %
  7087. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7088. counter to point to the instruction after \itm{label} depending on
  7089. whether the result in the EFLAGS register matches the condition code
  7090. \itm{cc}, otherwise the jump instruction falls through to the next
  7091. instruction. Like the abstract syntax for \code{set}, the abstract
  7092. syntax for conditional jump separates the instruction name from the
  7093. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7094. corresponds to \code{jle foo}. Because the conditional jump instruction
  7095. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7096. a \key{cmpq} instruction to set the EFLAGS register.
  7097. \section{Shrink the \LangIf{} Language}
  7098. \label{sec:shrink-Lif}
  7099. The \LangIf{} language includes several features that are easily
  7100. expressible with other features. For example, \code{and} and \code{or}
  7101. are expressible using \code{if} as follows.
  7102. \begin{align*}
  7103. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7104. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7105. \end{align*}
  7106. By performing these translations in the front-end of the compiler,
  7107. subsequent passes of the compiler do not need to deal with these features,
  7108. making the passes shorter.
  7109. On the other hand, sometimes translations reduce the efficiency of the
  7110. generated code by increasing the number of instructions. For example,
  7111. expressing subtraction in terms of negation
  7112. \[
  7113. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7114. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7115. \]
  7116. produces code with two x86 instructions (\code{negq} and \code{addq})
  7117. instead of just one (\code{subq}).
  7118. \begin{exercise}\normalfont\normalsize
  7119. %
  7120. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7121. the language by translating them to \code{if} expressions in \LangIf{}.
  7122. %
  7123. Create four test programs that involve these operators.
  7124. %
  7125. {\if\edition\racketEd
  7126. In the \code{run-tests.rkt} script, add the following entry for
  7127. \code{shrink} to the list of passes (it should be the only pass at
  7128. this point).
  7129. \begin{lstlisting}
  7130. (list "shrink" shrink interp_Lif type-check-Lif)
  7131. \end{lstlisting}
  7132. This instructs \code{interp-tests} to run the interpreter
  7133. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7134. output of \code{shrink}.
  7135. \fi}
  7136. %
  7137. Run the script to test your compiler on all the test programs.
  7138. \end{exercise}
  7139. {\if\edition\racketEd
  7140. \section{Uniquify Variables}
  7141. \label{sec:uniquify-Lif}
  7142. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7143. \code{if} expressions.
  7144. \begin{exercise}\normalfont\normalsize
  7145. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7146. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7147. \begin{lstlisting}
  7148. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7149. \end{lstlisting}
  7150. Run the script to test your compiler.
  7151. \end{exercise}
  7152. \fi}
  7153. \section{Remove Complex Operands}
  7154. \label{sec:remove-complex-opera-Lif}
  7155. The output language of \code{remove\_complex\_operands} is
  7156. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the monadic
  7157. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7158. but the \code{if} expression is not. All three sub-expressions of an
  7159. \code{if} are allowed to be complex expressions but the operands of
  7160. \code{not} and the comparisons must be atomic.
  7161. %
  7162. \python{We add a new language form, the \code{Begin} expression, to aid
  7163. in the translation of \code{if} expressions. When we recursively
  7164. process the two branches of the \code{if}, we generate temporary
  7165. variables and their initializing expressions. However, these
  7166. expressions may contain side effects and should only be executed
  7167. when the condition of the \code{if} is true (for the ``then''
  7168. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7169. a way to initialize the temporary variables within the two branches
  7170. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7171. form execute the statements $ss$ and then returns the result of
  7172. expression $e$.}
  7173. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7174. the new features in \LangIf{}. When recursively processing
  7175. subexpressions, recall that you should invoke \code{rco\_atom} when
  7176. the output needs to be an \Atm{} (as specified in the grammar for
  7177. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7178. \Exp{}. Regarding \code{if}, it is particularly important to
  7179. \textbf{not} replace its condition with a temporary variable because
  7180. that would interfere with the generation of high-quality output in the
  7181. upcoming \code{explicate\_control} pass.
  7182. \newcommand{\LifMonadASTRacket}{
  7183. \begin{array}{rcl}
  7184. \Atm &::=& \BOOL{\itm{bool}}\\
  7185. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7186. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7187. \MID \IF{\Exp}{\Exp}{\Exp}
  7188. \end{array}
  7189. }
  7190. \newcommand{\LifMonadASTPython}{
  7191. \begin{array}{rcl}
  7192. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7193. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7194. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7195. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7196. \Atm &::=& \BOOL{\itm{bool}}\\
  7197. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7198. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7199. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7200. \end{array}
  7201. }
  7202. \begin{figure}[tp]
  7203. \centering
  7204. \begin{tcolorbox}[colback=white]
  7205. {\if\edition\racketEd
  7206. \[
  7207. \begin{array}{l}
  7208. \gray{\LvarMonadASTRacket} \\ \hline
  7209. \LifMonadASTRacket \\
  7210. \begin{array}{rcl}
  7211. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7212. \end{array}
  7213. \end{array}
  7214. \]
  7215. \fi}
  7216. {\if\edition\pythonEd
  7217. \[
  7218. \begin{array}{l}
  7219. \gray{\LvarMonadASTPython} \\ \hline
  7220. \LifMonadASTPython \\
  7221. \begin{array}{rcl}
  7222. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7223. \end{array}
  7224. \end{array}
  7225. \]
  7226. \fi}
  7227. \end{tcolorbox}
  7228. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7229. (extends \LangVarANF in Figure~\ref{fig:Lvar-anf-syntax}).}
  7230. \label{fig:Lif-anf-syntax}
  7231. \end{figure}
  7232. \begin{exercise}\normalfont\normalsize
  7233. %
  7234. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7235. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7236. %
  7237. Create three new \LangIf{} programs that exercise the interesting
  7238. code in this pass.
  7239. %
  7240. {\if\edition\racketEd
  7241. In the \code{run-tests.rkt} script, add the following entry to the
  7242. list of \code{passes} and then run the script to test your compiler.
  7243. \begin{lstlisting}
  7244. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7245. \end{lstlisting}
  7246. \fi}
  7247. \end{exercise}
  7248. \section{Explicate Control}
  7249. \label{sec:explicate-control-Lif}
  7250. \racket{Recall that the purpose of \code{explicate\_control} is to
  7251. make the order of evaluation explicit in the syntax of the program.
  7252. With the addition of \key{if} this gets more interesting.}
  7253. %
  7254. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7255. %
  7256. The main challenge to overcome is that the condition of an \key{if}
  7257. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7258. condition must be a comparison.
  7259. As a motivating example, consider the following program that has an
  7260. \key{if} expression nested in the condition of another \key{if}.%
  7261. \python{\footnote{Programmers rarely write nested \code{if}
  7262. expressions, but it is not uncommon for the condition of an
  7263. \code{if} statement to be a call of a function that also contains an
  7264. \code{if} statement. When such a function is inlined, the result is
  7265. a nested \code{if} that requires the techniques discussed in this
  7266. section.}}
  7267. % cond_test_41.rkt, if_lt_eq.py
  7268. \begin{center}
  7269. \begin{minipage}{0.96\textwidth}
  7270. {\if\edition\racketEd
  7271. \begin{lstlisting}
  7272. (let ([x (read)])
  7273. (let ([y (read)])
  7274. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7275. (+ y 2)
  7276. (+ y 10))))
  7277. \end{lstlisting}
  7278. \fi}
  7279. {\if\edition\pythonEd
  7280. \begin{lstlisting}
  7281. x = input_int()
  7282. y = input_int()
  7283. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7284. \end{lstlisting}
  7285. \fi}
  7286. \end{minipage}
  7287. \end{center}
  7288. %
  7289. The naive way to compile \key{if} and the comparison operations would
  7290. be to handle each of them in isolation, regardless of their context.
  7291. Each comparison would be translated into a \key{cmpq} instruction
  7292. followed by several instructions to move the result from the EFLAGS
  7293. register into a general purpose register or stack location. Each
  7294. \key{if} would be translated into a \key{cmpq} instruction followed by
  7295. a conditional jump. The generated code for the inner \key{if} in the
  7296. above example would be as follows.
  7297. \begin{center}
  7298. \begin{minipage}{0.96\textwidth}
  7299. \begin{lstlisting}
  7300. cmpq $1, x
  7301. setl %al
  7302. movzbq %al, tmp
  7303. cmpq $1, tmp
  7304. je then_branch_1
  7305. jmp else_branch_1
  7306. \end{lstlisting}
  7307. \end{minipage}
  7308. \end{center}
  7309. Notice that the three instructions starting with \code{setl} are
  7310. redundant: the conditional jump could come immediately after the first
  7311. \code{cmpq}.
  7312. Our goal will be to compile \key{if} expressions so that the relevant
  7313. comparison instruction appears directly before the conditional jump.
  7314. For example, we want to generate the following code for the inner
  7315. \code{if}.
  7316. \begin{center}
  7317. \begin{minipage}{0.96\textwidth}
  7318. \begin{lstlisting}
  7319. cmpq $1, x
  7320. jl then_branch_1
  7321. jmp else_branch_1
  7322. \end{lstlisting}
  7323. \end{minipage}
  7324. \end{center}
  7325. One way to achieve this goal is to reorganize the code at the level of
  7326. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7327. the following code.
  7328. \begin{center}
  7329. \begin{minipage}{0.96\textwidth}
  7330. {\if\edition\racketEd
  7331. \begin{lstlisting}
  7332. (let ([x (read)])
  7333. (let ([y (read)])
  7334. (if (< x 1)
  7335. (if (eq? x 0)
  7336. (+ y 2)
  7337. (+ y 10))
  7338. (if (eq? x 2)
  7339. (+ y 2)
  7340. (+ y 10)))))
  7341. \end{lstlisting}
  7342. \fi}
  7343. {\if\edition\pythonEd
  7344. \begin{lstlisting}
  7345. x = input_int()
  7346. y = input_int()
  7347. print(((y + 2) if x == 0 else (y + 10)) \
  7348. if (x < 1) \
  7349. else ((y + 2) if (x == 2) else (y + 10)))
  7350. \end{lstlisting}
  7351. \fi}
  7352. \end{minipage}
  7353. \end{center}
  7354. Unfortunately, this approach duplicates the two branches from the
  7355. outer \code{if} and a compiler must never duplicate code! After all,
  7356. the two branches could be very large expressions.
  7357. How can we apply the above transformation but without duplicating
  7358. code? In other words, how can two different parts of a program refer
  7359. to one piece of code.
  7360. %
  7361. The answer is that we must move away from abstract syntax \emph{trees}
  7362. and instead use \emph{graphs}.
  7363. %
  7364. At the level of x86 assembly this is straightforward because we can
  7365. label the code for each branch and insert jumps in all the places that
  7366. need to execute the branch. In this way, jump instructions are edges
  7367. in the graph and the basic blocks are the nodes.
  7368. %
  7369. Likewise, our language \LangCIf{} provides the ability to label a
  7370. sequence of statements and to jump to a label via \code{goto}.
  7371. As a preview of what \code{explicate\_control} will do,
  7372. Figure~\ref{fig:explicate-control-s1-38} shows the output of
  7373. \code{explicate\_control} on the above example. Note how the condition
  7374. of every \code{if} is a comparison operation and that we have not
  7375. duplicated any code, but instead used labels and \code{goto} to enable
  7376. sharing of code.
  7377. \begin{figure}[tbp]
  7378. \begin{tcolorbox}[colback=white]
  7379. {\if\edition\racketEd
  7380. \begin{tabular}{lll}
  7381. \begin{minipage}{0.4\textwidth}
  7382. % cond_test_41.rkt
  7383. \begin{lstlisting}
  7384. (let ([x (read)])
  7385. (let ([y (read)])
  7386. (if (if (< x 1)
  7387. (eq? x 0)
  7388. (eq? x 2))
  7389. (+ y 2)
  7390. (+ y 10))))
  7391. \end{lstlisting}
  7392. \end{minipage}
  7393. &
  7394. $\Rightarrow$
  7395. &
  7396. \begin{minipage}{0.55\textwidth}
  7397. \begin{lstlisting}
  7398. start:
  7399. x = (read);
  7400. y = (read);
  7401. if (< x 1)
  7402. goto block_4;
  7403. else
  7404. goto block_5;
  7405. block_4:
  7406. if (eq? x 0)
  7407. goto block_2;
  7408. else
  7409. goto block_3;
  7410. block_5:
  7411. if (eq? x 2)
  7412. goto block_2;
  7413. else
  7414. goto block_3;
  7415. block_2:
  7416. return (+ y 2);
  7417. block_3:
  7418. return (+ y 10);
  7419. \end{lstlisting}
  7420. \end{minipage}
  7421. \end{tabular}
  7422. \fi}
  7423. {\if\edition\pythonEd
  7424. \begin{tabular}{lll}
  7425. \begin{minipage}{0.4\textwidth}
  7426. % cond_test_41.rkt
  7427. \begin{lstlisting}
  7428. x = input_int()
  7429. y = input_int()
  7430. print(y + 2 \
  7431. if (x == 0 \
  7432. if x < 1 \
  7433. else x == 2) \
  7434. else y + 10)
  7435. \end{lstlisting}
  7436. \end{minipage}
  7437. &
  7438. $\Rightarrow$
  7439. &
  7440. \begin{minipage}{0.55\textwidth}
  7441. \begin{lstlisting}
  7442. start:
  7443. x = input_int()
  7444. y = input_int()
  7445. if x < 1:
  7446. goto block_8
  7447. else:
  7448. goto block_9
  7449. block_8:
  7450. if x == 0:
  7451. goto block_4
  7452. else:
  7453. goto block_5
  7454. block_9:
  7455. if x == 2:
  7456. goto block_6
  7457. else:
  7458. goto block_7
  7459. block_4:
  7460. goto block_2
  7461. block_5:
  7462. goto block_3
  7463. block_6:
  7464. goto block_2
  7465. block_7:
  7466. goto block_3
  7467. block_2:
  7468. tmp_0 = y + 2
  7469. goto block_1
  7470. block_3:
  7471. tmp_0 = y + 10
  7472. goto block_1
  7473. block_1:
  7474. print(tmp_0)
  7475. return 0
  7476. \end{lstlisting}
  7477. \end{minipage}
  7478. \end{tabular}
  7479. \fi}
  7480. \end{tcolorbox}
  7481. \caption{Translation from \LangIf{} to \LangCIf{}
  7482. via the \code{explicate\_control}.}
  7483. \label{fig:explicate-control-s1-38}
  7484. \end{figure}
  7485. {\if\edition\racketEd
  7486. %
  7487. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7488. \code{explicate\_control} for \LangVar{} using two recursive
  7489. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7490. former function translates expressions in tail position whereas the
  7491. later function translates expressions on the right-hand-side of a
  7492. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  7493. have a new kind of position to deal with: the predicate position of
  7494. the \key{if}. We need another function, \code{explicate\_pred}, that
  7495. decides how to compile an \key{if} by analyzing its condition. So
  7496. \code{explicate\_pred} takes an \LangIf{} expression and two
  7497. \LangCIf{} tails for the then-branch and else-branch and outputs a
  7498. tail. In the following paragraphs we discuss specific cases in the
  7499. \code{explicate\_tail}, \code{explicate\_assign}, and
  7500. \code{explicate\_pred} functions.
  7501. %
  7502. \fi}
  7503. %
  7504. {\if\edition\pythonEd
  7505. %
  7506. We recommend implementing \code{explicate\_control} using the
  7507. following four auxiliary functions.
  7508. \begin{description}
  7509. \item[\code{explicate\_effect}] generates code for expressions as
  7510. statements, so their result is ignored and only their side effects
  7511. matter.
  7512. \item[\code{explicate\_assign}] generates code for expressions
  7513. on the right-hand side of an assignment.
  7514. \item[\code{explicate\_pred}] generates code for an \code{if}
  7515. expression or statement by analyzing the condition expression.
  7516. \item[\code{explicate\_stmt}] generates code for statements.
  7517. \end{description}
  7518. These four functions should build the dictionary of basic blocks. The
  7519. following auxiliary function can be used to create a new basic block
  7520. from a list of statements. It returns a \code{goto} statement that
  7521. jumps to the new basic block.
  7522. \begin{center}
  7523. \begin{minipage}{\textwidth}
  7524. \begin{lstlisting}
  7525. def create_block(stmts, basic_blocks):
  7526. label = label_name(generate_name('block'))
  7527. basic_blocks[label] = stmts
  7528. return Goto(label)
  7529. \end{lstlisting}
  7530. \end{minipage}
  7531. \end{center}
  7532. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7533. \code{explicate\_control} pass.
  7534. The \code{explicate\_effect} function has three parameters: 1) the
  7535. expression to be compiled, 2) the already-compiled code for this
  7536. expression's \emph{continuation}, that is, the list of statements that
  7537. should execute after this expression, and 3) the dictionary of
  7538. generated basic blocks. The \code{explicate\_effect} function returns
  7539. a list of \LangCIf{} statements and it may add to the dictionary of
  7540. basic blocks.
  7541. %
  7542. Let's consider a few of the cases for the expression to be compiled.
  7543. If the expression to be compiled is a constant, then it can be
  7544. discarded because it has no side effects. If it's a \CREAD{}, then it
  7545. has a side-effect and should be preserved. So the expression should be
  7546. translated into a statement using the \code{Expr} AST class. If the
  7547. expression to be compiled is an \code{if} expression, we translate the
  7548. two branches using \code{explicate\_effect} and then translate the
  7549. condition expression using \code{explicate\_pred}, which generates
  7550. code for the entire \code{if}.
  7551. The \code{explicate\_assign} function has four parameters: 1) the
  7552. right-hand-side of the assignment, 2) the left-hand-side of the
  7553. assignment (the variable), 3) the continuation, and 4) the dictionary
  7554. of basic blocks. The \code{explicate\_assign} function returns a list
  7555. of \LangCIf{} statements and it may add to the dictionary of basic
  7556. blocks.
  7557. When the right-hand-side is an \code{if} expression, there is some
  7558. work to do. In particular, the two branches should be translated using
  7559. \code{explicate\_assign} and the condition expression should be
  7560. translated using \code{explicate\_pred}. Otherwise we can simply
  7561. generate an assignment statement, with the given left and right-hand
  7562. sides, concatenated with its continuation.
  7563. \begin{figure}[tbp]
  7564. \begin{tcolorbox}[colback=white]
  7565. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7566. def explicate_effect(e, cont, basic_blocks):
  7567. match e:
  7568. case IfExp(test, body, orelse):
  7569. ...
  7570. case Call(func, args):
  7571. ...
  7572. case Begin(body, result):
  7573. ...
  7574. case _:
  7575. ...
  7576. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7577. match rhs:
  7578. case IfExp(test, body, orelse):
  7579. ...
  7580. case Begin(body, result):
  7581. ...
  7582. case _:
  7583. return [Assign([lhs], rhs)] + cont
  7584. def explicate_pred(cnd, thn, els, basic_blocks):
  7585. match cnd:
  7586. case Compare(left, [op], [right]):
  7587. goto_thn = create_block(thn, basic_blocks)
  7588. goto_els = create_block(els, basic_blocks)
  7589. return [If(cnd, [goto_thn], [goto_els])]
  7590. case Constant(True):
  7591. return thn;
  7592. case Constant(False):
  7593. return els;
  7594. case UnaryOp(Not(), operand):
  7595. ...
  7596. case IfExp(test, body, orelse):
  7597. ...
  7598. case Begin(body, result):
  7599. ...
  7600. case _:
  7601. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7602. [create_block(els, basic_blocks)],
  7603. [create_block(thn, basic_blocks)])]
  7604. def explicate_stmt(s, cont, basic_blocks):
  7605. match s:
  7606. case Assign([lhs], rhs):
  7607. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7608. case Expr(value):
  7609. return explicate_effect(value, cont, basic_blocks)
  7610. case If(test, body, orelse):
  7611. ...
  7612. def explicate_control(p):
  7613. match p:
  7614. case Module(body):
  7615. new_body = [Return(Constant(0))]
  7616. basic_blocks = {}
  7617. for s in reversed(body):
  7618. new_body = explicate_stmt(s, new_body, basic_blocks)
  7619. basic_blocks[label_name('start')] = new_body
  7620. return CProgram(basic_blocks)
  7621. \end{lstlisting}
  7622. \end{tcolorbox}
  7623. \caption{Skeleton for the \code{explicate\_control} pass.}
  7624. \label{fig:explicate-control-Lif}
  7625. \end{figure}
  7626. \fi}
  7627. {\if\edition\racketEd
  7628. \subsection{Explicate Tail and Assign}
  7629. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7630. additional cases for Boolean constants and \key{if}. The cases for
  7631. \code{if} should recursively compile the two branches using either
  7632. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7633. cases should then invoke \code{explicate\_pred} on the condition
  7634. expression, passing in the generated code for the two branches. For
  7635. example, consider the following program with an \code{if} in tail
  7636. position.
  7637. % cond_test_6.rkt
  7638. \begin{lstlisting}
  7639. (let ([x (read)])
  7640. (if (eq? x 0) 42 777))
  7641. \end{lstlisting}
  7642. The two branches are recursively compiled to return statements. We
  7643. then delegate to \code{explicate\_pred}, passing the condition
  7644. \code{(eq? x 0)} and the two return statements. We return to this
  7645. example shortly when we discuss \code{explicate\_pred}.
  7646. Next let us consider a program with an \code{if} on the right-hand
  7647. side of a \code{let}.
  7648. \begin{lstlisting}
  7649. (let ([y (read)])
  7650. (let ([x (if (eq? y 0) 40 777)])
  7651. (+ x 2)))
  7652. \end{lstlisting}
  7653. Note that the body of the inner \code{let} will have already been
  7654. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7655. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7656. to recursively process both branches of the \code{if}, and we do not
  7657. want to duplicate code, so we generate the following block using an
  7658. auxiliary function named \code{create\_block} that we discuss below.
  7659. \begin{lstlisting}
  7660. block_6:
  7661. return (+ x 2)
  7662. \end{lstlisting}
  7663. We then use \code{goto block\_6;} as the \code{cont} argument for
  7664. compiling the branches. So the two branches compile to
  7665. \begin{center}
  7666. \begin{minipage}{0.2\textwidth}
  7667. \begin{lstlisting}
  7668. x = 40;
  7669. goto block_6;
  7670. \end{lstlisting}
  7671. \end{minipage}
  7672. \hspace{0.5in} and \hspace{0.5in}
  7673. \begin{minipage}{0.2\textwidth}
  7674. \begin{lstlisting}
  7675. x = 777;
  7676. goto block_6;
  7677. \end{lstlisting}
  7678. \end{minipage}
  7679. \end{center}
  7680. Finally, we delegate to \code{explicate\_pred}, passing the condition
  7681. \code{(eq? y 0)} and the above code for the branches.
  7682. \subsection{Create Block}
  7683. We recommend implementing the \code{create\_block} auxiliary function
  7684. as follows, using a global variable \code{basic-blocks} to store a
  7685. dictionary that maps labels to $\Tail$ expressions. The main idea is
  7686. that \code{create\_block} generates a new label and then associates
  7687. the given \code{tail} with the new label in the \code{basic-blocks}
  7688. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  7689. new label. However, if the given \code{tail} is already a \code{Goto},
  7690. then there is no need to generate a new label and entry in
  7691. \code{basic-blocks}; we can simply return that \code{Goto}.
  7692. %
  7693. \begin{lstlisting}
  7694. (define (create_block tail)
  7695. (match tail
  7696. [(Goto label) (Goto label)]
  7697. [else
  7698. (let ([label (gensym 'block)])
  7699. (set! basic-blocks (cons (cons label tail) basic-blocks))
  7700. (Goto label))]))
  7701. \end{lstlisting}
  7702. \fi}
  7703. {\if\edition\racketEd
  7704. \subsection{Explicate Predicate}
  7705. \begin{figure}[tbp]
  7706. \begin{tcolorbox}[colback=white]
  7707. \begin{lstlisting}
  7708. (define (explicate_pred cnd thn els)
  7709. (match cnd
  7710. [(Var x) ___]
  7711. [(Let x rhs body) ___]
  7712. [(Prim 'not (list e)) ___]
  7713. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7714. (IfStmt (Prim op es) (create_block thn)
  7715. (create_block els))]
  7716. [(Bool b) (if b thn els)]
  7717. [(If cnd^ thn^ els^) ___]
  7718. [else (error "explicate_pred unhandled case" cnd)]))
  7719. \end{lstlisting}
  7720. \end{tcolorbox}
  7721. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7722. \label{fig:explicate-pred}
  7723. \end{figure}
  7724. \fi}
  7725. \racket{The skeleton for the \code{explicate\_pred} function is given
  7726. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7727. 1) \code{cnd}, the condition expression of the \code{if},
  7728. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7729. and 3) \code{els}, the code generated by
  7730. explicate for the ``else'' branch. The \code{explicate\_pred}
  7731. function should match on \code{cnd} with a case for
  7732. every kind of expression that can have type \BOOLTY{}.}
  7733. %
  7734. \python{The \code{explicate\_pred} function has four parameters: 1)
  7735. the condition expression, 2) the generated statements for the
  7736. ``then'' branch, 3) the generated statements for the ``else''
  7737. branch, and 4) the dictionary of basic blocks. The
  7738. \code{explicate\_pred} function returns a list of \LangCIf{}
  7739. statements and it may add to the dictionary of basic blocks.}
  7740. Consider the case for comparison operators. We translate the
  7741. comparison to an \code{if} statement whose branches are \code{goto}
  7742. statements created by applying \code{create\_block} to the code
  7743. generated for the \code{thn} and \code{els} branches. Let us
  7744. illustrate this translation by returning to the program with an
  7745. \code{if} expression in tail position, shown again below. We invoke
  7746. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  7747. \python{\code{x == 0}}.
  7748. %
  7749. {\if\edition\racketEd
  7750. \begin{lstlisting}
  7751. (let ([x (read)])
  7752. (if (eq? x 0) 42 777))
  7753. \end{lstlisting}
  7754. \fi}
  7755. %
  7756. {\if\edition\pythonEd
  7757. \begin{lstlisting}
  7758. x = input_int()
  7759. 42 if x == 0 else 777
  7760. \end{lstlisting}
  7761. \fi}
  7762. %
  7763. \noindent The two branches \code{42} and \code{777} were already
  7764. compiled to \code{return} statements, from which we now create the
  7765. following blocks.
  7766. %
  7767. \begin{center}
  7768. \begin{minipage}{\textwidth}
  7769. \begin{lstlisting}
  7770. block_1:
  7771. return 42;
  7772. block_2:
  7773. return 777;
  7774. \end{lstlisting}
  7775. \end{minipage}
  7776. \end{center}
  7777. %
  7778. After that, \code{explicate\_pred} compiles the comparison
  7779. \racket{\code{(eq? x 0)}}
  7780. \python{\code{x == 0}}
  7781. to the following \code{if} statement.
  7782. %
  7783. {\if\edition\racketEd
  7784. \begin{center}
  7785. \begin{minipage}{\textwidth}
  7786. \begin{lstlisting}
  7787. if (eq? x 0)
  7788. goto block_1;
  7789. else
  7790. goto block_2;
  7791. \end{lstlisting}
  7792. \end{minipage}
  7793. \end{center}
  7794. \fi}
  7795. {\if\edition\pythonEd
  7796. \begin{center}
  7797. \begin{minipage}{\textwidth}
  7798. \begin{lstlisting}
  7799. if x == 0:
  7800. goto block_1;
  7801. else
  7802. goto block_2;
  7803. \end{lstlisting}
  7804. \end{minipage}
  7805. \end{center}
  7806. \fi}
  7807. Next consider the case for Boolean constants. We perform a kind of
  7808. partial evaluation\index{subject}{partial evaluation} and output
  7809. either the \code{thn} or \code{els} branch depending on whether the
  7810. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7811. following program.
  7812. {\if\edition\racketEd
  7813. \begin{lstlisting}
  7814. (if #t 42 777)
  7815. \end{lstlisting}
  7816. \fi}
  7817. {\if\edition\pythonEd
  7818. \begin{lstlisting}
  7819. 42 if True else 777
  7820. \end{lstlisting}
  7821. \fi}
  7822. %
  7823. \noindent Again, the two branches \code{42} and \code{777} were
  7824. compiled to \code{return} statements, so \code{explicate\_pred}
  7825. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  7826. code for the ``then'' branch.
  7827. \begin{lstlisting}
  7828. return 42;
  7829. \end{lstlisting}
  7830. This case demonstrates that we sometimes discard the \code{thn} or
  7831. \code{els} blocks that are input to \code{explicate\_pred}.
  7832. The case for \key{if} expressions in \code{explicate\_pred} is
  7833. particularly illuminating because it deals with the challenges we
  7834. discussed above regarding nested \key{if} expressions
  7835. (Figure~\ref{fig:explicate-control-s1-38}). The
  7836. \racket{\lstinline{thn^}}\python{\code{body}} and
  7837. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7838. \key{if} inherit their context from the current one, that is,
  7839. predicate context. So you should recursively apply
  7840. \code{explicate\_pred} to the
  7841. \racket{\lstinline{thn^}}\python{\code{body}} and
  7842. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7843. those recursive calls, pass \code{thn} and \code{els} as the extra
  7844. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7845. inside each recursive call. As discussed above, to avoid duplicating
  7846. code, we need to add them to the dictionary of basic blocks so that we
  7847. can instead refer to them by name and execute them with a \key{goto}.
  7848. {\if\edition\pythonEd
  7849. %
  7850. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7851. three parameters: 1) the statement to be compiled, 2) the code for its
  7852. continuation, and 3) the dictionary of basic blocks. The
  7853. \code{explicate\_stmt} returns a list of statements and it may add to
  7854. the dictionary of basic blocks. The cases for assignment and an
  7855. expression-statement are given in full in the skeleton code: they
  7856. simply dispatch to \code{explicate\_assign} and
  7857. \code{explicate\_effect}, respectively. The case for \code{if}
  7858. statements is not given, and is similar to the case for \code{if}
  7859. expressions.
  7860. The \code{explicate\_control} function itself is given in
  7861. Figure~\ref{fig:explicate-control-Lif}. It applies
  7862. \code{explicate\_stmt} to each statement in the program, from back to
  7863. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7864. used as the continuation parameter in the next call to
  7865. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7866. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7867. the dictionary of basic blocks, labeling it as the ``start'' block.
  7868. %
  7869. \fi}
  7870. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7871. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7872. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7873. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7874. %% results from the two recursive calls. We complete the case for
  7875. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7876. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7877. %% the result $B_5$.
  7878. %% \[
  7879. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7880. %% \quad\Rightarrow\quad
  7881. %% B_5
  7882. %% \]
  7883. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7884. %% inherit the current context, so they are in tail position. Thus, the
  7885. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7886. %% \code{explicate\_tail}.
  7887. %% %
  7888. %% We need to pass $B_0$ as the accumulator argument for both of these
  7889. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7890. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7891. %% to the control-flow graph and obtain a promised goto $G_0$.
  7892. %% %
  7893. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7894. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7895. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7896. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7897. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7898. %% \[
  7899. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7900. %% \]
  7901. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7902. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7903. %% should not be confused with the labels for the blocks that appear in
  7904. %% the generated code. We initially construct unlabeled blocks; we only
  7905. %% attach labels to blocks when we add them to the control-flow graph, as
  7906. %% we see in the next case.
  7907. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7908. %% function. The context of the \key{if} is an assignment to some
  7909. %% variable $x$ and then the control continues to some promised block
  7910. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7911. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7912. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7913. %% branches of the \key{if} inherit the current context, so they are in
  7914. %% assignment positions. Let $B_2$ be the result of applying
  7915. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7916. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7917. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7918. %% the result of applying \code{explicate\_pred} to the predicate
  7919. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7920. %% translates to the promise $B_4$.
  7921. %% \[
  7922. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7923. %% \]
  7924. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7925. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7926. \code{remove\_complex\_operands} pass and then the
  7927. \code{explicate\_control} pass on the example program. We walk through
  7928. the output program.
  7929. %
  7930. Following the order of evaluation in the output of
  7931. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7932. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7933. in the predicate of the inner \key{if}. In the output of
  7934. \code{explicate\_control}, in the
  7935. block labeled \code{start}, are two assignment statements followed by a
  7936. \code{if} statement that branches to \code{block\_4} or
  7937. \code{block\_5}. The blocks associated with those labels contain the
  7938. translations of the code
  7939. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7940. and
  7941. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7942. respectively. In particular, we start \code{block\_4} with the
  7943. comparison
  7944. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7945. and then branch to \code{block\_2} or \code{block\_3},
  7946. which correspond to the two branches of the outer \key{if}, i.e.,
  7947. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7948. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7949. %
  7950. The story for \code{block\_5} is similar to that of \code{block\_4}.
  7951. %
  7952. \python{The \code{block\_1} corresponds to the \code{print} statement
  7953. at the end of the program.}
  7954. {\if\edition\racketEd
  7955. \subsection{Interactions between Explicate and Shrink}
  7956. The way in which the \code{shrink} pass transforms logical operations
  7957. such as \code{and} and \code{or} can impact the quality of code
  7958. generated by \code{explicate\_control}. For example, consider the
  7959. following program.
  7960. % cond_test_21.rkt, and_eq_input.py
  7961. \begin{lstlisting}
  7962. (if (and (eq? (read) 0) (eq? (read) 1))
  7963. 0
  7964. 42)
  7965. \end{lstlisting}
  7966. The \code{and} operation should transform into something that the
  7967. \code{explicate\_pred} function can still analyze and descend through to
  7968. reach the underlying \code{eq?} conditions. Ideally, your
  7969. \code{explicate\_control} pass should generate code similar to the
  7970. following for the above program.
  7971. \begin{center}
  7972. \begin{lstlisting}
  7973. start:
  7974. tmp1 = (read);
  7975. if (eq? tmp1 0) goto block40;
  7976. else goto block39;
  7977. block40:
  7978. tmp2 = (read);
  7979. if (eq? tmp2 1) goto block38;
  7980. else goto block39;
  7981. block38:
  7982. return 0;
  7983. block39:
  7984. return 42;
  7985. \end{lstlisting}
  7986. \end{center}
  7987. \fi}
  7988. \begin{exercise}\normalfont\normalsize
  7989. \racket{
  7990. Implement the pass \code{explicate\_control} by adding the cases for
  7991. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7992. \code{explicate\_assign} functions. Implement the auxiliary function
  7993. \code{explicate\_pred} for predicate contexts.}
  7994. \python{Implement \code{explicate\_control} pass with its
  7995. four auxiliary functions.}
  7996. %
  7997. Create test cases that exercise all of the new cases in the code for
  7998. this pass.
  7999. %
  8000. {\if\edition\racketEd
  8001. Add the following entry to the list of \code{passes} in
  8002. \code{run-tests.rkt} and then run this script to test your compiler.
  8003. \begin{lstlisting}
  8004. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8005. \end{lstlisting}
  8006. \fi}
  8007. \end{exercise}
  8008. \clearpage
  8009. \section{Select Instructions}
  8010. \label{sec:select-Lif}
  8011. \index{subject}{instruction selection}
  8012. The \code{select\_instructions} pass translates \LangCIf{} to
  8013. \LangXIfVar{}.
  8014. %
  8015. \racket{Recall that we implement this pass using three auxiliary
  8016. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  8017. $\Tail$ in \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  8018. %
  8019. \racket{For $\Atm$, we have new cases for the Booleans.}
  8020. %
  8021. \python{We begin with the Boolean constants.}
  8022. We take the usual approach of encoding them as integers.
  8023. \[
  8024. \TRUE{} \quad\Rightarrow\quad \key{1}
  8025. \qquad\qquad
  8026. \FALSE{} \quad\Rightarrow\quad \key{0}
  8027. \]
  8028. For translating statements, we discuss some of the cases. The
  8029. \code{not} operation can be implemented in terms of \code{xorq} as we
  8030. discussed at the beginning of this section. Given an assignment, if
  8031. the left-hand side variable is the same as the argument of \code{not},
  8032. then just the \code{xorq} instruction suffices.
  8033. \[
  8034. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8035. \quad\Rightarrow\quad
  8036. \key{xorq}~\key{\$}1\key{,}~\Var
  8037. \]
  8038. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8039. semantics of x86. In the following translation, let $\Arg$ be the
  8040. result of translating $\Atm$ to x86.
  8041. \[
  8042. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8043. \quad\Rightarrow\quad
  8044. \begin{array}{l}
  8045. \key{movq}~\Arg\key{,}~\Var\\
  8046. \key{xorq}~\key{\$}1\key{,}~\Var
  8047. \end{array}
  8048. \]
  8049. Next consider the cases for equality comparisons. Translating this
  8050. operation to x86 is slightly involved due to the unusual nature of the
  8051. \key{cmpq} instruction that we discussed in Section~\ref{sec:x86-if}.
  8052. We recommend translating an assignment with an equality on the
  8053. right-hand side into a sequence of three instructions. \\
  8054. \begin{tabular}{lll}
  8055. \begin{minipage}{0.4\textwidth}
  8056. \begin{lstlisting}
  8057. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  8058. \end{lstlisting}
  8059. \end{minipage}
  8060. &
  8061. $\Rightarrow$
  8062. &
  8063. \begin{minipage}{0.4\textwidth}
  8064. \begin{lstlisting}
  8065. cmpq |$\Arg_2$|, |$\Arg_1$|
  8066. sete %al
  8067. movzbq %al, |$\Var$|
  8068. \end{lstlisting}
  8069. \end{minipage}
  8070. \end{tabular} \\
  8071. The translations for the other comparison operators are similar to the
  8072. above but use different condition codes for the \code{set} instruction.
  8073. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  8074. \key{goto} and \key{if} statements. Both are straightforward to
  8075. translate to x86.}
  8076. %
  8077. A \key{goto} statement becomes a jump instruction.
  8078. \[
  8079. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8080. \]
  8081. %
  8082. An \key{if} statement becomes a compare instruction followed by a
  8083. conditional jump (for the ``then'' branch) and the fall-through is to
  8084. a regular jump (for the ``else'' branch).\\
  8085. \begin{tabular}{lll}
  8086. \begin{minipage}{0.4\textwidth}
  8087. \begin{lstlisting}
  8088. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8089. goto |$\ell_1$||$\racket{\key{;}}$|
  8090. else|$\python{\key{:}}$|
  8091. goto |$\ell_2$||$\racket{\key{;}}$|
  8092. \end{lstlisting}
  8093. \end{minipage}
  8094. &
  8095. $\Rightarrow$
  8096. &
  8097. \begin{minipage}{0.4\textwidth}
  8098. \begin{lstlisting}
  8099. cmpq |$\Arg_2$|, |$\Arg_1$|
  8100. je |$\ell_1$|
  8101. jmp |$\ell_2$|
  8102. \end{lstlisting}
  8103. \end{minipage}
  8104. \end{tabular} \\
  8105. Again, the translations for the other comparison operators are similar to the
  8106. above but use different condition codes for the conditional jump instruction.
  8107. \python{Regarding the \key{return} statement, we recommend treating it
  8108. as an assignment to the \key{rax} register followed by a jump to the
  8109. conclusion of the \code{main} function.}
  8110. \begin{exercise}\normalfont\normalsize
  8111. Expand your \code{select\_instructions} pass to handle the new
  8112. features of the \LangCIf{} language.
  8113. %
  8114. {\if\edition\racketEd
  8115. Add the following entry to the list of \code{passes} in
  8116. \code{run-tests.rkt}
  8117. \begin{lstlisting}
  8118. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8119. \end{lstlisting}
  8120. \fi}
  8121. %
  8122. Run the script to test your compiler on all the test programs.
  8123. \end{exercise}
  8124. \section{Register Allocation}
  8125. \label{sec:register-allocation-Lif}
  8126. \index{subject}{register allocation}
  8127. The changes required for compiling \LangIf{} affect liveness analysis,
  8128. building the interference graph, and assigning homes, but the graph
  8129. coloring algorithm itself does not change.
  8130. \subsection{Liveness Analysis}
  8131. \label{sec:liveness-analysis-Lif}
  8132. \index{subject}{liveness analysis}
  8133. Recall that for \LangVar{} we implemented liveness analysis for a
  8134. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  8135. the addition of \key{if} expressions to \LangIf{},
  8136. \code{explicate\_control} produces many basic blocks.
  8137. %% We recommend that you create a new auxiliary function named
  8138. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8139. %% control-flow graph.
  8140. The first question is: in what order should we process the basic blocks?
  8141. Recall that to perform liveness analysis on a basic block we need to
  8142. know the live-after set for the last instruction in the block. If a
  8143. basic block has no successors (i.e. contains no jumps to other
  8144. blocks), then it has an empty live-after set and we can immediately
  8145. apply liveness analysis to it. If a basic block has some successors,
  8146. then we need to complete liveness analysis on those blocks
  8147. first. These ordering constraints are the reverse of a
  8148. \emph{topological order}\index{subject}{topological order} on a graph
  8149. representation of the program. In particular, the \emph{control flow
  8150. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8151. of a program has a node for each basic block and an edge for each jump
  8152. from one block to another. It is straightforward to generate a CFG
  8153. from the dictionary of basic blocks. One then transposes the CFG and
  8154. applies the topological sort algorithm.
  8155. %
  8156. %
  8157. \racket{We recommend using the \code{tsort} and \code{transpose}
  8158. functions of the Racket \code{graph} package to accomplish this.}
  8159. %
  8160. \python{We provide implementations of \code{topological\_sort} and
  8161. \code{transpose} in the file \code{graph.py} of the support code.}
  8162. %
  8163. As an aside, a topological ordering is only guaranteed to exist if the
  8164. graph does not contain any cycles. This is the case for the
  8165. control-flow graphs that we generate from \LangIf{} programs.
  8166. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8167. and learn how to handle cycles in the control-flow graph.
  8168. \racket{You'll need to construct a directed graph to represent the
  8169. control-flow graph. Do not use the \code{directed-graph} of the
  8170. \code{graph} package because that only allows at most one edge
  8171. between each pair of vertices, but a control-flow graph may have
  8172. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8173. file in the support code implements a graph representation that
  8174. allows multiple edges between a pair of vertices.}
  8175. {\if\edition\racketEd
  8176. The next question is how to analyze jump instructions. Recall that in
  8177. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8178. \code{label->live} that maps each label to the set of live locations
  8179. at the beginning of its block. We use \code{label->live} to determine
  8180. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8181. that we have many basic blocks, \code{label->live} needs to be updated
  8182. as we process the blocks. In particular, after performing liveness
  8183. analysis on a block, we take the live-before set of its first
  8184. instruction and associate that with the block's label in the
  8185. \code{label->live} alist.
  8186. \fi}
  8187. %
  8188. {\if\edition\pythonEd
  8189. %
  8190. The next question is how to analyze jump instructions. The locations
  8191. that are live before a \code{jmp} should be the locations in
  8192. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8193. maintaining a dictionary named \code{live\_before\_block} that maps each
  8194. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8195. block. After performing liveness analysis on each block, we take the
  8196. live-before set of its first instruction and associate that with the
  8197. block's label in the \code{live\_before\_block} dictionary.
  8198. %
  8199. \fi}
  8200. In \LangXIfVar{} we also have the conditional jump
  8201. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8202. this instruction is particularly interesting because, during
  8203. compilation, we do not know which way a conditional jump will go. So
  8204. we do not know whether to use the live-before set for the block
  8205. associated with the $\itm{label}$ or the live-before set for the
  8206. following instruction. However, there is no harm to the correctness
  8207. of the generated code if we classify more locations as live than the
  8208. ones that are truly live during one particular execution of the
  8209. instruction. Thus, we can take the union of the live-before sets from
  8210. the following instruction and from the mapping for $\itm{label}$ in
  8211. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8212. The auxiliary functions for computing the variables in an
  8213. instruction's argument and for computing the variables read-from ($R$)
  8214. or written-to ($W$) by an instruction need to be updated to handle the
  8215. new kinds of arguments and instructions in \LangXIfVar{}.
  8216. \begin{exercise}\normalfont\normalsize
  8217. {\if\edition\racketEd
  8218. %
  8219. Update the \code{uncover\_live} pass to apply liveness analysis to
  8220. every basic block in the program.
  8221. %
  8222. Add the following entry to the list of \code{passes} in the
  8223. \code{run-tests.rkt} script.
  8224. \begin{lstlisting}
  8225. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8226. \end{lstlisting}
  8227. \fi}
  8228. {\if\edition\pythonEd
  8229. %
  8230. Update the \code{uncover\_live} function to perform liveness analysis,
  8231. in reverse topological order, on all of the basic blocks in the
  8232. program.
  8233. %
  8234. \fi}
  8235. % Check that the live-after sets that you generate for
  8236. % example X matches the following... -Jeremy
  8237. \end{exercise}
  8238. \subsection{Build the Interference Graph}
  8239. \label{sec:build-interference-Lif}
  8240. Many of the new instructions in \LangXIfVar{} can be handled in the
  8241. same way as the instructions in \LangXVar{}.
  8242. % Thus, if your code was
  8243. % already quite general, it will not need to be changed to handle the
  8244. % new instructions. If your code is not general enough, we recommend that
  8245. % you change your code to be more general. For example, you can factor
  8246. % out the computing of the the read and write sets for each kind of
  8247. % instruction into auxiliary functions.
  8248. %
  8249. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8250. similar to the \key{movq} instruction. See rule number 1 in
  8251. Section~\ref{sec:build-interference}.
  8252. \begin{exercise}\normalfont\normalsize
  8253. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8254. {\if\edition\racketEd
  8255. Add the following entries to the list of \code{passes} in the
  8256. \code{run-tests.rkt} script.
  8257. \begin{lstlisting}
  8258. (list "build_interference" build_interference interp-pseudo-x86-1)
  8259. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8260. \end{lstlisting}
  8261. \fi}
  8262. % Check that the interference graph that you generate for
  8263. % example X matches the following graph G... -Jeremy
  8264. \end{exercise}
  8265. \section{Patch Instructions}
  8266. The new instructions \key{cmpq} and \key{movzbq} have some special
  8267. restrictions that need to be handled in the \code{patch\_instructions}
  8268. pass.
  8269. %
  8270. The second argument of the \key{cmpq} instruction must not be an
  8271. immediate value (such as an integer). So if you are comparing two
  8272. immediates, we recommend inserting a \key{movq} instruction to put the
  8273. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8274. one memory reference.
  8275. %
  8276. The second argument of the \key{movzbq} must be a register.
  8277. \begin{exercise}\normalfont\normalsize
  8278. %
  8279. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8280. %
  8281. {\if\edition\racketEd
  8282. Add the following entry to the list of \code{passes} in
  8283. \code{run-tests.rkt} and then run this script to test your compiler.
  8284. \begin{lstlisting}
  8285. (list "patch_instructions" patch_instructions interp-x86-1)
  8286. \end{lstlisting}
  8287. \fi}
  8288. \end{exercise}
  8289. {\if\edition\pythonEd
  8290. \section{Prelude and Conclusion}
  8291. \label{sec:prelude-conclusion-cond}
  8292. The generation of the \code{main} function with its prelude and
  8293. conclusion must change to accommodate how the program now consists of
  8294. one or more basic blocks. After the prelude in \code{main}, jump to
  8295. the \code{start} block. Place the conclusion in a basic block labeled
  8296. with \code{conclusion}.
  8297. \fi}
  8298. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8299. \LangIf{} translated to x86, showing the results of
  8300. \code{explicate\_control}, \code{select\_instructions}, and the final
  8301. x86 assembly.
  8302. \begin{figure}[tbp]
  8303. \begin{tcolorbox}[colback=white]
  8304. {\if\edition\racketEd
  8305. \begin{tabular}{lll}
  8306. \begin{minipage}{0.4\textwidth}
  8307. % cond_test_20.rkt, eq_input.py
  8308. \begin{lstlisting}
  8309. (if (eq? (read) 1) 42 0)
  8310. \end{lstlisting}
  8311. $\Downarrow$
  8312. \begin{lstlisting}
  8313. start:
  8314. tmp7951 = (read);
  8315. if (eq? tmp7951 1)
  8316. goto block7952;
  8317. else
  8318. goto block7953;
  8319. block7952:
  8320. return 42;
  8321. block7953:
  8322. return 0;
  8323. \end{lstlisting}
  8324. $\Downarrow$
  8325. \begin{lstlisting}
  8326. start:
  8327. callq read_int
  8328. movq %rax, tmp7951
  8329. cmpq $1, tmp7951
  8330. je block7952
  8331. jmp block7953
  8332. block7953:
  8333. movq $0, %rax
  8334. jmp conclusion
  8335. block7952:
  8336. movq $42, %rax
  8337. jmp conclusion
  8338. \end{lstlisting}
  8339. \end{minipage}
  8340. &
  8341. $\Rightarrow\qquad$
  8342. \begin{minipage}{0.4\textwidth}
  8343. \begin{lstlisting}
  8344. start:
  8345. callq read_int
  8346. movq %rax, %rcx
  8347. cmpq $1, %rcx
  8348. je block7952
  8349. jmp block7953
  8350. block7953:
  8351. movq $0, %rax
  8352. jmp conclusion
  8353. block7952:
  8354. movq $42, %rax
  8355. jmp conclusion
  8356. .globl main
  8357. main:
  8358. pushq %rbp
  8359. movq %rsp, %rbp
  8360. pushq %r13
  8361. pushq %r12
  8362. pushq %rbx
  8363. pushq %r14
  8364. subq $0, %rsp
  8365. jmp start
  8366. conclusion:
  8367. addq $0, %rsp
  8368. popq %r14
  8369. popq %rbx
  8370. popq %r12
  8371. popq %r13
  8372. popq %rbp
  8373. retq
  8374. \end{lstlisting}
  8375. \end{minipage}
  8376. \end{tabular}
  8377. \fi}
  8378. {\if\edition\pythonEd
  8379. \begin{tabular}{lll}
  8380. \begin{minipage}{0.4\textwidth}
  8381. % cond_test_20.rkt, eq_input.py
  8382. \begin{lstlisting}
  8383. print(42 if input_int() == 1 else 0)
  8384. \end{lstlisting}
  8385. $\Downarrow$
  8386. \begin{lstlisting}
  8387. start:
  8388. tmp_0 = input_int()
  8389. if tmp_0 == 1:
  8390. goto block_3
  8391. else:
  8392. goto block_4
  8393. block_3:
  8394. tmp_1 = 42
  8395. goto block_2
  8396. block_4:
  8397. tmp_1 = 0
  8398. goto block_2
  8399. block_2:
  8400. print(tmp_1)
  8401. return 0
  8402. \end{lstlisting}
  8403. $\Downarrow$
  8404. \begin{lstlisting}
  8405. start:
  8406. callq read_int
  8407. movq %rax, tmp_0
  8408. cmpq 1, tmp_0
  8409. je block_3
  8410. jmp block_4
  8411. block_3:
  8412. movq 42, tmp_1
  8413. jmp block_2
  8414. block_4:
  8415. movq 0, tmp_1
  8416. jmp block_2
  8417. block_2:
  8418. movq tmp_1, %rdi
  8419. callq print_int
  8420. movq 0, %rax
  8421. jmp conclusion
  8422. \end{lstlisting}
  8423. \end{minipage}
  8424. &
  8425. $\Rightarrow\qquad$
  8426. \begin{minipage}{0.4\textwidth}
  8427. \begin{lstlisting}
  8428. .globl main
  8429. main:
  8430. pushq %rbp
  8431. movq %rsp, %rbp
  8432. subq $0, %rsp
  8433. jmp start
  8434. start:
  8435. callq read_int
  8436. movq %rax, %rcx
  8437. cmpq $1, %rcx
  8438. je block_3
  8439. jmp block_4
  8440. block_3:
  8441. movq $42, %rcx
  8442. jmp block_2
  8443. block_4:
  8444. movq $0, %rcx
  8445. jmp block_2
  8446. block_2:
  8447. movq %rcx, %rdi
  8448. callq print_int
  8449. movq $0, %rax
  8450. jmp conclusion
  8451. conclusion:
  8452. addq $0, %rsp
  8453. popq %rbp
  8454. retq
  8455. \end{lstlisting}
  8456. \end{minipage}
  8457. \end{tabular}
  8458. \fi}
  8459. \end{tcolorbox}
  8460. \caption{Example compilation of an \key{if} expression to x86, showing
  8461. the results of \code{explicate\_control},
  8462. \code{select\_instructions}, and the final x86 assembly code. }
  8463. \label{fig:if-example-x86}
  8464. \end{figure}
  8465. \begin{figure}[tbp]
  8466. \begin{tcolorbox}[colback=white]
  8467. {\if\edition\racketEd
  8468. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8469. \node (Lif) at (0,2) {\large \LangIf{}};
  8470. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8471. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8472. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8473. \node (Lif-5) at (9,0) {\large \LangIfANF{}};
  8474. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8475. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8476. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8477. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8478. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8479. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8480. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8481. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8482. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8483. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8484. \path[->,bend left=15] (Lif-4) edge [right] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8485. \path[->,bend right=15] (Lif-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8486. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  8487. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8488. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8489. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8490. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8491. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8492. \end{tikzpicture}
  8493. \fi}
  8494. {\if\edition\pythonEd
  8495. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8496. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8497. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8498. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8499. \node (C-1) at (3,0) {\large \LangCIf{}};
  8500. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8501. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8502. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8503. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8504. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8505. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8506. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8507. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8508. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8509. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8510. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8511. \end{tikzpicture}
  8512. \fi}
  8513. \end{tcolorbox}
  8514. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8515. \label{fig:Lif-passes}
  8516. \end{figure}
  8517. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8518. compilation of \LangIf{}.
  8519. \section{Challenge: Optimize Blocks and Remove Jumps}
  8520. \label{sec:opt-jumps}
  8521. We discuss two optional challenges that involve optimizing the
  8522. control-flow of the program.
  8523. \subsection{Optimize Blocks}
  8524. The algorithm for \code{explicate\_control} that we discussed in
  8525. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8526. blocks. It creates a basic block whenever a continuation \emph{might}
  8527. get used more than once (e.g., whenever the \code{cont} parameter is
  8528. passed into two or more recursive calls). However, some continuation
  8529. arguments may not be used at all. For example, consider the case for
  8530. the constant \TRUE{} in \code{explicate\_pred}, where we discard the
  8531. \code{els} continuation.
  8532. %
  8533. {\if\edition\racketEd
  8534. The following example program falls into this
  8535. case, and it creates two unused blocks.
  8536. \begin{center}
  8537. \begin{tabular}{lll}
  8538. \begin{minipage}{0.4\textwidth}
  8539. % cond_test_82.rkt
  8540. \begin{lstlisting}
  8541. (let ([y (if #t
  8542. (read)
  8543. (if (eq? (read) 0)
  8544. 777
  8545. (let ([x (read)])
  8546. (+ 1 x))))])
  8547. (+ y 2))
  8548. \end{lstlisting}
  8549. \end{minipage}
  8550. &
  8551. $\Rightarrow$
  8552. &
  8553. \begin{minipage}{0.55\textwidth}
  8554. \begin{lstlisting}
  8555. start:
  8556. y = (read);
  8557. goto block_5;
  8558. block_5:
  8559. return (+ y 2);
  8560. block_6:
  8561. y = 777;
  8562. goto block_5;
  8563. block_7:
  8564. x = (read);
  8565. y = (+ 1 x2);
  8566. goto block_5;
  8567. \end{lstlisting}
  8568. \end{minipage}
  8569. \end{tabular}
  8570. \end{center}
  8571. \fi}
  8572. So the question is how can we decide whether to create a basic block?
  8573. \emph{Lazy evaluation}\index{subject}{lazy
  8574. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  8575. delaying the creation of a basic block until the point in time where
  8576. we know it will be used.
  8577. %
  8578. {\if\edition\racketEd
  8579. %
  8580. Racket provides support for
  8581. lazy evaluation with the
  8582. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8583. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8584. \index{subject}{delay} creates a
  8585. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8586. expressions is postponed. When \key{(force}
  8587. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8588. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8589. result of $e_n$ is cached in the promise and returned. If \code{force}
  8590. is applied again to the same promise, then the cached result is
  8591. returned. If \code{force} is applied to an argument that is not a
  8592. promise, \code{force} simply returns the argument.
  8593. %
  8594. \fi}
  8595. %
  8596. {\if\edition\pythonEd
  8597. %
  8598. While Python does not provide direct support for lazy evaluation, it
  8599. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8600. by wrapping it inside a function with no parameters. We can
  8601. \emph{force} its evaluation by calling the function. However, in some
  8602. cases of \code{explicate\_pred}, etc., we will return a list of
  8603. statements and in other cases we will return a function that computes
  8604. a list of statements. We use the term \emph{promise} to refer to a
  8605. value that may be delayed. To uniformly deal with
  8606. promises, we define the following \code{force} function that checks
  8607. whether its input is delayed (i.e., whether it is a function) and then
  8608. either 1) calls the function, or 2) returns the input.
  8609. \begin{lstlisting}
  8610. def force(promise):
  8611. if isinstance(promise, types.FunctionType):
  8612. return promise()
  8613. else:
  8614. return promise
  8615. \end{lstlisting}
  8616. %
  8617. \fi}
  8618. We use promises for the input and output of the functions
  8619. \code{explicate\_pred}, \code{explicate\_assign},
  8620. %
  8621. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8622. %
  8623. So instead of taking and returning \racket{$\Tail$
  8624. expressions}\python{lists of statements}, they take and return
  8625. promises. Furthermore, when we come to a situation in which a
  8626. continuation might be used more than once, as in the case for
  8627. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8628. that creates a basic block for each continuation (if there is not
  8629. already one) and then returns a \code{goto} statement to that basic
  8630. block. When we come to a situation where we have a promise but need an
  8631. actual piece of code, e.g. to create a larger piece of code with a
  8632. constructor such as \code{Seq}, then insert a call to \code{force}.
  8633. %
  8634. {\if\edition\racketEd
  8635. %
  8636. Also we must modify the \code{create\_block} function to begin with
  8637. \code{delay} to create a promise. When forced, this promise forces the
  8638. original promise. If that returns a \code{Goto} (because the block was
  8639. already added to \code{basic-blocks}), then we return the
  8640. \code{Goto}. Otherwise we add the block to \code{basic-blocks} and
  8641. return a \code{Goto} to the new label.
  8642. \begin{center}
  8643. \begin{minipage}{\textwidth}
  8644. \begin{lstlisting}
  8645. (define (create_block tail)
  8646. (delay
  8647. (define t (force tail))
  8648. (match t
  8649. [(Goto label) (Goto label)]
  8650. [else
  8651. (let ([label (gensym 'block)])
  8652. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8653. (Goto label))]))
  8654. \end{lstlisting}
  8655. \end{minipage}
  8656. \end{center}
  8657. \fi}
  8658. {\if\edition\pythonEd
  8659. %
  8660. Here is the new version of the \code{create\_block} auxiliary function
  8661. that works on promises and that checks whether the block consists of a
  8662. solitary \code{goto} statement.\\
  8663. \begin{minipage}{\textwidth}
  8664. \begin{lstlisting}
  8665. def create_block(promise, basic_blocks):
  8666. stmts = force(promise)
  8667. match stmts:
  8668. case [Goto(l)]:
  8669. return Goto(l)
  8670. case _:
  8671. label = label_name(generate_name('block'))
  8672. basic_blocks[label] = stmts
  8673. return Goto(label)
  8674. \end{lstlisting}
  8675. \end{minipage}
  8676. \fi}
  8677. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8678. improved \code{explicate\_control} on the above example. As you can
  8679. see, the number of basic blocks has been reduced from 4 blocks (see
  8680. Figure~\ref{fig:explicate-control-s1-38}) down to 2 blocks.
  8681. \begin{figure}[tbp]
  8682. \begin{tcolorbox}[colback=white]
  8683. {\if\edition\racketEd
  8684. \begin{tabular}{lll}
  8685. \begin{minipage}{0.4\textwidth}
  8686. % cond_test_82.rkt
  8687. \begin{lstlisting}
  8688. (let ([y (if #t
  8689. (read)
  8690. (if (eq? (read) 0)
  8691. 777
  8692. (let ([x (read)])
  8693. (+ 1 x))))])
  8694. (+ y 2))
  8695. \end{lstlisting}
  8696. \end{minipage}
  8697. &
  8698. $\Rightarrow$
  8699. &
  8700. \begin{minipage}{0.55\textwidth}
  8701. \begin{lstlisting}
  8702. start:
  8703. y = (read);
  8704. goto block_5;
  8705. block_5:
  8706. return (+ y 2);
  8707. \end{lstlisting}
  8708. \end{minipage}
  8709. \end{tabular}
  8710. \fi}
  8711. {\if\edition\pythonEd
  8712. \begin{tabular}{lll}
  8713. \begin{minipage}{0.4\textwidth}
  8714. % cond_test_41.rkt
  8715. \begin{lstlisting}
  8716. x = input_int()
  8717. y = input_int()
  8718. print(y + 2 \
  8719. if (x == 0 \
  8720. if x < 1 \
  8721. else x == 2) \
  8722. else y + 10)
  8723. \end{lstlisting}
  8724. \end{minipage}
  8725. &
  8726. $\Rightarrow$
  8727. &
  8728. \begin{minipage}{0.55\textwidth}
  8729. \begin{lstlisting}
  8730. start:
  8731. x = input_int()
  8732. y = input_int()
  8733. if x < 1:
  8734. goto block_4
  8735. else:
  8736. goto block_5
  8737. block_4:
  8738. if x == 0:
  8739. goto block_2
  8740. else:
  8741. goto block_3
  8742. block_5:
  8743. if x == 2:
  8744. goto block_2
  8745. else:
  8746. goto block_3
  8747. block_2:
  8748. tmp_0 = y + 2
  8749. goto block_1
  8750. block_3:
  8751. tmp_0 = y + 10
  8752. goto block_1
  8753. block_1:
  8754. print(tmp_0)
  8755. return 0
  8756. \end{lstlisting}
  8757. \end{minipage}
  8758. \end{tabular}
  8759. \fi}
  8760. \end{tcolorbox}
  8761. \caption{Translation from \LangIf{} to \LangCIf{}
  8762. via the improved \code{explicate\_control}.}
  8763. \label{fig:explicate-control-challenge}
  8764. \end{figure}
  8765. %% Recall that in the example output of \code{explicate\_control} in
  8766. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8767. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8768. %% block. The first goal of this challenge assignment is to remove those
  8769. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8770. %% \code{explicate\_control} on the left and shows the result of bypassing
  8771. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8772. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8773. %% \code{block55}. The optimized code on the right of
  8774. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8775. %% \code{then} branch jumping directly to \code{block55}. The story is
  8776. %% similar for the \code{else} branch, as well as for the two branches in
  8777. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8778. %% have been optimized in this way, there are no longer any jumps to
  8779. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8780. %% \begin{figure}[tbp]
  8781. %% \begin{tabular}{lll}
  8782. %% \begin{minipage}{0.4\textwidth}
  8783. %% \begin{lstlisting}
  8784. %% block62:
  8785. %% tmp54 = (read);
  8786. %% if (eq? tmp54 2) then
  8787. %% goto block59;
  8788. %% else
  8789. %% goto block60;
  8790. %% block61:
  8791. %% tmp53 = (read);
  8792. %% if (eq? tmp53 0) then
  8793. %% goto block57;
  8794. %% else
  8795. %% goto block58;
  8796. %% block60:
  8797. %% goto block56;
  8798. %% block59:
  8799. %% goto block55;
  8800. %% block58:
  8801. %% goto block56;
  8802. %% block57:
  8803. %% goto block55;
  8804. %% block56:
  8805. %% return (+ 700 77);
  8806. %% block55:
  8807. %% return (+ 10 32);
  8808. %% start:
  8809. %% tmp52 = (read);
  8810. %% if (eq? tmp52 1) then
  8811. %% goto block61;
  8812. %% else
  8813. %% goto block62;
  8814. %% \end{lstlisting}
  8815. %% \end{minipage}
  8816. %% &
  8817. %% $\Rightarrow$
  8818. %% &
  8819. %% \begin{minipage}{0.55\textwidth}
  8820. %% \begin{lstlisting}
  8821. %% block62:
  8822. %% tmp54 = (read);
  8823. %% if (eq? tmp54 2) then
  8824. %% goto block55;
  8825. %% else
  8826. %% goto block56;
  8827. %% block61:
  8828. %% tmp53 = (read);
  8829. %% if (eq? tmp53 0) then
  8830. %% goto block55;
  8831. %% else
  8832. %% goto block56;
  8833. %% block56:
  8834. %% return (+ 700 77);
  8835. %% block55:
  8836. %% return (+ 10 32);
  8837. %% start:
  8838. %% tmp52 = (read);
  8839. %% if (eq? tmp52 1) then
  8840. %% goto block61;
  8841. %% else
  8842. %% goto block62;
  8843. %% \end{lstlisting}
  8844. %% \end{minipage}
  8845. %% \end{tabular}
  8846. %% \caption{Optimize jumps by removing trivial blocks.}
  8847. %% \label{fig:optimize-jumps}
  8848. %% \end{figure}
  8849. %% The name of this pass is \code{optimize-jumps}. We recommend
  8850. %% implementing this pass in two phases. The first phrase builds a hash
  8851. %% table that maps labels to possibly improved labels. The second phase
  8852. %% changes the target of each \code{goto} to use the improved label. If
  8853. %% the label is for a trivial block, then the hash table should map the
  8854. %% label to the first non-trivial block that can be reached from this
  8855. %% label by jumping through trivial blocks. If the label is for a
  8856. %% non-trivial block, then the hash table should map the label to itself;
  8857. %% we do not want to change jumps to non-trivial blocks.
  8858. %% The first phase can be accomplished by constructing an empty hash
  8859. %% table, call it \code{short-cut}, and then iterating over the control
  8860. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8861. %% then update the hash table, mapping the block's source to the target
  8862. %% of the \code{goto}. Also, the hash table may already have mapped some
  8863. %% labels to the block's source, to you must iterate through the hash
  8864. %% table and update all of those so that they instead map to the target
  8865. %% of the \code{goto}.
  8866. %% For the second phase, we recommend iterating through the $\Tail$ of
  8867. %% each block in the program, updating the target of every \code{goto}
  8868. %% according to the mapping in \code{short-cut}.
  8869. \begin{exercise}\normalfont\normalsize
  8870. Implement the improvements to the \code{explicate\_control} pass.
  8871. Check that it removes trivial blocks in a few example programs. Then
  8872. check that your compiler still passes all of your tests.
  8873. \end{exercise}
  8874. \subsection{Remove Jumps}
  8875. There is an opportunity for removing jumps that is apparent in the
  8876. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8877. ends with a jump to \code{block\_5} and there are no other jumps to
  8878. \code{block\_5} in the rest of the program. In this situation we can
  8879. avoid the runtime overhead of this jump by merging \code{block\_5}
  8880. into the preceding block, in this case the \code{start} block.
  8881. Figure~\ref{fig:remove-jumps} shows the output of
  8882. \code{allocate\_registers} on the left and the result of this
  8883. optimization on the right.
  8884. \begin{figure}[tbp]
  8885. \begin{tcolorbox}[colback=white]
  8886. {\if\edition\racketEd
  8887. \begin{tabular}{lll}
  8888. \begin{minipage}{0.5\textwidth}
  8889. % cond_test_82.rkt
  8890. \begin{lstlisting}
  8891. start:
  8892. callq read_int
  8893. movq %rax, %rcx
  8894. jmp block_5
  8895. block_5:
  8896. movq %rcx, %rax
  8897. addq $2, %rax
  8898. jmp conclusion
  8899. \end{lstlisting}
  8900. \end{minipage}
  8901. &
  8902. $\Rightarrow\qquad$
  8903. \begin{minipage}{0.4\textwidth}
  8904. \begin{lstlisting}
  8905. start:
  8906. callq read_int
  8907. movq %rax, %rcx
  8908. movq %rcx, %rax
  8909. addq $2, %rax
  8910. jmp conclusion
  8911. \end{lstlisting}
  8912. \end{minipage}
  8913. \end{tabular}
  8914. \fi}
  8915. {\if\edition\pythonEd
  8916. \begin{tabular}{lll}
  8917. \begin{minipage}{0.5\textwidth}
  8918. % cond_test_20.rkt
  8919. \begin{lstlisting}
  8920. start:
  8921. callq read_int
  8922. movq %rax, tmp_0
  8923. cmpq 1, tmp_0
  8924. je block_3
  8925. jmp block_4
  8926. block_3:
  8927. movq 42, tmp_1
  8928. jmp block_2
  8929. block_4:
  8930. movq 0, tmp_1
  8931. jmp block_2
  8932. block_2:
  8933. movq tmp_1, %rdi
  8934. callq print_int
  8935. movq 0, %rax
  8936. jmp conclusion
  8937. \end{lstlisting}
  8938. \end{minipage}
  8939. &
  8940. $\Rightarrow\qquad$
  8941. \begin{minipage}{0.4\textwidth}
  8942. \begin{lstlisting}
  8943. start:
  8944. callq read_int
  8945. movq %rax, tmp_0
  8946. cmpq 1, tmp_0
  8947. je block_3
  8948. movq 0, tmp_1
  8949. jmp block_2
  8950. block_3:
  8951. movq 42, tmp_1
  8952. jmp block_2
  8953. block_2:
  8954. movq tmp_1, %rdi
  8955. callq print_int
  8956. movq 0, %rax
  8957. jmp conclusion
  8958. \end{lstlisting}
  8959. \end{minipage}
  8960. \end{tabular}
  8961. \fi}
  8962. \end{tcolorbox}
  8963. \caption{Merging basic blocks by removing unnecessary jumps.}
  8964. \label{fig:remove-jumps}
  8965. \end{figure}
  8966. \begin{exercise}\normalfont\normalsize
  8967. %
  8968. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8969. into their preceding basic block, when there is only one preceding
  8970. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8971. %
  8972. {\if\edition\racketEd
  8973. In the \code{run-tests.rkt} script, add the following entry to the
  8974. list of \code{passes} between \code{allocate\_registers}
  8975. and \code{patch\_instructions}.
  8976. \begin{lstlisting}
  8977. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8978. \end{lstlisting}
  8979. \fi}
  8980. %
  8981. Run the script to test your compiler.
  8982. %
  8983. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8984. blocks on several test programs.
  8985. \end{exercise}
  8986. \section{Further Reading}
  8987. \label{sec:cond-further-reading}
  8988. The algorithm for the \code{explicate\_control} pass is based on the
  8989. \code{expose-basic-blocks} pass in the course notes of
  8990. \citet{Dybvig:2010aa}.
  8991. %
  8992. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8993. \citet{Appel:2003fk}, and is related to translations into continuation
  8994. passing
  8995. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8996. %
  8997. The treatment of conditionals in the \code{explicate\_control} pass is
  8998. similar to short-cut boolean
  8999. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9000. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9001. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9002. \chapter{Loops and Dataflow Analysis}
  9003. \label{ch:Lwhile}
  9004. % TODO: define R'_8
  9005. % TODO: multi-graph
  9006. {\if\edition\racketEd
  9007. %
  9008. In this chapter we study two features that are the hallmarks of
  9009. imperative programming languages: loops and assignments to local
  9010. variables. The following example demonstrates these new features by
  9011. computing the sum of the first five positive integers.
  9012. % similar to loop_test_1.rkt
  9013. \begin{lstlisting}
  9014. (let ([sum 0])
  9015. (let ([i 5])
  9016. (begin
  9017. (while (> i 0)
  9018. (begin
  9019. (set! sum (+ sum i))
  9020. (set! i (- i 1))))
  9021. sum)))
  9022. \end{lstlisting}
  9023. The \code{while} loop consists of a condition and a
  9024. body\footnote{The \code{while} loop is not a built-in
  9025. feature of the Racket language, but Racket includes many looping
  9026. constructs and it is straightforward to define \code{while} as a
  9027. macro.}. The body is evaluated repeatedly so long as the condition
  9028. remains true.
  9029. %
  9030. The \code{set!} consists of a variable and a right-hand-side
  9031. expression. The \code{set!} updates value of the variable to the
  9032. value of the right-hand-side.
  9033. %
  9034. The primary purpose of both the \code{while} loop and \code{set!} is
  9035. to cause side effects, so they do not have a meaningful result
  9036. value. Instead their result is the \code{\#<void>} value. The
  9037. expression \code{(void)} is an explicit way to create the
  9038. \code{\#<void>} value and it has type \code{Void}. The
  9039. \code{\#<void>} value can be passed around just like other values
  9040. inside an \LangLoop{} program and it can be compared for equality with
  9041. another \code{\#<void>} value. However, there are no other operations
  9042. specific to the the \code{\#<void>} value in \LangLoop{}. In contrast,
  9043. Racket defines the \code{void?} predicate that returns \code{\#t}
  9044. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9045. %
  9046. \footnote{Racket's \code{Void} type corresponds to what is often
  9047. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9048. by a single value \code{\#<void>} which corresponds to \code{unit}
  9049. or \code{()} in the literature~\citep{Pierce:2002hj}.}.
  9050. %
  9051. With the addition of side-effecting features such as \code{while} loop
  9052. and \code{set!}, it is helpful to also include in a language feature
  9053. for sequencing side effects: the \code{begin} expression. It consists
  9054. of one or more subexpressions that are evaluated left-to-right.
  9055. %
  9056. \fi}
  9057. {\if\edition\pythonEd
  9058. %
  9059. In this chapter we study loops, one of the hallmarks of imperative
  9060. programming languages. The following example demonstrates the
  9061. \code{while} loop by computing the sum of the first five positive
  9062. integers.
  9063. \begin{lstlisting}
  9064. sum = 0
  9065. i = 5
  9066. while i > 0:
  9067. sum = sum + i
  9068. i = i - 1
  9069. print(sum)
  9070. \end{lstlisting}
  9071. The \code{while} loop consists of a condition expression and a body (a
  9072. sequence of statements). The body is evaluated repeatedly so long as
  9073. the condition remains true.
  9074. %
  9075. \fi}
  9076. \section{The \LangLoop{} Language}
  9077. \newcommand{\LwhileGrammarRacket}{
  9078. \begin{array}{lcl}
  9079. \Type &::=& \key{Void}\\
  9080. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9081. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9082. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9083. \end{array}
  9084. }
  9085. \newcommand{\LwhileASTRacket}{
  9086. \begin{array}{lcl}
  9087. \Type &::=& \key{Void}\\
  9088. \Exp &::=& \SETBANG{\Var}{\Exp}
  9089. \MID \BEGIN{\Exp^{*}}{\Exp}
  9090. \MID \WHILE{\Exp}{\Exp}
  9091. \MID \VOID{}
  9092. \end{array}
  9093. }
  9094. \newcommand{\LwhileGrammarPython}{
  9095. \begin{array}{rcl}
  9096. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9097. \end{array}
  9098. }
  9099. \newcommand{\LwhileASTPython}{
  9100. \begin{array}{lcl}
  9101. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9102. \end{array}
  9103. }
  9104. \begin{figure}[tp]
  9105. \centering
  9106. \begin{tcolorbox}[colback=white]
  9107. \small
  9108. {\if\edition\racketEd
  9109. \[
  9110. \begin{array}{l}
  9111. \gray{\LintGrammarRacket{}} \\ \hline
  9112. \gray{\LvarGrammarRacket{}} \\ \hline
  9113. \gray{\LifGrammarRacket{}} \\ \hline
  9114. \LwhileGrammarRacket \\
  9115. \begin{array}{lcl}
  9116. \LangLoopM{} &::=& \Exp
  9117. \end{array}
  9118. \end{array}
  9119. \]
  9120. \fi}
  9121. {\if\edition\pythonEd
  9122. \[
  9123. \begin{array}{l}
  9124. \gray{\LintGrammarPython} \\ \hline
  9125. \gray{\LvarGrammarPython} \\ \hline
  9126. \gray{\LifGrammarPython} \\ \hline
  9127. \LwhileGrammarPython \\
  9128. \begin{array}{rcl}
  9129. \LangLoopM{} &::=& \Stmt^{*}
  9130. \end{array}
  9131. \end{array}
  9132. \]
  9133. \fi}
  9134. \end{tcolorbox}
  9135. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  9136. \label{fig:Lwhile-concrete-syntax}
  9137. \end{figure}
  9138. \begin{figure}[tp]
  9139. \centering
  9140. \begin{tcolorbox}[colback=white]
  9141. \small
  9142. {\if\edition\racketEd
  9143. \[
  9144. \begin{array}{l}
  9145. \gray{\LintOpAST} \\ \hline
  9146. \gray{\LvarASTRacket{}} \\ \hline
  9147. \gray{\LifASTRacket{}} \\ \hline
  9148. \LwhileASTRacket{} \\
  9149. \begin{array}{lcl}
  9150. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9151. \end{array}
  9152. \end{array}
  9153. \]
  9154. \fi}
  9155. {\if\edition\pythonEd
  9156. \[
  9157. \begin{array}{l}
  9158. \gray{\LintASTPython} \\ \hline
  9159. \gray{\LvarASTPython} \\ \hline
  9160. \gray{\LifASTPython} \\ \hline
  9161. \LwhileASTPython \\
  9162. \begin{array}{lcl}
  9163. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9164. \end{array}
  9165. \end{array}
  9166. \]
  9167. \fi}
  9168. \end{tcolorbox}
  9169. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9170. \label{fig:Lwhile-syntax}
  9171. \end{figure}
  9172. The concrete syntax of \LangLoop{} is defined in
  9173. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9174. in Figure~\ref{fig:Lwhile-syntax}.
  9175. %
  9176. The definitional interpreter for \LangLoop{} is shown in
  9177. Figure~\ref{fig:interp-Lwhile}.
  9178. %
  9179. {\if\edition\racketEd
  9180. %
  9181. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9182. and \code{Void} and we make changes to the cases for \code{Var} and
  9183. \code{Let} regarding variables. To support assignment to variables and
  9184. to make their lifetimes indefinite (see the second example in
  9185. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9186. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9187. value.
  9188. %
  9189. Now to discuss the new cases. For \code{SetBang}, we find the
  9190. variable in the environment to obtain a boxed value and then we change
  9191. it using \code{set-box!} to the result of evaluating the right-hand
  9192. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9193. %
  9194. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9195. if the result is true, 2) evaluate the body.
  9196. The result value of a \code{while} loop is also \code{\#<void>}.
  9197. %
  9198. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9199. subexpressions \itm{es} for their effects and then evaluates
  9200. and returns the result from \itm{body}.
  9201. %
  9202. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9203. %
  9204. \fi}
  9205. {\if\edition\pythonEd
  9206. %
  9207. We add a new case for \code{While} in the \code{interp\_stmts}
  9208. function, where we repeatedly interpret the \code{body} so long as the
  9209. \code{test} expression remains true.
  9210. %
  9211. \fi}
  9212. \begin{figure}[tbp]
  9213. \begin{tcolorbox}[colback=white]
  9214. {\if\edition\racketEd
  9215. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9216. (define interp-Lwhile-class
  9217. (class interp-Lif-class
  9218. (super-new)
  9219. (define/override ((interp-exp env) e)
  9220. (define recur (interp-exp env))
  9221. (match e
  9222. [(Let x e body)
  9223. (define new-env (dict-set env x (box (recur e))))
  9224. ((interp-exp new-env) body)]
  9225. [(Var x) (unbox (dict-ref env x))]
  9226. [(SetBang x rhs)
  9227. (set-box! (dict-ref env x) (recur rhs))]
  9228. [(WhileLoop cnd body)
  9229. (define (loop)
  9230. (cond [(recur cnd) (recur body) (loop)]
  9231. [else (void)]))
  9232. (loop)]
  9233. [(Begin es body)
  9234. (for ([e es]) (recur e))
  9235. (recur body)]
  9236. [(Void) (void)]
  9237. [else ((super interp-exp env) e)]))
  9238. ))
  9239. (define (interp-Lwhile p)
  9240. (send (new interp-Lwhile-class) interp-program p))
  9241. \end{lstlisting}
  9242. \fi}
  9243. {\if\edition\pythonEd
  9244. \begin{lstlisting}
  9245. class InterpLwhile(InterpLif):
  9246. def interp_stmts(self, ss, env):
  9247. if len(ss) == 0:
  9248. return
  9249. match ss[0]:
  9250. case While(test, body, []):
  9251. while self.interp_exp(test, env):
  9252. self.interp_stmts(body, env)
  9253. return self.interp_stmts(ss[1:], env)
  9254. case _:
  9255. return super().interp_stmts(ss, env)
  9256. \end{lstlisting}
  9257. \fi}
  9258. \end{tcolorbox}
  9259. \caption{Interpreter for \LangLoop{}.}
  9260. \label{fig:interp-Lwhile}
  9261. \end{figure}
  9262. The type checker for \LangLoop{} is defined in
  9263. Figure~\ref{fig:type-check-Lwhile}.
  9264. %
  9265. {\if\edition\racketEd
  9266. %
  9267. The type checking of the \code{SetBang} expression requires the type
  9268. of the variable and the right-hand-side to agree. The result type is
  9269. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  9270. and the result type is \code{Void}. For \code{Begin}, the result type
  9271. is the type of its last subexpression.
  9272. %
  9273. \fi}
  9274. %
  9275. {\if\edition\pythonEd
  9276. %
  9277. A \code{while} loop is well typed if the type of the \code{test}
  9278. expression is \code{bool} and the statements in the \code{body} are
  9279. well typed.
  9280. %
  9281. \fi}
  9282. \begin{figure}[tbp]
  9283. \begin{tcolorbox}[colback=white]
  9284. {\if\edition\racketEd
  9285. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9286. (define type-check-Lwhile-class
  9287. (class type-check-Lif-class
  9288. (super-new)
  9289. (inherit check-type-equal?)
  9290. (define/override (type-check-exp env)
  9291. (lambda (e)
  9292. (define recur (type-check-exp env))
  9293. (match e
  9294. [(SetBang x rhs)
  9295. (define-values (rhs^ rhsT) (recur rhs))
  9296. (define varT (dict-ref env x))
  9297. (check-type-equal? rhsT varT e)
  9298. (values (SetBang x rhs^) 'Void)]
  9299. [(WhileLoop cnd body)
  9300. (define-values (cnd^ Tc) (recur cnd))
  9301. (check-type-equal? Tc 'Boolean e)
  9302. (define-values (body^ Tbody) ((type-check-exp env) body))
  9303. (values (WhileLoop cnd^ body^) 'Void)]
  9304. [(Begin es body)
  9305. (define-values (es^ ts)
  9306. (for/lists (l1 l2) ([e es]) (recur e)))
  9307. (define-values (body^ Tbody) (recur body))
  9308. (values (Begin es^ body^) Tbody)]
  9309. [else ((super type-check-exp env) e)])))
  9310. ))
  9311. (define (type-check-Lwhile p)
  9312. (send (new type-check-Lwhile-class) type-check-program p))
  9313. \end{lstlisting}
  9314. \fi}
  9315. {\if\edition\pythonEd
  9316. \begin{lstlisting}
  9317. class TypeCheckLwhile(TypeCheckLif):
  9318. def type_check_stmts(self, ss, env):
  9319. if len(ss) == 0:
  9320. return
  9321. match ss[0]:
  9322. case While(test, body, []):
  9323. test_t = self.type_check_exp(test, env)
  9324. check_type_equal(bool, test_t, test)
  9325. body_t = self.type_check_stmts(body, env)
  9326. return self.type_check_stmts(ss[1:], env)
  9327. case _:
  9328. return super().type_check_stmts(ss, env)
  9329. \end{lstlisting}
  9330. \fi}
  9331. \end{tcolorbox}
  9332. \caption{Type checker for the \LangLoop{} language.}
  9333. \label{fig:type-check-Lwhile}
  9334. \end{figure}
  9335. {\if\edition\racketEd
  9336. %
  9337. At first glance, the translation of these language features to x86
  9338. seems straightforward because the \LangCIf{} intermediate language
  9339. already supports all of the ingredients that we need: assignment,
  9340. \code{goto}, conditional branching, and sequencing. However, there are
  9341. complications that arise which we discuss in the next section. After
  9342. that we introduce the changes necessary to the existing passes.
  9343. %
  9344. \fi}
  9345. {\if\edition\pythonEd
  9346. %
  9347. At first glance, the translation of \code{while} loops to x86 seems
  9348. straightforward because the \LangCIf{} intermediate language already
  9349. supports \code{goto} and conditional branching. However, there are
  9350. complications that arise which we discuss in the next section. After
  9351. that we introduce the changes necessary to the existing passes.
  9352. %
  9353. \fi}
  9354. \section{Cyclic Control Flow and Dataflow Analysis}
  9355. \label{sec:dataflow-analysis}
  9356. Up until this point the programs generated in
  9357. \code{explicate\_control} were guaranteed to be acyclic. However, each
  9358. \code{while} loop introduces a cycle. But does that matter?
  9359. %
  9360. Indeed it does. Recall that for register allocation, the compiler
  9361. performs liveness analysis to determine which variables can share the
  9362. same register. To accomplish this we analyzed the control-flow graph
  9363. in reverse topological order
  9364. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9365. only well-defined for acyclic graphs.
  9366. Let us return to the example of computing the sum of the first five
  9367. positive integers. Here is the program after instruction selection but
  9368. before register allocation.
  9369. \begin{center}
  9370. {\if\edition\racketEd
  9371. \begin{minipage}{0.45\textwidth}
  9372. \begin{lstlisting}
  9373. (define (main) : Integer
  9374. mainstart:
  9375. movq $0, sum
  9376. movq $5, i
  9377. jmp block5
  9378. block5:
  9379. movq i, tmp3
  9380. cmpq tmp3, $0
  9381. jl block7
  9382. jmp block8
  9383. \end{lstlisting}
  9384. \end{minipage}
  9385. \begin{minipage}{0.45\textwidth}
  9386. \begin{lstlisting}
  9387. block7:
  9388. addq i, sum
  9389. movq $1, tmp4
  9390. negq tmp4
  9391. addq tmp4, i
  9392. jmp block5
  9393. block8:
  9394. movq $27, %rax
  9395. addq sum, %rax
  9396. jmp mainconclusion
  9397. )
  9398. \end{lstlisting}
  9399. \end{minipage}
  9400. \fi}
  9401. {\if\edition\pythonEd
  9402. \begin{minipage}{0.45\textwidth}
  9403. \begin{lstlisting}
  9404. mainstart:
  9405. movq $0, sum
  9406. movq $5, i
  9407. jmp block5
  9408. block5:
  9409. cmpq $0, i
  9410. jg block7
  9411. jmp block8
  9412. \end{lstlisting}
  9413. \end{minipage}
  9414. \begin{minipage}{0.45\textwidth}
  9415. \begin{lstlisting}
  9416. block7:
  9417. addq i, sum
  9418. subq $1, i
  9419. jmp block5
  9420. block8:
  9421. movq sum, %rdi
  9422. callq print_int
  9423. movq $0, %rax
  9424. jmp mainconclusion
  9425. \end{lstlisting}
  9426. \end{minipage}
  9427. \fi}
  9428. \end{center}
  9429. Recall that liveness analysis works backwards, starting at the end
  9430. of each function. For this example we could start with \code{block8}
  9431. because we know what is live at the beginning of the conclusion,
  9432. just \code{rax} and \code{rsp}. So the live-before set
  9433. for \code{block8} is \code{\{rsp,sum\}}.
  9434. %
  9435. Next we might try to analyze \code{block5} or \code{block7}, but
  9436. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9437. we are stuck.
  9438. The way out of this impasse is to realize that we can compute an
  9439. under-approximation of each live-before set by starting with empty
  9440. live-after sets. By \emph{under-approximation}, we mean that the set
  9441. only contains variables that are live for some execution of the
  9442. program, but the set may be missing some variables that are live.
  9443. Next, the under-approximations for each block can be improved by 1)
  9444. updating the live-after set for each block using the approximate
  9445. live-before sets from the other blocks and 2) perform liveness
  9446. analysis again on each block. In fact, by iterating this process, the
  9447. under-approximations eventually become the correct solutions!
  9448. %
  9449. This approach of iteratively analyzing a control-flow graph is
  9450. applicable to many static analysis problems and goes by the name
  9451. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9452. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9453. Washington.
  9454. Let us apply this approach to the above example. We use the empty set
  9455. for the initial live-before set for each block. Let $m_0$ be the
  9456. following mapping from label names to sets of locations (variables and
  9457. registers).
  9458. \begin{center}
  9459. \begin{lstlisting}
  9460. mainstart: {}, block5: {}, block7: {}, block8: {}
  9461. \end{lstlisting}
  9462. \end{center}
  9463. Using the above live-before approximations, we determine the
  9464. live-after for each block and then apply liveness analysis to each
  9465. block. This produces our next approximation $m_1$ of the live-before
  9466. sets.
  9467. \begin{center}
  9468. \begin{lstlisting}
  9469. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9470. \end{lstlisting}
  9471. \end{center}
  9472. For the second round, the live-after for \code{mainstart} is the
  9473. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9474. liveness analysis for \code{mainstart} computes the empty set. The
  9475. live-after for \code{block5} is the union of the live-before sets for
  9476. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9477. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9478. sum\}}. The live-after for \code{block7} is the live-before for
  9479. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9480. So the liveness analysis for \code{block7} remains \code{\{i,
  9481. sum\}}. Together these yield the following approximation $m_2$ of
  9482. the live-before sets.
  9483. \begin{center}
  9484. \begin{lstlisting}
  9485. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9486. \end{lstlisting}
  9487. \end{center}
  9488. In the preceding iteration, only \code{block5} changed, so we can
  9489. limit our attention to \code{mainstart} and \code{block7}, the two
  9490. blocks that jump to \code{block5}. As a result, the live-before sets
  9491. for \code{mainstart} and \code{block7} are updated to include
  9492. \code{rsp}, yielding the following approximation $m_3$.
  9493. \begin{center}
  9494. \begin{lstlisting}
  9495. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9496. \end{lstlisting}
  9497. \end{center}
  9498. Because \code{block7} changed, we analyze \code{block5} once more, but
  9499. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9500. our approximations have converged, so $m_3$ is the solution.
  9501. This iteration process is guaranteed to converge to a solution by the
  9502. Kleene Fixed-Point Theorem, a general theorem about functions on
  9503. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9504. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9505. elements, a least element $\bot$ (pronounced bottom), and a join
  9506. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9507. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9508. working with join semi-lattices.} When two elements are ordered $m_i
  9509. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9510. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9511. approximation than $m_i$. The bottom element $\bot$ represents the
  9512. complete lack of information, i.e., the worst approximation. The join
  9513. operator takes two lattice elements and combines their information,
  9514. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9515. bound}
  9516. A dataflow analysis typically involves two lattices: one lattice to
  9517. represent abstract states and another lattice that aggregates the
  9518. abstract states of all the blocks in the control-flow graph. For
  9519. liveness analysis, an abstract state is a set of locations. We form
  9520. the lattice $L$ by taking its elements to be sets of locations, the
  9521. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9522. set, and the join operator to be set union.
  9523. %
  9524. We form a second lattice $M$ by taking its elements to be mappings
  9525. from the block labels to sets of locations (elements of $L$). We
  9526. order the mappings point-wise, using the ordering of $L$. So given any
  9527. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9528. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9529. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9530. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9531. We can think of one iteration of liveness analysis applied to the
  9532. whole program as being a function $f$ on the lattice $M$. It takes a
  9533. mapping as input and computes a new mapping.
  9534. \[
  9535. f(m_i) = m_{i+1}
  9536. \]
  9537. Next let us think for a moment about what a final solution $m_s$
  9538. should look like. If we perform liveness analysis using the solution
  9539. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9540. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9541. \[
  9542. f(m_s) = m_s
  9543. \]
  9544. Furthermore, the solution should only include locations that are
  9545. forced to be there by performing liveness analysis on the program, so
  9546. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9547. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9548. monotone (better inputs produce better outputs), then the least fixed
  9549. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9550. chain} obtained by starting at $\bot$ and iterating $f$ as
  9551. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9552. \[
  9553. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9554. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9555. \]
  9556. When a lattice contains only finitely-long ascending chains, then
  9557. every Kleene chain tops out at some fixed point after some number of
  9558. iterations of $f$.
  9559. \[
  9560. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9561. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9562. \]
  9563. The liveness analysis is indeed a monotone function and the lattice
  9564. $M$ only has finitely-long ascending chains because there are only a
  9565. finite number of variables and blocks in the program. Thus we are
  9566. guaranteed that iteratively applying liveness analysis to all blocks
  9567. in the program will eventually produce the least fixed point solution.
  9568. Next let us consider dataflow analysis in general and discuss the
  9569. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9570. %
  9571. The algorithm has four parameters: the control-flow graph \code{G}, a
  9572. function \code{transfer} that applies the analysis to one block, the
  9573. \code{bottom} and \code{join} operator for the lattice of abstract
  9574. states. The \code{analyze\_dataflow} function is formulated as a
  9575. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9576. function come from the predecessor nodes in the control-flow
  9577. graph. However, liveness analysis is a \emph{backward} dataflow
  9578. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9579. function with the transpose of the control-flow graph.
  9580. The algorithm begins by creating the bottom mapping, represented by a
  9581. hash table. It then pushes all of the nodes in the control-flow graph
  9582. onto the work list (a queue). The algorithm repeats the \code{while}
  9583. loop as long as there are items in the work list. In each iteration, a
  9584. node is popped from the work list and processed. The \code{input} for
  9585. the node is computed by taking the join of the abstract states of all
  9586. the predecessor nodes. The \code{transfer} function is then applied to
  9587. obtain the \code{output} abstract state. If the output differs from
  9588. the previous state for this block, the mapping for this block is
  9589. updated and its successor nodes are pushed onto the work list.
  9590. \begin{figure}[tb]
  9591. \begin{tcolorbox}[colback=white]
  9592. {\if\edition\racketEd
  9593. \begin{lstlisting}
  9594. (define (analyze_dataflow G transfer bottom join)
  9595. (define mapping (make-hash))
  9596. (for ([v (in-vertices G)])
  9597. (dict-set! mapping v bottom))
  9598. (define worklist (make-queue))
  9599. (for ([v (in-vertices G)])
  9600. (enqueue! worklist v))
  9601. (define trans-G (transpose G))
  9602. (while (not (queue-empty? worklist))
  9603. (define node (dequeue! worklist))
  9604. (define input (for/fold ([state bottom])
  9605. ([pred (in-neighbors trans-G node)])
  9606. (join state (dict-ref mapping pred))))
  9607. (define output (transfer node input))
  9608. (cond [(not (equal? output (dict-ref mapping node)))
  9609. (dict-set! mapping node output)
  9610. (for ([v (in-neighbors G node)])
  9611. (enqueue! worklist v))]))
  9612. mapping)
  9613. \end{lstlisting}
  9614. \fi}
  9615. {\if\edition\pythonEd
  9616. \begin{lstlisting}
  9617. def analyze_dataflow(G, transfer, bottom, join):
  9618. trans_G = transpose(G)
  9619. mapping = dict((v, bottom) for v in G.vertices())
  9620. worklist = deque(G.vertices)
  9621. while worklist:
  9622. node = worklist.pop()
  9623. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9624. output = transfer(node, input)
  9625. if output != mapping[node]:
  9626. mapping[node] = output
  9627. worklist.extend(G.adjacent(node))
  9628. \end{lstlisting}
  9629. \fi}
  9630. \end{tcolorbox}
  9631. \caption{Generic work list algorithm for dataflow analysis}
  9632. \label{fig:generic-dataflow}
  9633. \end{figure}
  9634. {\if\edition\racketEd
  9635. \section{Mutable Variables \& Remove Complex Operands}
  9636. There is a subtle interaction between the
  9637. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  9638. and the left-to-right order of evaluation of Racket. Consider the
  9639. following example.
  9640. \begin{lstlisting}
  9641. (let ([x 2])
  9642. (+ x (begin (set! x 40) x)))
  9643. \end{lstlisting}
  9644. The result of this program is \code{42} because the first read from
  9645. \code{x} produces \code{2} and the second produces \code{40}. However,
  9646. if we naively apply the \code{remove\_complex\_operands} pass to this
  9647. example we obtain the following program whose result is \code{80}!
  9648. \begin{lstlisting}
  9649. (let ([x 2])
  9650. (let ([tmp (begin (set! x 40) x)])
  9651. (+ x tmp)))
  9652. \end{lstlisting}
  9653. The problem is that, with mutable variables, the ordering between
  9654. reads and writes is important, and the
  9655. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9656. before the first read of \code{x}.
  9657. We recommend solving this problem by giving special treatment to reads
  9658. from mutable variables, that is, variables that occur on the left-hand
  9659. side of a \code{set!}. We mark each read from a mutable variable with
  9660. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9661. that the read operation is effectful in that it can produce different
  9662. results at different points in time. Let's apply this idea to the
  9663. following variation that also involves a variable that is not mutated.
  9664. % loop_test_24.rkt
  9665. \begin{lstlisting}
  9666. (let ([x 2])
  9667. (let ([y 0])
  9668. (+ y (+ x (begin (set! x 40) x)))))
  9669. \end{lstlisting}
  9670. We first analyze the above program to discover that variable \code{x}
  9671. is mutable but \code{y} is not. We then transform the program as
  9672. follows, replacing each occurrence of \code{x} with \code{(get! x)}.
  9673. \begin{lstlisting}
  9674. (let ([x 2])
  9675. (let ([y 0])
  9676. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9677. \end{lstlisting}
  9678. Now that we have a clear distinction between reads from mutable and
  9679. immutable variables, we can apply the \code{remove\_complex\_operands}
  9680. pass, where reads from immutable variables are still classified as
  9681. atomic expressions but reads from mutable variables are classified as
  9682. complex. Thus, \code{remove\_complex\_operands} yields the following
  9683. program.\\
  9684. \begin{minipage}{\textwidth}
  9685. \begin{lstlisting}
  9686. (let ([x 2])
  9687. (let ([y 0])
  9688. (+ y (let ([t1 (get! x)])
  9689. (let ([t2 (begin (set! x 40) (get! x))])
  9690. (+ t1 t2))))))
  9691. \end{lstlisting}
  9692. \end{minipage}
  9693. The temporary variable \code{t1} gets the value of \code{x} before the
  9694. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9695. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9696. do not generate a temporary variable for the occurrence of \code{y}
  9697. because it's an immutable variable. We want to avoid such unnecessary
  9698. extra temporaries because they would needless increase the number of
  9699. variables, making it more likely for some of them to be spilled. The
  9700. result of this program is \code{42}, the same as the result prior to
  9701. \code{remove\_complex\_operands}.
  9702. The approach that we've sketched above requires only a small
  9703. modification to \code{remove\_complex\_operands} to handle
  9704. \code{get!}. However, it requires a new pass, called
  9705. \code{uncover-get!}, that we discuss in
  9706. Section~\ref{sec:uncover-get-bang}.
  9707. As an aside, this problematic interaction between \code{set!} and the
  9708. pass \code{remove\_complex\_operands} is particular to Racket and not
  9709. its predecessor, the Scheme language. The key difference is that
  9710. Scheme does not specify an order of evaluation for the arguments of an
  9711. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9712. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9713. would be correct results for the example program. Interestingly,
  9714. Racket is implemented on top of the Chez Scheme
  9715. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9716. presented in this section (using extra \code{let} bindings to control
  9717. the order of evaluation) is used in the translation from Racket to
  9718. Scheme~\citep{Flatt:2019tb}.
  9719. \fi} % racket
  9720. Having discussed the complications that arise from adding support for
  9721. assignment and loops, we turn to discussing the individual compilation
  9722. passes.
  9723. {\if\edition\racketEd
  9724. \section{Uncover \texttt{get!}}
  9725. \label{sec:uncover-get-bang}
  9726. The goal of this pass it to mark uses of mutable variables so that
  9727. \code{remove\_complex\_operands} can treat them as complex expressions
  9728. and thereby preserve their ordering relative to the side-effects in
  9729. other operands. So the first step is to collect all the mutable
  9730. variables. We recommend creating an auxiliary function for this,
  9731. named \code{collect-set!}, that recursively traverses expressions,
  9732. returning the set of all variables that occur on the left-hand side of a
  9733. \code{set!}. Here's an excerpt of its implementation.
  9734. \begin{center}
  9735. \begin{minipage}{\textwidth}
  9736. \begin{lstlisting}
  9737. (define (collect-set! e)
  9738. (match e
  9739. [(Var x) (set)]
  9740. [(Int n) (set)]
  9741. [(Let x rhs body)
  9742. (set-union (collect-set! rhs) (collect-set! body))]
  9743. [(SetBang var rhs)
  9744. (set-union (set var) (collect-set! rhs))]
  9745. ...))
  9746. \end{lstlisting}
  9747. \end{minipage}
  9748. \end{center}
  9749. By placing this pass after \code{uniquify}, we need not worry about
  9750. variable shadowing and our logic for \code{Let} can remain simple, as
  9751. in the excerpt above.
  9752. The second step is to mark the occurrences of the mutable variables
  9753. with the new \code{GetBang} AST node (\code{get!} in concrete
  9754. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  9755. function, which takes two parameters: the set of mutable variables
  9756. \code{set!-vars}, and the expression \code{e} to be processed. The
  9757. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9758. mutable variable or leaves it alone if not.
  9759. \begin{center}
  9760. \begin{minipage}{\textwidth}
  9761. \begin{lstlisting}
  9762. (define ((uncover-get!-exp set!-vars) e)
  9763. (match e
  9764. [(Var x)
  9765. (if (set-member? set!-vars x)
  9766. (GetBang x)
  9767. (Var x))]
  9768. ...))
  9769. \end{lstlisting}
  9770. \end{minipage}
  9771. \end{center}
  9772. To wrap things up, define the \code{uncover-get!} function for
  9773. processing a whole program, using \code{collect-set!} to obtain the
  9774. set of mutable variables and then \code{uncover-get!-exp} to replace
  9775. their occurrences with \code{GetBang}.
  9776. \fi}
  9777. \section{Remove Complex Operands}
  9778. \label{sec:rco-loop}
  9779. {\if\edition\racketEd
  9780. %
  9781. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9782. \code{while} are all complex expressions. The subexpressions of
  9783. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9784. %
  9785. \fi}
  9786. {\if\edition\pythonEd
  9787. %
  9788. The change needed for this pass is to add a case for the \code{while}
  9789. statement. The condition of a \code{while} loop is allowed to be a
  9790. complex expression, just like the condition of the \code{if}
  9791. statement.
  9792. %
  9793. \fi}
  9794. %
  9795. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  9796. \LangLoopANF{} of this pass.
  9797. \newcommand{\LwhileMonadASTRacket}{
  9798. \begin{array}{rcl}
  9799. \Atm &::=& \VOID{} \\
  9800. \Exp &::=& \GETBANG{\Var}
  9801. \MID \SETBANG{\Var}{\Exp}
  9802. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9803. &\MID& \WHILE{\Exp}{\Exp}
  9804. \end{array}
  9805. }
  9806. \newcommand{\LwhileMonadASTPython}{
  9807. \begin{array}{rcl}
  9808. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9809. \end{array}
  9810. }
  9811. \begin{figure}[tp]
  9812. \centering
  9813. \begin{tcolorbox}[colback=white]
  9814. \small
  9815. {\if\edition\racketEd
  9816. \[
  9817. \begin{array}{l}
  9818. \gray{\LvarMonadASTRacket} \\ \hline
  9819. \gray{\LifMonadASTRacket} \\ \hline
  9820. \LwhileMonadASTRacket \\
  9821. \begin{array}{rcl}
  9822. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  9823. \end{array}
  9824. \end{array}
  9825. \]
  9826. \fi}
  9827. {\if\edition\pythonEd
  9828. \[
  9829. \begin{array}{l}
  9830. \gray{\LvarMonadASTPython} \\ \hline
  9831. \gray{\LifMonadASTPython} \\ \hline
  9832. \LwhileMonadASTPython \\
  9833. \begin{array}{rcl}
  9834. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9835. \end{array}
  9836. \end{array}
  9837. %% \begin{array}{rcl}
  9838. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9839. %% \Exp &::=& \Atm \MID \READ{} \\
  9840. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9841. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9842. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9843. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9844. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9845. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9846. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9847. %% \end{array}
  9848. \]
  9849. \fi}
  9850. \end{tcolorbox}
  9851. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9852. \label{fig:Lwhile-anf-syntax}
  9853. \end{figure}
  9854. {\if\edition\racketEd
  9855. %
  9856. As usual, when a complex expression appears in a grammar position that
  9857. needs to be atomic, such as the argument of a primitive operator, we
  9858. must introduce a temporary variable and bind it to the complex
  9859. expression. This approach applies, unchanged, to handle the new
  9860. language forms. For example, in the following code there are two
  9861. \code{begin} expressions appearing as arguments to the \code{+}
  9862. operator. The output of \code{rco\_exp} is shown below, in which the
  9863. \code{begin} expressions have been bound to temporary
  9864. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  9865. allowed to have arbitrary expressions in their right-hand-side
  9866. expression, so it is fine to place \code{begin} there.
  9867. %
  9868. \begin{center}
  9869. \begin{tabular}{lcl}
  9870. \begin{minipage}{0.4\textwidth}
  9871. \begin{lstlisting}
  9872. (let ([x2 10])
  9873. (let ([y3 0])
  9874. (+ (+ (begin
  9875. (set! y3 (read))
  9876. (get! x2))
  9877. (begin
  9878. (set! x2 (read))
  9879. (get! y3)))
  9880. (get! x2))))
  9881. \end{lstlisting}
  9882. \end{minipage}
  9883. &
  9884. $\Rightarrow$
  9885. &
  9886. \begin{minipage}{0.4\textwidth}
  9887. \begin{lstlisting}
  9888. (let ([x2 10])
  9889. (let ([y3 0])
  9890. (let ([tmp4 (begin
  9891. (set! y3 (read))
  9892. x2)])
  9893. (let ([tmp5 (begin
  9894. (set! x2 (read))
  9895. y3)])
  9896. (let ([tmp6 (+ tmp4 tmp5)])
  9897. (let ([tmp7 x2])
  9898. (+ tmp6 tmp7)))))))
  9899. \end{lstlisting}
  9900. \end{minipage}
  9901. \end{tabular}
  9902. \end{center}
  9903. \fi}
  9904. \section{Explicate Control \racket{and \LangCLoop{}}}
  9905. \label{sec:explicate-loop}
  9906. \newcommand{\CloopASTRacket}{
  9907. \begin{array}{lcl}
  9908. \Atm &::=& \VOID \\
  9909. \Stmt &::=& \READ{}
  9910. \end{array}
  9911. }
  9912. {\if\edition\racketEd
  9913. Recall that in the \code{explicate\_control} pass we define one helper
  9914. function for each kind of position in the program. For the \LangVar{}
  9915. language of integers and variables we needed assignment and tail
  9916. positions. The \code{if} expressions of \LangIf{} introduced predicate
  9917. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  9918. another kind of position: effect position. Except for the last
  9919. subexpression, the subexpressions inside a \code{begin} are evaluated
  9920. only for their effect. Their result values are discarded. We can
  9921. generate better code by taking this fact into account.
  9922. The output language of \code{explicate\_control} is \LangCLoop{}
  9923. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9924. \LangCIf{}. The only syntactic difference is the addition of \VOID{}
  9925. and that \code{read} may appear as a statement. The most significant
  9926. difference between the programs generated by \code{explicate\_control}
  9927. in Chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  9928. chapter is that the control-flow graphs of the later may contain
  9929. cycles.
  9930. \begin{figure}[tp]
  9931. \begin{tcolorbox}[colback=white]
  9932. \small
  9933. \[
  9934. \begin{array}{l}
  9935. \gray{\CvarASTRacket} \\ \hline
  9936. \gray{\CifASTRacket} \\ \hline
  9937. \CloopASTRacket \\
  9938. \begin{array}{lcl}
  9939. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9940. \end{array}
  9941. \end{array}
  9942. \]
  9943. \end{tcolorbox}
  9944. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9945. \label{fig:c7-syntax}
  9946. \end{figure}
  9947. The new auxiliary function \code{explicate\_effect} takes an
  9948. expression (in an effect position) and the code for its
  9949. continuation. The function returns a $\Tail$ that includes the
  9950. generated code for the input expression followed by the
  9951. continuation. If the expression is obviously pure, that is, never
  9952. causes side effects, then the expression can be removed, so the result
  9953. is just the continuation.
  9954. %
  9955. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  9956. interesting; the generated code is depicted in the following diagram.
  9957. \begin{center}
  9958. \begin{minipage}{0.3\textwidth}
  9959. \xymatrix{
  9960. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  9961. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  9962. & *+[F]{\txt{\itm{cont}}} \\
  9963. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  9964. }
  9965. \end{minipage}
  9966. \end{center}
  9967. We start by creating a fresh label $\itm{loop}$ for the top of the
  9968. loop. Next, recursively process the \itm{body} (in effect position)
  9969. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  9970. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  9971. \itm{body'} as the then-branch and the continuation block as the
  9972. else-branch. The result should be added to the dictionary of
  9973. \code{basic-blocks} with the label \itm{loop}. The result for the
  9974. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  9975. The auxiliary functions for tail, assignment, and predicate positions
  9976. need to be updated. The three new language forms, \code{while},
  9977. \code{set!}, and \code{begin}, can appear in assignment and tail
  9978. positions. Only \code{begin} may appear in predicate positions; the
  9979. other two have result type \code{Void}.
  9980. \fi}
  9981. %
  9982. {\if\edition\pythonEd
  9983. %
  9984. The output of this pass is the language \LangCIf{}. No new language
  9985. features are needed in the output because a \code{while} loop can be
  9986. expressed in terms of \code{goto} and \code{if} statements, which are
  9987. already in \LangCIf{}.
  9988. %
  9989. Add a case for the \code{while} statement to the
  9990. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9991. the condition expression.
  9992. %
  9993. \fi}
  9994. {\if\edition\racketEd
  9995. \section{Select Instructions}
  9996. \label{sec:select-instructions-loop}
  9997. Only two small additions are needed in the \code{select\_instructions}
  9998. pass to handle the changes to \LangCLoop{}. First, to handle the
  9999. addition of \VOID{} we simply translate it to \code{0}. Second,
  10000. \code{read} may appear as a stand-alone statement instead of only
  10001. appearing on the right-hand side of an assignment statement. The code
  10002. generation is nearly identical to the one for assignment; just leave
  10003. off the instruction for moving the result into the left-hand side.
  10004. \fi}
  10005. \section{Register Allocation}
  10006. \label{sec:register-allocation-loop}
  10007. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10008. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10009. which complicates the liveness analysis needed for register
  10010. allocation.
  10011. %
  10012. We recommend using the generic \code{analyze\_dataflow} function that
  10013. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10014. perform liveness analysis, replacing the code in
  10015. \code{uncover\_live} that processed the basic blocks in topological
  10016. order (Section~\ref{sec:liveness-analysis-Lif}).
  10017. The \code{analyze\_dataflow} function has four parameters.
  10018. \begin{enumerate}
  10019. \item The first parameter \code{G} should be passed the transpose
  10020. of the control-flow graph.
  10021. \item The second parameter \code{transfer} should be passed a function
  10022. that applies liveness analysis to a basic block. It takes two
  10023. parameters: the label for the block to analyze and the live-after
  10024. set for that block. The transfer function should return the
  10025. live-before set for the block.
  10026. %
  10027. \racket{Also, as a side-effect, it should update the block's
  10028. $\itm{info}$ with the liveness information for each instruction.}
  10029. %
  10030. \python{Also, as a side-effect, it should update the live-before and
  10031. live-after sets for each instruction.}
  10032. %
  10033. To implement the \code{transfer} function, you should be able to
  10034. reuse the code you already have for analyzing basic blocks.
  10035. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10036. \code{bottom} and \code{join} for the lattice of abstract states,
  10037. i.e. sets of locations. For liveness analysis, the bottom of the
  10038. lattice is the empty set and the join operator is set union.
  10039. \end{enumerate}
  10040. \begin{figure}[p]
  10041. \begin{tcolorbox}[colback=white]
  10042. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10043. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10044. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10045. %\node (Lfun-3) at (6,2) {\large \LangLoop{}};
  10046. %\node (Lfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10047. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10048. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10049. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10050. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10051. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10052. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10053. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10054. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  10055. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  10056. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  10057. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  10058. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  10059. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  10060. %% \path[->,bend left=15] (Lfun) edge [above] node
  10061. %% {\ttfamily\footnotesize type-check} (Lfun-2);
  10062. \path[->,bend left=15] (Lfun) edge [above] node
  10063. {\ttfamily\footnotesize shrink} (Lfun-2);
  10064. \path[->,bend left=15] (Lfun-2) edge [above] node
  10065. {\ttfamily\footnotesize uniquify} (F1-4);
  10066. %% \path[->,bend left=15] (Lfun-3) edge [above] node
  10067. %% {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  10068. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10069. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  10070. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10071. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  10072. %% \path[->,bend right=15] (F1-2) edge [above] node
  10073. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  10074. %% \path[->,bend right=15] (F1-3) edge [above] node
  10075. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10076. \path[->,bend left=15] (F1-4) edge [above] node
  10077. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10078. \path[->,bend left=15] (F1-5) edge [right] node
  10079. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  10080. \path[->,bend right=15] (F1-6) edge [above] node
  10081. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10082. \path[->,bend left=15] (C3-2) edge [left] node
  10083. {\ttfamily\footnotesize select\_instr.} (x86-2);
  10084. \path[->,bend right=15] (x86-2) edge [left] node
  10085. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10086. \path[->,bend right=15] (x86-2-1) edge [below] node
  10087. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  10088. \path[->,bend right=15] (x86-2-2) edge [left] node
  10089. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  10090. \path[->,bend left=15] (x86-3) edge [above] node
  10091. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  10092. \path[->,bend left=15] (x86-4) edge [right] node
  10093. {\ttfamily\footnotesize pre.\_and\_concl.} (x86-5);
  10094. \end{tikzpicture}
  10095. \end{tcolorbox}
  10096. \caption{Diagram of the passes for \LangLoop{}.}
  10097. \label{fig:Lwhile-passes}
  10098. \end{figure}
  10099. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10100. for the compilation of \LangLoop{}.
  10101. % Further Reading: dataflow analysis
  10102. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10103. \chapter{Tuples and Garbage Collection}
  10104. \label{ch:Lvec}
  10105. \index{subject}{tuple}
  10106. \index{subject}{vector}
  10107. \index{subject}{allocate}
  10108. \index{subject}{heap allocate}
  10109. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10110. %% all the IR grammars are spelled out! \\ --Jeremy}
  10111. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10112. %% the root stack. \\ --Jeremy}
  10113. In this chapter we study the implementation of tuples\racket{, called
  10114. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10115. where each element may have a different type.
  10116. %
  10117. This language feature is the first to use the computer's
  10118. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  10119. indefinite, that is, a tuple lives forever from the programmer's
  10120. viewpoint. Of course, from an implementer's viewpoint, it is important
  10121. to reclaim the space associated with a tuple when it is no longer
  10122. needed, which is why we also study \emph{garbage collection}
  10123. \index{garbage collection} techniques in this chapter.
  10124. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  10125. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10126. language of Chapter~\ref{ch:Lwhile} with tuples.
  10127. %
  10128. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10129. copying live tuples back and forth between two halves of the heap. The
  10130. garbage collector requires coordination with the compiler so that it
  10131. can find all of the live tuples.
  10132. %
  10133. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10134. discuss the necessary changes and additions to the compiler passes,
  10135. including a new compiler pass named \code{expose\_allocation}.
  10136. \section{The \LangVec{} Language}
  10137. \label{sec:r3}
  10138. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  10139. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  10140. %
  10141. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10142. creating a tuple, \code{vector-ref} for reading an element of a
  10143. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10144. \code{vector-length} for obtaining the number of elements of a
  10145. tuple.}
  10146. %
  10147. \python{The \LangVec{} language adds 1) tuple creation via a
  10148. comma-separated list of expressions, 2) accessing an element of a
  10149. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10150. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10151. operator, and 4) obtaining the number of elements (the length) of a
  10152. tuple. In this chapter, we restrict access indices to constant
  10153. integers.}
  10154. %
  10155. The program below shows an example use of tuples. It creates a tuple
  10156. \code{t} containing the elements \code{40},
  10157. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10158. contains just \code{2}. The element at index $1$ of \code{t} is
  10159. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  10160. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10161. to which we add \code{2}, the element at index $0$ of the tuple. So
  10162. the result of the program is \code{42}.
  10163. %
  10164. {\if\edition\racketEd
  10165. \begin{lstlisting}
  10166. (let ([t (vector 40 #t (vector 2))])
  10167. (if (vector-ref t 1)
  10168. (+ (vector-ref t 0)
  10169. (vector-ref (vector-ref t 2) 0))
  10170. 44))
  10171. \end{lstlisting}
  10172. \fi}
  10173. {\if\edition\pythonEd
  10174. \begin{lstlisting}
  10175. t = 40, True, (2,)
  10176. print( t[0] + t[2][0] if t[1] else 44 )
  10177. \end{lstlisting}
  10178. \fi}
  10179. \newcommand{\LtupGrammarRacket}{
  10180. \begin{array}{lcl}
  10181. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10182. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  10183. \MID \LP\key{vector-length}\;\Exp\RP \\
  10184. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10185. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10186. \end{array}
  10187. }
  10188. \newcommand{\LtupASTRacket}{
  10189. \begin{array}{lcl}
  10190. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10191. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10192. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10193. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10194. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10195. \end{array}
  10196. }
  10197. \newcommand{\LtupGrammarPython}{
  10198. \begin{array}{rcl}
  10199. \itm{cmp} &::= & \key{is} \\
  10200. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10201. \end{array}
  10202. }
  10203. \newcommand{\LtupASTPython}{
  10204. \begin{array}{lcl}
  10205. \itm{cmp} &::= & \code{Is()} \\
  10206. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10207. &\MID& \LEN{\Exp}
  10208. \end{array}
  10209. }
  10210. \begin{figure}[tbp]
  10211. \centering
  10212. \begin{tcolorbox}[colback=white]
  10213. \small
  10214. {\if\edition\racketEd
  10215. \[
  10216. \begin{array}{l}
  10217. \gray{\LintGrammarRacket{}} \\ \hline
  10218. \gray{\LvarGrammarRacket{}} \\ \hline
  10219. \gray{\LifGrammarRacket{}} \\ \hline
  10220. \gray{\LwhileGrammarRacket} \\ \hline
  10221. \LtupGrammarRacket \\
  10222. \begin{array}{lcl}
  10223. \LangVecM{} &::=& \Exp
  10224. \end{array}
  10225. \end{array}
  10226. \]
  10227. \fi}
  10228. {\if\edition\pythonEd
  10229. \[
  10230. \begin{array}{l}
  10231. \gray{\LintGrammarPython{}} \\ \hline
  10232. \gray{\LvarGrammarPython{}} \\ \hline
  10233. \gray{\LifGrammarPython{}} \\ \hline
  10234. \gray{\LwhileGrammarPython} \\ \hline
  10235. \LtupGrammarPython \\
  10236. \begin{array}{rcl}
  10237. \LangVecM{} &::=& \Stmt^{*}
  10238. \end{array}
  10239. \end{array}
  10240. \]
  10241. \fi}
  10242. \end{tcolorbox}
  10243. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10244. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10245. \label{fig:Lvec-concrete-syntax}
  10246. \end{figure}
  10247. \begin{figure}[tp]
  10248. \centering
  10249. \begin{tcolorbox}[colback=white]
  10250. \small
  10251. {\if\edition\racketEd
  10252. \[
  10253. \begin{array}{l}
  10254. \gray{\LintOpAST} \\ \hline
  10255. \gray{\LvarASTRacket{}} \\ \hline
  10256. \gray{\LifASTRacket{}} \\ \hline
  10257. \gray{\LwhileASTRacket{}} \\ \hline
  10258. \LtupASTRacket{} \\
  10259. \begin{array}{lcl}
  10260. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10261. \end{array}
  10262. \end{array}
  10263. \]
  10264. \fi}
  10265. {\if\edition\pythonEd
  10266. \[
  10267. \begin{array}{l}
  10268. \gray{\LintASTPython} \\ \hline
  10269. \gray{\LvarASTPython} \\ \hline
  10270. \gray{\LifASTPython} \\ \hline
  10271. \gray{\LwhileASTPython} \\ \hline
  10272. \LtupASTPython \\
  10273. \begin{array}{lcl}
  10274. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10275. \end{array}
  10276. \end{array}
  10277. \]
  10278. \fi}
  10279. \end{tcolorbox}
  10280. \caption{The abstract syntax of \LangVec{}.}
  10281. \label{fig:Lvec-syntax}
  10282. \end{figure}
  10283. Tuples raise several interesting new issues. First, variable binding
  10284. performs a shallow-copy when dealing with tuples, which means that
  10285. different variables can refer to the same tuple, that is, two
  10286. variables can be \emph{aliases}\index{subject}{alias} for the same
  10287. entity. Consider the following example in which both \code{t1} and
  10288. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10289. different tuple value but with equal elements. The result of the
  10290. program is \code{42}.
  10291. \begin{center}
  10292. \begin{minipage}{0.96\textwidth}
  10293. {\if\edition\racketEd
  10294. \begin{lstlisting}
  10295. (let ([t1 (vector 3 7)])
  10296. (let ([t2 t1])
  10297. (let ([t3 (vector 3 7)])
  10298. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10299. 42
  10300. 0))))
  10301. \end{lstlisting}
  10302. \fi}
  10303. {\if\edition\pythonEd
  10304. \begin{lstlisting}
  10305. t1 = 3, 7
  10306. t2 = t1
  10307. t3 = 3, 7
  10308. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10309. \end{lstlisting}
  10310. \fi}
  10311. \end{minipage}
  10312. \end{center}
  10313. {\if\edition\racketEd
  10314. Whether two variables are aliased or not affects what happens
  10315. when the underlying tuple is mutated\index{subject}{mutation}.
  10316. Consider the following example in which \code{t1} and \code{t2}
  10317. again refer to the same tuple value.
  10318. \begin{center}
  10319. \begin{minipage}{0.96\textwidth}
  10320. \begin{lstlisting}
  10321. (let ([t1 (vector 3 7)])
  10322. (let ([t2 t1])
  10323. (let ([_ (vector-set! t2 0 42)])
  10324. (vector-ref t1 0))))
  10325. \end{lstlisting}
  10326. \end{minipage}
  10327. \end{center}
  10328. The mutation through \code{t2} is visible when referencing the tuple
  10329. from \code{t1}, so the result of this program is \code{42}.
  10330. \fi}
  10331. The next issue concerns the lifetime of tuples. When does their
  10332. lifetime end? Notice that \LangVec{} does not include an operation
  10333. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10334. to any notion of static scoping.
  10335. %
  10336. {\if\edition\racketEd
  10337. %
  10338. For example, the following program returns \code{42} even though the
  10339. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10340. that reads from the vector it was bound to.
  10341. \begin{center}
  10342. \begin{minipage}{0.96\textwidth}
  10343. \begin{lstlisting}
  10344. (let ([v (vector (vector 44))])
  10345. (let ([x (let ([w (vector 42)])
  10346. (let ([_ (vector-set! v 0 w)])
  10347. 0))])
  10348. (+ x (vector-ref (vector-ref v 0) 0))))
  10349. \end{lstlisting}
  10350. \end{minipage}
  10351. \end{center}
  10352. \fi}
  10353. %
  10354. {\if\edition\pythonEd
  10355. %
  10356. For example, the following program returns \code{42} even though the
  10357. variable \code{x} goes out of scope when the function returns, prior
  10358. to reading the tuple element at index zero. (We study the compilation
  10359. of functions in Chapter~\ref{ch:Lfun}.)
  10360. %
  10361. \begin{center}
  10362. \begin{minipage}{0.96\textwidth}
  10363. \begin{lstlisting}
  10364. def f():
  10365. x = 42, 43
  10366. return x
  10367. t = f()
  10368. print( t[0] )
  10369. \end{lstlisting}
  10370. \end{minipage}
  10371. \end{center}
  10372. \fi}
  10373. %
  10374. From the perspective of programmer-observable behavior, tuples live
  10375. forever. However, if they really lived forever then many long-running
  10376. programs would run out of memory. To solve this problem, the
  10377. language's runtime system performs automatic garbage collection.
  10378. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10379. \LangVec{} language.
  10380. %
  10381. \racket{We define the \code{vector}, \code{vector-ref},
  10382. \code{vector-set!}, and \code{vector-length} operations for
  10383. \LangVec{} in terms of the corresponding operations in Racket. One
  10384. subtle point is that the \code{vector-set!} operation returns the
  10385. \code{\#<void>} value.}
  10386. %
  10387. \python{We represent tuples with Python lists in the interpreter
  10388. because we need to write to them
  10389. (Section~\ref{sec:expose-allocation}). (Python tuples are
  10390. immutable.) We define element access, the \code{is} operator, and
  10391. the \code{len} operator for \LangVec{} in terms of the corresponding
  10392. operations in Python.}
  10393. \begin{figure}[tbp]
  10394. \begin{tcolorbox}[colback=white]
  10395. {\if\edition\racketEd
  10396. \begin{lstlisting}
  10397. (define interp-Lvec-class
  10398. (class interp-Lwhile-class
  10399. (super-new)
  10400. (define/override (interp-op op)
  10401. (match op
  10402. ['eq? (lambda (v1 v2)
  10403. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10404. (and (boolean? v1) (boolean? v2))
  10405. (and (vector? v1) (vector? v2))
  10406. (and (void? v1) (void? v2)))
  10407. (eq? v1 v2)]))]
  10408. ['vector vector]
  10409. ['vector-length vector-length]
  10410. ['vector-ref vector-ref]
  10411. ['vector-set! vector-set!]
  10412. [else (super interp-op op)]
  10413. ))
  10414. (define/override ((interp-exp env) e)
  10415. (match e
  10416. [(HasType e t) ((interp-exp env) e)]
  10417. [else ((super interp-exp env) e)]
  10418. ))
  10419. ))
  10420. (define (interp-Lvec p)
  10421. (send (new interp-Lvec-class) interp-program p))
  10422. \end{lstlisting}
  10423. \fi}
  10424. %
  10425. {\if\edition\pythonEd
  10426. \begin{lstlisting}
  10427. class InterpLtup(InterpLwhile):
  10428. def interp_cmp(self, cmp):
  10429. match cmp:
  10430. case Is():
  10431. return lambda x, y: x is y
  10432. case _:
  10433. return super().interp_cmp(cmp)
  10434. def interp_exp(self, e, env):
  10435. match e:
  10436. case Tuple(es, Load()):
  10437. return tuple([self.interp_exp(e, env) for e in es])
  10438. case Subscript(tup, index, Load()):
  10439. t = self.interp_exp(tup, env)
  10440. n = self.interp_exp(index, env)
  10441. return t[n]
  10442. case _:
  10443. return super().interp_exp(e, env)
  10444. \end{lstlisting}
  10445. \fi}
  10446. \end{tcolorbox}
  10447. \caption{Interpreter for the \LangVec{} language.}
  10448. \label{fig:interp-Lvec}
  10449. \end{figure}
  10450. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10451. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10452. we need to know which elements of the tuple are themselves tuples for
  10453. the purposes of garbage collection. We can obtain this information
  10454. during type checking. The type checker in
  10455. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10456. expression, it also
  10457. %
  10458. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10459. where $T$ is the tuple's type.
  10460. To create the s-expression for the \code{Vector} type in
  10461. Figure~\ref{fig:type-check-Lvec}, we use the
  10462. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10463. operator} \code{,@} to insert the list \code{t*} without its usual
  10464. start and end parentheses. \index{subject}{unquote-slicing}}
  10465. %
  10466. \python{records the type of each tuple expression in a new field
  10467. named \code{has\_type}. Because the type checker has to compute the type
  10468. of each tuple access, the index must be a constant.}
  10469. \begin{figure}[tp]
  10470. \begin{tcolorbox}[colback=white]
  10471. {\if\edition\racketEd
  10472. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10473. (define type-check-Lvec-class
  10474. (class type-check-Lif-class
  10475. (super-new)
  10476. (inherit check-type-equal?)
  10477. (define/override (type-check-exp env)
  10478. (lambda (e)
  10479. (define recur (type-check-exp env))
  10480. (match e
  10481. [(Prim 'vector es)
  10482. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10483. (define t `(Vector ,@t*))
  10484. (values (HasType (Prim 'vector e*) t) t)]
  10485. [(Prim 'vector-ref (list e1 (Int i)))
  10486. (define-values (e1^ t) (recur e1))
  10487. (match t
  10488. [`(Vector ,ts ...)
  10489. (unless (and (0 . <= . i) (i . < . (length ts)))
  10490. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10491. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10492. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10493. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10494. (define-values (e-vec t-vec) (recur e1))
  10495. (define-values (e-arg^ t-arg) (recur arg))
  10496. (match t-vec
  10497. [`(Vector ,ts ...)
  10498. (unless (and (0 . <= . i) (i . < . (length ts)))
  10499. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10500. (check-type-equal? (list-ref ts i) t-arg e)
  10501. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10502. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10503. [(Prim 'vector-length (list e))
  10504. (define-values (e^ t) (recur e))
  10505. (match t
  10506. [`(Vector ,ts ...)
  10507. (values (Prim 'vector-length (list e^)) 'Integer)]
  10508. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10509. [(Prim 'eq? (list arg1 arg2))
  10510. (define-values (e1 t1) (recur arg1))
  10511. (define-values (e2 t2) (recur arg2))
  10512. (match* (t1 t2)
  10513. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10514. [(other wise) (check-type-equal? t1 t2 e)])
  10515. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10516. [(HasType (Prim 'vector es) t)
  10517. ((type-check-exp env) (Prim 'vector es))]
  10518. [(HasType e1 t)
  10519. (define-values (e1^ t^) (recur e1))
  10520. (check-type-equal? t t^ e)
  10521. (values (HasType e1^ t) t)]
  10522. [else ((super type-check-exp env) e)]
  10523. )))
  10524. ))
  10525. (define (type-check-Lvec p)
  10526. (send (new type-check-Lvec-class) type-check-program p))
  10527. \end{lstlisting}
  10528. \fi}
  10529. {\if\edition\pythonEd
  10530. \begin{lstlisting}
  10531. class TypeCheckLtup(TypeCheckLwhile):
  10532. def type_check_exp(self, e, env):
  10533. match e:
  10534. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10535. l = self.type_check_exp(left, env)
  10536. r = self.type_check_exp(right, env)
  10537. check_type_equal(l, r, e)
  10538. return bool
  10539. case Tuple(es, Load()):
  10540. ts = [self.type_check_exp(e, env) for e in es]
  10541. e.has_type = tuple(ts)
  10542. return e.has_type
  10543. case Subscript(tup, Constant(index), Load()):
  10544. tup_ty = self.type_check_exp(tup, env)
  10545. index_ty = self.type_check_exp(Constant(index), env)
  10546. check_type_equal(index_ty, int, index)
  10547. match tup_ty:
  10548. case tuple(ts):
  10549. return ts[index]
  10550. case _:
  10551. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10552. case _:
  10553. return super().type_check_exp(e, env)
  10554. \end{lstlisting}
  10555. \fi}
  10556. \end{tcolorbox}
  10557. \caption{Type checker for the \LangVec{} language.}
  10558. \label{fig:type-check-Lvec}
  10559. \end{figure}
  10560. \section{Garbage Collection}
  10561. \label{sec:GC}
  10562. Garbage collection is a runtime technique for reclaiming space on the
  10563. heap that will not be used in the future of the running program. We
  10564. use the term \emph{object}\index{subject}{object} to refer to any
  10565. value that is stored in the heap, which for now only includes
  10566. tuples.%
  10567. %
  10568. \footnote{The term ``object'' as it is used in the context of
  10569. object-oriented programming has a more specific meaning than how we
  10570. are using the term here.}
  10571. %
  10572. Unfortunately, it is impossible to know precisely which objects will
  10573. be accessed in the future and which will not. Instead, garbage
  10574. collectors over approximate the set of objects that will be accessed by
  10575. identifying which objects can possibly be accessed. The running
  10576. program can directly access objects that are in registers and on the
  10577. procedure call stack. It can also transitively access the elements of
  10578. tuples, starting with a tuple whose address is in a register or on the
  10579. procedure call stack. We define the \emph{root
  10580. set}\index{subject}{root set} to be all the tuple addresses that are
  10581. in registers or on the procedure call stack. We define the \emph{live
  10582. objects}\index{subject}{live objects} to be the objects that are
  10583. reachable from the root set. Garbage collectors reclaim the space that
  10584. is allocated to objects that are no longer live. That means that some
  10585. objects may not get reclaimed as soon as they could be, but at least
  10586. garbage collectors do not reclaim the space dedicated to objects that
  10587. will be accessed in the future! The programmer can influence which
  10588. objects get reclaimed by causing them to become unreachable.
  10589. So the goal of the garbage collector is twofold:
  10590. \begin{enumerate}
  10591. \item preserve all the live objects, and
  10592. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10593. \end{enumerate}
  10594. \subsection{Two-Space Copying Collector}
  10595. Here we study a relatively simple algorithm for garbage collection
  10596. that is the basis of many state-of-the-art garbage
  10597. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10598. particular, we describe a two-space copying
  10599. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10600. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10601. collector} \index{subject}{two-space copying collector}
  10602. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10603. what happens in a two-space collector, showing two time steps, prior
  10604. to garbage collection (on the top) and after garbage collection (on
  10605. the bottom). In a two-space collector, the heap is divided into two
  10606. parts named the FromSpace\index{subject}{FromSpace} and the
  10607. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10608. FromSpace until there is not enough room for the next allocation
  10609. request. At that point, the garbage collector goes to work to make
  10610. room for the next allocation.
  10611. A copying collector makes more room by copying all of the live objects
  10612. from the FromSpace into the ToSpace and then performs a sleight of
  10613. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10614. as the new ToSpace. In the example of
  10615. Figure~\ref{fig:copying-collector}, the root set consists of three
  10616. pointers, one in a register and two on the stack. All of the live
  10617. objects have been copied to the ToSpace (the right-hand side of
  10618. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10619. pointer relationships. For example, the pointer in the register still
  10620. points to a tuple that in turn points to two other tuples. There are
  10621. four tuples that are not reachable from the root set and therefore do
  10622. not get copied into the ToSpace.
  10623. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10624. created by a well-typed program in \LangVec{} because it contains a
  10625. cycle. However, creating cycles will be possible once we get to
  10626. \LangDyn{} (Chapter~\ref{ch:Ldyn}). We design the garbage collector
  10627. to deal with cycles to begin with so we will not need to revisit this
  10628. issue.
  10629. \begin{figure}[tbp]
  10630. \centering
  10631. \begin{tcolorbox}[colback=white]
  10632. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10633. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10634. \\[5ex]
  10635. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10636. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10637. \end{tcolorbox}
  10638. \caption{A copying collector in action.}
  10639. \label{fig:copying-collector}
  10640. \end{figure}
  10641. \subsection{Graph Copying via Cheney's Algorithm}
  10642. \label{sec:cheney}
  10643. \index{subject}{Cheney's algorithm}
  10644. Let us take a closer look at the copying of the live objects. The
  10645. allocated objects and pointers can be viewed as a graph and we need to
  10646. copy the part of the graph that is reachable from the root set. To
  10647. make sure we copy all of the reachable vertices in the graph, we need
  10648. an exhaustive graph traversal algorithm, such as depth-first search or
  10649. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10650. such algorithms take into account the possibility of cycles by marking
  10651. which vertices have already been visited, so as to ensure termination
  10652. of the algorithm. These search algorithms also use a data structure
  10653. such as a stack or queue as a to-do list to keep track of the vertices
  10654. that need to be visited. We use breadth-first search and a trick
  10655. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10656. and copying tuples into the ToSpace.
  10657. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10658. copy progresses. The queue is represented by a chunk of contiguous
  10659. memory at the beginning of the ToSpace, using two pointers to track
  10660. the front and the back of the queue, called the \emph{free pointer}
  10661. and the \emph{scan pointer} respectively. The algorithm starts by
  10662. copying all tuples that are immediately reachable from the root set
  10663. into the ToSpace to form the initial queue. When we copy a tuple, we
  10664. mark the old tuple to indicate that it has been visited. We discuss
  10665. how this marking is accomplish in Section~\ref{sec:data-rep-gc}. Note
  10666. that any pointers inside the copied tuples in the queue still point
  10667. back to the FromSpace. Once the initial queue has been created, the
  10668. algorithm enters a loop in which it repeatedly processes the tuple at
  10669. the front of the queue and pops it off the queue. To process a tuple,
  10670. the algorithm copies all the objects that are directly reachable from it
  10671. to the ToSpace, placing them at the back of the queue. The algorithm
  10672. then updates the pointers in the popped tuple so they point to the
  10673. newly copied objects.
  10674. \begin{figure}[tbp]
  10675. \centering
  10676. \begin{tcolorbox}[colback=white]
  10677. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10678. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10679. \end{tcolorbox}
  10680. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10681. \label{fig:cheney}
  10682. \end{figure}
  10683. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10684. tuple whose second element is $42$ to the back of the queue. The other
  10685. pointer goes to a tuple that has already been copied, so we do not
  10686. need to copy it again, but we do need to update the pointer to the new
  10687. location. This can be accomplished by storing a \emph{forwarding
  10688. pointer}\index{subject}{forwarding pointer} to the new location in the
  10689. old tuple, back when we initially copied the tuple into the
  10690. ToSpace. This completes one step of the algorithm. The algorithm
  10691. continues in this way until the queue is empty, that is, when the scan
  10692. pointer catches up with the free pointer.
  10693. \subsection{Data Representation}
  10694. \label{sec:data-rep-gc}
  10695. The garbage collector places some requirements on the data
  10696. representations used by our compiler. First, the garbage collector
  10697. needs to distinguish between pointers and other kinds of data such as
  10698. integers. There are several ways to accomplish this.
  10699. \begin{enumerate}
  10700. \item Attached a tag to each object that identifies what type of
  10701. object it is~\citep{McCarthy:1960dz}.
  10702. \item Store different types of objects in different
  10703. regions~\citep{Steele:1977ab}.
  10704. \item Use type information from the program to either (a) generate
  10705. type-specific code for collecting or (b) generate tables that
  10706. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10707. \end{enumerate}
  10708. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10709. need to tag objects anyways, so option 1 is a natural choice for those
  10710. languages. However, \LangVec{} is a statically typed language, so it
  10711. would be unfortunate to require tags on every object, especially small
  10712. and pervasive objects like integers and Booleans. Option 3 is the
  10713. best-performing choice for statically typed languages, but comes with
  10714. a relatively high implementation complexity. To keep this chapter
  10715. within a reasonable time budget, we recommend a combination of options
  10716. 1 and 2, using separate strategies for the stack and the heap.
  10717. Regarding the stack, we recommend using a separate stack for pointers,
  10718. which we call the \emph{root stack}\index{subject}{root stack}
  10719. (a.k.a. ``shadow
  10720. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10721. is, when a local variable needs to be spilled and is of type
  10722. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10723. root stack instead of putting it on the procedure call
  10724. stack. Furthermore, we always spill tuple-typed variables if they are
  10725. live during a call to the collector, thereby ensuring that no pointers
  10726. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10727. reproduces the example from Figure~\ref{fig:copying-collector} and
  10728. contrasts it with the data layout using a root stack. The root stack
  10729. contains the two pointers from the regular stack and also the pointer
  10730. in the second register.
  10731. \begin{figure}[tbp]
  10732. \centering
  10733. \begin{tcolorbox}[colback=white]
  10734. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10735. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10736. \end{tcolorbox}
  10737. \caption{Maintaining a root stack to facilitate garbage collection.}
  10738. \label{fig:shadow-stack}
  10739. \end{figure}
  10740. The problem of distinguishing between pointers and other kinds of data
  10741. also arises inside of each tuple on the heap. We solve this problem by
  10742. attaching a tag, an extra 64-bits, to each
  10743. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10744. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10745. that we have drawn the bits in a big-endian way, from right-to-left,
  10746. with bit location 0 (the least significant bit) on the far right,
  10747. which corresponds to the direction of the x86 shifting instructions
  10748. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10749. is dedicated to specifying which elements of the tuple are pointers,
  10750. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10751. indicates there is a pointer and a 0 bit indicates some other kind of
  10752. data. The pointer mask starts at bit location 7. We limit tuples to a
  10753. maximum size of 50 elements, so we just need 50 bits for the pointer
  10754. mask.%
  10755. %
  10756. \footnote{A production-quality compiler would handle
  10757. arbitrary-sized tuples and use a more complex approach.}
  10758. %
  10759. The tag also contains two other pieces of information. The length of
  10760. the tuple (number of elements) is stored in bits location 1 through
  10761. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10762. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10763. has not yet been copied. If the bit has value 0 then the entire tag
  10764. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10765. zero anyways because our tuples are 8-byte aligned.)
  10766. \begin{figure}[tbp]
  10767. \centering
  10768. \begin{tcolorbox}[colback=white]
  10769. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10770. \end{tcolorbox}
  10771. \caption{Representation of tuples in the heap.}
  10772. \label{fig:tuple-rep}
  10773. \end{figure}
  10774. \subsection{Implementation of the Garbage Collector}
  10775. \label{sec:organize-gz}
  10776. \index{subject}{prelude}
  10777. An implementation of the copying collector is provided in the
  10778. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10779. interface to the garbage collector that is used by the compiler. The
  10780. \code{initialize} function creates the FromSpace, ToSpace, and root
  10781. stack and should be called in the prelude of the \code{main}
  10782. function. The arguments of \code{initialize} are the root stack size
  10783. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10784. good choice for both. The \code{initialize} function puts the address
  10785. of the beginning of the FromSpace into the global variable
  10786. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10787. the address that is 1-past the last element of the FromSpace. We use
  10788. half-open intervals to represent chunks of
  10789. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  10790. points to the first element of the root stack.
  10791. As long as there is room left in the FromSpace, your generated code
  10792. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10793. %
  10794. The amount of room left in the FromSpace is the difference between the
  10795. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10796. function should be called when there is not enough room left in the
  10797. FromSpace for the next allocation. The \code{collect} function takes
  10798. a pointer to the current top of the root stack (one past the last item
  10799. that was pushed) and the number of bytes that need to be
  10800. allocated. The \code{collect} function performs the copying collection
  10801. and leaves the heap in a state such that there is enough room for the
  10802. next allocation.
  10803. \begin{figure}[tbp]
  10804. \begin{tcolorbox}[colback=white]
  10805. \begin{lstlisting}
  10806. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10807. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10808. int64_t* free_ptr;
  10809. int64_t* fromspace_begin;
  10810. int64_t* fromspace_end;
  10811. int64_t** rootstack_begin;
  10812. \end{lstlisting}
  10813. \end{tcolorbox}
  10814. \caption{The compiler's interface to the garbage collector.}
  10815. \label{fig:gc-header}
  10816. \end{figure}
  10817. %% \begin{exercise}
  10818. %% In the file \code{runtime.c} you will find the implementation of
  10819. %% \code{initialize} and a partial implementation of \code{collect}.
  10820. %% The \code{collect} function calls another function, \code{cheney},
  10821. %% to perform the actual copy, and that function is left to the reader
  10822. %% to implement. The following is the prototype for \code{cheney}.
  10823. %% \begin{lstlisting}
  10824. %% static void cheney(int64_t** rootstack_ptr);
  10825. %% \end{lstlisting}
  10826. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10827. %% rootstack (which is an array of pointers). The \code{cheney} function
  10828. %% also communicates with \code{collect} through the global
  10829. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10830. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10831. %% the ToSpace:
  10832. %% \begin{lstlisting}
  10833. %% static int64_t* tospace_begin;
  10834. %% static int64_t* tospace_end;
  10835. %% \end{lstlisting}
  10836. %% The job of the \code{cheney} function is to copy all the live
  10837. %% objects (reachable from the root stack) into the ToSpace, update
  10838. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10839. %% update the root stack so that it points to the objects in the
  10840. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10841. %% and ToSpace.
  10842. %% \end{exercise}
  10843. The introduction of garbage collection has a non-trivial impact on our
  10844. compiler passes. We introduce a new compiler pass named
  10845. \code{expose\_allocation} that elaborates the code for allocating
  10846. tuples. We also make significant changes to
  10847. \code{select\_instructions}, \code{build\_interference},
  10848. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10849. make minor changes in several more passes.
  10850. The following program will serve as our running example. It creates
  10851. two tuples, one nested inside the other. Both tuples have length
  10852. one. The program accesses the element in the inner tuple.
  10853. % tests/vectors_test_17.rkt
  10854. {\if\edition\racketEd
  10855. \begin{lstlisting}
  10856. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10857. \end{lstlisting}
  10858. \fi}
  10859. {\if\edition\pythonEd
  10860. \begin{lstlisting}
  10861. print( ((42,),)[0][0] )
  10862. \end{lstlisting}
  10863. \fi}
  10864. {\if\edition\racketEd
  10865. \section{Shrink}
  10866. \label{sec:shrink-Lvec}
  10867. Recall that the \code{shrink} pass translates the primitives operators
  10868. into a smaller set of primitives.
  10869. %
  10870. This pass comes after type checking and the type checker adds a
  10871. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10872. need to add a case for \code{HasType} to the \code{shrink} pass.
  10873. \fi}
  10874. \section{Expose Allocation}
  10875. \label{sec:expose-allocation}
  10876. The pass \code{expose\_allocation} lowers tuple creation into a
  10877. conditional call to the collector followed by allocating the
  10878. appropriate amount of memory and initializing it. We choose to place
  10879. the \code{expose\_allocation} pass before
  10880. \code{remove\_complex\_operands} because it generates
  10881. code that contains complex operands.
  10882. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10883. replaces tuple creation with new lower-level forms that we use in the
  10884. translation of tuple creation.
  10885. %
  10886. {\if\edition\racketEd
  10887. \[
  10888. \begin{array}{lcl}
  10889. \Exp &::=& \cdots
  10890. \MID (\key{collect} \,\itm{int})
  10891. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10892. \MID (\key{global-value} \,\itm{name})
  10893. \end{array}
  10894. \]
  10895. \fi}
  10896. {\if\edition\pythonEd
  10897. \[
  10898. \begin{array}{lcl}
  10899. \Exp &::=& \cdots\\
  10900. &\MID& \key{collect}(\itm{int})
  10901. \MID \key{allocate}(\itm{int},\itm{type})
  10902. \MID \key{global\_value}(\itm{name}) \\
  10903. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10904. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10905. \end{array}
  10906. \]
  10907. \fi}
  10908. %
  10909. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10910. make sure that there are $n$ bytes ready to be allocated. During
  10911. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10912. the \code{collect} function in \code{runtime.c}.
  10913. %
  10914. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10915. space at the front for the 64 bit tag), but the elements are not
  10916. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10917. of the tuple:
  10918. %
  10919. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10920. %
  10921. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10922. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10923. as \code{free\_ptr}.
  10924. %
  10925. \python{The \code{begin} form is an expression that executes a
  10926. sequence of statements and then produces the value of the expression
  10927. at the end.}
  10928. The following shows the transformation of tuple creation into 1) a
  10929. sequence of temporary variable bindings for the initializing
  10930. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10931. \code{allocate}, and 4) the initialization of the tuple. The
  10932. \itm{len} placeholder refers to the length of the tuple and
  10933. \itm{bytes} is how many total bytes need to be allocated for the
  10934. tuple, which is 8 for the tag plus \itm{len} times 8.
  10935. %
  10936. \python{The \itm{type} needed for the second argument of the
  10937. \code{allocate} form can be obtained from the \code{has\_type} field
  10938. of the tuple AST node, which is stored there by running the type
  10939. checker for \LangVec{} immediately before this pass.}
  10940. %
  10941. \begin{center}
  10942. \begin{minipage}{\textwidth}
  10943. {\if\edition\racketEd
  10944. \begin{lstlisting}
  10945. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10946. |$\Longrightarrow$|
  10947. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10948. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10949. (global-value fromspace_end))
  10950. (void)
  10951. (collect |\itm{bytes}|))])
  10952. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10953. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10954. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10955. |$v$|) ... )))) ...)
  10956. \end{lstlisting}
  10957. \fi}
  10958. {\if\edition\pythonEd
  10959. \begin{lstlisting}
  10960. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10961. |$\Longrightarrow$|
  10962. begin:
  10963. |$x_0$| = |$e_0$|
  10964. |$\vdots$|
  10965. |$x_{n-1}$| = |$e_{n-1}$|
  10966. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10967. 0
  10968. else:
  10969. collect(|\itm{bytes}|)
  10970. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10971. |$v$|[0] = |$x_0$|
  10972. |$\vdots$|
  10973. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10974. |$v$|
  10975. \end{lstlisting}
  10976. \fi}
  10977. \end{minipage}
  10978. \end{center}
  10979. %
  10980. \noindent The sequencing of the initializing expressions
  10981. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10982. they may trigger garbage collection and we cannot have an allocated
  10983. but uninitialized tuple on the heap during a collection.
  10984. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10985. \code{expose\_allocation} pass on our running example.
  10986. \begin{figure}[tbp]
  10987. \begin{tcolorbox}[colback=white]
  10988. % tests/s2_17.rkt
  10989. {\if\edition\racketEd
  10990. \begin{lstlisting}
  10991. (vector-ref
  10992. (vector-ref
  10993. (let ([vecinit6
  10994. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  10995. (global-value fromspace_end))
  10996. (void)
  10997. (collect 16))])
  10998. (let ([alloc2 (allocate 1 (Vector Integer))])
  10999. (let ([_3 (vector-set! alloc2 0 42)])
  11000. alloc2)))])
  11001. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11002. (global-value fromspace_end))
  11003. (void)
  11004. (collect 16))])
  11005. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11006. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11007. alloc5))))
  11008. 0)
  11009. 0)
  11010. \end{lstlisting}
  11011. \fi}
  11012. {\if\edition\pythonEd
  11013. \begin{lstlisting}
  11014. print( |$T_1$|[0][0] )
  11015. \end{lstlisting}
  11016. where $T_1$ is
  11017. \begin{lstlisting}
  11018. begin:
  11019. tmp.1 = |$T_2$|
  11020. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11021. 0
  11022. else:
  11023. collect(16)
  11024. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11025. tmp.2[0] = tmp.1
  11026. tmp.2
  11027. \end{lstlisting}
  11028. and $T_2$ is
  11029. \begin{lstlisting}
  11030. begin:
  11031. tmp.3 = 42
  11032. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11033. 0
  11034. else:
  11035. collect(16)
  11036. tmp.4 = allocate(1, TupleType([int]))
  11037. tmp.4[0] = tmp.3
  11038. tmp.4
  11039. \end{lstlisting}
  11040. \fi}
  11041. \end{tcolorbox}
  11042. \caption{Output of the \code{expose\_allocation} pass.}
  11043. \label{fig:expose-alloc-output}
  11044. \end{figure}
  11045. \section{Remove Complex Operands}
  11046. \label{sec:remove-complex-opera-Lvec}
  11047. {\if\edition\racketEd
  11048. %
  11049. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11050. should be treated as complex operands.
  11051. %
  11052. \fi}
  11053. %
  11054. {\if\edition\pythonEd
  11055. %
  11056. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11057. and tuple access should be treated as complex operands. The
  11058. sub-expressions of tuple access must be atomic.
  11059. %
  11060. \fi}
  11061. %% A new case for
  11062. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11063. %% handled carefully to prevent the \code{Prim} node from being separated
  11064. %% from its enclosing \code{HasType}.
  11065. Figure~\ref{fig:Lvec-anf-syntax}
  11066. shows the grammar for the output language \LangAllocANF{} of this
  11067. pass, which is \LangAlloc{} in monadic normal form.
  11068. \newcommand{\LtupMonadASTRacket}{
  11069. \begin{array}{rcl}
  11070. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11071. \MID \GLOBALVALUE{\Var}
  11072. \end{array}
  11073. }
  11074. \newcommand{\LtupMonadASTPython}{
  11075. \begin{array}{rcl}
  11076. \Exp &::=& \GET{\Atm}{\Atm} \\
  11077. &\MID& \LEN{\Atm}\\
  11078. &\MID& \ALLOCATE{\Int}{\Type}
  11079. \MID \GLOBALVALUE{\Var} \\
  11080. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11081. &\MID& \COLLECT{\Int}
  11082. \end{array}
  11083. }
  11084. \begin{figure}[tp]
  11085. \centering
  11086. \begin{tcolorbox}[colback=white]
  11087. \small
  11088. {\if\edition\racketEd
  11089. \[
  11090. \begin{array}{l}
  11091. \gray{\LvarMonadASTRacket} \\ \hline
  11092. \gray{\LifMonadASTRacket} \\ \hline
  11093. \gray{\LwhileMonadASTRacket} \\ \hline
  11094. \LtupMonadASTRacket \\
  11095. \begin{array}{rcl}
  11096. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11097. \end{array}
  11098. \end{array}
  11099. \]
  11100. \fi}
  11101. {\if\edition\pythonEd
  11102. \[
  11103. \begin{array}{l}
  11104. \gray{\LvarMonadASTPython} \\ \hline
  11105. \gray{\LifMonadASTPython} \\ \hline
  11106. \gray{\LwhileMonadASTPython} \\ \hline
  11107. \LtupMonadASTPython \\
  11108. \begin{array}{rcl}
  11109. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11110. \end{array}
  11111. \end{array}
  11112. %% \begin{array}{lcl}
  11113. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  11114. %% \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  11115. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  11116. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  11117. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  11118. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  11119. %% \Exp &::=& \Atm \MID \READ{} \MID \\
  11120. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  11121. %% \MID \UNIOP{\itm{unaryop}}{\Atm}\\
  11122. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  11123. %% % \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp} \\ % removed by RCO
  11124. %% &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  11125. %% &\MID& \GET{\Atm}{\Atm} \\
  11126. %% &\MID& \LEN{\Exp}\\
  11127. %% &\MID& \ALLOCATE{\Int}{\Type}
  11128. %% \MID \GLOBALVALUE{\Var}\RP\\
  11129. %% &\MID& \BEGIN{\Stmt^{*}}{\Atm} \\ % can use this in place of \LET;
  11130. %% % why have \LET?
  11131. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  11132. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  11133. %% &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  11134. %% &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  11135. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  11136. %% \MID \COLLECT{\Int} \\
  11137. %% \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11138. %% \end{array}
  11139. \]
  11140. \fi}
  11141. \end{tcolorbox}
  11142. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11143. \label{fig:Lvec-anf-syntax}
  11144. \end{figure}
  11145. \section{Explicate Control and the \LangCVec{} language}
  11146. \label{sec:explicate-control-r3}
  11147. \newcommand{\CtupASTRacket}{
  11148. \begin{array}{lcl}
  11149. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11150. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11151. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11152. &\MID& \VECLEN{\Atm} \\
  11153. &\MID& \GLOBALVALUE{\Var} \\
  11154. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11155. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11156. \end{array}
  11157. }
  11158. \newcommand{\CtupASTPython}{
  11159. \begin{array}{lcl}
  11160. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11161. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11162. \Stmt &::=& \COLLECT{\Int} \\
  11163. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11164. \end{array}
  11165. }
  11166. \begin{figure}[tp]
  11167. \begin{tcolorbox}[colback=white]
  11168. \small
  11169. {\if\edition\racketEd
  11170. \[
  11171. \begin{array}{l}
  11172. \gray{\CvarASTRacket} \\ \hline
  11173. \gray{\CifASTRacket} \\ \hline
  11174. \gray{\CloopASTRacket} \\ \hline
  11175. \CtupASTRacket \\
  11176. \begin{array}{lcl}
  11177. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11178. \end{array}
  11179. \end{array}
  11180. \]
  11181. \fi}
  11182. {\if\edition\pythonEd
  11183. \[
  11184. \begin{array}{l}
  11185. \gray{\CifASTPython} \\ \hline
  11186. \CtupASTPython \\
  11187. \begin{array}{lcl}
  11188. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11189. \end{array}
  11190. \end{array}
  11191. \]
  11192. \fi}
  11193. \end{tcolorbox}
  11194. \caption{The abstract syntax of \LangCVec{}, extending
  11195. \racket{\LangCLoop{} (Figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11196. (Figure~\ref{fig:c1-syntax})}.}
  11197. \label{fig:c2-syntax}
  11198. \end{figure}
  11199. The output of \code{explicate\_control} is a program in the
  11200. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11201. Figure~\ref{fig:c2-syntax}.
  11202. %
  11203. %% \racket{(The concrete syntax is defined in
  11204. %% Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11205. %
  11206. The new expressions of \LangCVec{} include \key{allocate},
  11207. %
  11208. \racket{\key{vector-ref}, and \key{vector-set!},}
  11209. %
  11210. \python{accessing tuple elements,}
  11211. %
  11212. and \key{global\_value}.
  11213. %
  11214. \python{\LangCVec{} also includes the \code{collect} statement and
  11215. assignment to a tuple element.}
  11216. %
  11217. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11218. %
  11219. The \code{explicate\_control} pass can treat these new forms much like
  11220. the other forms that we've already encountered. The output of the
  11221. \code{explicate\_control} pass on the running example is shown on the
  11222. left-side of Figure~\ref{fig:select-instr-output-gc} in the next
  11223. section.
  11224. \section{Select Instructions and the \LangXGlobal{} Language}
  11225. \label{sec:select-instructions-gc}
  11226. \index{subject}{instruction selection}
  11227. %% void (rep as zero)
  11228. %% allocate
  11229. %% collect (callq collect)
  11230. %% vector-ref
  11231. %% vector-set!
  11232. %% vector-length
  11233. %% global (postpone)
  11234. In this pass we generate x86 code for most of the new operations that
  11235. were needed to compile tuples, including \code{Allocate},
  11236. \code{Collect}, and accessing tuple elements.
  11237. %
  11238. We compile \code{GlobalValue} to \code{Global} because the later has a
  11239. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11240. \ref{fig:x86-2}). \index{subject}{x86}
  11241. The tuple read and write forms translate into \code{movq}
  11242. instructions. (The $+1$ in the offset is to move past the tag at the
  11243. beginning of the tuple representation.)
  11244. %
  11245. \begin{center}
  11246. \begin{minipage}{\textwidth}
  11247. {\if\edition\racketEd
  11248. \begin{lstlisting}
  11249. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11250. |$\Longrightarrow$|
  11251. movq |$\itm{tup}'$|, %r11
  11252. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11253. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11254. |$\Longrightarrow$|
  11255. movq |$\itm{tup}'$|, %r11
  11256. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11257. movq $0, |$\itm{lhs'}$|
  11258. \end{lstlisting}
  11259. \fi}
  11260. {\if\edition\pythonEd
  11261. \begin{lstlisting}
  11262. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11263. |$\Longrightarrow$|
  11264. movq |$\itm{tup}'$|, %r11
  11265. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11266. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11267. |$\Longrightarrow$|
  11268. movq |$\itm{tup}'$|, %r11
  11269. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11270. \end{lstlisting}
  11271. \fi}
  11272. \end{minipage}
  11273. \end{center}
  11274. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11275. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11276. are obtained by translating from \LangCVec{} to x86.
  11277. %
  11278. The move of $\itm{tup}'$ to
  11279. register \code{r11} ensures that offset expression
  11280. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  11281. removing \code{r11} from consideration by the register allocating.
  11282. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11283. \code{rax}. Then the generated code for tuple assignment would be
  11284. \begin{lstlisting}
  11285. movq |$\itm{tup}'$|, %rax
  11286. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11287. \end{lstlisting}
  11288. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11289. \code{patch\_instructions} would insert a move through \code{rax}
  11290. as follows.
  11291. \begin{lstlisting}
  11292. movq |$\itm{tup}'$|, %rax
  11293. movq |$\itm{rhs}'$|, %rax
  11294. movq %rax, |$8(n+1)$|(%rax)
  11295. \end{lstlisting}
  11296. But the above sequence of instructions does not work because we're
  11297. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11298. $\itm{rhs}'$) at the same time!
  11299. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11300. be translated into a sequence of instructions that read the tag of the
  11301. tuple and extract the six bits that represent the tuple length, which
  11302. are the bits starting at index 1 and going up to and including bit 6.
  11303. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11304. (shift right) can be used to accomplish this.
  11305. We compile the \code{allocate} form to operations on the
  11306. \code{free\_ptr}, as shown below. This approach is called
  11307. \emph{inline allocation} as it implements allocation without a
  11308. function call, by simply bumping the allocation pointer. It is much
  11309. more efficient than calling a function for each allocation. The
  11310. address in the \code{free\_ptr} is the next free address in the
  11311. FromSpace, so we copy it into \code{r11} and then move it forward by
  11312. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  11313. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  11314. the tag. We then initialize the \itm{tag} and finally copy the
  11315. address in \code{r11} to the left-hand-side. Refer to
  11316. Figure~\ref{fig:tuple-rep} to see how the tag is organized.
  11317. %
  11318. \racket{We recommend using the Racket operations
  11319. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11320. during compilation.}
  11321. %
  11322. \python{We recommend using the bitwise-or operator \code{|} and the
  11323. shift-left operator \code{<<} to compute the tag during
  11324. compilation.}
  11325. %
  11326. The type annotation in the \code{allocate} form is used to determine
  11327. the pointer mask region of the tag.
  11328. %
  11329. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11330. address of the \code{free\_ptr} global variable but uses a special
  11331. instruction-pointer relative addressing mode of the x86-64 processor.
  11332. In particular, the assembler computes the distance $d$ between the
  11333. address of \code{free\_ptr} and where the \code{rip} would be at that
  11334. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11335. \code{$d$(\%rip)}, which at runtime will compute the address of
  11336. \code{free\_ptr}.
  11337. %
  11338. {\if\edition\racketEd
  11339. \begin{lstlisting}
  11340. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11341. |$\Longrightarrow$|
  11342. movq free_ptr(%rip), %r11
  11343. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11344. movq $|$\itm{tag}$|, 0(%r11)
  11345. movq %r11, |$\itm{lhs}'$|
  11346. \end{lstlisting}
  11347. \fi}
  11348. {\if\edition\pythonEd
  11349. \begin{lstlisting}
  11350. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11351. |$\Longrightarrow$|
  11352. movq free_ptr(%rip), %r11
  11353. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11354. movq $|$\itm{tag}$|, 0(%r11)
  11355. movq %r11, |$\itm{lhs}'$|
  11356. \end{lstlisting}
  11357. \fi}
  11358. The \code{collect} form is compiled to a call to the \code{collect}
  11359. function in the runtime. The arguments to \code{collect} are 1) the
  11360. top of the root stack and 2) the number of bytes that need to be
  11361. allocated. We use another dedicated register, \code{r15}, to
  11362. store the pointer to the top of the root stack. So \code{r15} is not
  11363. available for use by the register allocator.
  11364. {\if\edition\racketEd
  11365. \begin{lstlisting}
  11366. (collect |$\itm{bytes}$|)
  11367. |$\Longrightarrow$|
  11368. movq %r15, %rdi
  11369. movq $|\itm{bytes}|, %rsi
  11370. callq collect
  11371. \end{lstlisting}
  11372. \fi}
  11373. {\if\edition\pythonEd
  11374. \begin{lstlisting}
  11375. collect(|$\itm{bytes}$|)
  11376. |$\Longrightarrow$|
  11377. movq %r15, %rdi
  11378. movq $|\itm{bytes}|, %rsi
  11379. callq collect
  11380. \end{lstlisting}
  11381. \fi}
  11382. \newcommand{\GrammarXGlobal}{
  11383. \begin{array}{lcl}
  11384. \Arg &::=& \itm{label} \key{(\%rip)}
  11385. \end{array}
  11386. }
  11387. \newcommand{\ASTXGlobalRacket}{
  11388. \begin{array}{lcl}
  11389. \Arg &::=& \GLOBAL{\itm{label}}
  11390. \end{array}
  11391. }
  11392. \begin{figure}[tp]
  11393. \begin{tcolorbox}[colback=white]
  11394. \[
  11395. \begin{array}{l}
  11396. \gray{\GrammarXInt} \\ \hline
  11397. \gray{\GrammarXIf} \\ \hline
  11398. \GrammarXGlobal \\
  11399. \begin{array}{lcl}
  11400. \LangXGlobalM{} &::= & \key{.globl main} \\
  11401. & & \key{main:} \; \Instr^{*}
  11402. \end{array}
  11403. \end{array}
  11404. \]
  11405. \end{tcolorbox}
  11406. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11407. \label{fig:x86-2-concrete}
  11408. \end{figure}
  11409. \begin{figure}[tp]
  11410. \begin{tcolorbox}[colback=white]
  11411. \small
  11412. \[
  11413. \begin{array}{l}
  11414. \gray{\ASTXIntRacket} \\ \hline
  11415. \gray{\ASTXIfRacket} \\ \hline
  11416. \ASTXGlobalRacket \\
  11417. \begin{array}{lcl}
  11418. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  11419. \end{array}
  11420. \end{array}
  11421. \]
  11422. \end{tcolorbox}
  11423. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11424. \label{fig:x86-2}
  11425. \end{figure}
  11426. The concrete and abstract syntax of the \LangXGlobal{} language is
  11427. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11428. differs from \LangXIf{} just in the addition of global variables.
  11429. %
  11430. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11431. \code{select\_instructions} pass on the running example.
  11432. \begin{figure}[tbp]
  11433. \centering
  11434. \begin{tcolorbox}[colback=white]
  11435. % tests/s2_17.rkt
  11436. \begin{tabular}{lll}
  11437. \begin{minipage}{0.5\textwidth}
  11438. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11439. start:
  11440. tmp9 = (global-value free_ptr);
  11441. tmp0 = (+ tmp9 16);
  11442. tmp1 = (global-value fromspace_end);
  11443. if (< tmp0 tmp1)
  11444. goto block0;
  11445. else
  11446. goto block1;
  11447. block0:
  11448. _4 = (void);
  11449. goto block9;
  11450. block1:
  11451. (collect 16)
  11452. goto block9;
  11453. block9:
  11454. alloc2 = (allocate 1 (Vector Integer));
  11455. _3 = (vector-set! alloc2 0 42);
  11456. vecinit6 = alloc2;
  11457. tmp2 = (global-value free_ptr);
  11458. tmp3 = (+ tmp2 16);
  11459. tmp4 = (global-value fromspace_end);
  11460. if (< tmp3 tmp4)
  11461. goto block7;
  11462. else
  11463. goto block8;
  11464. block7:
  11465. _8 = (void);
  11466. goto block6;
  11467. block8:
  11468. (collect 16)
  11469. goto block6;
  11470. block6:
  11471. alloc5 = (allocate 1 (Vector (Vector Integer)));
  11472. _7 = (vector-set! alloc5 0 vecinit6);
  11473. tmp5 = (vector-ref alloc5 0);
  11474. return (vector-ref tmp5 0);
  11475. \end{lstlisting}
  11476. \end{minipage}
  11477. &$\Rightarrow$&
  11478. \begin{minipage}{0.4\textwidth}
  11479. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11480. start:
  11481. movq free_ptr(%rip), tmp9
  11482. movq tmp9, tmp0
  11483. addq $16, tmp0
  11484. movq fromspace_end(%rip), tmp1
  11485. cmpq tmp1, tmp0
  11486. jl block0
  11487. jmp block1
  11488. block0:
  11489. movq $0, _4
  11490. jmp block9
  11491. block1:
  11492. movq %r15, %rdi
  11493. movq $16, %rsi
  11494. callq collect
  11495. jmp block9
  11496. block9:
  11497. movq free_ptr(%rip), %r11
  11498. addq $16, free_ptr(%rip)
  11499. movq $3, 0(%r11)
  11500. movq %r11, alloc2
  11501. movq alloc2, %r11
  11502. movq $42, 8(%r11)
  11503. movq $0, _3
  11504. movq alloc2, vecinit6
  11505. movq free_ptr(%rip), tmp2
  11506. movq tmp2, tmp3
  11507. addq $16, tmp3
  11508. movq fromspace_end(%rip), tmp4
  11509. cmpq tmp4, tmp3
  11510. jl block7
  11511. jmp block8
  11512. block7:
  11513. movq $0, _8
  11514. jmp block6
  11515. block8:
  11516. movq %r15, %rdi
  11517. movq $16, %rsi
  11518. callq collect
  11519. jmp block6
  11520. block6:
  11521. movq free_ptr(%rip), %r11
  11522. addq $16, free_ptr(%rip)
  11523. movq $131, 0(%r11)
  11524. movq %r11, alloc5
  11525. movq alloc5, %r11
  11526. movq vecinit6, 8(%r11)
  11527. movq $0, _7
  11528. movq alloc5, %r11
  11529. movq 8(%r11), tmp5
  11530. movq tmp5, %r11
  11531. movq 8(%r11), %rax
  11532. jmp conclusion
  11533. \end{lstlisting}
  11534. \end{minipage}
  11535. \end{tabular}
  11536. \end{tcolorbox}
  11537. \caption{Output of the \code{explicate\_control} (left)
  11538. and \code{select\_instructions} (right) passes on the running example.}
  11539. \label{fig:select-instr-output-gc}
  11540. \end{figure}
  11541. \clearpage
  11542. \section{Register Allocation}
  11543. \label{sec:reg-alloc-gc}
  11544. \index{subject}{register allocation}
  11545. As discussed earlier in this chapter, the garbage collector needs to
  11546. access all the pointers in the root set, that is, all variables that
  11547. are tuples. It will be the responsibility of the register allocator
  11548. to make sure that:
  11549. \begin{enumerate}
  11550. \item the root stack is used for spilling tuple-typed variables, and
  11551. \item if a tuple-typed variable is live during a call to the
  11552. collector, it must be spilled to ensure it is visible to the
  11553. collector.
  11554. \end{enumerate}
  11555. The later responsibility can be handled during construction of the
  11556. interference graph, by adding interference edges between the call-live
  11557. tuple-typed variables and all the callee-saved registers. (They
  11558. already interfere with the caller-saved registers.)
  11559. %
  11560. \racket{The type information for variables is in the \code{Program}
  11561. form, so we recommend adding another parameter to the
  11562. \code{build\_interference} function to communicate this alist.}
  11563. %
  11564. \python{The type information for variables is generated by the type
  11565. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11566. the \code{CProgram} AST mode. You'll need to propagate that
  11567. information so that it is available in this pass.}
  11568. The spilling of tuple-typed variables to the root stack can be handled
  11569. after graph coloring, when choosing how to assign the colors
  11570. (integers) to registers and stack locations. The
  11571. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11572. changes to also record the number of spills to the root stack.
  11573. % build-interference
  11574. %
  11575. % callq
  11576. % extra parameter for var->type assoc. list
  11577. % update 'program' and 'if'
  11578. % allocate-registers
  11579. % allocate spilled vectors to the rootstack
  11580. % don't change color-graph
  11581. % TODO:
  11582. %\section{Patch Instructions}
  11583. %[mention that global variables are memory references]
  11584. \section{Prelude and Conclusion}
  11585. \label{sec:print-x86-gc}
  11586. \label{sec:prelude-conclusion-x86-gc}
  11587. \index{subject}{prelude}\index{subject}{conclusion}
  11588. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11589. \code{prelude\_and\_conclusion} pass on the running example. In the
  11590. prelude and conclusion of the \code{main} function, we allocate space
  11591. on the root stack to make room for the spills of tuple-typed
  11592. variables. We do so by bumping the root stack pointer (\code{r15})
  11593. taking care that the root stack grows up instead of down. For the
  11594. running example, there was just one spill so we increment \code{r15}
  11595. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  11596. One issue that deserves special care is that there may be a call to
  11597. \code{collect} prior to the initializing assignments for all the
  11598. variables in the root stack. We do not want the garbage collector to
  11599. accidentally think that some uninitialized variable is a pointer that
  11600. needs to be followed. Thus, we zero-out all locations on the root
  11601. stack in the prelude of \code{main}. In
  11602. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11603. %
  11604. \lstinline{movq $0, 0(%r15)}
  11605. %
  11606. is sufficient to accomplish this task because there is only one spill.
  11607. In general, we have to clear as many words as there are spills of
  11608. tuple-typed variables. The garbage collector tests each root to see
  11609. if it is null prior to dereferencing it.
  11610. \begin{figure}[htbp]
  11611. % TODO: Python Version -Jeremy
  11612. \begin{tcolorbox}[colback=white]
  11613. \begin{minipage}[t]{0.5\textwidth}
  11614. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11615. .globl main
  11616. main:
  11617. pushq %rbp
  11618. movq %rsp, %rbp
  11619. subq $0, %rsp
  11620. movq $65536, %rdi
  11621. movq $65536, %rsi
  11622. callq initialize
  11623. movq rootstack_begin(%rip), %r15
  11624. movq $0, 0(%r15)
  11625. addq $8, %r15
  11626. jmp start
  11627. conclusion:
  11628. subq $8, %r15
  11629. addq $0, %rsp
  11630. popq %rbp
  11631. retq
  11632. \end{lstlisting}
  11633. \end{minipage}
  11634. \end{tcolorbox}
  11635. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  11636. \label{fig:print-x86-output-gc}
  11637. \end{figure}
  11638. \begin{figure}[tbp]
  11639. \begin{tcolorbox}[colback=white]
  11640. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11641. \node (Lvec) at (0,2) {\large \LangVec{}};
  11642. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11643. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11644. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11645. \node (Lvec-5) at (9,0) {\large \LangAlloc{}};
  11646. \node (Lvec-6) at (6,0) {\large \LangAllocANF{}};
  11647. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11648. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11649. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11650. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11651. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11652. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11653. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11654. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11655. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11656. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11657. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11658. \path[->,bend left=15] (Lvec-4) edge [right] node
  11659. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  11660. \path[->,bend left=15] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex.} (Lvec-6);
  11661. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11662. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11663. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11664. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11665. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11666. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11667. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  11668. \end{tikzpicture}
  11669. \end{tcolorbox}
  11670. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11671. \label{fig:Lvec-passes}
  11672. \end{figure}
  11673. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11674. for the compilation of \LangVec{}.
  11675. \clearpage
  11676. {\if\edition\racketEd
  11677. \section{Challenge: Simple Structures}
  11678. \label{sec:simple-structures}
  11679. \index{subject}{struct}
  11680. \index{subject}{structure}
  11681. The language \LangStruct{} extends \LangVec{} with support for simple
  11682. structures. Its concrete syntax is defined in
  11683. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11684. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11685. Racket is a user-defined data type that contains named fields and that
  11686. is heap allocated, similar to a vector. The following is an example of
  11687. a structure definition, in this case the definition of a \code{point}
  11688. type.
  11689. \begin{lstlisting}
  11690. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11691. \end{lstlisting}
  11692. \newcommand{\LstructGrammarRacket}{
  11693. \begin{array}{lcl}
  11694. \Type &::=& \Var \\
  11695. \Exp &::=& (\Var\;\Exp \ldots)\\
  11696. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11697. \end{array}
  11698. }
  11699. \newcommand{\LstructASTRacket}{
  11700. \begin{array}{lcl}
  11701. \Type &::=& \VAR{\Var} \\
  11702. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11703. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11704. \end{array}
  11705. }
  11706. \begin{figure}[tbp]
  11707. \centering
  11708. \begin{tcolorbox}[colback=white]
  11709. \[
  11710. \begin{array}{l}
  11711. \gray{\LintGrammarRacket{}} \\ \hline
  11712. \gray{\LvarGrammarRacket{}} \\ \hline
  11713. \gray{\LifGrammarRacket{}} \\ \hline
  11714. \gray{\LwhileGrammarRacket} \\ \hline
  11715. \gray{\LtupGrammarRacket} \\ \hline
  11716. \LstructGrammarRacket \\
  11717. \begin{array}{lcl}
  11718. \LangStruct{} &::=& \Def \ldots \; \Exp
  11719. \end{array}
  11720. \end{array}
  11721. \]
  11722. \end{tcolorbox}
  11723. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11724. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11725. \label{fig:Lstruct-concrete-syntax}
  11726. \end{figure}
  11727. \begin{figure}[tbp]
  11728. \centering
  11729. \begin{tcolorbox}[colback=white]
  11730. \small
  11731. \[
  11732. \begin{array}{l}
  11733. \gray{\LintASTRacket{}} \\ \hline
  11734. \gray{\LvarASTRacket{}} \\ \hline
  11735. \gray{\LifASTRacket{}} \\ \hline
  11736. \gray{\LwhileASTRacket} \\ \hline
  11737. \gray{\LtupASTRacket} \\ \hline
  11738. \LstructASTRacket \\
  11739. \begin{array}{lcl}
  11740. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11741. \end{array}
  11742. \end{array}
  11743. \]
  11744. \end{tcolorbox}
  11745. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11746. (Figure~\ref{fig:Lvec-syntax}).}
  11747. \label{fig:Lstruct-syntax}
  11748. \end{figure}
  11749. An instance of a structure is created using function call syntax, with
  11750. the name of the structure in the function position:
  11751. \begin{lstlisting}
  11752. (point 7 12)
  11753. \end{lstlisting}
  11754. Function-call syntax is also used to read a field of a structure. The
  11755. function name is formed by the structure name, a dash, and the field
  11756. name. The following example uses \code{point-x} and \code{point-y} to
  11757. access the \code{x} and \code{y} fields of two point instances.
  11758. \begin{center}
  11759. \begin{lstlisting}
  11760. (let ([pt1 (point 7 12)])
  11761. (let ([pt2 (point 4 3)])
  11762. (+ (- (point-x pt1) (point-x pt2))
  11763. (- (point-y pt1) (point-y pt2)))))
  11764. \end{lstlisting}
  11765. \end{center}
  11766. Similarly, to write to a field of a structure, use its set function,
  11767. whose name starts with \code{set-}, followed by the structure name,
  11768. then a dash, then the field name, and concluded with an exclamation
  11769. mark. The following example uses \code{set-point-x!} to change the
  11770. \code{x} field from \code{7} to \code{42}.
  11771. \begin{center}
  11772. \begin{lstlisting}
  11773. (let ([pt (point 7 12)])
  11774. (let ([_ (set-point-x! pt 42)])
  11775. (point-x pt)))
  11776. \end{lstlisting}
  11777. \end{center}
  11778. \begin{exercise}\normalfont\normalsize
  11779. Create a type checker for \LangStruct{} by extending the type
  11780. checker for \LangVec{}. Extend your compiler with support for simple
  11781. structures, compiling \LangStruct{} to x86 assembly code. Create
  11782. five new test cases that use structures and test your compiler.
  11783. \end{exercise}
  11784. % TODO: create an interpreter for L_struct
  11785. \clearpage
  11786. \fi}
  11787. \section{Challenge: Arrays}
  11788. \label{sec:arrays}
  11789. In this chapter we have studied tuples, that is, a heterogeneous
  11790. sequences of elements whose length is determined at compile-time. This
  11791. challenge is also about sequences, but this time the length is
  11792. determined at run-time and all the elements have the same type (they
  11793. are homogeneous). We use the term ``array'' for this later kind of
  11794. sequence.
  11795. %
  11796. \racket{
  11797. The Racket language does not distinguish between tuples and arrays,
  11798. they are both represented by vectors. However, Typed Racket
  11799. distinguishes between tuples and arrays: the \code{Vector} type is for
  11800. tuples and the \code{Vectorof} type is for arrays.}
  11801. \python{
  11802. Arrays correspond to the \code{list} type in Python language.
  11803. }
  11804. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11805. for \LangArray{} and Figure~\ref{fig:Lvecof-syntax} defines the
  11806. abstract syntax, extending \LangVec{} with the
  11807. \racket{\code{Vectorof}}\python{\code{list}} type and the
  11808. %
  11809. \racket{\code{make-vector} primitive operator for creating an array,
  11810. whose arguments are the length of the array and an initial value for
  11811. all the elements in the array.}
  11812. \python{bracket notation for creating an array literal.}
  11813. \racket{
  11814. The \code{vector-length},
  11815. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11816. for tuples become overloaded for use with arrays.}
  11817. \python{
  11818. The subscript operator becomes overloaded for use with arrays and tuples
  11819. and now may appear on the left-hand side of an assignment.
  11820. Note that the index of the subscript, when applied to an array, may be an
  11821. arbitrary expression and not just a constant integer.
  11822. The \code{len} function is also applicable to arrays.
  11823. }
  11824. %
  11825. We include integer multiplication in \LangArray{}, as it is
  11826. useful in many examples involving arrays such as computing the
  11827. inner product of two arrays (Figure~\ref{fig:inner_product}).
  11828. \newcommand{\LarrayGrammarRacket}{
  11829. \begin{array}{lcl}
  11830. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11831. \Exp &::=& \CMUL{\Exp}{\Exp}
  11832. \MID \CMAKEVEC{\Exp}{\Exp}
  11833. \end{array}
  11834. }
  11835. \newcommand{\LarrayASTRacket}{
  11836. \begin{array}{lcl}
  11837. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11838. \Exp &::=& \MUL{\Exp}{\Exp}
  11839. \MID \MAKEVEC{\Exp}{\Exp}
  11840. \end{array}
  11841. }
  11842. \newcommand{\LarrayGrammarPython}{
  11843. \begin{array}{lcl}
  11844. \Type &::=& \key{list}\LS\Type\RS \\
  11845. \Exp &::=& \CMUL{\Exp}{\Exp}
  11846. \MID \CGET{\Exp}{\Exp}
  11847. \MID \LS \Exp \code{,} \ldots \RS \\
  11848. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  11849. \end{array}
  11850. }
  11851. \newcommand{\LarrayASTPython}{
  11852. \begin{array}{lcl}
  11853. \Type &::=& \key{ListType}\LP\Type\RP \\
  11854. \Exp &::=& \MUL{\Exp}{\Exp}
  11855. \MID \GET{\Exp}{\Exp} \\
  11856. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  11857. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  11858. \end{array}
  11859. }
  11860. \begin{figure}[tp]
  11861. \centering
  11862. \begin{tcolorbox}[colback=white]
  11863. \small
  11864. {\if\edition\racketEd
  11865. \[
  11866. \begin{array}{l}
  11867. \gray{\LintGrammarRacket{}} \\ \hline
  11868. \gray{\LvarGrammarRacket{}} \\ \hline
  11869. \gray{\LifGrammarRacket{}} \\ \hline
  11870. \gray{\LwhileGrammarRacket} \\ \hline
  11871. \gray{\LtupGrammarRacket} \\ \hline
  11872. \LarrayGrammarRacket \\
  11873. \begin{array}{lcl}
  11874. \LangArray{} &::=& \Exp
  11875. \end{array}
  11876. \end{array}
  11877. \]
  11878. \fi}
  11879. {\if\edition\pythonEd
  11880. \[
  11881. \begin{array}{l}
  11882. \gray{\LintGrammarPython{}} \\ \hline
  11883. \gray{\LvarGrammarPython{}} \\ \hline
  11884. \gray{\LifGrammarPython{}} \\ \hline
  11885. \gray{\LwhileGrammarPython} \\ \hline
  11886. \gray{\LtupGrammarPython} \\ \hline
  11887. \LarrayGrammarPython \\
  11888. \begin{array}{rcl}
  11889. \LangArrayM{} &::=& \Stmt^{*}
  11890. \end{array}
  11891. \end{array}
  11892. \]
  11893. \fi}
  11894. \end{tcolorbox}
  11895. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11896. \label{fig:Lvecof-concrete-syntax}
  11897. \end{figure}
  11898. \begin{figure}[tp]
  11899. \centering
  11900. \begin{tcolorbox}[colback=white]
  11901. \small
  11902. {\if\edition\racketEd
  11903. \[
  11904. \begin{array}{l}
  11905. \gray{\LintASTRacket{}} \\ \hline
  11906. \gray{\LvarASTRacket{}} \\ \hline
  11907. \gray{\LifASTRacket{}} \\ \hline
  11908. \gray{\LwhileASTRacket} \\ \hline
  11909. \gray{\LtupASTRacket} \\ \hline
  11910. \LarrayASTRacket \\
  11911. \begin{array}{lcl}
  11912. \LangArray{} &::=& \Exp
  11913. \end{array}
  11914. \end{array}
  11915. \]
  11916. \fi}
  11917. {\if\edition\pythonEd
  11918. \[
  11919. \begin{array}{l}
  11920. \gray{\LintASTPython{}} \\ \hline
  11921. \gray{\LvarASTPython{}} \\ \hline
  11922. \gray{\LifASTPython{}} \\ \hline
  11923. \gray{\LwhileASTPython} \\ \hline
  11924. \gray{\LtupASTPython} \\ \hline
  11925. \LarrayASTPython \\
  11926. \begin{array}{rcl}
  11927. \LangArrayM{} &::=& \Stmt^{*}
  11928. \end{array}
  11929. \end{array}
  11930. \]
  11931. \fi}
  11932. \end{tcolorbox}
  11933. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  11934. \label{fig:Lvecof-syntax}
  11935. \end{figure}
  11936. \begin{figure}[tp]
  11937. \begin{tcolorbox}[colback=white]
  11938. {\if\edition\racketEd
  11939. % TODO: remove the function from the following example, like the python version -Jeremy
  11940. \begin{lstlisting}
  11941. (let ([A (make-vector 2 2)])
  11942. (let ([B (make-vector 2 3)])
  11943. (let ([i 0])
  11944. (let ([prod 0])
  11945. (begin
  11946. (while (< i n)
  11947. (begin
  11948. (set! prod (+ prod (* (vector-ref A i)
  11949. (vector-ref B i))))
  11950. (set! i (+ i 1))))
  11951. prod)))))
  11952. \end{lstlisting}
  11953. \fi}
  11954. {\if\edition\pythonEd
  11955. \begin{lstlisting}
  11956. A = [2, 2]
  11957. B = [3, 3]
  11958. i = 0
  11959. prod = 0
  11960. while i != len(A):
  11961. prod = prod + A[i] * B[i]
  11962. i = i + 1
  11963. print( prod )
  11964. \end{lstlisting}
  11965. \fi}
  11966. \end{tcolorbox}
  11967. \caption{Example program that computes the inner product.}
  11968. \label{fig:inner_product}
  11969. \end{figure}
  11970. {\if\edition\racketEd
  11971. The type checker for \LangArray{} is defined in
  11972. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11973. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11974. of the initializing expression. The length expression is required to
  11975. have type \code{Integer}. The type checking of the operators
  11976. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11977. updated to handle the situation where the vector has type
  11978. \code{Vectorof}. In these cases we translate the operators to their
  11979. \code{vectorof} form so that later passes can easily distinguish
  11980. between operations on tuples versus arrays. We override the
  11981. \code{operator-types} method to provide the type signature for
  11982. multiplication: it takes two integers and returns an integer.
  11983. \fi}
  11984. {\if\edition\pythonEd
  11985. %
  11986. The type checker for \LangArray{} is defined in
  11987. Figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  11988. is \code{list[T]} where \code{T} is the type of the initializing
  11989. expressions. The type checking of the \code{len} function and the
  11990. subscript operator is updated to handle lists. The type checker now
  11991. also handles a subscript on the left-hand side of an assignment.
  11992. Regarding multiplication, it takes two integers and returns an
  11993. integer.
  11994. %
  11995. \fi}
  11996. \begin{figure}[tbp]
  11997. \begin{tcolorbox}[colback=white]
  11998. {\if\edition\racketEd
  11999. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12000. (define type-check-Lvecof-class
  12001. (class type-check-Lvec-class
  12002. (super-new)
  12003. (inherit check-type-equal?)
  12004. (define/override (operator-types)
  12005. (append '((* . ((Integer Integer) . Integer)))
  12006. (super operator-types)))
  12007. (define/override (type-check-exp env)
  12008. (lambda (e)
  12009. (define recur (type-check-exp env))
  12010. (match e
  12011. [(Prim 'make-vector (list e1 e2))
  12012. (define-values (e1^ t1) (recur e1))
  12013. (define-values (e2^ elt-type) (recur e2))
  12014. (define vec-type `(Vectorof ,elt-type))
  12015. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  12016. vec-type)]
  12017. [(Prim 'vector-ref (list e1 e2))
  12018. (define-values (e1^ t1) (recur e1))
  12019. (define-values (e2^ t2) (recur e2))
  12020. (match* (t1 t2)
  12021. [(`(Vectorof ,elt-type) 'Integer)
  12022. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12023. [(other wise) ((super type-check-exp env) e)])]
  12024. [(Prim 'vector-set! (list e1 e2 e3) )
  12025. (define-values (e-vec t-vec) (recur e1))
  12026. (define-values (e2^ t2) (recur e2))
  12027. (define-values (e-arg^ t-arg) (recur e3))
  12028. (match t-vec
  12029. [`(Vectorof ,elt-type)
  12030. (check-type-equal? elt-type t-arg e)
  12031. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12032. [else ((super type-check-exp env) e)])]
  12033. [(Prim 'vector-length (list e1))
  12034. (define-values (e1^ t1) (recur e1))
  12035. (match t1
  12036. [`(Vectorof ,t)
  12037. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12038. [else ((super type-check-exp env) e)])]
  12039. [else ((super type-check-exp env) e)])))
  12040. ))
  12041. (define (type-check-Lvecof p)
  12042. (send (new type-check-Lvecof-class) type-check-program p))
  12043. \end{lstlisting}
  12044. \fi}
  12045. {\if\edition\pythonEd
  12046. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12047. class TypeCheckLarray(TypeCheckLtup):
  12048. def type_check_exp(self, e, env):
  12049. match e:
  12050. case ast.List(es, Load()):
  12051. ts = [self.type_check_exp(e, env) for e in es]
  12052. elt_ty = ts[0]
  12053. for (ty, elt) in zip(ts, es):
  12054. self.check_type_equal(elt_ty, ty, elt)
  12055. e.has_type = ListType(elt_ty)
  12056. return e.has_type
  12057. case Call(Name('len'), [tup]):
  12058. tup_t = self.type_check_exp(tup, env)
  12059. tup.has_type = tup_t
  12060. match tup_t:
  12061. case TupleType(ts):
  12062. return IntType()
  12063. case ListType(ty):
  12064. return IntType()
  12065. case _:
  12066. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12067. case Subscript(tup, index, Load()):
  12068. tup_ty = self.type_check_exp(tup, env)
  12069. index_ty = self.type_check_exp(index, env)
  12070. self.check_type_equal(index_ty, IntType(), index)
  12071. match tup_ty:
  12072. case TupleType(ts):
  12073. match index:
  12074. case Constant(i):
  12075. return ts[i]
  12076. case _:
  12077. raise Exception('subscript required constant integer index')
  12078. case ListType(ty):
  12079. return ty
  12080. case _:
  12081. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12082. case BinOp(left, Mult(), right):
  12083. l = self.type_check_exp(left, env)
  12084. self.check_type_equal(l, IntType(), left)
  12085. r = self.type_check_exp(right, env)
  12086. self.check_type_equal(r, IntType(), right)
  12087. return IntType()
  12088. case _:
  12089. return super().type_check_exp(e, env)
  12090. def type_check_stmts(self, ss, env):
  12091. if len(ss) == 0:
  12092. return VoidType()
  12093. match ss[0]:
  12094. case Assign([Subscript(tup, index, Store())], value):
  12095. tup_t = self.type_check_exp(tup, env)
  12096. value_t = self.type_check_exp(value, env)
  12097. index_ty = self.type_check_exp(index, env)
  12098. self.check_type_equal(index_ty, IntType(), index)
  12099. match tup_t:
  12100. case ListType(ty):
  12101. self.check_type_equal(ty, value_t, ss[0])
  12102. case _:
  12103. raise Exception('type_check_stmts: expected a list, not ' \
  12104. + repr(tup_t))
  12105. return self.type_check_stmts(ss[1:], env)
  12106. case _:
  12107. return super().type_check_stmts(ss, env)
  12108. \end{lstlisting}
  12109. \fi}
  12110. \end{tcolorbox}
  12111. \caption{Type checker for the \LangArray{} language.}
  12112. \label{fig:type-check-Lvecof}
  12113. \end{figure}
  12114. The interpreter for \LangArray{} is defined in
  12115. Figure~\ref{fig:interp-Lvecof}.
  12116. \racket{The \code{make-vector} operator is
  12117. implemented with Racket's \code{make-vector} function and
  12118. multiplication is \code{fx*}, multiplication for \code{fixnum}
  12119. integers.}
  12120. %
  12121. \python{We implement list creation with a Python list comprehension
  12122. and multiplication is implemented with Python multiplication. We
  12123. add a case to handle a subscript on the left-hand side of
  12124. assignment. Other uses of subscript can be handled by the existing
  12125. code for tuples.}
  12126. \begin{figure}[tbp]
  12127. \begin{tcolorbox}[colback=white]
  12128. {\if\edition\racketEd
  12129. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12130. (define interp-Lvecof-class
  12131. (class interp-Lvec-class
  12132. (super-new)
  12133. (define/override (interp-op op)
  12134. (match op
  12135. ['make-vector make-vector]
  12136. ['* fx*]
  12137. [else (super interp-op op)]))
  12138. ))
  12139. (define (interp-Lvecof p)
  12140. (send (new interp-Lvecof-class) interp-program p))
  12141. \end{lstlisting}
  12142. \fi}
  12143. {\if\edition\pythonEd
  12144. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12145. class InterpLarray(InterpLtup):
  12146. def interp_exp(self, e, env):
  12147. match e:
  12148. case ast.List(es, Load()):
  12149. return [self.interp_exp(e, env) for e in es]
  12150. case BinOp(left, Mult(), right):
  12151. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  12152. return l * r
  12153. case _:
  12154. return super().interp_exp(e, env)
  12155. def interp_stmts(self, ss, env):
  12156. if len(ss) == 0:
  12157. return
  12158. match ss[0]:
  12159. case Assign([Subscript(lst, index)], value):
  12160. lst = self.interp_exp(lst, env)
  12161. index = self.interp_exp(index, env)
  12162. lst[index] = self.interp_exp(value, env)
  12163. return self.interp_stmts(ss[1:], env)
  12164. case _:
  12165. return super().interp_stmts(ss, env)
  12166. \end{lstlisting}
  12167. \fi}
  12168. \end{tcolorbox}
  12169. \caption{Interpreter for \LangArray{}.}
  12170. \label{fig:interp-Lvecof}
  12171. \end{figure}
  12172. \subsection{Data Representation}
  12173. \label{sec:array-rep}
  12174. Just like tuples, we store arrays on the heap which means that the
  12175. garbage collector will need to inspect arrays. An immediate thought is
  12176. to use the same representation for arrays that we use for tuples.
  12177. However, we limit tuples to a length of $50$ so that their length and
  12178. pointer mask can fit into the 64-bit tag at the beginning of each
  12179. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12180. millions of elements, so we need more bits to store the length.
  12181. However, because arrays are homogeneous, we only need $1$ bit for the
  12182. pointer mask instead of one bit per array elements. Finally, the
  12183. garbage collector will need to be able to distinguish between tuples
  12184. and arrays, so we need to reserve $1$ bit for that purpose. So we
  12185. arrive at the following layout for the 64-bit tag at the beginning of
  12186. an array:
  12187. \begin{itemize}
  12188. \item The right-most bit is the forwarding bit, just like in a tuple.
  12189. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  12190. it is not.
  12191. \item The next bit to the left is the pointer mask. A $0$ indicates
  12192. that none of the elements are pointers to the heap and a $1$
  12193. indicates that all of the elements are pointers.
  12194. \item The next $60$ bits store the length of the array.
  12195. \item The bit at position $62$ distinguishes between a tuple ($0$)
  12196. versus an array ($1$).
  12197. \item The left-most bit is reserved for use in Chapter~\ref{ch:Lgrad}.
  12198. \end{itemize}
  12199. %% Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  12200. %% differentiate the kinds of values that have been injected into the
  12201. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12202. %% to indicate that the value is an array.
  12203. In the following subsections we provide hints regarding how to update
  12204. the passes to handle arrays.
  12205. \subsection{Type-based Resolution}
  12206. As noted above, with the addition of arrays, several operators have
  12207. become \emph{overloaded}, that is, they can be applied to values of
  12208. more than one type. In this case, the element access and \code{len}
  12209. operators can be applied to both tuples and arrays. This kind of
  12210. overloading is quite common in programming languages, so many
  12211. compilers perform \emph{overload resolution}\index{subject}{overload resolution}
  12212. to handle it. The idea is to translate each overloaded
  12213. operator into different operators for the different types.
  12214. Implement a new pass named \code{resolve}.
  12215. Translate the reading of an array element
  12216. into a call to
  12217. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  12218. and the writing of an array element to
  12219. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  12220. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  12221. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  12222. When these operators are applied to tuples, leave them as-is.
  12223. %
  12224. \python{The type checker for \LangArray{} adds a \code{has\_type}
  12225. field which can be inspected to determine whether the operator
  12226. is applied to a tuple or an array.}
  12227. \subsection{Bounds Checking}
  12228. We recommend inserting a new pass named \code{check\_bounds} that
  12229. inserts code around each \racket{\code{vector-ref} and \code{vector-set!}}
  12230. \python{subscript} operation to ensure that the index is greater than or
  12231. equal to zero and less than the array's length.
  12232. %% \subsection{Reveal Casts}
  12233. %% The array-access operators \code{vectorof-ref} and
  12234. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12235. %% \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  12236. %% that the type checker cannot tell whether the index will be in bounds,
  12237. %% so the bounds check must be performed at run time. Recall that the
  12238. %% \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  12239. %% an \code{If} arround a vector reference for update to check whether
  12240. %% the index is less than the length. You should do the same for
  12241. %% \code{vectorof-ref} and \code{vectorof-set!} .
  12242. %% In addition, the handling of the \code{any-vector} operators in
  12243. %% \code{reveal-casts} needs to be updated to account for arrays that are
  12244. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  12245. %% generated code should test whether the tag is for tuples (\code{010})
  12246. %% or arrays (\code{110}) and then dispatch to either
  12247. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12248. %% we add a case in \code{select\_instructions} to generate the
  12249. %% appropriate instructions for accessing the array length from the
  12250. %% header of an array.
  12251. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12252. %% the generated code needs to check that the index is less than the
  12253. %% vector length, so like the code for \code{any-vector-length}, check
  12254. %% the tag to determine whether to use \code{any-vector-length} or
  12255. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  12256. %% is complete, the generated code can use \code{any-vector-ref} and
  12257. %% \code{any-vector-set!} for both tuples and arrays because the
  12258. %% instructions used for those operators do not look at the tag at the
  12259. %% front of the tuple or array.
  12260. \subsection{Expose Allocation}
  12261. This pass should translate array creation into lower-level
  12262. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  12263. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  12264. argument must be \ARRAYTY{T} where $T$ is the element type for the
  12265. array. The \code{AllocateArray} AST node allocates an array of the
  12266. length specified by the $\Exp$ but does not initialize the elements of
  12267. the array. Generate code in this pass to initialize the elements.
  12268. \subsection{Remove Complex Operands}
  12269. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  12270. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12271. complex and its subexpression must be atomic.
  12272. \subsection{Explicate Control}
  12273. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  12274. \code{explicate\_assign}.
  12275. \subsection{Select Instructions}
  12276. Generate instructions for \code{AllocateArray} similar to those for
  12277. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  12278. that the tag at the front of the array should instead use the
  12279. representation discussed in Section~\ref{sec:array-rep}.
  12280. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  12281. extract the length from the tag according to the representation discussed in
  12282. Section~\ref{sec:array-rep}.
  12283. The instructions generated for accessing an element of an array differ
  12284. from those for a tuple (Section~\ref{sec:select-instructions-gc}) in
  12285. that the index is not a constant so the offset must be computed at
  12286. runtime.
  12287. %% Also, note that assignment to an array element may appear in
  12288. %% as a stand-alone statement, so make sure to handle that situation in
  12289. %% this pass.
  12290. %% Finally, the instructions for \code{any-vectorof-length} should be
  12291. %% similar to those for \code{vectorof-length}, except that one must
  12292. %% first project the array by writing zeroes into the $3$-bit tag
  12293. \begin{exercise}\normalfont\normalsize
  12294. Implement a compiler for the \LangArray{} language by extending your
  12295. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12296. programs, including the one in Figure~\ref{fig:inner_product} and also
  12297. a program that multiplies two matrices. Note that although matrices
  12298. are 2-dimensional arrays, they can be encoded into 1-dimensional
  12299. arrays by laying out each row in the array, one after the next.
  12300. \end{exercise}
  12301. {\if\edition\racketEd
  12302. \section{Challenge: Generational Collection}
  12303. The copying collector described in Section~\ref{sec:GC} can incur
  12304. significant runtime overhead because the call to \code{collect} takes
  12305. time proportional to all of the live data. One way to reduce this
  12306. overhead is to reduce how much data is inspected in each call to
  12307. \code{collect}. In particular, researchers have observed that recently
  12308. allocated data is more likely to become garbage then data that has
  12309. survived one or more previous calls to \code{collect}. This insight
  12310. motivated the creation of \emph{generational garbage collectors}
  12311. \index{subject}{generational garbage collector} that
  12312. 1) segregates data according to its age into two or more generations,
  12313. 2) allocates less space for younger generations, so collecting them is
  12314. faster, and more space for the older generations, and 3) performs
  12315. collection on the younger generations more frequently then for older
  12316. generations~\citep{Wilson:1992fk}.
  12317. For this challenge assignment, the goal is to adapt the copying
  12318. collector implemented in \code{runtime.c} to use two generations, one
  12319. for young data and one for old data. Each generation consists of a
  12320. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  12321. \code{collect} function to use the two generations.
  12322. \begin{enumerate}
  12323. \item Copy the young generation's FromSpace to its ToSpace then switch
  12324. the role of the ToSpace and FromSpace
  12325. \item If there is enough space for the requested number of bytes in
  12326. the young FromSpace, then return from \code{collect}.
  12327. \item If there is not enough space in the young FromSpace for the
  12328. requested bytes, then move the data from the young generation to the
  12329. old one with the following steps:
  12330. \begin{enumerate}
  12331. \item If there is enough room in the old FromSpace, copy the young
  12332. FromSpace to the old FromSpace and then return.
  12333. \item If there is not enough room in the old FromSpace, then collect
  12334. the old generation by copying the old FromSpace to the old ToSpace
  12335. and swap the roles of the old FromSpace and ToSpace.
  12336. \item If there is enough room now, copy the young FromSpace to the
  12337. old FromSpace and return. Otherwise, allocate a larger FromSpace
  12338. and ToSpace for the old generation. Copy the young FromSpace and
  12339. the old FromSpace into the larger FromSpace for the old
  12340. generation and then return.
  12341. \end{enumerate}
  12342. \end{enumerate}
  12343. We recommend that you generalize the \code{cheney} function so that it
  12344. can be used for all the copies mentioned above: between the young
  12345. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  12346. between the young FromSpace and old FromSpace. This can be
  12347. accomplished by adding parameters to \code{cheney} that replace its
  12348. use of the global variables \code{fromspace\_begin},
  12349. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  12350. Note that the collection of the young generation does not traverse the
  12351. old generation. This introduces a potential problem: there may be
  12352. young data that is only reachable through pointers in the old
  12353. generation. If these pointers are not taken into account, the
  12354. collector could throw away young data that is live! One solution,
  12355. called \emph{pointer recording}, is to maintain a set of all the
  12356. pointers from the old generation into the new generation and consider
  12357. this set as part of the root set. To maintain this set, the compiler
  12358. must insert extra instructions around every \code{vector-set!}. If the
  12359. vector being modified is in the old generation, and if the value being
  12360. written is a pointer into the new generation, than that pointer must
  12361. be added to the set. Also, if the value being overwritten was a
  12362. pointer into the new generation, then that pointer should be removed
  12363. from the set.
  12364. \begin{exercise}\normalfont\normalsize
  12365. Adapt the \code{collect} function in \code{runtime.c} to implement
  12366. generational garbage collection, as outlined in this section.
  12367. Update the code generation for \code{vector-set!} to implement
  12368. pointer recording. Make sure that your new compiler and runtime
  12369. passes your test suite.
  12370. \end{exercise}
  12371. \fi}
  12372. \section{Further Reading}
  12373. \citet{Appel90} describes many data representation approaches,
  12374. including the ones used in the compilation of Standard ML.
  12375. There are many alternatives to copying collectors (and their bigger
  12376. siblings, the generational collectors) when its comes to garbage
  12377. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12378. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12379. collectors are that allocation is fast (just a comparison and pointer
  12380. increment), there is no fragmentation, cyclic garbage is collected,
  12381. and the time complexity of collection only depends on the amount of
  12382. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12383. main disadvantages of a two-space copying collector is that it uses a
  12384. lot of extra space and takes a long time to perform the copy, though
  12385. these problems are ameliorated in generational collectors.
  12386. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12387. small objects and generate a lot of garbage, so copying and
  12388. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12389. Garbage collection is an active research topic, especially concurrent
  12390. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12391. developing new techniques and revisiting old
  12392. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12393. meet every year at the International Symposium on Memory Management to
  12394. present these findings.
  12395. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12396. \chapter{Functions}
  12397. \label{ch:Lfun}
  12398. \index{subject}{function}
  12399. This chapter studies the compilation of a subset of \racket{Typed
  12400. Racket}\python{Python} in which only top-level function definitions
  12401. are allowed. This kind of function appears in the C programming
  12402. language and it serves as an important stepping stone to implementing
  12403. lexically-scoped functions in the form of \key{lambda} abstractions,
  12404. which is the topic of Chapter~\ref{ch:Llambda}.
  12405. \section{The \LangFun{} Language}
  12406. The concrete and abstract syntax for function definitions and function
  12407. application is shown in Figures~\ref{fig:Lfun-concrete-syntax} and
  12408. \ref{fig:Lfun-syntax}, where we define the \LangFun{} language.
  12409. Programs in \LangFun{} begin with zero or more function definitions.
  12410. The function names from these definitions are in-scope for the entire
  12411. program, including all of the function definitions (so the ordering of
  12412. function definitions does not matter).
  12413. %
  12414. \python{The abstract syntax for function parameters in
  12415. Figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  12416. consists of a parameter name and its type. This design differs from
  12417. Python's \code{ast} module, which has a more complex structure for
  12418. function parameters to handle keyword parameters,
  12419. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12420. complex Python abstract syntax into the simpler syntax of
  12421. Figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  12422. \code{FunctionDef} constructor are for decorators and a type
  12423. comment, neither of which are used by our compiler. We recommend
  12424. replacing them with \code{None} in the \code{shrink} pass.
  12425. }
  12426. %
  12427. The concrete syntax for function application\index{subject}{function
  12428. application} is
  12429. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12430. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12431. where the first expression
  12432. must evaluate to a function and the remaining expressions are the arguments. The
  12433. abstract syntax for function application is
  12434. $\APPLY{\Exp}{\Exp^*}$.
  12435. %% The syntax for function application does not include an explicit
  12436. %% keyword, which is error prone when using \code{match}. To alleviate
  12437. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12438. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12439. Functions are first-class in the sense that a function pointer
  12440. \index{subject}{function pointer} is data and can be stored in memory or passed
  12441. as a parameter to another function. Thus, there is a function
  12442. type, written
  12443. {\if\edition\racketEd
  12444. \begin{lstlisting}
  12445. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12446. \end{lstlisting}
  12447. \fi}
  12448. {\if\edition\pythonEd
  12449. \begin{lstlisting}
  12450. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12451. \end{lstlisting}
  12452. \fi}
  12453. %
  12454. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12455. through $\Type_n$ and whose return type is $\Type_R$. The main
  12456. limitation of these functions (with respect to
  12457. \racket{Racket}\python{Python} functions) is that they are not
  12458. lexically scoped. That is, the only external entities that can be
  12459. referenced from inside a function body are other globally-defined
  12460. functions. The syntax of \LangFun{} prevents function definitions from being
  12461. nested inside each other.
  12462. \newcommand{\LfunGrammarRacket}{
  12463. \begin{array}{lcl}
  12464. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12465. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12466. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12467. \end{array}
  12468. }
  12469. \newcommand{\LfunASTRacket}{
  12470. \begin{array}{lcl}
  12471. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12472. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12473. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12474. \end{array}
  12475. }
  12476. \newcommand{\LfunGrammarPython}{
  12477. \begin{array}{lcl}
  12478. \Type &::=& \key{int}
  12479. \MID \key{bool}
  12480. \MID \key{tuple}\LS \Type^+ \RS
  12481. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12482. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12483. \Stmt &::=& \CRETURN{\Exp} \\
  12484. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12485. \end{array}
  12486. }
  12487. \newcommand{\LfunASTPython}{
  12488. \begin{array}{lcl}
  12489. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  12490. \MID \key{TupleType}\LS\Type^+\RS\\
  12491. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12492. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12493. \Stmt &::=& \RETURN{\Exp} \\
  12494. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  12495. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12496. \end{array}
  12497. }
  12498. \begin{figure}[tp]
  12499. \centering
  12500. \begin{tcolorbox}[colback=white]
  12501. \small
  12502. {\if\edition\racketEd
  12503. \[
  12504. \begin{array}{l}
  12505. \gray{\LintGrammarRacket{}} \\ \hline
  12506. \gray{\LvarGrammarRacket{}} \\ \hline
  12507. \gray{\LifGrammarRacket{}} \\ \hline
  12508. \gray{\LwhileGrammarRacket} \\ \hline
  12509. \gray{\LtupGrammarRacket} \\ \hline
  12510. \LfunGrammarRacket \\
  12511. \begin{array}{lcl}
  12512. \LangFunM{} &::=& \Def \ldots \; \Exp
  12513. \end{array}
  12514. \end{array}
  12515. \]
  12516. \fi}
  12517. {\if\edition\pythonEd
  12518. \[
  12519. \begin{array}{l}
  12520. \gray{\LintGrammarPython{}} \\ \hline
  12521. \gray{\LvarGrammarPython{}} \\ \hline
  12522. \gray{\LifGrammarPython{}} \\ \hline
  12523. \gray{\LwhileGrammarPython} \\ \hline
  12524. \gray{\LtupGrammarPython} \\ \hline
  12525. \LfunGrammarPython \\
  12526. \begin{array}{rcl}
  12527. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12528. \end{array}
  12529. \end{array}
  12530. \]
  12531. \fi}
  12532. \end{tcolorbox}
  12533. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  12534. \label{fig:Lfun-concrete-syntax}
  12535. \end{figure}
  12536. \begin{figure}[tp]
  12537. \centering
  12538. \begin{tcolorbox}[colback=white]
  12539. \small
  12540. {\if\edition\racketEd
  12541. \[
  12542. \begin{array}{l}
  12543. \gray{\LintOpAST} \\ \hline
  12544. \gray{\LvarASTRacket{}} \\ \hline
  12545. \gray{\LifASTRacket{}} \\ \hline
  12546. \gray{\LwhileASTRacket{}} \\ \hline
  12547. \gray{\LtupASTRacket{}} \\ \hline
  12548. \LfunASTRacket \\
  12549. \begin{array}{lcl}
  12550. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12551. \end{array}
  12552. \end{array}
  12553. \]
  12554. \fi}
  12555. {\if\edition\pythonEd
  12556. \[
  12557. \begin{array}{l}
  12558. \gray{\LintASTPython{}} \\ \hline
  12559. \gray{\LvarASTPython{}} \\ \hline
  12560. \gray{\LifASTPython{}} \\ \hline
  12561. \gray{\LwhileASTPython} \\ \hline
  12562. \gray{\LtupASTPython} \\ \hline
  12563. \LfunASTPython \\
  12564. \begin{array}{rcl}
  12565. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12566. \end{array}
  12567. \end{array}
  12568. \]
  12569. \fi}
  12570. \end{tcolorbox}
  12571. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12572. \label{fig:Lfun-syntax}
  12573. \end{figure}
  12574. The program in Figure~\ref{fig:Lfun-function-example} is a
  12575. representative example of defining and using functions in \LangFun{}.
  12576. We define a function \code{map} that applies some other function
  12577. \code{f} to both elements of a tuple and returns a new tuple
  12578. containing the results. We also define a function \code{inc}. The
  12579. program applies \code{map} to \code{inc} and
  12580. %
  12581. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12582. %
  12583. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12584. %
  12585. from which we return \code{42}.
  12586. \begin{figure}[tbp]
  12587. \begin{tcolorbox}[colback=white]
  12588. {\if\edition\racketEd
  12589. \begin{lstlisting}
  12590. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12591. : (Vector Integer Integer)
  12592. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12593. (define (inc [x : Integer]) : Integer
  12594. (+ x 1))
  12595. (vector-ref (map inc (vector 0 41)) 1)
  12596. \end{lstlisting}
  12597. \fi}
  12598. {\if\edition\pythonEd
  12599. \begin{lstlisting}
  12600. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12601. return f(v[0]), f(v[1])
  12602. def inc(x : int) -> int:
  12603. return x + 1
  12604. print( map(inc, (0, 41))[1] )
  12605. \end{lstlisting}
  12606. \fi}
  12607. \end{tcolorbox}
  12608. \caption{Example of using functions in \LangFun{}.}
  12609. \label{fig:Lfun-function-example}
  12610. \end{figure}
  12611. The definitional interpreter for \LangFun{} is in
  12612. Figure~\ref{fig:interp-Lfun}. The case for the
  12613. %
  12614. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12615. %
  12616. AST is responsible for setting up the mutual recursion between the
  12617. top-level function definitions.
  12618. %
  12619. \racket{We use the classic back-patching
  12620. \index{subject}{back-patching} approach that uses mutable variables
  12621. and makes two passes over the function
  12622. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12623. top-level environment using a mutable cons cell for each function
  12624. definition. Note that the \code{lambda} value for each function is
  12625. incomplete; it does not yet include the environment. Once the
  12626. top-level environment is constructed, we then iterate over it and
  12627. update the \code{lambda} values to use the top-level environment.}
  12628. %
  12629. \python{We create a dictionary named \code{env} and fill it in
  12630. by mapping each function name to a new \code{Function} value,
  12631. each of which stores a reference to the \code{env}.
  12632. (We define the class \code{Function} for this purpose.)}
  12633. %
  12634. To interpret a function \racket{application}\python{call}, we match
  12635. the result of the function expression to obtain a function value. We
  12636. then extend the function's environment with the mapping of parameters to
  12637. argument values. Finally, we interpret the body of the function in
  12638. this extended environment.
  12639. \begin{figure}[tp]
  12640. \begin{tcolorbox}[colback=white]
  12641. {\if\edition\racketEd
  12642. \begin{lstlisting}
  12643. (define interp-Lfun-class
  12644. (class interp-Lvec-class
  12645. (super-new)
  12646. (define/override ((interp-exp env) e)
  12647. (define recur (interp-exp env))
  12648. (match e
  12649. [(Apply fun args)
  12650. (define fun-val (recur fun))
  12651. (define arg-vals (for/list ([e args]) (recur e)))
  12652. (match fun-val
  12653. [`(function (,xs ...) ,body ,fun-env)
  12654. (define params-args (for/list ([x xs] [arg arg-vals])
  12655. (cons x (box arg))))
  12656. (define new-env (append params-args fun-env))
  12657. ((interp-exp new-env) body)]
  12658. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12659. [else ((super interp-exp env) e)]
  12660. ))
  12661. (define/public (interp-def d)
  12662. (match d
  12663. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12664. (cons f (box `(function ,xs ,body ())))]))
  12665. (define/override (interp-program p)
  12666. (match p
  12667. [(ProgramDefsExp info ds body)
  12668. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12669. (for/list ([f (in-dict-values top-level)])
  12670. (set-box! f (match (unbox f)
  12671. [`(function ,xs ,body ())
  12672. `(function ,xs ,body ,top-level)])))
  12673. ((interp-exp top-level) body))]))
  12674. ))
  12675. (define (interp-Lfun p)
  12676. (send (new interp-Lfun-class) interp-program p))
  12677. \end{lstlisting}
  12678. \fi}
  12679. {\if\edition\pythonEd
  12680. \begin{lstlisting}
  12681. class InterpLfun(InterpLtup):
  12682. def apply_fun(self, fun, args, e):
  12683. match fun:
  12684. case Function(name, xs, body, env):
  12685. new_env = env.copy().update(zip(xs, args))
  12686. return self.interp_stmts(body, new_env)
  12687. case _:
  12688. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12689. def interp_exp(self, e, env):
  12690. match e:
  12691. case Call(Name('input_int'), []):
  12692. return super().interp_exp(e, env)
  12693. case Call(func, args):
  12694. f = self.interp_exp(func, env)
  12695. vs = [self.interp_exp(arg, env) for arg in args]
  12696. return self.apply_fun(f, vs, e)
  12697. case _:
  12698. return super().interp_exp(e, env)
  12699. def interp_stmts(self, ss, env):
  12700. if len(ss) == 0:
  12701. return
  12702. match ss[0]:
  12703. case Return(value):
  12704. return self.interp_exp(value, env)
  12705. case FunctionDef(name, params, bod, dl, returns, comment):
  12706. ps = [x for (x,t) in params]
  12707. env[name] = Function(name, ps, bod, env)
  12708. return self.interp_stmts(ss[1:], env)
  12709. case _:
  12710. return super().interp_stmts(ss, env)
  12711. def interp(self, p):
  12712. match p:
  12713. case Module(ss):
  12714. env = {}
  12715. self.interp_stmts(ss, env)
  12716. if 'main' in env.keys():
  12717. self.apply_fun(env['main'], [], None)
  12718. case _:
  12719. raise Exception('interp: unexpected ' + repr(p))
  12720. \end{lstlisting}
  12721. \fi}
  12722. \end{tcolorbox}
  12723. \caption{Interpreter for the \LangFun{} language.}
  12724. \label{fig:interp-Lfun}
  12725. \end{figure}
  12726. %\margincomment{TODO: explain type checker}
  12727. The type checker for \LangFun{} is in
  12728. Figure~\ref{fig:type-check-Lfun}.
  12729. %
  12730. \python{(We omit the code that parses function parameters into the
  12731. simpler abstract syntax.)}
  12732. %
  12733. Similar to the interpreter, the case for the
  12734. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12735. %
  12736. AST is responsible for setting up the mutual recursion between the
  12737. top-level function definitions. We begin by create a mapping
  12738. \code{env} from every function name to its type. We then type check
  12739. the program using this mapping.
  12740. %
  12741. In the case for function \racket{application}\python{call}, we match
  12742. the type of the function expression to a function type and check that
  12743. the types of the argument expressions are equal to the function's
  12744. parameter types. The type of the \racket{application}\python{call} as
  12745. a whole is the return type from the function type.
  12746. \begin{figure}[tp]
  12747. \begin{tcolorbox}[colback=white]
  12748. {\if\edition\racketEd
  12749. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12750. (define type-check-Lfun-class
  12751. (class type-check-Lvec-class
  12752. (super-new)
  12753. (inherit check-type-equal?)
  12754. (define/public (type-check-apply env e es)
  12755. (define-values (e^ ty) ((type-check-exp env) e))
  12756. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12757. ((type-check-exp env) e)))
  12758. (match ty
  12759. [`(,ty^* ... -> ,rt)
  12760. (for ([arg-ty ty*] [param-ty ty^*])
  12761. (check-type-equal? arg-ty param-ty (Apply e es)))
  12762. (values e^ e* rt)]))
  12763. (define/override (type-check-exp env)
  12764. (lambda (e)
  12765. (match e
  12766. [(FunRef f n)
  12767. (values (FunRef f n) (dict-ref env f))]
  12768. [(Apply e es)
  12769. (define-values (e^ es^ rt) (type-check-apply env e es))
  12770. (values (Apply e^ es^) rt)]
  12771. [(Call e es)
  12772. (define-values (e^ es^ rt) (type-check-apply env e es))
  12773. (values (Call e^ es^) rt)]
  12774. [else ((super type-check-exp env) e)])))
  12775. (define/public (type-check-def env)
  12776. (lambda (e)
  12777. (match e
  12778. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12779. (define new-env (append (map cons xs ps) env))
  12780. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12781. (check-type-equal? ty^ rt body)
  12782. (Def f p:t* rt info body^)])))
  12783. (define/public (fun-def-type d)
  12784. (match d
  12785. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12786. (define/override (type-check-program e)
  12787. (match e
  12788. [(ProgramDefsExp info ds body)
  12789. (define env (for/list ([d ds])
  12790. (cons (Def-name d) (fun-def-type d))))
  12791. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12792. (define-values (body^ ty) ((type-check-exp env) body))
  12793. (check-type-equal? ty 'Integer body)
  12794. (ProgramDefsExp info ds^ body^)]))))
  12795. (define (type-check-Lfun p)
  12796. (send (new type-check-Lfun-class) type-check-program p))
  12797. \end{lstlisting}
  12798. \fi}
  12799. {\if\edition\pythonEd
  12800. \begin{lstlisting}
  12801. class TypeCheckLfun(TypeCheckLtup):
  12802. def type_check_exp(self, e, env):
  12803. match e:
  12804. case Call(Name('input_int'), []):
  12805. return super().type_check_exp(e, env)
  12806. case Call(func, args):
  12807. func_t = self.type_check_exp(func, env)
  12808. args_t = [self.type_check_exp(arg, env) for arg in args]
  12809. match func_t:
  12810. case FunctionType(params_t, return_t):
  12811. for (arg_t, param_t) in zip(args_t, params_t):
  12812. check_type_equal(param_t, arg_t, e)
  12813. return return_t
  12814. case _:
  12815. raise Exception('type_check_exp: in call, unexpected ' +
  12816. repr(func_t))
  12817. case _:
  12818. return super().type_check_exp(e, env)
  12819. def type_check_stmts(self, ss, env):
  12820. if len(ss) == 0:
  12821. return
  12822. match ss[0]:
  12823. case FunctionDef(name, params, body, dl, returns, comment):
  12824. new_env = env.copy().update(params)
  12825. rt = self.type_check_stmts(body, new_env)
  12826. check_type_equal(returns, rt, ss[0])
  12827. return self.type_check_stmts(ss[1:], env)
  12828. case Return(value):
  12829. return self.type_check_exp(value, env)
  12830. case _:
  12831. return super().type_check_stmts(ss, env)
  12832. def type_check(self, p):
  12833. match p:
  12834. case Module(body):
  12835. env = {}
  12836. for s in body:
  12837. match s:
  12838. case FunctionDef(name, params, bod, dl, returns, comment):
  12839. if name in env:
  12840. raise Exception('type_check: function ' +
  12841. repr(name) + ' defined twice')
  12842. params_t = [t for (x,t) in params]
  12843. env[name] = FunctionType(params_t, returns)
  12844. self.type_check_stmts(body, env)
  12845. case _:
  12846. raise Exception('type_check: unexpected ' + repr(p))
  12847. \end{lstlisting}
  12848. \fi}
  12849. \end{tcolorbox}
  12850. \caption{Type checker for the \LangFun{} language.}
  12851. \label{fig:type-check-Lfun}
  12852. \end{figure}
  12853. \clearpage
  12854. \section{Functions in x86}
  12855. \label{sec:fun-x86}
  12856. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12857. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12858. %% \margincomment{\tiny Talk about the return address on the
  12859. %% stack and what callq and retq does.\\ --Jeremy }
  12860. The x86 architecture provides a few features to support the
  12861. implementation of functions. We have already seen that there are
  12862. labels in x86 so that one can refer to the location of an instruction,
  12863. as is needed for jump instructions. Labels can also be used to mark
  12864. the beginning of the instructions for a function. Going further, we
  12865. can obtain the address of a label by using the \key{leaq}
  12866. instruction. For example, the following puts the address of the
  12867. \code{inc} label into the \code{rbx} register.
  12868. \begin{lstlisting}
  12869. leaq inc(%rip), %rbx
  12870. \end{lstlisting}
  12871. Recall from Section~\ref{sec:select-instructions-gc} that
  12872. \verb!inc(%rip)! is an example of instruction-pointer relative
  12873. addressing. It computes the address of \code{inc}.
  12874. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12875. to functions whose locations were given by a label, such as
  12876. \code{read\_int}. To support function calls in this chapter we instead
  12877. will be jumping to functions whose location are given by an address in
  12878. a register, that is, we shall use \emph{indirect function calls}. The
  12879. x86 syntax for this is a \code{callq} instruction but with an asterisk
  12880. before the register name.\index{subject}{indirect function call}
  12881. \begin{lstlisting}
  12882. callq *%rbx
  12883. \end{lstlisting}
  12884. \subsection{Calling Conventions}
  12885. \label{sec:calling-conventions-fun}
  12886. \index{subject}{calling conventions}
  12887. The \code{callq} instruction provides partial support for implementing
  12888. functions: it pushes the return address on the stack and it jumps to
  12889. the target. However, \code{callq} does not handle
  12890. \begin{enumerate}
  12891. \item parameter passing,
  12892. \item pushing frames on the procedure call stack and popping them off,
  12893. or
  12894. \item determining how registers are shared by different functions.
  12895. \end{enumerate}
  12896. Regarding (1) parameter passing, recall that the x86-64 calling
  12897. convention for Unix-based system uses the following six registers to
  12898. pass arguments to a function, in this order.
  12899. \begin{lstlisting}
  12900. rdi rsi rdx rcx r8 r9
  12901. \end{lstlisting}
  12902. If there are more than six arguments, then the calling convention
  12903. mandates to use space on the frame of the caller for the rest of the
  12904. arguments. However, to ease the implementation of efficient tail calls
  12905. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12906. arguments.
  12907. %
  12908. The return value of the function is stored in register \code{rax}.
  12909. \index{subject}{prelude}\index{subject}{conclusion}
  12910. Regarding (2) frames \index{subject}{frame} and the procedure call
  12911. stack, \index{subject}{procedure call stack} recall from
  12912. Section~\ref{sec:x86} that the stack grows down and each function call
  12913. uses a chunk of space on the stack called a frame. The caller sets the
  12914. stack pointer, register \code{rsp}, to the last data item in its
  12915. frame. The callee must not change anything in the caller's frame, that
  12916. is, anything that is at or above the stack pointer. The callee is free
  12917. to use locations that are below the stack pointer.
  12918. Recall that we store variables of tuple type on the root stack. So
  12919. the prelude of a function needs to move the root stack pointer
  12920. \code{r15} up according to the number of variables of tuple type and
  12921. the conclusion needs to move the root stack pointer back down. Also,
  12922. the prelude must initialize to \code{0} this frame's slots in the root
  12923. stack to signal to the garbage collector that those slots do not yet
  12924. contain a valid pointer. Otherwise the garbage collector will
  12925. interpret the garbage bits in those slots as memory addresses and try
  12926. to traverse them, causing serious mayhem!
  12927. Regarding (3) the sharing of registers between different functions,
  12928. recall from Section~\ref{sec:calling-conventions} that the registers
  12929. are divided into two groups, the caller-saved registers and the
  12930. callee-saved registers. The caller should assume that all the
  12931. caller-saved registers get overwritten with arbitrary values by the
  12932. callee. For that reason we recommend in
  12933. Section~\ref{sec:calling-conventions} that variables that are live
  12934. during a function call should not be assigned to caller-saved
  12935. registers.
  12936. On the flip side, if the callee wants to use a callee-saved register,
  12937. the callee must save the contents of those registers on their stack
  12938. frame and then put them back prior to returning to the caller. For
  12939. that reason we recommend in Section~\ref{sec:calling-conventions} that if
  12940. the register allocator assigns a variable to a callee-saved register,
  12941. then the prelude of the \code{main} function must save that register
  12942. to the stack and the conclusion of \code{main} must restore it. This
  12943. recommendation now generalizes to all functions.
  12944. Recall that the base pointer, register \code{rbp}, is used as a
  12945. point-of-reference within a frame, so that each local variable can be
  12946. accessed at a fixed offset from the base pointer
  12947. (Section~\ref{sec:x86}).
  12948. %
  12949. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12950. and callee frames.
  12951. \begin{figure}[tbp]
  12952. \centering
  12953. \begin{tcolorbox}[colback=white]
  12954. \begin{tabular}{r|r|l|l} \hline
  12955. Caller View & Callee View & Contents & Frame \\ \hline
  12956. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12957. 0(\key{\%rbp}) & & old \key{rbp} \\
  12958. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12959. \ldots & & \ldots \\
  12960. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12961. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12962. \ldots & & \ldots \\
  12963. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12964. %% & & \\
  12965. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12966. %% & \ldots & \ldots \\
  12967. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12968. \hline
  12969. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12970. & 0(\key{\%rbp}) & old \key{rbp} \\
  12971. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12972. & \ldots & \ldots \\
  12973. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12974. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12975. & \ldots & \ldots \\
  12976. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12977. \end{tabular}
  12978. \end{tcolorbox}
  12979. \caption{Memory layout of caller and callee frames.}
  12980. \label{fig:call-frames}
  12981. \end{figure}
  12982. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12983. %% local variables and for storing the values of callee-saved registers
  12984. %% (we shall refer to all of these collectively as ``locals''), and that
  12985. %% at the beginning of a function we move the stack pointer \code{rsp}
  12986. %% down to make room for them.
  12987. %% We recommend storing the local variables
  12988. %% first and then the callee-saved registers, so that the local variables
  12989. %% can be accessed using \code{rbp} the same as before the addition of
  12990. %% functions.
  12991. %% To make additional room for passing arguments, we shall
  12992. %% move the stack pointer even further down. We count how many stack
  12993. %% arguments are needed for each function call that occurs inside the
  12994. %% body of the function and find their maximum. Adding this number to the
  12995. %% number of locals gives us how much the \code{rsp} should be moved at
  12996. %% the beginning of the function. In preparation for a function call, we
  12997. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12998. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12999. %% so on.
  13000. %% Upon calling the function, the stack arguments are retrieved by the
  13001. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13002. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13003. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13004. %% the layout of the caller and callee frames. Notice how important it is
  13005. %% that we correctly compute the maximum number of arguments needed for
  13006. %% function calls; if that number is too small then the arguments and
  13007. %% local variables will smash into each other!
  13008. \subsection{Efficient Tail Calls}
  13009. \label{sec:tail-call}
  13010. In general, the amount of stack space used by a program is determined
  13011. by the longest chain of nested function calls. That is, if function
  13012. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13013. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13014. large if functions are recursive. However, in some cases we can
  13015. arrange to use only a constant amount of space for a long chain of
  13016. nested function calls.
  13017. A \emph{tail call}\index{subject}{tail call} is a function call that
  13018. happens as the last action in a function body.
  13019. For example, in the following
  13020. program, the recursive call to \code{tail\_sum} is a tail call.
  13021. \begin{center}
  13022. {\if\edition\racketEd
  13023. \begin{lstlisting}
  13024. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13025. (if (eq? n 0)
  13026. r
  13027. (tail_sum (- n 1) (+ n r))))
  13028. (+ (tail_sum 3 0) 36)
  13029. \end{lstlisting}
  13030. \fi}
  13031. {\if\edition\pythonEd
  13032. \begin{lstlisting}
  13033. def tail_sum(n : int, r : int) -> int:
  13034. if n == 0:
  13035. return r
  13036. else:
  13037. return tail_sum(n - 1, n + r)
  13038. print( tail_sum(3, 0) + 36)
  13039. \end{lstlisting}
  13040. \fi}
  13041. \end{center}
  13042. At a tail call, the frame of the caller is no longer needed, so we can
  13043. pop the caller's frame before making the tail call. With this
  13044. approach, a recursive function that only makes tail calls ends up
  13045. using a constant amount of stack space. Functional languages like
  13046. Racket rely heavily on recursive functions, so the definition of
  13047. Racket \emph{requires} that all tail calls be optimized in this way.
  13048. \index{subject}{frame}
  13049. Some care is needed with regards to argument passing in tail calls.
  13050. As mentioned above, for arguments beyond the sixth, the convention is
  13051. to use space in the caller's frame for passing arguments. But for a
  13052. tail call we pop the caller's frame and can no longer use it. An
  13053. alternative is to use space in the callee's frame for passing
  13054. arguments. However, this option is also problematic because the caller
  13055. and callee's frames overlap in memory. As we begin to copy the
  13056. arguments from their sources in the caller's frame, the target
  13057. locations in the callee's frame might collide with the sources for
  13058. later arguments! We solve this problem by using the heap instead of
  13059. the stack for passing more than six arguments
  13060. (Section~\ref{sec:limit-functions-r4}).
  13061. As mentioned above, for a tail call we pop the caller's frame prior to
  13062. making the tail call. The instructions for popping a frame are the
  13063. instructions that we usually place in the conclusion of a
  13064. function. Thus, we also need to place such code immediately before
  13065. each tail call. These instructions include restoring the callee-saved
  13066. registers, so it is fortunate that the argument passing registers are
  13067. all caller-saved registers!
  13068. One last note regarding which instruction to use to make the tail
  13069. call. When the callee is finished, it should not return to the current
  13070. function, but it should return to the function that called the current
  13071. one. Thus, the return address that is already on the stack is the
  13072. right one and we should not use \key{callq} to make the tail call, as
  13073. that would overwrite the return address. Instead we simply use the
  13074. \key{jmp} instruction. Like the indirect function call, we write an
  13075. \emph{indirect jump}\index{subject}{indirect jump} with a register
  13076. prefixed with an asterisk. We recommend using \code{rax} to hold the
  13077. jump target because the conclusion can overwrite just about everything
  13078. else.
  13079. \begin{lstlisting}
  13080. jmp *%rax
  13081. \end{lstlisting}
  13082. \section{Shrink \LangFun{}}
  13083. \label{sec:shrink-r4}
  13084. The \code{shrink} pass performs a minor modification to ease the
  13085. later passes. This pass introduces an explicit \code{main} function
  13086. that gobbles up all the top-level statements of the module.
  13087. %
  13088. \racket{It also changes the top \code{ProgramDefsExp} form to
  13089. \code{ProgramDefs}.}
  13090. {\if\edition\racketEd
  13091. \begin{lstlisting}
  13092. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  13093. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  13094. \end{lstlisting}
  13095. where $\itm{mainDef}$ is
  13096. \begin{lstlisting}
  13097. (Def 'main '() 'Integer '() |$\Exp'$|)
  13098. \end{lstlisting}
  13099. \fi}
  13100. {\if\edition\pythonEd
  13101. \begin{lstlisting}
  13102. Module(|$\Def\ldots\Stmt\ldots$|)
  13103. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  13104. \end{lstlisting}
  13105. where $\itm{mainDef}$ is
  13106. \begin{lstlisting}
  13107. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  13108. \end{lstlisting}
  13109. \fi}
  13110. \section{Reveal Functions and the \LangFunRef{} language}
  13111. \label{sec:reveal-functions-r4}
  13112. The syntax of \LangFun{} is inconvenient for purposes of compilation
  13113. in that it conflates the use of function names and local
  13114. variables. This is a problem because we need to compile the use of a
  13115. function name differently than the use of a local variable. In
  13116. particular, we use \code{leaq} to convert the function name (a label
  13117. in x86) to an address in a register. Thus, we create a new pass that
  13118. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  13119. $n$ is the arity of the function.\python{\footnote{The arity is not
  13120. needed in this chapter but is used in Chapter~\ref{ch:Ldyn}.}}
  13121. This pass is named \code{reveal\_functions} and the output language
  13122. is \LangFunRef{}.
  13123. %is defined in Figure~\ref{fig:f1-syntax}.
  13124. %% The concrete syntax for a
  13125. %% function reference is $\CFUNREF{f}$.
  13126. %% \begin{figure}[tp]
  13127. %% \centering
  13128. %% \fbox{
  13129. %% \begin{minipage}{0.96\textwidth}
  13130. %% {\if\edition\racketEd
  13131. %% \[
  13132. %% \begin{array}{lcl}
  13133. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  13134. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13135. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  13136. %% \end{array}
  13137. %% \]
  13138. %% \fi}
  13139. %% {\if\edition\pythonEd
  13140. %% \[
  13141. %% \begin{array}{lcl}
  13142. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  13143. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  13144. %% \end{array}
  13145. %% \]
  13146. %% \fi}
  13147. %% \end{minipage}
  13148. %% }
  13149. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  13150. %% (Figure~\ref{fig:Lfun-syntax}).}
  13151. %% \label{fig:f1-syntax}
  13152. %% \end{figure}
  13153. %% Distinguishing between calls in tail position and non-tail position
  13154. %% requires the pass to have some notion of context. We recommend using
  13155. %% two mutually recursive functions, one for processing expressions in
  13156. %% tail position and another for the rest.
  13157. \racket{Placing this pass after \code{uniquify} will make sure that
  13158. there are no local variables and functions that share the same
  13159. name.}
  13160. %
  13161. The \code{reveal\_functions} pass should come before the
  13162. \code{remove\_complex\_operands} pass because function references
  13163. should be categorized as complex expressions.
  13164. \section{Limit Functions}
  13165. \label{sec:limit-functions-r4}
  13166. Recall that we wish to limit the number of function parameters to six
  13167. so that we do not need to use the stack for argument passing, which
  13168. makes it easier to implement efficient tail calls. However, because
  13169. the input language \LangFun{} supports arbitrary numbers of function
  13170. arguments, we have some work to do!
  13171. This pass transforms functions and function calls that involve more
  13172. than six arguments to pass the first five arguments as usual, but it
  13173. packs the rest of the arguments into a tuple and passes it as the
  13174. sixth argument.
  13175. Each function definition with seven or more parameters is transformed as
  13176. follows.
  13177. {\if\edition\racketEd
  13178. \begin{lstlisting}
  13179. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  13180. |$\Rightarrow$|
  13181. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  13182. \end{lstlisting}
  13183. \fi}
  13184. {\if\edition\pythonEd
  13185. \begin{lstlisting}
  13186. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  13187. |$\Rightarrow$|
  13188. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  13189. |$T_r$|, None, |$\itm{body}'$|, None)
  13190. \end{lstlisting}
  13191. \fi}
  13192. %
  13193. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  13194. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  13195. the $k$th element of the tuple, where $k = i - 6$.
  13196. %
  13197. {\if\edition\racketEd
  13198. \begin{lstlisting}
  13199. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  13200. \end{lstlisting}
  13201. \fi}
  13202. {\if\edition\pythonEd
  13203. \begin{lstlisting}
  13204. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  13205. \end{lstlisting}
  13206. \fi}
  13207. For function calls with too many arguments, the \code{limit\_functions}
  13208. pass transforms them in the following way.
  13209. \begin{tabular}{lll}
  13210. \begin{minipage}{0.3\textwidth}
  13211. {\if\edition\racketEd
  13212. \begin{lstlisting}
  13213. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  13214. \end{lstlisting}
  13215. \fi}
  13216. {\if\edition\pythonEd
  13217. \begin{lstlisting}
  13218. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  13219. \end{lstlisting}
  13220. \fi}
  13221. \end{minipage}
  13222. &
  13223. $\Rightarrow$
  13224. &
  13225. \begin{minipage}{0.5\textwidth}
  13226. {\if\edition\racketEd
  13227. \begin{lstlisting}
  13228. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  13229. \end{lstlisting}
  13230. \fi}
  13231. {\if\edition\pythonEd
  13232. \begin{lstlisting}
  13233. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  13234. \end{lstlisting}
  13235. \fi}
  13236. \end{minipage}
  13237. \end{tabular}
  13238. \section{Remove Complex Operands}
  13239. \label{sec:rco-r4}
  13240. The primary decisions to make for this pass are whether to classify
  13241. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  13242. atomic or complex expressions. Recall that an atomic expression will
  13243. end up as an immediate argument of an x86 instruction. Function
  13244. application will be translated to a sequence of instructions, so
  13245. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  13246. complex expression. On the other hand, the arguments of
  13247. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  13248. expressions.
  13249. %
  13250. Regarding \code{FunRef}, as discussed above, the function label needs
  13251. to be converted to an address using the \code{leaq} instruction. Thus,
  13252. even though \code{FunRef} seems rather simple, it needs to be
  13253. classified as a complex expression so that we generate an assignment
  13254. statement with a left-hand side that can serve as the target of the
  13255. \code{leaq}.
  13256. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  13257. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  13258. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  13259. %
  13260. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  13261. % TODO: Return?
  13262. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  13263. %% \LangFunANF{} of this pass.
  13264. %% \begin{figure}[tp]
  13265. %% \centering
  13266. %% \fbox{
  13267. %% \begin{minipage}{0.96\textwidth}
  13268. %% \small
  13269. %% \[
  13270. %% \begin{array}{rcl}
  13271. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  13272. %% \MID \VOID{} } \\
  13273. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  13274. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  13275. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  13276. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  13277. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  13278. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  13279. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  13280. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13281. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13282. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  13283. %% \end{array}
  13284. %% \]
  13285. %% \end{minipage}
  13286. %% }
  13287. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  13288. %% \label{fig:Lfun-anf-syntax}
  13289. %% \end{figure}
  13290. \section{Explicate Control and the \LangCFun{} language}
  13291. \label{sec:explicate-control-r4}
  13292. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  13293. output of \code{explicate\_control}.
  13294. %
  13295. %% \racket{(The concrete syntax is given in
  13296. %% Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  13297. %
  13298. The auxiliary functions for assignment\racket{ and tail contexts} should
  13299. be updated with cases for
  13300. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  13301. function for predicate context should be updated for
  13302. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  13303. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  13304. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  13305. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  13306. auxiliary function for processing function definitions. This code is
  13307. similar to the case for \code{Program} in \LangVec{}. The top-level
  13308. \code{explicate\_control} function that handles the \code{ProgramDefs}
  13309. form of \LangFun{} can then apply this new function to all the
  13310. function definitions.
  13311. {\if\edition\pythonEd
  13312. The translation of \code{Return} statements requires a new auxiliary
  13313. function to handle expressions in tail context, called
  13314. \code{explicate\_tail}. The function should take an expression and the
  13315. dictionary of basic blocks and produce a list of statements in the
  13316. \LangCFun{} language. The \code{explicate\_tail} function should
  13317. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  13318. and a default case for other kinds of expressions. The default case
  13319. should produce a \code{Return} statement. The case for \code{Call}
  13320. should change it into \code{TailCall}. The other cases should
  13321. recursively process their subexpressions and statements, choosing the
  13322. appropriate explicate functions for the various contexts.
  13323. \fi}
  13324. \newcommand{\CfunASTRacket}{
  13325. \begin{array}{lcl}
  13326. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  13327. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  13328. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  13329. \end{array}
  13330. }
  13331. \newcommand{\CfunASTPython}{
  13332. \begin{array}{lcl}
  13333. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  13334. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  13335. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  13336. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  13337. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  13338. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  13339. \end{array}
  13340. }
  13341. \begin{figure}[tp]
  13342. \begin{tcolorbox}[colback=white]
  13343. \small
  13344. {\if\edition\racketEd
  13345. \[
  13346. \begin{array}{l}
  13347. \gray{\CvarASTRacket} \\ \hline
  13348. \gray{\CifASTRacket} \\ \hline
  13349. \gray{\CloopASTRacket} \\ \hline
  13350. \gray{\CtupASTRacket} \\ \hline
  13351. \CfunASTRacket \\
  13352. \begin{array}{lcl}
  13353. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13354. \end{array}
  13355. \end{array}
  13356. \]
  13357. \fi}
  13358. {\if\edition\pythonEd
  13359. \[
  13360. \begin{array}{l}
  13361. \gray{\CifASTPython} \\ \hline
  13362. \gray{\CtupASTPython} \\ \hline
  13363. \CfunASTPython \\
  13364. \begin{array}{lcl}
  13365. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13366. \end{array}
  13367. \end{array}
  13368. \]
  13369. \fi}
  13370. \end{tcolorbox}
  13371. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  13372. \label{fig:c3-syntax}
  13373. \end{figure}
  13374. \clearpage
  13375. \section{Select Instructions and the \LangXIndCall{} Language}
  13376. \label{sec:select-r4}
  13377. \index{subject}{instruction selection}
  13378. The output of select instructions is a program in the \LangXIndCall{}
  13379. language, whose concrete syntax is defined in
  13380. Figure~\ref{fig:x86-3-concrete} and abstract syntax is defined in
  13381. Figure~\ref{fig:x86-3}. We use the \code{align} directive on the
  13382. labels of function definitions to make sure the bottom three bits are
  13383. zero, which we make use of in Chapter~\ref{ch:Ldyn}. We discuss the
  13384. new instructions as needed in this section. \index{subject}{x86}
  13385. \newcommand{\GrammarXIndCall}{
  13386. \begin{array}{lcl}
  13387. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13388. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13389. \Block &::= & \Instr^{+} \\
  13390. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  13391. \end{array}
  13392. }
  13393. \newcommand{\ASTXIndCallRacket}{
  13394. \begin{array}{lcl}
  13395. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  13396. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13397. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13398. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13399. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  13400. \end{array}
  13401. }
  13402. \begin{figure}[tp]
  13403. \begin{tcolorbox}[colback=white]
  13404. \small
  13405. \[
  13406. \begin{array}{l}
  13407. \gray{\GrammarXInt} \\ \hline
  13408. \gray{\GrammarXIf} \\ \hline
  13409. \gray{\GrammarXGlobal} \\ \hline
  13410. \GrammarXIndCall \\
  13411. \begin{array}{lcl}
  13412. \LangXIndCallM{} &::= & \Def^{*}
  13413. \end{array}
  13414. \end{array}
  13415. \]
  13416. \end{tcolorbox}
  13417. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  13418. \label{fig:x86-3-concrete}
  13419. \end{figure}
  13420. \begin{figure}[tp]
  13421. \begin{tcolorbox}[colback=white]
  13422. \small
  13423. {\if\edition\racketEd
  13424. \[\arraycolsep=3pt
  13425. \begin{array}{l}
  13426. \gray{\ASTXIntRacket} \\ \hline
  13427. \gray{\ASTXIfRacket} \\ \hline
  13428. \gray{\ASTXGlobalRacket} \\ \hline
  13429. \ASTXIndCallRacket \\
  13430. \begin{array}{lcl}
  13431. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13432. \end{array}
  13433. \end{array}
  13434. \]
  13435. \fi}
  13436. {\if\edition\pythonEd
  13437. \[
  13438. \begin{array}{lcl}
  13439. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13440. \MID \BYTEREG{\Reg} } \\
  13441. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  13442. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13443. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13444. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13445. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13446. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13447. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13448. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13449. \end{array}
  13450. \]
  13451. \fi}
  13452. \end{tcolorbox}
  13453. \caption{The abstract syntax of \LangXIndCall{} (extends
  13454. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  13455. \label{fig:x86-3}
  13456. \end{figure}
  13457. An assignment of a function reference to a variable becomes a
  13458. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  13459. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  13460. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  13461. node, whose concrete syntax is instruction-pointer relative
  13462. addressing.
  13463. \begin{center}
  13464. \begin{tabular}{lcl}
  13465. \begin{minipage}{0.35\textwidth}
  13466. {\if\edition\racketEd
  13467. \begin{lstlisting}
  13468. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13469. \end{lstlisting}
  13470. \fi}
  13471. {\if\edition\pythonEd
  13472. \begin{lstlisting}
  13473. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  13474. \end{lstlisting}
  13475. \fi}
  13476. \end{minipage}
  13477. &
  13478. $\Rightarrow$\qquad\qquad
  13479. &
  13480. \begin{minipage}{0.3\textwidth}
  13481. \begin{lstlisting}
  13482. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13483. \end{lstlisting}
  13484. \end{minipage}
  13485. \end{tabular}
  13486. \end{center}
  13487. Regarding function definitions, we need to remove the parameters and
  13488. instead perform parameter passing using the conventions discussed in
  13489. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13490. registers. We recommend turning the parameters into local variables
  13491. and generating instructions at the beginning of the function to move
  13492. from the argument passing registers
  13493. (Section~\ref{sec:calling-conventions-fun}) to these local variables.
  13494. {\if\edition\racketEd
  13495. \begin{lstlisting}
  13496. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13497. |$\Rightarrow$|
  13498. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13499. \end{lstlisting}
  13500. \fi}
  13501. {\if\edition\pythonEd
  13502. \begin{lstlisting}
  13503. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13504. |$\Rightarrow$|
  13505. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13506. \end{lstlisting}
  13507. \fi}
  13508. The basic blocks $B'$ are the same as $B$ except that the
  13509. \code{start} block is modified to add the instructions for moving from
  13510. the argument registers to the parameter variables. So the \code{start}
  13511. block of $B$ shown on the left is changed to the code on the right.
  13512. \begin{center}
  13513. \begin{minipage}{0.3\textwidth}
  13514. \begin{lstlisting}
  13515. start:
  13516. |$\itm{instr}_1$|
  13517. |$\cdots$|
  13518. |$\itm{instr}_n$|
  13519. \end{lstlisting}
  13520. \end{minipage}
  13521. $\Rightarrow$
  13522. \begin{minipage}{0.3\textwidth}
  13523. \begin{lstlisting}
  13524. start:
  13525. movq %rdi, |$x_1$|
  13526. movq %rsi, |$x_2$|
  13527. |$\cdots$|
  13528. |$\itm{instr}_1$|
  13529. |$\cdots$|
  13530. |$\itm{instr}_n$|
  13531. \end{lstlisting}
  13532. \end{minipage}
  13533. \end{center}
  13534. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13535. parameters the function expects, but the parameters are no longer in
  13536. the syntax of function definitions. Instead, add an entry to
  13537. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13538. to construct $\itm{info}'$.}
  13539. By changing the parameters to local variables, we are giving the
  13540. register allocator control over which registers or stack locations to
  13541. use for them. If you implemented the move-biasing challenge
  13542. (Section~\ref{sec:move-biasing}), the register allocator will try to
  13543. assign the parameter variables to the corresponding argument register,
  13544. in which case the \code{patch\_instructions} pass will remove the
  13545. \code{movq} instruction. This happens in the example translation in
  13546. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  13547. the \code{add} function.
  13548. %
  13549. Also, note that the register allocator will perform liveness analysis
  13550. on this sequence of move instructions and build the interference
  13551. graph. So, for example, $x_1$ will be marked as interfering with
  13552. \code{rsi} and that will prevent the assignment of $x_1$ to
  13553. \code{rsi}, which is good, because that would overwrite the argument
  13554. that needs to move into $x_2$.
  13555. Next, consider the compilation of function calls. In the mirror image
  13556. of the handling of parameters in function definitions, the arguments
  13557. are moved to the argument passing registers. Note that the function
  13558. is not given as a label, but its address is produced by the argument
  13559. $\itm{arg}_0$. So we translate the call into an indirect function
  13560. call. The return value from the function is stored in \code{rax}, so
  13561. it needs to be moved into the \itm{lhs}.
  13562. \begin{lstlisting}
  13563. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  13564. |$\Rightarrow$|
  13565. movq |$\itm{arg}_1$|, %rdi
  13566. movq |$\itm{arg}_2$|, %rsi
  13567. |$\vdots$|
  13568. callq *|$\itm{arg}_0$|
  13569. movq %rax, |$\itm{lhs}$|
  13570. \end{lstlisting}
  13571. The \code{IndirectCallq} AST node includes an integer for the arity of
  13572. the function, i.e., the number of parameters. That information is
  13573. useful in the \code{uncover\_live} pass for determining which
  13574. argument-passing registers are potentially read during the call.
  13575. For tail calls, the parameter passing is the same as non-tail calls:
  13576. generate instructions to move the arguments into the argument
  13577. passing registers. After that we need to pop the frame from the
  13578. procedure call stack. However, we do not yet know how big the frame
  13579. is; that gets determined during register allocation. So instead of
  13580. generating those instructions here, we invent a new instruction that
  13581. means ``pop the frame and then do an indirect jump'', which we name
  13582. \code{TailJmp}. The abstract syntax for this instruction includes an
  13583. argument that specifies where to jump and an integer that represents
  13584. the arity of the function being called.
  13585. Recall that we use the label \code{start} for the initial block of a
  13586. program, and in Section~\ref{sec:select-Lvar} we recommend labeling
  13587. the conclusion of the program with \code{conclusion}, so that
  13588. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13589. by a jump to \code{conclusion}. With the addition of function
  13590. definitions, there is a start block and conclusion for each function,
  13591. but their labels need to be unique. We recommend prepending the
  13592. function's name to \code{start} and \code{conclusion}, respectively,
  13593. to obtain unique labels.
  13594. \section{Register Allocation}
  13595. \label{sec:register-allocation-r4}
  13596. The addition of functions requires some changes to all three aspects
  13597. of register allocation, which we discuss in the following subsections.
  13598. \subsection{Liveness Analysis}
  13599. \label{sec:liveness-analysis-r4}
  13600. \index{subject}{liveness analysis}
  13601. %% The rest of the passes need only minor modifications to handle the new
  13602. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13603. %% \code{leaq}.
  13604. The \code{IndirectCallq} instruction should be treated like
  13605. \code{Callq} regarding its written locations $W$, in that they should
  13606. include all the caller-saved registers. Recall that the reason for
  13607. that is to force variables that are live across a function call to be assigned to callee-saved
  13608. registers or to be spilled to the stack.
  13609. Regarding the set of read locations $R$, the arity field of
  13610. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13611. argument-passing registers should be considered as read by those
  13612. instructions. Also, the target field of \code{TailJmp} and
  13613. \code{IndirectCallq} should be included in the set of read locations
  13614. $R$.
  13615. \subsection{Build Interference Graph}
  13616. \label{sec:build-interference-r4}
  13617. With the addition of function definitions, we compute a separate interference
  13618. graph for each function (not just one for the whole program).
  13619. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13620. spill tuple-typed variables that are live during a call to
  13621. \code{collect}, the garbage collector. With the addition of functions
  13622. to our language, we need to revisit this issue. Functions that perform
  13623. allocation contain calls to the collector. Thus, we should not only
  13624. spill a tuple-typed variable when it is live during a call to
  13625. \code{collect}, but we should spill the variable if it is live during
  13626. call to any user-defined function. Thus, in the
  13627. \code{build\_interference} pass, we recommend adding interference
  13628. edges between call-live tuple-typed variables and the callee-saved
  13629. registers (in addition to the usual addition of edges between
  13630. call-live variables and the caller-saved registers).
  13631. \subsection{Allocate Registers}
  13632. The primary change to the \code{allocate\_registers} pass is adding an
  13633. auxiliary function for handling definitions (the \Def{} non-terminal
  13634. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13635. logic is the same as described in
  13636. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13637. allocation is performed many times, once for each function definition,
  13638. instead of just once for the whole program.
  13639. \section{Patch Instructions}
  13640. In \code{patch\_instructions}, you should deal with the x86
  13641. idiosyncrasy that the destination argument of \code{leaq} must be a
  13642. register. Additionally, you should ensure that the argument of
  13643. \code{TailJmp} is \itm{rax}, our reserved register---because we
  13644. trample many other registers before the tail call (as explained in the
  13645. next section).
  13646. \section{Prelude and Conclusion}
  13647. Now that register allocation is complete, we can translate the
  13648. \code{TailJmp} into a sequence of instructions. A naive translation of
  13649. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  13650. before the jump we need to pop the current frame to achieve efficient
  13651. tail calls. This sequence of instructions is the same as the code for
  13652. the conclusion of a function, except the \code{retq} is replaced with
  13653. \code{jmp *$\itm{arg}$}.
  13654. Regarding function definitions, we generate a prelude and conclusion
  13655. for each one. This code is similar to the prelude and conclusion
  13656. generated for the \code{main} function in Chapter~\ref{ch:Lvec}. To
  13657. review, the prelude of every function should carry out the following
  13658. steps.
  13659. % TODO: .align the functions!
  13660. \begin{enumerate}
  13661. %% \item Start with \code{.global} and \code{.align} directives followed
  13662. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13663. %% example.)
  13664. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13665. pointer.
  13666. \item Push to the stack all of the callee-saved registers that were
  13667. used for register allocation.
  13668. \item Move the stack pointer \code{rsp} down to make room for the
  13669. regular spills. (Aligned to 16 bytes.)
  13670. \item Move the root stack pointer \code{r15} up by the size of the
  13671. root-stack frame for this function, which depends on the number of
  13672. spilled tuple-typed variables. \label{root-stack-init}
  13673. \item Initialize to zero all new entries in the root-stack frame.
  13674. \item Jump to the start block.
  13675. \end{enumerate}
  13676. The prelude of the \code{main} function has an additional task: call
  13677. the \code{initialize} function to set up the garbage collector and
  13678. then move the value of the global \code{rootstack\_begin} in
  13679. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13680. above, which depends on \code{r15}.
  13681. The conclusion of every function should do the following.
  13682. \begin{enumerate}
  13683. \item Move the stack pointer back up past the regular spills.
  13684. \item Restore the callee-saved registers by popping them from the
  13685. stack.
  13686. \item Move the root stack pointer back down by the size of the
  13687. root-stack frame for this function.
  13688. \item Restore \code{rbp} by popping it from the stack.
  13689. \item Return to the caller with the \code{retq} instruction.
  13690. \end{enumerate}
  13691. \begin{exercise}\normalfont\normalsize
  13692. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13693. Create 8 new programs that use functions, including examples that pass
  13694. functions and return functions from other functions, recursive
  13695. functions, functions that create vectors, and functions that make tail
  13696. calls. Test your compiler on these new programs and all of your
  13697. previously created test programs.
  13698. \end{exercise}
  13699. \begin{figure}[tbp]
  13700. \begin{tcolorbox}[colback=white]
  13701. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13702. \node (Lfun) at (0,2) {\large \LangFun{}};
  13703. \node (Lfun-1) at (3,2) {\large \LangFun{}};
  13704. \node (Lfun-2) at (6,2) {\large \LangFun{}};
  13705. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13706. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13707. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13708. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13709. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13710. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13711. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13712. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13713. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13714. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13715. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13716. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13717. \path[->,bend left=15] (Lfun) edge [above] node
  13718. {\ttfamily\footnotesize shrink} (Lfun-1);
  13719. \path[->,bend left=15] (Lfun-1) edge [above] node
  13720. {\ttfamily\footnotesize uniquify} (Lfun-2);
  13721. \path[->,bend left=15] (Lfun-2) edge [above] node
  13722. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13723. \path[->,bend left=15] (F1-1) edge [left] node
  13724. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13725. \path[->,bend left=15] (F1-2) edge [below] node
  13726. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13727. \path[->,bend left=15] (F1-3) edge [below] node
  13728. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  13729. \path[->,bend right=15] (F1-4) edge [above] node
  13730. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13731. \path[->,bend right=15] (F1-5) edge [left] node
  13732. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13733. \path[->,bend right=15] (C3-2) edge [left] node
  13734. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13735. \path[->,bend left=15] (x86-2) edge [left] node
  13736. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13737. \path[->,bend right=15] (x86-2-1) edge [below] node
  13738. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13739. \path[->,bend right=15] (x86-2-2) edge [left] node
  13740. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13741. \path[->,bend left=15] (x86-3) edge [above] node
  13742. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13743. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize prelude.} (x86-5);
  13744. \end{tikzpicture}
  13745. \end{tcolorbox}
  13746. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13747. \label{fig:Lfun-passes}
  13748. \end{figure}
  13749. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  13750. compiling \LangFun{} to x86.
  13751. \section{An Example Translation}
  13752. \label{sec:functions-example}
  13753. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13754. function in \LangFun{} to x86. The figure also includes the results of the
  13755. \code{explicate\_control} and \code{select\_instructions} passes.
  13756. \begin{figure}[htbp]
  13757. \begin{tcolorbox}[colback=white]
  13758. \begin{tabular}{ll}
  13759. \begin{minipage}{0.4\textwidth}
  13760. % s3_2.rkt
  13761. {\if\edition\racketEd
  13762. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13763. (define (add [x : Integer]
  13764. [y : Integer])
  13765. : Integer
  13766. (+ x y))
  13767. (add 40 2)
  13768. \end{lstlisting}
  13769. \fi}
  13770. {\if\edition\pythonEd
  13771. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13772. def add(x:int, y:int) -> int:
  13773. return x + y
  13774. print(add(40, 2))
  13775. \end{lstlisting}
  13776. \fi}
  13777. $\Downarrow$
  13778. {\if\edition\racketEd
  13779. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13780. (define (add86 [x87 : Integer]
  13781. [y88 : Integer])
  13782. : Integer
  13783. add86start:
  13784. return (+ x87 y88);
  13785. )
  13786. (define (main) : Integer ()
  13787. mainstart:
  13788. tmp89 = (fun-ref add86 2);
  13789. (tail-call tmp89 40 2)
  13790. )
  13791. \end{lstlisting}
  13792. \fi}
  13793. {\if\edition\pythonEd
  13794. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13795. def add(x:int, y:int) -> int:
  13796. addstart:
  13797. return x + y
  13798. def main() -> int:
  13799. mainstart:
  13800. fun.0 = add
  13801. tmp.1 = fun.0(40, 2)
  13802. print(tmp.1)
  13803. return 0
  13804. \end{lstlisting}
  13805. \fi}
  13806. \end{minipage}
  13807. &
  13808. $\Rightarrow$
  13809. \begin{minipage}{0.5\textwidth}
  13810. {\if\edition\racketEd
  13811. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13812. (define (add86) : Integer
  13813. add86start:
  13814. movq %rdi, x87
  13815. movq %rsi, y88
  13816. movq x87, %rax
  13817. addq y88, %rax
  13818. jmp inc1389conclusion
  13819. )
  13820. (define (main) : Integer
  13821. mainstart:
  13822. leaq (fun-ref add86 2), tmp89
  13823. movq $40, %rdi
  13824. movq $2, %rsi
  13825. tail-jmp tmp89
  13826. )
  13827. \end{lstlisting}
  13828. \fi}
  13829. {\if\edition\pythonEd
  13830. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13831. def add() -> int:
  13832. addstart:
  13833. movq %rdi, x
  13834. movq %rsi, y
  13835. movq x, %rax
  13836. addq y, %rax
  13837. jmp addconclusion
  13838. def main() -> int:
  13839. mainstart:
  13840. leaq add, fun.0
  13841. movq $40, %rdi
  13842. movq $2, %rsi
  13843. callq *fun.0
  13844. movq %rax, tmp.1
  13845. movq tmp.1, %rdi
  13846. callq print_int
  13847. movq $0, %rax
  13848. jmp mainconclusion
  13849. \end{lstlisting}
  13850. \fi}
  13851. $\Downarrow$
  13852. \end{minipage}
  13853. \end{tabular}
  13854. \begin{tabular}{ll}
  13855. \begin{minipage}{0.3\textwidth}
  13856. {\if\edition\racketEd
  13857. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13858. .globl add86
  13859. .align 8
  13860. add86:
  13861. pushq %rbp
  13862. movq %rsp, %rbp
  13863. jmp add86start
  13864. add86start:
  13865. movq %rdi, %rax
  13866. addq %rsi, %rax
  13867. jmp add86conclusion
  13868. add86conclusion:
  13869. popq %rbp
  13870. retq
  13871. \end{lstlisting}
  13872. \fi}
  13873. {\if\edition\pythonEd
  13874. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13875. .align 8
  13876. add:
  13877. pushq %rbp
  13878. movq %rsp, %rbp
  13879. subq $0, %rsp
  13880. jmp addstart
  13881. addstart:
  13882. movq %rdi, %rdx
  13883. movq %rsi, %rcx
  13884. movq %rdx, %rax
  13885. addq %rcx, %rax
  13886. jmp addconclusion
  13887. addconclusion:
  13888. subq $0, %r15
  13889. addq $0, %rsp
  13890. popq %rbp
  13891. retq
  13892. \end{lstlisting}
  13893. \fi}
  13894. \end{minipage}
  13895. &
  13896. \begin{minipage}{0.5\textwidth}
  13897. {\if\edition\racketEd
  13898. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13899. .globl main
  13900. .align 8
  13901. main:
  13902. pushq %rbp
  13903. movq %rsp, %rbp
  13904. movq $16384, %rdi
  13905. movq $16384, %rsi
  13906. callq initialize
  13907. movq rootstack_begin(%rip), %r15
  13908. jmp mainstart
  13909. mainstart:
  13910. leaq add86(%rip), %rcx
  13911. movq $40, %rdi
  13912. movq $2, %rsi
  13913. movq %rcx, %rax
  13914. popq %rbp
  13915. jmp *%rax
  13916. mainconclusion:
  13917. popq %rbp
  13918. retq
  13919. \end{lstlisting}
  13920. \fi}
  13921. {\if\edition\pythonEd
  13922. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13923. .globl main
  13924. .align 8
  13925. main:
  13926. pushq %rbp
  13927. movq %rsp, %rbp
  13928. subq $0, %rsp
  13929. movq $65536, %rdi
  13930. movq $65536, %rsi
  13931. callq initialize
  13932. movq rootstack_begin(%rip), %r15
  13933. jmp mainstart
  13934. mainstart:
  13935. leaq add(%rip), %rcx
  13936. movq $40, %rdi
  13937. movq $2, %rsi
  13938. callq *%rcx
  13939. movq %rax, %rcx
  13940. movq %rcx, %rdi
  13941. callq print_int
  13942. movq $0, %rax
  13943. jmp mainconclusion
  13944. mainconclusion:
  13945. subq $0, %r15
  13946. addq $0, %rsp
  13947. popq %rbp
  13948. retq
  13949. \end{lstlisting}
  13950. \fi}
  13951. \end{minipage}
  13952. \end{tabular}
  13953. \end{tcolorbox}
  13954. \caption{Example compilation of a simple function to x86.}
  13955. \label{fig:add-fun}
  13956. \end{figure}
  13957. % Challenge idea: inlining! (simple version)
  13958. % Further Reading
  13959. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13960. \chapter{Lexically Scoped Functions}
  13961. \label{ch:Llambda}
  13962. \index{subject}{lambda}
  13963. \index{subject}{lexical scoping}
  13964. This chapter studies lexically scoped functions. Lexical scoping means
  13965. that a function's body may refer to variables whose binding site is
  13966. outside of the function, in an enclosing scope.
  13967. %
  13968. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13969. \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  13970. creating lexically scoped functions. The body of the \key{lambda}
  13971. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  13972. binding sites for \code{x} and \code{y} are outside of the
  13973. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  13974. \key{let}}\python{a local variable of function \code{f}} and
  13975. \code{x} is a parameter of function \code{f}. Note that function
  13976. \code{f} returns the \key{lambda} as its result value. The main
  13977. expression of the program includes two calls to \code{f} with
  13978. different arguments for \code{x}, first \code{5} then \code{3}. The
  13979. functions returned from \code{f} are bound to variables \code{g} and
  13980. \code{h}. Even though these two functions were created by the same
  13981. \code{lambda}, they are really different functions because they use
  13982. different values for \code{x}. Applying \code{g} to \code{11} produces
  13983. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  13984. so the result of the program is \code{42}.
  13985. \begin{figure}[btp]
  13986. \begin{tcolorbox}[colback=white]
  13987. {\if\edition\racketEd
  13988. % lambda_test_21.rkt
  13989. \begin{lstlisting}
  13990. (define (f [x : Integer]) : (Integer -> Integer)
  13991. (let ([y 4])
  13992. (lambda: ([z : Integer]) : Integer
  13993. (+ x (+ y z)))))
  13994. (let ([g (f 5)])
  13995. (let ([h (f 3)])
  13996. (+ (g 11) (h 15))))
  13997. \end{lstlisting}
  13998. \fi}
  13999. {\if\edition\pythonEd
  14000. \begin{lstlisting}
  14001. def f(x : int) -> Callable[[int], int]:
  14002. y = 4
  14003. return lambda z: x + y + z
  14004. g = f(5)
  14005. h = f(3)
  14006. print( g(11) + h(15) )
  14007. \end{lstlisting}
  14008. \fi}
  14009. \end{tcolorbox}
  14010. \caption{Example of a lexically scoped function.}
  14011. \label{fig:lexical-scoping}
  14012. \end{figure}
  14013. The approach that we take for implementing lexically scoped functions
  14014. is to compile them into top-level function definitions, translating
  14015. from \LangLam{} into \LangFun{}. However, the compiler must give
  14016. special treatment to variable occurrences such as \code{x} and
  14017. \code{y} in the body of the \code{lambda} of
  14018. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  14019. may not refer to variables defined outside of it. To identify such
  14020. variable occurrences, we review the standard notion of free variable.
  14021. \begin{definition}
  14022. A variable is \textbf{free in expression} $e$ if the variable occurs
  14023. inside $e$ but does not have an enclosing definition that is also in
  14024. $e$.\index{subject}{free variable}
  14025. \end{definition}
  14026. For example, in the expression
  14027. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  14028. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  14029. only \code{x} and \code{y} are free in the following expression
  14030. because \code{z} is defined by the \code{lambda}.
  14031. {\if\edition\racketEd
  14032. \begin{lstlisting}
  14033. (lambda: ([z : Integer]) : Integer
  14034. (+ x (+ y z)))
  14035. \end{lstlisting}
  14036. \fi}
  14037. {\if\edition\pythonEd
  14038. \begin{lstlisting}
  14039. lambda z: x + y + z
  14040. \end{lstlisting}
  14041. \fi}
  14042. %
  14043. So the free variables of a \code{lambda} are the ones that need
  14044. special treatment. We need to transport, at runtime, the values of
  14045. those variables from the point where the \code{lambda} was created to
  14046. the point where the \code{lambda} is applied. An efficient solution to
  14047. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  14048. of the free variables together with a function pointer into a tuple,
  14049. an arrangement called a \emph{flat closure} (which we shorten to just
  14050. ``closure'').\index{subject}{closure}\index{subject}{flat closure}
  14051. %
  14052. By design, we have all the ingredients to make closures:
  14053. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  14054. function pointers. The function pointer resides at index $0$ and the
  14055. values for the free variables fill in the rest of the tuple.
  14056. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  14057. how closures work. It is a three-step dance. The program calls
  14058. function \code{f}, which creates a closure for the \code{lambda}. The
  14059. closure is a tuple whose first element is a pointer to the top-level
  14060. function that we will generate for the \code{lambda}, the second
  14061. element is the value of \code{x}, which is \code{5}, and the third
  14062. element is \code{4}, the value of \code{y}. The closure does not
  14063. contain an element for \code{z} because \code{z} is not a free
  14064. variable of the \code{lambda}. Creating the closure is step 1 of the
  14065. dance. The closure is returned from \code{f} and bound to \code{g}, as
  14066. shown in Figure~\ref{fig:closures}.
  14067. %
  14068. The second call to \code{f} creates another closure, this time with
  14069. \code{3} in the second slot (for \code{x}). This closure is also
  14070. returned from \code{f} but bound to \code{h}, which is also shown in
  14071. Figure~\ref{fig:closures}.
  14072. \begin{figure}[tbp]
  14073. \centering
  14074. \begin{minipage}{0.65\textwidth}
  14075. \begin{tcolorbox}[colback=white]
  14076. \includegraphics[width=\textwidth]{figs/closures}
  14077. \end{tcolorbox}
  14078. \end{minipage}
  14079. \caption{Flat closure representations for the two functions
  14080. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  14081. \label{fig:closures}
  14082. \end{figure}
  14083. Continuing with the example, consider the application of \code{g} to
  14084. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  14085. obtain the function pointer from the first element of the closure and
  14086. call it, passing in the closure itself and then the regular arguments,
  14087. in this case \code{11}. This technique for applying a closure is step
  14088. 2 of the dance.
  14089. %
  14090. But doesn't this \code{lambda} only take 1 argument, for parameter
  14091. \code{z}? The third and final step of the dance is generating a
  14092. top-level function for a \code{lambda}. We add an additional
  14093. parameter for the closure and we insert an initialization at the beginning
  14094. of the function for each free variable, to bind those variables to the
  14095. appropriate elements from the closure parameter.
  14096. %
  14097. This three-step dance is known as \emph{closure conversion}. We
  14098. discuss the details of closure conversion in
  14099. Section~\ref{sec:closure-conversion} and show the code generated from
  14100. the example in Section~\ref{sec:example-lambda}. But first we define
  14101. the syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  14102. \section{The \LangLam{} Language}
  14103. \label{sec:r5}
  14104. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  14105. functions and lexical scoping, is defined in
  14106. Figures~\ref{fig:Llam-concrete-syntax} and \ref{fig:Llam-syntax}. It adds
  14107. the \key{lambda} form to the grammar for \LangFun{}, which already has
  14108. syntax for function application.
  14109. %
  14110. \python{The syntax also includes an assignment statement that includes
  14111. a type annotation for the variable on the left-hand side, which
  14112. facilitates the type checking of \code{lambda} expressions that we
  14113. discuss later in this section.}
  14114. %
  14115. \racket{The \code{procedure-arity} operation returns the number of parameters
  14116. of a given function, an operation that we need for the translation
  14117. of dynamic typing in Chapter~\ref{ch:Ldyn}.}
  14118. %
  14119. \python{The \code{arity} operation returns the number of parameters of
  14120. a given function, an operation that we need for the translation
  14121. of dynamic typing in Chapter~\ref{ch:Ldyn}.
  14122. The \code{arity} operation is not in Python, but the same functionality
  14123. is available in a more complex form. We include \code{arity} in the
  14124. \LangLam{} source language to enable testing.}
  14125. \newcommand{\LlambdaGrammarRacket}{
  14126. \begin{array}{lcl}
  14127. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  14128. &\MID& \LP \key{procedure-arity}~\Exp\RP
  14129. \end{array}
  14130. }
  14131. \newcommand{\LlambdaASTRacket}{
  14132. \begin{array}{lcl}
  14133. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  14134. \itm{op} &::=& \code{procedure-arity}
  14135. \end{array}
  14136. }
  14137. \newcommand{\LlambdaGrammarPython}{
  14138. \begin{array}{lcl}
  14139. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  14140. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  14141. \end{array}
  14142. }
  14143. \newcommand{\LlambdaASTPython}{
  14144. \begin{array}{lcl}
  14145. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  14146. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  14147. \end{array}
  14148. }
  14149. % include AnnAssign in ASTPython
  14150. \begin{figure}[tp]
  14151. \centering
  14152. \begin{tcolorbox}[colback=white]
  14153. \small
  14154. {\if\edition\racketEd
  14155. \[
  14156. \begin{array}{l}
  14157. \gray{\LintGrammarRacket{}} \\ \hline
  14158. \gray{\LvarGrammarRacket{}} \\ \hline
  14159. \gray{\LifGrammarRacket{}} \\ \hline
  14160. \gray{\LwhileGrammarRacket} \\ \hline
  14161. \gray{\LtupGrammarRacket} \\ \hline
  14162. \gray{\LfunGrammarRacket} \\ \hline
  14163. \LlambdaGrammarRacket \\
  14164. \begin{array}{lcl}
  14165. \LangLamM{} &::=& \Def\ldots \; \Exp
  14166. \end{array}
  14167. \end{array}
  14168. \]
  14169. \fi}
  14170. {\if\edition\pythonEd
  14171. \[
  14172. \begin{array}{l}
  14173. \gray{\LintGrammarPython{}} \\ \hline
  14174. \gray{\LvarGrammarPython{}} \\ \hline
  14175. \gray{\LifGrammarPython{}} \\ \hline
  14176. \gray{\LwhileGrammarPython} \\ \hline
  14177. \gray{\LtupGrammarPython} \\ \hline
  14178. \gray{\LfunGrammarPython} \\ \hline
  14179. \LlambdaGrammarPython \\
  14180. \begin{array}{lcl}
  14181. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  14182. \end{array}
  14183. \end{array}
  14184. \]
  14185. \fi}
  14186. \end{tcolorbox}
  14187. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Lfun-concrete-syntax})
  14188. with \key{lambda}.}
  14189. \label{fig:Llam-concrete-syntax}
  14190. \end{figure}
  14191. \begin{figure}[tp]
  14192. \centering
  14193. \begin{tcolorbox}[colback=white]
  14194. \small
  14195. {\if\edition\racketEd
  14196. \[\arraycolsep=3pt
  14197. \begin{array}{l}
  14198. \gray{\LintOpAST} \\ \hline
  14199. \gray{\LvarASTRacket{}} \\ \hline
  14200. \gray{\LifASTRacket{}} \\ \hline
  14201. \gray{\LwhileASTRacket{}} \\ \hline
  14202. \gray{\LtupASTRacket{}} \\ \hline
  14203. \gray{\LfunASTRacket} \\ \hline
  14204. \LlambdaASTRacket \\
  14205. \begin{array}{lcl}
  14206. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14207. \end{array}
  14208. \end{array}
  14209. \]
  14210. \fi}
  14211. {\if\edition\pythonEd
  14212. \[
  14213. \begin{array}{l}
  14214. \gray{\LintASTPython} \\ \hline
  14215. \gray{\LvarASTPython{}} \\ \hline
  14216. \gray{\LifASTPython{}} \\ \hline
  14217. \gray{\LwhileASTPython{}} \\ \hline
  14218. \gray{\LtupASTPython{}} \\ \hline
  14219. \gray{\LfunASTPython} \\ \hline
  14220. \LlambdaASTPython \\
  14221. \begin{array}{lcl}
  14222. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14223. \end{array}
  14224. \end{array}
  14225. \]
  14226. \fi}
  14227. \end{tcolorbox}
  14228. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Lfun-syntax}).}
  14229. \label{fig:Llam-syntax}
  14230. \end{figure}
  14231. \index{subject}{interpreter}
  14232. \label{sec:interp-Llambda}
  14233. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  14234. \LangLam{}. The case for \key{Lambda} saves the current environment
  14235. inside the returned function value. Recall that during function
  14236. application, the environment stored in the function value, extended
  14237. with the mapping of parameters to argument values, is used to
  14238. interpret the body of the function.
  14239. \begin{figure}[tbp]
  14240. \begin{tcolorbox}[colback=white]
  14241. {\if\edition\racketEd
  14242. \begin{lstlisting}
  14243. (define interp-Llambda-class
  14244. (class interp-Lfun-class
  14245. (super-new)
  14246. (define/override (interp-op op)
  14247. (match op
  14248. ['procedure-arity
  14249. (lambda (v)
  14250. (match v
  14251. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  14252. [else (error 'interp-op "expected a function, not ~a" v)]))]
  14253. [else (super interp-op op)]))
  14254. (define/override ((interp-exp env) e)
  14255. (define recur (interp-exp env))
  14256. (match e
  14257. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  14258. `(function ,xs ,body ,env)]
  14259. [else ((super interp-exp env) e)]))
  14260. ))
  14261. (define (interp-Llambda p)
  14262. (send (new interp-Llambda-class) interp-program p))
  14263. \end{lstlisting}
  14264. \fi}
  14265. {\if\edition\pythonEd
  14266. \begin{lstlisting}
  14267. class InterpLlambda(InterpLfun):
  14268. def arity(self, v):
  14269. match v:
  14270. case Function(name, params, body, env):
  14271. return len(params)
  14272. case _:
  14273. raise Exception('Llambda arity unexpected ' + repr(v))
  14274. def interp_exp(self, e, env):
  14275. match e:
  14276. case Call(Name('arity'), [fun]):
  14277. f = self.interp_exp(fun, env)
  14278. return self.arity(f)
  14279. case Lambda(params, body):
  14280. return Function('lambda', params, [Return(body)], env)
  14281. case _:
  14282. return super().interp_exp(e, env)
  14283. def interp_stmts(self, ss, env):
  14284. if len(ss) == 0:
  14285. return
  14286. match ss[0]:
  14287. case AnnAssign(lhs, typ, value, simple):
  14288. env[lhs.id] = self.interp_exp(value, env)
  14289. return self.interp_stmts(ss[1:], env)
  14290. case _:
  14291. return super().interp_stmts(ss, env)
  14292. \end{lstlisting}
  14293. \fi}
  14294. \end{tcolorbox}
  14295. \caption{Interpreter for \LangLam{}.}
  14296. \label{fig:interp-Llambda}
  14297. \end{figure}
  14298. \label{sec:type-check-r5}
  14299. \index{subject}{type checking}
  14300. {\if\edition\racketEd
  14301. %
  14302. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  14303. \key{lambda} form. The body of the \key{lambda} is checked in an
  14304. environment that includes the current environment (because it is
  14305. lexically scoped) and also includes the \key{lambda}'s parameters. We
  14306. require the body's type to match the declared return type.
  14307. %
  14308. \fi}
  14309. {\if\edition\pythonEd
  14310. %
  14311. Figures~\ref{fig:type-check-Llambda} and
  14312. \ref{fig:type-check-Llambda-part2} define the type checker for
  14313. \LangLam{}, which is more complex than one might expect. The reason
  14314. for the added complexity is that the syntax of \key{lambda} does not
  14315. include type annotations for the parameters or return type. Instead
  14316. they must be inferred. There are many approaches of type inference to
  14317. choose from of varying degrees of complexity. We choose one of the
  14318. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  14319. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  14320. this book is compilation, not type inference.
  14321. The main idea of bidirectional type inference is to add an auxiliary
  14322. function, here named \code{check\_exp}, that takes an expected type
  14323. and checks whether the given expression is of that type. Thus, in
  14324. \code{check\_exp}, type information flows in a top-down manner with
  14325. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  14326. function, where type information flows in a primarily bottom-up
  14327. manner.
  14328. %
  14329. The idea then is to use \code{check\_exp} in all the places where we
  14330. already know what the type of an expression should be, such as in the
  14331. \code{return} statement of a top-level function definition, or on the
  14332. right-hand side of an annotated assignment statement.
  14333. Getting back to \code{lambda}, it is straightforward to check a
  14334. \code{lambda} inside \code{check\_exp} because the expected type
  14335. provides the parameter types and the return type. On the other hand,
  14336. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  14337. that we do not allow \code{lambda} in contexts where we don't already
  14338. know its type. This restriction does not incur a loss of
  14339. expressiveness for \LangLam{} because it is straightforward to modify
  14340. a program to sidestep the restriction, for example, by using an
  14341. annotated assignment statement to assign the \code{lambda} to a
  14342. temporary variable.
  14343. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  14344. checker records their type in a \code{has\_type} field. This type
  14345. information is used later in this chapter.
  14346. %
  14347. \fi}
  14348. \begin{figure}[tbp]
  14349. \begin{tcolorbox}[colback=white]
  14350. {\if\edition\racketEd
  14351. \begin{lstlisting}
  14352. (define (type-check-Llambda env)
  14353. (lambda (e)
  14354. (match e
  14355. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  14356. (define-values (new-body bodyT)
  14357. ((type-check-exp (append (map cons xs Ts) env)) body))
  14358. (define ty `(,@Ts -> ,rT))
  14359. (cond
  14360. [(equal? rT bodyT)
  14361. (values (HasType (Lambda params rT new-body) ty) ty)]
  14362. [else
  14363. (error "mismatch in return type" bodyT rT)])]
  14364. ...
  14365. )))
  14366. \end{lstlisting}
  14367. \fi}
  14368. {\if\edition\pythonEd
  14369. \begin{lstlisting}
  14370. class TypeCheckLlambda(TypeCheckLfun):
  14371. def type_check_exp(self, e, env):
  14372. match e:
  14373. case Name(id):
  14374. e.has_type = env[id]
  14375. return env[id]
  14376. case Lambda(params, body):
  14377. raise Exception('cannot synthesize a type for a lambda')
  14378. case Call(Name('arity'), [func]):
  14379. func_t = self.type_check_exp(func, env)
  14380. match func_t:
  14381. case FunctionType(params_t, return_t):
  14382. return IntType()
  14383. case _:
  14384. raise Exception('in arity, unexpected ' + repr(func_t))
  14385. case _:
  14386. return super().type_check_exp(e, env)
  14387. def check_exp(self, e, ty, env):
  14388. match e:
  14389. case Lambda(params, body):
  14390. e.has_type = ty
  14391. match ty:
  14392. case FunctionType(params_t, return_t):
  14393. new_env = env.copy().update(zip(params, params_t))
  14394. self.check_exp(body, return_t, new_env)
  14395. case _:
  14396. raise Exception('lambda does not have type ' + str(ty))
  14397. case Call(func, args):
  14398. func_t = self.type_check_exp(func, env)
  14399. match func_t:
  14400. case FunctionType(params_t, return_t):
  14401. for (arg, param_t) in zip(args, params_t):
  14402. self.check_exp(arg, param_t, env)
  14403. self.check_type_equal(return_t, ty, e)
  14404. case _:
  14405. raise Exception('type_check_exp: in call, unexpected ' + \
  14406. repr(func_t))
  14407. case _:
  14408. t = self.type_check_exp(e, env)
  14409. self.check_type_equal(t, ty, e)
  14410. \end{lstlisting}
  14411. \fi}
  14412. \end{tcolorbox}
  14413. \caption{Type checking \LangLam{}\python{, part 1}.}
  14414. \label{fig:type-check-Llambda}
  14415. \end{figure}
  14416. {\if\edition\pythonEd
  14417. \begin{figure}[tbp]
  14418. \begin{tcolorbox}[colback=white]
  14419. \begin{lstlisting}
  14420. def check_stmts(self, ss, return_ty, env):
  14421. if len(ss) == 0:
  14422. return
  14423. match ss[0]:
  14424. case FunctionDef(name, params, body, dl, returns, comment):
  14425. new_env = env.copy().update(params)
  14426. rt = self.check_stmts(body, returns, new_env)
  14427. self.check_stmts(ss[1:], return_ty, env)
  14428. case Return(value):
  14429. self.check_exp(value, return_ty, env)
  14430. case Assign([Name(id)], value):
  14431. if id in env:
  14432. self.check_exp(value, env[id], env)
  14433. else:
  14434. env[id] = self.type_check_exp(value, env)
  14435. self.check_stmts(ss[1:], return_ty, env)
  14436. case Assign([Subscript(tup, Constant(index), Store())], value):
  14437. tup_t = self.type_check_exp(tup, env)
  14438. match tup_t:
  14439. case TupleType(ts):
  14440. self.check_exp(value, ts[index], env)
  14441. case _:
  14442. raise Exception('expected a tuple, not ' + repr(tup_t))
  14443. self.check_stmts(ss[1:], return_ty, env)
  14444. case AnnAssign(Name(id), ty_annot, value, simple):
  14445. ss[0].annotation = ty_annot
  14446. if id in env:
  14447. self.check_type_equal(env[id], ty_annot)
  14448. else:
  14449. env[id] = ty_annot
  14450. self.check_exp(value, ty_annot, env)
  14451. self.check_stmts(ss[1:], return_ty, env)
  14452. case _:
  14453. self.type_check_stmts(ss, env)
  14454. def type_check(self, p):
  14455. match p:
  14456. case Module(body):
  14457. env = {}
  14458. for s in body:
  14459. match s:
  14460. case FunctionDef(name, params, bod, dl, returns, comment):
  14461. params_t = [t for (x,t) in params]
  14462. env[name] = FunctionType(params_t, returns)
  14463. self.check_stmts(body, int, env)
  14464. \end{lstlisting}
  14465. \end{tcolorbox}
  14466. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14467. \label{fig:type-check-Llambda-part2}
  14468. \end{figure}
  14469. \fi}
  14470. \clearpage
  14471. \section{Assignment and Lexically Scoped Functions}
  14472. \label{sec:assignment-scoping}
  14473. The combination of lexically-scoped functions and assignment to
  14474. variables raises a challenge with the flat-closure approach to
  14475. implementing lexically-scoped functions. Consider the following
  14476. example in which function \code{f} has a free variable \code{x} that
  14477. is changed after \code{f} is created but before the call to \code{f}.
  14478. % loop_test_11.rkt
  14479. {\if\edition\racketEd
  14480. \begin{lstlisting}
  14481. (let ([x 0])
  14482. (let ([y 0])
  14483. (let ([z 20])
  14484. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14485. (begin
  14486. (set! x 10)
  14487. (set! y 12)
  14488. (f y))))))
  14489. \end{lstlisting}
  14490. \fi}
  14491. {\if\edition\pythonEd
  14492. % box_free_assign.py
  14493. \begin{lstlisting}
  14494. def g(z : int) -> int:
  14495. x = 0
  14496. y = 0
  14497. f : Callable[[int],int] = lambda a: a + x + z
  14498. x = 10
  14499. y = 12
  14500. return f(y)
  14501. print( g(20) )
  14502. \end{lstlisting}
  14503. \fi} The correct output for this example is \code{42} because the call
  14504. to \code{f} is required to use the current value of \code{x} (which is
  14505. \code{10}). Unfortunately, the closure conversion pass
  14506. (Section~\ref{sec:closure-conversion}) generates code for the
  14507. \code{lambda} that copies the old value of \code{x} into a
  14508. closure. Thus, if we naively apply closure conversion, the output of
  14509. this program would be \code{32}.
  14510. A first attempt at solving this problem would be to save a pointer to
  14511. \code{x} in the closure and change the occurrences of \code{x} inside
  14512. the lambda to dereference the pointer. Of course, this would require
  14513. assigning \code{x} to the stack and not to a register. However, the
  14514. problem goes a bit deeper.
  14515. Consider the following example that returns a function that refers to
  14516. a local variable of the enclosing function.
  14517. \begin{center}
  14518. \begin{minipage}{\textwidth}
  14519. {\if\edition\racketEd
  14520. \begin{lstlisting}
  14521. (define (f []) : Integer
  14522. (let ([x 0])
  14523. (let ([g (lambda: () : Integer x)])
  14524. (begin
  14525. (set! x 42)
  14526. g))))
  14527. ((f))
  14528. \end{lstlisting}
  14529. \fi}
  14530. {\if\edition\pythonEd
  14531. % counter.py
  14532. \begin{lstlisting}
  14533. def f():
  14534. x = 0
  14535. g = lambda: x
  14536. x = 42
  14537. return g
  14538. print( f()() )
  14539. \end{lstlisting}
  14540. \fi}
  14541. \end{minipage}
  14542. \end{center}
  14543. In this example, the lifetime of \code{x} extends beyond the lifetime
  14544. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14545. stack frame for the call to \code{f}, it would be gone by the time we
  14546. call \code{g}, leaving us with dangling pointers for
  14547. \code{x}. This example demonstrates that when a variable occurs free
  14548. inside a function, its lifetime becomes indefinite. Thus, the value of
  14549. the variable needs to live on the heap. The verb
  14550. \emph{box}\index{subject}{box} is often used for allocating a single
  14551. value on the heap, producing a pointer, and
  14552. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14553. %
  14554. We introduce a new pass named \code{convert\_assignments} to address
  14555. this challenge.
  14556. %
  14557. \python{But before diving into that, we have one more
  14558. problem to discuss.}
  14559. \if\edition\pythonEd
  14560. \section{Uniquify Variables}
  14561. \label{sec:uniquify-lambda}
  14562. With the addition of \code{lambda} we have a complication to deal
  14563. with: name shadowing. Consider the following program with a function
  14564. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14565. \code{lambda} expressions. The first \code{lambda} has a parameter
  14566. that is also named \code{x}.
  14567. \begin{lstlisting}
  14568. def f(x:int, y:int) -> Callable[[int], int]:
  14569. g : Callable[[int],int] = (lambda x: x + y)
  14570. h : Callable[[int],int] = (lambda y: x + y)
  14571. x = input_int()
  14572. return g
  14573. print(f(0, 10)(32))
  14574. \end{lstlisting}
  14575. Many of our compiler passes rely on being able to connect variable
  14576. uses with their definitions using just the name of the variable,
  14577. including new passes in this chapter. However, in the above example
  14578. the name of the variable does not uniquely determine its
  14579. definition. To solve this problem we recommend implementing a pass
  14580. named \code{uniquify} that renames every variable in the program to
  14581. make sure they are all unique.
  14582. The following shows the result of \code{uniquify} for the above
  14583. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14584. and the \code{x} parameter of the \code{lambda} is renamed to
  14585. \code{x\_4}.
  14586. \begin{lstlisting}
  14587. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14588. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14589. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14590. x_0 = input_int()
  14591. return g_2
  14592. def main() -> int :
  14593. print(f(0, 10)(32))
  14594. return 0
  14595. \end{lstlisting}
  14596. \fi
  14597. %% \section{Reveal Functions}
  14598. %% \label{sec:reveal-functions-r5}
  14599. %% \racket{To support the \code{procedure-arity} operator we need to
  14600. %% communicate the arity of a function to the point of closure
  14601. %% creation.}
  14602. %% %
  14603. %% \python{In Chapter~\ref{ch:Ldyn} we need to access the arity of a
  14604. %% function at runtime. Thus, we need to communicate the arity of a
  14605. %% function to the point of closure creation.}
  14606. %% %
  14607. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14608. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14609. %% \[
  14610. %% \begin{array}{lcl}
  14611. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14612. %% \end{array}
  14613. %% \]
  14614. \section{Assignment Conversion}
  14615. \label{sec:convert-assignments}
  14616. The purpose of the \code{convert\_assignments} pass is to address the
  14617. challenge regarding the interaction between variable assignments and
  14618. closure conversion. First we identify which variables need to be
  14619. boxed, then we transform the program to box those variables. In
  14620. general, boxing introduces runtime overhead that we would like to
  14621. avoid, so we should box as few variables as possible. We recommend
  14622. boxing the variables in the intersection of the following two sets of
  14623. variables:
  14624. \begin{enumerate}
  14625. \item The variables that are free in a \code{lambda}.
  14626. \item The variables that appear on the left-hand side of an
  14627. assignment.
  14628. \end{enumerate}
  14629. The first condition is a must but the second condition is
  14630. conservative. It is possible to develop a more liberal condition using
  14631. static program analysis.
  14632. Consider again the first example from
  14633. Section~\ref{sec:assignment-scoping}:
  14634. %
  14635. {\if\edition\racketEd
  14636. \begin{lstlisting}
  14637. (let ([x 0])
  14638. (let ([y 0])
  14639. (let ([z 20])
  14640. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14641. (begin
  14642. (set! x 10)
  14643. (set! y 12)
  14644. (f y))))))
  14645. \end{lstlisting}
  14646. \fi}
  14647. {\if\edition\pythonEd
  14648. \begin{lstlisting}
  14649. def g(z : int) -> int:
  14650. x = 0
  14651. y = 0
  14652. f : Callable[[int],int] = lambda a: a + x + z
  14653. x = 10
  14654. y = 12
  14655. return f(y)
  14656. print( g(20) )
  14657. \end{lstlisting}
  14658. \fi}
  14659. %
  14660. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14661. variables \code{x} and \code{z} occur free inside the
  14662. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14663. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14664. transformations: initialize \code{x} with a tuple whose elements are uninitialized,
  14665. replace reads from \code{x} with tuple reads, and replace each assignment to \code{x}
  14666. with a tuple write. The output of \code{convert\_assignments} for
  14667. this example is as follows.
  14668. %
  14669. {\if\edition\racketEd
  14670. \begin{lstlisting}
  14671. (define (main) : Integer
  14672. (let ([x0 (vector 0)])
  14673. (let ([y1 0])
  14674. (let ([z2 20])
  14675. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14676. (+ a3 (+ (vector-ref x0 0) z2)))])
  14677. (begin
  14678. (vector-set! x0 0 10)
  14679. (set! y1 12)
  14680. (f4 y1)))))))
  14681. \end{lstlisting}
  14682. \fi}
  14683. %
  14684. {\if\edition\pythonEd
  14685. \begin{lstlisting}
  14686. def g(z : int)-> int:
  14687. x = (uninitialized(int),)
  14688. x[0] = 0
  14689. y = 0
  14690. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14691. x[0] = 10
  14692. y = 12
  14693. return f(y)
  14694. def main() -> int:
  14695. print(g(20))
  14696. return 0
  14697. \end{lstlisting}
  14698. \fi}
  14699. To compute the free variables of all the \code{lambda} expressions, we
  14700. recommend defining two auxiliary functions:
  14701. \begin{enumerate}
  14702. \item \code{free\_variables} computes the free variables of an expression, and
  14703. \item \code{free\_in\_lambda} collects all of the variables that are
  14704. free in any of the \code{lambda} expressions, using
  14705. \code{free\_variables} in the case for each \code{lambda}.
  14706. \end{enumerate}
  14707. {\if\edition\racketEd
  14708. %
  14709. To compute the variables that are assigned-to, we recommend using the
  14710. \code{collect-set!} function that we introduced in
  14711. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14712. forms such as \code{Lambda}.
  14713. %
  14714. \fi}
  14715. {\if\edition\pythonEd
  14716. %
  14717. To compute the variables that are assigned-to, we recommend defining
  14718. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14719. the set of variables that occur in the left-hand side of an assignment
  14720. statement, and otherwise returns the empty set.
  14721. %
  14722. \fi}
  14723. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14724. free in a \code{lambda} and that are assigned-to in the enclosing
  14725. function definition.
  14726. Next we discuss the \code{convert\_assignments} pass. In the case for
  14727. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14728. $\VAR{x}$ to a tuple read.
  14729. %
  14730. {\if\edition\racketEd
  14731. \begin{lstlisting}
  14732. (Var |$x$|)
  14733. |$\Rightarrow$|
  14734. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14735. \end{lstlisting}
  14736. \fi}
  14737. %
  14738. {\if\edition\pythonEd
  14739. \begin{lstlisting}
  14740. Name(|$x$|)
  14741. |$\Rightarrow$|
  14742. Subscript(Name(|$x$|), Constant(0), Load())
  14743. \end{lstlisting}
  14744. \fi}
  14745. %
  14746. \noindent In the case for assignment, recursively process the
  14747. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  14748. $x$ is in $\mathit{AF}$, translate the assignment into a tuple-write
  14749. as follows.
  14750. %
  14751. {\if\edition\racketEd
  14752. \begin{lstlisting}
  14753. (SetBang |$x$| |$\itm{rhs}$|)
  14754. |$\Rightarrow$|
  14755. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14756. \end{lstlisting}
  14757. \fi}
  14758. {\if\edition\pythonEd
  14759. \begin{lstlisting}
  14760. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14761. |$\Rightarrow$|
  14762. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14763. \end{lstlisting}
  14764. \fi}
  14765. %
  14766. {\if\edition\racketEd
  14767. The case for \code{Lambda} is non-trivial, but it is similar to the
  14768. case for function definitions, which we discuss next.
  14769. \fi}
  14770. %
  14771. To translate a function definition, we first compute $\mathit{AF}$,
  14772. the intersection of the variables that are free in a \code{lambda} and
  14773. that are assigned-to. We then apply assignment conversion to the body
  14774. of the function definition. Finally, we box the parameters of this
  14775. function definition that are in $\mathit{AF}$. For example,
  14776. the parameter \code{x} of the following function \code{g}
  14777. needs to be boxed.
  14778. {\if\edition\racketEd
  14779. \begin{lstlisting}
  14780. (define (g [x : Integer]) : Integer
  14781. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14782. (begin
  14783. (set! x 10)
  14784. (f 32))))
  14785. \end{lstlisting}
  14786. \fi}
  14787. %
  14788. {\if\edition\pythonEd
  14789. \begin{lstlisting}
  14790. def g(x : int) -> int:
  14791. f : Callable[[int],int] = lambda a: a + x
  14792. x = 10
  14793. return f(32)
  14794. \end{lstlisting}
  14795. \fi}
  14796. %
  14797. \noindent We box parameter \code{x} by creating a local variable named
  14798. \code{x} that is initialized to a tuple whose contents is the value of
  14799. the parameter, which has been renamed to \code{x\_0}.
  14800. %
  14801. {\if\edition\racketEd
  14802. \begin{lstlisting}
  14803. (define (g [x_0 : Integer]) : Integer
  14804. (let ([x (vector x_0)])
  14805. (let ([f (lambda: ([a : Integer]) : Integer
  14806. (+ a (vector-ref x 0)))])
  14807. (begin
  14808. (vector-set! x 0 10)
  14809. (f 32)))))
  14810. \end{lstlisting}
  14811. \fi}
  14812. %
  14813. {\if\edition\pythonEd
  14814. \begin{lstlisting}
  14815. def g(x_0 : int)-> int:
  14816. x = (x_0,)
  14817. f : Callable[[int], int] = (lambda a: a + x[0])
  14818. x[0] = 10
  14819. return f(32)
  14820. \end{lstlisting}
  14821. \fi}
  14822. \section{Closure Conversion}
  14823. \label{sec:closure-conversion}
  14824. \index{subject}{closure conversion}
  14825. The compiling of lexically-scoped functions into top-level function
  14826. definitions and flat closures is accomplished in the pass
  14827. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  14828. and before \code{limit\_functions}.
  14829. As usual, we implement the pass as a recursive function over the
  14830. AST. The interesting cases are the ones for \key{lambda} and function
  14831. application. We transform a \key{lambda} expression into an expression
  14832. that creates a closure, that is, a tuple whose first element is a
  14833. function pointer and the rest of the elements are the values of the
  14834. free variables of the \key{lambda}.
  14835. %
  14836. However, we use the \code{Closure} AST node instead of using a tuple
  14837. so that we can record the arity.
  14838. %
  14839. In the generated code below, \itm{fvs} is the free variables of the
  14840. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14841. %
  14842. \racket{The \itm{arity} is the number of parameters (the length of
  14843. \itm{ps}).}
  14844. %
  14845. {\if\edition\racketEd
  14846. \begin{lstlisting}
  14847. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14848. |$\Rightarrow$|
  14849. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  14850. \end{lstlisting}
  14851. \fi}
  14852. %
  14853. {\if\edition\pythonEd
  14854. \begin{lstlisting}
  14855. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  14856. |$\Rightarrow$|
  14857. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  14858. \end{lstlisting}
  14859. \fi}
  14860. %
  14861. In addition to transforming each \key{Lambda} AST node into a
  14862. tuple, we create a top-level function definition for each
  14863. \key{Lambda}, as shown below.\\
  14864. \begin{minipage}{0.8\textwidth}
  14865. {\if\edition\racketEd
  14866. \begin{lstlisting}
  14867. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14868. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14869. ...
  14870. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14871. |\itm{body'}|)...))
  14872. \end{lstlisting}
  14873. \fi}
  14874. {\if\edition\pythonEd
  14875. \begin{lstlisting}
  14876. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14877. |$\itm{fvs}_1$| = clos[1]
  14878. |$\ldots$|
  14879. |$\itm{fvs}_n$| = clos[|$n$|]
  14880. |\itm{body'}|
  14881. \end{lstlisting}
  14882. \fi}
  14883. \end{minipage}\\
  14884. The \code{clos} parameter refers to the closure. Translate the type
  14885. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14886. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14887. \itm{closTy} is a tuple type whose first element type is
  14888. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14889. the element types are the types of the free variables in the
  14890. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14891. is non-trivial to give a type to the function in the closure's type.%
  14892. %
  14893. \footnote{To give an accurate type to a closure, we would need to add
  14894. existential types to the type checker~\citep{Minamide:1996ys}.}
  14895. %
  14896. %% The dummy type is considered to be equal to any other type during type
  14897. %% checking.
  14898. The free variables become local variables that are initialized with
  14899. their values in the closure.
  14900. Closure conversion turns every function into a tuple, so the type
  14901. annotations in the program must also be translated. We recommend
  14902. defining an auxiliary recursive function for this purpose. Function
  14903. types should be translated as follows.
  14904. %
  14905. {\if\edition\racketEd
  14906. \begin{lstlisting}
  14907. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14908. |$\Rightarrow$|
  14909. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14910. \end{lstlisting}
  14911. \fi}
  14912. {\if\edition\pythonEd
  14913. \begin{lstlisting}
  14914. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14915. |$\Rightarrow$|
  14916. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14917. \end{lstlisting}
  14918. \fi}
  14919. %
  14920. The above type says that the first thing in the tuple is a
  14921. function. The first parameter of the function is a tuple (a closure)
  14922. and the rest of the parameters are the ones from the original
  14923. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14924. omits the types of the free variables because 1) those types are not
  14925. available in this context and 2) we do not need them in the code that
  14926. is generated for function application. So this type only describes the
  14927. first component of the closure tuple. At runtime the tuple may have
  14928. more components, but we ignore them at this point.
  14929. We transform function application into code that retrieves the
  14930. function from the closure and then calls the function, passing the
  14931. closure as the first argument. We place $e'$ in a temporary variable
  14932. to avoid code duplication.
  14933. \begin{center}
  14934. \begin{minipage}{\textwidth}
  14935. {\if\edition\racketEd
  14936. \begin{lstlisting}
  14937. (Apply |$e$| |$\itm{es}$|)
  14938. |$\Rightarrow$|
  14939. (Let |$\itm{tmp}$| |$e'$|
  14940. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  14941. \end{lstlisting}
  14942. \fi}
  14943. %
  14944. {\if\edition\pythonEd
  14945. \begin{lstlisting}
  14946. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14947. |$\Rightarrow$|
  14948. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  14949. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14950. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14951. \end{lstlisting}
  14952. \fi}
  14953. \end{minipage}
  14954. \end{center}
  14955. There is also the question of what to do with references to top-level
  14956. function definitions. To maintain a uniform translation of function
  14957. application, we turn function references into closures.
  14958. \begin{tabular}{lll}
  14959. \begin{minipage}{0.3\textwidth}
  14960. {\if\edition\racketEd
  14961. \begin{lstlisting}
  14962. (FunRef |$f$| |$n$|)
  14963. \end{lstlisting}
  14964. \fi}
  14965. {\if\edition\pythonEd
  14966. \begin{lstlisting}
  14967. FunRef(|$f$|, |$n$|)
  14968. \end{lstlisting}
  14969. \fi}
  14970. \end{minipage}
  14971. &
  14972. $\Rightarrow$
  14973. &
  14974. \begin{minipage}{0.5\textwidth}
  14975. {\if\edition\racketEd
  14976. \begin{lstlisting}
  14977. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  14978. \end{lstlisting}
  14979. \fi}
  14980. {\if\edition\pythonEd
  14981. \begin{lstlisting}
  14982. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  14983. \end{lstlisting}
  14984. \fi}
  14985. \end{minipage}
  14986. \end{tabular} \\
  14987. We no longer need the annotated assignment statement \code{AnnAssign}
  14988. to support the type checking of \code{lambda} expressions, so we
  14989. translate it to a regular \code{Assign} statement.
  14990. The top-level function definitions need to be updated to take an extra
  14991. closure parameter but that parameter is ignored in the body of those
  14992. functions.
  14993. \section{An Example Translation}
  14994. \label{sec:example-lambda}
  14995. Figure~\ref{fig:lexical-functions-example} shows the result of
  14996. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14997. program demonstrating lexical scoping that we discussed at the
  14998. beginning of this chapter.
  14999. \begin{figure}[tbp]
  15000. \begin{tcolorbox}[colback=white]
  15001. \begin{minipage}{0.8\textwidth}
  15002. {\if\edition\racketEd
  15003. % tests/lambda_test_6.rkt
  15004. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15005. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  15006. (let ([y8 4])
  15007. (lambda: ([z9 : Integer]) : Integer
  15008. (+ x7 (+ y8 z9)))))
  15009. (define (main) : Integer
  15010. (let ([g0 ((fun-ref f6 1) 5)])
  15011. (let ([h1 ((fun-ref f6 1) 3)])
  15012. (+ (g0 11) (h1 15)))))
  15013. \end{lstlisting}
  15014. $\Rightarrow$
  15015. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15016. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  15017. (let ([y8 4])
  15018. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  15019. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  15020. (let ([x7 (vector-ref fvs3 1)])
  15021. (let ([y8 (vector-ref fvs3 2)])
  15022. (+ x7 (+ y8 z9)))))
  15023. (define (main) : Integer
  15024. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  15025. ((vector-ref clos5 0) clos5 5))])
  15026. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  15027. ((vector-ref clos6 0) clos6 3))])
  15028. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  15029. \end{lstlisting}
  15030. \fi}
  15031. %
  15032. {\if\edition\pythonEd
  15033. % free_var.py
  15034. \begin{lstlisting}
  15035. def f(x : int) -> Callable[[int], int]:
  15036. y = 4
  15037. return lambda z: x + y + z
  15038. g = f(5)
  15039. h = f(3)
  15040. print( g(11) + h(15) )
  15041. \end{lstlisting}
  15042. $\Rightarrow$
  15043. \begin{lstlisting}
  15044. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  15045. x = fvs_1[1]
  15046. y = fvs_1[2]
  15047. return x + y[0] + z
  15048. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  15049. y = (777,)
  15050. y[0] = 4
  15051. return (lambda_0, x, y)
  15052. def main() -> int:
  15053. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  15054. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  15055. print((let clos_5 = g in clos_5[0](clos_5, 11))
  15056. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  15057. return 0
  15058. \end{lstlisting}
  15059. \fi}
  15060. \end{minipage}
  15061. \end{tcolorbox}
  15062. \caption{Example of closure conversion.}
  15063. \label{fig:lexical-functions-example}
  15064. \end{figure}
  15065. \begin{exercise}\normalfont\normalsize
  15066. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  15067. Create 5 new programs that use \key{lambda} functions and make use of
  15068. lexical scoping. Test your compiler on these new programs and all of
  15069. your previously created test programs.
  15070. \end{exercise}
  15071. \section{Expose Allocation}
  15072. \label{sec:expose-allocation-r5}
  15073. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  15074. that allocates and initializes a tuple, similar to the translation of
  15075. the tuple creation in Section~\ref{sec:expose-allocation}.
  15076. The only difference is replacing the use of
  15077. \ALLOC{\itm{len}}{\itm{type}} with
  15078. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  15079. \section{Explicate Control and \LangCLam{}}
  15080. \label{sec:explicate-r5}
  15081. The output language of \code{explicate\_control} is \LangCLam{} whose
  15082. abstract syntax is defined in Figure~\ref{fig:Clam-syntax}.
  15083. %
  15084. \racket{The only differences with respect to \LangCFun{} is the
  15085. addition of the \code{AllocateClosure} form to the grammar for
  15086. $\Exp$ and the \code{procedure-arity} operator. The handling of
  15087. \code{AllocateClosure} in the \code{explicate\_control} pass is
  15088. similar to the handling of other expressions such as primitive
  15089. operators.}
  15090. %
  15091. \python{The differences with respect to \LangCFun{} are the
  15092. additions of \code{Uninitialized}, \code{AllocateClosure},
  15093. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  15094. \code{explicate\_control} pass is similar to the handling of other
  15095. expressions such as primitive operators.}
  15096. \newcommand{\ClambdaASTRacket}{
  15097. \begin{array}{lcl}
  15098. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  15099. \itm{op} &::= & \code{procedure-arity}
  15100. \end{array}
  15101. }
  15102. \newcommand{\ClambdaASTPython}{
  15103. \begin{array}{lcl}
  15104. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  15105. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  15106. &\MID& \ARITY{\Atm}
  15107. \end{array}
  15108. }
  15109. \begin{figure}[tp]
  15110. \begin{tcolorbox}[colback=white]
  15111. \small
  15112. {\if\edition\racketEd
  15113. \[
  15114. \begin{array}{l}
  15115. \gray{\CvarASTRacket} \\ \hline
  15116. \gray{\CifASTRacket} \\ \hline
  15117. \gray{\CloopASTRacket} \\ \hline
  15118. \gray{\CtupASTRacket} \\ \hline
  15119. \gray{\CfunASTRacket} \\ \hline
  15120. \ClambdaASTRacket \\
  15121. \begin{array}{lcl}
  15122. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  15123. \end{array}
  15124. \end{array}
  15125. \]
  15126. \fi}
  15127. {\if\edition\pythonEd
  15128. \[
  15129. \begin{array}{l}
  15130. \gray{\CifASTPython} \\ \hline
  15131. \gray{\CtupASTPython} \\ \hline
  15132. \gray{\CfunASTPython} \\ \hline
  15133. \ClambdaASTPython \\
  15134. \begin{array}{lcl}
  15135. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  15136. \end{array}
  15137. \end{array}
  15138. \]
  15139. \fi}
  15140. \end{tcolorbox}
  15141. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  15142. \label{fig:Clam-syntax}
  15143. \end{figure}
  15144. \section{Select Instructions}
  15145. \label{sec:select-instructions-Llambda}
  15146. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  15147. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  15148. (Section~\ref{sec:select-instructions-gc}). The only difference is
  15149. that you should place the \itm{arity} in the tag that is stored at
  15150. position $0$ of the vector. Recall that in
  15151. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  15152. was not used. We store the arity in the $5$ bits starting at position
  15153. $58$.
  15154. \racket{Compile the \code{procedure-arity} operator into a sequence of
  15155. instructions that access the tag from position $0$ of the vector and
  15156. extract the $5$-bits starting at position $58$ from the tag.}
  15157. %
  15158. \python{Compile a call to the \code{arity} operator to a sequence of
  15159. instructions that access the tag from position $0$ of the tuple
  15160. (representing a closure) and extract the $5$-bits starting at position
  15161. $58$ from the tag.}
  15162. \begin{figure}[p]
  15163. \begin{tcolorbox}[colback=white]
  15164. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15165. \node (Lfun) at (0,2) {\large \LangLam{}};
  15166. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  15167. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  15168. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  15169. \node (F1-1) at (12,2) {\large \LangLamFunRef{}};
  15170. \node (F1-2) at (12,0) {\large \LangFunRef{}};
  15171. \node (F1-3) at (9,0) {\large \LangFunRef{}};
  15172. \node (F1-4) at (6,0) {\large \LangFunRefAlloc{}};
  15173. \node (F1-5) at (3,0) {\large \LangFunRefAlloc{}};
  15174. \node (F1-6) at (0,0) {\large \LangFunANF{}};
  15175. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  15176. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15177. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15178. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15179. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15180. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15181. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15182. \path[->,bend left=15] (Lfun) edge [above] node
  15183. {\ttfamily\footnotesize shrink} (Lfun-2);
  15184. \path[->,bend left=15] (Lfun-2) edge [above] node
  15185. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15186. \path[->,bend left=15] (Lfun-3) edge [above] node
  15187. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15188. \path[->,bend left=15] (F1-0) edge [above] node
  15189. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  15190. \path[->,bend left=15] (F1-1) edge [left] node
  15191. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15192. \path[->,bend left=15] (F1-2) edge [below] node
  15193. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15194. \path[->,bend right=15] (F1-3) edge [above] node
  15195. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15196. \path[->,bend left=15] (F1-4) edge [below] node
  15197. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  15198. \path[->,bend right=15] (F1-5) edge [above] node
  15199. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  15200. \path[->,bend right=15] (F1-6) edge [right] node
  15201. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15202. \path[->,bend left=15] (C3-2) edge [left] node
  15203. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15204. \path[->,bend right=15] (x86-2) edge [left] node
  15205. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15206. \path[->,bend right=15] (x86-2-1) edge [below] node
  15207. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15208. \path[->,bend right=15] (x86-2-2) edge [left] node
  15209. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15210. \path[->,bend left=15] (x86-3) edge [above] node
  15211. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15212. \path[->,bend left=15] (x86-4) edge [right] node
  15213. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  15214. \end{tikzpicture}
  15215. \end{tcolorbox}
  15216. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  15217. functions.}
  15218. \label{fig:Llambda-passes}
  15219. \end{figure}
  15220. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  15221. needed for the compilation of \LangLam{}.
  15222. \clearpage
  15223. \section{Challenge: Optimize Closures}
  15224. \label{sec:optimize-closures}
  15225. In this chapter we compiled lexically-scoped functions into a
  15226. relatively efficient representation: flat closures. However, even this
  15227. representation comes with some overhead. For example, consider the
  15228. following program with a function \code{tail\_sum} that does not have
  15229. any free variables and where all the uses of \code{tail\_sum} are in
  15230. applications where we know that only \code{tail\_sum} is being applied
  15231. (and not any other functions).
  15232. \begin{center}
  15233. \begin{minipage}{0.95\textwidth}
  15234. {\if\edition\racketEd
  15235. \begin{lstlisting}
  15236. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  15237. (if (eq? n 0)
  15238. s
  15239. (tail_sum (- n 1) (+ n s))))
  15240. (+ (tail_sum 3 0) 36)
  15241. \end{lstlisting}
  15242. \fi}
  15243. {\if\edition\pythonEd
  15244. \begin{lstlisting}
  15245. def tail_sum(n : int, s : int) -> int:
  15246. if n == 0:
  15247. return s
  15248. else:
  15249. return tail_sum(n - 1, n + s)
  15250. print( tail_sum(3, 0) + 36)
  15251. \end{lstlisting}
  15252. \fi}
  15253. \end{minipage}
  15254. \end{center}
  15255. As described in this chapter, we uniformly apply closure conversion to
  15256. all functions, obtaining the following output for this program.
  15257. \begin{center}
  15258. \begin{minipage}{0.95\textwidth}
  15259. {\if\edition\racketEd
  15260. \begin{lstlisting}
  15261. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  15262. (if (eq? n2 0)
  15263. s3
  15264. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  15265. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  15266. (define (main) : Integer
  15267. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  15268. ((vector-ref clos6 0) clos6 3 0)) 27))
  15269. \end{lstlisting}
  15270. \fi}
  15271. {\if\edition\pythonEd
  15272. \begin{lstlisting}
  15273. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  15274. if n_0 == 0:
  15275. return s_1
  15276. else:
  15277. return (let clos_2 = (tail_sum,)
  15278. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  15279. def main() -> int :
  15280. print((let clos_4 = (tail_sum,)
  15281. in clos_4[0](clos_4, 3, 0)) + 36)
  15282. return 0
  15283. \end{lstlisting}
  15284. \fi}
  15285. \end{minipage}
  15286. \end{center}
  15287. In the previous chapter, there would be no allocation in the program
  15288. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  15289. the above program allocates memory for each closure and the calls to
  15290. \code{tail\_sum} are indirect. These two differences incur
  15291. considerable overhead in a program such as this one, where the
  15292. allocations and indirect calls occur inside a tight loop.
  15293. One might think that this problem is trivial to solve: can't we just
  15294. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  15295. and compile them to direct calls instead of treating it like a call to
  15296. a closure? We would also drop the new \code{fvs} parameter of
  15297. \code{tail\_sum}.
  15298. %
  15299. However, this problem is not so trivial because a global function may
  15300. ``escape'' and become involved in applications that also involve
  15301. closures. Consider the following example in which the application
  15302. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  15303. application, because the \code{lambda} may flow into \code{f}, but the
  15304. \code{inc} function might also flow into \code{f}.
  15305. \begin{center}
  15306. \begin{minipage}{\textwidth}
  15307. % lambda_test_30.rkt
  15308. {\if\edition\racketEd
  15309. \begin{lstlisting}
  15310. (define (inc [x : Integer]) : Integer
  15311. (+ x 1))
  15312. (let ([y (read)])
  15313. (let ([f (if (eq? (read) 0)
  15314. inc
  15315. (lambda: ([x : Integer]) : Integer (- x y)))])
  15316. (f 41)))
  15317. \end{lstlisting}
  15318. \fi}
  15319. {\if\edition\pythonEd
  15320. \begin{lstlisting}
  15321. def add1(x : int) -> int:
  15322. return x + 1
  15323. y = input_int()
  15324. g : Callable[[int], int] = lambda x: x - y
  15325. f = add1 if input_int() == 0 else g
  15326. print( f(41) )
  15327. \end{lstlisting}
  15328. \fi}
  15329. \end{minipage}
  15330. \end{center}
  15331. If a global function name is used in any way other than as the
  15332. operator in a direct call, then we say that the function
  15333. \emph{escapes}. If a global function does not escape, then we do not
  15334. need to perform closure conversion on the function.
  15335. \begin{exercise}\normalfont\normalsize
  15336. Implement an auxiliary function for detecting which global
  15337. functions escape. Using that function, implement an improved version
  15338. of closure conversion that does not apply closure conversion to
  15339. global functions that do not escape but instead compiles them as
  15340. regular functions. Create several new test cases that check whether
  15341. you properly detect whether global functions escape or not.
  15342. \end{exercise}
  15343. So far we have reduced the overhead of calling global functions, but
  15344. it would also be nice to reduce the overhead of calling a
  15345. \code{lambda} when we can determine at compile time which
  15346. \code{lambda} will be called. We refer to such calls as \emph{known
  15347. calls}. Consider the following example in which a \code{lambda} is
  15348. bound to \code{f} and then applied.
  15349. {\if\edition\racketEd
  15350. % lambda_test_9.rkt
  15351. \begin{lstlisting}
  15352. (let ([y (read)])
  15353. (let ([f (lambda: ([x : Integer]) : Integer
  15354. (+ x y))])
  15355. (f 21)))
  15356. \end{lstlisting}
  15357. \fi}
  15358. {\if\edition\pythonEd
  15359. \begin{lstlisting}
  15360. y = input_int()
  15361. f : Callable[[int],int] = lambda x: x + y
  15362. print( f(21) )
  15363. \end{lstlisting}
  15364. \fi}
  15365. %
  15366. \noindent Closure conversion compiles the application
  15367. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  15368. %
  15369. {\if\edition\racketEd
  15370. \begin{lstlisting}
  15371. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15372. (let ([y2 (vector-ref fvs6 1)])
  15373. (+ x3 y2)))
  15374. (define (main) : Integer
  15375. (let ([y2 (read)])
  15376. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15377. ((vector-ref f4 0) f4 21))))
  15378. \end{lstlisting}
  15379. \fi}
  15380. {\if\edition\pythonEd
  15381. \begin{lstlisting}
  15382. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15383. y_1 = fvs_4[1]
  15384. return x_2 + y_1[0]
  15385. def main() -> int:
  15386. y_1 = (777,)
  15387. y_1[0] = input_int()
  15388. f_0 = (lambda_3, y_1)
  15389. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15390. return 0
  15391. \end{lstlisting}
  15392. \fi}
  15393. %
  15394. \noindent but we can instead compile the application
  15395. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  15396. %
  15397. {\if\edition\racketEd
  15398. \begin{lstlisting}
  15399. (define (main) : Integer
  15400. (let ([y2 (read)])
  15401. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15402. ((fun-ref lambda5 1) f4 21))))
  15403. \end{lstlisting}
  15404. \fi}
  15405. {\if\edition\pythonEd
  15406. \begin{lstlisting}
  15407. def main() -> int:
  15408. y_1 = (777,)
  15409. y_1[0] = input_int()
  15410. f_0 = (lambda_3, y_1)
  15411. print(lambda_3(f_0, 21))
  15412. return 0
  15413. \end{lstlisting}
  15414. \fi}
  15415. The problem of determining which \code{lambda} will be called from a
  15416. particular application is quite challenging in general and the topic
  15417. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15418. following exercise we recommend that you compile an application to a
  15419. direct call when the operator is a variable and \racket{the variable
  15420. is \code{let}-bound to a closure}\python{the previous assignment to
  15421. the variable is a closure}. This can be accomplished by maintaining
  15422. an environment mapping variables to function names. Extend the
  15423. environment whenever you encounter a closure on the right-hand side of
  15424. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15425. name of the global function for the closure. This pass should come
  15426. after closure conversion.
  15427. \begin{exercise}\normalfont\normalsize
  15428. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15429. compiles known calls into direct calls. Verify that your compiler is
  15430. successful in this regard on several example programs.
  15431. \end{exercise}
  15432. These exercises only scratches the surface of optimizing of
  15433. closures. A good next step for the interested reader is to look at the
  15434. work of \citet{Keep:2012ab}.
  15435. \section{Further Reading}
  15436. The notion of lexically scoped functions predates modern computers by
  15437. about a decade. They were invented by \citet{Church:1932aa}, who
  15438. proposed the lambda calculus as a foundation for logic. Anonymous
  15439. functions were included in the LISP~\citep{McCarthy:1960dz}
  15440. programming language but were initially dynamically scoped. The Scheme
  15441. dialect of LISP adopted lexical scoping and
  15442. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15443. Scheme programs. However, environments were represented as linked
  15444. lists, so variable look-up was linear in the size of the
  15445. environment. \citet{Appel91} gives a detailed description of several
  15446. closure representations. In this chapter we represent environments
  15447. using flat closures, which were invented by
  15448. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15449. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15450. closures, variable look-up is constant time but the time to create a
  15451. closure is proportional to the number of its free variables. Flat
  15452. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  15453. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15454. % todo: related work on assignment conversion (e.g. orbit and rabbit
  15455. % compilers)
  15456. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15457. \chapter{Dynamic Typing}
  15458. \label{ch:Ldyn}
  15459. \index{subject}{dynamic typing}
  15460. In this chapter we learn how to compile \LangDyn{}, a dynamically
  15461. typed language that is a subset of \racket{Racket}\python{Python}. The
  15462. focus on dynamic typing is in contrast to the previous chapters, which
  15463. have studied the compilation of statically typed languages. In
  15464. dynamically typed languages such as \LangDyn{}, a particular
  15465. expression may produce a value of a different type each time it is
  15466. executed. Consider the following example with a conditional \code{if}
  15467. expression that may return a Boolean or an integer depending on the
  15468. input to the program.
  15469. % part of dynamic_test_25.rkt
  15470. {\if\edition\racketEd
  15471. \begin{lstlisting}
  15472. (not (if (eq? (read) 1) #f 0))
  15473. \end{lstlisting}
  15474. \fi}
  15475. {\if\edition\pythonEd
  15476. \begin{lstlisting}
  15477. not (False if input_int() == 1 else 0)
  15478. \end{lstlisting}
  15479. \fi}
  15480. Languages that allow expressions to produce different kinds of values
  15481. are called \emph{polymorphic}, a word composed of the Greek roots
  15482. ``poly'', meaning ``many'', and ``morph'', meaning ``form''. There
  15483. are several kinds of polymorphism in programming languages, such as
  15484. subtype polymorphism and parametric
  15485. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  15486. study in this chapter does not have a special name but it is the kind
  15487. that arises in dynamically typed languages.
  15488. Another characteristic of dynamically typed languages is that
  15489. primitive operations, such as \code{not}, are often defined to operate
  15490. on many different types of values. In fact, in
  15491. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15492. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15493. given anything else it returns \FALSE{}.
  15494. Furthermore, even when primitive operations restrict their inputs to
  15495. values of a certain type, this restriction is enforced at runtime
  15496. instead of during compilation. For example, the tuple read
  15497. operation
  15498. \racket{\code{(vector-ref \#t 0)}}
  15499. \python{\code{True[0]}}
  15500. results in a run-time error because the first argument must
  15501. be a tuple, not a Boolean.
  15502. \section{The \LangDyn{} Language}
  15503. \newcommand{\LdynGrammarRacket}{
  15504. \begin{array}{rcl}
  15505. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  15506. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15507. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15508. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15509. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  15510. \end{array}
  15511. }
  15512. \newcommand{\LdynASTRacket}{
  15513. \begin{array}{lcl}
  15514. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  15515. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15516. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  15517. \end{array}
  15518. }
  15519. \begin{figure}[tp]
  15520. \centering
  15521. \begin{tcolorbox}[colback=white]
  15522. \small
  15523. {\if\edition\racketEd
  15524. \[
  15525. \begin{array}{l}
  15526. \gray{\LintGrammarRacket{}} \\ \hline
  15527. \gray{\LvarGrammarRacket{}} \\ \hline
  15528. \gray{\LifGrammarRacket{}} \\ \hline
  15529. \gray{\LwhileGrammarRacket} \\ \hline
  15530. \gray{\LtupGrammarRacket} \\ \hline
  15531. \LdynGrammarRacket \\
  15532. \begin{array}{rcl}
  15533. \LangDynM{} &::=& \Def\ldots\; \Exp
  15534. \end{array}
  15535. \end{array}
  15536. \]
  15537. \fi}
  15538. {\if\edition\pythonEd
  15539. \[
  15540. \begin{array}{rcl}
  15541. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15542. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15543. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15544. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15545. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15546. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15547. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15548. \MID \CLEN{\Exp} \\
  15549. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15550. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15551. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15552. \MID \Var\mathop{\key{=}}\Exp \\
  15553. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15554. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15555. &\MID& \CRETURN{\Exp} \\
  15556. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15557. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15558. \end{array}
  15559. \]
  15560. \fi}
  15561. \end{tcolorbox}
  15562. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15563. \label{fig:r7-concrete-syntax}
  15564. \end{figure}
  15565. \begin{figure}[tp]
  15566. \centering
  15567. \begin{tcolorbox}[colback=white]
  15568. \small
  15569. {\if\edition\racketEd
  15570. \[
  15571. \begin{array}{l}
  15572. \gray{\LintASTRacket{}} \\ \hline
  15573. \gray{\LvarASTRacket{}} \\ \hline
  15574. \gray{\LifASTRacket{}} \\ \hline
  15575. \gray{\LwhileASTRacket} \\ \hline
  15576. \gray{\LtupASTRacket} \\ \hline
  15577. \LdynASTRacket \\
  15578. \begin{array}{lcl}
  15579. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15580. \end{array}
  15581. \end{array}
  15582. \]
  15583. \fi}
  15584. {\if\edition\pythonEd
  15585. \[
  15586. \begin{array}{rcl}
  15587. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15588. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15589. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15590. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15591. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15592. &\MID & \code{Is()} \\
  15593. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15594. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15595. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15596. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  15597. \MID \VAR{\Var{}} \\
  15598. &\MID& \BOOL{\itm{bool}}
  15599. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15600. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15601. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15602. &\MID& \LEN{\Exp} \\
  15603. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15604. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15605. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15606. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15607. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15608. &\MID& \RETURN{\Exp} \\
  15609. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15610. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  15611. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15612. \end{array}
  15613. \]
  15614. \fi}
  15615. \end{tcolorbox}
  15616. \caption{The abstract syntax of \LangDyn{}.}
  15617. \label{fig:r7-syntax}
  15618. \end{figure}
  15619. The concrete and abstract syntax of \LangDyn{} is defined in
  15620. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15621. %
  15622. There is no type checker for \LangDyn{} because it only checks types
  15623. at runtime.
  15624. The definitional interpreter for \LangDyn{} is presented in
  15625. \racket{Figure~\ref{fig:interp-Ldyn}}
  15626. \python{Figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}
  15627. and its auxiliary functions are defined in
  15628. Figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15629. \INT{n}. Instead of simply returning the integer \code{n} (as
  15630. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  15631. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15632. value} that combines an underlying value with a tag that identifies
  15633. what kind of value it is. We define the following \racket{struct}\python{class}
  15634. to represented tagged values.
  15635. %
  15636. {\if\edition\racketEd
  15637. \begin{lstlisting}
  15638. (struct Tagged (value tag) #:transparent)
  15639. \end{lstlisting}
  15640. \fi}
  15641. {\if\edition\pythonEd
  15642. \begin{minipage}{\textwidth}
  15643. \begin{lstlisting}
  15644. @dataclass(eq=True)
  15645. class Tagged(Value):
  15646. value : Value
  15647. tag : str
  15648. def __str__(self):
  15649. return str(self.value)
  15650. \end{lstlisting}
  15651. \end{minipage}
  15652. \fi}
  15653. %
  15654. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  15655. \code{Vector}, and \code{Procedure}.}
  15656. %
  15657. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15658. \code{'tuple'}, and \code{'function'}.}
  15659. %
  15660. Tags are closely related to types but don't always capture all the
  15661. information that a type does.
  15662. %
  15663. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15664. tagged with \code{Vector} and a procedure of type \code{(Any Any ->
  15665. Any)} is tagged with \code{Procedure}.}
  15666. %
  15667. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15668. is tagged with \code{'tuple'} and a function of type
  15669. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15670. is tagged with \code{'function'}.}
  15671. Next consider the match case for accessing the element of a tuple.
  15672. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15673. (Figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15674. argument is a tuple and the second is an integer.
  15675. \racket{
  15676. If they are not, a \code{trapped-error} is raised. Recall from
  15677. Section~\ref{sec:interp_Lint} that when a definition interpreter
  15678. raises a \code{trapped-error} error, the compiled code must also
  15679. signal an error by exiting with return code \code{255}. A
  15680. \code{trapped-error} is also raised if the index is not less than the
  15681. length of the vector.
  15682. }
  15683. %
  15684. \python{If they are not, an exception is raised. The compiled code
  15685. must also signal an error by exiting with return code \code{255}. A
  15686. exception is also raised if the index is not less than the length of the
  15687. tuple or if it is negative.}
  15688. \begin{figure}[tbp]
  15689. \begin{tcolorbox}[colback=white]
  15690. {\if\edition\racketEd
  15691. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15692. (define ((interp-Ldyn-exp env) ast)
  15693. (define recur (interp-Ldyn-exp env))
  15694. (match ast
  15695. [(Var x) (dict-ref env x)]
  15696. [(Int n) (Tagged n 'Integer)]
  15697. [(Bool b) (Tagged b 'Boolean)]
  15698. [(Lambda xs rt body)
  15699. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15700. [(Prim 'vector es)
  15701. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15702. [(Prim 'vector-ref (list e1 e2))
  15703. (define vec (recur e1)) (define i (recur e2))
  15704. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15705. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15706. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15707. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15708. [(Prim 'vector-set! (list e1 e2 e3))
  15709. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15710. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15711. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15712. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15713. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15714. (Tagged (void) 'Void)]
  15715. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  15716. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15717. [(Prim 'or (list e1 e2))
  15718. (define v1 (recur e1))
  15719. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15720. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15721. [(Prim op (list e1))
  15722. #:when (set-member? type-predicates op)
  15723. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15724. [(Prim op es)
  15725. (define args (map recur es))
  15726. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15727. (unless (for/or ([expected-tags (op-tags op)])
  15728. (equal? expected-tags tags))
  15729. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15730. (tag-value
  15731. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15732. [(If q t f)
  15733. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15734. [(Apply f es)
  15735. (define new-f (recur f)) (define args (map recur es))
  15736. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15737. (match f-val
  15738. [`(function ,xs ,body ,lam-env)
  15739. (unless (eq? (length xs) (length args))
  15740. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15741. (define new-env (append (map cons xs args) lam-env))
  15742. ((interp-Ldyn-exp new-env) body)]
  15743. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  15744. \end{lstlisting}
  15745. \fi}
  15746. {\if\edition\pythonEd
  15747. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15748. class InterpLdyn(InterpLlambda):
  15749. def interp_exp(self, e, env):
  15750. match e:
  15751. case Constant(n):
  15752. return self.tag(super().interp_exp(e, env))
  15753. case Tuple(es, Load()):
  15754. return self.tag(super().interp_exp(e, env))
  15755. case Lambda(params, body):
  15756. return self.tag(super().interp_exp(e, env))
  15757. case Call(Name('input_int'), []):
  15758. return self.tag(super().interp_exp(e, env))
  15759. case BinOp(left, Add(), right):
  15760. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15761. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  15762. case BinOp(left, Sub(), right):
  15763. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15764. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  15765. case UnaryOp(USub(), e1):
  15766. v = self.interp_exp(e1, env)
  15767. return self.tag(- self.untag(v, 'int', e))
  15768. case IfExp(test, body, orelse):
  15769. v = self.interp_exp(test, env)
  15770. if self.untag(v, 'bool', e):
  15771. return self.interp_exp(body, env)
  15772. else:
  15773. return self.interp_exp(orelse, env)
  15774. case UnaryOp(Not(), e1):
  15775. v = self.interp_exp(e1, env)
  15776. return self.tag(not self.untag(v, 'bool', e))
  15777. case BoolOp(And(), values):
  15778. left = values[0]; right = values[1]
  15779. l = self.interp_exp(left, env)
  15780. if self.untag(l, 'bool', e):
  15781. return self.interp_exp(right, env)
  15782. else:
  15783. return self.tag(False)
  15784. case BoolOp(Or(), values):
  15785. left = values[0]; right = values[1]
  15786. l = self.interp_exp(left, env)
  15787. if self.untag(l, 'bool', e):
  15788. return self.tag(True)
  15789. else:
  15790. return self.interp_exp(right, env)
  15791. case Compare(left, [cmp], [right]):
  15792. l = self.interp_exp(left, env)
  15793. r = self.interp_exp(right, env)
  15794. if l.tag == r.tag:
  15795. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  15796. else:
  15797. raise Exception('interp Compare unexpected '
  15798. + repr(l) + ' ' + repr(r))
  15799. case Subscript(tup, index, Load()):
  15800. t = self.interp_exp(tup, env)
  15801. n = self.interp_exp(index, env)
  15802. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  15803. case Call(Name('len'), [tup]):
  15804. t = self.interp_exp(tup, env)
  15805. return self.tag(len(self.untag(t, 'tuple', e)))
  15806. case _:
  15807. return self.tag(super().interp_exp(e, env))
  15808. \end{lstlisting}
  15809. \fi}
  15810. \end{tcolorbox}
  15811. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  15812. \label{fig:interp-Ldyn}
  15813. \end{figure}
  15814. {\if\edition\pythonEd
  15815. \begin{figure}[tbp]
  15816. \begin{tcolorbox}[colback=white]
  15817. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15818. class InterpLdyn(InterpLlambda):
  15819. def interp_stmts(self, ss, env):
  15820. if len(ss) == 0:
  15821. return
  15822. match ss[0]:
  15823. case If(test, body, orelse):
  15824. v = self.interp_exp(test, env)
  15825. if self.untag(v, 'bool', ss[0]):
  15826. return self.interp_stmts(body + ss[1:], env)
  15827. else:
  15828. return self.interp_stmts(orelse + ss[1:], env)
  15829. case While(test, body, []):
  15830. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  15831. self.interp_stmts(body, env)
  15832. return self.interp_stmts(ss[1:], env)
  15833. case Assign([Subscript(tup, index)], value):
  15834. tup = self.interp_exp(tup, env)
  15835. index = self.interp_exp(index, env)
  15836. tup_v = self.untag(tup, 'tuple', ss[0])
  15837. index_v = self.untag(index, 'int', ss[0])
  15838. tup_v[index_v] = self.interp_exp(value, env)
  15839. return self.interp_stmts(ss[1:], env)
  15840. case FunctionDef(name, params, bod, dl, returns, comment):
  15841. ps = [x for (x,t) in params]
  15842. env[name] = self.tag(Function(name, ps, bod, env))
  15843. return self.interp_stmts(ss[1:], env)
  15844. case _:
  15845. return super().interp_stmts(ss, env)
  15846. \end{lstlisting}
  15847. \end{tcolorbox}
  15848. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  15849. \label{fig:interp-Ldyn-2}
  15850. \end{figure}
  15851. \fi}
  15852. \begin{figure}[tbp]
  15853. \begin{tcolorbox}[colback=white]
  15854. {\if\edition\racketEd
  15855. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15856. (define (interp-op op)
  15857. (match op
  15858. ['+ fx+]
  15859. ['- fx-]
  15860. ['read read-fixnum]
  15861. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  15862. ['< (lambda (v1 v2)
  15863. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  15864. ['<= (lambda (v1 v2)
  15865. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  15866. ['> (lambda (v1 v2)
  15867. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  15868. ['>= (lambda (v1 v2)
  15869. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  15870. ['boolean? boolean?]
  15871. ['integer? fixnum?]
  15872. ['void? void?]
  15873. ['vector? vector?]
  15874. ['vector-length vector-length]
  15875. ['procedure? (match-lambda
  15876. [`(functions ,xs ,body ,env) #t] [else #f])]
  15877. [else (error 'interp-op "unknown operator" op)]))
  15878. (define (op-tags op)
  15879. (match op
  15880. ['+ '((Integer Integer))]
  15881. ['- '((Integer Integer) (Integer))]
  15882. ['read '(())]
  15883. ['not '((Boolean))]
  15884. ['< '((Integer Integer))]
  15885. ['<= '((Integer Integer))]
  15886. ['> '((Integer Integer))]
  15887. ['>= '((Integer Integer))]
  15888. ['vector-length '((Vector))]))
  15889. (define type-predicates
  15890. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15891. (define (tag-value v)
  15892. (cond [(boolean? v) (Tagged v 'Boolean)]
  15893. [(fixnum? v) (Tagged v 'Integer)]
  15894. [(procedure? v) (Tagged v 'Procedure)]
  15895. [(vector? v) (Tagged v 'Vector)]
  15896. [(void? v) (Tagged v 'Void)]
  15897. [else (error 'tag-value "unidentified value ~a" v)]))
  15898. (define (check-tag val expected ast)
  15899. (define tag (Tagged-tag val))
  15900. (unless (eq? tag expected)
  15901. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  15902. \end{lstlisting}
  15903. \fi}
  15904. {\if\edition\pythonEd
  15905. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15906. class InterpLdyn(InterpLlambda):
  15907. def tag(self, v):
  15908. if v is True or v is False:
  15909. return Tagged(v, 'bool')
  15910. elif isinstance(v, int):
  15911. return Tagged(v, 'int')
  15912. elif isinstance(v, Function):
  15913. return Tagged(v, 'function')
  15914. elif isinstance(v, tuple):
  15915. return Tagged(v, 'tuple')
  15916. elif isinstance(v, type(None)):
  15917. return Tagged(v, 'none')
  15918. else:
  15919. raise Exception('tag: unexpected ' + repr(v))
  15920. def untag(self, v, expected_tag, ast):
  15921. match v:
  15922. case Tagged(val, tag) if tag == expected_tag:
  15923. return val
  15924. case _:
  15925. raise Exception('expected Tagged value with '
  15926. + expected_tag + ', not ' + ' ' + repr(v))
  15927. def apply_fun(self, fun, args, e):
  15928. f = self.untag(fun, 'function', e)
  15929. return super().apply_fun(f, args, e)
  15930. \end{lstlisting}
  15931. \fi}
  15932. \end{tcolorbox}
  15933. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  15934. \label{fig:interp-Ldyn-aux}
  15935. \end{figure}
  15936. \clearpage
  15937. \section{Representation of Tagged Values}
  15938. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  15939. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  15940. values at the bit level. Because almost every operation in \LangDyn{}
  15941. involves manipulating tagged values, the representation must be
  15942. efficient. Recall that all of our values are 64 bits. We shall steal
  15943. the 3 right-most bits to encode the tag. We use $001$ to identify
  15944. integers, $100$ for Booleans, $010$ for tuples, $011$ for procedures,
  15945. and $101$ for the void value\python{, \key{None}}. We define the following auxiliary
  15946. function for mapping types to tag codes.
  15947. {\if\edition\racketEd
  15948. \begin{align*}
  15949. \itm{tagof}(\key{Integer}) &= 001 \\
  15950. \itm{tagof}(\key{Boolean}) &= 100 \\
  15951. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  15952. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  15953. \itm{tagof}(\key{Void}) &= 101
  15954. \end{align*}
  15955. \fi}
  15956. {\if\edition\pythonEd
  15957. \begin{align*}
  15958. \itm{tagof}(\key{IntType()}) &= 001 \\
  15959. \itm{tagof}(\key{BoolType()}) &= 100 \\
  15960. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  15961. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  15962. \itm{tagof}(\key{type(None)}) &= 101
  15963. \end{align*}
  15964. \fi}
  15965. This stealing of 3 bits comes at some price: integers are now restricted
  15966. to the range from $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  15967. affect tuples and procedures because those values are addresses, and
  15968. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  15969. they are always $000$. Thus, we do not lose information by overwriting
  15970. the rightmost 3 bits with the tag and we can simply zero-out the tag
  15971. to recover the original address.
  15972. To make tagged values into first-class entities, we can give them a
  15973. type, called \racket{\code{Any}}\python{\code{AnyType()}}, and define
  15974. operations such as \code{Inject} and \code{Project} for creating and
  15975. using them, yielding the statically typed \LangAny{} intermediate
  15976. language. We describe how to compile \LangDyn{} to \LangAny{} in
  15977. Section~\ref{sec:compile-r7} but first we describe the \LangAny{}
  15978. language in greater detail.
  15979. \section{The \LangAny{} Language}
  15980. \label{sec:Rany-lang}
  15981. \newcommand{\LanyASTRacket}{
  15982. \begin{array}{lcl}
  15983. \Type &::= & \ANYTY \\
  15984. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  15985. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  15986. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  15987. \itm{op} &::= & \code{any-vector-length}
  15988. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15989. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15990. \MID \code{procedure?} \MID \code{void?} \\
  15991. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  15992. \end{array}
  15993. }
  15994. \newcommand{\LanyASTPython}{
  15995. \begin{array}{lcl}
  15996. \Type &::= & \key{AnyType()} \\
  15997. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  15998. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  15999. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  16000. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  16001. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  16002. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  16003. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  16004. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  16005. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  16006. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  16007. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  16008. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  16009. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  16010. \end{array}
  16011. }
  16012. \begin{figure}[tp]
  16013. \centering
  16014. \begin{tcolorbox}[colback=white]
  16015. \small
  16016. {\if\edition\racketEd
  16017. \[
  16018. \begin{array}{l}
  16019. \gray{\LintOpAST} \\ \hline
  16020. \gray{\LvarASTRacket{}} \\ \hline
  16021. \gray{\LifASTRacket{}} \\ \hline
  16022. \gray{\LwhileASTRacket{}} \\ \hline
  16023. \gray{\LtupASTRacket{}} \\ \hline
  16024. \gray{\LfunASTRacket} \\ \hline
  16025. \gray{\LlambdaASTRacket} \\ \hline
  16026. \LanyASTRacket \\
  16027. \begin{array}{lcl}
  16028. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16029. \end{array}
  16030. \end{array}
  16031. \]
  16032. \fi}
  16033. {\if\edition\pythonEd
  16034. \[
  16035. \begin{array}{l}
  16036. \gray{\LintASTPython} \\ \hline
  16037. \gray{\LvarASTPython{}} \\ \hline
  16038. \gray{\LifASTPython{}} \\ \hline
  16039. \gray{\LwhileASTPython{}} \\ \hline
  16040. \gray{\LtupASTPython{}} \\ \hline
  16041. \gray{\LfunASTPython} \\ \hline
  16042. \gray{\LlambdaASTPython} \\ \hline
  16043. \LanyASTPython \\
  16044. \begin{array}{lcl}
  16045. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16046. \end{array}
  16047. \end{array}
  16048. \]
  16049. \fi}
  16050. \end{tcolorbox}
  16051. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Llam-syntax}).}
  16052. \label{fig:Lany-syntax}
  16053. \end{figure}
  16054. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Lany-syntax}.
  16055. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  16056. %% Figure~\ref{fig:Lany-concrete-syntax}.)}
  16057. The $\INJECT{e}{T}$ form
  16058. converts the value produced by expression $e$ of type $T$ into a
  16059. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  16060. produced by expression $e$ into a value of type $T$ or halts the
  16061. program if the type tag does not match $T$.
  16062. %
  16063. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  16064. restricted to a flat type $\FType$, which simplifies the
  16065. implementation and corresponds with the needs for compiling \LangDyn{}.
  16066. The \racket{\code{any-vector}} operators
  16067. \python{\code{any\_tuple\_load} and \code{any\_len}}
  16068. adapt the tuple operations so that they can be applied to a value of
  16069. type \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  16070. tuple operations in that the index is not restricted to be a literal
  16071. integer in the grammar but is allowed to be any expression.
  16072. \racket{The type predicates such as
  16073. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  16074. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  16075. the predicate and they return {\FALSE} otherwise.}
  16076. The type checker for \LangAny{} is shown in
  16077. Figure~\ref{fig:type-check-Lany}
  16078. %
  16079. \racket{ and uses the auxiliary functions in
  16080. Figure~\ref{fig:type-check-Lany-aux}}.
  16081. %
  16082. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Lany} and
  16083. its auxiliary functions are in Figure~\ref{fig:interp-Lany-aux}.
  16084. \begin{figure}[btp]
  16085. \begin{tcolorbox}[colback=white]
  16086. {\if\edition\racketEd
  16087. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16088. (define type-check-Lany-class
  16089. (class type-check-Llambda-class
  16090. (super-new)
  16091. (inherit check-type-equal?)
  16092. (define/override (type-check-exp env)
  16093. (lambda (e)
  16094. (define recur (type-check-exp env))
  16095. (match e
  16096. [(Inject e1 ty)
  16097. (unless (flat-ty? ty)
  16098. (error 'type-check "may only inject from flat type, not ~a" ty))
  16099. (define-values (new-e1 e-ty) (recur e1))
  16100. (check-type-equal? e-ty ty e)
  16101. (values (Inject new-e1 ty) 'Any)]
  16102. [(Project e1 ty)
  16103. (unless (flat-ty? ty)
  16104. (error 'type-check "may only project to flat type, not ~a" ty))
  16105. (define-values (new-e1 e-ty) (recur e1))
  16106. (check-type-equal? e-ty 'Any e)
  16107. (values (Project new-e1 ty) ty)]
  16108. [(Prim 'any-vector-length (list e1))
  16109. (define-values (e1^ t1) (recur e1))
  16110. (check-type-equal? t1 'Any e)
  16111. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  16112. [(Prim 'any-vector-ref (list e1 e2))
  16113. (define-values (e1^ t1) (recur e1))
  16114. (define-values (e2^ t2) (recur e2))
  16115. (check-type-equal? t1 'Any e)
  16116. (check-type-equal? t2 'Integer e)
  16117. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  16118. [(Prim 'any-vector-set! (list e1 e2 e3))
  16119. (define-values (e1^ t1) (recur e1))
  16120. (define-values (e2^ t2) (recur e2))
  16121. (define-values (e3^ t3) (recur e3))
  16122. (check-type-equal? t1 'Any e)
  16123. (check-type-equal? t2 'Integer e)
  16124. (check-type-equal? t3 'Any e)
  16125. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  16126. [(Prim pred (list e1))
  16127. #:when (set-member? (type-predicates) pred)
  16128. (define-values (new-e1 e-ty) (recur e1))
  16129. (check-type-equal? e-ty 'Any e)
  16130. (values (Prim pred (list new-e1)) 'Boolean)]
  16131. [(Prim 'eq? (list arg1 arg2))
  16132. (define-values (e1 t1) (recur arg1))
  16133. (define-values (e2 t2) (recur arg2))
  16134. (match* (t1 t2)
  16135. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  16136. [(other wise) (check-type-equal? t1 t2 e)])
  16137. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  16138. [else ((super type-check-exp env) e)])))
  16139. ))
  16140. \end{lstlisting}
  16141. \fi}
  16142. {\if\edition\pythonEd
  16143. \begin{lstlisting}
  16144. class TypeCheckLany(TypeCheckLlambda):
  16145. def type_check_exp(self, e, env):
  16146. match e:
  16147. case Inject(value, typ):
  16148. self.check_exp(value, typ, env)
  16149. return AnyType()
  16150. case Project(value, typ):
  16151. self.check_exp(value, AnyType(), env)
  16152. return typ
  16153. case Call(Name('any_tuple_load'), [tup, index]):
  16154. self.check_exp(tup, AnyType(), env)
  16155. self.check_exp(index, IntType(), env)
  16156. return AnyType()
  16157. case Call(Name('any_len'), [tup]):
  16158. self.check_exp(tup, AnyType(), env)
  16159. return IntType()
  16160. case Call(Name('arity'), [fun]):
  16161. ty = self.type_check_exp(fun, env)
  16162. match ty:
  16163. case FunctionType(ps, rt):
  16164. return IntType()
  16165. case TupleType([FunctionType(ps,rs)]):
  16166. return IntType()
  16167. case _:
  16168. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  16169. case Call(Name('make_any'), [value, tag]):
  16170. self.type_check_exp(value, env)
  16171. self.check_exp(tag, IntType(), env)
  16172. return AnyType()
  16173. case AnnLambda(params, returns, body):
  16174. new_env = {x:t for (x,t) in env.items()}
  16175. for (x,t) in params:
  16176. new_env[x] = t
  16177. return_t = self.type_check_exp(body, new_env)
  16178. self.check_type_equal(returns, return_t, e)
  16179. return FunctionType([t for (x,t) in params], return_t)
  16180. case _:
  16181. return super().type_check_exp(e, env)
  16182. \end{lstlisting}
  16183. \fi}
  16184. \end{tcolorbox}
  16185. \caption{Type checker for the \LangAny{} language.}
  16186. \label{fig:type-check-Lany}
  16187. \end{figure}
  16188. {\if\edition\racketEd
  16189. \begin{figure}[tbp]
  16190. \begin{tcolorbox}[colback=white]
  16191. \begin{lstlisting}
  16192. (define/override (operator-types)
  16193. (append
  16194. '((integer? . ((Any) . Boolean))
  16195. (vector? . ((Any) . Boolean))
  16196. (procedure? . ((Any) . Boolean))
  16197. (void? . ((Any) . Boolean)))
  16198. (super operator-types)))
  16199. (define/public (type-predicates)
  16200. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16201. (define/public (flat-ty? ty)
  16202. (match ty
  16203. [(or `Integer `Boolean `Void) #t]
  16204. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  16205. ['(Vectorof Any) #t]
  16206. [`(,ts ... -> ,rt)
  16207. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  16208. [else #f]))
  16209. \end{lstlisting}
  16210. \end{tcolorbox}
  16211. \caption{Auxiliary methods for type checking \LangAny{}.}
  16212. \label{fig:type-check-Lany-aux}
  16213. \end{figure}
  16214. \fi}
  16215. \begin{figure}[btp]
  16216. \begin{tcolorbox}[colback=white]
  16217. {\if\edition\racketEd
  16218. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16219. (define interp-Lany-class
  16220. (class interp-Llambda-class
  16221. (super-new)
  16222. (define/override (interp-op op)
  16223. (match op
  16224. ['boolean? (match-lambda
  16225. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  16226. [else #f])]
  16227. ['integer? (match-lambda
  16228. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  16229. [else #f])]
  16230. ['vector? (match-lambda
  16231. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  16232. [else #f])]
  16233. ['procedure? (match-lambda
  16234. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  16235. [else #f])]
  16236. ['eq? (match-lambda*
  16237. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  16238. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  16239. [ls (apply (super interp-op op) ls)])]
  16240. ['any-vector-ref (lambda (v i)
  16241. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  16242. ['any-vector-set! (lambda (v i a)
  16243. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  16244. ['any-vector-length (lambda (v)
  16245. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  16246. [else (super interp-op op)]))
  16247. (define/override ((interp-exp env) e)
  16248. (define recur (interp-exp env))
  16249. (match e
  16250. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  16251. [(Project e ty2) (apply-project (recur e) ty2)]
  16252. [else ((super interp-exp env) e)]))
  16253. ))
  16254. (define (interp-Lany p)
  16255. (send (new interp-Lany-class) interp-program p))
  16256. \end{lstlisting}
  16257. \fi}
  16258. {\if\edition\pythonEd
  16259. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16260. class InterpLany(InterpLlambda):
  16261. def interp_exp(self, e, env):
  16262. match e:
  16263. case Inject(value, typ):
  16264. v = self.interp_exp(value, env)
  16265. return Tagged(v, self.type_to_tag(typ))
  16266. case Project(value, typ):
  16267. v = self.interp_exp(value, env)
  16268. match v:
  16269. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  16270. return val
  16271. case _:
  16272. raise Exception('interp project to ' + repr(typ)
  16273. + ' unexpected ' + repr(v))
  16274. case Call(Name('any_tuple_load'), [tup, index]):
  16275. tv = self.interp_exp(tup, env)
  16276. n = self.interp_exp(index, env)
  16277. match tv:
  16278. case Tagged(v, tag):
  16279. return v[n]
  16280. case _:
  16281. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  16282. case Call(Name('any_len'), [value]):
  16283. v = self.interp_exp(value, env)
  16284. match v:
  16285. case Tagged(value, tag):
  16286. return len(value)
  16287. case _:
  16288. raise Exception('interp any_len unexpected ' + repr(v))
  16289. case Call(Name('arity'), [fun]):
  16290. f = self.interp_exp(fun, env)
  16291. return self.arity(f)
  16292. case _:
  16293. return super().interp_exp(e, env)
  16294. \end{lstlisting}
  16295. \fi}
  16296. \end{tcolorbox}
  16297. \caption{Interpreter for \LangAny{}.}
  16298. \label{fig:interp-Lany}
  16299. \end{figure}
  16300. \begin{figure}[tbp]
  16301. \begin{tcolorbox}[colback=white]
  16302. {\if\edition\racketEd
  16303. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16304. (define/public (apply-inject v tg) (Tagged v tg))
  16305. (define/public (apply-project v ty2)
  16306. (define tag2 (any-tag ty2))
  16307. (match v
  16308. [(Tagged v1 tag1)
  16309. (cond
  16310. [(eq? tag1 tag2)
  16311. (match ty2
  16312. [`(Vector ,ts ...)
  16313. (define l1 ((interp-op 'vector-length) v1))
  16314. (cond
  16315. [(eq? l1 (length ts)) v1]
  16316. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  16317. l1 (length ts))])]
  16318. [`(,ts ... -> ,rt)
  16319. (match v1
  16320. [`(function ,xs ,body ,env)
  16321. (cond [(eq? (length xs) (length ts)) v1]
  16322. [else
  16323. (error 'apply-project "arity mismatch ~a != ~a"
  16324. (length xs) (length ts))])]
  16325. [else (error 'apply-project "expected function not ~a" v1)])]
  16326. [else v1])]
  16327. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16328. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16329. \end{lstlisting}
  16330. \fi}
  16331. {\if\edition\pythonEd
  16332. \begin{lstlisting}
  16333. class InterpLany(InterpLlambda):
  16334. def type_to_tag(self, typ):
  16335. match typ:
  16336. case FunctionType(params, rt):
  16337. return 'function'
  16338. case TupleType(fields):
  16339. return 'tuple'
  16340. case t if t == int:
  16341. return 'int'
  16342. case t if t == bool:
  16343. return 'bool'
  16344. case IntType():
  16345. return 'int'
  16346. case BoolType():
  16347. return 'int'
  16348. case _:
  16349. raise Exception('type_to_tag unexpected ' + repr(typ))
  16350. def arity(self, v):
  16351. match v:
  16352. case Function(name, params, body, env):
  16353. return len(params)
  16354. case ClosureTuple(args, arity):
  16355. return arity
  16356. case _:
  16357. raise Exception('Lany arity unexpected ' + repr(v))
  16358. \end{lstlisting}
  16359. \fi}
  16360. \end{tcolorbox}
  16361. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16362. \label{fig:interp-Lany-aux}
  16363. \end{figure}
  16364. \clearpage
  16365. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16366. \label{sec:compile-r7}
  16367. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16368. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  16369. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  16370. is that given any subexpression $e$ in the \LangDyn{} program, the
  16371. pass will produce an expression $e'$ in \LangAny{} that has type
  16372. \ANYTY{}. For example, the first row in
  16373. Figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  16374. \TRUE{}, which must be injected to produce an expression of type
  16375. \ANYTY{}.
  16376. %
  16377. The second row of Figure~\ref{fig:compile-r7-Lany}, the compilation of
  16378. addition, is representative of compilation for many primitive
  16379. operations: the arguments have type \ANYTY{} and must be projected to
  16380. \INTTYPE{} before the addition can be performed.
  16381. The compilation of \key{lambda} (third row of
  16382. Figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  16383. produce type annotations: we simply use \ANYTY{}.
  16384. %
  16385. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16386. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16387. this pass has to account for some differences in behavior between
  16388. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16389. permissive than \LangAny{} regarding what kind of values can be used
  16390. in various places. For example, the condition of an \key{if} does
  16391. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16392. of the same type (in that case the result is \code{\#f}).}
  16393. \begin{figure}[btp]
  16394. \centering
  16395. \begin{tcolorbox}[colback=white]
  16396. {\if\edition\racketEd
  16397. \begin{tabular}{lll}
  16398. \begin{minipage}{0.27\textwidth}
  16399. \begin{lstlisting}
  16400. #t
  16401. \end{lstlisting}
  16402. \end{minipage}
  16403. &
  16404. $\Rightarrow$
  16405. &
  16406. \begin{minipage}{0.65\textwidth}
  16407. \begin{lstlisting}
  16408. (inject #t Boolean)
  16409. \end{lstlisting}
  16410. \end{minipage}
  16411. \\[2ex]\hline
  16412. \begin{minipage}{0.27\textwidth}
  16413. \begin{lstlisting}
  16414. (+ |$e_1$| |$e_2$|)
  16415. \end{lstlisting}
  16416. \end{minipage}
  16417. &
  16418. $\Rightarrow$
  16419. &
  16420. \begin{minipage}{0.65\textwidth}
  16421. \begin{lstlisting}
  16422. (inject
  16423. (+ (project |$e'_1$| Integer)
  16424. (project |$e'_2$| Integer))
  16425. Integer)
  16426. \end{lstlisting}
  16427. \end{minipage}
  16428. \\[2ex]\hline
  16429. \begin{minipage}{0.27\textwidth}
  16430. \begin{lstlisting}
  16431. (lambda (|$x_1 \ldots$|) |$e$|)
  16432. \end{lstlisting}
  16433. \end{minipage}
  16434. &
  16435. $\Rightarrow$
  16436. &
  16437. \begin{minipage}{0.65\textwidth}
  16438. \begin{lstlisting}
  16439. (inject
  16440. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  16441. (Any|$\ldots$|Any -> Any))
  16442. \end{lstlisting}
  16443. \end{minipage}
  16444. \\[2ex]\hline
  16445. \begin{minipage}{0.27\textwidth}
  16446. \begin{lstlisting}
  16447. (|$e_0$| |$e_1 \ldots e_n$|)
  16448. \end{lstlisting}
  16449. \end{minipage}
  16450. &
  16451. $\Rightarrow$
  16452. &
  16453. \begin{minipage}{0.65\textwidth}
  16454. \begin{lstlisting}
  16455. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16456. \end{lstlisting}
  16457. \end{minipage}
  16458. \\[2ex]\hline
  16459. \begin{minipage}{0.27\textwidth}
  16460. \begin{lstlisting}
  16461. (vector-ref |$e_1$| |$e_2$|)
  16462. \end{lstlisting}
  16463. \end{minipage}
  16464. &
  16465. $\Rightarrow$
  16466. &
  16467. \begin{minipage}{0.65\textwidth}
  16468. \begin{lstlisting}
  16469. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  16470. \end{lstlisting}
  16471. \end{minipage}
  16472. \\[2ex]\hline
  16473. \begin{minipage}{0.27\textwidth}
  16474. \begin{lstlisting}
  16475. (if |$e_1$| |$e_2$| |$e_3$|)
  16476. \end{lstlisting}
  16477. \end{minipage}
  16478. &
  16479. $\Rightarrow$
  16480. &
  16481. \begin{minipage}{0.65\textwidth}
  16482. \begin{lstlisting}
  16483. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16484. \end{lstlisting}
  16485. \end{minipage}
  16486. \\[2ex]\hline
  16487. \begin{minipage}{0.27\textwidth}
  16488. \begin{lstlisting}
  16489. (eq? |$e_1$| |$e_2$|)
  16490. \end{lstlisting}
  16491. \end{minipage}
  16492. &
  16493. $\Rightarrow$
  16494. &
  16495. \begin{minipage}{0.65\textwidth}
  16496. \begin{lstlisting}
  16497. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16498. \end{lstlisting}
  16499. \end{minipage}
  16500. \\[2ex]\hline
  16501. \begin{minipage}{0.27\textwidth}
  16502. \begin{lstlisting}
  16503. (not |$e_1$|)
  16504. \end{lstlisting}
  16505. \end{minipage}
  16506. &
  16507. $\Rightarrow$
  16508. &
  16509. \begin{minipage}{0.65\textwidth}
  16510. \begin{lstlisting}
  16511. (if (eq? |$e'_1$| (inject #f Boolean))
  16512. (inject #t Boolean) (inject #f Boolean))
  16513. \end{lstlisting}
  16514. \end{minipage}
  16515. \end{tabular}
  16516. \fi}
  16517. {\if\edition\pythonEd
  16518. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  16519. \begin{minipage}{0.23\textwidth}
  16520. \begin{lstlisting}
  16521. True
  16522. \end{lstlisting}
  16523. \end{minipage}
  16524. &
  16525. $\Rightarrow$
  16526. &
  16527. \begin{minipage}{0.7\textwidth}
  16528. \begin{lstlisting}
  16529. Inject(True, BoolType())
  16530. \end{lstlisting}
  16531. \end{minipage}
  16532. \\[2ex]\hline
  16533. \begin{minipage}{0.23\textwidth}
  16534. \begin{lstlisting}
  16535. |$e_1$| + |$e_2$|
  16536. \end{lstlisting}
  16537. \end{minipage}
  16538. &
  16539. $\Rightarrow$
  16540. &
  16541. \begin{minipage}{0.7\textwidth}
  16542. \begin{lstlisting}
  16543. Inject(Project(|$e'_1$|, IntType())
  16544. + Project(|$e'_2$|, IntType()),
  16545. IntType())
  16546. \end{lstlisting}
  16547. \end{minipage}
  16548. \\[2ex]\hline
  16549. \begin{minipage}{0.23\textwidth}
  16550. \begin{lstlisting}
  16551. lambda |$x_1 \ldots$|: |$e$|
  16552. \end{lstlisting}
  16553. \end{minipage}
  16554. &
  16555. $\Rightarrow$
  16556. &
  16557. \begin{minipage}{0.7\textwidth}
  16558. \begin{lstlisting}
  16559. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  16560. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16561. \end{lstlisting}
  16562. \end{minipage}
  16563. \\[2ex]\hline
  16564. \begin{minipage}{0.23\textwidth}
  16565. \begin{lstlisting}
  16566. |$e_0$|(|$e_1 \ldots e_n$|)
  16567. \end{lstlisting}
  16568. \end{minipage}
  16569. &
  16570. $\Rightarrow$
  16571. &
  16572. \begin{minipage}{0.7\textwidth}
  16573. \begin{lstlisting}
  16574. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16575. AnyType())), |$e'_1, \ldots, e'_n$|)
  16576. \end{lstlisting}
  16577. \end{minipage}
  16578. \\[2ex]\hline
  16579. \begin{minipage}{0.23\textwidth}
  16580. \begin{lstlisting}
  16581. |$e_1$|[|$e_2$|]
  16582. \end{lstlisting}
  16583. \end{minipage}
  16584. &
  16585. $\Rightarrow$
  16586. &
  16587. \begin{minipage}{0.7\textwidth}
  16588. \begin{lstlisting}
  16589. Call(Name('any_tuple_load'),
  16590. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  16591. \end{lstlisting}
  16592. \end{minipage}
  16593. %% \begin{minipage}{0.23\textwidth}
  16594. %% \begin{lstlisting}
  16595. %% |$e_2$| if |$e_1$| else |$e_3$|
  16596. %% \end{lstlisting}
  16597. %% \end{minipage}
  16598. %% &
  16599. %% $\Rightarrow$
  16600. %% &
  16601. %% \begin{minipage}{0.7\textwidth}
  16602. %% \begin{lstlisting}
  16603. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16604. %% \end{lstlisting}
  16605. %% \end{minipage}
  16606. %% \\[2ex]\hline
  16607. %% \begin{minipage}{0.23\textwidth}
  16608. %% \begin{lstlisting}
  16609. %% (eq? |$e_1$| |$e_2$|)
  16610. %% \end{lstlisting}
  16611. %% \end{minipage}
  16612. %% &
  16613. %% $\Rightarrow$
  16614. %% &
  16615. %% \begin{minipage}{0.7\textwidth}
  16616. %% \begin{lstlisting}
  16617. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16618. %% \end{lstlisting}
  16619. %% \end{minipage}
  16620. %% \\[2ex]\hline
  16621. %% \begin{minipage}{0.23\textwidth}
  16622. %% \begin{lstlisting}
  16623. %% (not |$e_1$|)
  16624. %% \end{lstlisting}
  16625. %% \end{minipage}
  16626. %% &
  16627. %% $\Rightarrow$
  16628. %% &
  16629. %% \begin{minipage}{0.7\textwidth}
  16630. %% \begin{lstlisting}
  16631. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16632. %% (inject #t Boolean) (inject #f Boolean))
  16633. %% \end{lstlisting}
  16634. %% \end{minipage}
  16635. %% \\[2ex]\hline
  16636. \\\hline
  16637. \end{tabular}
  16638. \fi}
  16639. \end{tcolorbox}
  16640. \caption{Cast Insertion}
  16641. \label{fig:compile-r7-Lany}
  16642. \end{figure}
  16643. \section{Reveal Casts}
  16644. \label{sec:reveal-casts-Lany}
  16645. % TODO: define R'_6
  16646. In the \code{reveal\_casts} pass we recommend compiling \code{Project}
  16647. into a conditional expression that checks whether the value's tag
  16648. matches the target type; if it does, the value is converted to a value
  16649. of the target type by removing the tag; if it does not, the program
  16650. exits.
  16651. %
  16652. {\if\edition\racketEd
  16653. %
  16654. To perform these actions we need a new primitive operation,
  16655. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16656. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16657. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16658. underlying value from a tagged value. The \code{ValueOf} form
  16659. includes the type for the underlying value which is used by the type
  16660. checker. Finally, the \code{Exit} form ends the execution of the
  16661. program.
  16662. %
  16663. \fi}
  16664. %
  16665. {\if\edition\pythonEd
  16666. %
  16667. To perform these actions we need the \code{exit} function (from the C
  16668. standard library) and two new AST classes: \code{TagOf} and
  16669. \code{ValueOf}. The \code{exit} function ends the execution of the
  16670. program. The \code{TagOf} operation retrieves the type tag from a
  16671. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16672. the underlying value from a tagged value. The \code{ValueOf}
  16673. operation includes the type for the underlying value which is used by
  16674. the type checker.
  16675. %
  16676. \fi}
  16677. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16678. \code{Project} can be translated as follows.
  16679. \begin{center}
  16680. \begin{minipage}{1.0\textwidth}
  16681. {\if\edition\racketEd
  16682. \begin{lstlisting}
  16683. (Project |$e$| |$\FType$|)
  16684. |$\Rightarrow$|
  16685. (Let |$\itm{tmp}$| |$e'$|
  16686. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16687. (Int |$\itm{tagof}(\FType)$|)))
  16688. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16689. (Exit)))
  16690. \end{lstlisting}
  16691. \fi}
  16692. {\if\edition\pythonEd
  16693. \begin{lstlisting}
  16694. Project(|$e$|, |$\FType$|)
  16695. |$\Rightarrow$|
  16696. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16697. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16698. [Constant(|$\itm{tagof}(\FType)$|)]),
  16699. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16700. Call(Name('exit'), [])))
  16701. \end{lstlisting}
  16702. \fi}
  16703. \end{minipage}
  16704. \end{center}
  16705. If the target type of the projection is a tuple or function type, then
  16706. there is a bit more work to do. For tuples, check that the length of
  16707. the tuple type matches the length of the tuple. For functions, check
  16708. that the number of parameters in the function type matches the
  16709. function's arity.
  16710. Regarding \code{Inject}, we recommend compiling it to a slightly
  16711. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  16712. takes a tag instead of a type.
  16713. \begin{center}
  16714. \begin{minipage}{1.0\textwidth}
  16715. {\if\edition\racketEd
  16716. \begin{lstlisting}
  16717. (Inject |$e$| |$\FType$|)
  16718. |$\Rightarrow$|
  16719. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16720. \end{lstlisting}
  16721. \fi}
  16722. {\if\edition\pythonEd
  16723. \begin{lstlisting}
  16724. Inject(|$e$|, |$\FType$|)
  16725. |$\Rightarrow$|
  16726. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16727. \end{lstlisting}
  16728. \fi}
  16729. \end{minipage}
  16730. \end{center}
  16731. {\if\edition\pythonEd
  16732. %
  16733. The introduction of \code{make\_any} makes it difficult to use
  16734. bidirectional type checking because we no longer have an expected type
  16735. to use for type checking the expression $e'$. Thus, we run into
  16736. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16737. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16738. annotated lambda) whose parameters have type annotations and that
  16739. records the return type.
  16740. %
  16741. \fi}
  16742. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16743. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16744. translation of \code{Project}.}
  16745. {\if\edition\racketEd
  16746. The \code{any-vector-ref} and \code{any-vector-set!} operations
  16747. combine the projection action with the vector operation. Also, the
  16748. read and write operations allow arbitrary expressions for the index so
  16749. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Lany})
  16750. cannot guarantee that the index is within bounds. Thus, we insert code
  16751. to perform bounds checking at runtime. The translation for
  16752. \code{any-vector-ref} is as follows and the other two operations are
  16753. translated in a similar way.
  16754. \begin{center}
  16755. \begin{minipage}{0.95\textwidth}
  16756. \begin{lstlisting}
  16757. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  16758. |$\Rightarrow$|
  16759. (Let |$v$| |$e'_1$|
  16760. (Let |$i$| |$e'_2$|
  16761. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  16762. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  16763. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  16764. (Exit))
  16765. (Exit))))
  16766. \end{lstlisting}
  16767. \end{minipage}
  16768. \end{center}
  16769. \fi}
  16770. %
  16771. {\if\edition\pythonEd
  16772. %
  16773. The \code{any\_tuple\_load} operation combines the projection action
  16774. with the load operation. Also, the load operation allows arbitrary
  16775. expressions for the index so the type checker for \LangAny{}
  16776. (Figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  16777. within bounds. Thus, we insert code to perform bounds checking at
  16778. runtime. The translation for \code{any\_tuple\_load} is as follows.
  16779. \begin{lstlisting}
  16780. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  16781. |$\Rightarrow$|
  16782. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  16783. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  16784. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  16785. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  16786. Call(Name('exit'), [])),
  16787. Call(Name('exit'), [])))
  16788. \end{lstlisting}
  16789. \fi}
  16790. {\if\edition\pythonEd
  16791. \section{Assignment Conversion}
  16792. \label{sec:convert-assignments-Lany}
  16793. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16794. \code{AnnLambda} AST classes.
  16795. \section{Closure Conversion}
  16796. \label{sec:closure-conversion-Lany}
  16797. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16798. \code{AnnLambda} AST classes.
  16799. \fi}
  16800. \section{Remove Complex Operands}
  16801. \label{sec:rco-Lany}
  16802. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  16803. expressions. The subexpression of \code{ValueOf} must be atomic.}
  16804. %
  16805. \python{The \code{ValueOf} and \code{TagOf} operations are both
  16806. complex expressions. Their subexpressions must be atomic.}
  16807. \section{Explicate Control and \LangCAny{}}
  16808. \label{sec:explicate-Lany}
  16809. The output of \code{explicate\_control} is the \LangCAny{} language
  16810. whose syntax is defined in Figure~\ref{fig:c5-syntax}.
  16811. %
  16812. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  16813. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  16814. note that the index argument of \code{vector-ref} and
  16815. \code{vector-set!} is an $\Atm$ instead of an integer, as it was in
  16816. \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  16817. %
  16818. \python{
  16819. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  16820. and \code{explicate\_pred} as appropriately to handle the new expressions
  16821. in \LangCAny{}.
  16822. }
  16823. \newcommand{\CanyASTPython}{
  16824. \begin{array}{lcl}
  16825. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  16826. &\MID& \key{TagOf}\LP \Atm \RP
  16827. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  16828. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  16829. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  16830. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  16831. \end{array}
  16832. }
  16833. \newcommand{\CanyASTRacket}{
  16834. \begin{array}{lcl}
  16835. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  16836. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  16837. &\MID& \VALUEOF{\Atm}{\FType} \\
  16838. \Tail &::= & \LP\key{Exit}\RP
  16839. \end{array}
  16840. }
  16841. \begin{figure}[tp]
  16842. \begin{tcolorbox}[colback=white]
  16843. \small
  16844. {\if\edition\racketEd
  16845. \[
  16846. \begin{array}{l}
  16847. \gray{\CvarASTRacket} \\ \hline
  16848. \gray{\CifASTRacket} \\ \hline
  16849. \gray{\CloopASTRacket} \\ \hline
  16850. \gray{\CtupASTRacket} \\ \hline
  16851. \gray{\CfunASTRacket} \\ \hline
  16852. \gray{\ClambdaASTRacket} \\ \hline
  16853. \CanyASTRacket \\
  16854. \begin{array}{lcl}
  16855. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  16856. \end{array}
  16857. \end{array}
  16858. \]
  16859. \fi}
  16860. {\if\edition\pythonEd
  16861. \[
  16862. \begin{array}{l}
  16863. \gray{\CifASTPython} \\ \hline
  16864. \gray{\CtupASTPython} \\ \hline
  16865. \gray{\CfunASTPython} \\ \hline
  16866. \gray{\ClambdaASTPython} \\ \hline
  16867. \CanyASTPython \\
  16868. \begin{array}{lcl}
  16869. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16870. \end{array}
  16871. \end{array}
  16872. \]
  16873. \fi}
  16874. \end{tcolorbox}
  16875. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:Clam-syntax}).}
  16876. \label{fig:c5-syntax}
  16877. \end{figure}
  16878. \section{Select Instructions}
  16879. \label{sec:select-Lany}
  16880. In the \code{select\_instructions} pass we translate the primitive
  16881. operations on the \ANYTY{} type to x86 instructions that manipulate
  16882. the 3 tag bits of the tagged value. In the following descriptions,
  16883. given an atom $e$ we use a primed variable $e'$ to refer to the result
  16884. of translating $e$ into an x86 argument.
  16885. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  16886. We recommend compiling the
  16887. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  16888. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  16889. shifts the destination to the left by the number of bits specified its
  16890. source argument (in this case $3$, the length of the tag) and it
  16891. preserves the sign of the integer. We use the \key{orq} instruction to
  16892. combine the tag and the value to form the tagged value. \\
  16893. %
  16894. {\if\edition\racketEd
  16895. \begin{lstlisting}
  16896. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16897. |$\Rightarrow$|
  16898. movq |$e'$|, |\itm{lhs'}|
  16899. salq $3, |\itm{lhs'}|
  16900. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16901. \end{lstlisting}
  16902. \fi}
  16903. %
  16904. {\if\edition\pythonEd
  16905. \begin{lstlisting}
  16906. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16907. |$\Rightarrow$|
  16908. movq |$e'$|, |\itm{lhs'}|
  16909. salq $3, |\itm{lhs'}|
  16910. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16911. \end{lstlisting}
  16912. \fi}
  16913. %
  16914. The instruction selection for tuples and procedures is different
  16915. because their is no need to shift them to the left. The rightmost 3
  16916. bits are already zeros so we simply combine the value and the tag
  16917. using \key{orq}. \\
  16918. %
  16919. {\if\edition\racketEd
  16920. \begin{center}
  16921. \begin{minipage}{\textwidth}
  16922. \begin{lstlisting}
  16923. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16924. |$\Rightarrow$|
  16925. movq |$e'$|, |\itm{lhs'}|
  16926. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16927. \end{lstlisting}
  16928. \end{minipage}
  16929. \end{center}
  16930. \fi}
  16931. %
  16932. {\if\edition\pythonEd
  16933. \begin{lstlisting}
  16934. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16935. |$\Rightarrow$|
  16936. movq |$e'$|, |\itm{lhs'}|
  16937. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16938. \end{lstlisting}
  16939. \fi}
  16940. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  16941. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  16942. operation extracts the type tag from a value of type \ANYTY{}. The
  16943. type tag is the bottom three bits, so we obtain the tag by taking the
  16944. bitwise-and of the value with $111$ ($7$ in decimal).
  16945. %
  16946. {\if\edition\racketEd
  16947. \begin{lstlisting}
  16948. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  16949. |$\Rightarrow$|
  16950. movq |$e'$|, |\itm{lhs'}|
  16951. andq $7, |\itm{lhs'}|
  16952. \end{lstlisting}
  16953. \fi}
  16954. %
  16955. {\if\edition\pythonEd
  16956. \begin{lstlisting}
  16957. Assign([|\itm{lhs}|], TagOf(|$e$|))
  16958. |$\Rightarrow$|
  16959. movq |$e'$|, |\itm{lhs'}|
  16960. andq $7, |\itm{lhs'}|
  16961. \end{lstlisting}
  16962. \fi}
  16963. \paragraph{\code{ValueOf}}
  16964. The instructions for \key{ValueOf} also differ depending on whether
  16965. the type $T$ is a pointer (tuple or function) or not (integer or
  16966. Boolean). The following shows the instruction selection for integers
  16967. and Booleans. We produce an untagged value by shifting it to the
  16968. right by 3 bits.
  16969. %
  16970. {\if\edition\racketEd
  16971. \begin{lstlisting}
  16972. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16973. |$\Rightarrow$|
  16974. movq |$e'$|, |\itm{lhs'}|
  16975. sarq $3, |\itm{lhs'}|
  16976. \end{lstlisting}
  16977. \fi}
  16978. %
  16979. {\if\edition\pythonEd
  16980. \begin{lstlisting}
  16981. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16982. |$\Rightarrow$|
  16983. movq |$e'$|, |\itm{lhs'}|
  16984. sarq $3, |\itm{lhs'}|
  16985. \end{lstlisting}
  16986. \fi}
  16987. %
  16988. In the case for tuples and procedures, we zero-out the rightmost 3
  16989. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  16990. ($7$ in decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  16991. in decimal) which we \code{movq} into the destination $\itm{lhs'}$.
  16992. Finally, we apply \code{andq} with the tagged value to get the desired
  16993. result.
  16994. %
  16995. {\if\edition\racketEd
  16996. \begin{lstlisting}
  16997. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16998. |$\Rightarrow$|
  16999. movq $|$-8$|, |\itm{lhs'}|
  17000. andq |$e'$|, |\itm{lhs'}|
  17001. \end{lstlisting}
  17002. \fi}
  17003. %
  17004. {\if\edition\pythonEd
  17005. \begin{lstlisting}
  17006. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17007. |$\Rightarrow$|
  17008. movq $|$-8$|, |\itm{lhs'}|
  17009. andq |$e'$|, |\itm{lhs'}|
  17010. \end{lstlisting}
  17011. \fi}
  17012. %% \paragraph{Type Predicates} We leave it to the reader to
  17013. %% devise a sequence of instructions to implement the type predicates
  17014. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  17015. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  17016. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  17017. operation combines the effect of \code{ValueOf} with accessing the
  17018. length of a tuple from the tag stored at the zero index of the tuple.
  17019. {\if\edition\racketEd
  17020. \begin{lstlisting}
  17021. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  17022. |$\Longrightarrow$|
  17023. movq $|$-8$|, %r11
  17024. andq |$e_1'$|, %r11
  17025. movq 0(%r11), %r11
  17026. andq $126, %r11
  17027. sarq $1, %r11
  17028. movq %r11, |$\itm{lhs'}$|
  17029. \end{lstlisting}
  17030. \fi}
  17031. {\if\edition\pythonEd
  17032. \begin{lstlisting}
  17033. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  17034. |$\Longrightarrow$|
  17035. movq $|$-8$|, %r11
  17036. andq |$e_1'$|, %r11
  17037. movq 0(%r11), %r11
  17038. andq $126, %r11
  17039. sarq $1, %r11
  17040. movq %r11, |$\itm{lhs'}$|
  17041. \end{lstlisting}
  17042. \fi}
  17043. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  17044. This operation combines the effect of \code{ValueOf} with reading an
  17045. element of the tuple (see
  17046. Section~\ref{sec:select-instructions-gc}). However, the index may be
  17047. an arbitrary atom so instead of computing the offset at compile time,
  17048. we must generate instructions to compute the offset at runtime as
  17049. follows. Note the use of the new instruction \code{imulq}.
  17050. \begin{center}
  17051. \begin{minipage}{0.96\textwidth}
  17052. {\if\edition\racketEd
  17053. \begin{lstlisting}
  17054. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17055. |$\Longrightarrow$|
  17056. movq |$\neg 111$|, %r11
  17057. andq |$e_1'$|, %r11
  17058. movq |$e_2'$|, %rax
  17059. addq $1, %rax
  17060. imulq $8, %rax
  17061. addq %rax, %r11
  17062. movq 0(%r11) |$\itm{lhs'}$|
  17063. \end{lstlisting}
  17064. \fi}
  17065. %
  17066. {\if\edition\pythonEd
  17067. \begin{lstlisting}
  17068. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  17069. |$\Longrightarrow$|
  17070. movq $|$-8$|, %r11
  17071. andq |$e_1'$|, %r11
  17072. movq |$e_2'$|, %rax
  17073. addq $1, %rax
  17074. imulq $8, %rax
  17075. addq %rax, %r11
  17076. movq 0(%r11) |$\itm{lhs'}$|
  17077. \end{lstlisting}
  17078. \fi}
  17079. \end{minipage}
  17080. \end{center}
  17081. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  17082. %% The code generation for
  17083. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  17084. %% analogous to the above translation for reading from a tuple.
  17085. \section{Register Allocation for \LangAny{}}
  17086. \label{sec:register-allocation-Lany}
  17087. \index{subject}{register allocation}
  17088. There is an interesting interaction between tagged values and garbage
  17089. collection that has an impact on register allocation. A variable of
  17090. type \ANYTY{} might refer to a tuple and therefore it might be a root
  17091. that needs to be inspected and copied during garbage collection. Thus,
  17092. we need to treat variables of type \ANYTY{} in a similar way to
  17093. variables of tuple type for purposes of register allocation. In
  17094. particular,
  17095. \begin{itemize}
  17096. \item If a variable of type \ANYTY{} is live during a function call,
  17097. then it must be spilled. This can be accomplished by changing
  17098. \code{build\_interference} to mark all variables of type \ANYTY{}
  17099. that are live after a \code{callq} as interfering with all the
  17100. registers.
  17101. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  17102. the root stack instead of the normal procedure call stack.
  17103. \end{itemize}
  17104. Another concern regarding the root stack is that the garbage collector
  17105. needs to differentiate between (1) plain old pointers to tuples, (2) a
  17106. tagged value that points to a tuple, and (3) a tagged value that is
  17107. not a tuple. We enable this differentiation by choosing not to use the
  17108. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  17109. reserved for identifying plain old pointers to tuples. That way, if
  17110. one of the first three bits is set, then we have a tagged value and
  17111. inspecting the tag can differentiate between tuples ($010$) and the
  17112. other kinds of values.
  17113. %% \begin{exercise}\normalfont
  17114. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  17115. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  17116. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  17117. %% compiler on these new programs and all of your previously created test
  17118. %% programs.
  17119. %% \end{exercise}
  17120. \begin{exercise}\normalfont\normalsize
  17121. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  17122. Create tests for \LangDyn{} by adapting ten of your previous test programs
  17123. by removing type annotations. Add 5 more tests programs that
  17124. specifically rely on the language being dynamically typed. That is,
  17125. they should not be legal programs in a statically typed language, but
  17126. nevertheless, they should be valid \LangDyn{} programs that run to
  17127. completion without error.
  17128. \end{exercise}
  17129. \begin{figure}[p]
  17130. \begin{tcolorbox}[colback=white]
  17131. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  17132. \node (Lfun) at (0,4) {\large \LangDyn{}};
  17133. \node (Lfun-2) at (3,4) {\large \LangDyn{}};
  17134. \node (Lfun-3) at (6,4) {\large \LangDyn{}};
  17135. \node (Lfun-4) at (9,4) {\large \LangDynFunRef{}};
  17136. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  17137. \node (Lfun-6) at (9,2) {\large \LangAnyFunRef{}};
  17138. \node (Lfun-7) at (6,2) {\large \LangAnyFunRef{}};
  17139. \node (F1-2) at (3,2) {\large \LangAnyFunRef{}};
  17140. \node (F1-3) at (0,2) {\large \LangAnyFunRef{}};
  17141. \node (F1-4) at (0,0) {\large \LangAnyAlloc{}};
  17142. \node (F1-5) at (3,0) {\large \LangAnyAlloc{}};
  17143. \node (F1-6) at (6,0) {\large \LangAnyAlloc{}};
  17144. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  17145. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17146. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17147. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17148. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17149. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17150. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17151. \path[->,bend left=15] (Lfun) edge [above] node
  17152. {\ttfamily\footnotesize shrink} (Lfun-2);
  17153. \path[->,bend left=15] (Lfun-2) edge [above] node
  17154. {\ttfamily\footnotesize uniquify} (Lfun-3);
  17155. \path[->,bend left=15] (Lfun-3) edge [above] node
  17156. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  17157. \path[->,bend left=15] (Lfun-4) edge [left] node
  17158. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  17159. \path[->,bend left=15] (Lfun-5) edge [below] node
  17160. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  17161. \path[->,bend left=15] (Lfun-6) edge [below] node
  17162. {\ttfamily\footnotesize convert\_assign.} (Lfun-7);
  17163. \path[->,bend right=15] (Lfun-7) edge [above] node
  17164. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17165. \path[->,bend right=15] (F1-2) edge [above] node
  17166. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17167. \path[->,bend right=15] (F1-3) edge [right] node
  17168. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17169. \path[->,bend right=15] (F1-4) edge [below] node
  17170. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  17171. \path[->,bend left=15] (F1-5) edge [above] node
  17172. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  17173. \path[->,bend left=15] (F1-6) edge [right] node
  17174. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17175. \path[->,bend left=15] (C3-2) edge [left] node
  17176. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17177. \path[->,bend right=15] (x86-2) edge [left] node
  17178. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17179. \path[->,bend right=15] (x86-2-1) edge [below] node
  17180. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17181. \path[->,bend right=15] (x86-2-2) edge [left] node
  17182. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17183. \path[->,bend left=15] (x86-3) edge [above] node
  17184. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17185. \path[->,bend left=15] (x86-4) edge [right] node
  17186. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  17187. \end{tikzpicture}
  17188. \end{tcolorbox}
  17189. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  17190. \label{fig:Ldyn-passes}
  17191. \end{figure}
  17192. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  17193. for the compilation of \LangDyn{}.
  17194. % Further Reading
  17195. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17196. %% {\if\edition\pythonEd
  17197. %% \chapter{Objects}
  17198. %% \label{ch:Lobject}
  17199. %% \index{subject}{objects}
  17200. %% \index{subject}{classes}
  17201. %% \fi}
  17202. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17203. \chapter{Gradual Typing}
  17204. \label{ch:Lgrad}
  17205. \index{subject}{gradual typing}
  17206. This chapter studies a language, \LangGrad{}, in which the programmer
  17207. can choose between static and dynamic type checking in different parts
  17208. of a program, thereby mixing the statically typed \LangLam{} language
  17209. with the dynamically typed \LangDyn{}. There are several approaches to
  17210. mixing static and dynamic typing, including multi-language
  17211. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  17212. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  17213. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  17214. programmer controls the amount of static versus dynamic checking by
  17215. adding or removing type annotations on parameters and
  17216. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  17217. %
  17218. The concrete syntax of \LangGrad{} is defined in
  17219. Figure~\ref{fig:Lgrad-concrete-syntax} and its abstract syntax is
  17220. defined in Figure~\ref{fig:Lgrad-syntax}. The main syntactic
  17221. difference between \LangLam{} and \LangGrad{} is that type annotations
  17222. optional, which is specified in the grammar using the \Param{} and
  17223. \itm{ret} non-terminals. In the abstract syntax, type annotations are
  17224. not optional but we use the \CANYTY{} type when a type annotation is
  17225. absent.
  17226. \newcommand{\LgradGrammarRacket}{
  17227. \begin{array}{lcl}
  17228. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  17229. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17230. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  17231. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  17232. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  17233. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  17234. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  17235. \end{array}
  17236. }
  17237. \newcommand{\LgradASTRacket}{
  17238. \begin{array}{lcl}
  17239. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  17240. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17241. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17242. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  17243. \itm{op} &::=& \code{procedure-arity} \\
  17244. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  17245. \end{array}
  17246. }
  17247. \newcommand{\LgradGrammarPython}{
  17248. \begin{array}{lcl}
  17249. \Type &::=& \key{Any}
  17250. \MID \key{int}
  17251. \MID \key{bool}
  17252. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  17253. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  17254. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17255. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  17256. \MID \CARITY{\Exp} \\
  17257. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  17258. \Param &::=& \Var \MID \Var \key{:} \Type \\
  17259. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  17260. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  17261. \end{array}
  17262. }
  17263. \newcommand{\LgradASTPython}{
  17264. \begin{array}{lcl}
  17265. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  17266. &\MID& \key{TupleType}\LP\Type^{*}\RP
  17267. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  17268. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  17269. &\MID& \ARITY{\Exp} \\
  17270. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  17271. \MID \RETURN{\Exp} \\
  17272. \Param &::=& \LP\Var\key{,}\Type\RP \\
  17273. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  17274. \end{array}
  17275. }
  17276. \begin{figure}[tp]
  17277. \centering
  17278. \begin{tcolorbox}[colback=white]
  17279. \small
  17280. {\if\edition\racketEd
  17281. \[
  17282. \begin{array}{l}
  17283. \gray{\LintGrammarRacket{}} \\ \hline
  17284. \gray{\LvarGrammarRacket{}} \\ \hline
  17285. \gray{\LifGrammarRacket{}} \\ \hline
  17286. \gray{\LwhileGrammarRacket} \\ \hline
  17287. \gray{\LtupGrammarRacket} \\ \hline
  17288. \LgradGrammarRacket \\
  17289. \begin{array}{lcl}
  17290. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  17291. \end{array}
  17292. \end{array}
  17293. \]
  17294. \fi}
  17295. {\if\edition\pythonEd
  17296. \[
  17297. \begin{array}{l}
  17298. \gray{\LintGrammarPython{}} \\ \hline
  17299. \gray{\LvarGrammarPython{}} \\ \hline
  17300. \gray{\LifGrammarPython{}} \\ \hline
  17301. \gray{\LwhileGrammarPython} \\ \hline
  17302. \gray{\LtupGrammarPython} \\ \hline
  17303. \LgradGrammarPython \\
  17304. \begin{array}{lcl}
  17305. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  17306. \end{array}
  17307. \end{array}
  17308. \]
  17309. \fi}
  17310. \end{tcolorbox}
  17311. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  17312. \label{fig:Lgrad-concrete-syntax}
  17313. \end{figure}
  17314. \begin{figure}[tp]
  17315. \centering
  17316. \begin{tcolorbox}[colback=white]
  17317. \small
  17318. {\if\edition\racketEd
  17319. \[
  17320. \begin{array}{l}
  17321. \gray{\LintOpAST} \\ \hline
  17322. \gray{\LvarASTRacket{}} \\ \hline
  17323. \gray{\LifASTRacket{}} \\ \hline
  17324. \gray{\LwhileASTRacket{}} \\ \hline
  17325. \gray{\LtupASTRacket{}} \\ \hline
  17326. \LgradASTRacket \\
  17327. \begin{array}{lcl}
  17328. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17329. \end{array}
  17330. \end{array}
  17331. \]
  17332. \fi}
  17333. {\if\edition\pythonEd
  17334. \[
  17335. \begin{array}{l}
  17336. \gray{\LintASTPython{}} \\ \hline
  17337. \gray{\LvarASTPython{}} \\ \hline
  17338. \gray{\LifASTPython{}} \\ \hline
  17339. \gray{\LwhileASTPython} \\ \hline
  17340. \gray{\LtupASTPython} \\ \hline
  17341. \LgradASTPython \\
  17342. \begin{array}{lcl}
  17343. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17344. \end{array}
  17345. \end{array}
  17346. \]
  17347. \fi}
  17348. \end{tcolorbox}
  17349. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  17350. \label{fig:Lgrad-syntax}
  17351. \end{figure}
  17352. Both the type checker and the interpreter for \LangGrad{} require some
  17353. interesting changes to enable gradual typing, which we discuss in the
  17354. next two sections.
  17355. % TODO: more road map -Jeremy
  17356. %\clearpage
  17357. \section{Type Checking \LangGrad{}}
  17358. \label{sec:gradual-type-check}
  17359. We begin by discussing the type checking of a partially-typed variant
  17360. of the \code{map} example from Chapter~\ref{ch:Lfun}, shown in
  17361. Figure~\ref{fig:gradual-map}. The \code{map} function itself is
  17362. statically typed, so there is nothing special happening there with
  17363. respect to type checking. On the other hand, the \code{inc} function
  17364. does not have type annotations, so parameter \code{x} is given the
  17365. type \CANYTY{} and the return type of \code{inc} is \CANYTY{}. Now
  17366. consider the \code{+} operator inside \code{inc}. It expects both
  17367. arguments to have type \INTTY{}, but its first argument \code{x}
  17368. has type \CANYTY{}. In a gradually typed language, such differences
  17369. are allowed so long as the types are \emph{consistent}, that is, they
  17370. are equal except in places where there is an \CANYTY{} type. That is,
  17371. the type \CANYTY{} is consistent with every other type.
  17372. Figure~\ref{fig:consistent} defines the
  17373. \racket{\code{consistent?}}\python{\code{consistent}} method.
  17374. %
  17375. So the type checker allows the \code{+} operator to be applied
  17376. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  17377. %
  17378. Next consider the call to the \code{map} function in
  17379. Figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  17380. tuple. The \code{inc} function has type
  17381. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17382. but parameter \code{f} of \code{map} has type
  17383. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17384. The type checker for \LangGrad{} allows this because the two types are
  17385. consistent.
  17386. \begin{figure}[btp]
  17387. % gradual_test_9.rkt
  17388. \begin{tcolorbox}[colback=white]
  17389. {\if\edition\racketEd
  17390. \begin{lstlisting}
  17391. (define (map [f : (Integer -> Integer)]
  17392. [v : (Vector Integer Integer)])
  17393. : (Vector Integer Integer)
  17394. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17395. (define (inc x) (+ x 1))
  17396. (vector-ref (map inc (vector 0 41)) 1)
  17397. \end{lstlisting}
  17398. \fi}
  17399. {\if\edition\pythonEd
  17400. \begin{lstlisting}
  17401. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17402. return f(v[0]), f(v[1])
  17403. def inc(x):
  17404. return x + 1
  17405. t = map(inc, (0, 41))
  17406. print(t[1])
  17407. \end{lstlisting}
  17408. \fi}
  17409. \end{tcolorbox}
  17410. \caption{A partially-typed version of the \code{map} example.}
  17411. \label{fig:gradual-map}
  17412. \end{figure}
  17413. \begin{figure}[tbp]
  17414. \begin{tcolorbox}[colback=white]
  17415. {\if\edition\racketEd
  17416. \begin{lstlisting}
  17417. (define/public (consistent? t1 t2)
  17418. (match* (t1 t2)
  17419. [('Integer 'Integer) #t]
  17420. [('Boolean 'Boolean) #t]
  17421. [('Void 'Void) #t]
  17422. [('Any t2) #t]
  17423. [(t1 'Any) #t]
  17424. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17425. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  17426. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17427. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  17428. (consistent? rt1 rt2))]
  17429. [(other wise) #f]))
  17430. \end{lstlisting}
  17431. \fi}
  17432. {\if\edition\pythonEd
  17433. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17434. def consistent(self, t1, t2):
  17435. match (t1, t2):
  17436. case (AnyType(), _):
  17437. return True
  17438. case (_, AnyType()):
  17439. return True
  17440. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17441. return all([self.consistent(p1, p2) for (p1,p2) in zip(ps1,ps2)]) \
  17442. and consistent(rt1, rt2)
  17443. case (TupleType(ts1), TupleType(ts2)):
  17444. return all([self.consistent(ty1, ty2) for (ty1,ty2) in zip(ts1,ts2)])
  17445. case (_, _):
  17446. return t1 == t2
  17447. \end{lstlisting}
  17448. \fi}
  17449. \end{tcolorbox}
  17450. \caption{The consistency method on types.}
  17451. \label{fig:consistent}
  17452. \end{figure}
  17453. It is also helpful to consider how gradual typing handles programs with an
  17454. error, such as applying \code{map} to a function that sometimes
  17455. returns a Boolean, as shown in Figure~\ref{fig:map-maybe_inc}. The
  17456. type checker for \LangGrad{} accepts this program because the type of
  17457. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  17458. \code{map}, that is,
  17459. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17460. is consistent with
  17461. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17462. One might say that a gradual type checker is optimistic in that it
  17463. accepts programs that might execute without a runtime type error.
  17464. %
  17465. The type checker for \LangGrad{} is defined in
  17466. Figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  17467. and \ref{fig:type-check-Lgradual-3}.
  17468. %% \begin{figure}[tp]
  17469. %% \centering
  17470. %% \fbox{
  17471. %% \begin{minipage}{0.96\textwidth}
  17472. %% \small
  17473. %% \[
  17474. %% \begin{array}{lcl}
  17475. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17476. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17477. %% \end{array}
  17478. %% \]
  17479. %% \end{minipage}
  17480. %% }
  17481. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (Figure~\ref{fig:Lwhile-syntax}).}
  17482. %% \label{fig:Lgrad-prime-syntax}
  17483. %% \end{figure}
  17484. \begin{figure}[tbp]
  17485. \begin{tcolorbox}[colback=white]
  17486. {\if\edition\racketEd
  17487. \begin{lstlisting}
  17488. (define (map [f : (Integer -> Integer)]
  17489. [v : (Vector Integer Integer)])
  17490. : (Vector Integer Integer)
  17491. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17492. (define (inc x) (+ x 1))
  17493. (define (true) #t)
  17494. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  17495. (vector-ref (map maybe_inc (vector 0 41)) 0)
  17496. \end{lstlisting}
  17497. \fi}
  17498. {\if\edition\pythonEd
  17499. \begin{lstlisting}
  17500. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17501. return f(v[0]), f(v[1])
  17502. def inc(x):
  17503. return x + 1
  17504. def true():
  17505. return True
  17506. def maybe_inc(x):
  17507. return inc(x) if input_int() == 0 else true()
  17508. t = map(maybe_inc, (0, 41))
  17509. print( t[1] )
  17510. \end{lstlisting}
  17511. \fi}
  17512. \end{tcolorbox}
  17513. \caption{A variant of the \code{map} example with an error.}
  17514. \label{fig:map-maybe_inc}
  17515. \end{figure}
  17516. Running this program with input \code{1} triggers an
  17517. error when the \code{maybe\_inc} function returns
  17518. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  17519. performs checking at runtime to ensure the integrity of the static
  17520. types, such as the
  17521. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  17522. annotation on
  17523. parameter \code{f} of \code{map}.
  17524. Here we give a preview of how the runtime checking is accomplished;
  17525. the following sections provide the details.
  17526. The runtime checking is carried out by a new \code{Cast} AST node that
  17527. is generate in a new pass named \code{cast\_insert}. The output of
  17528. \code{cast\_insert} is a program in the \LangCast{} language, which
  17529. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  17530. %
  17531. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  17532. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  17533. inserted every time the type checker sees two types that are
  17534. consistent but not equal. In the \code{inc} function, \code{x} is
  17535. cast to \INTTY{} and the result of the \code{+} is cast to
  17536. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  17537. is cast from
  17538. \racket{\code{(Any -> Any)}}
  17539. \python{\code{Callable[[Any], Any]}}
  17540. to
  17541. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17542. %
  17543. In the next section we see how to interpret the \code{Cast} node.
  17544. \begin{figure}[btp]
  17545. \begin{tcolorbox}[colback=white]
  17546. {\if\edition\racketEd
  17547. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17548. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17549. : (Vector Integer Integer)
  17550. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17551. (define (inc [x : Any]) : Any
  17552. (cast (+ (cast x Any Integer) 1) Integer Any))
  17553. (define (true) : Any (cast #t Boolean Any))
  17554. (define (maybe_inc [x : Any]) : Any
  17555. (if (eq? 0 (read)) (inc x) (true)))
  17556. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  17557. (vector 0 41)) 0)
  17558. \end{lstlisting}
  17559. \fi}
  17560. {\if\edition\pythonEd
  17561. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17562. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17563. return f(v[0]), f(v[1])
  17564. def inc(x : Any) -> Any:
  17565. return Cast(Cast(x, Any, int) + 1, int, Any)
  17566. def true() -> Any:
  17567. return Cast(True, bool, Any)
  17568. def maybe_inc(x : Any) -> Any:
  17569. return inc(x) if input_int() == 0 else true()
  17570. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  17571. (0, 41))
  17572. print(t[1])
  17573. \end{lstlisting}
  17574. \fi}
  17575. \end{tcolorbox}
  17576. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  17577. and \code{maybe\_inc} example.}
  17578. \label{fig:map-cast}
  17579. \end{figure}
  17580. {\if\edition\pythonEd
  17581. \begin{figure}[tbp]
  17582. \begin{tcolorbox}[colback=white]
  17583. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17584. class TypeCheckLgrad(TypeCheckLlambda):
  17585. def type_check_exp(self, e, env):
  17586. match e:
  17587. case Name(id):
  17588. return env[id]
  17589. case Constant(value) if value is True or value is False:
  17590. return BoolType()
  17591. case Constant(value) if isinstance(value, int):
  17592. return IntType()
  17593. case Call(Name('input_int'), []):
  17594. return IntType()
  17595. case BinOp(left, op, right):
  17596. left_type = self.type_check_exp(left, env)
  17597. self.check_consistent(left_type, IntType(), left)
  17598. right_type = self.type_check_exp(right, env)
  17599. self.check_consistent(right_type, IntType(), right)
  17600. return IntType()
  17601. case IfExp(test, body, orelse):
  17602. test_t = self.type_check_exp(test, env)
  17603. self.check_consistent(test_t, BoolType(), test)
  17604. body_t = self.type_check_exp(body, env)
  17605. orelse_t = self.type_check_exp(orelse, env)
  17606. self.check_consistent(body_t, orelse_t, e)
  17607. return self.join_types(body_t, orelse_t)
  17608. case Call(func, args):
  17609. func_t = self.type_check_exp(func, env)
  17610. args_t = unzip([self.type_check_exp(arg, env) for arg in args])
  17611. match func_t:
  17612. case FunctionType(params_t, return_t):
  17613. for (arg_t, param_t) in zip(args_t, params_t):
  17614. self.check_consistent(param_t, arg_t, e)
  17615. return return_t
  17616. case AnyType():
  17617. return AnyType()
  17618. case _:
  17619. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  17620. ...
  17621. case _:
  17622. raise Exception('type_check_exp: unexpected ' + repr(e))
  17623. \end{lstlisting}
  17624. \end{tcolorbox}
  17625. \caption{Type checking expressions in the \LangGrad{} language.}
  17626. \label{fig:type-check-Lgradual-1}
  17627. \end{figure}
  17628. \begin{figure}[tbp]
  17629. \begin{tcolorbox}[colback=white]
  17630. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17631. def check_exp(self, e, expected_ty, env):
  17632. match e:
  17633. case Lambda(params, body):
  17634. match expected_ty:
  17635. case FunctionType(params_t, return_t):
  17636. new_env = {x:t for (x,t) in env.items()}
  17637. for (p,t) in zip(new_params, params_t):
  17638. new_env[p] = t
  17639. e.has_type = expected_ty
  17640. case AnyType():
  17641. new_env = {x:t for (x,t) in env.items()}
  17642. for p in new_params:
  17643. new_env[p] = AnyType()
  17644. e.has_type = FunctionType([AnyType() for _ in new_params], AnyType())
  17645. case _:
  17646. raise Exception('lambda does not have type ' + str(expected_ty))
  17647. case _:
  17648. e_ty = self.type_check_exp(e, env)
  17649. self.check_consistent(e_ty, expected_ty, e)
  17650. \end{lstlisting}
  17651. \end{tcolorbox}
  17652. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  17653. \label{fig:type-check-Lgradual-2}
  17654. \end{figure}
  17655. \begin{figure}[tbp]
  17656. \begin{tcolorbox}[colback=white]
  17657. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17658. def type_check_stmt(self, s, env, return_type):
  17659. match s:
  17660. case Assign([Name(id)], value):
  17661. value_ty = self.type_check_exp(value, env)
  17662. if id in env:
  17663. self.check_consistent(env[id], value_ty, value)
  17664. else:
  17665. env[id] = t
  17666. ...
  17667. case _:
  17668. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  17669. def type_check_stmts(self, ss, env, return_type):
  17670. for s in ss:
  17671. self.type_check_stmt(s, env, return_type)
  17672. \end{lstlisting}
  17673. \end{tcolorbox}
  17674. \caption{Type checking statements in the \LangGrad{} language.}
  17675. \label{fig:type-check-Lgradual-3}
  17676. \end{figure}
  17677. \begin{figure}[tbp]
  17678. \begin{tcolorbox}[colback=white]
  17679. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17680. def join_types(self, t1, t2):
  17681. match (t1, t2):
  17682. case (AnyType(), _):
  17683. return t2
  17684. case (_, AnyType()):
  17685. return t1
  17686. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17687. return FunctionType([self.join_types(p1, p2) for (p1,p2) in zip(ps1, ps2)],
  17688. self.join_types(rt1,rt2))
  17689. case (TupleType(ts1), TupleType(ts2)):
  17690. return TupleType([self.join_types(ty1, ty2) for (ty1,ty2) in zip(ts1,ts2)])
  17691. case (_, _):
  17692. return t1
  17693. def check_consistent(self, t1, t2, e):
  17694. if not self.consistent(t1, t2):
  17695. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  17696. + ' in ' + repr(e))
  17697. \end{lstlisting}
  17698. \end{tcolorbox}
  17699. \caption{Auxiliary methods for type checking \LangGrad{}.}
  17700. \label{fig:type-check-Lgradual-aux}
  17701. \end{figure}
  17702. \fi}
  17703. {\if\edition\racketEd
  17704. \begin{figure}[tbp]
  17705. \begin{tcolorbox}[colback=white]
  17706. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17707. (define type-check-gradual-class
  17708. (class type-check-Llambda-class
  17709. (super-new)
  17710. (inherit operator-types type-predicates)
  17711. (define/override (type-check-exp env)
  17712. (lambda (e)
  17713. (define recur (type-check-exp env))
  17714. (match e
  17715. [(Prim 'vector-length (list e1))
  17716. (define-values (e1^ t) (recur e1))
  17717. (match t
  17718. [`(Vector ,ts ...)
  17719. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17720. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17721. [(Prim 'vector-ref (list e1 e2))
  17722. (define-values (e1^ t1) (recur e1))
  17723. (define-values (e2^ t2) (recur e2))
  17724. (check-consistent? t2 'Integer e)
  17725. (match t1
  17726. [`(Vector ,ts ...)
  17727. (match e2^
  17728. [(Int i)
  17729. (unless (and (0 . <= . i) (i . < . (length ts)))
  17730. (error 'type-check "invalid index ~a in ~a" i e))
  17731. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17732. [else (define e1^^ (make-cast e1^ t1 'Any))
  17733. (define e2^^ (make-cast e2^ t2 'Integer))
  17734. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17735. ['Any
  17736. (define e2^^ (make-cast e2^ t2 'Integer))
  17737. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17738. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17739. [(Prim 'vector-set! (list e1 e2 e3) )
  17740. (define-values (e1^ t1) (recur e1))
  17741. (define-values (e2^ t2) (recur e2))
  17742. (define-values (e3^ t3) (recur e3))
  17743. (check-consistent? t2 'Integer e)
  17744. (match t1
  17745. [`(Vector ,ts ...)
  17746. (match e2^
  17747. [(Int i)
  17748. (unless (and (0 . <= . i) (i . < . (length ts)))
  17749. (error 'type-check "invalid index ~a in ~a" i e))
  17750. (check-consistent? (list-ref ts i) t3 e)
  17751. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  17752. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  17753. [else
  17754. (define e1^^ (make-cast e1^ t1 'Any))
  17755. (define e2^^ (make-cast e2^ t2 'Integer))
  17756. (define e3^^ (make-cast e3^ t3 'Any))
  17757. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  17758. ['Any
  17759. (define e2^^ (make-cast e2^ t2 'Integer))
  17760. (define e3^^ (make-cast e3^ t3 'Any))
  17761. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  17762. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17763. \end{lstlisting}
  17764. \end{tcolorbox}
  17765. \caption{Type checker for the \LangGrad{} language, part 1.}
  17766. \label{fig:type-check-Lgradual-1}
  17767. \end{figure}
  17768. \begin{figure}[tbp]
  17769. \begin{tcolorbox}[colback=white]
  17770. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17771. [(Prim 'eq? (list e1 e2))
  17772. (define-values (e1^ t1) (recur e1))
  17773. (define-values (e2^ t2) (recur e2))
  17774. (check-consistent? t1 t2 e)
  17775. (define T (meet t1 t2))
  17776. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  17777. 'Boolean)]
  17778. [(Prim 'not (list e1))
  17779. (define-values (e1^ t1) (recur e1))
  17780. (match t1
  17781. ['Any
  17782. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  17783. (Bool #t) (Bool #f)))]
  17784. [else
  17785. (define-values (t-ret new-es^)
  17786. (type-check-op 'not (list t1) (list e1^) e))
  17787. (values (Prim 'not new-es^) t-ret)])]
  17788. [(Prim 'and (list e1 e2))
  17789. (recur (If e1 e2 (Bool #f)))]
  17790. [(Prim 'or (list e1 e2))
  17791. (define tmp (gensym 'tmp))
  17792. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  17793. [(Prim op es)
  17794. #:when (not (set-member? explicit-prim-ops op))
  17795. (define-values (new-es ts)
  17796. (for/lists (exprs types) ([e es])
  17797. (recur e)))
  17798. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  17799. (values (Prim op new-es^) t-ret)]
  17800. [(If e1 e2 e3)
  17801. (define-values (e1^ T1) (recur e1))
  17802. (define-values (e2^ T2) (recur e2))
  17803. (define-values (e3^ T3) (recur e3))
  17804. (check-consistent? T2 T3 e)
  17805. (match T1
  17806. ['Boolean
  17807. (define Tif (join T2 T3))
  17808. (values (If e1^ (make-cast e2^ T2 Tif)
  17809. (make-cast e3^ T3 Tif)) Tif)]
  17810. ['Any
  17811. (define Tif (meet T2 T3))
  17812. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  17813. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  17814. Tif)]
  17815. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  17816. [(HasType e1 T)
  17817. (define-values (e1^ T1) (recur e1))
  17818. (check-consistent? T1 T)
  17819. (values (make-cast e1^ T1 T) T)]
  17820. [(SetBang x e1)
  17821. (define-values (e1^ T1) (recur e1))
  17822. (define varT (dict-ref env x))
  17823. (check-consistent? T1 varT e)
  17824. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  17825. [(WhileLoop e1 e2)
  17826. (define-values (e1^ T1) (recur e1))
  17827. (check-consistent? T1 'Boolean e)
  17828. (define-values (e2^ T2) ((type-check-exp env) e2))
  17829. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  17830. \end{lstlisting}
  17831. \end{tcolorbox}
  17832. \caption{Type checker for the \LangGrad{} language, part 2.}
  17833. \label{fig:type-check-Lgradual-2}
  17834. \end{figure}
  17835. \begin{figure}[tbp]
  17836. \begin{tcolorbox}[colback=white]
  17837. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17838. [(Apply e1 e2s)
  17839. (define-values (e1^ T1) (recur e1))
  17840. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  17841. (match T1
  17842. [`(,T1ps ... -> ,T1rt)
  17843. (for ([T2 T2s] [Tp T1ps])
  17844. (check-consistent? T2 Tp e))
  17845. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  17846. (make-cast e2 src tgt)))
  17847. (values (Apply e1^ e2s^^) T1rt)]
  17848. [`Any
  17849. (define e1^^ (make-cast e1^ 'Any
  17850. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  17851. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  17852. (make-cast e2 src 'Any)))
  17853. (values (Apply e1^^ e2s^^) 'Any)]
  17854. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  17855. [(Lambda params Tr e1)
  17856. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  17857. (match p
  17858. [`[,x : ,T] (values x T)]
  17859. [(? symbol? x) (values x 'Any)])))
  17860. (define-values (e1^ T1)
  17861. ((type-check-exp (append (map cons xs Ts) env)) e1))
  17862. (check-consistent? Tr T1 e)
  17863. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  17864. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  17865. [else ((super type-check-exp env) e)]
  17866. )))
  17867. \end{lstlisting}
  17868. \end{tcolorbox}
  17869. \caption{Type checker for the \LangGrad{} language, part 3.}
  17870. \label{fig:type-check-Lgradual-3}
  17871. \end{figure}
  17872. \begin{figure}[tbp]
  17873. \begin{tcolorbox}[colback=white]
  17874. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17875. (define/public (join t1 t2)
  17876. (match* (t1 t2)
  17877. [('Integer 'Integer) 'Integer]
  17878. [('Boolean 'Boolean) 'Boolean]
  17879. [('Void 'Void) 'Void]
  17880. [('Any t2) t2]
  17881. [(t1 'Any) t1]
  17882. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17883. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  17884. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17885. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  17886. -> ,(join rt1 rt2))]))
  17887. (define/public (meet t1 t2)
  17888. (match* (t1 t2)
  17889. [('Integer 'Integer) 'Integer]
  17890. [('Boolean 'Boolean) 'Boolean]
  17891. [('Void 'Void) 'Void]
  17892. [('Any t2) 'Any]
  17893. [(t1 'Any) 'Any]
  17894. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17895. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  17896. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17897. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  17898. -> ,(meet rt1 rt2))]))
  17899. (define/public (make-cast e src tgt)
  17900. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  17901. (define/public (check-consistent? t1 t2 e)
  17902. (unless (consistent? t1 t2)
  17903. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  17904. (define/override (type-check-op op arg-types args e)
  17905. (match (dict-ref (operator-types) op)
  17906. [`(,param-types . ,return-type)
  17907. (for ([at arg-types] [pt param-types])
  17908. (check-consistent? at pt e))
  17909. (values return-type
  17910. (for/list ([e args] [s arg-types] [t param-types])
  17911. (make-cast e s t)))]
  17912. [else (error 'type-check-op "unrecognized ~a" op)]))
  17913. (define explicit-prim-ops
  17914. (set-union
  17915. (type-predicates)
  17916. (set 'procedure-arity 'eq?
  17917. 'vector 'vector-length 'vector-ref 'vector-set!
  17918. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  17919. (define/override (fun-def-type d)
  17920. (match d
  17921. [(Def f params rt info body)
  17922. (define ps
  17923. (for/list ([p params])
  17924. (match p
  17925. [`[,x : ,T] T]
  17926. [(? symbol?) 'Any]
  17927. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  17928. `(,@ps -> ,rt)]
  17929. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  17930. \end{lstlisting}
  17931. \end{tcolorbox}
  17932. \caption{Auxiliary functions for type checking \LangGrad{}.}
  17933. \label{fig:type-check-Lgradual-aux}
  17934. \end{figure}
  17935. \fi}
  17936. \clearpage
  17937. \section{Interpreting \LangCast{}}
  17938. \label{sec:interp-casts}
  17939. The runtime behavior of casts involving simple types such as
  17940. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  17941. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  17942. \code{Inject} operator of \LangAny{}, which puts the integer into a
  17943. tagged value (Figure~\ref{fig:interp-Lany}). Similarly, a cast from
  17944. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  17945. operator, that is, by checking the value's tag and either retrieving
  17946. the underlying integer or signaling an error if it the tag is not the
  17947. one for integers (Figure~\ref{fig:interp-Lany-aux}).
  17948. %
  17949. Things get more interesting casts involving function, tuple, or array
  17950. types, that is, casts involving higher-order types.
  17951. Consider the cast of the function \code{maybe\_inc} from
  17952. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  17953. to
  17954. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  17955. in Figure~\ref{fig:map-maybe_inc}.
  17956. When the \code{maybe\_inc} function flows through
  17957. this cast at runtime, we don't know whether it will return
  17958. an integer, as that depends on the input from the user.
  17959. The \LangCast{} interpreter therefore delays the checking
  17960. of the cast until the function is applied. This is accomplished by
  17961. wrapping \code{maybe\_inc} in a new function that casts its parameter
  17962. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  17963. casts the return value from \CANYTY{} to \INTTY{}.
  17964. {\if\edition\pythonEd
  17965. %
  17966. There are further complicatons regarding casts on mutable data
  17967. such as the \code{list} type introduced in
  17968. the challenge assignment of Section~\ref{sec:arrays}.
  17969. %
  17970. \fi}
  17971. %
  17972. Consider the example in Figure~\ref{fig:map-bang} that
  17973. defines a partially-typed version of \code{map} whose parameter
  17974. \code{v} has type
  17975. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  17976. and that updates \code{v} in place
  17977. instead of returning a new tuple. So we name this function
  17978. \code{map\_inplace}. We apply \code{map\_inplace} to a
  17979. \racket{tuple}\python{list} of integers, so the type checker inserts a
  17980. cast from
  17981. \racket{\code{(Vector Integer Integer)}}
  17982. \python{\code{list[int]}}
  17983. to
  17984. \racket{\code{(Vector Any Any)}}
  17985. \python{\code{list[Any]}}.
  17986. A naive way for the \LangCast{} interpreter to cast between
  17987. \racket{tuple}\python{list} types would be a build a new
  17988. \racket{tuple}\python{list}
  17989. whose elements are the result
  17990. of casting each of the original elements to the appropriate target
  17991. type.
  17992. However, this approach is not valid for mutable data structures.
  17993. In the example of Figure~\ref{fig:map-bang},
  17994. if the cast created a new \racket{tuple}\python{list}, then the updates inside of
  17995. \code{map\_inplace} would happen to the new \racket{tuple}\python{list} and not
  17996. the original one.
  17997. \begin{figure}[tbp]
  17998. \begin{tcolorbox}[colback=white]
  17999. % gradual_test_11.rkt
  18000. {\if\edition\racketEd
  18001. \begin{lstlisting}
  18002. (define (map_inplace [f : (Any -> Any)]
  18003. [v : (Vector Any Any)]) : Void
  18004. (begin
  18005. (vector-set! v 0 (f (vector-ref v 0)))
  18006. (vector-set! v 1 (f (vector-ref v 1)))))
  18007. (define (inc x) (+ x 1))
  18008. (let ([v (vector 0 41)])
  18009. (begin (map_inplace inc v) (vector-ref v 1)))
  18010. \end{lstlisting}
  18011. \fi}
  18012. {\if\edition\pythonEd
  18013. \begin{lstlisting}
  18014. def map_inplace(f : Callable[[Any], Any], v : list[Any]) -> None:
  18015. i = 0
  18016. while i != len(v):
  18017. v[i] = f(v[i])
  18018. i = i + 1
  18019. def inc(x):
  18020. return x + 1
  18021. v = [0, 41]
  18022. map_inplace(inc, v)
  18023. print( v[1] )
  18024. \end{lstlisting}
  18025. \fi}
  18026. \end{tcolorbox}
  18027. \caption{An example involving casts on arrays.}
  18028. \label{fig:map-bang}
  18029. \end{figure}
  18030. Instead the interpreter needs to create a new kind of value, a
  18031. \emph{proxy}, that intercepts every \racket{tuple}\python{list} operation.
  18032. On a read, the proxy reads from the underlying \racket{tuple}\python{list}
  18033. and then applies a
  18034. cast to the resulting value. On a write, the proxy casts the argument
  18035. value and then performs the write to the underlying tuple.
  18036. \racket{
  18037. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  18038. \code{0} from \INTTY{} to \CANYTY{}.
  18039. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  18040. from \CANYTY{} to \INTTY{}.
  18041. }
  18042. \python{
  18043. For the subscript \code{v[i]} in \code{f([v[i])} of \code{map\_inplace},
  18044. the proxy casts integer from \INTTY{} to \CANYTY{}.
  18045. Then for the subscript on the left of the assignment,
  18046. the proxy casts the tagged value from from \CANYTY{} to \INTTY{}.
  18047. }
  18048. The final category of cast that we need to consider are casts between
  18049. the \CANYTY{} type and higher-order types such as functions or
  18050. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  18051. variant of \code{map\_inplace} in which parameter \code{v} does not
  18052. have a type annotation, so it is given type \CANYTY{}. In the call to
  18053. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  18054. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  18055. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  18056. \code{Inject}, but that doesn't work because
  18057. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  18058. a flat type. Instead, we must first cast to
  18059. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}} (which is flat)
  18060. and then inject to \CANYTY{}.
  18061. \begin{figure}[tbp]
  18062. \begin{tcolorbox}[colback=white]
  18063. {\if\edition\racketEd
  18064. \begin{lstlisting}
  18065. (define (map_inplace [f : (Any -> Any)] v) : Void
  18066. (begin
  18067. (vector-set! v 0 (f (vector-ref v 0)))
  18068. (vector-set! v 1 (f (vector-ref v 1)))))
  18069. (define (inc x) (+ x 1))
  18070. (let ([v (vector 0 41)])
  18071. (begin (map_inplace inc v) (vector-ref v 1)))
  18072. \end{lstlisting}
  18073. \fi}
  18074. {\if\edition\pythonEd
  18075. \begin{lstlisting}
  18076. def map_inplace(f : Callable[[Any], Any], v) -> None:
  18077. i = 0
  18078. while i != len(v):
  18079. v[i] = f(v[i])
  18080. i = i + 1
  18081. def inc(x):
  18082. return x + 1
  18083. v = [0, 41]
  18084. map_inplace(inc, v)
  18085. print( v[1] )
  18086. \end{lstlisting}
  18087. \fi}
  18088. \end{tcolorbox}
  18089. \caption{Casting a \racket{tuple}\python{list} to \CANYTY{}.}
  18090. \label{fig:map-any}
  18091. \end{figure}
  18092. The \LangCast{} interpreter uses an auxiliary function named
  18093. \code{apply\_cast} to cast a value from a source type to a target type,
  18094. shown in Figure~\ref{fig:apply_cast}. You'll find that it handles all
  18095. of the kinds of casts that we've discussed in this section.
  18096. \begin{figure}[tbp]
  18097. \begin{tcolorbox}[colback=white]
  18098. {\if\edition\racketEd
  18099. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18100. (define/public (apply_cast v s t)
  18101. (match* (s t)
  18102. [(t1 t2) #:when (equal? t1 t2) v]
  18103. [('Any t2)
  18104. (match t2
  18105. [`(,ts ... -> ,rt)
  18106. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18107. (define v^ (apply-project v any->any))
  18108. (apply_cast v^ any->any `(,@ts -> ,rt))]
  18109. [`(Vector ,ts ...)
  18110. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18111. (define v^ (apply-project v vec-any))
  18112. (apply_cast v^ vec-any `(Vector ,@ts))]
  18113. [else (apply-project v t2)])]
  18114. [(t1 'Any)
  18115. (match t1
  18116. [`(,ts ... -> ,rt)
  18117. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18118. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  18119. (apply-inject v^ (any-tag any->any))]
  18120. [`(Vector ,ts ...)
  18121. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18122. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  18123. (apply-inject v^ (any-tag vec-any))]
  18124. [else (apply-inject v (any-tag t1))])]
  18125. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18126. (define x (gensym 'x))
  18127. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  18128. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  18129. (define cast-writes
  18130. (for/list ([t1 ts1] [t2 ts2])
  18131. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  18132. `(vector-proxy ,(vector v (apply vector cast-reads)
  18133. (apply vector cast-writes)))]
  18134. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18135. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  18136. `(function ,xs ,(Cast
  18137. (Apply (Value v)
  18138. (for/list ([x xs][t1 ts1][t2 ts2])
  18139. (Cast (Var x) t2 t1)))
  18140. rt1 rt2) ())]
  18141. ))
  18142. \end{lstlisting}
  18143. \fi}
  18144. {\if\edition\pythonEd
  18145. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18146. UNDER CONSTRUCTION
  18147. \end{lstlisting}
  18148. \fi}
  18149. \end{tcolorbox}
  18150. \caption{The \code{apply\_cast} auxiliary method.}
  18151. \label{fig:apply_cast}
  18152. \end{figure}
  18153. The interpreter for \LangCast{} is defined in
  18154. Figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  18155. dispatching to \code{apply\_cast}. To handle the addition of tuple
  18156. proxies, we update the tuple primitives in \code{interp-op} using the
  18157. functions in Figure~\ref{fig:guarded-tuple}.
  18158. \begin{figure}[tbp]
  18159. \begin{tcolorbox}[colback=white]
  18160. {\if\edition\racketEd
  18161. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18162. (define interp-Lcast-class
  18163. (class interp-Llambda-class
  18164. (super-new)
  18165. (inherit apply-fun apply-inject apply-project)
  18166. (define/override (interp-op op)
  18167. (match op
  18168. ['vector-length guarded-vector-length]
  18169. ['vector-ref guarded-vector-ref]
  18170. ['vector-set! guarded-vector-set!]
  18171. ['any-vector-ref (lambda (v i)
  18172. (match v [`(tagged ,v^ ,tg)
  18173. (guarded-vector-ref v^ i)]))]
  18174. ['any-vector-set! (lambda (v i a)
  18175. (match v [`(tagged ,v^ ,tg)
  18176. (guarded-vector-set! v^ i a)]))]
  18177. ['any-vector-length (lambda (v)
  18178. (match v [`(tagged ,v^ ,tg)
  18179. (guarded-vector-length v^)]))]
  18180. [else (super interp-op op)]
  18181. ))
  18182. (define/override ((interp-exp env) e)
  18183. (define (recur e) ((interp-exp env) e))
  18184. (match e
  18185. [(Value v) v]
  18186. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  18187. [else ((super interp-exp env) e)]))
  18188. ))
  18189. (define (interp-Lcast p)
  18190. (send (new interp-Lcast-class) interp-program p))
  18191. \end{lstlisting}
  18192. \fi}
  18193. {\if\edition\pythonEd
  18194. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18195. UNDER CONSTRUCTION
  18196. \end{lstlisting}
  18197. \fi}
  18198. \end{tcolorbox}
  18199. \caption{The interpreter for \LangCast{}.}
  18200. \label{fig:interp-Lcast}
  18201. \end{figure}
  18202. \begin{figure}[tbp]
  18203. \begin{tcolorbox}[colback=white]
  18204. {\if\edition\racketEd
  18205. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18206. (define (guarded-vector-ref vec i)
  18207. (match vec
  18208. [`(vector-proxy ,proxy)
  18209. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  18210. (define rd (vector-ref (vector-ref proxy 1) i))
  18211. (apply-fun rd (list val) 'guarded-vector-ref)]
  18212. [else (vector-ref vec i)]))
  18213. (define (guarded-vector-set! vec i arg)
  18214. (match vec
  18215. [`(vector-proxy ,proxy)
  18216. (define wr (vector-ref (vector-ref proxy 2) i))
  18217. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  18218. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  18219. [else (vector-set! vec i arg)]))
  18220. (define (guarded-vector-length vec)
  18221. (match vec
  18222. [`(vector-proxy ,proxy)
  18223. (guarded-vector-length (vector-ref proxy 0))]
  18224. [else (vector-length vec)]))
  18225. \end{lstlisting}
  18226. \fi}
  18227. {\if\edition\pythonEd
  18228. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18229. UNDER CONSTRUCTION
  18230. \end{lstlisting}
  18231. \fi}
  18232. \end{tcolorbox}
  18233. \caption{The \code{guarded-vector} auxiliary functions.}
  18234. \label{fig:guarded-tuple}
  18235. \end{figure}
  18236. \section{Lower Casts}
  18237. \label{sec:lower_casts}
  18238. The next step in the journey towards x86 is the \code{lower\_casts}
  18239. pass that translates the casts in \LangCast{} to the lower-level
  18240. \code{Inject} and \code{Project} operators and a new operator for
  18241. creating tuple proxies, extending the \LangLam{} language to create
  18242. \LangProxy{}. We recommend creating an auxiliary function named
  18243. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  18244. and a target type, and translates it to expression in \LangProxy{} that has
  18245. the same behavior as casting the expression from the source to the
  18246. target type in the interpreter.
  18247. The \code{lower\_cast} function can follow a code structure similar to
  18248. the \code{apply\_cast} function (Figure~\ref{fig:apply_cast}) used in
  18249. the interpreter for \LangCast{} because it must handle the same cases as
  18250. \code{apply\_cast} and it needs to mimic the behavior of
  18251. \code{apply\_cast}. The most interesting cases are those concerning the
  18252. casts between two tuple types and between two function types.
  18253. As mentioned in Section~\ref{sec:interp-casts}, a cast from one tuple
  18254. type to another tuple type is accomplished by creating a proxy that
  18255. intercepts the operations on the underlying tuple. Here we make the
  18256. creation of the proxy explicit with the
  18257. \racket{\code{vector-proxy}}\python{\code{tuple\_proxy}}
  18258. primitive operation. It takes three arguments, the first is an expression for
  18259. the tuple, the second is a tuple of functions for casting an element
  18260. that is being read from the tuple, and the third is a tuple of
  18261. functions for casting an element that is being written to the tuple.
  18262. You can create the functions using \code{Lambda}. Also, as we shall
  18263. see in the next section, we need to differentiate these tuples from
  18264. the user-created ones, so we recommend using a new primitive function
  18265. named \racket{\code{raw-vector}}\python{\code{raw\_tuple}} instead of
  18266. \racket{\code{vector}}\python{\code{Tuple}} to create these
  18267. tuples of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  18268. the output of \code{lower\_casts} on the example in
  18269. Figure~\ref{fig:map-bang} that involved casting a tuple of
  18270. integers to a tuple of \CANYTY{}.
  18271. \begin{figure}[tbp]
  18272. \begin{tcolorbox}[colback=white]
  18273. {\if\edition\racketEd
  18274. \begin{lstlisting}
  18275. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  18276. (begin
  18277. (vector-set! v 0 (f (vector-ref v 0)))
  18278. (vector-set! v 1 (f (vector-ref v 1)))))
  18279. (define (inc [x : Any]) : Any
  18280. (inject (+ (project x Integer) 1) Integer))
  18281. (let ([v (vector 0 41)])
  18282. (begin
  18283. (map_inplace inc (vector-proxy v
  18284. (raw-vector (lambda: ([x9 : Integer]) : Any
  18285. (inject x9 Integer))
  18286. (lambda: ([x9 : Integer]) : Any
  18287. (inject x9 Integer)))
  18288. (raw-vector (lambda: ([x9 : Any]) : Integer
  18289. (project x9 Integer))
  18290. (lambda: ([x9 : Any]) : Integer
  18291. (project x9 Integer)))))
  18292. (vector-ref v 1)))
  18293. \end{lstlisting}
  18294. \fi}
  18295. {\if\edition\pythonEd
  18296. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18297. UNDER CONSTRUCTION
  18298. \end{lstlisting}
  18299. \fi}
  18300. \end{tcolorbox}
  18301. \caption{Output of \code{lower\_casts} on the example in
  18302. Figure~\ref{fig:map-bang}.}
  18303. \label{fig:map-bang-lower-cast}
  18304. \end{figure}
  18305. A cast from one function type to another function type is accomplished
  18306. by generating a \code{Lambda} whose parameter and return types match
  18307. the target function type. The body of the \code{Lambda} should cast
  18308. the parameters from the target type to the source type. (Yes,
  18309. backwards! Functions are contravariant\index{subject}{contravariant}
  18310. in the parameters.). Afterwards, call the underlying function and then
  18311. cast the result from the source return type to the target return type.
  18312. Figure~\ref{fig:map-lower-cast} shows the output of the
  18313. \code{lower\_casts} pass on the \code{map} example in
  18314. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  18315. call to \code{map} is wrapped in a \code{lambda}.
  18316. \begin{figure}[tbp]
  18317. \begin{tcolorbox}[colback=white]
  18318. {\if\edition\racketEd
  18319. \begin{lstlisting}
  18320. (define (map [f : (Integer -> Integer)]
  18321. [v : (Vector Integer Integer)])
  18322. : (Vector Integer Integer)
  18323. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18324. (define (inc [x : Any]) : Any
  18325. (inject (+ (project x Integer) 1) Integer))
  18326. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  18327. (project (inc (inject x9 Integer)) Integer))
  18328. (vector 0 41)) 1)
  18329. \end{lstlisting}
  18330. \fi}
  18331. {\if\edition\pythonEd
  18332. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18333. UNDER CONSTRUCTION
  18334. \end{lstlisting}
  18335. \fi}
  18336. \end{tcolorbox}
  18337. \caption{Output of \code{lower\_casts} on the example in
  18338. Figure~\ref{fig:gradual-map}.}
  18339. \label{fig:map-lower-cast}
  18340. \end{figure}
  18341. \section{Differentiate Proxies}
  18342. \label{sec:differentiate-proxies}
  18343. So far the job of differentiating tuples and tuple proxies has been
  18344. the job of the interpreter. For example, the interpreter for \LangCast{}
  18345. implements \code{vector-ref} using the \code{guarded-vector-ref}
  18346. function in Figure~\ref{fig:guarded-tuple}. In the
  18347. \code{differentiate-proxies} pass we shift this responsibility to the
  18348. generated code.
  18349. We begin by designing the output language \LangPVec. In
  18350. \LangGrad{} we used the type \code{Vector} for both real tuples and tuple
  18351. proxies. In \LangPVec we return the \code{Vector} type to
  18352. its original meaning, as the type of real tuples, and we introduce a
  18353. new type, \code{PVector}, whose values can be either real tuples or
  18354. tuple proxies. This new type comes with a suite of new primitive
  18355. operations for creating and using values of type \code{PVector}.
  18356. %We don't need to introduce a new type to represent tuple proxies.
  18357. A proxy is represented by a tuple containing three things: 1) the
  18358. underlying tuple, 2) a tuple of functions for casting elements that
  18359. are read from the tuple, and 3) a tuple of functions for casting
  18360. values to be written to the tuple. So we define the following
  18361. abbreviation for the type of a tuple proxy:
  18362. \[
  18363. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  18364. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  18365. \to (\key{PVector}~ T' \ldots)
  18366. \]
  18367. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  18368. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  18369. %
  18370. Next we describe each of the new primitive operations.
  18371. \begin{description}
  18372. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  18373. (\key{PVector} $T \ldots$)]\ \\
  18374. %
  18375. This operation brands a vector as a value of the \code{PVector} type.
  18376. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  18377. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  18378. %
  18379. This operation brands a vector proxy as value of the \code{PVector} type.
  18380. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  18381. \BOOLTY{}] \ \\
  18382. %
  18383. This returns true if the value is a tuple proxy and false if it is a
  18384. real tuple.
  18385. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  18386. (\key{Vector} $T \ldots$)]\ \\
  18387. %
  18388. Assuming that the input is a tuple, this operation returns the
  18389. tuple.
  18390. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  18391. $\to$ \BOOLTY{}]\ \\
  18392. %
  18393. Given a tuple proxy, this operation returns the length of the tuple.
  18394. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  18395. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  18396. %
  18397. Given a tuple proxy, this operation returns the $i$th element of the
  18398. tuple.
  18399. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  18400. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  18401. Given a tuple proxy, this operation writes a value to the $i$th element
  18402. of the tuple.
  18403. \end{description}
  18404. Now to discuss the translation that differentiates tuples from
  18405. proxies. First, every type annotation in the program is translated
  18406. (recursively) to replace \code{Vector} with \code{PVector}. Next, we
  18407. insert uses of \code{PVector} operations in the appropriate
  18408. places. For example, we wrap every tuple creation with an
  18409. \code{inject-vector}.
  18410. \begin{lstlisting}
  18411. (vector |$e_1 \ldots e_n$|)
  18412. |$\Rightarrow$|
  18413. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  18414. \end{lstlisting}
  18415. The \code{raw-vector} operator that we introduced in the previous
  18416. section does not get injected.
  18417. \begin{lstlisting}
  18418. (raw-vector |$e_1 \ldots e_n$|)
  18419. |$\Rightarrow$|
  18420. (vector |$e'_1 \ldots e'_n$|)
  18421. \end{lstlisting}
  18422. The \code{vector-proxy} primitive translates as follows.
  18423. \begin{lstlisting}
  18424. (vector-proxy |$e_1~e_2~e_3$|)
  18425. |$\Rightarrow$|
  18426. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  18427. \end{lstlisting}
  18428. We translate the tuple operations into conditional expressions that
  18429. check whether the value is a proxy and then dispatch to either the
  18430. appropriate proxy tuple operation or the regular tuple operation.
  18431. For example, the following is the translation for \code{vector-ref}.
  18432. \begin{lstlisting}
  18433. (vector-ref |$e_1$| |$i$|)
  18434. |$\Rightarrow$|
  18435. (let ([|$v~e_1$|])
  18436. (if (proxy? |$v$|)
  18437. (proxy-vector-ref |$v$| |$i$|)
  18438. (vector-ref (project-vector |$v$|) |$i$|)
  18439. \end{lstlisting}
  18440. Note in the case of a real tuple, we must apply \code{project-vector}
  18441. before the \code{vector-ref}.
  18442. \section{Reveal Casts}
  18443. \label{sec:reveal-casts-gradual}
  18444. Recall that the \code{reveal-casts} pass
  18445. (Section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  18446. \code{Inject} and \code{Project} into lower-level operations. In
  18447. particular, \code{Project} turns into a conditional expression that
  18448. inspects the tag and retrieves the underlying value. Here we need to
  18449. augment the translation of \code{Project} to handle the situation when
  18450. the target type is \code{PVector}. Instead of using
  18451. \code{vector-length} we need to use \code{proxy-vector-length}.
  18452. \begin{lstlisting}
  18453. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  18454. |$\Rightarrow$|
  18455. (let |$\itm{tmp}$| |$e'$|
  18456. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  18457. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  18458. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  18459. (exit)))
  18460. \end{lstlisting}
  18461. \section{Closure Conversion}
  18462. \label{sec:closure-conversion-gradual}
  18463. The closure conversion pass only requires one minor adjustment. The
  18464. auxiliary function that translates type annotations needs to be
  18465. updated to handle the \code{PVector} type.
  18466. \section{Explicate Control}
  18467. \label{sec:explicate-control-gradual}
  18468. Update the \code{explicate\_control} pass to handle the new primitive
  18469. operations on the \code{PVector} type.
  18470. \section{Select Instructions}
  18471. \label{sec:select-instructions-gradual}
  18472. Recall that the \code{select\_instructions} pass is responsible for
  18473. lowering the primitive operations into x86 instructions. So we need
  18474. to translate the new \code{PVector} operations to x86. To do so, the
  18475. first question we need to answer is how to differentiate the two
  18476. kinds of values (tuples and proxies) that can inhabit \code{PVector}.
  18477. We need just one bit to accomplish this, and use the bit in position
  18478. $57$ of the 64-bit tag at the front of every tuple (see
  18479. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  18480. for \code{inject-vector} we leave it that way.
  18481. \begin{lstlisting}
  18482. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  18483. |$\Rightarrow$|
  18484. movq |$e'_1$|, |$\itm{lhs'}$|
  18485. \end{lstlisting}
  18486. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  18487. \begin{lstlisting}
  18488. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  18489. |$\Rightarrow$|
  18490. movq |$e'_1$|, %r11
  18491. movq |$(1 << 57)$|, %rax
  18492. orq 0(%r11), %rax
  18493. movq %rax, 0(%r11)
  18494. movq %r11, |$\itm{lhs'}$|
  18495. \end{lstlisting}
  18496. The \code{proxy?} operation consumes the information so carefully
  18497. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  18498. isolates the $57$th bit to tell whether the value is a real tuple or
  18499. a proxy.
  18500. \begin{lstlisting}
  18501. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  18502. |$\Rightarrow$|
  18503. movq |$e_1'$|, %r11
  18504. movq 0(%r11), %rax
  18505. sarq $57, %rax
  18506. andq $1, %rax
  18507. movq %rax, |$\itm{lhs'}$|
  18508. \end{lstlisting}
  18509. The \code{project-vector} operation is straightforward to translate,
  18510. so we leave it up to the reader.
  18511. Regarding the \code{proxy-vector} operations, the runtime provides
  18512. procedures that implement them (they are recursive functions!) so
  18513. here we simply need to translate these tuple operations into the
  18514. appropriate function call. For example, here is the translation for
  18515. \code{proxy-vector-ref}.
  18516. \begin{lstlisting}
  18517. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  18518. |$\Rightarrow$|
  18519. movq |$e_1'$|, %rdi
  18520. movq |$e_2'$|, %rsi
  18521. callq proxy_vector_ref
  18522. movq %rax, |$\itm{lhs'}$|
  18523. \end{lstlisting}
  18524. We have another batch of tuple operations to deal with, those for the
  18525. \CANYTY{} type. Recall that the type checker for \LangGrad{}
  18526. generates an \code{any-vector-ref} when there is a \code{vector-ref}
  18527. on something of type \CANYTY{}, and similarly for
  18528. \code{any-vector-set!} and \code{any-vector-length}
  18529. (Figure~\ref{fig:type-check-Lgradual-1}). In
  18530. Section~\ref{sec:select-Lany} we selected instructions for these
  18531. operations based on the idea that the underlying value was a real
  18532. tuple. But in the current setting, the underlying value is of type
  18533. \code{PVector}. So \code{any-vector-ref} can be translated follows. We
  18534. begin by projecting the underlying value out of the tagged value and
  18535. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  18536. \begin{lstlisting}
  18537. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18538. movq |$\neg 111$|, %rdi
  18539. andq |$e_1'$|, %rdi
  18540. movq |$e_2'$|, %rsi
  18541. callq proxy_vector_ref
  18542. movq %rax, |$\itm{lhs'}$|
  18543. \end{lstlisting}
  18544. The \code{any-vector-set!} and \code{any-vector-length} operators can
  18545. be translated in a similar way.
  18546. \begin{exercise}\normalfont\normalsize
  18547. Implement a compiler for the gradually-typed \LangGrad{} language by
  18548. extending and adapting your compiler for \LangLam{}. Create 10 new
  18549. partially-typed test programs. In addition to testing with these
  18550. new programs, also test your compiler on all the tests for \LangLam{}
  18551. and tests for \LangDyn{}. Sometimes you may get a type checking error
  18552. on the \LangDyn{} programs but you can adapt them by inserting
  18553. a cast to the \CANYTY{} type around each subexpression
  18554. causing a type error. While \LangDyn{} does not have explicit casts,
  18555. you can induce one by wrapping the subexpression \code{e}
  18556. with a call to an un-annotated identity function, like this:
  18557. \code{((lambda (x) x) e)}.
  18558. \end{exercise}
  18559. \begin{figure}[p]
  18560. \begin{tcolorbox}[colback=white]
  18561. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18562. \node (Lgradual) at (9,4) {\large \LangGrad{}};
  18563. \node (Lgradualp) at (6,4) {\large \LangCast{}};
  18564. \node (Llambdapp) at (3,4) {\large \LangProxy{}};
  18565. \node (Llambdaproxy) at (0,4) {\large \LangPVec{}};
  18566. \node (Llambdaproxy-2) at (0,2) {\large \LangPVec{}};
  18567. \node (Llambdaproxy-3) at (3,2) {\large \LangPVec{}};
  18568. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  18569. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  18570. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  18571. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  18572. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  18573. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  18574. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  18575. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  18576. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  18577. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  18578. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  18579. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  18580. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  18581. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  18582. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  18583. \path[->,bend right=15] (Lgradual) edge [above] node
  18584. {\ttfamily\footnotesize type\_check} (Lgradualp);
  18585. \path[->,bend right=15] (Lgradualp) edge [above] node
  18586. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  18587. \path[->,bend right=15] (Llambdapp) edge [above] node
  18588. {\ttfamily\footnotesize differentiate.} (Llambdaproxy);
  18589. \path[->,bend left=15] (Llambdaproxy) edge [right] node
  18590. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  18591. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  18592. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  18593. \path[->,bend left=15] (Llambdaproxy-3) edge [above] node
  18594. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  18595. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  18596. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  18597. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  18598. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  18599. \path[->,bend left=15] (F1-1) edge [left] node
  18600. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  18601. \path[->,bend left=15] (F1-2) edge [below] node
  18602. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  18603. \path[->,bend right=15] (F1-3) edge [above] node
  18604. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  18605. \path[->,bend right=15] (F1-4) edge [above] node
  18606. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18607. \path[->,bend right=15] (F1-5) edge [above] node
  18608. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  18609. \path[->,bend right=15] (F1-6) edge [right] node
  18610. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18611. \path[->,bend left=15] (C3-2) edge [left] node
  18612. {\ttfamily\footnotesize select\_instr.} (x86-2);
  18613. \path[->,bend right=15] (x86-2) edge [left] node
  18614. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18615. \path[->,bend right=15] (x86-2-1) edge [below] node
  18616. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  18617. \path[->,bend right=15] (x86-2-2) edge [left] node
  18618. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  18619. \path[->,bend left=15] (x86-3) edge [above] node
  18620. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  18621. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  18622. \end{tikzpicture}
  18623. \end{tcolorbox}
  18624. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  18625. \label{fig:Lgradual-passes}
  18626. \end{figure}
  18627. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  18628. needed for the compilation of \LangGrad{}.
  18629. \section{Further Reading}
  18630. This chapter just scratches the surface of gradual typing. The basic
  18631. approach described here is missing two key ingredients that one would
  18632. want in a implementation of gradual typing: blame
  18633. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  18634. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  18635. problem addressed by blame tracking is that when a cast on a
  18636. higher-order value fails, it often does so at a point in the program
  18637. that is far removed from the original cast. Blame tracking is a
  18638. technique for propagating extra information through casts and proxies
  18639. so that when a cast fails, the error message can point back to the
  18640. original location of the cast in the source program.
  18641. The problem addressed by space-efficient casts also relates to
  18642. higher-order casts. It turns out that in partially typed programs, a
  18643. function or tuple can flow through very-many casts at runtime. With
  18644. the approach described in this chapter, each cast adds another
  18645. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  18646. considerable space, but it also makes the function calls and tuple
  18647. operations slow. For example, a partially-typed version of quicksort
  18648. could, in the worst case, build a chain of proxies of length $O(n)$
  18649. around the tuple, changing the overall time complexity of the
  18650. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  18651. solution to this problem by representing casts using the coercion
  18652. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  18653. long chains of proxies by compressing them into a concise normal
  18654. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  18655. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  18656. the Grift compiler.
  18657. \begin{center}
  18658. \url{https://github.com/Gradual-Typing/Grift}
  18659. \end{center}
  18660. There are also interesting interactions between gradual typing and
  18661. other language features, such as parametetric polymorphism,
  18662. information-flow types, and type inference, to name a few. We
  18663. recommend the reader to the online gradual typing bibliography:
  18664. \begin{center}
  18665. \url{http://samth.github.io/gradual-typing-bib/}
  18666. \end{center}
  18667. % TODO: challenge problem:
  18668. % type analysis and type specialization?
  18669. % coercions?
  18670. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18671. \chapter{Parametric Polymorphism}
  18672. \label{ch:Lpoly}
  18673. \index{subject}{parametric polymorphism}
  18674. \index{subject}{generics}
  18675. \if\edition\pythonEd
  18676. UNDER CONSTRUCTION
  18677. \fi
  18678. \if\edition\racketEd
  18679. This chapter studies the compilation of parametric
  18680. polymorphism\index{subject}{parametric polymorphism}
  18681. (aka. generics\index{subject}{generics}), compiling the \LangPoly{}
  18682. subset of Typed Racket. Parametric polymorphism enables programmers to
  18683. make code more reusable by parameterizing functions and data
  18684. structures with respect to the types that they operate on. For
  18685. example, Figure~\ref{fig:map-poly} revisits the \code{map} example but
  18686. this time gives it a more fitting type. This \code{map} function is
  18687. parameterized with respect to the element type of the tuple. The type
  18688. of \code{map} is the following polymorphic type as specified by the
  18689. \code{All} and the type parameter \code{a}.
  18690. \begin{lstlisting}
  18691. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18692. \end{lstlisting}
  18693. The idea is that \code{map} can be used at \emph{all} choices of a
  18694. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  18695. \code{map} to a tuple of integers, a choice of \code{Integer} for
  18696. \code{a}, but we could have just as well applied \code{map} to a tuple
  18697. of Booleans.
  18698. \begin{figure}[tbp]
  18699. % poly_test_2.rkt
  18700. \begin{tcolorbox}[colback=white]
  18701. \begin{lstlisting}
  18702. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  18703. (define (map f v)
  18704. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18705. (define (inc [x : Integer]) : Integer (+ x 1))
  18706. (vector-ref (map inc (vector 0 41)) 1)
  18707. \end{lstlisting}
  18708. \end{tcolorbox}
  18709. \caption{The \code{map} example using parametric polymorphism.}
  18710. \label{fig:map-poly}
  18711. \end{figure}
  18712. Figure~\ref{fig:Lpoly-concrete-syntax} defines the concrete syntax of
  18713. \LangPoly{} and Figure~\ref{fig:Lpoly-syntax} defines the abstract
  18714. syntax. We add a second form for function definitions in which a type
  18715. declaration comes before the \code{define}. In the abstract syntax,
  18716. the return type in the \code{Def} is \CANYTY{}, but that should be
  18717. ignored in favor of the return type in the type declaration. (The
  18718. \CANYTY{} comes from using the same parser as in
  18719. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  18720. enables the use of an \code{All} type for a function, thereby making
  18721. it polymorphic. The grammar for types is extended to include
  18722. polymorphic types and type variables.
  18723. \newcommand{\LpolyGrammarRacket}{
  18724. \begin{array}{lcl}
  18725. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18726. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  18727. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  18728. \end{array}
  18729. }
  18730. \newcommand{\LpolyASTRacket}{
  18731. \begin{array}{lcl}
  18732. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18733. \Def &::=& \DECL{\Var}{\Type} \\
  18734. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  18735. \end{array}
  18736. }
  18737. \begin{figure}[tp]
  18738. \centering
  18739. \begin{tcolorbox}[colback=white]
  18740. \footnotesize
  18741. \[
  18742. \begin{array}{l}
  18743. \gray{\LintGrammarRacket{}} \\ \hline
  18744. \gray{\LvarGrammarRacket{}} \\ \hline
  18745. \gray{\LifGrammarRacket{}} \\ \hline
  18746. \gray{\LwhileGrammarRacket} \\ \hline
  18747. \gray{\LtupGrammarRacket} \\ \hline
  18748. \gray{\LfunGrammarRacket} \\ \hline
  18749. \gray{\LlambdaGrammarRacket} \\ \hline
  18750. \LpolyGrammarRacket \\
  18751. \begin{array}{lcl}
  18752. \LangPoly{} &::=& \Def \ldots ~ \Exp
  18753. \end{array}
  18754. \end{array}
  18755. \]
  18756. \end{tcolorbox}
  18757. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  18758. (Figure~\ref{fig:Llam-concrete-syntax}).}
  18759. \label{fig:Lpoly-concrete-syntax}
  18760. \end{figure}
  18761. \begin{figure}[tp]
  18762. \centering
  18763. \begin{tcolorbox}[colback=white]
  18764. \footnotesize
  18765. \[
  18766. \begin{array}{l}
  18767. \gray{\LintOpAST} \\ \hline
  18768. \gray{\LvarASTRacket{}} \\ \hline
  18769. \gray{\LifASTRacket{}} \\ \hline
  18770. \gray{\LwhileASTRacket{}} \\ \hline
  18771. \gray{\LtupASTRacket{}} \\ \hline
  18772. \gray{\LfunASTRacket} \\ \hline
  18773. \gray{\LlambdaASTRacket} \\ \hline
  18774. \LpolyASTRacket \\
  18775. \begin{array}{lcl}
  18776. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18777. \end{array}
  18778. \end{array}
  18779. \]
  18780. \end{tcolorbox}
  18781. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  18782. (Figure~\ref{fig:Llam-syntax}).}
  18783. \label{fig:Lpoly-syntax}
  18784. \end{figure}
  18785. By including polymorphic types in the $\Type$ non-terminal we choose
  18786. to make them first-class which has interesting repercussions on the
  18787. compiler. Many languages with polymorphism, such as
  18788. C++~\citep{stroustrup88:_param_types} and Standard
  18789. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  18790. it may be helpful to see an example of first-class polymorphism in
  18791. action. In Figure~\ref{fig:apply-twice} we define a function
  18792. \code{apply-twice} whose parameter is a polymorphic function. The
  18793. occurrence of a polymorphic type underneath a function type is enabled
  18794. by the normal recursive structure of the grammar for $\Type$ and the
  18795. categorization of the \code{All} type as a $\Type$. The body of
  18796. \code{apply-twice} applies the polymorphic function to a Boolean and
  18797. to an integer.
  18798. \begin{figure}[tbp]
  18799. \begin{tcolorbox}[colback=white]
  18800. \begin{lstlisting}
  18801. (: apply-twice ((All (b) (b -> b)) -> Integer))
  18802. (define (apply-twice f)
  18803. (if (f #t) (f 42) (f 777)))
  18804. (: id (All (a) (a -> a)))
  18805. (define (id x) x)
  18806. (apply-twice id)
  18807. \end{lstlisting}
  18808. \end{tcolorbox}
  18809. \caption{An example illustrating first-class polymorphism.}
  18810. \label{fig:apply-twice}
  18811. \end{figure}
  18812. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  18813. three new responsibilities (compared to \LangLam{}). The type checking of
  18814. function application is extended to handle the case where the operator
  18815. expression is a polymorphic function. In that case the type arguments
  18816. are deduced by matching the type of the parameters with the types of
  18817. the arguments.
  18818. %
  18819. The \code{match-types} auxiliary function carries out this deduction
  18820. by recursively descending through a parameter type \code{pt} and the
  18821. corresponding argument type \code{at}, making sure that they are equal
  18822. except when there is a type parameter on the left (in the parameter
  18823. type). If it is the first time that the type parameter has been
  18824. encountered, then the algorithm deduces an association of the type
  18825. parameter to the corresponding type on the right (in the argument
  18826. type). If it is not the first time that the type parameter has been
  18827. encountered, the algorithm looks up its deduced type and makes sure
  18828. that it is equal to the type on the right.
  18829. %
  18830. Once the type arguments are deduced, the operator expression is
  18831. wrapped in an \code{Inst} AST node (for instantiate) that records the
  18832. type of the operator, but more importantly, records the deduced type
  18833. arguments. The return type of the application is the return type of
  18834. the polymorphic function, but with the type parameters replaced by the
  18835. deduced type arguments, using the \code{subst-type} function.
  18836. The second responsibility of the type checker to extend the
  18837. \code{type-equal?} function to handle the \code{All} type. This is
  18838. not quite as simple as for other types, such as function and tuple
  18839. types, because two polymorphic types can be syntactically different
  18840. even though they are equivalent types. For example, \code{(All (a) (a
  18841. -> a))} is equivalent to \code{(All (b) (b -> b))}. Two polymorphic
  18842. types should be considered equal if they differ only in the choice of
  18843. the names of the type parameters. The \code{type-equal?} function in
  18844. Figure~\ref{fig:type-check-Lvar0-aux} renames the type parameters of
  18845. the first type to match the type parameters of the second type.
  18846. The third responsibility of the type checker is to make sure that only
  18847. defined type variables appear in type annotations. The
  18848. \code{check-well-formed} function defined in
  18849. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  18850. sure that each type variable has been defined.
  18851. The output language of the type checker is \LangInst{}, defined in
  18852. Figure~\ref{fig:Lpoly-prime-syntax}. The type checker combines the type
  18853. declaration and polymorphic function into a single definition, using
  18854. the \code{Poly} form, to make polymorphic functions more convenient to
  18855. process in next pass of the compiler.
  18856. \begin{figure}[tp]
  18857. \centering
  18858. \begin{tcolorbox}[colback=white]
  18859. \small
  18860. \[
  18861. \begin{array}{lcl}
  18862. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18863. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  18864. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  18865. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  18866. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18867. \end{array}
  18868. \]
  18869. \end{tcolorbox}
  18870. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  18871. (Figure~\ref{fig:Llam-syntax}).}
  18872. \label{fig:Lpoly-prime-syntax}
  18873. \end{figure}
  18874. The output of the type checker on the polymorphic \code{map}
  18875. example is listed in Figure~\ref{fig:map-type-check}.
  18876. \begin{figure}[tbp]
  18877. % poly_test_2.rkt
  18878. \begin{tcolorbox}[colback=white]
  18879. \begin{lstlisting}
  18880. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  18881. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  18882. (define (inc [x : Integer]) : Integer (+ x 1))
  18883. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18884. (Integer))
  18885. inc (vector 0 41)) 1)
  18886. \end{lstlisting}
  18887. \end{tcolorbox}
  18888. \caption{Output of the type checker on the \code{map} example.}
  18889. \label{fig:map-type-check}
  18890. \end{figure}
  18891. \begin{figure}[tbp]
  18892. \begin{tcolorbox}[colback=white]
  18893. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18894. (define type-check-poly-class
  18895. (class type-check-Llambda-class
  18896. (super-new)
  18897. (inherit check-type-equal?)
  18898. (define/override (type-check-apply env e1 es)
  18899. (define-values (e^ ty) ((type-check-exp env) e1))
  18900. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  18901. ((type-check-exp env) e)))
  18902. (match ty
  18903. [`(,ty^* ... -> ,rt)
  18904. (for ([arg-ty ty*] [param-ty ty^*])
  18905. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  18906. (values e^ es^ rt)]
  18907. [`(All ,xs (,tys ... -> ,rt))
  18908. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18909. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  18910. (match-types env^^ param-ty arg-ty)))
  18911. (define targs
  18912. (for/list ([x xs])
  18913. (match (dict-ref env^^ x (lambda () #f))
  18914. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  18915. x (Apply e1 es))]
  18916. [ty ty])))
  18917. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  18918. [else (error 'type-check "expected a function, not ~a" ty)]))
  18919. (define/override ((type-check-exp env) e)
  18920. (match e
  18921. [(Lambda `([,xs : ,Ts] ...) rT body)
  18922. (for ([T Ts]) ((check-well-formed env) T))
  18923. ((check-well-formed env) rT)
  18924. ((super type-check-exp env) e)]
  18925. [(HasType e1 ty)
  18926. ((check-well-formed env) ty)
  18927. ((super type-check-exp env) e)]
  18928. [else ((super type-check-exp env) e)]))
  18929. (define/override ((type-check-def env) d)
  18930. (verbose 'type-check "poly/def" d)
  18931. (match d
  18932. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  18933. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  18934. (for ([p ps]) ((check-well-formed ts-env) p))
  18935. ((check-well-formed ts-env) rt)
  18936. (define new-env (append ts-env (map cons xs ps) env))
  18937. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18938. (check-type-equal? ty^ rt body)
  18939. (Generic ts (Def f p:t* rt info body^))]
  18940. [else ((super type-check-def env) d)]))
  18941. (define/override (type-check-program p)
  18942. (match p
  18943. [(Program info body)
  18944. (type-check-program (ProgramDefsExp info '() body))]
  18945. [(ProgramDefsExp info ds body)
  18946. (define ds^ (combine-decls-defs ds))
  18947. (define new-env (for/list ([d ds^])
  18948. (cons (def-name d) (fun-def-type d))))
  18949. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  18950. (define-values (body^ ty) ((type-check-exp new-env) body))
  18951. (check-type-equal? ty 'Integer body)
  18952. (ProgramDefsExp info ds^^ body^)]))
  18953. ))
  18954. \end{lstlisting}
  18955. \end{tcolorbox}
  18956. \caption{Type checker for the \LangPoly{} language.}
  18957. \label{fig:type-check-Lvar0}
  18958. \end{figure}
  18959. \begin{figure}[tbp]
  18960. \begin{tcolorbox}[colback=white]
  18961. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18962. (define/override (type-equal? t1 t2)
  18963. (match* (t1 t2)
  18964. [(`(All ,xs ,T1) `(All ,ys ,T2))
  18965. (define env (map cons xs ys))
  18966. (type-equal? (subst-type env T1) T2)]
  18967. [(other wise)
  18968. (super type-equal? t1 t2)]))
  18969. (define/public (match-types env pt at)
  18970. (match* (pt at)
  18971. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  18972. [('Void 'Void) env] [('Any 'Any) env]
  18973. [(`(Vector ,pts ...) `(Vector ,ats ...))
  18974. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  18975. (match-types env^ pt1 at1))]
  18976. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  18977. (define env^ (match-types env prt art))
  18978. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  18979. (match-types env^^ pt1 at1))]
  18980. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  18981. (define env^ (append (map cons pxs axs) env))
  18982. (match-types env^ pt1 at1)]
  18983. [((? symbol? x) at)
  18984. (match (dict-ref env x (lambda () #f))
  18985. [#f (error 'type-check "undefined type variable ~a" x)]
  18986. ['Type (cons (cons x at) env)]
  18987. [t^ (check-type-equal? at t^ 'matching) env])]
  18988. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  18989. (define/public (subst-type env pt)
  18990. (match pt
  18991. ['Integer 'Integer] ['Boolean 'Boolean]
  18992. ['Void 'Void] ['Any 'Any]
  18993. [`(Vector ,ts ...)
  18994. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  18995. [`(,ts ... -> ,rt)
  18996. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  18997. [`(All ,xs ,t)
  18998. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  18999. [(? symbol? x) (dict-ref env x)]
  19000. [else (error 'type-check "expected a type not ~a" pt)]))
  19001. (define/public (combine-decls-defs ds)
  19002. (match ds
  19003. ['() '()]
  19004. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  19005. (unless (equal? name f)
  19006. (error 'type-check "name mismatch, ~a != ~a" name f))
  19007. (match type
  19008. [`(All ,xs (,ps ... -> ,rt))
  19009. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19010. (cons (Generic xs (Def name params^ rt info body))
  19011. (combine-decls-defs ds^))]
  19012. [`(,ps ... -> ,rt)
  19013. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19014. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  19015. [else (error 'type-check "expected a function type, not ~a" type) ])]
  19016. [`(,(Def f params rt info body) . ,ds^)
  19017. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  19018. \end{lstlisting}
  19019. \end{tcolorbox}
  19020. \caption{Auxiliary functions for type checking \LangPoly{}.}
  19021. \label{fig:type-check-Lvar0-aux}
  19022. \end{figure}
  19023. \begin{figure}[tbp]
  19024. \begin{tcolorbox}[colback=white]
  19025. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  19026. (define/public ((check-well-formed env) ty)
  19027. (match ty
  19028. ['Integer (void)]
  19029. ['Boolean (void)]
  19030. ['Void (void)]
  19031. [(? symbol? a)
  19032. (match (dict-ref env a (lambda () #f))
  19033. ['Type (void)]
  19034. [else (error 'type-check "undefined type variable ~a" a)])]
  19035. [`(Vector ,ts ...)
  19036. (for ([t ts]) ((check-well-formed env) t))]
  19037. [`(,ts ... -> ,t)
  19038. (for ([t ts]) ((check-well-formed env) t))
  19039. ((check-well-formed env) t)]
  19040. [`(All ,xs ,t)
  19041. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19042. ((check-well-formed env^) t)]
  19043. [else (error 'type-check "unrecognized type ~a" ty)]))
  19044. \end{lstlisting}
  19045. \end{tcolorbox}
  19046. \caption{Well-formed types.}
  19047. \label{fig:well-formed-types}
  19048. \end{figure}
  19049. % TODO: interpreter for R'_10
  19050. \clearpage
  19051. \section{Compiling Polymorphism}
  19052. \label{sec:compiling-poly}
  19053. Broadly speaking, there are four approaches to compiling parametric
  19054. polymorphism, which we describe below.
  19055. \begin{description}
  19056. \item[Monomorphization] generates a different version of a polymorphic
  19057. function for each set of type arguments that it is used with,
  19058. producing type-specialized code. This approach results in the most
  19059. efficient code but requires whole-program compilation (no separate
  19060. compilation) and increases code size. For our current purposes
  19061. monomorphization is a non-starter because, with first-class
  19062. polymorphism, it is sometimes not possible to determine which
  19063. generic functions are used with which type arguments during
  19064. compilation. (It can be done at runtime, with just-in-time
  19065. compilation.) Monomorphization is used to compile C++
  19066. templates~\citep{stroustrup88:_param_types} and polymorphic
  19067. functions in NESL~\citep{Blelloch:1993aa} and
  19068. ML~\citep{Weeks:2006aa}.
  19069. \item[Uniform representation] generates one version of each
  19070. polymorphic function but requires all values to have a common
  19071. ``boxed'' format, such as the tagged values of type \CANYTY{} in
  19072. \LangAny{}. Both polymorphic and non-polymorphic (i.e. monomorphic)
  19073. code is compiled similarly to code in a dynamically typed language
  19074. (like \LangDyn{}), in which primitive operators require their
  19075. arguments to be projected from \CANYTY{} and their results are
  19076. injected into \CANYTY{}. (In object-oriented languages, the
  19077. projection is accomplished via virtual method dispatch.) The uniform
  19078. representation approach is compatible with separate compilation and
  19079. with first-class polymorphism. However, it produces the
  19080. least-efficient code because it introduces overhead in the entire
  19081. program. This approach is used in implementations of
  19082. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  19083. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  19084. Java~\citep{Bracha:1998fk}.
  19085. \item[Mixed representation] generates one version of each polymorphic
  19086. function, using a boxed representation for type
  19087. variables. Monomorphic code is compiled as usual (as in \LangLam{})
  19088. and conversions are performed at the boundaries between monomorphic
  19089. and polymorphic (e.g. when a polymorphic function is instantiated
  19090. and called). This approach is compatible with separate compilation
  19091. and first-class polymorphism and maintains efficiency in monomorphic
  19092. code. The trade off is increased overhead at the boundary between
  19093. monomorphic and polymorphic code. This approach is used in
  19094. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  19095. Java 5 with the addition of autoboxing.
  19096. \item[Type passing] uses the unboxed representation in both
  19097. monomorphic and polymorphic code. Each polymorphic function is
  19098. compiled to a single function with extra parameters that describe
  19099. the type arguments. The type information is used by the generated
  19100. code to know how to access the unboxed values at runtime. This
  19101. approach is used in implementation of the Napier88
  19102. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  19103. passing is compatible with separate compilation and first-class
  19104. polymorphism and maintains the efficiency for monomorphic
  19105. code. There is runtime overhead in polymorphic code from dispatching
  19106. on type information.
  19107. \end{description}
  19108. In this chapter we use the mixed representation approach, partly
  19109. because of its favorable attributes, and partly because it is
  19110. straightforward to implement using the tools that we have already
  19111. built to support gradual typing. To compile polymorphic functions, we
  19112. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  19113. \LangCast{}.
  19114. \section{Erase Types}
  19115. \label{sec:erase-types}
  19116. We use the \CANYTY{} type from Chapter~\ref{ch:Ldyn} to
  19117. represent type variables. For example, Figure~\ref{fig:map-erase}
  19118. shows the output of the \code{erase-types} pass on the polymorphic
  19119. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  19120. type parameter \code{a} are replaced by \CANYTY{} and the polymorphic
  19121. \code{All} types are removed from the type of \code{map}.
  19122. \begin{figure}[tbp]
  19123. \begin{tcolorbox}[colback=white]
  19124. \begin{lstlisting}
  19125. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  19126. : (Vector Any Any)
  19127. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19128. (define (inc [x : Integer]) : Integer (+ x 1))
  19129. (vector-ref ((cast map
  19130. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  19131. ((Integer -> Integer) (Vector Integer Integer)
  19132. -> (Vector Integer Integer)))
  19133. inc (vector 0 41)) 1)
  19134. \end{lstlisting}
  19135. \end{tcolorbox}
  19136. \caption{The polymorphic \code{map} example after type erasure.}
  19137. \label{fig:map-erase}
  19138. \end{figure}
  19139. This process of type erasure creates a challenge at points of
  19140. instantiation. For example, consider the instantiation of
  19141. \code{map} in Figure~\ref{fig:map-type-check}.
  19142. The type of \code{map} is
  19143. \begin{lstlisting}
  19144. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  19145. \end{lstlisting}
  19146. and it is instantiated to
  19147. \begin{lstlisting}
  19148. ((Integer -> Integer) (Vector Integer Integer)
  19149. -> (Vector Integer Integer))
  19150. \end{lstlisting}
  19151. After erasure, the type of \code{map} is
  19152. \begin{lstlisting}
  19153. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  19154. \end{lstlisting}
  19155. but we need to convert it to the instantiated type. This is easy to
  19156. do in the language \LangCast{} with a single \code{cast}. In
  19157. Figure~\ref{fig:map-erase}, the instantiation of \code{map} has been
  19158. compiled to a \code{cast} from the type of \code{map} to the
  19159. instantiated type. The source and target type of a cast must be
  19160. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  19161. because both the source and target are obtained from the same
  19162. polymorphic type of \code{map}, replacing the type parameters with
  19163. \CANYTY{} in the former and with the deduced type arguments in the
  19164. later. (Recall that the \CANYTY{} type is consistent with any type.)
  19165. To implement the \code{erase-types} pass, we recommend defining a
  19166. recursive auxiliary function named \code{erase-type} that applies the
  19167. following two transformations. It replaces type variables with
  19168. \CANYTY{}
  19169. \begin{lstlisting}
  19170. |$x$|
  19171. |$\Rightarrow$|
  19172. Any
  19173. \end{lstlisting}
  19174. and it removes the polymorphic \code{All} types.
  19175. \begin{lstlisting}
  19176. (All |$xs$| |$T_1$|)
  19177. |$\Rightarrow$|
  19178. |$T'_1$|
  19179. \end{lstlisting}
  19180. Apply the \code{erase-type} function to all of the type annotations in
  19181. the program.
  19182. Regarding the translation of expressions, the case for \code{Inst} is
  19183. the interesting one. We translate it into a \code{Cast}, as shown
  19184. below. The type of the subexpression $e$ is the polymorphic type
  19185. $\LP\key{All}~\itm{xs}~T\RP$. The source type of the cast is the erasure of
  19186. $T$, the type $T'$. The target type $T''$ is the result of
  19187. substituting the argument types $ts$ for the type parameters $xs$ in
  19188. $T$ followed by doing type erasure.
  19189. \begin{lstlisting}
  19190. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  19191. |$\Rightarrow$|
  19192. (Cast |$e'$| |$T'$| |$T''$|)
  19193. \end{lstlisting}
  19194. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  19195. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  19196. Finally, each polymorphic function is translated to a regular
  19197. function in which type erasure has been applied to all the type
  19198. annotations and the body.
  19199. \begin{lstlisting}
  19200. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  19201. |$\Rightarrow$|
  19202. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  19203. \end{lstlisting}
  19204. \begin{exercise}\normalfont\normalsize
  19205. Implement a compiler for the polymorphic language \LangPoly{} by
  19206. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  19207. programs that use polymorphic functions. Some of them should make
  19208. use of first-class polymorphism.
  19209. \end{exercise}
  19210. \begin{figure}[p]
  19211. \begin{tcolorbox}[colback=white]
  19212. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  19213. \node (Lpoly) at (12,4) {\large \LangPoly{}};
  19214. \node (Lpolyp) at (9,4) {\large \LangInst{}};
  19215. \node (Lgradualp) at (6,4) {\large \LangCast{}};
  19216. \node (Llambdapp) at (3,4) {\large \LangProxy{}};
  19217. \node (Llambdaproxy) at (0,4) {\large \LangPVec{}};
  19218. \node (Llambdaproxy-2) at (0,2) {\large \LangPVec{}};
  19219. \node (Llambdaproxy-3) at (3,2) {\large \LangPVec{}};
  19220. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  19221. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  19222. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  19223. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  19224. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  19225. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  19226. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  19227. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  19228. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  19229. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  19230. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  19231. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  19232. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  19233. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  19234. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  19235. \path[->,bend right=15] (Lpoly) edge [above] node
  19236. {\ttfamily\footnotesize type\_check} (Lpolyp);
  19237. \path[->,bend right=15] (Lpolyp) edge [above] node
  19238. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  19239. \path[->,bend right=15] (Lgradualp) edge [above] node
  19240. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  19241. \path[->,bend right=15] (Llambdapp) edge [above] node
  19242. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  19243. \path[->,bend right=15] (Llambdaproxy) edge [right] node
  19244. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  19245. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  19246. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  19247. \path[->,bend left=15] (Llambdaproxy-3) edge [above] node
  19248. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  19249. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  19250. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  19251. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  19252. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  19253. \path[->,bend left=15] (F1-1) edge [left] node
  19254. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  19255. \path[->,bend left=15] (F1-2) edge [below] node
  19256. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  19257. \path[->,bend right=15] (F1-3) edge [above] node
  19258. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  19259. \path[->,bend right=15] (F1-4) edge [above] node
  19260. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  19261. \path[->,bend right=15] (F1-5) edge [above] node
  19262. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  19263. \path[->,bend right=15] (F1-6) edge [right] node
  19264. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19265. \path[->,bend left=15] (C3-2) edge [left] node
  19266. {\ttfamily\footnotesize select\_instr.} (x86-2);
  19267. \path[->,bend right=15] (x86-2) edge [left] node
  19268. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  19269. \path[->,bend right=15] (x86-2-1) edge [below] node
  19270. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  19271. \path[->,bend right=15] (x86-2-2) edge [left] node
  19272. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  19273. \path[->,bend left=15] (x86-3) edge [above] node
  19274. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  19275. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  19276. \end{tikzpicture}
  19277. \end{tcolorbox}
  19278. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  19279. \label{fig:Lpoly-passes}
  19280. \end{figure}
  19281. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  19282. needed to compile \LangPoly{}.
  19283. % TODO: challenge problem: specialization of instantiations
  19284. % Further Reading
  19285. \fi
  19286. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  19287. \clearpage
  19288. \appendix
  19289. \chapter{Appendix}
  19290. \if\edition\racketEd
  19291. \section{Interpreters}
  19292. \label{appendix:interp}
  19293. \index{subject}{interpreter}
  19294. We provide interpreters for each of the source languages \LangInt{},
  19295. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  19296. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  19297. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  19298. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  19299. and x86 are in the \key{interp.rkt} file.
  19300. \section{Utility Functions}
  19301. \label{appendix:utilities}
  19302. The utility functions described in this section are in the
  19303. \key{utilities.rkt} file of the support code.
  19304. \paragraph{\code{interp-tests}}
  19305. The \key{interp-tests} function runs the compiler passes and the
  19306. interpreters on each of the specified tests to check whether each pass
  19307. is correct. The \key{interp-tests} function has the following
  19308. parameters:
  19309. \begin{description}
  19310. \item[name (a string)] a name to identify the compiler,
  19311. \item[typechecker] a function of exactly one argument that either
  19312. raises an error using the \code{error} function when it encounters a
  19313. type error, or returns \code{\#f} when it encounters a type
  19314. error. If there is no type error, the type checker returns the
  19315. program.
  19316. \item[passes] a list with one entry per pass. An entry is a list with
  19317. four things:
  19318. \begin{enumerate}
  19319. \item a string giving the name of the pass,
  19320. \item the function that implements the pass (a translator from AST
  19321. to AST),
  19322. \item a function that implements the interpreter (a function from
  19323. AST to result value) for the output language,
  19324. \item and a type checker for the output language. Type checkers for
  19325. the $R$ and $C$ languages are provided in the support code. For
  19326. example, the type checkers for \LangVar{} and \LangCVar{} are in
  19327. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  19328. type checker entry is optional. The support code does not provide
  19329. type checkers for the x86 languages.
  19330. \end{enumerate}
  19331. \item[source-interp] an interpreter for the source language. The
  19332. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  19333. \item[test-family (a string)] for example, \code{"var"}, \code{"cond"}, etc.
  19334. \item[tests] a list of test numbers that specifies which tests to
  19335. run. (see below)
  19336. \end{description}
  19337. %
  19338. The \key{interp-tests} function assumes that the subdirectory
  19339. \key{tests} has a collection of Racket programs whose names all start
  19340. with the family name, followed by an underscore and then the test
  19341. number, ending with the file extension \key{.rkt}. Also, for each test
  19342. program that calls \code{read} one or more times, there is a file with
  19343. the same name except that the file extension is \key{.in} that
  19344. provides the input for the Racket program. If the test program is
  19345. expected to fail type checking, then there should be an empty file of
  19346. the same name but with extension \key{.tyerr}.
  19347. \paragraph{\code{compiler-tests}}
  19348. runs the compiler passes to generate x86 (a \key{.s} file) and then
  19349. runs the GNU C compiler (gcc) to generate machine code. It runs the
  19350. machine code and checks that the output is $42$. The parameters to the
  19351. \code{compiler-tests} function are similar to those of the
  19352. \code{interp-tests} function, and consist of
  19353. \begin{itemize}
  19354. \item a compiler name (a string),
  19355. \item a type checker,
  19356. \item description of the passes,
  19357. \item name of a test-family, and
  19358. \item a list of test numbers.
  19359. \end{itemize}
  19360. \paragraph{\code{compile-file}}
  19361. takes a description of the compiler passes (see the comment for
  19362. \key{interp-tests}) and returns a function that, given a program file
  19363. name (a string ending in \key{.rkt}), applies all of the passes and
  19364. writes the output to a file whose name is the same as the program file
  19365. name but with \key{.rkt} replaced with \key{.s}.
  19366. \paragraph{\code{read-program}}
  19367. takes a file path and parses that file (it must be a Racket program)
  19368. into an abstract syntax tree.
  19369. \paragraph{\code{parse-program}}
  19370. takes an S-expression representation of an abstract syntax tree and converts it into
  19371. the struct-based representation.
  19372. \paragraph{\code{assert}}
  19373. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  19374. and displays the message \key{msg} if the Boolean \key{bool} is false.
  19375. \paragraph{\code{lookup}}
  19376. % remove discussion of lookup? -Jeremy
  19377. takes a key and an alist, and returns the first value that is
  19378. associated with the given key, if there is one. If not, an error is
  19379. triggered. The alist may contain both immutable pairs (built with
  19380. \key{cons}) and mutable pairs (built with \key{mcons}).
  19381. %The \key{map2} function ...
  19382. \fi %\racketEd
  19383. \section{x86 Instruction Set Quick-Reference}
  19384. \label{sec:x86-quick-reference}
  19385. \index{subject}{x86}
  19386. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  19387. do. We write $A \to B$ to mean that the value of $A$ is written into
  19388. location $B$. Address offsets are given in bytes. The instruction
  19389. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  19390. registers (such as \code{\%rax}), or memory references (such as
  19391. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  19392. reference per instruction. Other operands must be immediates or
  19393. registers.
  19394. \begin{table}[tbp]
  19395. \centering
  19396. \begin{tabular}{l|l}
  19397. \textbf{Instruction} & \textbf{Operation} \\ \hline
  19398. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  19399. \texttt{negq} $A$ & $- A \to A$ \\
  19400. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  19401. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  19402. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  19403. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  19404. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  19405. \texttt{retq} & Pops the return address and jumps to it \\
  19406. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  19407. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  19408. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  19409. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  19410. be an immediate) \\
  19411. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  19412. matches the condition code of the instruction, otherwise go to the
  19413. next instructions. The condition codes are \key{e} for ``equal'',
  19414. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  19415. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  19416. \texttt{jl} $L$ & \\
  19417. \texttt{jle} $L$ & \\
  19418. \texttt{jg} $L$ & \\
  19419. \texttt{jge} $L$ & \\
  19420. \texttt{jmp} $L$ & Jump to label $L$ \\
  19421. \texttt{movq} $A$, $B$ & $A \to B$ \\
  19422. \texttt{movzbq} $A$, $B$ &
  19423. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  19424. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  19425. and the extra bytes of $B$ are set to zero.} \\
  19426. & \\
  19427. & \\
  19428. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  19429. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  19430. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  19431. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  19432. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  19433. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  19434. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  19435. description of the condition codes. $A$ must be a single byte register
  19436. (e.g., \texttt{al} or \texttt{cl}).} \\
  19437. \texttt{setl} $A$ & \\
  19438. \texttt{setle} $A$ & \\
  19439. \texttt{setg} $A$ & \\
  19440. \texttt{setge} $A$ &
  19441. \end{tabular}
  19442. \vspace{5pt}
  19443. \caption{Quick-reference for the x86 instructions used in this book.}
  19444. \label{tab:x86-instr}
  19445. \end{table}
  19446. %% \if\edition\racketEd
  19447. %% \cleardoublepage
  19448. %% \section{Concrete Syntax for Intermediate Languages}
  19449. %% The concrete syntax of \LangAny{} is defined in
  19450. %% Figure~\ref{fig:Lany-concrete-syntax}.
  19451. %% \begin{figure}[tp]
  19452. %% \centering
  19453. %% \fbox{
  19454. %% \begin{minipage}{0.97\textwidth}\small
  19455. %% \[
  19456. %% \begin{array}{lcl}
  19457. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  19458. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  19459. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  19460. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  19461. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  19462. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  19463. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  19464. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  19465. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  19466. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  19467. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  19468. %% \MID \LP\key{void?}\;\Exp\RP \\
  19469. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  19470. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  19471. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  19472. %% \end{array}
  19473. %% \]
  19474. %% \end{minipage}
  19475. %% }
  19476. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  19477. %% (Figure~\ref{fig:Llam-syntax}).}
  19478. %% \label{fig:Lany-concrete-syntax}
  19479. %% \end{figure}
  19480. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  19481. %% \LangCFun{} is defined in Figures~\ref{fig:c0-concrete-syntax},
  19482. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  19483. %% \ref{fig:c3-concrete-syntax}, respectively.
  19484. %% \begin{figure}[tbp]
  19485. %% \fbox{
  19486. %% \begin{minipage}{0.96\textwidth}
  19487. %% \small
  19488. %% \[
  19489. %% \begin{array}{lcl}
  19490. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  19491. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  19492. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  19493. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  19494. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  19495. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  19496. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  19497. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  19498. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  19499. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  19500. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  19501. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  19502. %% \end{array}
  19503. %% \]
  19504. %% \end{minipage}
  19505. %% }
  19506. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  19507. %% \label{fig:c2-concrete-syntax}
  19508. %% \end{figure}
  19509. %% \begin{figure}[tp]
  19510. %% \fbox{
  19511. %% \begin{minipage}{0.96\textwidth}
  19512. %% \small
  19513. %% \[
  19514. %% \begin{array}{lcl}
  19515. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  19516. %% \\
  19517. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  19518. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  19519. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  19520. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  19521. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  19522. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  19523. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  19524. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  19525. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  19526. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  19527. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  19528. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  19529. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  19530. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  19531. %% \LangCFunM{} & ::= & \Def\ldots
  19532. %% \end{array}
  19533. %% \]
  19534. %% \end{minipage}
  19535. %% }
  19536. %% \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  19537. %% \label{fig:c3-concrete-syntax}
  19538. %% \end{figure}
  19539. %% \fi % racketEd
  19540. \backmatter
  19541. \addtocontents{toc}{\vspace{11pt}}
  19542. %% \addtocontents{toc}{\vspace{11pt}}
  19543. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  19544. \nocite{*}\let\bibname\refname
  19545. \addcontentsline{toc}{fmbm}{\refname}
  19546. \printbibliography
  19547. %\printindex{authors}{Author Index}
  19548. \printindex{subject}{Subject Index}
  19549. \end{document}
  19550. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  19551. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  19552. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  19553. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  19554. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  19555. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  19556. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  19557. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  19558. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  19559. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  19560. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  19561. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  19562. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  19563. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  19564. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  19565. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  19566. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  19567. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  19568. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  19569. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  19570. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  19571. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  19572. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  19573. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  19574. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  19575. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  19576. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  19577. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  19578. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  19579. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  19580. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  19581. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  19582. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  19583. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  19584. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  19585. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  19586. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  19587. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  19588. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  19589. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  19590. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  19591. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  19592. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  19593. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  19594. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  19595. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  19596. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  19597. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  19598. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  19599. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  19600. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  19601. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  19602. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  19603. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  19604. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  19605. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  19606. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  19607. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  19608. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  19609. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  19610. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  19611. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  19612. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  19613. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  19614. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  19615. % LocalWords: notq setle setg setge