book.tex 773 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486
  1. \documentclass[7x10]{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} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  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. \numberwithin{theorem}{chapter}
  65. \numberwithin{definition}{chapter}
  66. \numberwithin{equation}{chapter}
  67. % Adjusted settings
  68. \setlength{\columnsep}{4pt}
  69. %% \begingroup
  70. %% \setlength{\intextsep}{0pt}%
  71. %% \setlength{\columnsep}{0pt}%
  72. %% \begin{wrapfigure}{r}{0.5\textwidth}
  73. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  74. %% \caption{Basic layout}
  75. %% \end{wrapfigure}
  76. %% \lipsum[1]
  77. %% \endgroup
  78. \newbox\oiintbox
  79. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  80. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  81. \def\oiint{\copy\oiintbox}
  82. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  83. %\usepackage{showframe}
  84. \def\ShowFrameLinethickness{0.125pt}
  85. \addbibresource{book.bib}
  86. \begin{document}
  87. \frontmatter
  88. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  89. \HalfTitle{Essentials of Compilation}
  90. \halftitlepage
  91. \Title{Essentials of Compilation}
  92. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  93. %\edition{First Edition}
  94. \BookAuthor{Jeremy G. Siek}
  95. \imprint{The MIT Press\\
  96. Cambridge, Massachusetts\\
  97. London, England}
  98. \begin{copyrightpage}
  99. \textcopyright\ 2023 Massachusetts Institute of Technology \\[2ex]
  100. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  101. Subject to such license, all rights are reserved. \\[2ex]
  102. \includegraphics{CCBY-logo}
  103. The MIT Press would like to thank the anonymous peer reviewers who
  104. provided comments on drafts of this book. The generous work of
  105. academic experts is essential for establishing the authority and
  106. quality of our publications. We acknowledge with gratitude the
  107. contributions of these otherwise uncredited readers.
  108. This book was set in Times LT Std Roman by the author. Printed and
  109. bound in the United States of America.
  110. Library of Congress Cataloging-in-Publication Data is available.
  111. ISBN:
  112. 10 9 8 7 6 5 4 3 2 1
  113. %% Jeremy G. Siek. Available for free viewing
  114. %% or personal downloading under the
  115. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  116. %% license.
  117. %% Copyright in this monograph has been licensed exclusively to The MIT
  118. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  119. %% version to the public in 2022. All inquiries regarding rights should
  120. %% be addressed to The MIT Press, Rights and Permissions Department.
  121. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  122. %% All rights reserved. No part of this book may be reproduced in any
  123. %% form by any electronic or mechanical means (including photocopying,
  124. %% recording, or information storage and retrieval) without permission in
  125. %% writing from the publisher.
  126. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  127. %% United States of America.
  128. %% Library of Congress Cataloging-in-Publication Data is available.
  129. %% ISBN:
  130. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  131. \end{copyrightpage}
  132. \dedication{This book is dedicated to the programming language wonks
  133. at Indiana University.}
  134. %% \begin{epigraphpage}
  135. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  136. %% \textit{Book Name if any}}
  137. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  138. %% \end{epigraphpage}
  139. \tableofcontents
  140. %\listoffigures
  141. %\listoftables
  142. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  143. \chapter*{Preface}
  144. \addcontentsline{toc}{fmbm}{Preface}
  145. There is a magical moment when a programmer presses the run button
  146. and the software begins to execute. Somehow a program written in a
  147. high-level language is running on a computer that is capable only of
  148. shuffling bits. Here we reveal the wizardry that makes that moment
  149. possible. Beginning with the groundbreaking work of Backus and
  150. colleagues in the 1950s, computer scientists developed techniques for
  151. constructing programs called \emph{compilers} that automatically
  152. translate high-level programs into machine code.
  153. We take you on a journey through constructing your own compiler for a
  154. small but powerful language. Along the way we explain the essential
  155. concepts, algorithms, and data structures that underlie compilers. We
  156. develop your understanding of how programs are mapped onto computer
  157. hardware, which is helpful in reasoning about properties at the
  158. junction of hardware and software, such as execution time, software
  159. errors, and security vulnerabilities. For those interested in
  160. pursuing compiler construction as a career, our goal is to provide a
  161. stepping-stone to advanced topics such as just-in-time compilation,
  162. program analysis, and program optimization. For those interested in
  163. designing and implementing programming languages, we connect language
  164. design choices to their impact on the compiler and the generated code.
  165. A compiler is typically organized as a sequence of stages that
  166. progressively translate a program to the code that runs on
  167. hardware. We take this approach to the extreme by partitioning our
  168. compiler into a large number of \emph{nanopasses}, each of which
  169. performs a single task. This enables the testing of each pass in
  170. isolation and focuses our attention, making the compiler far easier to
  171. understand.
  172. The most familiar approach to describing compilers is to dedicate each
  173. chapter to one pass. The problem with that approach is that it
  174. obfuscates how language features motivate design choices in a
  175. compiler. We instead take an \emph{incremental} approach in which we
  176. build a complete compiler in each chapter, starting with a small input
  177. language that includes only arithmetic and variables. We add new
  178. language features in subsequent chapters, extending the compiler as
  179. necessary.
  180. Our choice of language features is designed to elicit fundamental
  181. concepts and algorithms used in compilers.
  182. \begin{itemize}
  183. \item We begin with integer arithmetic and local variables in
  184. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  185. the fundamental tools of compiler construction: \emph{abstract
  186. syntax trees} and \emph{recursive functions}.
  187. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  188. \emph{graph coloring} to assign variables to machine registers.
  189. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  190. motivates an elegant recursive algorithm for translating them into
  191. conditional \code{goto} statements.
  192. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  193. variables}. This elicits the need for \emph{dataflow
  194. analysis} in the register allocator.
  195. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  196. \emph{garbage collection}.
  197. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  198. without lexical scoping, similar to functions in the C programming
  199. language~\citep{Kernighan:1988nx}. The reader learns about the
  200. procedure call stack and \emph{calling conventions} and how they interact
  201. with register allocation and garbage collection. The chapter also
  202. describes how to generate efficient tail calls.
  203. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  204. scoping, that is, \emph{lambda} expressions. The reader learns about
  205. \emph{closure conversion}, in which lambdas are translated into a
  206. combination of functions and tuples.
  207. % Chapter about classes and objects?
  208. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  209. point the input languages are statically typed. The reader extends
  210. the statically typed language with an \code{Any} type that serves
  211. as a target for compiling the dynamically typed language.
  212. {\if\edition\pythonEd
  213. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  214. \emph{classes}.
  215. \fi}
  216. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  217. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  218. in which different regions of a program may be static or dynamically
  219. typed. The reader implements runtime support for \emph{proxies} that
  220. allow values to safely move between regions.
  221. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  222. leveraging the \code{Any} type and type casts developed in chapters
  223. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  224. \end{itemize}
  225. There are many language features that we do not include. Our choices
  226. balance the incidental complexity of a feature versus the fundamental
  227. concepts that it exposes. For example, we include tuples and not
  228. records because although they both elicit the study of heap allocation and
  229. garbage collection, records come with more incidental complexity.
  230. Since 2009, drafts of this book have served as the textbook for
  231. sixteen week compiler courses for upper-level undergraduates and
  232. first-year graduate students at the University of Colorado and Indiana
  233. University.
  234. %
  235. Students come into the course having learned the basics of
  236. programming, data structures and algorithms, and discrete
  237. mathematics.
  238. %
  239. At the beginning of the course, students form groups of two to four
  240. people. The groups complete one chapter every two weeks, starting
  241. with chapter~\ref{ch:Lvar} and finishing with
  242. chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  243. that we assign to the graduate students. The last two weeks of the
  244. course involve a final project in which students design and implement
  245. a compiler extension of their choosing. The last few chapters can be
  246. used in support of these projects. For compiler courses at
  247. universities on the quarter system (about ten weeks in length), we
  248. recommend completing the course through chapter~\ref{ch:Lvec} or
  249. chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  250. students for each compiler pass.
  251. %
  252. The course can be adapted to emphasize functional languages by
  253. skipping chapter~\ref{ch:Lwhile} (loops) and including
  254. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  255. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  256. %
  257. %% \python{A course that emphasizes object-oriented languages would
  258. %% include Chapter~\ref{ch:Lobject}.}
  259. %
  260. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  261. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  262. chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  263. tail calls.
  264. This book has been used in compiler courses at California Polytechnic
  265. State University, Portland State University, Rose–Hulman Institute of
  266. Technology, University of Freiburg, University of Massachusetts
  267. Lowell, and the University of Vermont.
  268. \begin{figure}[tp]
  269. \begin{tcolorbox}[colback=white]
  270. {\if\edition\racketEd
  271. \begin{tikzpicture}[baseline=(current bounding box.center)]
  272. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  273. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  274. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  275. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  276. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  277. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  278. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  279. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  280. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  281. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  282. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  283. \path[->] (C1) edge [above] node {} (C2);
  284. \path[->] (C2) edge [above] node {} (C3);
  285. \path[->] (C3) edge [above] node {} (C4);
  286. \path[->] (C4) edge [above] node {} (C5);
  287. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  288. \path[->] (C5) edge [above] node {} (C7);
  289. \path[->] (C6) edge [above] node {} (C7);
  290. \path[->] (C4) edge [above] node {} (C8);
  291. \path[->] (C4) edge [above] node {} (C9);
  292. \path[->] (C7) edge [above] node {} (C10);
  293. \path[->] (C8) edge [above] node {} (C10);
  294. \path[->] (C10) edge [above] node {} (C11);
  295. \end{tikzpicture}
  296. \fi}
  297. {\if\edition\pythonEd
  298. \begin{tikzpicture}[baseline=(current bounding box.center)]
  299. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  300. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  301. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  302. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  303. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  304. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  305. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  306. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  307. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  308. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  309. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  310. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  311. \path[->] (C1) edge [above] node {} (C2);
  312. \path[->] (C2) edge [above] node {} (C3);
  313. \path[->] (C3) edge [above] node {} (C4);
  314. \path[->] (C4) edge [above] node {} (C5);
  315. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  316. \path[->] (C5) edge [above] node {} (C7);
  317. \path[->] (C6) edge [above] node {} (C7);
  318. \path[->] (C4) edge [above] node {} (C8);
  319. \path[->] (C4) edge [above] node {} (C9);
  320. \path[->] (C7) edge [above] node {} (C10);
  321. \path[->] (C8) edge [above] node {} (C10);
  322. % \path[->] (C8) edge [above] node {} (CO);
  323. \path[->] (C10) edge [above] node {} (C11);
  324. \end{tikzpicture}
  325. \fi}
  326. \end{tcolorbox}
  327. \caption{Diagram of chapter dependencies.}
  328. \label{fig:chapter-dependences}
  329. \end{figure}
  330. \racket{
  331. We use the \href{https://racket-lang.org/}{Racket} language both for
  332. the implementation of the compiler and for the input language, so the
  333. reader should be proficient with Racket or Scheme. There are many
  334. excellent resources for learning Scheme and
  335. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  336. }
  337. \python{
  338. This edition of the book uses \href{https://www.python.org/}{Python}
  339. both for the implementation of the compiler and for the input language, so the
  340. reader should be proficient with Python. There are many
  341. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  342. }
  343. The support code for this book is in the GitHub repository at
  344. the following location:
  345. \begin{center}\small\texttt
  346. https://github.com/IUCompilerCourse/
  347. \end{center}
  348. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  349. is helpful but not necessary for the reader to have taken a computer
  350. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  351. assembly language that are needed in the compiler.
  352. %
  353. We follow the System V calling
  354. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  355. that we generate works with the runtime system (written in C) when it
  356. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  357. operating systems on Intel hardware.
  358. %
  359. On the Windows operating system, \code{gcc} uses the Microsoft x64
  360. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  361. assembly code that we generate does \emph{not} work with the runtime
  362. system on Windows. One workaround is to use a virtual machine with
  363. Linux as the guest operating system.
  364. \section*{Acknowledgments}
  365. The tradition of compiler construction at Indiana University goes back
  366. to research and courses on programming languages by Daniel Friedman in
  367. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  368. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  369. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  370. the compiler course and continued the development of Chez Scheme.
  371. %
  372. The compiler course evolved to incorporate novel pedagogical ideas
  373. while also including elements of real-world compilers. One of
  374. Friedman's ideas was to split the compiler into many small
  375. passes. Another idea, called ``the game,'' was to test the code
  376. generated by each pass using interpreters.
  377. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  378. developed infrastructure to support this approach and evolved the
  379. course to use even smaller
  380. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  381. design decisions in this book are inspired by the assignment
  382. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  383. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  384. organization of the course made it difficult for students to
  385. understand the rationale for the compiler design. Ghuloum proposed the
  386. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  387. based.
  388. We thank the many students who served as teaching assistants for the
  389. compiler course at IU, including Carl Factora, Ryan Scott, Cameron
  390. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  391. garbage collector and x86 interpreter, Michael Vollmer for work on
  392. efficient tail calls, and Michael Vitousek for help with the first
  393. offering of the incremental compiler course at IU.
  394. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  395. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  396. Michael Wollowski for teaching courses based on drafts of this book
  397. and for their feedback. We thank the National Science Foundation for
  398. the grants that helped to support this work: Grant Numbers 1518844,
  399. 1763922, and 1814460.
  400. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  401. course in the early 2000s and especially for finding the bug that
  402. sent our garbage collector on a wild goose chase!
  403. \mbox{}\\
  404. \noindent Jeremy G. Siek \\
  405. Bloomington, Indiana
  406. \mainmatter
  407. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  408. \chapter{Preliminaries}
  409. \label{ch:trees-recur}
  410. \setcounter{footnote}{0}
  411. In this chapter we review the basic tools needed to implement a
  412. compiler. Programs are typically input by a programmer as text, that
  413. is, a sequence of characters. The program-as-text representation is
  414. called \emph{concrete syntax}. We use concrete syntax to concisely
  415. write down and talk about programs. Inside the compiler, we use
  416. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  417. that efficiently supports the operations that the compiler needs to
  418. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  419. syntax}\index{subject}{abstract syntax
  420. tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse}
  421. The process of translating from concrete syntax to abstract syntax is
  422. called \emph{parsing}~\citep{Aho:2006wb}. This book does not cover the
  423. theory and implementation of parsing.
  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 inside the compiler in many different ways,
  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 a brief
  446. introduction to these components.
  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 such as, for a given part of a program,
  453. what kind of language feature is it? What are its subparts? Consider
  454. the program on the left and the diagram of its AST on the
  455. right~\eqref{eq:arith-prog}. This program is an addition operation
  456. that has two subparts, a \racket{read}\python{input} operation and a
  457. negation. The negation has another subpart, the integer constant
  458. \code{8}. By using a tree to represent the program, we can easily
  459. follow the links to go from one part of a program to its subparts.
  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 of which it is the child). 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 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 contains just one thing: the integer value.
  557. We establish the convention that \code{struct} names, such
  558. as \code{Int}, are capitalized.
  559. To create an AST node for the integer $8$, we write \INT{8}.
  560. \begin{lstlisting}
  561. (define eight (Int 8))
  562. \end{lstlisting}
  563. We say that the value created by \INT{8} is an
  564. \emph{instance} of the
  565. \code{Int} structure.
  566. The following is the \code{struct} definition for primitive operations.
  567. \begin{lstlisting}
  568. (struct Prim (op args))
  569. \end{lstlisting}
  570. A primitive operation node includes an operator symbol \code{op} and a
  571. list of child arguments called \code{args}. For example, to create an
  572. AST that negates the number $8$, we write the following.
  573. \begin{lstlisting}
  574. (define neg-eight (Prim '- (list eight)))
  575. \end{lstlisting}
  576. Primitive operations may have zero or more children. The \code{read}
  577. operator has zero:
  578. \begin{lstlisting}
  579. (define rd (Prim 'read '()))
  580. \end{lstlisting}
  581. The addition operator has two children:
  582. \begin{lstlisting}
  583. (define ast1_1 (Prim '+ (list rd neg-eight)))
  584. \end{lstlisting}
  585. We have made a design choice regarding the \code{Prim} structure.
  586. Instead of using one structure for many different operations
  587. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  588. structure for each operation, as follows:
  589. \begin{lstlisting}
  590. (struct Read ())
  591. (struct Add (left right))
  592. (struct Neg (value))
  593. \end{lstlisting}
  594. The reason that we choose to use just one structure is that many parts
  595. of the compiler can use the same code for the different primitive
  596. operators, so we might as well just write that code once by using a
  597. single structure.
  598. %
  599. \fi}
  600. {\if\edition\pythonEd
  601. We use a Python \code{class} for each kind of node.
  602. The following is the class definition for
  603. constants.
  604. \begin{lstlisting}
  605. class Constant:
  606. def __init__(self, value):
  607. self.value = value
  608. \end{lstlisting}
  609. An integer constant node includes just one thing: the integer value.
  610. To create an AST node for the integer $8$, we write \INT{8}.
  611. \begin{lstlisting}
  612. eight = Constant(8)
  613. \end{lstlisting}
  614. We say that the value created by \INT{8} is an
  615. \emph{instance} of the \code{Constant} class.
  616. The following is the class definition for unary operators.
  617. \begin{lstlisting}
  618. class UnaryOp:
  619. def __init__(self, op, operand):
  620. self.op = op
  621. self.operand = operand
  622. \end{lstlisting}
  623. The specific operation is specified by the \code{op} parameter. For
  624. example, the class \code{USub} is for unary subtraction.
  625. (More unary operators are introduced in later chapters.) To create an AST that
  626. negates the number $8$, we write the following.
  627. \begin{lstlisting}
  628. neg_eight = UnaryOp(USub(), eight)
  629. \end{lstlisting}
  630. The call to the \code{input\_int} function is represented by the
  631. \code{Call} and \code{Name} classes.
  632. \begin{lstlisting}
  633. class Call:
  634. def __init__(self, func, args):
  635. self.func = func
  636. self.args = args
  637. class Name:
  638. def __init__(self, id):
  639. self.id = id
  640. \end{lstlisting}
  641. To create an AST node that calls \code{input\_int}, we write
  642. \begin{lstlisting}
  643. read = Call(Name('input_int'), [])
  644. \end{lstlisting}
  645. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  646. the \code{BinOp} class for binary operators.
  647. \begin{lstlisting}
  648. class BinOp:
  649. def __init__(self, left, op, right):
  650. self.op = op
  651. self.left = left
  652. self.right = right
  653. \end{lstlisting}
  654. Similar to \code{UnaryOp}, the specific operation is specified by the
  655. \code{op} parameter, which for now is just an instance of the
  656. \code{Add} class. So to create the AST
  657. node that adds negative eight to some user input, we write the following.
  658. \begin{lstlisting}
  659. ast1_1 = BinOp(read, Add(), neg_eight)
  660. \end{lstlisting}
  661. \fi}
  662. To compile a program such as \eqref{eq:arith-prog}, we need to know
  663. that the operation associated with the root node is addition and we
  664. need to be able to access its two
  665. children. \racket{Racket}\python{Python} provides pattern matching to
  666. support these kinds of queries, as we see in
  667. section~\ref{sec:pattern-matching}.
  668. We often write down the concrete syntax of a program even when we
  669. actually have in mind the AST, because the concrete syntax is more
  670. concise. We recommend that you always think of programs as abstract
  671. syntax trees.
  672. \section{Grammars}
  673. \label{sec:grammar}
  674. \index{subject}{integer}
  675. \index{subject}{literal}
  676. %\index{subject}{constant}
  677. A programming language can be thought of as a \emph{set} of programs.
  678. The set is infinite (that is, one can always create larger programs),
  679. so one cannot simply describe a language by listing all the
  680. programs in the language. Instead we write down a set of rules, a
  681. \emph{grammar}, for building programs. Grammars are often used to
  682. define the concrete syntax of a language, but they can also be used to
  683. describe the abstract syntax. We write our rules in a variant of
  684. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  685. \index{subject}{Backus-Naur Form}\index{subject}{BNF} As an example,
  686. we describe a small language, named \LangInt{}, that consists of
  687. integers and arithmetic operations. \index{subject}{grammar}
  688. The first grammar rule for the abstract syntax of \LangInt{} says that an
  689. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  690. \begin{equation}
  691. \Exp ::= \INT{\Int} \label{eq:arith-int}
  692. \end{equation}
  693. %
  694. Each rule has a left-hand side and a right-hand side.
  695. If you have an AST node that matches the
  696. right-hand side, then you can categorize it according to the
  697. left-hand side.
  698. %
  699. Symbols in typewriter font are \emph{terminal} symbols and must
  700. literally appear in the program for the rule to be applicable.
  701. \index{subject}{terminal}
  702. %
  703. Our grammars do not mention \emph{white space}, that is, delimiter
  704. characters like spaces, tabs, and new lines. White space may be
  705. inserted between symbols for disambiguation and to improve
  706. readability. \index{subject}{white space}
  707. %
  708. A name such as $\Exp$ that is defined by the grammar rules is a
  709. \emph{nonterminal}. \index{subject}{nonterminal}
  710. %
  711. The name $\Int$ is also a nonterminal, but instead of defining it with
  712. a grammar rule, we define it with the following explanation. An
  713. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  714. $-$ (for negative integers), such that the sequence of decimals
  715. represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  716. enables the representation of integers using 63 bits, which simplifies
  717. several aspects of compilation.
  718. %
  719. \racket{Thus, these integers correspond to the Racket \texttt{fixnum}
  720. datatype on a 64-bit machine.}
  721. %
  722. \python{In contrast, integers in Python have unlimited precision, but
  723. the techniques needed to handle unlimited precision fall outside the
  724. scope of this book.}
  725. The second grammar rule is the \READOP{} operation, which receives an
  726. input integer from the user of the program.
  727. \begin{equation}
  728. \Exp ::= \READ{} \label{eq:arith-read}
  729. \end{equation}
  730. The third rule categorizes the negation of an $\Exp$ node as an
  731. $\Exp$.
  732. \begin{equation}
  733. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  734. \end{equation}
  735. We can apply these rules to categorize the ASTs that are in the
  736. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  737. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  738. following AST is an $\Exp$.
  739. \begin{center}
  740. \begin{minipage}{0.5\textwidth}
  741. \NEG{\INT{\code{8}}}
  742. \end{minipage}
  743. \begin{minipage}{0.25\textwidth}
  744. \begin{equation}
  745. \begin{tikzpicture}
  746. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  747. \node[draw, circle] (8) at (0, -1.2) {$8$};
  748. \draw[->] (minus) to (8);
  749. \end{tikzpicture}
  750. \label{eq:arith-neg8}
  751. \end{equation}
  752. \end{minipage}
  753. \end{center}
  754. The next two grammar rules are for addition and subtraction expressions:
  755. \begin{align}
  756. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  757. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  758. \end{align}
  759. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  760. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  761. \eqref{eq:arith-read}, and we have already categorized
  762. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  763. to show that
  764. \[
  765. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  766. \]
  767. is an $\Exp$ in the \LangInt{} language.
  768. If you have an AST for which these rules do not apply, then the
  769. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  770. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  771. because there is no rule for the \key{*} operator. Whenever we
  772. define a language with a grammar, the language includes only those
  773. programs that are justified by the grammar rules.
  774. {\if\edition\pythonEd
  775. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  776. There is a statement for printing the value of an expression
  777. \[
  778. \Stmt{} ::= \PRINT{\Exp}
  779. \]
  780. and a statement that evaluates an expression but ignores the result.
  781. \[
  782. \Stmt{} ::= \EXPR{\Exp}
  783. \]
  784. \fi}
  785. {\if\edition\racketEd
  786. The last grammar rule for \LangInt{} states that there is a
  787. \code{Program} node to mark the top of the whole program:
  788. \[
  789. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  790. \]
  791. The \code{Program} structure is defined as follows:
  792. \begin{lstlisting}
  793. (struct Program (info body))
  794. \end{lstlisting}
  795. where \code{body} is an expression. In further chapters, the \code{info}
  796. part is used to store auxiliary information, but for now it is
  797. just the empty list.
  798. \fi}
  799. {\if\edition\pythonEd
  800. The last grammar rule for \LangInt{} states that there is a
  801. \code{Module} node to mark the top of the whole program:
  802. \[
  803. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  804. \]
  805. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  806. this case, a list of statements.
  807. %
  808. The \code{Module} class is defined as follows
  809. \begin{lstlisting}
  810. class Module:
  811. def __init__(self, body):
  812. self.body = body
  813. \end{lstlisting}
  814. where \code{body} is a list of statements.
  815. \fi}
  816. It is common to have many grammar rules with the same left-hand side
  817. but different right-hand sides, such as the rules for $\Exp$ in the
  818. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  819. combine several right-hand sides into a single rule.
  820. The concrete syntax for \LangInt{} is shown in
  821. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  822. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.
  823. \racket{The \code{read-program} function provided in
  824. \code{utilities.rkt} of the support code reads a program from a file
  825. (the sequence of characters in the concrete syntax of Racket) and
  826. parses it into an abstract syntax tree. Refer to the description of
  827. \code{read-program} in appendix~\ref{appendix:utilities} for more
  828. details.}
  829. \python{The \code{parse} function in Python's \code{ast} module
  830. converts the concrete syntax (represented as a string) into an
  831. abstract syntax tree.}
  832. \newcommand{\LintGrammarRacket}{
  833. \begin{array}{rcl}
  834. \Type &::=& \key{Integer} \\
  835. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  836. \MID \CSUB{\Exp}{\Exp}
  837. \end{array}
  838. }
  839. \newcommand{\LintASTRacket}{
  840. \begin{array}{rcl}
  841. \Type &::=& \key{Integer} \\
  842. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  843. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  844. \end{array}
  845. }
  846. \newcommand{\LintGrammarPython}{
  847. \begin{array}{rcl}
  848. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  849. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  850. \end{array}
  851. }
  852. \newcommand{\LintASTPython}{
  853. \begin{array}{rcl}
  854. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  855. \itm{unaryop} &::= & \code{USub()} \\
  856. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  857. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  858. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  859. \end{array}
  860. }
  861. \begin{figure}[tp]
  862. \begin{tcolorbox}[colback=white]
  863. {\if\edition\racketEd
  864. \[
  865. \begin{array}{l}
  866. \LintGrammarRacket \\
  867. \begin{array}{rcl}
  868. \LangInt{} &::=& \Exp
  869. \end{array}
  870. \end{array}
  871. \]
  872. \fi}
  873. {\if\edition\pythonEd
  874. \[
  875. \begin{array}{l}
  876. \LintGrammarPython \\
  877. \begin{array}{rcl}
  878. \LangInt{} &::=& \Stmt^{*}
  879. \end{array}
  880. \end{array}
  881. \]
  882. \fi}
  883. \end{tcolorbox}
  884. \caption{The concrete syntax of \LangInt{}.}
  885. \label{fig:r0-concrete-syntax}
  886. \end{figure}
  887. \begin{figure}[tp]
  888. \begin{tcolorbox}[colback=white]
  889. {\if\edition\racketEd
  890. \[
  891. \begin{array}{l}
  892. \LintASTRacket{} \\
  893. \begin{array}{rcl}
  894. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  895. \end{array}
  896. \end{array}
  897. \]
  898. \fi}
  899. {\if\edition\pythonEd
  900. \[
  901. \begin{array}{l}
  902. \LintASTPython\\
  903. \begin{array}{rcl}
  904. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  905. \end{array}
  906. \end{array}
  907. \]
  908. \fi}
  909. \end{tcolorbox}
  910. \python{
  911. \index{subject}{Constant@\texttt{Constant}}
  912. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  913. \index{subject}{USub@\texttt{USub}}
  914. \index{subject}{inputint@\texttt{input\_int}}
  915. \index{subject}{Call@\texttt{Call}}
  916. \index{subject}{Name@\texttt{Name}}
  917. \index{subject}{BinOp@\texttt{BinOp}}
  918. \index{subject}{Add@\texttt{Add}}
  919. \index{subject}{Sub@\texttt{Sub}}
  920. \index{subject}{print@\texttt{print}}
  921. \index{subject}{Expr@\texttt{Expr}}
  922. \index{subject}{Module@\texttt{Module}}
  923. }
  924. \caption{The abstract syntax of \LangInt{}.}
  925. \label{fig:r0-syntax}
  926. \end{figure}
  927. \section{Pattern Matching}
  928. \label{sec:pattern-matching}
  929. As mentioned in section~\ref{sec:ast}, compilers often need to access
  930. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  931. provides the \texttt{match} feature to access the parts of a value.
  932. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  933. \begin{center}
  934. \begin{minipage}{0.5\textwidth}
  935. {\if\edition\racketEd
  936. \begin{lstlisting}
  937. (match ast1_1
  938. [(Prim op (list child1 child2))
  939. (print op)])
  940. \end{lstlisting}
  941. \fi}
  942. {\if\edition\pythonEd
  943. \begin{lstlisting}
  944. match ast1_1:
  945. case BinOp(child1, op, child2):
  946. print(op)
  947. \end{lstlisting}
  948. \fi}
  949. \end{minipage}
  950. \end{center}
  951. {\if\edition\racketEd
  952. %
  953. In this example, the \texttt{match} form checks whether the AST
  954. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  955. three pattern variables \texttt{op}, \texttt{child1}, and
  956. \texttt{child2}. In general, a match clause consists of a
  957. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  958. recursively defined to be a pattern variable, a structure name
  959. followed by a pattern for each of the structure's arguments, or an
  960. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  961. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  962. and chapter 9 of The Racket
  963. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  964. for complete descriptions of \code{match}.)
  965. %
  966. The body of a match clause may contain arbitrary Racket code. The
  967. pattern variables can be used in the scope of the body, such as
  968. \code{op} in \code{(print op)}.
  969. %
  970. \fi}
  971. %
  972. %
  973. {\if\edition\pythonEd
  974. %
  975. In the above example, the \texttt{match} form checks whether the AST
  976. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  977. three pattern variables \texttt{child1}, \texttt{op}, and
  978. \texttt{child2}, and then prints out the operator. In general, each
  979. \code{case} consists of a \emph{pattern} and a
  980. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  981. to be either a pattern variable, a class name followed by a pattern
  982. for each of its constructor's arguments, or other literals such as
  983. strings, lists, etc.
  984. %
  985. The body of each \code{case} may contain arbitrary Python code. The
  986. pattern variables can be used in the body, such as \code{op} in
  987. \code{print(op)}.
  988. %
  989. \fi}
  990. A \code{match} form may contain several clauses, as in the following
  991. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  992. the AST. The \code{match} proceeds through the clauses in order,
  993. checking whether the pattern can match the input AST. The body of the
  994. first clause that matches is executed. The output of \code{leaf} for
  995. several ASTs is shown on the right side of the following:
  996. \begin{center}
  997. \begin{minipage}{0.6\textwidth}
  998. {\if\edition\racketEd
  999. \begin{lstlisting}
  1000. (define (leaf arith)
  1001. (match arith
  1002. [(Int n) #t]
  1003. [(Prim 'read '()) #t]
  1004. [(Prim '- (list e1)) #f]
  1005. [(Prim '+ (list e1 e2)) #f]
  1006. [(Prim '- (list e1 e2)) #f]))
  1007. (leaf (Prim 'read '()))
  1008. (leaf (Prim '- (list (Int 8))))
  1009. (leaf (Int 8))
  1010. \end{lstlisting}
  1011. \fi}
  1012. {\if\edition\pythonEd
  1013. \begin{lstlisting}
  1014. def leaf(arith):
  1015. match arith:
  1016. case Constant(n):
  1017. return True
  1018. case Call(Name('input_int'), []):
  1019. return True
  1020. case UnaryOp(USub(), e1):
  1021. return False
  1022. case BinOp(e1, Add(), e2):
  1023. return False
  1024. case BinOp(e1, Sub(), e2):
  1025. return False
  1026. print(leaf(Call(Name('input_int'), [])))
  1027. print(leaf(UnaryOp(USub(), eight)))
  1028. print(leaf(Constant(8)))
  1029. \end{lstlisting}
  1030. \fi}
  1031. \end{minipage}
  1032. \vrule
  1033. \begin{minipage}{0.25\textwidth}
  1034. {\if\edition\racketEd
  1035. \begin{lstlisting}
  1036. #t
  1037. #f
  1038. #t
  1039. \end{lstlisting}
  1040. \fi}
  1041. {\if\edition\pythonEd
  1042. \begin{lstlisting}
  1043. True
  1044. False
  1045. True
  1046. \end{lstlisting}
  1047. \fi}
  1048. \end{minipage}
  1049. \end{center}
  1050. When constructing a \code{match} expression, we refer to the grammar
  1051. definition to identify which nonterminal we are expecting to match
  1052. against, and then we make sure that (1) we have one
  1053. \racket{clause}\python{case} for each alternative of that nonterminal
  1054. and (2) the pattern in each \racket{clause}\python{case}
  1055. corresponds to the corresponding right-hand side of a grammar
  1056. rule. For the \code{match} in the \code{leaf} function, we refer to
  1057. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1058. nonterminal has four alternatives, so the \code{match} has four
  1059. \racket{clauses}\python{cases}. The pattern in each
  1060. \racket{clause}\python{case} corresponds to the right-hand side of a
  1061. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1062. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1063. translating from grammars to patterns, replace nonterminals such as
  1064. $\Exp$ with pattern variables of your choice (e.g., \code{e1} and
  1065. \code{e2}).
  1066. \section{Recursive Functions}
  1067. \label{sec:recursion}
  1068. \index{subject}{recursive function}
  1069. Programs are inherently recursive. For example, an expression is often
  1070. made of smaller expressions. Thus, the natural way to process an
  1071. entire program is to use a recursive function. As a first example of
  1072. such a recursive function, we define the function \code{is\_exp} as
  1073. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1074. value and determine whether or not it is an expression in \LangInt{}.
  1075. %
  1076. We say that a function is defined by \emph{structural recursion} if
  1077. it is defined using a sequence of match \racket{clauses}\python{cases}
  1078. that correspond to a grammar and the body of each
  1079. \racket{clause}\python{case} makes a recursive call on each child
  1080. node.\footnote{This principle of structuring code according to the
  1081. data definition is advocated in the book \emph{How to Design
  1082. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1083. second function, named \code{stmt}, that recognizes whether a value
  1084. is a \LangInt{} statement.} \python{Finally, }
  1085. Figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1086. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1087. In general, we can write one recursive function to handle each
  1088. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1089. two examples at the bottom of the figure, the first is in
  1090. \LangInt{} and the second is not.
  1091. \begin{figure}[tp]
  1092. \begin{tcolorbox}[colback=white]
  1093. {\if\edition\racketEd
  1094. \begin{lstlisting}
  1095. (define (is_exp ast)
  1096. (match ast
  1097. [(Int n) #t]
  1098. [(Prim 'read '()) #t]
  1099. [(Prim '- (list e)) (is_exp e)]
  1100. [(Prim '+ (list e1 e2))
  1101. (and (is_exp e1) (is_exp e2))]
  1102. [(Prim '- (list e1 e2))
  1103. (and (is_exp e1) (is_exp e2))]
  1104. [else #f]))
  1105. (define (is_Lint ast)
  1106. (match ast
  1107. [(Program '() e) (is_exp e)]
  1108. [else #f]))
  1109. (is_Lint (Program '() ast1_1)
  1110. (is_Lint (Program '()
  1111. (Prim '* (list (Prim 'read '())
  1112. (Prim '+ (list (Int 8)))))))
  1113. \end{lstlisting}
  1114. \fi}
  1115. {\if\edition\pythonEd
  1116. \begin{lstlisting}
  1117. def is_exp(e):
  1118. match e:
  1119. case Constant(n):
  1120. return True
  1121. case Call(Name('input_int'), []):
  1122. return True
  1123. case UnaryOp(USub(), e1):
  1124. return is_exp(e1)
  1125. case BinOp(e1, Add(), e2):
  1126. return is_exp(e1) and is_exp(e2)
  1127. case BinOp(e1, Sub(), e2):
  1128. return is_exp(e1) and is_exp(e2)
  1129. case _:
  1130. return False
  1131. def stmt(s):
  1132. match s:
  1133. case Expr(Call(Name('print'), [e])):
  1134. return is_exp(e)
  1135. case Expr(e):
  1136. return is_exp(e)
  1137. case _:
  1138. return False
  1139. def is_Lint(p):
  1140. match p:
  1141. case Module(body):
  1142. return all([stmt(s) for s in body])
  1143. case _:
  1144. return False
  1145. print(is_Lint(Module([Expr(ast1_1)])))
  1146. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1147. UnaryOp(Add(), Constant(8))))])))
  1148. \end{lstlisting}
  1149. \fi}
  1150. \end{tcolorbox}
  1151. \caption{Example of recursive functions for \LangInt{}. These functions
  1152. recognize whether an AST is in \LangInt{}.}
  1153. \label{fig:exp-predicate}
  1154. \end{figure}
  1155. %% You may be tempted to merge the two functions into one, like this:
  1156. %% \begin{center}
  1157. %% \begin{minipage}{0.5\textwidth}
  1158. %% \begin{lstlisting}
  1159. %% (define (Lint ast)
  1160. %% (match ast
  1161. %% [(Int n) #t]
  1162. %% [(Prim 'read '()) #t]
  1163. %% [(Prim '- (list e)) (Lint e)]
  1164. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1165. %% [(Program '() e) (Lint e)]
  1166. %% [else #f]))
  1167. %% \end{lstlisting}
  1168. %% \end{minipage}
  1169. %% \end{center}
  1170. %% %
  1171. %% Sometimes such a trick will save a few lines of code, especially when
  1172. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1173. %% \emph{not} recommended because it can get you into trouble.
  1174. %% %
  1175. %% For example, the above function is subtly wrong:
  1176. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1177. %% returns true when it should return false.
  1178. \section{Interpreters}
  1179. \label{sec:interp_Lint}
  1180. \index{subject}{interpreter}
  1181. The behavior of a program is defined by the specification of the
  1182. programming language.
  1183. %
  1184. \racket{For example, the Scheme language is defined in the report by
  1185. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1186. reference manual~\citep{plt-tr}.}
  1187. %
  1188. \python{For example, the Python language is defined in the Python
  1189. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1190. %
  1191. In this book we use interpreters to specify each language that we
  1192. consider. An interpreter that is designated as the definition of a
  1193. language is called a \emph{definitional
  1194. interpreter}~\citep{reynolds72:_def_interp}.
  1195. \index{subject}{definitional interpreter} We warm up by creating a
  1196. definitional interpreter for the \LangInt{} language. This interpreter
  1197. serves as a second example of structural recursion. The definition of the
  1198. \code{interp\_Lint} function is shown in
  1199. figure~\ref{fig:interp_Lint}.
  1200. %
  1201. \racket{The body of the function is a match on the input program
  1202. followed by a call to the \lstinline{interp_exp} helper function,
  1203. which in turn has one match clause per grammar rule for \LangInt{}
  1204. expressions.}
  1205. %
  1206. \python{The body of the function matches on the \code{Module} AST node
  1207. and then invokes \code{interp\_stmt} on each statement in the
  1208. module. The \code{interp\_stmt} function includes a case for each
  1209. grammar rule of the \Stmt{} nonterminal and it calls
  1210. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1211. function includes a case for each grammar rule of the \Exp{}
  1212. nonterminal.}
  1213. \begin{figure}[tp]
  1214. \begin{tcolorbox}[colback=white]
  1215. {\if\edition\racketEd
  1216. \begin{lstlisting}
  1217. (define (interp_exp e)
  1218. (match e
  1219. [(Int n) n]
  1220. [(Prim 'read '())
  1221. (define r (read))
  1222. (cond [(fixnum? r) r]
  1223. [else (error 'interp_exp "read expected an integer" r)])]
  1224. [(Prim '- (list e))
  1225. (define v (interp_exp e))
  1226. (fx- 0 v)]
  1227. [(Prim '+ (list e1 e2))
  1228. (define v1 (interp_exp e1))
  1229. (define v2 (interp_exp e2))
  1230. (fx+ v1 v2)]
  1231. [(Prim '- (list e1 e2))
  1232. (define v1 ((interp-exp env) e1))
  1233. (define v2 ((interp-exp env) e2))
  1234. (fx- v1 v2)]))
  1235. (define (interp_Lint p)
  1236. (match p
  1237. [(Program '() e) (interp_exp e)]))
  1238. \end{lstlisting}
  1239. \fi}
  1240. {\if\edition\pythonEd
  1241. \begin{lstlisting}
  1242. def interp_exp(e):
  1243. match e:
  1244. case BinOp(left, Add(), right):
  1245. l = interp_exp(left); r = interp_exp(right)
  1246. return l + r
  1247. case BinOp(left, Sub(), right):
  1248. l = interp_exp(left); r = interp_exp(right)
  1249. return l - r
  1250. case UnaryOp(USub(), v):
  1251. return - interp_exp(v)
  1252. case Constant(value):
  1253. return value
  1254. case Call(Name('input_int'), []):
  1255. return int(input())
  1256. def interp_stmt(s):
  1257. match s:
  1258. case Expr(Call(Name('print'), [arg])):
  1259. print(interp_exp(arg))
  1260. case Expr(value):
  1261. interp_exp(value)
  1262. def interp_Lint(p):
  1263. match p:
  1264. case Module(body):
  1265. for s in body:
  1266. interp_stmt(s)
  1267. \end{lstlisting}
  1268. \fi}
  1269. \end{tcolorbox}
  1270. \caption{Interpreter for the \LangInt{} language.}
  1271. \label{fig:interp_Lint}
  1272. \end{figure}
  1273. Let us consider the result of interpreting a few \LangInt{} programs. The
  1274. following program adds two integers:
  1275. {\if\edition\racketEd
  1276. \begin{lstlisting}
  1277. (+ 10 32)
  1278. \end{lstlisting}
  1279. \fi}
  1280. {\if\edition\pythonEd
  1281. \begin{lstlisting}
  1282. print(10 + 32)
  1283. \end{lstlisting}
  1284. \fi}
  1285. %
  1286. \noindent The result is \key{42}, the answer to life, the universe,
  1287. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1288. the Galaxy} by Douglas Adams.}
  1289. %
  1290. We wrote this program in concrete syntax, whereas the parsed
  1291. abstract syntax is
  1292. {\if\edition\racketEd
  1293. \begin{lstlisting}
  1294. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1295. \end{lstlisting}
  1296. \fi}
  1297. {\if\edition\pythonEd
  1298. \begin{lstlisting}
  1299. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1300. \end{lstlisting}
  1301. \fi}
  1302. The following program demonstrates that expressions may be nested within
  1303. each other, in this case nesting several additions and negations.
  1304. {\if\edition\racketEd
  1305. \begin{lstlisting}
  1306. (+ 10 (- (+ 12 20)))
  1307. \end{lstlisting}
  1308. \fi}
  1309. {\if\edition\pythonEd
  1310. \begin{lstlisting}
  1311. print(10 + -(12 + 20))
  1312. \end{lstlisting}
  1313. \fi}
  1314. %
  1315. \noindent What is the result of this program?
  1316. {\if\edition\racketEd
  1317. As mentioned previously, the \LangInt{} language does not support
  1318. arbitrarily large integers but only $63$-bit integers, so we
  1319. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1320. in Racket.
  1321. Suppose that
  1322. \[
  1323. n = 999999999999999999
  1324. \]
  1325. which indeed fits in $63$ bits. What happens when we run the
  1326. following program in our interpreter?
  1327. \begin{lstlisting}
  1328. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1329. \end{lstlisting}
  1330. It produces the following error:
  1331. \begin{lstlisting}
  1332. fx+: result is not a fixnum
  1333. \end{lstlisting}
  1334. We establish the convention that if running the definitional
  1335. interpreter on a program produces an error, then the meaning of that
  1336. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1337. error is a \code{trapped-error}. A compiler for the language is under
  1338. no obligation regarding programs with unspecified behavior; it does
  1339. not have to produce an executable, and if it does, that executable can
  1340. do anything. On the other hand, if the error is a
  1341. \code{trapped-error}, then the compiler must produce an executable and
  1342. it is required to report that an error occurred. To signal an error,
  1343. exit with a return code of \code{255}. The interpreters in chapters
  1344. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1345. \code{trapped-error}.
  1346. \fi}
  1347. % TODO: how to deal with too-large integers in the Python interpreter?
  1348. %% This convention applies to the languages defined in this
  1349. %% book, as a way to simplify the student's task of implementing them,
  1350. %% but this convention is not applicable to all programming languages.
  1351. %%
  1352. The last feature of the \LangInt{} language, the \READOP{} operation,
  1353. prompts the user of the program for an integer. Recall that program
  1354. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1355. \code{8}. So, if we run {\if\edition\racketEd
  1356. \begin{lstlisting}
  1357. (interp_Lint (Program '() ast1_1))
  1358. \end{lstlisting}
  1359. \fi}
  1360. {\if\edition\pythonEd
  1361. \begin{lstlisting}
  1362. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1363. \end{lstlisting}
  1364. \fi}
  1365. \noindent and if the input is \code{50}, the result is \code{42}.
  1366. We include the \READOP{} operation in \LangInt{} so that a clever
  1367. student cannot implement a compiler for \LangInt{} that simply runs
  1368. the interpreter during compilation to obtain the output and then
  1369. generates the trivial code to produce the output.\footnote{Yes, a
  1370. clever student did this in the first instance of this course!}
  1371. The job of a compiler is to translate a program in one language into a
  1372. program in another language so that the output program behaves the
  1373. same way as the input program. This idea is depicted in the
  1374. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1375. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1376. Given a compiler that translates from language $\mathcal{L}_1$ to
  1377. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1378. compiler must translate it into some program $P_2$ such that
  1379. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1380. same input $i$ yields the same output $o$.
  1381. \begin{equation} \label{eq:compile-correct}
  1382. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1383. \node (p1) at (0, 0) {$P_1$};
  1384. \node (p2) at (3, 0) {$P_2$};
  1385. \node (o) at (3, -2.5) {$o$};
  1386. \path[->] (p1) edge [above] node {compile} (p2);
  1387. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1388. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1389. \end{tikzpicture}
  1390. \end{equation}
  1391. In the next section we see our first example of a compiler.
  1392. \section{Example Compiler: A Partial Evaluator}
  1393. \label{sec:partial-evaluation}
  1394. In this section we consider a compiler that translates \LangInt{}
  1395. programs into \LangInt{} programs that may be more efficient. The
  1396. compiler eagerly computes the parts of the program that do not depend
  1397. on any inputs, a process known as \emph{partial
  1398. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1399. For example, given the following program
  1400. {\if\edition\racketEd
  1401. \begin{lstlisting}
  1402. (+ (read) (- (+ 5 3)))
  1403. \end{lstlisting}
  1404. \fi}
  1405. {\if\edition\pythonEd
  1406. \begin{lstlisting}
  1407. print(input_int() + -(5 + 3) )
  1408. \end{lstlisting}
  1409. \fi}
  1410. \noindent our compiler translates it into the program
  1411. {\if\edition\racketEd
  1412. \begin{lstlisting}
  1413. (+ (read) -8)
  1414. \end{lstlisting}
  1415. \fi}
  1416. {\if\edition\pythonEd
  1417. \begin{lstlisting}
  1418. print(input_int() + -8)
  1419. \end{lstlisting}
  1420. \fi}
  1421. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1422. evaluator for the \LangInt{} language. The output of the partial evaluator
  1423. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1424. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1425. whereas the code for partially evaluating the negation and addition
  1426. operations is factored into three auxiliary functions:
  1427. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1428. functions is the output of partially evaluating the children.
  1429. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1430. arguments are integers and if they are, perform the appropriate
  1431. arithmetic. Otherwise, they create an AST node for the arithmetic
  1432. operation.
  1433. \begin{figure}[tp]
  1434. \begin{tcolorbox}[colback=white]
  1435. {\if\edition\racketEd
  1436. \begin{lstlisting}
  1437. (define (pe_neg r)
  1438. (match r
  1439. [(Int n) (Int (fx- 0 n))]
  1440. [else (Prim '- (list r))]))
  1441. (define (pe_add r1 r2)
  1442. (match* (r1 r2)
  1443. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1444. [(_ _) (Prim '+ (list r1 r2))]))
  1445. (define (pe_sub r1 r2)
  1446. (match* (r1 r2)
  1447. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1448. [(_ _) (Prim '- (list r1 r2))]))
  1449. (define (pe_exp e)
  1450. (match e
  1451. [(Int n) (Int n)]
  1452. [(Prim 'read '()) (Prim 'read '())]
  1453. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1454. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1455. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1456. (define (pe_Lint p)
  1457. (match p
  1458. [(Program '() e) (Program '() (pe_exp e))]))
  1459. \end{lstlisting}
  1460. \fi}
  1461. {\if\edition\pythonEd
  1462. \begin{lstlisting}
  1463. def pe_neg(r):
  1464. match r:
  1465. case Constant(n):
  1466. return Constant(-n)
  1467. case _:
  1468. return UnaryOp(USub(), r)
  1469. def pe_add(r1, r2):
  1470. match (r1, r2):
  1471. case (Constant(n1), Constant(n2)):
  1472. return Constant(n1 + n2)
  1473. case _:
  1474. return BinOp(r1, Add(), r2)
  1475. def pe_sub(r1, r2):
  1476. match (r1, r2):
  1477. case (Constant(n1), Constant(n2)):
  1478. return Constant(n1 - n2)
  1479. case _:
  1480. return BinOp(r1, Sub(), r2)
  1481. def pe_exp(e):
  1482. match e:
  1483. case BinOp(left, Add(), right):
  1484. return pe_add(pe_exp(left), pe_exp(right))
  1485. case BinOp(left, Sub(), right):
  1486. return pe_sub(pe_exp(left), pe_exp(right))
  1487. case UnaryOp(USub(), v):
  1488. return pe_neg(pe_exp(v))
  1489. case Constant(value):
  1490. return e
  1491. case Call(Name('input_int'), []):
  1492. return e
  1493. def pe_stmt(s):
  1494. match s:
  1495. case Expr(Call(Name('print'), [arg])):
  1496. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1497. case Expr(value):
  1498. return Expr(pe_exp(value))
  1499. def pe_P_int(p):
  1500. match p:
  1501. case Module(body):
  1502. new_body = [pe_stmt(s) for s in body]
  1503. return Module(new_body)
  1504. \end{lstlisting}
  1505. \fi}
  1506. \end{tcolorbox}
  1507. \caption{A partial evaluator for \LangInt{}.}
  1508. \label{fig:pe-arith}
  1509. \end{figure}
  1510. To gain some confidence that the partial evaluator is correct, we can
  1511. test whether it produces programs that produce the same result as the
  1512. input programs. That is, we can test whether it satisfies the diagram
  1513. of \eqref{eq:compile-correct}.
  1514. %
  1515. {\if\edition\racketEd
  1516. The following code runs the partial evaluator on several examples and
  1517. tests the output program. The \texttt{parse-program} and
  1518. \texttt{assert} functions are defined in
  1519. appendix~\ref{appendix:utilities}.\\
  1520. \begin{minipage}{1.0\textwidth}
  1521. \begin{lstlisting}
  1522. (define (test_pe p)
  1523. (assert "testing pe_Lint"
  1524. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1525. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1526. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1527. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1528. \end{lstlisting}
  1529. \end{minipage}
  1530. \fi}
  1531. % TODO: python version of testing the PE
  1532. \begin{exercise}\normalfont\normalsize
  1533. Create three programs in the \LangInt{} language and test whether
  1534. partially evaluating them with \code{pe\_Lint} and then
  1535. interpreting them with \code{interp\_Lint} gives the same result
  1536. as directly interpreting them with \code{interp\_Lint}.
  1537. \end{exercise}
  1538. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1539. \chapter{Integers and Variables}
  1540. \label{ch:Lvar}
  1541. \setcounter{footnote}{0}
  1542. This chapter covers compiling a subset of
  1543. \racket{Racket}\python{Python} to x86-64 assembly
  1544. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1545. integer arithmetic and local variables. We often refer to x86-64
  1546. simply as x86. The chapter first describes the \LangVar{} language
  1547. (section~\ref{sec:s0}) and then introduces x86 assembly
  1548. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1549. discuss only the instructions needed for compiling \LangVar{}. We
  1550. introduce more x86 instructions in subsequent chapters. After
  1551. introducing \LangVar{} and x86, we reflect on their differences and
  1552. create a plan to break down the translation from \LangVar{} to x86
  1553. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1554. the chapter gives detailed hints regarding each step. We aim to give
  1555. enough hints that the well-prepared reader, together with a few
  1556. friends, can implement a compiler from \LangVar{} to x86 in a short
  1557. time. To suggest the scale of this first compiler, we note that the
  1558. instructor solution for the \LangVar{} compiler is approximately
  1559. \racket{500}\python{300} lines of code.
  1560. \section{The \LangVar{} Language}
  1561. \label{sec:s0}
  1562. \index{subject}{variable}
  1563. The \LangVar{} language extends the \LangInt{} language with
  1564. variables. The concrete syntax of the \LangVar{} language is defined
  1565. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax} and
  1566. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1567. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1568. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1569. \key{-} is a unary operator, and \key{+} is a binary operator.
  1570. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1571. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1572. the top of the program.
  1573. %% The $\itm{info}$
  1574. %% field of the \key{Program} structure contains an \emph{association
  1575. %% list} (a list of key-value pairs) that is used to communicate
  1576. %% auxiliary data from one compiler pass the next.
  1577. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1578. exhibit several compilation techniques.
  1579. \newcommand{\LvarGrammarRacket}{
  1580. \begin{array}{rcl}
  1581. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1582. \end{array}
  1583. }
  1584. \newcommand{\LvarASTRacket}{
  1585. \begin{array}{rcl}
  1586. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1587. \end{array}
  1588. }
  1589. \newcommand{\LvarGrammarPython}{
  1590. \begin{array}{rcl}
  1591. \Exp &::=& \Var{} \\
  1592. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1593. \end{array}
  1594. }
  1595. \newcommand{\LvarASTPython}{
  1596. \begin{array}{rcl}
  1597. \Exp{} &::=& \VAR{\Var{}} \\
  1598. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1599. \end{array}
  1600. }
  1601. \begin{figure}[tp]
  1602. \centering
  1603. \begin{tcolorbox}[colback=white]
  1604. {\if\edition\racketEd
  1605. \[
  1606. \begin{array}{l}
  1607. \gray{\LintGrammarRacket{}} \\ \hline
  1608. \LvarGrammarRacket{} \\
  1609. \begin{array}{rcl}
  1610. \LangVarM{} &::=& \Exp
  1611. \end{array}
  1612. \end{array}
  1613. \]
  1614. \fi}
  1615. {\if\edition\pythonEd
  1616. \[
  1617. \begin{array}{l}
  1618. \gray{\LintGrammarPython} \\ \hline
  1619. \LvarGrammarPython \\
  1620. \begin{array}{rcl}
  1621. \LangVarM{} &::=& \Stmt^{*}
  1622. \end{array}
  1623. \end{array}
  1624. \]
  1625. \fi}
  1626. \end{tcolorbox}
  1627. \caption{The concrete syntax of \LangVar{}.}
  1628. \label{fig:Lvar-concrete-syntax}
  1629. \end{figure}
  1630. \begin{figure}[tp]
  1631. \centering
  1632. \begin{tcolorbox}[colback=white]
  1633. {\if\edition\racketEd
  1634. \[
  1635. \begin{array}{l}
  1636. \gray{\LintASTRacket{}} \\ \hline
  1637. \LvarASTRacket \\
  1638. \begin{array}{rcl}
  1639. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1640. \end{array}
  1641. \end{array}
  1642. \]
  1643. \fi}
  1644. {\if\edition\pythonEd
  1645. \[
  1646. \begin{array}{l}
  1647. \gray{\LintASTPython}\\ \hline
  1648. \LvarASTPython \\
  1649. \begin{array}{rcl}
  1650. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1651. \end{array}
  1652. \end{array}
  1653. \]
  1654. \fi}
  1655. \end{tcolorbox}
  1656. \caption{The abstract syntax of \LangVar{}.}
  1657. \label{fig:Lvar-syntax}
  1658. \end{figure}
  1659. {\if\edition\racketEd
  1660. Let us dive further into the syntax and semantics of the \LangVar{}
  1661. language. The \key{let} feature defines a variable for use within its
  1662. body and initializes the variable with the value of an expression.
  1663. The abstract syntax for \key{let} is shown in
  1664. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1665. \begin{lstlisting}
  1666. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1667. \end{lstlisting}
  1668. For example, the following program initializes \code{x} to $32$ and then
  1669. evaluates the body \code{(+ 10 x)}, producing $42$.
  1670. \begin{lstlisting}
  1671. (let ([x (+ 12 20)]) (+ 10 x))
  1672. \end{lstlisting}
  1673. \fi}
  1674. %
  1675. {\if\edition\pythonEd
  1676. %
  1677. The \LangVar{} language includes assignment statements, which define a
  1678. variable for use in later statements and initializes the variable with
  1679. the value of an expression. The abstract syntax for assignment is
  1680. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1681. assignment is \index{subject}{Assign@\texttt{Assign}}
  1682. \begin{lstlisting}
  1683. |$\itm{var}$| = |$\itm{exp}$|
  1684. \end{lstlisting}
  1685. For example, the following program initializes the variable \code{x}
  1686. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1687. \begin{lstlisting}
  1688. x = 12 + 20
  1689. print(10 + x)
  1690. \end{lstlisting}
  1691. \fi}
  1692. {\if\edition\racketEd
  1693. %
  1694. When there are multiple \key{let}s for the same variable, the closest
  1695. enclosing \key{let} is used. That is, variable definitions overshadow
  1696. prior definitions. Consider the following program with two \key{let}s
  1697. that define two variables named \code{x}. Can you figure out the
  1698. result?
  1699. \begin{lstlisting}
  1700. (let ([x 32]) (+ (let ([x 10]) x) x))
  1701. \end{lstlisting}
  1702. For the purposes of depicting which variable occurrences correspond to
  1703. which definitions, the following shows the \code{x}'s annotated with
  1704. subscripts to distinguish them. Double check that your answer for the
  1705. previous program is the same as your answer for this annotated version
  1706. of the program.
  1707. \begin{lstlisting}
  1708. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1709. \end{lstlisting}
  1710. The initializing expression is always evaluated before the body of the
  1711. \key{let}, so in the following, the \key{read} for \code{x} is
  1712. performed before the \key{read} for \code{y}. Given the input
  1713. $52$ then $10$, the following produces $42$ (not $-42$).
  1714. \begin{lstlisting}
  1715. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1716. \end{lstlisting}
  1717. \fi}
  1718. \subsection{Extensible Interpreters via Method Overriding}
  1719. \label{sec:extensible-interp}
  1720. To prepare for discussing the interpreter of \LangVar{}, we explain
  1721. why we implement it in an object-oriented style. Throughout this book
  1722. we define many interpreters, one for each language that we
  1723. study. Because each language builds on the prior one, there is a lot
  1724. of commonality between these interpreters. We want to write down the
  1725. common parts just once instead of many times. A naive interpreter for
  1726. \LangVar{} would handle the \racket{cases for variables and
  1727. \code{let}} \python{case for variables} but dispatch to an
  1728. interpreter for \LangInt{} in the rest of the cases. The following
  1729. code sketches this idea. (We explain the \code{env} parameter in
  1730. section~\ref{sec:interp-Lvar}.)
  1731. \begin{center}
  1732. {\if\edition\racketEd
  1733. \begin{minipage}{0.45\textwidth}
  1734. \begin{lstlisting}
  1735. (define ((interp_Lint env) e)
  1736. (match e
  1737. [(Prim '- (list e1))
  1738. (fx- 0 ((interp_Lint env) e1))]
  1739. ...))
  1740. \end{lstlisting}
  1741. \end{minipage}
  1742. \begin{minipage}{0.45\textwidth}
  1743. \begin{lstlisting}
  1744. (define ((interp_Lvar env) e)
  1745. (match e
  1746. [(Var x)
  1747. (dict-ref env x)]
  1748. [(Let x e body)
  1749. (define v ((interp_exp env) e))
  1750. (define env^ (dict-set env x v))
  1751. ((interp_exp env^) body)]
  1752. [else ((interp_Lint env) e)]))
  1753. \end{lstlisting}
  1754. \end{minipage}
  1755. \fi}
  1756. {\if\edition\pythonEd
  1757. \begin{minipage}{0.45\textwidth}
  1758. \begin{lstlisting}
  1759. def interp_Lint(e, env):
  1760. match e:
  1761. case UnaryOp(USub(), e1):
  1762. return - interp_Lint(e1, env)
  1763. ...
  1764. \end{lstlisting}
  1765. \end{minipage}
  1766. \begin{minipage}{0.45\textwidth}
  1767. \begin{lstlisting}
  1768. def interp_Lvar(e, env):
  1769. match e:
  1770. case Name(id):
  1771. return env[id]
  1772. case _:
  1773. return interp_Lint(e, env)
  1774. \end{lstlisting}
  1775. \end{minipage}
  1776. \fi}
  1777. \end{center}
  1778. The problem with this naive approach is that it does not handle
  1779. situations in which an \LangVar{} feature, such as a variable, is
  1780. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1781. in the following program.
  1782. %
  1783. {\if\edition\racketEd
  1784. \begin{lstlisting}
  1785. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1786. \end{lstlisting}
  1787. \fi}
  1788. {\if\edition\pythonEd
  1789. \begin{lstlisting}
  1790. y = 10
  1791. print(-y)
  1792. \end{lstlisting}
  1793. \fi}
  1794. %
  1795. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1796. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1797. then it recursively calls \code{interp\_Lint} again on its argument.
  1798. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1799. an error!
  1800. To make our interpreters extensible we need something called
  1801. \emph{open recursion}\index{subject}{open recursion}, in which the
  1802. tying of the recursive knot is delayed until the functions are
  1803. composed. Object-oriented languages provide open recursion via method
  1804. overriding\index{subject}{method overriding}. The following code uses
  1805. method overriding to interpret \LangInt{} and \LangVar{} using
  1806. %
  1807. \racket{the
  1808. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1809. \index{subject}{class} feature of Racket.}
  1810. %
  1811. \python{a Python \code{class} definition.}
  1812. %
  1813. We define one class for each language and define a method for
  1814. interpreting expressions inside each class. The class for \LangVar{}
  1815. inherits from the class for \LangInt{}, and the method
  1816. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1817. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1818. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1819. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1820. \code{interp\_exp} in \LangInt{}.
  1821. \begin{center}
  1822. \hspace{-20pt}
  1823. {\if\edition\racketEd
  1824. \begin{minipage}{0.45\textwidth}
  1825. \begin{lstlisting}
  1826. (define interp-Lint-class
  1827. (class object%
  1828. (define/public ((interp_exp env) e)
  1829. (match e
  1830. [(Prim '- (list e))
  1831. (fx- 0 ((interp_exp env) e))]
  1832. ...))
  1833. ...))
  1834. \end{lstlisting}
  1835. \end{minipage}
  1836. \begin{minipage}{0.45\textwidth}
  1837. \begin{lstlisting}
  1838. (define interp-Lvar-class
  1839. (class interp-Lint-class
  1840. (define/override ((interp_exp env) e)
  1841. (match e
  1842. [(Var x)
  1843. (dict-ref env x)]
  1844. [(Let x e body)
  1845. (define v ((interp_exp env) e))
  1846. (define env^ (dict-set env x v))
  1847. ((interp_exp env^) body)]
  1848. [else
  1849. (super (interp_exp env) e)]))
  1850. ...
  1851. ))
  1852. \end{lstlisting}
  1853. \end{minipage}
  1854. \fi}
  1855. {\if\edition\pythonEd
  1856. \begin{minipage}{0.45\textwidth}
  1857. \begin{lstlisting}
  1858. class InterpLint:
  1859. def interp_exp(e):
  1860. match e:
  1861. case UnaryOp(USub(), e1):
  1862. return -self.interp_exp(e1)
  1863. ...
  1864. ...
  1865. \end{lstlisting}
  1866. \end{minipage}
  1867. \begin{minipage}{0.45\textwidth}
  1868. \begin{lstlisting}
  1869. def InterpLvar(InterpLint):
  1870. def interp_exp(e):
  1871. match e:
  1872. case Name(id):
  1873. return env[id]
  1874. case _:
  1875. return super().interp_exp(e)
  1876. ...
  1877. \end{lstlisting}
  1878. \end{minipage}
  1879. \fi}
  1880. \end{center}
  1881. Getting back to the troublesome example, repeated here
  1882. {\if\edition\racketEd
  1883. \begin{lstlisting}
  1884. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1885. \end{lstlisting}
  1886. \fi}
  1887. {\if\edition\pythonEd
  1888. \begin{lstlisting}
  1889. y = 10
  1890. print(-y)
  1891. \end{lstlisting}
  1892. \fi}
  1893. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1894. \racket{on this expression,}
  1895. \python{on the \code{-y} expression,}
  1896. %
  1897. which we call \code{e0}, by creating an object of the \LangVar{} class
  1898. and calling the \code{interp\_exp} method
  1899. {\if\edition\racketEd
  1900. \begin{lstlisting}
  1901. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1902. \end{lstlisting}
  1903. \fi}
  1904. {\if\edition\pythonEd
  1905. \begin{lstlisting}
  1906. InterpLvar().interp_exp(e0)
  1907. \end{lstlisting}
  1908. \fi}
  1909. \noindent To process the \code{-} operator, the default case of
  1910. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1911. method in \LangInt{}. But then for the recursive method call, it
  1912. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1913. \code{Var} node is handled correctly. Thus, method overriding gives us
  1914. the open recursion that we need to implement our interpreters in an
  1915. extensible way.
  1916. \subsection{Definitional Interpreter for \LangVar{}}
  1917. \label{sec:interp-Lvar}
  1918. Having justified the use of classes and methods to implement
  1919. interpreters, we revisit the definitional interpreter for \LangInt{}
  1920. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1921. create an interpreter for \LangVar{}, shown in figure~\ref{fig:interp-Lvar}.
  1922. The interpreter for \LangVar{} adds two new \key{match} cases for
  1923. variables and \racket{\key{let}}\python{assignment}. For
  1924. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1925. value bound to a variable to all the uses of the variable. To
  1926. accomplish this, we maintain a mapping from variables to values called
  1927. an \emph{environment}\index{subject}{environment}.
  1928. %
  1929. We use
  1930. %
  1931. \racket{an association list (alist) }%
  1932. %
  1933. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1934. %
  1935. to represent the environment.
  1936. %
  1937. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1938. and the \code{racket/dict} package.}
  1939. %
  1940. The \code{interp\_exp} function takes the current environment,
  1941. \code{env}, as an extra parameter. When the interpreter encounters a
  1942. variable, it looks up the corresponding value in the dictionary.
  1943. %
  1944. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1945. initializing expression, extends the environment with the result
  1946. value bound to the variable, using \code{dict-set}, then evaluates
  1947. the body of the \key{Let}.}
  1948. %
  1949. \python{When the interpreter encounters an assignment, it evaluates
  1950. the initializing expression and then associates the resulting value
  1951. with the variable in the environment.}
  1952. \begin{figure}[tp]
  1953. \begin{tcolorbox}[colback=white]
  1954. {\if\edition\racketEd
  1955. \begin{lstlisting}
  1956. (define interp-Lint-class
  1957. (class object%
  1958. (super-new)
  1959. (define/public ((interp_exp env) e)
  1960. (match e
  1961. [(Int n) n]
  1962. [(Prim 'read '())
  1963. (define r (read))
  1964. (cond [(fixnum? r) r]
  1965. [else (error 'interp_exp "expected an integer" r)])]
  1966. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1967. [(Prim '+ (list e1 e2))
  1968. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1969. [(Prim '- (list e1 e2))
  1970. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1971. (define/public (interp_program p)
  1972. (match p
  1973. [(Program '() e) ((interp_exp '()) e)]))
  1974. ))
  1975. \end{lstlisting}
  1976. \fi}
  1977. {\if\edition\pythonEd
  1978. \begin{lstlisting}
  1979. class InterpLint:
  1980. def interp_exp(self, e, env):
  1981. match e:
  1982. case BinOp(left, Add(), right):
  1983. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1984. case BinOp(left, Sub(), right):
  1985. return self.interp_exp(left, env) - self.interp_exp(right, env)
  1986. case UnaryOp(USub(), v):
  1987. return - self.interp_exp(v, env)
  1988. case Constant(value):
  1989. return value
  1990. case Call(Name('input_int'), []):
  1991. return int(input())
  1992. def interp_stmts(self, ss, env):
  1993. if len(ss) == 0:
  1994. return
  1995. match ss[0]:
  1996. case Expr(Call(Name('print'), [arg])):
  1997. print(self.interp_exp(arg, env), end='')
  1998. return self.interp_stmts(ss[1:], env)
  1999. case Expr(value):
  2000. self.interp_exp(value, env)
  2001. return self.interp_stmts(ss[1:], env)
  2002. def interp(self, p):
  2003. match p:
  2004. case Module(body):
  2005. self.interp_stmts(body, {})
  2006. def interp_Lint(p):
  2007. return InterpLint().interp(p)
  2008. \end{lstlisting}
  2009. \fi}
  2010. \end{tcolorbox}
  2011. \caption{Interpreter for \LangInt{} as a class.}
  2012. \label{fig:interp-Lint-class}
  2013. \end{figure}
  2014. \begin{figure}[tp]
  2015. \begin{tcolorbox}[colback=white]
  2016. {\if\edition\racketEd
  2017. \begin{lstlisting}
  2018. (define interp-Lvar-class
  2019. (class interp-Lint-class
  2020. (super-new)
  2021. (define/override ((interp_exp env) e)
  2022. (match e
  2023. [(Var x) (dict-ref env x)]
  2024. [(Let x e body)
  2025. (define new-env (dict-set env x ((interp_exp env) e)))
  2026. ((interp_exp new-env) body)]
  2027. [else ((super interp-exp env) e)]))
  2028. ))
  2029. (define (interp_Lvar p)
  2030. (send (new interp-Lvar-class) interp_program p))
  2031. \end{lstlisting}
  2032. \fi}
  2033. {\if\edition\pythonEd
  2034. \begin{lstlisting}
  2035. class InterpLvar(InterpLint):
  2036. def interp_exp(self, e, env):
  2037. match e:
  2038. case Name(id):
  2039. return env[id]
  2040. case _:
  2041. return super().interp_exp(e, env)
  2042. def interp_stmts(self, ss, env):
  2043. if len(ss) == 0:
  2044. return
  2045. match ss[0]:
  2046. case Assign([lhs], value):
  2047. env[lhs.id] = self.interp_exp(value, env)
  2048. return self.interp_stmts(ss[1:], env)
  2049. case _:
  2050. return super().interp_stmts(ss, env)
  2051. def interp_Lvar(p):
  2052. return InterpLvar().interp(p)
  2053. \end{lstlisting}
  2054. \fi}
  2055. \end{tcolorbox}
  2056. \caption{Interpreter for the \LangVar{} language.}
  2057. \label{fig:interp-Lvar}
  2058. \end{figure}
  2059. {\if\edition\racketEd
  2060. \begin{figure}[tp]
  2061. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2062. \small
  2063. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2064. An \emph{association list} (called an alist) is a list of key-value pairs.
  2065. For example, we can map people to their ages with an alist
  2066. \index{subject}{alist}\index{subject}{association list}
  2067. \begin{lstlisting}[basicstyle=\ttfamily]
  2068. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2069. \end{lstlisting}
  2070. The \emph{dictionary} interface is for mapping keys to values.
  2071. Every alist implements this interface. \index{subject}{dictionary}
  2072. The package
  2073. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2074. provides many functions for working with dictionaries, such as
  2075. \begin{description}
  2076. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2077. returns the value associated with the given $\itm{key}$.
  2078. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2079. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2080. and otherwise is the same as $\itm{dict}$.
  2081. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2082. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2083. of keys and values in $\itm{dict}$. For example, the following
  2084. creates a new alist in which the ages are incremented:
  2085. \end{description}
  2086. \vspace{-10pt}
  2087. \begin{lstlisting}[basicstyle=\ttfamily]
  2088. (for/list ([(k v) (in-dict ages)])
  2089. (cons k (add1 v)))
  2090. \end{lstlisting}
  2091. \end{tcolorbox}
  2092. %\end{wrapfigure}
  2093. \caption{Association lists implement the dictionary interface.}
  2094. \label{fig:alist}
  2095. \end{figure}
  2096. \fi}
  2097. The goal for this chapter is to implement a compiler that translates
  2098. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2099. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2100. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2101. That is, they output the same integer $n$. We depict this correctness
  2102. criteria in the following diagram:
  2103. \[
  2104. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2105. \node (p1) at (0, 0) {$P_1$};
  2106. \node (p2) at (4, 0) {$P_2$};
  2107. \node (o) at (4, -2) {$n$};
  2108. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2109. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2110. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2111. \end{tikzpicture}
  2112. \]
  2113. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2114. compiling \LangVar{}.
  2115. \section{The \LangXInt{} Assembly Language}
  2116. \label{sec:x86}
  2117. \index{subject}{x86}
  2118. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2119. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2120. assembler.
  2121. %
  2122. A program begins with a \code{main} label followed by a sequence of
  2123. instructions. The \key{globl} directive makes the \key{main} procedure
  2124. externally visible so that the operating system can call it.
  2125. %
  2126. An x86 program is stored in the computer's memory. For our purposes,
  2127. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2128. values. The computer has a \emph{program counter}
  2129. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2130. \code{rip} register that points to the address of the next instruction
  2131. to be executed. For most instructions, the program counter is
  2132. incremented after the instruction is executed so that it points to the
  2133. next instruction in memory. Most x86 instructions take two operands,
  2134. each of which is an integer constant (called an \emph{immediate
  2135. value}\index{subject}{immediate value}), a
  2136. \emph{register}\index{subject}{register}, or a memory location.
  2137. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2138. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2139. && \key{r8} \MID \key{r9} \MID \key{r10}
  2140. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2141. \MID \key{r14} \MID \key{r15}}
  2142. \newcommand{\GrammarXInt}{
  2143. \begin{array}{rcl}
  2144. \Reg &::=& \allregisters{} \\
  2145. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2146. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2147. \key{subq} \; \Arg\key{,} \Arg \MID
  2148. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2149. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2150. \key{callq} \; \mathit{label} \MID
  2151. \key{retq} \MID
  2152. \key{jmp}\,\itm{label} \MID \\
  2153. && \itm{label}\key{:}\; \Instr
  2154. \end{array}
  2155. }
  2156. \begin{figure}[tp]
  2157. \begin{tcolorbox}[colback=white]
  2158. {\if\edition\racketEd
  2159. \[
  2160. \begin{array}{l}
  2161. \GrammarXInt \\
  2162. \begin{array}{lcl}
  2163. \LangXIntM{} &::= & \key{.globl main}\\
  2164. & & \key{main:} \; \Instr\ldots
  2165. \end{array}
  2166. \end{array}
  2167. \]
  2168. \fi}
  2169. {\if\edition\pythonEd
  2170. \[
  2171. \begin{array}{lcl}
  2172. \Reg &::=& \allregisters{} \\
  2173. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2174. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2175. \key{subq} \; \Arg\key{,} \Arg \MID
  2176. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2177. && \key{callq} \; \mathit{label} \MID
  2178. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2179. \LangXIntM{} &::= & \key{.globl main}\\
  2180. & & \key{main:} \; \Instr^{*}
  2181. \end{array}
  2182. \]
  2183. \fi}
  2184. \end{tcolorbox}
  2185. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2186. \label{fig:x86-int-concrete}
  2187. \end{figure}
  2188. A register is a special kind of variable that holds a 64-bit
  2189. value. There are 16 general-purpose registers in the computer; their
  2190. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2191. written with a percent sign, \key{\%}, followed by the register name,
  2192. for example \key{\%rax}.
  2193. An immediate value is written using the notation \key{\$}$n$ where $n$
  2194. is an integer.
  2195. %
  2196. %
  2197. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2198. which obtains the address stored in register $r$ and then adds $n$
  2199. bytes to the address. The resulting address is used to load or to store
  2200. to memory depending on whether it occurs as a source or destination
  2201. argument of an instruction.
  2202. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2203. the source $s$ and destination $d$, applies the arithmetic operation,
  2204. and then writes the result to the destination $d$. \index{subject}{instruction}
  2205. %
  2206. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2207. stores the result in $d$.
  2208. %
  2209. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2210. specified by the label, and $\key{retq}$ returns from a procedure to
  2211. its caller.
  2212. %
  2213. We discuss procedure calls in more detail further in this chapter and
  2214. in chapter~\ref{ch:Lfun}.
  2215. %
  2216. The last letter \key{q} indicates that these instructions operate on
  2217. quadwords which are 64-bit values.
  2218. %
  2219. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2220. counter to the address of the instruction immediately after the
  2221. specified label.}
  2222. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2223. all the x86 instructions used in this book.
  2224. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2225. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2226. \lstinline{movq $10, %rax}
  2227. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2228. adds $32$ to the $10$ in \key{rax} and
  2229. puts the result, $42$, into \key{rax}.
  2230. %
  2231. The last instruction \key{retq} finishes the \key{main} function by
  2232. returning the integer in \key{rax} to the operating system. The
  2233. operating system interprets this integer as the program's exit
  2234. code. By convention, an exit code of 0 indicates that a program has
  2235. completed successfully, and all other exit codes indicate various
  2236. errors.
  2237. %
  2238. \racket{However, in this book we return the result of the program
  2239. as the exit code.}
  2240. \begin{figure}[tbp]
  2241. \begin{minipage}{0.45\textwidth}
  2242. \begin{tcolorbox}[colback=white]
  2243. \begin{lstlisting}
  2244. .globl main
  2245. main:
  2246. movq $10, %rax
  2247. addq $32, %rax
  2248. retq
  2249. \end{lstlisting}
  2250. \end{tcolorbox}
  2251. \end{minipage}
  2252. \caption{An x86 program that computes
  2253. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2254. \label{fig:p0-x86}
  2255. \end{figure}
  2256. We exhibit the use of memory for storing intermediate results in the
  2257. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2258. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2259. uses a region of memory called the \emph{procedure call stack}
  2260. (\emph{stack} for
  2261. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2262. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2263. for each procedure call. The memory layout for an individual frame is
  2264. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2265. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2266. address of the item at the top of the stack. In general, we use the
  2267. term \emph{pointer}\index{subject}{pointer} for something that
  2268. contains an address. The stack grows downward in memory, so we
  2269. increase the size of the stack by subtracting from the stack pointer.
  2270. In the context of a procedure call, the \emph{return
  2271. address}\index{subject}{return address} is the location of the
  2272. instruction that immediately follows the call instruction on the
  2273. caller side. The function call instruction, \code{callq}, pushes the
  2274. return address onto the stack prior to jumping to the procedure. The
  2275. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2276. pointer} and is used to access variables that are stored in the
  2277. frame of the current procedure call. The base pointer of the caller
  2278. is stored immediately after the return address.
  2279. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2280. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2281. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2282. $-16\key{(\%rbp)}$, and so on.
  2283. \begin{figure}[tbp]
  2284. \begin{minipage}{0.66\textwidth}
  2285. \begin{tcolorbox}[colback=white]
  2286. {\if\edition\racketEd
  2287. \begin{lstlisting}
  2288. start:
  2289. movq $10, -8(%rbp)
  2290. negq -8(%rbp)
  2291. movq -8(%rbp), %rax
  2292. addq $52, %rax
  2293. jmp conclusion
  2294. .globl main
  2295. main:
  2296. pushq %rbp
  2297. movq %rsp, %rbp
  2298. subq $16, %rsp
  2299. jmp start
  2300. conclusion:
  2301. addq $16, %rsp
  2302. popq %rbp
  2303. retq
  2304. \end{lstlisting}
  2305. \fi}
  2306. {\if\edition\pythonEd
  2307. \begin{lstlisting}
  2308. .globl main
  2309. main:
  2310. pushq %rbp
  2311. movq %rsp, %rbp
  2312. subq $16, %rsp
  2313. movq $10, -8(%rbp)
  2314. negq -8(%rbp)
  2315. movq -8(%rbp), %rax
  2316. addq $52, %rax
  2317. addq $16, %rsp
  2318. popq %rbp
  2319. retq
  2320. \end{lstlisting}
  2321. \fi}
  2322. \end{tcolorbox}
  2323. \end{minipage}
  2324. \caption{An x86 program that computes
  2325. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2326. \label{fig:p1-x86}
  2327. \end{figure}
  2328. \begin{figure}[tbp]
  2329. \begin{minipage}{0.66\textwidth}
  2330. \begin{tcolorbox}[colback=white]
  2331. \centering
  2332. \begin{tabular}{|r|l|} \hline
  2333. Position & Contents \\ \hline
  2334. $8$(\key{\%rbp}) & return address \\
  2335. $0$(\key{\%rbp}) & old \key{rbp} \\
  2336. $-8$(\key{\%rbp}) & variable $1$ \\
  2337. $-16$(\key{\%rbp}) & variable $2$ \\
  2338. \ldots & \ldots \\
  2339. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2340. \end{tabular}
  2341. \end{tcolorbox}
  2342. \end{minipage}
  2343. \caption{Memory layout of a frame.}
  2344. \label{fig:frame}
  2345. \end{figure}
  2346. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2347. is transferred from the operating system to the \code{main} function.
  2348. The operating system issues a \code{callq main} instruction that
  2349. pushes its return address on the stack and then jumps to
  2350. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2351. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2352. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2353. out of alignment (because the \code{callq} pushed the return address).
  2354. The first three instructions are the typical
  2355. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2356. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2357. pointer \code{rsp} and then saves the base pointer of the caller at
  2358. address \code{rsp} on the stack. The next instruction \code{movq
  2359. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2360. which is pointing to the location of the old base pointer. The
  2361. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2362. make enough room for storing variables. This program needs one
  2363. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2364. 16-byte-aligned, and then we are ready to make calls to other functions.
  2365. \racket{The last instruction of the prelude is \code{jmp start}, which
  2366. transfers control to the instructions that were generated from the
  2367. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2368. \racket{The first instruction under the \code{start} label is}
  2369. %
  2370. \python{The first instruction after the prelude is}
  2371. %
  2372. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2373. %
  2374. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2375. $1$ to $-10$.
  2376. %
  2377. The next instruction moves the $-10$ from variable $1$ into the
  2378. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2379. the value in \code{rax}, updating its contents to $42$.
  2380. \racket{The three instructions under the label \code{conclusion} are the
  2381. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2382. %
  2383. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2384. \code{main} function consists of the last three instructions.}
  2385. %
  2386. The first two restore the \code{rsp} and \code{rbp} registers to their
  2387. states at the beginning of the procedure. In particular,
  2388. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2389. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2390. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2391. \key{retq}, jumps back to the procedure that called this one and adds
  2392. $8$ to the stack pointer.
  2393. Our compiler needs a convenient representation for manipulating x86
  2394. programs, so we define an abstract syntax for x86, shown in
  2395. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2396. \LangXInt{}.
  2397. %
  2398. {\if\edition\pythonEd%
  2399. The main difference between this and the concrete syntax of \LangXInt{}
  2400. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2401. names, and register names are explicitly represented by strings.
  2402. \fi} %
  2403. {\if\edition\racketEd
  2404. The main difference between this and the concrete syntax of \LangXInt{}
  2405. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2406. front of every instruction. Instead instructions are grouped into
  2407. \emph{basic blocks}\index{subject}{basic block} with a
  2408. label associated with every basic block; this is why the \key{X86Program}
  2409. struct includes an alist mapping labels to basic blocks. The reason for this
  2410. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2411. introduce conditional branching. The \code{Block} structure includes
  2412. an $\itm{info}$ field that is not needed in this chapter but becomes
  2413. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2414. $\itm{info}$ field should contain an empty list.
  2415. \fi}
  2416. %
  2417. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2418. node includes an integer for representing the arity of the function,
  2419. that is, the number of arguments, which is helpful to know during
  2420. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2421. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2422. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2423. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2424. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2425. \MID \skey{r14} \MID \skey{r15}}
  2426. \newcommand{\ASTXIntRacket}{
  2427. \begin{array}{lcl}
  2428. \Reg &::=& \allregisters{} \\
  2429. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2430. \MID \DEREF{\Reg}{\Int} \\
  2431. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2432. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}
  2433. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2434. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2435. \MID \PUSHQ{\Arg}
  2436. \MID \POPQ{\Arg} \\
  2437. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2438. \MID \RETQ{}
  2439. \MID \JMP{\itm{label}} \\
  2440. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2441. \end{array}
  2442. }
  2443. \begin{figure}[tp]
  2444. \begin{tcolorbox}[colback=white]
  2445. \small
  2446. {\if\edition\racketEd
  2447. \[\arraycolsep=3pt
  2448. \begin{array}{l}
  2449. \ASTXIntRacket \\
  2450. \begin{array}{lcl}
  2451. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2452. \end{array}
  2453. \end{array}
  2454. \]
  2455. \fi}
  2456. {\if\edition\pythonEd
  2457. \[
  2458. \begin{array}{lcl}
  2459. \Reg &::=& \allastregisters{} \\
  2460. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2461. \MID \DEREF{\Reg}{\Int} \\
  2462. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2463. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2464. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2465. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2466. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2467. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2468. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2469. \end{array}
  2470. \]
  2471. \fi}
  2472. \end{tcolorbox}
  2473. \caption{The abstract syntax of \LangXInt{} assembly.}
  2474. \label{fig:x86-int-ast}
  2475. \end{figure}
  2476. \section{Planning the Trip to x86}
  2477. \label{sec:plan-s0-x86}
  2478. To compile one language to another, it helps to focus on the
  2479. differences between the two languages because the compiler will need
  2480. to bridge those differences. What are the differences between \LangVar{}
  2481. and x86 assembly? Here are some of the most important ones:
  2482. \begin{enumerate}
  2483. \item x86 arithmetic instructions typically have two arguments and
  2484. update the second argument in place. In contrast, \LangVar{}
  2485. arithmetic operations take two arguments and produce a new value.
  2486. An x86 instruction may have at most one memory-accessing argument.
  2487. Furthermore, some x86 instructions place special restrictions on
  2488. their arguments.
  2489. \item An argument of an \LangVar{} operator can be a deeply nested
  2490. expression, whereas x86 instructions restrict their arguments to be
  2491. integer constants, registers, and memory locations.
  2492. {\if\edition\racketEd
  2493. \item The order of execution in x86 is explicit in the syntax, which
  2494. is a sequence of instructions and jumps to labeled positions,
  2495. whereas in \LangVar{} the order of evaluation is a left-to-right
  2496. depth-first traversal of the abstract syntax tree. \fi}
  2497. \item A program in \LangVar{} can have any number of variables,
  2498. whereas x86 has 16 registers and the procedure call stack.
  2499. {\if\edition\racketEd
  2500. \item Variables in \LangVar{} can shadow other variables with the
  2501. same name. In x86, registers have unique names, and memory locations
  2502. have unique addresses.
  2503. \fi}
  2504. \end{enumerate}
  2505. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2506. down the problem into several steps, which deal with these differences
  2507. one at a time. Each of these steps is called a \emph{pass} of the
  2508. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2509. %
  2510. This term indicates that each step passes over, or traverses, the AST
  2511. of the program.
  2512. %
  2513. Furthermore, we follow the nanopass approach, which means that we
  2514. strive for each pass to accomplish one clear objective rather than two
  2515. or three at the same time.
  2516. %
  2517. We begin by sketching how we might implement each pass and give each
  2518. pass a name. We then figure out an ordering of the passes and the
  2519. input/output language for each pass. The very first pass has
  2520. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2521. its output language. In between these two passes, we can choose
  2522. whichever language is most convenient for expressing the output of
  2523. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2524. \emph{intermediate languages} of our own design. Finally, to
  2525. implement each pass we write one recursive function per nonterminal in
  2526. the grammar of the input language of the pass.
  2527. \index{subject}{intermediate language}
  2528. Our compiler for \LangVar{} consists of the following passes:
  2529. %
  2530. \begin{description}
  2531. {\if\edition\racketEd
  2532. \item[\key{uniquify}] deals with the shadowing of variables by
  2533. renaming every variable to a unique name.
  2534. \fi}
  2535. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2536. of a primitive operation or function call is a variable or integer,
  2537. that is, an \emph{atomic} expression. We refer to nonatomic
  2538. expressions as \emph{complex}. This pass introduces temporary
  2539. variables to hold the results of complex
  2540. subexpressions.\index{subject}{atomic
  2541. expression}\index{subject}{complex expression}%
  2542. {\if\edition\racketEd
  2543. \item[\key{explicate\_control}] makes the execution order of the
  2544. program explicit. It converts the abstract syntax tree
  2545. representation into a graph in which each node is a labeled sequence
  2546. of statements and the edges are \code{goto} statements.
  2547. \fi}
  2548. \item[\key{select\_instructions}] handles the difference between
  2549. \LangVar{} operations and x86 instructions. This pass converts each
  2550. \LangVar{} operation to a short sequence of instructions that
  2551. accomplishes the same task.
  2552. \item[\key{assign\_homes}] replaces variables with registers or stack
  2553. locations.
  2554. \end{description}
  2555. %
  2556. {\if\edition\racketEd
  2557. %
  2558. Our treatment of \code{remove\_complex\_operands} and
  2559. \code{explicate\_control} as separate passes is an example of the
  2560. nanopass approach\footnote{For analogous decompositions of the
  2561. translation into continuation passing style, see the work of
  2562. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2563. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2564. %
  2565. \fi}
  2566. The next question is, in what order should we apply these passes? This
  2567. question can be challenging because it is difficult to know ahead of
  2568. time which orderings will be better (that is, will be easier to
  2569. implement, produce more efficient code, and so on), and therefore
  2570. ordering often involves trial and error. Nevertheless, we can plan
  2571. ahead and make educated choices regarding the ordering.
  2572. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2573. \key{uniquify}? The \key{uniquify} pass should come first because
  2574. \key{explicate\_control} changes all the \key{let}-bound variables to
  2575. become local variables whose scope is the entire program, which would
  2576. confuse variables with the same name.}
  2577. %
  2578. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2579. because the later removes the \key{let} form, but it is convenient to
  2580. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2581. %
  2582. \racket{The ordering of \key{uniquify} with respect to
  2583. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2584. \key{uniquify} to come first.}
  2585. The \key{select\_instructions} and \key{assign\_homes} passes are
  2586. intertwined.
  2587. %
  2588. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2589. passing arguments to functions and that it is preferable to assign
  2590. parameters to their corresponding registers. This suggests that it
  2591. would be better to start with the \key{select\_instructions} pass,
  2592. which generates the instructions for argument passing, before
  2593. performing register allocation.
  2594. %
  2595. On the other hand, by selecting instructions first we may run into a
  2596. dead end in \key{assign\_homes}. Recall that only one argument of an
  2597. x86 instruction may be a memory access, but \key{assign\_homes} might
  2598. be forced to assign both arguments to memory locations.
  2599. %
  2600. A sophisticated approach is to repeat the two passes until a solution
  2601. is found. However, to reduce implementation complexity we recommend
  2602. placing \key{select\_instructions} first, followed by the
  2603. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2604. that uses a reserved register to fix outstanding problems.
  2605. \begin{figure}[tbp]
  2606. \begin{tcolorbox}[colback=white]
  2607. {\if\edition\racketEd
  2608. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2609. \node (Lvar) at (0,2) {\large \LangVar{}};
  2610. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2611. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2612. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2613. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2614. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2615. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2616. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2617. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2618. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2619. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2620. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2621. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2622. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2623. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2624. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2625. \end{tikzpicture}
  2626. \fi}
  2627. {\if\edition\pythonEd
  2628. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2629. \node (Lvar) at (0,2) {\large \LangVar{}};
  2630. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2631. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2632. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2633. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2634. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2635. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2636. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2637. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2638. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2639. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2640. \end{tikzpicture}
  2641. \fi}
  2642. \end{tcolorbox}
  2643. \caption{Diagram of the passes for compiling \LangVar{}. }
  2644. \label{fig:Lvar-passes}
  2645. \end{figure}
  2646. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2647. passes and identifies the input and output language of each pass.
  2648. %
  2649. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2650. language, which extends \LangXInt{} with an unbounded number of
  2651. program-scope variables and removes the restrictions regarding
  2652. instruction arguments.
  2653. %
  2654. The last pass, \key{prelude\_and\_conclusion}, places the program
  2655. instructions inside a \code{main} function with instructions for the
  2656. prelude and conclusion.
  2657. %
  2658. \racket{In the next section we discuss the \LangCVar{} intermediate
  2659. language that serves as the output of \code{explicate\_control}.}
  2660. %
  2661. The remainder of this chapter provides guidance on the implementation
  2662. of each of the compiler passes represented in
  2663. figure~\ref{fig:Lvar-passes}.
  2664. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2665. %% are programs that are still in the \LangVar{} language, though the
  2666. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2667. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2668. %% %
  2669. %% The output of \code{explicate\_control} is in an intermediate language
  2670. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2671. %% syntax, which we introduce in the next section. The
  2672. %% \key{select-instruction} pass translates from \LangCVar{} to
  2673. %% \LangXVar{}. The \key{assign-homes} and
  2674. %% \key{patch-instructions}
  2675. %% passes input and output variants of x86 assembly.
  2676. \newcommand{\CvarGrammarRacket}{
  2677. \begin{array}{lcl}
  2678. \Atm &::=& \Int \MID \Var \\
  2679. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2680. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2681. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2682. \end{array}
  2683. }
  2684. \newcommand{\CvarASTRacket}{
  2685. \begin{array}{lcl}
  2686. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2687. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2688. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2689. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2690. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2691. \end{array}
  2692. }
  2693. {\if\edition\racketEd
  2694. \subsection{The \LangCVar{} Intermediate Language}
  2695. The output of \code{explicate\_control} is similar to the C
  2696. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2697. categories for expressions and statements, so we name it \LangCVar{}.
  2698. This style of intermediate language is also known as
  2699. \emph{three-address code}, to emphasize that the typical form of a
  2700. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2701. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2702. The concrete syntax for \LangCVar{} is shown in
  2703. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2704. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2705. %
  2706. The \LangCVar{} language supports the same operators as \LangVar{} but
  2707. the arguments of operators are restricted to atomic
  2708. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2709. assignment statements that can be executed in sequence using the
  2710. \key{Seq} form. A sequence of statements always ends with
  2711. \key{Return}, a guarantee that is baked into the grammar rules for
  2712. \itm{tail}. The naming of this nonterminal comes from the term
  2713. \emph{tail position}\index{subject}{tail position}, which refers to an
  2714. expression that is the last one to execute within a function or
  2715. program.
  2716. A \LangCVar{} program consists of an alist mapping labels to
  2717. tails. This is more general than necessary for the present chapter, as
  2718. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2719. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2720. there is just one label, \key{start}, and the whole program is
  2721. its tail.
  2722. %
  2723. The $\itm{info}$ field of the \key{CProgram} form, after the
  2724. \code{explicate\_control} pass, contains an alist that associates the
  2725. symbol \key{locals} with a list of all the variables used in the
  2726. program. At the start of the program, these variables are
  2727. uninitialized; they become initialized on their first assignment.
  2728. \begin{figure}[tbp]
  2729. \begin{tcolorbox}[colback=white]
  2730. \[
  2731. \begin{array}{l}
  2732. \CvarGrammarRacket \\
  2733. \begin{array}{lcl}
  2734. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2735. \end{array}
  2736. \end{array}
  2737. \]
  2738. \end{tcolorbox}
  2739. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2740. \label{fig:c0-concrete-syntax}
  2741. \end{figure}
  2742. \begin{figure}[tbp]
  2743. \begin{tcolorbox}[colback=white]
  2744. \[
  2745. \begin{array}{l}
  2746. \CvarASTRacket \\
  2747. \begin{array}{lcl}
  2748. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2749. \end{array}
  2750. \end{array}
  2751. \]
  2752. \end{tcolorbox}
  2753. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2754. \label{fig:c0-syntax}
  2755. \end{figure}
  2756. The definitional interpreter for \LangCVar{} is in the support code,
  2757. in the file \code{interp-Cvar.rkt}.
  2758. \fi}
  2759. {\if\edition\racketEd
  2760. \section{Uniquify Variables}
  2761. \label{sec:uniquify-Lvar}
  2762. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2763. programs in which every \key{let} binds a unique variable name. For
  2764. example, the \code{uniquify} pass should translate the program on the
  2765. left into the program on the right.
  2766. \begin{transformation}
  2767. \begin{lstlisting}
  2768. (let ([x 32])
  2769. (+ (let ([x 10]) x) x))
  2770. \end{lstlisting}
  2771. \compilesto
  2772. \begin{lstlisting}
  2773. (let ([x.1 32])
  2774. (+ (let ([x.2 10]) x.2) x.1))
  2775. \end{lstlisting}
  2776. \end{transformation}
  2777. The following is another example translation, this time of a program
  2778. with a \key{let} nested inside the initializing expression of another
  2779. \key{let}.
  2780. \begin{transformation}
  2781. \begin{lstlisting}
  2782. (let ([x (let ([x 4])
  2783. (+ x 1))])
  2784. (+ x 2))
  2785. \end{lstlisting}
  2786. \compilesto
  2787. \begin{lstlisting}
  2788. (let ([x.2 (let ([x.1 4])
  2789. (+ x.1 1))])
  2790. (+ x.2 2))
  2791. \end{lstlisting}
  2792. \end{transformation}
  2793. We recommend implementing \code{uniquify} by creating a structurally
  2794. recursive function named \code{uniquify\_exp} that does little other
  2795. than copy an expression. However, when encountering a \key{let}, it
  2796. should generate a unique name for the variable and associate the old
  2797. name with the new name in an alist.\footnote{The Racket function
  2798. \code{gensym} is handy for generating unique variable names.} The
  2799. \code{uniquify\_exp} function needs to access this alist when it gets
  2800. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2801. for the alist.
  2802. The skeleton of the \code{uniquify\_exp} function is shown in
  2803. figure~\ref{fig:uniquify-Lvar}.
  2804. %% The function is curried so that it is
  2805. %% convenient to partially apply it to an alist and then apply it to
  2806. %% different expressions, as in the last case for primitive operations in
  2807. %% figure~\ref{fig:uniquify-Lvar}.
  2808. The
  2809. %
  2810. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2811. %
  2812. form of Racket is useful for transforming the element of a list to
  2813. produce a new list.\index{subject}{for/list}
  2814. \begin{figure}[tbp]
  2815. \begin{tcolorbox}[colback=white]
  2816. \begin{lstlisting}
  2817. (define (uniquify_exp env)
  2818. (lambda (e)
  2819. (match e
  2820. [(Var x) ___]
  2821. [(Int n) (Int n)]
  2822. [(Let x e body) ___]
  2823. [(Prim op es)
  2824. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2825. (define (uniquify p)
  2826. (match p
  2827. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2828. \end{lstlisting}
  2829. \end{tcolorbox}
  2830. \caption{Skeleton for the \key{uniquify} pass.}
  2831. \label{fig:uniquify-Lvar}
  2832. \end{figure}
  2833. \begin{exercise}
  2834. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2835. Complete the \code{uniquify} pass by filling in the blanks in
  2836. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2837. variables and for the \key{let} form in the file \code{compiler.rkt}
  2838. in the support code.
  2839. \end{exercise}
  2840. \begin{exercise}
  2841. \normalfont\normalsize
  2842. \label{ex:Lvar}
  2843. Create five \LangVar{} programs that exercise the most interesting
  2844. parts of the \key{uniquify} pass; that is, the programs should include
  2845. \key{let} forms, variables, and variables that shadow each other.
  2846. The five programs should be placed in the subdirectory named
  2847. \key{tests}, and the file names should start with \code{var\_test\_}
  2848. followed by a unique integer and end with the file extension
  2849. \key{.rkt}.
  2850. %
  2851. The \key{run-tests.rkt} script in the support code checks whether the
  2852. output programs produce the same result as the input programs. The
  2853. script uses the \key{interp-tests} function
  2854. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2855. your \key{uniquify} pass on the example programs. The \code{passes}
  2856. parameter of \key{interp-tests} is a list that should have one entry
  2857. for each pass in your compiler. For now, define \code{passes} to
  2858. contain just one entry for \code{uniquify} as follows:
  2859. \begin{lstlisting}
  2860. (define passes
  2861. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2862. \end{lstlisting}
  2863. Run the \key{run-tests.rkt} script in the support code to check
  2864. whether the output programs produce the same result as the input
  2865. programs.
  2866. \end{exercise}
  2867. \fi}
  2868. \section{Remove Complex Operands}
  2869. \label{sec:remove-complex-opera-Lvar}
  2870. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2871. into a restricted form in which the arguments of operations are atomic
  2872. expressions. Put another way, this pass removes complex
  2873. operands\index{subject}{complex operand}, such as the expression
  2874. \racket{\code{(- 10)}}\python{\code{-10}}
  2875. in the following program. This is accomplished by introducing a new
  2876. temporary variable, assigning the complex operand to the new
  2877. variable, and then using the new variable in place of the complex
  2878. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2879. right.
  2880. {\if\edition\racketEd
  2881. \begin{transformation}
  2882. % var_test_19.rkt
  2883. \begin{lstlisting}
  2884. (let ([x (+ 42 (- 10))])
  2885. (+ x 10))
  2886. \end{lstlisting}
  2887. \compilesto
  2888. \begin{lstlisting}
  2889. (let ([x (let ([tmp.1 (- 10)])
  2890. (+ 42 tmp.1))])
  2891. (+ x 10))
  2892. \end{lstlisting}
  2893. \end{transformation}
  2894. \fi}
  2895. {\if\edition\pythonEd
  2896. \begin{transformation}
  2897. \begin{lstlisting}
  2898. x = 42 + -10
  2899. print(x + 10)
  2900. \end{lstlisting}
  2901. \compilesto
  2902. \begin{lstlisting}
  2903. tmp_0 = -10
  2904. x = 42 + tmp_0
  2905. tmp_1 = x + 10
  2906. print(tmp_1)
  2907. \end{lstlisting}
  2908. \end{transformation}
  2909. \fi}
  2910. \newcommand{\LvarMonadASTRacket}{
  2911. \begin{array}{rcl}
  2912. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2913. \Exp &::=& \Atm \MID \READ{} \\
  2914. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2915. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2916. \end{array}
  2917. }
  2918. \newcommand{\LvarMonadASTPython}{
  2919. \begin{array}{rcl}
  2920. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2921. \Exp{} &::=& \Atm \MID \READ{} \\
  2922. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2923. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2924. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2925. \end{array}
  2926. }
  2927. \begin{figure}[tp]
  2928. \centering
  2929. \begin{tcolorbox}[colback=white]
  2930. {\if\edition\racketEd
  2931. \[
  2932. \begin{array}{l}
  2933. \LvarMonadASTRacket \\
  2934. \begin{array}{rcl}
  2935. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2936. \end{array}
  2937. \end{array}
  2938. \]
  2939. \fi}
  2940. {\if\edition\pythonEd
  2941. \[
  2942. \begin{array}{l}
  2943. \LvarMonadASTPython \\
  2944. \begin{array}{rcl}
  2945. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2946. \end{array}
  2947. \end{array}
  2948. \]
  2949. \fi}
  2950. \end{tcolorbox}
  2951. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2952. atomic expressions.}
  2953. \label{fig:Lvar-anf-syntax}
  2954. \end{figure}
  2955. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2956. of this pass, the language \LangVarANF{}. The only difference is that
  2957. operator arguments are restricted to be atomic expressions that are
  2958. defined by the \Atm{} nonterminal. In particular, integer constants
  2959. and variables are atomic.
  2960. The atomic expressions are pure (they do not cause or depend on side
  2961. effects) whereas complex expressions may have side effects, such as
  2962. \READ{}. A language with this separation between pure expression
  2963. versus expressions with side effects is said to be in monadic normal
  2964. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  2965. in the name \LangVarANF{}. An important invariant of the
  2966. \code{remove\_complex\_operands} pass is that the relative ordering
  2967. among complex expressions is not changed, but the relative ordering
  2968. between atomic expressions and complex expressions can change and
  2969. often does. The reason that these changes are behavior preserving is
  2970. that the atomic expressions are pure.
  2971. Another well-known form for intermediate languages is the
  2972. \emph{administrative normal form}
  2973. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2974. \index{subject}{administrative normal form} \index{subject}{ANF}
  2975. %
  2976. The \LangVarANF{} language is not quite in ANF because we allow the
  2977. right-hand side of a \code{let} to be a complex expression.
  2978. {\if\edition\racketEd
  2979. We recommend implementing this pass with two mutually recursive
  2980. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2981. \code{rco\_atom} to subexpressions that need to become atomic and to
  2982. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2983. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2984. returns an expression. The \code{rco\_atom} function returns two
  2985. things: an atomic expression and an alist mapping temporary variables to
  2986. complex subexpressions. You can return multiple things from a function
  2987. using Racket's \key{values} form, and you can receive multiple things
  2988. from a function call using the \key{define-values} form.
  2989. \fi}
  2990. %
  2991. {\if\edition\pythonEd
  2992. %
  2993. We recommend implementing this pass with an auxiliary method named
  2994. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2995. Boolean that specifies whether the expression needs to become atomic
  2996. or not. The \code{rco\_exp} method should return a pair consisting of
  2997. the new expression and a list of pairs, associating new temporary
  2998. variables with their initializing expressions.
  2999. %
  3000. \fi}
  3001. {\if\edition\racketEd
  3002. %
  3003. Returning to the example program with the expression \code{(+ 42 (-
  3004. 10))}, the subexpression \code{(- 10)} should be processed using the
  3005. \code{rco\_atom} function because it is an argument of the \code{+}
  3006. operator and therefore needs to become atomic. The output of
  3007. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3008. \begin{transformation}
  3009. \begin{lstlisting}
  3010. (- 10)
  3011. \end{lstlisting}
  3012. \compilesto
  3013. \begin{lstlisting}
  3014. tmp.1
  3015. ((tmp.1 . (- 10)))
  3016. \end{lstlisting}
  3017. \end{transformation}
  3018. \fi}
  3019. %
  3020. {\if\edition\pythonEd
  3021. %
  3022. Returning to the example program with the expression \code{42 + -10},
  3023. the subexpression \code{-10} should be processed using the
  3024. \code{rco\_exp} function with \code{True} as the second argument
  3025. because \code{-10} is an argument of the \code{+} operator and
  3026. therefore needs to become atomic. The output of \code{rco\_exp}
  3027. applied to \code{-10} is as follows.
  3028. \begin{transformation}
  3029. \begin{lstlisting}
  3030. -10
  3031. \end{lstlisting}
  3032. \compilesto
  3033. \begin{lstlisting}
  3034. tmp_1
  3035. [(tmp_1, -10)]
  3036. \end{lstlisting}
  3037. \end{transformation}
  3038. %
  3039. \fi}
  3040. Take special care of programs, such as the following, that
  3041. %
  3042. \racket{bind a variable to an atomic expression.}
  3043. %
  3044. \python{assign an atomic expression to a variable.}
  3045. %
  3046. You should leave such \racket{variable bindings}\python{assignments}
  3047. unchanged, as shown in the program on the right\\
  3048. %
  3049. {\if\edition\racketEd
  3050. \begin{transformation}
  3051. % var_test_20.rkt
  3052. \begin{lstlisting}
  3053. (let ([a 42])
  3054. (let ([b a])
  3055. b))
  3056. \end{lstlisting}
  3057. \compilesto
  3058. \begin{lstlisting}
  3059. (let ([a 42])
  3060. (let ([b a])
  3061. b))
  3062. \end{lstlisting}
  3063. \end{transformation}
  3064. \fi}
  3065. {\if\edition\pythonEd
  3066. \begin{transformation}
  3067. \begin{lstlisting}
  3068. a = 42
  3069. b = a
  3070. print(b)
  3071. \end{lstlisting}
  3072. \compilesto
  3073. \begin{lstlisting}
  3074. a = 42
  3075. b = a
  3076. print(b)
  3077. \end{lstlisting}
  3078. \end{transformation}
  3079. \fi}
  3080. %
  3081. \noindent A careless implementation might produce the following output with
  3082. unnecessary temporary variables.
  3083. \begin{center}
  3084. \begin{minipage}{0.4\textwidth}
  3085. {\if\edition\racketEd
  3086. \begin{lstlisting}
  3087. (let ([tmp.1 42])
  3088. (let ([a tmp.1])
  3089. (let ([tmp.2 a])
  3090. (let ([b tmp.2])
  3091. b))))
  3092. \end{lstlisting}
  3093. \fi}
  3094. {\if\edition\pythonEd
  3095. \begin{lstlisting}
  3096. tmp_1 = 42
  3097. a = tmp_1
  3098. tmp_2 = a
  3099. b = tmp_2
  3100. print(b)
  3101. \end{lstlisting}
  3102. \fi}
  3103. \end{minipage}
  3104. \end{center}
  3105. \begin{exercise}
  3106. \normalfont\normalsize
  3107. {\if\edition\racketEd
  3108. Implement the \code{remove\_complex\_operands} function in
  3109. \code{compiler.rkt}.
  3110. %
  3111. Create three new \LangVar{} programs that exercise the interesting
  3112. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3113. regarding file names described in exercise~\ref{ex:Lvar}.
  3114. %
  3115. In the \code{run-tests.rkt} script, add the following entry to the
  3116. list of \code{passes}, and then run the script to test your compiler.
  3117. \begin{lstlisting}
  3118. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3119. \end{lstlisting}
  3120. In debugging your compiler, it is often useful to see the intermediate
  3121. programs that are output from each pass. To print the intermediate
  3122. programs, place \lstinline{(debug-level 1)} before the call to
  3123. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3124. %
  3125. {\if\edition\pythonEd
  3126. Implement the \code{remove\_complex\_operands} pass in
  3127. \code{compiler.py}, creating auxiliary functions for each
  3128. nonterminal in the grammar, i.e., \code{rco\_exp}
  3129. and \code{rco\_stmt}. We recommend you use the function
  3130. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3131. \fi}
  3132. \end{exercise}
  3133. {\if\edition\pythonEd
  3134. \begin{exercise}
  3135. \normalfont\normalsize
  3136. \label{ex:Lvar}
  3137. Create five \LangVar{} programs that exercise the most interesting
  3138. parts of the \code{remove\_complex\_operands} pass. The five programs
  3139. should be placed in the subdirectory named \key{tests}, and the file
  3140. names should start with \code{var\_test\_} followed by a unique
  3141. integer and end with the file extension \key{.py}.
  3142. %% The \key{run-tests.rkt} script in the support code checks whether the
  3143. %% output programs produce the same result as the input programs. The
  3144. %% script uses the \key{interp-tests} function
  3145. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3146. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3147. %% parameter of \key{interp-tests} is a list that should have one entry
  3148. %% for each pass in your compiler. For now, define \code{passes} to
  3149. %% contain just one entry for \code{uniquify} as shown below.
  3150. %% \begin{lstlisting}
  3151. %% (define passes
  3152. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3153. %% \end{lstlisting}
  3154. Run the \key{run-tests.py} script in the support code to check
  3155. whether the output programs produce the same result as the input
  3156. programs.
  3157. \end{exercise}
  3158. \fi}
  3159. {\if\edition\racketEd
  3160. \section{Explicate Control}
  3161. \label{sec:explicate-control-Lvar}
  3162. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3163. programs that make the order of execution explicit in their
  3164. syntax. For now this amounts to flattening \key{let} constructs into a
  3165. sequence of assignment statements. For example, consider the following
  3166. \LangVar{} program:\\
  3167. % var_test_11.rkt
  3168. \begin{minipage}{0.96\textwidth}
  3169. \begin{lstlisting}
  3170. (let ([y (let ([x 20])
  3171. (+ x (let ([x 22]) x)))])
  3172. y)
  3173. \end{lstlisting}
  3174. \end{minipage}\\
  3175. %
  3176. The output of the previous pass is shown next, on the left, and the
  3177. output of \code{explicate\_control} is on the right. Recall that the
  3178. right-hand side of a \key{let} executes before its body, so that the order
  3179. of evaluation for this program is to assign \code{20} to \code{x.1},
  3180. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3181. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3182. this ordering explicit.
  3183. \begin{transformation}
  3184. \begin{lstlisting}
  3185. (let ([y (let ([x.1 20])
  3186. (let ([x.2 22])
  3187. (+ x.1 x.2)))])
  3188. y)
  3189. \end{lstlisting}
  3190. \compilesto
  3191. \begin{lstlisting}[language=C]
  3192. start:
  3193. x.1 = 20;
  3194. x.2 = 22;
  3195. y = (+ x.1 x.2);
  3196. return y;
  3197. \end{lstlisting}
  3198. \end{transformation}
  3199. \begin{figure}[tbp]
  3200. \begin{tcolorbox}[colback=white]
  3201. \begin{lstlisting}
  3202. (define (explicate_tail e)
  3203. (match e
  3204. [(Var x) ___]
  3205. [(Int n) (Return (Int n))]
  3206. [(Let x rhs body) ___]
  3207. [(Prim op es) ___]
  3208. [else (error "explicate_tail unhandled case" e)]))
  3209. (define (explicate_assign e x cont)
  3210. (match e
  3211. [(Var x) ___]
  3212. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3213. [(Let y rhs body) ___]
  3214. [(Prim op es) ___]
  3215. [else (error "explicate_assign unhandled case" e)]))
  3216. (define (explicate_control p)
  3217. (match p
  3218. [(Program info body) ___]))
  3219. \end{lstlisting}
  3220. \end{tcolorbox}
  3221. \caption{Skeleton for the \code{explicate\_control} pass.}
  3222. \label{fig:explicate-control-Lvar}
  3223. \end{figure}
  3224. The organization of this pass depends on the notion of tail position
  3225. to which we have alluded. Here is the definition.
  3226. \begin{definition}\normalfont
  3227. The following rules define when an expression is in \emph{tail
  3228. position}\index{subject}{tail position} for the language \LangVar{}.
  3229. \begin{enumerate}
  3230. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3231. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3232. \end{enumerate}
  3233. \end{definition}
  3234. We recommend implementing \code{explicate\_control} using two
  3235. recursive functions, \code{explicate\_tail} and
  3236. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3237. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3238. function should be applied to expressions in tail position, whereas the
  3239. \code{explicate\_assign} should be applied to expressions that occur on
  3240. the right-hand side of a \key{let}.
  3241. %
  3242. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3243. input and produces a \Tail{} in \LangCVar{} (see
  3244. figure~\ref{fig:c0-syntax}).
  3245. %
  3246. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3247. the variable to which it is to be assigned to, and a \Tail{} in
  3248. \LangCVar{} for the code that comes after the assignment. The
  3249. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3250. The \code{explicate\_assign} function is in accumulator-passing style:
  3251. the \code{cont} parameter is used for accumulating the output. This
  3252. accumulator-passing style plays an important role in the way that we
  3253. generate high-quality code for conditional expressions in
  3254. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3255. continuation because it contains the generated code that should come
  3256. after the current assignment. This code organization is also related
  3257. to continuation-passing style, except that \code{cont} is not what
  3258. happens next during compilation but is what happens next in the
  3259. generated code.
  3260. \begin{exercise}\normalfont\normalsize
  3261. %
  3262. Implement the \code{explicate\_control} function in
  3263. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3264. exercise the code in \code{explicate\_control}.
  3265. %
  3266. In the \code{run-tests.rkt} script, add the following entry to the
  3267. list of \code{passes} and then run the script to test your compiler.
  3268. \begin{lstlisting}
  3269. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3270. \end{lstlisting}
  3271. \end{exercise}
  3272. \fi}
  3273. \section{Select Instructions}
  3274. \label{sec:select-Lvar}
  3275. \index{subject}{instruction selection}
  3276. In the \code{select\_instructions} pass we begin the work of
  3277. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3278. language of this pass is a variant of x86 that still uses variables,
  3279. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3280. nonterminal of the \LangXInt{} abstract syntax
  3281. (figure~\ref{fig:x86-int-ast}).
  3282. \racket{We recommend implementing the
  3283. \code{select\_instructions} with three auxiliary functions, one for
  3284. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3285. $\Tail$.}
  3286. \python{We recommend implementing an auxiliary function
  3287. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3288. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3289. same and integer constants change to immediates; that is, $\INT{n}$
  3290. changes to $\IMM{n}$.}
  3291. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3292. arithmetic operations. For example, consider the following addition
  3293. operation, on the left side. There is an \key{addq} instruction in
  3294. x86, but it performs an in-place update. So, we could move $\Arg_1$
  3295. into the left-hand \itm{var} and then add $\Arg_2$ to \itm{var},
  3296. where $\Arg_1$ and $\Arg_2$ are the translations of $\Atm_1$ and
  3297. $\Atm_2$, respectively.
  3298. \begin{transformation}
  3299. {\if\edition\racketEd
  3300. \begin{lstlisting}
  3301. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3302. \end{lstlisting}
  3303. \fi}
  3304. {\if\edition\pythonEd
  3305. \begin{lstlisting}
  3306. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3307. \end{lstlisting}
  3308. \fi}
  3309. \compilesto
  3310. \begin{lstlisting}
  3311. movq |$\Arg_1$|, |$\itm{var}$|
  3312. addq |$\Arg_2$|, |$\itm{var}$|
  3313. \end{lstlisting}
  3314. \end{transformation}
  3315. There are also cases that require special care to avoid generating
  3316. needlessly complicated code. For example, if one of the arguments of
  3317. the addition is the same variable as the left-hand side of the
  3318. assignment, as shown next, then there is no need for the extra move
  3319. instruction. The assignment statement can be translated into a single
  3320. \key{addq} instruction, as follows.
  3321. \begin{transformation}
  3322. {\if\edition\racketEd
  3323. \begin{lstlisting}
  3324. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3325. \end{lstlisting}
  3326. \fi}
  3327. {\if\edition\pythonEd
  3328. \begin{lstlisting}
  3329. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3330. \end{lstlisting}
  3331. \fi}
  3332. \compilesto
  3333. \begin{lstlisting}
  3334. addq |$\Arg_1$|, |$\itm{var}$|
  3335. \end{lstlisting}
  3336. \end{transformation}
  3337. The \READOP{} operation does not have a direct counterpart in x86
  3338. assembly, so we provide this functionality with the function
  3339. \code{read\_int} in the file \code{runtime.c}, written in
  3340. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3341. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3342. system}, or simply the \emph{runtime} for short. When compiling your
  3343. generated x86 assembly code, you need to compile \code{runtime.c} to
  3344. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3345. \code{-c}) and link it into the executable. For our purposes of code
  3346. generation, all you need to do is translate an assignment of
  3347. \READOP{} into a call to the \code{read\_int} function followed by a
  3348. move from \code{rax} to the left-hand side variable. (Recall that the
  3349. return value of a function goes into \code{rax}.)
  3350. \begin{transformation}
  3351. {\if\edition\racketEd
  3352. \begin{lstlisting}
  3353. |$\itm{var}$| = (read);
  3354. \end{lstlisting}
  3355. \fi}
  3356. {\if\edition\pythonEd
  3357. \begin{lstlisting}
  3358. |$\itm{var}$| = input_int();
  3359. \end{lstlisting}
  3360. \fi}
  3361. \compilesto
  3362. \begin{lstlisting}
  3363. callq read_int
  3364. movq %rax, |$\itm{var}$|
  3365. \end{lstlisting}
  3366. \end{transformation}
  3367. {\if\edition\pythonEd
  3368. %
  3369. Similarly, we translate the \code{print} operation, shown below, into
  3370. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3371. In x86, the first six arguments to functions are passed in registers,
  3372. with the first argument passed in register \code{rdi}. So we move the
  3373. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3374. \code{callq} instruction.
  3375. \begin{transformation}
  3376. \begin{lstlisting}
  3377. print(|$\Atm$|)
  3378. \end{lstlisting}
  3379. \compilesto
  3380. \begin{lstlisting}
  3381. movq |$\Arg$|, %rdi
  3382. callq print_int
  3383. \end{lstlisting}
  3384. \end{transformation}
  3385. %
  3386. \fi}
  3387. {\if\edition\racketEd
  3388. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3389. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3390. assignment to the \key{rax} register followed by a jump to the
  3391. conclusion of the program (so the conclusion needs to be labeled).
  3392. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3393. recursively and then append the resulting instructions.
  3394. \fi}
  3395. {\if\edition\pythonEd
  3396. We recommend that you use the function \code{utils.label\_name()} to
  3397. transform a string into an label argument suitably suitable for, e.g.,
  3398. the target of the \code{callq} instruction. This practice makes your
  3399. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3400. all labels.
  3401. \fi}
  3402. \begin{exercise}
  3403. \normalfont\normalsize
  3404. {\if\edition\racketEd
  3405. Implement the \code{select\_instructions} pass in
  3406. \code{compiler.rkt}. Create three new example programs that are
  3407. designed to exercise all the interesting cases in this pass.
  3408. %
  3409. In the \code{run-tests.rkt} script, add the following entry to the
  3410. list of \code{passes} and then run the script to test your compiler.
  3411. \begin{lstlisting}
  3412. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3413. \end{lstlisting}
  3414. \fi}
  3415. {\if\edition\pythonEd
  3416. Implement the \key{select\_instructions} pass in
  3417. \code{compiler.py}. Create three new example programs that are
  3418. designed to exercise all of the interesting cases in this pass.
  3419. Run the \code{run-tests.py} script to to check
  3420. whether the output programs produce the same result as the input
  3421. programs.
  3422. \fi}
  3423. \end{exercise}
  3424. \section{Assign Homes}
  3425. \label{sec:assign-Lvar}
  3426. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3427. \LangXVar{} programs that no longer use program variables. Thus, the
  3428. \code{assign\_homes} pass is responsible for placing all the program
  3429. variables in registers or on the stack. For runtime efficiency, it is
  3430. better to place variables in registers, but because there are only
  3431. sixteen registers, some programs must necessarily resort to placing
  3432. some variables on the stack. In this chapter we focus on the mechanics
  3433. of placing variables on the stack. We study an algorithm for placing
  3434. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3435. Consider again the following \LangVar{} program from
  3436. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3437. % var_test_20.rkt
  3438. \begin{minipage}{0.96\textwidth}
  3439. {\if\edition\racketEd
  3440. \begin{lstlisting}
  3441. (let ([a 42])
  3442. (let ([b a])
  3443. b))
  3444. \end{lstlisting}
  3445. \fi}
  3446. {\if\edition\pythonEd
  3447. \begin{lstlisting}
  3448. a = 42
  3449. b = a
  3450. print(b)
  3451. \end{lstlisting}
  3452. \fi}
  3453. \end{minipage}\\
  3454. %
  3455. The output of \code{select\_instructions} is shown next, on the left,
  3456. and the output of \code{assign\_homes} is on the right. In this
  3457. example, we assign variable \code{a} to stack location
  3458. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3459. \begin{transformation}
  3460. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3461. movq $42, a
  3462. movq a, b
  3463. movq b, %rax
  3464. \end{lstlisting}
  3465. \compilesto
  3466. %stack-space: 16
  3467. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3468. movq $42, -8(%rbp)
  3469. movq -8(%rbp), -16(%rbp)
  3470. movq -16(%rbp), %rax
  3471. \end{lstlisting}
  3472. \end{transformation}
  3473. \racket{
  3474. The \code{assign\_homes} pass should replace all variables
  3475. with stack locations.
  3476. The list of variables can be obtained from
  3477. the \code{locals-types} entry in the $\itm{info}$ of the
  3478. \code{X86Program} node. The \code{locals-types} entry is an alist
  3479. mapping all the variables in the program to their types
  3480. (for now, just \code{Integer}).
  3481. As an aside, the \code{locals-types} entry is
  3482. computed by \code{type-check-Cvar} in the support code, which
  3483. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3484. which you should propagate to the \code{X86Program} node.}
  3485. %
  3486. \python{The \code{assign\_homes} pass should replace all uses of
  3487. variables with stack locations.}
  3488. %
  3489. In the process of assigning variables to stack locations, it is
  3490. convenient for you to compute and store the size of the frame (in
  3491. bytes) in
  3492. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3493. %
  3494. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3495. %
  3496. which is needed later to generate the conclusion of the \code{main}
  3497. procedure. The x86-64 standard requires the frame size to be a
  3498. multiple of 16 bytes.\index{subject}{frame}
  3499. % TODO: store the number of variables instead? -Jeremy
  3500. \begin{exercise}\normalfont\normalsize
  3501. Implement the \code{assign\_homes} pass in
  3502. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3503. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3504. grammar. We recommend that the auxiliary functions take an extra
  3505. parameter that maps variable names to homes (stack locations for now).
  3506. %
  3507. {\if\edition\racketEd
  3508. In the \code{run-tests.rkt} script, add the following entry to the
  3509. list of \code{passes} and then run the script to test your compiler.
  3510. \begin{lstlisting}
  3511. (list "assign homes" assign-homes interp_x86-0)
  3512. \end{lstlisting}
  3513. \fi}
  3514. {\if\edition\pythonEd
  3515. Run the \code{run-tests.py} script to to check
  3516. whether the output programs produce the same result as the input
  3517. programs.
  3518. \fi}
  3519. \end{exercise}
  3520. \section{Patch Instructions}
  3521. \label{sec:patch-s0}
  3522. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3523. \LangXInt{} by making sure that each instruction adheres to the
  3524. restriction that at most one argument of an instruction may be a
  3525. memory reference.
  3526. We return to the following example.\\
  3527. \begin{minipage}{0.5\textwidth}
  3528. % var_test_20.rkt
  3529. {\if\edition\racketEd
  3530. \begin{lstlisting}
  3531. (let ([a 42])
  3532. (let ([b a])
  3533. b))
  3534. \end{lstlisting}
  3535. \fi}
  3536. {\if\edition\pythonEd
  3537. \begin{lstlisting}
  3538. a = 42
  3539. b = a
  3540. print(b)
  3541. \end{lstlisting}
  3542. \fi}
  3543. \end{minipage}\\
  3544. The \code{assign\_homes} pass produces the following translation. \\
  3545. \begin{minipage}{0.5\textwidth}
  3546. {\if\edition\racketEd
  3547. \begin{lstlisting}
  3548. movq $42, -8(%rbp)
  3549. movq -8(%rbp), -16(%rbp)
  3550. movq -16(%rbp), %rax
  3551. \end{lstlisting}
  3552. \fi}
  3553. {\if\edition\pythonEd
  3554. \begin{lstlisting}
  3555. movq 42, -8(%rbp)
  3556. movq -8(%rbp), -16(%rbp)
  3557. movq -16(%rbp), %rdi
  3558. callq print_int
  3559. \end{lstlisting}
  3560. \fi}
  3561. \end{minipage}\\
  3562. The second \key{movq} instruction is problematic because both
  3563. arguments are stack locations. We suggest fixing this problem by
  3564. moving from the source location to the register \key{rax} and then
  3565. from \key{rax} to the destination location, as follows.
  3566. \begin{lstlisting}
  3567. movq -8(%rbp), %rax
  3568. movq %rax, -16(%rbp)
  3569. \end{lstlisting}
  3570. \begin{exercise}
  3571. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3572. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3573. Create three new example programs that are
  3574. designed to exercise all the interesting cases in this pass.
  3575. %
  3576. {\if\edition\racketEd
  3577. In the \code{run-tests.rkt} script, add the following entry to the
  3578. list of \code{passes} and then run the script to test your compiler.
  3579. \begin{lstlisting}
  3580. (list "patch instructions" patch_instructions interp_x86-0)
  3581. \end{lstlisting}
  3582. \fi}
  3583. {\if\edition\pythonEd
  3584. Run the \code{run-tests.py} script to to check
  3585. whether the output programs produce the same result as the input
  3586. programs.
  3587. \fi}
  3588. \end{exercise}
  3589. \section{Generate Prelude and Conclusion}
  3590. \label{sec:print-x86}
  3591. \index{subject}{prelude}\index{subject}{conclusion}
  3592. The last step of the compiler from \LangVar{} to x86 is to generate
  3593. the \code{main} function with a prelude and conclusion wrapped around
  3594. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3595. discussed in section~\ref{sec:x86}.
  3596. When running on Mac OS X, your compiler should prefix an underscore to
  3597. all labels, e.g., changing \key{main} to \key{\_main}.
  3598. %
  3599. \racket{The Racket call \code{(system-type 'os)} is useful for
  3600. determining which operating system the compiler is running on. It
  3601. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3602. %
  3603. \python{The Python \code{platform} library includes a \code{system()}
  3604. function that returns \code{'Linux'}, \code{'Windows'}, or
  3605. \code{'Darwin'} (for Mac).}
  3606. \begin{exercise}\normalfont\normalsize
  3607. %
  3608. Implement the \key{prelude\_and\_conclusion} pass in
  3609. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3610. %
  3611. {\if\edition\racketEd
  3612. In the \code{run-tests.rkt} script, add the following entry to the
  3613. list of \code{passes} and then run the script to test your compiler.
  3614. \begin{lstlisting}
  3615. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3616. \end{lstlisting}
  3617. %
  3618. Uncomment the call to the \key{compiler-tests} function
  3619. (appendix~\ref{appendix:utilities}), which tests your complete
  3620. compiler by executing the generated x86 code. It translates the x86
  3621. AST that you produce into a string by invoking the \code{print-x86}
  3622. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3623. the provided \key{runtime.c} file to \key{runtime.o} using
  3624. \key{gcc}. Run the script to test your compiler.
  3625. %
  3626. \fi}
  3627. {\if\edition\pythonEd
  3628. %
  3629. Run the \code{run-tests.py} script to to check whether the output
  3630. programs produce the same result as the input programs. That script
  3631. translates the x86 AST that you produce into a string by invoking the
  3632. \code{repr} method that is implemented by the x86 AST classes in
  3633. \code{x86\_ast.py}.
  3634. %
  3635. \fi}
  3636. \end{exercise}
  3637. \section{Challenge: Partial Evaluator for \LangVar{}}
  3638. \label{sec:pe-Lvar}
  3639. \index{subject}{partial evaluation}
  3640. This section describes two optional challenge exercises that involve
  3641. adapting and improving the partial evaluator for \LangInt{} that was
  3642. introduced in section~\ref{sec:partial-evaluation}.
  3643. \begin{exercise}\label{ex:pe-Lvar}
  3644. \normalfont\normalsize
  3645. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3646. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3647. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3648. %
  3649. \racket{\key{let} binding}\python{assignment}
  3650. %
  3651. to the \LangInt{} language, so you will need to add cases for them in
  3652. the \code{pe\_exp}
  3653. %
  3654. \racket{function.}
  3655. %
  3656. \python{and \code{pe\_stmt} functions.}
  3657. %
  3658. Once complete, add the partial evaluation pass to the front of your
  3659. compiler, and make sure that your compiler still passes all of the
  3660. tests.
  3661. \end{exercise}
  3662. \begin{exercise}
  3663. \normalfont\normalsize
  3664. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3665. \code{pe\_add} auxiliary functions with functions that know more about
  3666. arithmetic. For example, your partial evaluator should translate
  3667. {\if\edition\racketEd
  3668. \[
  3669. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3670. \code{(+ 2 (read))}
  3671. \]
  3672. \fi}
  3673. {\if\edition\pythonEd
  3674. \[
  3675. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3676. \code{2 + input\_int()}
  3677. \]
  3678. \fi}
  3679. %
  3680. To accomplish this, the \code{pe\_exp} function should produce output
  3681. in the form of the $\itm{residual}$ nonterminal of the following
  3682. grammar. The idea is that when processing an addition expression, we
  3683. can always produce one of the following: (1) an integer constant, (2)
  3684. an addition expression with an integer constant on the left-hand side
  3685. but not the right-hand side, or (3) an addition expression in which
  3686. neither subexpression is a constant.
  3687. %
  3688. {\if\edition\racketEd
  3689. \[
  3690. \begin{array}{lcl}
  3691. \itm{inert} &::=& \Var
  3692. \MID \LP\key{read}\RP
  3693. \MID \LP\key{-} ~\Var\RP
  3694. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3695. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3696. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3697. \itm{residual} &::=& \Int
  3698. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3699. \MID \itm{inert}
  3700. \end{array}
  3701. \]
  3702. \fi}
  3703. {\if\edition\pythonEd
  3704. \[
  3705. \begin{array}{lcl}
  3706. \itm{inert} &::=& \Var
  3707. \MID \key{input\_int}\LP\RP
  3708. \MID \key{-} \Var
  3709. \MID \key{-} \key{input\_int}\LP\RP
  3710. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3711. \itm{residual} &::=& \Int
  3712. \MID \Int ~ \key{+} ~ \itm{inert}
  3713. \MID \itm{inert}
  3714. \end{array}
  3715. \]
  3716. \fi}
  3717. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3718. inputs are $\itm{residual}$ expressions and they should return
  3719. $\itm{residual}$ expressions. Once the improvements are complete,
  3720. make sure that your compiler still passes all of the tests. After
  3721. all, fast code is useless if it produces incorrect results!
  3722. \end{exercise}
  3723. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3724. \chapter{Register Allocation}
  3725. \label{ch:register-allocation-Lvar}
  3726. \setcounter{footnote}{0}
  3727. \index{subject}{register allocation}
  3728. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  3729. storing variables on the procedure call stack. The CPU may require tens
  3730. to hundreds of cycles to access a location on the stack, whereas
  3731. accessing a register takes only a single cycle. In this chapter we
  3732. improve the efficiency of our generated code by storing some variables
  3733. in registers. The goal of register allocation is to fit as many
  3734. variables into registers as possible. Some programs have more
  3735. variables than registers, so we cannot always map each variable to a
  3736. different register. Fortunately, it is common for different variables
  3737. to be in use during different periods of time during program
  3738. execution, and in those cases we can map multiple variables to the
  3739. same register.
  3740. The program shown in figure~\ref{fig:reg-eg} serves as a running
  3741. example. The source program is on the left and the output of
  3742. instruction selection is on the right. The program is almost
  3743. completely in the x86 assembly language, but it still uses variables.
  3744. Consider variables \code{x} and \code{z}. After the variable \code{x}
  3745. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  3746. the other hand, is used only after this point, so \code{x} and
  3747. \code{z} could share the same register.
  3748. \begin{figure}
  3749. \begin{tcolorbox}[colback=white]
  3750. \begin{minipage}{0.45\textwidth}
  3751. Example \LangVar{} program:
  3752. % var_test_28.rkt
  3753. {\if\edition\racketEd
  3754. \begin{lstlisting}
  3755. (let ([v 1])
  3756. (let ([w 42])
  3757. (let ([x (+ v 7)])
  3758. (let ([y x])
  3759. (let ([z (+ x w)])
  3760. (+ z (- y)))))))
  3761. \end{lstlisting}
  3762. \fi}
  3763. {\if\edition\pythonEd
  3764. \begin{lstlisting}
  3765. v = 1
  3766. w = 42
  3767. x = v + 7
  3768. y = x
  3769. z = x + w
  3770. print(z + (- y))
  3771. \end{lstlisting}
  3772. \fi}
  3773. \end{minipage}
  3774. \begin{minipage}{0.45\textwidth}
  3775. After instruction selection:
  3776. {\if\edition\racketEd
  3777. \begin{lstlisting}
  3778. locals-types:
  3779. x : Integer, y : Integer,
  3780. z : Integer, t : Integer,
  3781. v : Integer, w : Integer
  3782. start:
  3783. movq $1, v
  3784. movq $42, w
  3785. movq v, x
  3786. addq $7, x
  3787. movq x, y
  3788. movq x, z
  3789. addq w, z
  3790. movq y, t
  3791. negq t
  3792. movq z, %rax
  3793. addq t, %rax
  3794. jmp conclusion
  3795. \end{lstlisting}
  3796. \fi}
  3797. {\if\edition\pythonEd
  3798. \begin{lstlisting}
  3799. movq $1, v
  3800. movq $42, w
  3801. movq v, x
  3802. addq $7, x
  3803. movq x, y
  3804. movq x, z
  3805. addq w, z
  3806. movq y, tmp_0
  3807. negq tmp_0
  3808. movq z, tmp_1
  3809. addq tmp_0, tmp_1
  3810. movq tmp_1, %rdi
  3811. callq print_int
  3812. \end{lstlisting}
  3813. \fi}
  3814. \end{minipage}
  3815. \end{tcolorbox}
  3816. \caption{A running example for register allocation.}
  3817. \label{fig:reg-eg}
  3818. \end{figure}
  3819. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  3820. compute where a variable is in use. Once we have that information, we
  3821. compute which variables are in use at the same time, i.e., which ones
  3822. \emph{interfere}\index{subject}{interfere} with each other, and
  3823. represent this relation as an undirected graph whose vertices are
  3824. variables and edges indicate when two variables interfere
  3825. (section~\ref{sec:build-interference}). We then model register
  3826. allocation as a graph coloring problem
  3827. (section~\ref{sec:graph-coloring}).
  3828. If we run out of registers despite these efforts, we place the
  3829. remaining variables on the stack, similarly to how we handled
  3830. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  3831. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3832. location. The decision to spill a variable is handled as part of the
  3833. graph coloring process.
  3834. We make the simplifying assumption that each variable is assigned to
  3835. one location (a register or stack address). A more sophisticated
  3836. approach is to assign a variable to one or more locations in different
  3837. regions of the program. For example, if a variable is used many times
  3838. in short sequence and then used again only after many other
  3839. instructions, it could be more efficient to assign the variable to a
  3840. register during the initial sequence and then move it to the stack for
  3841. the rest of its lifetime. We refer the interested reader to
  3842. \citet{Cooper:2011aa} (chapter 13) for more information about that
  3843. approach.
  3844. % discuss prioritizing variables based on how much they are used.
  3845. \section{Registers and Calling Conventions}
  3846. \label{sec:calling-conventions}
  3847. \index{subject}{calling conventions}
  3848. As we perform register allocation, we must be aware of the
  3849. \emph{calling conventions} \index{subject}{calling conventions} that
  3850. govern how functions calls are performed in x86.
  3851. %
  3852. Even though \LangVar{} does not include programmer-defined functions,
  3853. our generated code includes a \code{main} function that is called by
  3854. the operating system and our generated code contains calls to the
  3855. \code{read\_int} function.
  3856. Function calls require coordination between two pieces of code that
  3857. may be written by different programmers or generated by different
  3858. compilers. Here we follow the System V calling conventions that are
  3859. used by the GNU C compiler on Linux and
  3860. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3861. %
  3862. The calling conventions include rules about how functions share the
  3863. use of registers. In particular, the caller is responsible for freeing
  3864. some registers prior to the function call for use by the callee.
  3865. These are called the \emph{caller-saved registers}
  3866. \index{subject}{caller-saved registers}
  3867. and they are
  3868. \begin{lstlisting}
  3869. rax rcx rdx rsi rdi r8 r9 r10 r11
  3870. \end{lstlisting}
  3871. On the other hand, the callee is responsible for preserving the values
  3872. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3873. which are
  3874. \begin{lstlisting}
  3875. rsp rbp rbx r12 r13 r14 r15
  3876. \end{lstlisting}
  3877. We can think about this caller/callee convention from two points of
  3878. view, the caller view and the callee view, as follows:
  3879. \begin{itemize}
  3880. \item The caller should assume that all the caller-saved registers get
  3881. overwritten with arbitrary values by the callee. On the other hand,
  3882. the caller can safely assume that all the callee-saved registers
  3883. retain their original values.
  3884. \item The callee can freely use any of the caller-saved registers.
  3885. However, if the callee wants to use a callee-saved register, the
  3886. callee must arrange to put the original value back in the register
  3887. prior to returning to the caller. This can be accomplished by saving
  3888. the value to the stack in the prelude of the function and restoring
  3889. the value in the conclusion of the function.
  3890. \end{itemize}
  3891. In x86, registers are also used for passing arguments to a function
  3892. and for the return value. In particular, the first six arguments of a
  3893. function are passed in the following six registers, in this order.
  3894. \index{subject}{argument-passing registers}
  3895. \index{subject}{parameter-passing registers}
  3896. \begin{lstlisting}
  3897. rdi rsi rdx rcx r8 r9
  3898. \end{lstlisting}
  3899. If there are more than six arguments, the convention is to use
  3900. space on the frame of the caller for the rest of the
  3901. arguments. However, in chapter~\ref{ch:Lfun} we arrange never to
  3902. need more than six arguments.
  3903. %
  3904. \racket{For now, the only function we care about is \code{read\_int},
  3905. which takes zero arguments.}
  3906. %
  3907. \python{For now, the only functions we care about are \code{read\_int}
  3908. and \code{print\_int}, which take zero and one argument, respectively.}
  3909. %
  3910. The register \code{rax} is used for the return value of a function.
  3911. The next question is how these calling conventions impact register
  3912. allocation. Consider the \LangVar{} program presented in
  3913. figure~\ref{fig:example-calling-conventions}. We first analyze this
  3914. example from the caller point of view and then from the callee point
  3915. of view. We refer to a variable that is in use during a function call
  3916. as a \emph{call-live variable}\index{subject}{call-live variable}.
  3917. The program makes two calls to \READOP{}. The variable \code{x} is
  3918. call-live because it is in use during the second call to \READOP{}; we
  3919. must ensure that the value in \code{x} does not get overwritten during
  3920. the call to \READOP{}. One obvious approach is to save all the values
  3921. that reside in caller-saved registers to the stack prior to each
  3922. function call and to restore them after each call. That way, if the
  3923. register allocator chooses to assign \code{x} to a caller-saved
  3924. register, its value will be preserved across the call to \READOP{}.
  3925. However, saving and restoring to the stack is relatively slow. If
  3926. \code{x} is not used many times, it may be better to assign \code{x}
  3927. to a stack location in the first place. Or better yet, if we can
  3928. arrange for \code{x} to be placed in a callee-saved register, then it
  3929. won't need to be saved and restored during function calls.
  3930. The approach that we recommend for call-live variables is either to
  3931. assign them to callee-saved registers or to spill them to the
  3932. stack. On the other hand, for variables that are not call-live, we try
  3933. the following alternatives in order: (1) look for an available
  3934. caller-saved register (to leave room for other variables in the
  3935. callee-saved register), (2) look for a callee-saved register, and (3)
  3936. spill the variable to the stack.
  3937. It is straightforward to implement this approach in a graph coloring
  3938. register allocator. First, we know which variables are call-live
  3939. because we already need to compute which variables are in use at every
  3940. instruction (section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3941. we build the interference graph
  3942. (section~\ref{sec:build-interference}), we can place an edge between
  3943. each of the call-live variables and the caller-saved registers in the
  3944. interference graph. This will prevent the graph coloring algorithm
  3945. from assigning them to caller-saved registers.
  3946. Returning to the example in
  3947. figure~\ref{fig:example-calling-conventions}, let us analyze the
  3948. generated x86 code on the right-hand side. Notice that variable
  3949. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3950. is already in a safe place during the second call to
  3951. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3952. \code{rcx}, a caller-saved register, because \code{y} is not a
  3953. call-live variable.
  3954. Next we analyze the example from the callee point of view, focusing on
  3955. the prelude and conclusion of the \code{main} function. As usual, the
  3956. prelude begins with saving the \code{rbp} register to the stack and
  3957. setting the \code{rbp} to the current stack pointer. We now know why
  3958. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3959. The prelude then pushes \code{rbx} to the stack because (1) \code{rbx}
  3960. is a callee-saved register and (2) \code{rbx} is assigned to a variable
  3961. (\code{x}). The other callee-saved registers are not saved in the
  3962. prelude because they are not used. The prelude subtracts 8 bytes from
  3963. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3964. conclusion, we see that \code{rbx} is restored from the stack with a
  3965. \code{popq} instruction.
  3966. \index{subject}{prelude}\index{subject}{conclusion}
  3967. \begin{figure}[tp]
  3968. \begin{tcolorbox}[colback=white]
  3969. \begin{minipage}{0.45\textwidth}
  3970. Example \LangVar{} program:
  3971. %var_test_14.rkt
  3972. {\if\edition\racketEd
  3973. \begin{lstlisting}
  3974. (let ([x (read)])
  3975. (let ([y (read)])
  3976. (+ (+ x y) 42)))
  3977. \end{lstlisting}
  3978. \fi}
  3979. {\if\edition\pythonEd
  3980. \begin{lstlisting}
  3981. x = input_int()
  3982. y = input_int()
  3983. print((x + y) + 42)
  3984. \end{lstlisting}
  3985. \fi}
  3986. \end{minipage}
  3987. \begin{minipage}{0.45\textwidth}
  3988. Generated x86 assembly:
  3989. {\if\edition\racketEd
  3990. \begin{lstlisting}
  3991. start:
  3992. callq read_int
  3993. movq %rax, %rbx
  3994. callq read_int
  3995. movq %rax, %rcx
  3996. addq %rcx, %rbx
  3997. movq %rbx, %rax
  3998. addq $42, %rax
  3999. jmp _conclusion
  4000. .globl main
  4001. main:
  4002. pushq %rbp
  4003. movq %rsp, %rbp
  4004. pushq %rbx
  4005. subq $8, %rsp
  4006. jmp start
  4007. conclusion:
  4008. addq $8, %rsp
  4009. popq %rbx
  4010. popq %rbp
  4011. retq
  4012. \end{lstlisting}
  4013. \fi}
  4014. {\if\edition\pythonEd
  4015. \begin{lstlisting}
  4016. .globl main
  4017. main:
  4018. pushq %rbp
  4019. movq %rsp, %rbp
  4020. pushq %rbx
  4021. subq $8, %rsp
  4022. callq read_int
  4023. movq %rax, %rbx
  4024. callq read_int
  4025. movq %rax, %rcx
  4026. movq %rbx, %rdx
  4027. addq %rcx, %rdx
  4028. movq %rdx, %rcx
  4029. addq $42, %rcx
  4030. movq %rcx, %rdi
  4031. callq print_int
  4032. addq $8, %rsp
  4033. popq %rbx
  4034. popq %rbp
  4035. retq
  4036. \end{lstlisting}
  4037. \fi}
  4038. \end{minipage}
  4039. \end{tcolorbox}
  4040. \caption{An example with function calls.}
  4041. \label{fig:example-calling-conventions}
  4042. \end{figure}
  4043. %\clearpage
  4044. \section{Liveness Analysis}
  4045. \label{sec:liveness-analysis-Lvar}
  4046. \index{subject}{liveness analysis}
  4047. The \code{uncover\_live} \racket{pass}\python{function} performs
  4048. \emph{liveness analysis}; that is, it discovers which variables are
  4049. in use in different regions of a program.
  4050. %
  4051. A variable or register is \emph{live} at a program point if its
  4052. current value is used at some later point in the program. We refer to
  4053. variables, stack locations, and registers collectively as
  4054. \emph{locations}.
  4055. %
  4056. Consider the following code fragment in which there are two writes to
  4057. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4058. time?
  4059. \begin{center}
  4060. \begin{minipage}{0.96\textwidth}
  4061. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4062. movq $5, a
  4063. movq $30, b
  4064. movq a, c
  4065. movq $10, b
  4066. addq b, c
  4067. \end{lstlisting}
  4068. \end{minipage}
  4069. \end{center}
  4070. The answer is no, because \code{a} is live from line 1 to 3 and
  4071. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4072. line 2 is never used because it is overwritten (line 4) before the
  4073. next read (line 5).
  4074. The live locations for each instruction can be computed by traversing
  4075. the instruction sequence back to front (i.e., backward in execution
  4076. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4077. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4078. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4079. locations before instruction $I_k$. \racket{We recommend representing
  4080. these sets with the Racket \code{set} data structure described in
  4081. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4082. with the Python
  4083. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4084. data structure.}
  4085. {\if\edition\racketEd
  4086. \begin{figure}[tp]
  4087. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4088. \small
  4089. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4090. A \emph{set} is an unordered collection of elements without duplicates.
  4091. Here are some of the operations defined on sets.
  4092. \index{subject}{set}
  4093. \begin{description}
  4094. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4095. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4096. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4097. difference of the two sets.
  4098. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4099. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4100. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4101. \end{description}
  4102. \end{tcolorbox}
  4103. %\end{wrapfigure}
  4104. \caption{The \code{set} data structure.}
  4105. \label{fig:set}
  4106. \end{figure}
  4107. \fi}
  4108. The live locations after an instruction are always the same as the
  4109. live locations before the next instruction.
  4110. \index{subject}{live-after} \index{subject}{live-before}
  4111. \begin{equation} \label{eq:live-after-before-next}
  4112. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4113. \end{equation}
  4114. To start things off, there are no live locations after the last
  4115. instruction, so
  4116. \begin{equation}\label{eq:live-last-empty}
  4117. L_{\mathsf{after}}(n) = \emptyset
  4118. \end{equation}
  4119. We then apply the following rule repeatedly, traversing the
  4120. instruction sequence back to front.
  4121. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4122. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4123. \end{equation}
  4124. where $W(k)$ are the locations written to by instruction $I_k$, and
  4125. $R(k)$ are the locations read by instruction $I_k$.
  4126. {\if\edition\racketEd
  4127. %
  4128. There is a special case for \code{jmp} instructions. The locations
  4129. that are live before a \code{jmp} should be the locations in
  4130. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4131. maintaining an alist named \code{label->live} that maps each label to
  4132. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  4133. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4134. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  4135. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4136. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4137. %
  4138. \fi}
  4139. Let us walk through the previous example, applying these formulas
  4140. starting with the instruction on line 5 of the code fragment. We
  4141. collect the answers in figure~\ref{fig:liveness-example-0}. The
  4142. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  4143. $\emptyset$ because it is the last instruction
  4144. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  4145. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  4146. variables \code{b} and \code{c}
  4147. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads})
  4148. \[
  4149. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4150. \]
  4151. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4152. the live-before set from line 5 to be the live-after set for this
  4153. instruction (formula~\eqref{eq:live-after-before-next}).
  4154. \[
  4155. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4156. \]
  4157. This move instruction writes to \code{b} and does not read from any
  4158. variables, so we have the following live-before set
  4159. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  4160. \[
  4161. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4162. \]
  4163. The live-before for instruction \code{movq a, c}
  4164. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4165. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  4166. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4167. variable that is not live and does not read from a variable.
  4168. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4169. because it writes to variable \code{a}.
  4170. \begin{figure}[tbp]
  4171. \centering
  4172. \begin{tcolorbox}[colback=white]
  4173. \hspace{10pt}
  4174. \begin{minipage}{0.4\textwidth}
  4175. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4176. movq $5, a
  4177. movq $30, b
  4178. movq a, c
  4179. movq $10, b
  4180. addq b, c
  4181. \end{lstlisting}
  4182. \end{minipage}
  4183. \vrule\hspace{10pt}
  4184. \begin{minipage}{0.45\textwidth}
  4185. \begin{align*}
  4186. L_{\mathsf{before}}(1)= \emptyset,
  4187. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4188. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4189. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4190. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4191. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4192. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4193. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4194. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4195. L_{\mathsf{after}}(5)= \emptyset
  4196. \end{align*}
  4197. \end{minipage}
  4198. \end{tcolorbox}
  4199. \caption{Example output of liveness analysis on a short example.}
  4200. \label{fig:liveness-example-0}
  4201. \end{figure}
  4202. \begin{exercise}\normalfont\normalsize
  4203. Perform liveness analysis by hand on the running example in
  4204. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4205. sets for each instruction. Compare your answers to the solution
  4206. shown in figure~\ref{fig:live-eg}.
  4207. \end{exercise}
  4208. \begin{figure}[tp]
  4209. \hspace{20pt}
  4210. \begin{minipage}{0.55\textwidth}
  4211. \begin{tcolorbox}[colback=white]
  4212. {\if\edition\racketEd
  4213. \begin{lstlisting}
  4214. |$\{\ttm{rsp}\}$|
  4215. movq $1, v
  4216. |$\{\ttm{v},\ttm{rsp}\}$|
  4217. movq $42, w
  4218. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4219. movq v, x
  4220. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4221. addq $7, x
  4222. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4223. movq x, y
  4224. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4225. movq x, z
  4226. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4227. addq w, z
  4228. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4229. movq y, t
  4230. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4231. negq t
  4232. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4233. movq z, %rax
  4234. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4235. addq t, %rax
  4236. |$\{\ttm{rax},\ttm{rsp}\}$|
  4237. jmp conclusion
  4238. \end{lstlisting}
  4239. \fi}
  4240. {\if\edition\pythonEd
  4241. \begin{lstlisting}
  4242. movq $1, v
  4243. |$\{\ttm{v}\}$|
  4244. movq $42, w
  4245. |$\{\ttm{w}, \ttm{v}\}$|
  4246. movq v, x
  4247. |$\{\ttm{w}, \ttm{x}\}$|
  4248. addq $7, x
  4249. |$\{\ttm{w}, \ttm{x}\}$|
  4250. movq x, y
  4251. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4252. movq x, z
  4253. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4254. addq w, z
  4255. |$\{\ttm{y}, \ttm{z}\}$|
  4256. movq y, tmp_0
  4257. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4258. negq tmp_0
  4259. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4260. movq z, tmp_1
  4261. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4262. addq tmp_0, tmp_1
  4263. |$\{\ttm{tmp\_1}\}$|
  4264. movq tmp_1, %rdi
  4265. |$\{\ttm{rdi}\}$|
  4266. callq print_int
  4267. |$\{\}$|
  4268. \end{lstlisting}
  4269. \fi}
  4270. \end{tcolorbox}
  4271. \end{minipage}
  4272. \caption{The running example annotated with live-after sets.}
  4273. \label{fig:live-eg}
  4274. \end{figure}
  4275. \begin{exercise}\normalfont\normalsize
  4276. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4277. %
  4278. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4279. field of the \code{Block} structure.}
  4280. %
  4281. \python{Return a dictionary that maps each instruction to its
  4282. live-after set.}
  4283. %
  4284. \racket{We recommend creating an auxiliary function that takes a list
  4285. of instructions and an initial live-after set (typically empty) and
  4286. returns the list of live-after sets.}
  4287. %
  4288. We recommend creating auxiliary functions to (1) compute the set
  4289. of locations that appear in an \Arg{}, (2) compute the locations read
  4290. by an instruction (the $R$ function), and (3) the locations written by
  4291. an instruction (the $W$ function). The \code{callq} instruction should
  4292. include all the caller-saved registers in its write set $W$ because
  4293. the calling convention says that those registers may be written to
  4294. during the function call. Likewise, the \code{callq} instruction
  4295. should include the appropriate argument-passing registers in its
  4296. read set $R$, depending on the arity of the function being
  4297. called. (This is why the abstract syntax for \code{callq} includes the
  4298. arity.)
  4299. \end{exercise}
  4300. %\clearpage
  4301. \section{Build the Interference Graph}
  4302. \label{sec:build-interference}
  4303. {\if\edition\racketEd
  4304. \begin{figure}[tp]
  4305. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4306. \small
  4307. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4308. A \emph{graph} is a collection of vertices and edges where each
  4309. edge connects two vertices. A graph is \emph{directed} if each
  4310. edge points from a source to a target. Otherwise the graph is
  4311. \emph{undirected}.
  4312. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4313. \begin{description}
  4314. %% We currently don't use directed graphs. We instead use
  4315. %% directed multi-graphs. -Jeremy
  4316. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4317. directed graph from a list of edges. Each edge is a list
  4318. containing the source and target vertex.
  4319. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4320. undirected graph from a list of edges. Each edge is represented by
  4321. a list containing two vertices.
  4322. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4323. inserts a vertex into the graph.
  4324. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4325. inserts an edge between the two vertices.
  4326. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4327. returns a sequence of vertices adjacent to the vertex.
  4328. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4329. returns a sequence of all vertices in the graph.
  4330. \end{description}
  4331. \end{tcolorbox}
  4332. %\end{wrapfigure}
  4333. \caption{The Racket \code{graph} package.}
  4334. \label{fig:graph}
  4335. \end{figure}
  4336. \fi}
  4337. On the basis of the liveness analysis, we know where each location is
  4338. live. However, during register allocation, we need to answer
  4339. questions of the specific form: are locations $u$ and $v$ live at the
  4340. same time? (If so, they cannot be assigned to the same register.) To
  4341. make this question more efficient to answer, we create an explicit
  4342. data structure, an \emph{interference
  4343. graph}\index{subject}{interference graph}. An interference graph is
  4344. an undirected graph that has an edge between two locations if they are
  4345. live at the same time, that is, if they interfere with each other.
  4346. %
  4347. \racket{We recommend using the Racket \code{graph} package
  4348. (figure~\ref{fig:graph}) to represent the interference graph.}
  4349. %
  4350. \python{We provide implementations of directed and undirected graph
  4351. data structures in the file \code{graph.py} of the support code.}
  4352. A straightforward way to compute the interference graph is to look at
  4353. the set of live locations between each instruction and add an edge to
  4354. the graph for every pair of variables in the same set. This approach
  4355. is less than ideal for two reasons. First, it can be expensive because
  4356. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4357. locations. Second, in the special case in which two locations hold the
  4358. same value (because one was assigned to the other), they can be live
  4359. at the same time without interfering with each other.
  4360. A better way to compute the interference graph is to focus on
  4361. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4362. must not overwrite something in a live location. So for each
  4363. instruction, we create an edge between the locations being written to
  4364. and the live locations. (However, a location never interferes with
  4365. itself.) For the \key{callq} instruction, we consider all the
  4366. caller-saved registers to have been written to, so an edge is added
  4367. between every live variable and every caller-saved register. Also, for
  4368. \key{movq} there is the special case of two variables holding the same
  4369. value. If a live variable $v$ is the same as the source of the
  4370. \key{movq}, then there is no need to add an edge between $v$ and the
  4371. destination, because they both hold the same value.
  4372. %
  4373. Hence we have the following two rules:
  4374. \begin{enumerate}
  4375. \item If instruction $I_k$ is a move instruction of the form
  4376. \key{movq} $s$\key{,} $d$, then for every $v \in
  4377. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4378. $(d,v)$.
  4379. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4380. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4381. $(d,v)$.
  4382. \end{enumerate}
  4383. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  4384. these rules to each instruction. We highlight a few of the
  4385. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  4386. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4387. so \code{v} interferes with \code{rsp}.}
  4388. %
  4389. \python{The first instruction is \lstinline{movq $1, v}, and the
  4390. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4391. no interference because $\ttm{v}$ is the destination of the move.}
  4392. %
  4393. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  4394. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4395. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4396. %
  4397. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  4398. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4399. $\ttm{x}$ interferes with \ttm{w}.}
  4400. %
  4401. \racket{The next instruction is \lstinline{movq x, y}, and the
  4402. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4403. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4404. \ttm{x} because \ttm{x} is the source of the move and therefore
  4405. \ttm{x} and \ttm{y} hold the same value.}
  4406. %
  4407. \python{The next instruction is \lstinline{movq x, y}, and the
  4408. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4409. applies, so \ttm{y} interferes with \ttm{w} but not
  4410. \ttm{x}, because \ttm{x} is the source of the move and therefore
  4411. \ttm{x} and \ttm{y} hold the same value.}
  4412. %
  4413. Figure~\ref{fig:interference-results} lists the interference results
  4414. for all the instructions, and the resulting interference graph is
  4415. shown in figure~\ref{fig:interfere}.
  4416. \begin{figure}[tbp]
  4417. \begin{tcolorbox}[colback=white]
  4418. \begin{quote}
  4419. {\if\edition\racketEd
  4420. \begin{tabular}{ll}
  4421. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4422. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4423. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4424. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4425. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4426. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4427. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4428. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4429. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4430. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4431. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4432. \lstinline!jmp conclusion!& no interference.
  4433. \end{tabular}
  4434. \fi}
  4435. {\if\edition\pythonEd
  4436. \begin{tabular}{ll}
  4437. \lstinline!movq $1, v!& no interference\\
  4438. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4439. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4440. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4441. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4442. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4443. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4444. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4445. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4446. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4447. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4448. \lstinline!movq tmp_1, %rdi! & no interference \\
  4449. \lstinline!callq print_int!& no interference.
  4450. \end{tabular}
  4451. \fi}
  4452. \end{quote}
  4453. \end{tcolorbox}
  4454. \caption{Interference results for the running example.}
  4455. \label{fig:interference-results}
  4456. \end{figure}
  4457. \begin{figure}[tbp]
  4458. \begin{tcolorbox}[colback=white]
  4459. \large
  4460. {\if\edition\racketEd
  4461. \[
  4462. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4463. \node (rax) at (0,0) {$\ttm{rax}$};
  4464. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4465. \node (t1) at (0,2) {$\ttm{t}$};
  4466. \node (z) at (3,2) {$\ttm{z}$};
  4467. \node (x) at (6,2) {$\ttm{x}$};
  4468. \node (y) at (3,0) {$\ttm{y}$};
  4469. \node (w) at (6,0) {$\ttm{w}$};
  4470. \node (v) at (9,0) {$\ttm{v}$};
  4471. \draw (t1) to (rax);
  4472. \draw (t1) to (z);
  4473. \draw (z) to (y);
  4474. \draw (z) to (w);
  4475. \draw (x) to (w);
  4476. \draw (y) to (w);
  4477. \draw (v) to (w);
  4478. \draw (v) to (rsp);
  4479. \draw (w) to (rsp);
  4480. \draw (x) to (rsp);
  4481. \draw (y) to (rsp);
  4482. \path[-.,bend left=15] (z) edge node {} (rsp);
  4483. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4484. \draw (rax) to (rsp);
  4485. \end{tikzpicture}
  4486. \]
  4487. \fi}
  4488. {\if\edition\pythonEd
  4489. \[
  4490. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4491. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4492. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4493. \node (z) at (3,2) {$\ttm{z}$};
  4494. \node (x) at (6,2) {$\ttm{x}$};
  4495. \node (y) at (3,0) {$\ttm{y}$};
  4496. \node (w) at (6,0) {$\ttm{w}$};
  4497. \node (v) at (9,0) {$\ttm{v}$};
  4498. \draw (t0) to (t1);
  4499. \draw (t0) to (z);
  4500. \draw (z) to (y);
  4501. \draw (z) to (w);
  4502. \draw (x) to (w);
  4503. \draw (y) to (w);
  4504. \draw (v) to (w);
  4505. \end{tikzpicture}
  4506. \]
  4507. \fi}
  4508. \end{tcolorbox}
  4509. \caption{The interference graph of the example program.}
  4510. \label{fig:interfere}
  4511. \end{figure}
  4512. %% Our next concern is to choose a data structure for representing the
  4513. %% interference graph. There are many choices for how to represent a
  4514. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4515. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4516. %% data structure is to study the algorithm that uses the data structure,
  4517. %% determine what operations need to be performed, and then choose the
  4518. %% data structure that provide the most efficient implementations of
  4519. %% those operations. Often times the choice of data structure can have an
  4520. %% effect on the time complexity of the algorithm, as it does here. If
  4521. %% you skim the next section, you will see that the register allocation
  4522. %% algorithm needs to ask the graph for all of its vertices and, given a
  4523. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4524. %% correct choice of graph representation is that of an adjacency
  4525. %% list. There are helper functions in \code{utilities.rkt} for
  4526. %% representing graphs using the adjacency list representation:
  4527. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4528. %% (Appendix~\ref{appendix:utilities}).
  4529. %% %
  4530. %% \margincomment{\footnotesize To do: change to use the
  4531. %% Racket graph library. \\ --Jeremy}
  4532. %% %
  4533. %% In particular, those functions use a hash table to map each vertex to
  4534. %% the set of adjacent vertices, and the sets are represented using
  4535. %% Racket's \key{set}, which is also a hash table.
  4536. \begin{exercise}\normalfont\normalsize
  4537. \racket{Implement the compiler pass named \code{build\_interference} according
  4538. to the algorithm suggested here. We recommend using the Racket
  4539. \code{graph} package to create and inspect the interference graph.
  4540. The output graph of this pass should be stored in the $\itm{info}$ field of
  4541. the program, under the key \code{conflicts}.}
  4542. %
  4543. \python{Implement a function named \code{build\_interference}
  4544. according to the algorithm suggested above that
  4545. returns the interference graph.}
  4546. \end{exercise}
  4547. \section{Graph Coloring via Sudoku}
  4548. \label{sec:graph-coloring}
  4549. \index{subject}{graph coloring}
  4550. \index{subject}{sudoku}
  4551. \index{subject}{color}
  4552. We come to the main event discussed in this chapter, mapping variables
  4553. to registers and stack locations. Variables that interfere with each
  4554. other must be mapped to different locations. In terms of the
  4555. interference graph, this means that adjacent vertices must be mapped
  4556. to different locations. If we think of locations as colors, the
  4557. register allocation problem becomes the graph coloring
  4558. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4559. The reader may be more familiar with the graph coloring problem than he
  4560. or she realizes; the popular game of sudoku is an instance of the
  4561. graph coloring problem. The following describes how to build a graph
  4562. out of an initial sudoku board.
  4563. \begin{itemize}
  4564. \item There is one vertex in the graph for each sudoku square.
  4565. \item There is an edge between two vertices if the corresponding squares
  4566. are in the same row, in the same column, or in the same $3\times 3$ region.
  4567. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4568. \item On the basis of the initial assignment of numbers to squares on the
  4569. sudoku board, assign the corresponding colors to the corresponding
  4570. vertices in the graph.
  4571. \end{itemize}
  4572. If you can color the remaining vertices in the graph with the nine
  4573. colors, then you have also solved the corresponding game of sudoku.
  4574. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  4575. the corresponding graph with colored vertices. Here we use a
  4576. monochrome representation of colors, mapping the sudoku number 1 to
  4577. black, 2 to white, and 3 to gray. We show edges for only a sampling
  4578. of the vertices (the colored ones) because showing edges for all the
  4579. vertices would make the graph unreadable.
  4580. \begin{figure}[tbp]
  4581. \begin{tcolorbox}[colback=white]
  4582. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  4583. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4584. \end{tcolorbox}
  4585. \caption{A sudoku game board and the corresponding colored graph.}
  4586. \label{fig:sudoku-graph}
  4587. \end{figure}
  4588. Some techniques for playing sudoku correspond to heuristics used in
  4589. graph coloring algorithms. For example, one of the basic techniques
  4590. for sudoku is called Pencil Marks. The idea is to use a process of
  4591. elimination to determine what numbers are no longer available for a
  4592. square and to write those numbers in the square (writing very
  4593. small). For example, if the number $1$ is assigned to a square, then
  4594. write the pencil mark $1$ in all the squares in the same row, column,
  4595. and region to indicate that $1$ is no longer an option for those other
  4596. squares.
  4597. %
  4598. The Pencil Marks technique corresponds to the notion of
  4599. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  4600. saturation of a vertex, in sudoku terms, is the set of numbers that
  4601. are no longer available. In graph terminology, we have the following
  4602. definition:
  4603. \begin{equation*}
  4604. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4605. \text{ and } \mathrm{color}(v) = c \}
  4606. \end{equation*}
  4607. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4608. edge with $u$.
  4609. The Pencil Marks technique leads to a simple strategy for filling in
  4610. numbers: if there is a square with only one possible number left, then
  4611. choose that number! But what if there are no squares with only one
  4612. possibility left? One brute-force approach is to try them all: choose
  4613. the first one, and if that ultimately leads to a solution, great. If
  4614. not, backtrack and choose the next possibility. One good thing about
  4615. Pencil Marks is that it reduces the degree of branching in the search
  4616. tree. Nevertheless, backtracking can be terribly time consuming. One
  4617. way to reduce the amount of backtracking is to use the
  4618. most-constrained-first heuristic (aka minimum remaining
  4619. values)~\citep{Russell2003}. That is, in choosing a square, always
  4620. choose one with the fewest possibilities left (the vertex with the
  4621. highest saturation). The idea is that choosing highly constrained
  4622. squares earlier rather than later is better, because later on there may
  4623. not be any possibilities left in the highly saturated squares.
  4624. However, register allocation is easier than sudoku, because the
  4625. register allocator can fall back to assigning variables to stack
  4626. locations when the registers run out. Thus, it makes sense to replace
  4627. backtracking with greedy search: make the best choice at the time and
  4628. keep going. We still wish to minimize the number of colors needed, so
  4629. we use the most-constrained-first heuristic in the greedy search.
  4630. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  4631. algorithm for register allocation based on saturation and the
  4632. most-constrained-first heuristic. It is roughly equivalent to the
  4633. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4634. %,Gebremedhin:1999fk,Omari:2006uq
  4635. Just as in sudoku, the algorithm represents colors with integers. The
  4636. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4637. for register allocation. The integers $k$ and larger correspond to
  4638. stack locations. The registers that are not used for register
  4639. allocation, such as \code{rax}, are assigned to negative integers. In
  4640. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4641. %% One might wonder why we include registers at all in the liveness
  4642. %% analysis and interference graph. For example, we never allocate a
  4643. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4644. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  4645. %% to use register for passing arguments to functions, it will be
  4646. %% necessary for those registers to appear in the interference graph
  4647. %% because those registers will also be assigned to variables, and we
  4648. %% don't want those two uses to encroach on each other. Regarding
  4649. %% registers such as \code{rax} and \code{rsp} that are not used for
  4650. %% variables, we could omit them from the interference graph but that
  4651. %% would require adding special cases to our algorithm, which would
  4652. %% complicate the logic for little gain.
  4653. \begin{figure}[btp]
  4654. \begin{tcolorbox}[colback=white]
  4655. \centering
  4656. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4657. Algorithm: DSATUR
  4658. Input: A graph |$G$|
  4659. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4660. |$W \gets \mathrm{vertices}(G)$|
  4661. while |$W \neq \emptyset$| do
  4662. pick a vertex |$u$| from |$W$| with the highest saturation,
  4663. breaking ties randomly
  4664. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4665. |$\mathrm{color}[u] \gets c$|
  4666. |$W \gets W - \{u\}$|
  4667. \end{lstlisting}
  4668. \end{tcolorbox}
  4669. \caption{The saturation-based greedy graph coloring algorithm.}
  4670. \label{fig:satur-algo}
  4671. \end{figure}
  4672. {\if\edition\racketEd
  4673. With the DSATUR algorithm in hand, let us return to the running
  4674. example and consider how to color the interference graph shown in
  4675. figure~\ref{fig:interfere}.
  4676. %
  4677. We start by assigning each register node to its own color. For
  4678. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4679. assigned $-2$. The variables are not yet colored, so they are
  4680. annotated with a dash. We then update the saturation for vertices that
  4681. are adjacent to a register, obtaining the following annotated
  4682. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4683. it interferes with both \code{rax} and \code{rsp}.
  4684. \[
  4685. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4686. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4687. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4688. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4689. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4690. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4691. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4692. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4693. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4694. \draw (t1) to (rax);
  4695. \draw (t1) to (z);
  4696. \draw (z) to (y);
  4697. \draw (z) to (w);
  4698. \draw (x) to (w);
  4699. \draw (y) to (w);
  4700. \draw (v) to (w);
  4701. \draw (v) to (rsp);
  4702. \draw (w) to (rsp);
  4703. \draw (x) to (rsp);
  4704. \draw (y) to (rsp);
  4705. \path[-.,bend left=15] (z) edge node {} (rsp);
  4706. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4707. \draw (rax) to (rsp);
  4708. \end{tikzpicture}
  4709. \]
  4710. The algorithm says to select a maximally saturated vertex. So, we pick
  4711. $\ttm{t}$ and color it with the first available integer, which is
  4712. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4713. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4714. \[
  4715. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4716. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4717. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4718. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4719. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4720. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4721. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4722. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4723. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4724. \draw (t1) to (rax);
  4725. \draw (t1) to (z);
  4726. \draw (z) to (y);
  4727. \draw (z) to (w);
  4728. \draw (x) to (w);
  4729. \draw (y) to (w);
  4730. \draw (v) to (w);
  4731. \draw (v) to (rsp);
  4732. \draw (w) to (rsp);
  4733. \draw (x) to (rsp);
  4734. \draw (y) to (rsp);
  4735. \path[-.,bend left=15] (z) edge node {} (rsp);
  4736. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4737. \draw (rax) to (rsp);
  4738. \end{tikzpicture}
  4739. \]
  4740. We repeat the process, selecting a maximally saturated vertex,
  4741. choosing \code{z}, and coloring it with the first available number, which
  4742. is $1$. We add $1$ to the saturation for the neighboring vertices
  4743. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  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}:-,\{-2\}$};
  4751. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4752. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4753. \node (v) at (10,0) {$\ttm{v}:-,\{-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. The most saturated vertices are now \code{w} and \code{y}. We color
  4771. \code{w} with the first available color, which is $0$.
  4772. \[
  4773. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4774. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4775. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4776. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4777. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4778. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4779. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4780. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4781. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4782. \draw (t1) to (rax);
  4783. \draw (t1) to (z);
  4784. \draw (z) to (y);
  4785. \draw (z) to (w);
  4786. \draw (x) to (w);
  4787. \draw (y) to (w);
  4788. \draw (v) to (w);
  4789. \draw (v) to (rsp);
  4790. \draw (w) to (rsp);
  4791. \draw (x) to (rsp);
  4792. \draw (y) to (rsp);
  4793. \path[-.,bend left=15] (z) edge node {} (rsp);
  4794. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4795. \draw (rax) to (rsp);
  4796. \end{tikzpicture}
  4797. \]
  4798. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4799. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4800. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4801. and \code{z}, whose colors are $0$ and $1$ respectively.
  4802. \[
  4803. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4804. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4805. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4806. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4807. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4808. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4809. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4810. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4811. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4812. \draw (t1) to (rax);
  4813. \draw (t1) to (z);
  4814. \draw (z) to (y);
  4815. \draw (z) to (w);
  4816. \draw (x) to (w);
  4817. \draw (y) to (w);
  4818. \draw (v) to (w);
  4819. \draw (v) to (rsp);
  4820. \draw (w) to (rsp);
  4821. \draw (x) to (rsp);
  4822. \draw (y) to (rsp);
  4823. \path[-.,bend left=15] (z) edge node {} (rsp);
  4824. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4825. \draw (rax) to (rsp);
  4826. \end{tikzpicture}
  4827. \]
  4828. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4829. \[
  4830. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4831. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4832. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4833. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4834. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4835. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4836. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4837. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4838. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4839. \draw (t1) to (rax);
  4840. \draw (t1) to (z);
  4841. \draw (z) to (y);
  4842. \draw (z) to (w);
  4843. \draw (x) to (w);
  4844. \draw (y) to (w);
  4845. \draw (v) to (w);
  4846. \draw (v) to (rsp);
  4847. \draw (w) to (rsp);
  4848. \draw (x) to (rsp);
  4849. \draw (y) to (rsp);
  4850. \path[-.,bend left=15] (z) edge node {} (rsp);
  4851. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4852. \draw (rax) to (rsp);
  4853. \end{tikzpicture}
  4854. \]
  4855. In the last step of the algorithm, we color \code{x} with $1$.
  4856. \[
  4857. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4858. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4859. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4860. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4861. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4862. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4863. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4864. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4865. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4866. \draw (t1) to (rax);
  4867. \draw (t1) to (z);
  4868. \draw (z) to (y);
  4869. \draw (z) to (w);
  4870. \draw (x) to (w);
  4871. \draw (y) to (w);
  4872. \draw (v) to (w);
  4873. \draw (v) to (rsp);
  4874. \draw (w) to (rsp);
  4875. \draw (x) to (rsp);
  4876. \draw (y) to (rsp);
  4877. \path[-.,bend left=15] (z) edge node {} (rsp);
  4878. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4879. \draw (rax) to (rsp);
  4880. \end{tikzpicture}
  4881. \]
  4882. So, we obtain the following coloring:
  4883. \[
  4884. \{
  4885. \ttm{rax} \mapsto -1,
  4886. \ttm{rsp} \mapsto -2,
  4887. \ttm{t} \mapsto 0,
  4888. \ttm{z} \mapsto 1,
  4889. \ttm{x} \mapsto 1,
  4890. \ttm{y} \mapsto 2,
  4891. \ttm{w} \mapsto 0,
  4892. \ttm{v} \mapsto 1
  4893. \}
  4894. \]
  4895. \fi}
  4896. %
  4897. {\if\edition\pythonEd
  4898. %
  4899. With the DSATUR algorithm in hand, let us return to the running
  4900. example and consider how to color the interference graph in
  4901. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4902. to indicate that it has not yet been assigned a color. The saturation
  4903. sets are also shown for each node; all of them start as the empty set.
  4904. (We do not include the register nodes in the graph below because there
  4905. were no interference edges involving registers in this program, but in
  4906. general there can be.)
  4907. %
  4908. \[
  4909. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4910. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4911. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4912. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4913. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4914. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4915. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4916. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4917. \draw (t0) to (t1);
  4918. \draw (t0) to (z);
  4919. \draw (z) to (y);
  4920. \draw (z) to (w);
  4921. \draw (x) to (w);
  4922. \draw (y) to (w);
  4923. \draw (v) to (w);
  4924. \end{tikzpicture}
  4925. \]
  4926. The algorithm says to select a maximally saturated vertex, but they
  4927. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4928. then color it with the first available integer, which is $0$. We mark
  4929. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4930. they interfere with $\ttm{tmp\_0}$.
  4931. \[
  4932. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4933. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4934. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4935. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4936. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4937. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4938. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4939. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4940. \draw (t0) to (t1);
  4941. \draw (t0) to (z);
  4942. \draw (z) to (y);
  4943. \draw (z) to (w);
  4944. \draw (x) to (w);
  4945. \draw (y) to (w);
  4946. \draw (v) to (w);
  4947. \end{tikzpicture}
  4948. \]
  4949. We repeat the process. The most saturated vertices are \code{z} and
  4950. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4951. available number, which is $1$. We add $1$ to the saturation for the
  4952. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4953. \[
  4954. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4955. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4956. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4957. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4958. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4959. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4960. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4961. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4962. \draw (t0) to (t1);
  4963. \draw (t0) to (z);
  4964. \draw (z) to (y);
  4965. \draw (z) to (w);
  4966. \draw (x) to (w);
  4967. \draw (y) to (w);
  4968. \draw (v) to (w);
  4969. \end{tikzpicture}
  4970. \]
  4971. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4972. \code{y}. We color \code{w} with the first available color, which
  4973. is $0$.
  4974. \[
  4975. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4976. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4977. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4978. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4979. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4980. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4981. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4982. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4983. \draw (t0) to (t1);
  4984. \draw (t0) to (z);
  4985. \draw (z) to (y);
  4986. \draw (z) to (w);
  4987. \draw (x) to (w);
  4988. \draw (y) to (w);
  4989. \draw (v) to (w);
  4990. \end{tikzpicture}
  4991. \]
  4992. Now \code{y} is the most saturated, so we color it with $2$.
  4993. \[
  4994. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4995. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4996. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4997. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4998. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4999. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5000. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5001. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5002. \draw (t0) to (t1);
  5003. \draw (t0) to (z);
  5004. \draw (z) to (y);
  5005. \draw (z) to (w);
  5006. \draw (x) to (w);
  5007. \draw (y) to (w);
  5008. \draw (v) to (w);
  5009. \end{tikzpicture}
  5010. \]
  5011. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5012. We choose to color \code{v} with $1$.
  5013. \[
  5014. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5015. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5016. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5017. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5018. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5019. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5020. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5021. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5022. \draw (t0) to (t1);
  5023. \draw (t0) to (z);
  5024. \draw (z) to (y);
  5025. \draw (z) to (w);
  5026. \draw (x) to (w);
  5027. \draw (y) to (w);
  5028. \draw (v) to (w);
  5029. \end{tikzpicture}
  5030. \]
  5031. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5032. \[
  5033. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5034. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5035. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5036. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5037. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5038. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5039. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5040. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5041. \draw (t0) to (t1);
  5042. \draw (t0) to (z);
  5043. \draw (z) to (y);
  5044. \draw (z) to (w);
  5045. \draw (x) to (w);
  5046. \draw (y) to (w);
  5047. \draw (v) to (w);
  5048. \end{tikzpicture}
  5049. \]
  5050. So, we obtain the following coloring:
  5051. \[
  5052. \{ \ttm{tmp\_0} \mapsto 0,
  5053. \ttm{tmp\_1} \mapsto 1,
  5054. \ttm{z} \mapsto 1,
  5055. \ttm{x} \mapsto 1,
  5056. \ttm{y} \mapsto 2,
  5057. \ttm{w} \mapsto 0,
  5058. \ttm{v} \mapsto 1 \}
  5059. \]
  5060. \fi}
  5061. We recommend creating an auxiliary function named \code{color\_graph}
  5062. that takes an interference graph and a list of all the variables in
  5063. the program. This function should return a mapping of variables to
  5064. their colors (represented as natural numbers). By creating this helper
  5065. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5066. when we add support for functions.
  5067. To prioritize the processing of highly saturated nodes inside the
  5068. \code{color\_graph} function, we recommend using the priority queue
  5069. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5070. addition, you will need to maintain a mapping from variables to their
  5071. handles in the priority queue so that you can notify the priority
  5072. queue when their saturation changes.}
  5073. {\if\edition\racketEd
  5074. \begin{figure}[tp]
  5075. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5076. \small
  5077. \begin{tcolorbox}[title=Priority Queue]
  5078. A \emph{priority queue} is a collection of items in which the
  5079. removal of items is governed by priority. In a min queue,
  5080. lower priority items are removed first. An implementation is in
  5081. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5082. queue} \index{subject}{minimum priority queue}
  5083. \begin{description}
  5084. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5085. priority queue that uses the $\itm{cmp}$ predicate to determine
  5086. whether its first argument has lower or equal priority to its
  5087. second argument.
  5088. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5089. items in the queue.
  5090. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5091. the item into the queue and returns a handle for the item in the
  5092. queue.
  5093. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5094. the lowest priority.
  5095. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5096. notifies the queue that the priority has decreased for the item
  5097. associated with the given handle.
  5098. \end{description}
  5099. \end{tcolorbox}
  5100. %\end{wrapfigure}
  5101. \caption{The priority queue data structure.}
  5102. \label{fig:priority-queue}
  5103. \end{figure}
  5104. \fi}
  5105. With the coloring complete, we finalize the assignment of variables to
  5106. registers and stack locations. We map the first $k$ colors to the $k$
  5107. registers and the rest of the colors to stack locations. Suppose for
  5108. the moment that we have just one register to use for register
  5109. allocation, \key{rcx}. Then we have the following map from colors to
  5110. locations.
  5111. \[
  5112. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5113. \]
  5114. Composing this mapping with the coloring, we arrive at the following
  5115. assignment of variables to locations.
  5116. {\if\edition\racketEd
  5117. \begin{gather*}
  5118. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5119. \ttm{w} \mapsto \key{\%rcx}, \,
  5120. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5121. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5122. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5123. \ttm{t} \mapsto \key{\%rcx} \}
  5124. \end{gather*}
  5125. \fi}
  5126. {\if\edition\pythonEd
  5127. \begin{gather*}
  5128. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5129. \ttm{w} \mapsto \key{\%rcx}, \,
  5130. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5131. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5132. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5133. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5134. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5135. \end{gather*}
  5136. \fi}
  5137. Adapt the code from the \code{assign\_homes} pass
  5138. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  5139. assigned location. Applying this assignment to our running
  5140. example shown next, on the left, yields the program on the right.
  5141. % why frame size of 32? -JGS
  5142. \begin{center}
  5143. {\if\edition\racketEd
  5144. \begin{minipage}{0.3\textwidth}
  5145. \begin{lstlisting}
  5146. movq $1, v
  5147. movq $42, w
  5148. movq v, x
  5149. addq $7, x
  5150. movq x, y
  5151. movq x, z
  5152. addq w, z
  5153. movq y, t
  5154. negq t
  5155. movq z, %rax
  5156. addq t, %rax
  5157. jmp conclusion
  5158. \end{lstlisting}
  5159. \end{minipage}
  5160. $\Rightarrow\qquad$
  5161. \begin{minipage}{0.45\textwidth}
  5162. \begin{lstlisting}
  5163. movq $1, -8(%rbp)
  5164. movq $42, %rcx
  5165. movq -8(%rbp), -8(%rbp)
  5166. addq $7, -8(%rbp)
  5167. movq -8(%rbp), -16(%rbp)
  5168. movq -8(%rbp), -8(%rbp)
  5169. addq %rcx, -8(%rbp)
  5170. movq -16(%rbp), %rcx
  5171. negq %rcx
  5172. movq -8(%rbp), %rax
  5173. addq %rcx, %rax
  5174. jmp conclusion
  5175. \end{lstlisting}
  5176. \end{minipage}
  5177. \fi}
  5178. {\if\edition\pythonEd
  5179. \begin{minipage}{0.3\textwidth}
  5180. \begin{lstlisting}
  5181. movq $1, v
  5182. movq $42, w
  5183. movq v, x
  5184. addq $7, x
  5185. movq x, y
  5186. movq x, z
  5187. addq w, z
  5188. movq y, tmp_0
  5189. negq tmp_0
  5190. movq z, tmp_1
  5191. addq tmp_0, tmp_1
  5192. movq tmp_1, %rdi
  5193. callq print_int
  5194. \end{lstlisting}
  5195. \end{minipage}
  5196. $\Rightarrow\qquad$
  5197. \begin{minipage}{0.45\textwidth}
  5198. \begin{lstlisting}
  5199. movq $1, -8(%rbp)
  5200. movq $42, %rcx
  5201. movq -8(%rbp), -8(%rbp)
  5202. addq $7, -8(%rbp)
  5203. movq -8(%rbp), -16(%rbp)
  5204. movq -8(%rbp), -8(%rbp)
  5205. addq %rcx, -8(%rbp)
  5206. movq -16(%rbp), %rcx
  5207. negq %rcx
  5208. movq -8(%rbp), -8(%rbp)
  5209. addq %rcx, -8(%rbp)
  5210. movq -8(%rbp), %rdi
  5211. callq print_int
  5212. \end{lstlisting}
  5213. \end{minipage}
  5214. \fi}
  5215. \end{center}
  5216. \begin{exercise}\normalfont\normalsize
  5217. Implement the \code{allocate\_registers} pass.
  5218. Create five programs that exercise all aspects of the register
  5219. allocation algorithm, including spilling variables to the stack.
  5220. %
  5221. {\if\edition\racketEd
  5222. Replace \code{assign\_homes} in the list of \code{passes} in the
  5223. \code{run-tests.rkt} script with the three new passes:
  5224. \code{uncover\_live}, \code{build\_interference}, and
  5225. \code{allocate\_registers}.
  5226. Temporarily remove the call to \code{compiler-tests}.
  5227. Run the script to test the register allocator.
  5228. \fi}
  5229. %
  5230. {\if\edition\pythonEd
  5231. Run the \code{run-tests.py} script to to check whether the
  5232. output programs produce the same result as the input programs.
  5233. \fi}
  5234. \end{exercise}
  5235. \section{Patch Instructions}
  5236. \label{sec:patch-instructions}
  5237. The remaining step in the compilation to x86 is to ensure that the
  5238. instructions have at most one argument that is a memory access.
  5239. %
  5240. In the running example, the instruction \code{movq -8(\%rbp),
  5241. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  5242. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5243. then move \code{rax} into \code{-16(\%rbp)}.
  5244. %
  5245. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5246. problematic, but they can simply be deleted. In general, we recommend
  5247. deleting all the trivial moves whose source and destination are the
  5248. same location.
  5249. %
  5250. The following is the output of \code{patch\_instructions} on the
  5251. running example.
  5252. \begin{center}
  5253. {\if\edition\racketEd
  5254. \begin{minipage}{0.4\textwidth}
  5255. \begin{lstlisting}
  5256. movq $1, -8(%rbp)
  5257. movq $42, %rcx
  5258. movq -8(%rbp), -8(%rbp)
  5259. addq $7, -8(%rbp)
  5260. movq -8(%rbp), -16(%rbp)
  5261. movq -8(%rbp), -8(%rbp)
  5262. addq %rcx, -8(%rbp)
  5263. movq -16(%rbp), %rcx
  5264. negq %rcx
  5265. movq -8(%rbp), %rax
  5266. addq %rcx, %rax
  5267. jmp conclusion
  5268. \end{lstlisting}
  5269. \end{minipage}
  5270. $\Rightarrow\qquad$
  5271. \begin{minipage}{0.45\textwidth}
  5272. \begin{lstlisting}
  5273. movq $1, -8(%rbp)
  5274. movq $42, %rcx
  5275. addq $7, -8(%rbp)
  5276. movq -8(%rbp), %rax
  5277. movq %rax, -16(%rbp)
  5278. addq %rcx, -8(%rbp)
  5279. movq -16(%rbp), %rcx
  5280. negq %rcx
  5281. movq -8(%rbp), %rax
  5282. addq %rcx, %rax
  5283. jmp conclusion
  5284. \end{lstlisting}
  5285. \end{minipage}
  5286. \fi}
  5287. {\if\edition\pythonEd
  5288. \begin{minipage}{0.4\textwidth}
  5289. \begin{lstlisting}
  5290. movq $1, -8(%rbp)
  5291. movq $42, %rcx
  5292. movq -8(%rbp), -8(%rbp)
  5293. addq $7, -8(%rbp)
  5294. movq -8(%rbp), -16(%rbp)
  5295. movq -8(%rbp), -8(%rbp)
  5296. addq %rcx, -8(%rbp)
  5297. movq -16(%rbp), %rcx
  5298. negq %rcx
  5299. movq -8(%rbp), -8(%rbp)
  5300. addq %rcx, -8(%rbp)
  5301. movq -8(%rbp), %rdi
  5302. callq print_int
  5303. \end{lstlisting}
  5304. \end{minipage}
  5305. $\Rightarrow\qquad$
  5306. \begin{minipage}{0.45\textwidth}
  5307. \begin{lstlisting}
  5308. movq $1, -8(%rbp)
  5309. movq $42, %rcx
  5310. addq $7, -8(%rbp)
  5311. movq -8(%rbp), %rax
  5312. movq %rax, -16(%rbp)
  5313. addq %rcx, -8(%rbp)
  5314. movq -16(%rbp), %rcx
  5315. negq %rcx
  5316. addq %rcx, -8(%rbp)
  5317. movq -8(%rbp), %rdi
  5318. callq print_int
  5319. \end{lstlisting}
  5320. \end{minipage}
  5321. \fi}
  5322. \end{center}
  5323. \begin{exercise}\normalfont\normalsize
  5324. %
  5325. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5326. %
  5327. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5328. %in the \code{run-tests.rkt} script.
  5329. %
  5330. Run the script to test the \code{patch\_instructions} pass.
  5331. \end{exercise}
  5332. \section{Prelude and Conclusion}
  5333. \label{sec:print-x86-reg-alloc}
  5334. \index{subject}{calling conventions}
  5335. \index{subject}{prelude}\index{subject}{conclusion}
  5336. Recall that this pass generates the prelude and conclusion
  5337. instructions to satisfy the x86 calling conventions
  5338. (section~\ref{sec:calling-conventions}). With the addition of the
  5339. register allocator, the callee-saved registers used by the register
  5340. allocator must be saved in the prelude and restored in the conclusion.
  5341. In the \code{allocate\_registers} pass,
  5342. %
  5343. \racket{add an entry to the \itm{info}
  5344. of \code{X86Program} named \code{used\_callee}}
  5345. %
  5346. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5347. %
  5348. that stores the set of callee-saved registers that were assigned to
  5349. variables. The \code{prelude\_and\_conclusion} pass can then access
  5350. this information to decide which callee-saved registers need to be
  5351. saved and restored.
  5352. %
  5353. When calculating the amount to adjust the \code{rsp} in the prelude,
  5354. make sure to take into account the space used for saving the
  5355. callee-saved registers. Also, remember that the frame needs to be a
  5356. multiple of 16 bytes! We recommend using the following equation for
  5357. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5358. of spilled variables and $C$ be the number of callee-saved registers
  5359. that were allocated to variables. The $\itm{align}$ function rounds a
  5360. number up to the nearest 16 bytes.
  5361. \[
  5362. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5363. \]
  5364. The reason we subtract $8\itm{C}$ in this equation is that the
  5365. prelude uses \code{pushq} to save each of the callee-saved registers,
  5366. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5367. \racket{An overview of all of the passes involved in register
  5368. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  5369. {\if\edition\racketEd
  5370. \begin{figure}[tbp]
  5371. \begin{tcolorbox}[colback=white]
  5372. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5373. \node (Lvar) at (0,2) {\large \LangVar{}};
  5374. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5375. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  5376. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  5377. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  5378. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  5379. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  5380. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  5381. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  5382. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  5383. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5384. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  5385. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5386. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  5387. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5388. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  5389. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  5390. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  5391. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  5392. \end{tikzpicture}
  5393. \end{tcolorbox}
  5394. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5395. \label{fig:reg-alloc-passes}
  5396. \end{figure}
  5397. \fi}
  5398. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5399. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  5400. use of registers and the stack, we limit the register allocator for
  5401. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5402. the prelude\index{subject}{prelude} of the \code{main} function, we
  5403. push \code{rbx} onto the stack because it is a callee-saved register
  5404. and it was assigned to a variable by the register allocator. We
  5405. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5406. reserve space for the one spilled variable. After that subtraction,
  5407. the \code{rsp} is aligned to 16 bytes.
  5408. Moving on to the program proper, we see how the registers were
  5409. allocated.
  5410. %
  5411. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5412. \code{rbx}, and variable \code{z} was assigned to \code{rcx}.}
  5413. %
  5414. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5415. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5416. were assigned to \code{rbx}.}
  5417. %
  5418. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5419. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5420. callee-save register \code{rbx} onto the stack. The spilled variables
  5421. must be placed lower on the stack than the saved callee-save
  5422. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5423. \code{-16(\%rbp)}.
  5424. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5425. done in the prelude. We move the stack pointer up by \code{8} bytes
  5426. (the room for spilled variables), then pop the old values of
  5427. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5428. \code{retq} to return control to the operating system.
  5429. \begin{figure}[tbp]
  5430. \begin{minipage}{0.55\textwidth}
  5431. \begin{tcolorbox}[colback=white]
  5432. % var_test_28.rkt
  5433. % (use-minimal-set-of-registers! #t)
  5434. % and only rbx rcx
  5435. % tmp 0 rbx
  5436. % z 1 rcx
  5437. % y 0 rbx
  5438. % w 2 16(%rbp)
  5439. % v 0 rbx
  5440. % x 0 rbx
  5441. {\if\edition\racketEd
  5442. \begin{lstlisting}
  5443. start:
  5444. movq $1, %rbx
  5445. movq $42, -16(%rbp)
  5446. addq $7, %rbx
  5447. movq %rbx, %rcx
  5448. addq -16(%rbp), %rcx
  5449. negq %rbx
  5450. movq %rcx, %rax
  5451. addq %rbx, %rax
  5452. jmp conclusion
  5453. .globl main
  5454. main:
  5455. pushq %rbp
  5456. movq %rsp, %rbp
  5457. pushq %rbx
  5458. subq $8, %rsp
  5459. jmp start
  5460. conclusion:
  5461. addq $8, %rsp
  5462. popq %rbx
  5463. popq %rbp
  5464. retq
  5465. \end{lstlisting}
  5466. \fi}
  5467. {\if\edition\pythonEd
  5468. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5469. \begin{lstlisting}
  5470. .globl main
  5471. main:
  5472. pushq %rbp
  5473. movq %rsp, %rbp
  5474. pushq %rbx
  5475. subq $8, %rsp
  5476. movq $1, %rcx
  5477. movq $42, %rbx
  5478. addq $7, %rcx
  5479. movq %rcx, -16(%rbp)
  5480. addq %rbx, -16(%rbp)
  5481. negq %rcx
  5482. movq -16(%rbp), %rbx
  5483. addq %rcx, %rbx
  5484. movq %rbx, %rdi
  5485. callq print_int
  5486. addq $8, %rsp
  5487. popq %rbx
  5488. popq %rbp
  5489. retq
  5490. \end{lstlisting}
  5491. \fi}
  5492. \end{tcolorbox}
  5493. \end{minipage}
  5494. \caption{The x86 output from the running example
  5495. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5496. and \code{rcx}.}
  5497. \label{fig:running-example-x86}
  5498. \end{figure}
  5499. \begin{exercise}\normalfont\normalsize
  5500. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5501. %
  5502. \racket{
  5503. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5504. list of passes and the call to \code{compiler-tests}.}
  5505. %
  5506. Run the script to test the complete compiler for \LangVar{} that
  5507. performs register allocation.
  5508. \end{exercise}
  5509. \section{Challenge: Move Biasing}
  5510. \label{sec:move-biasing}
  5511. \index{subject}{move biasing}
  5512. This section describes an enhancement to the register allocator,
  5513. called move biasing, for students who are looking for an extra
  5514. challenge.
  5515. {\if\edition\racketEd
  5516. To motivate the need for move biasing we return to the running example,
  5517. but this time we use all of the general purpose registers. So, we have
  5518. the following mapping of color numbers to registers.
  5519. \[
  5520. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5521. \]
  5522. Using the same assignment of variables to color numbers that was
  5523. produced by the register allocator described in the last section, we
  5524. get the following program.
  5525. \begin{center}
  5526. \begin{minipage}{0.3\textwidth}
  5527. \begin{lstlisting}
  5528. movq $1, v
  5529. movq $42, w
  5530. movq v, x
  5531. addq $7, x
  5532. movq x, y
  5533. movq x, z
  5534. addq w, z
  5535. movq y, t
  5536. negq t
  5537. movq z, %rax
  5538. addq t, %rax
  5539. jmp conclusion
  5540. \end{lstlisting}
  5541. \end{minipage}
  5542. $\Rightarrow\qquad$
  5543. \begin{minipage}{0.45\textwidth}
  5544. \begin{lstlisting}
  5545. movq $1, %rdx
  5546. movq $42, %rcx
  5547. movq %rdx, %rdx
  5548. addq $7, %rdx
  5549. movq %rdx, %rsi
  5550. movq %rdx, %rdx
  5551. addq %rcx, %rdx
  5552. movq %rsi, %rcx
  5553. negq %rcx
  5554. movq %rdx, %rax
  5555. addq %rcx, %rax
  5556. jmp conclusion
  5557. \end{lstlisting}
  5558. \end{minipage}
  5559. \end{center}
  5560. In this output code there are two \key{movq} instructions that
  5561. can be removed because their source and target are the same. However,
  5562. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5563. register, we could instead remove three \key{movq} instructions. We
  5564. can accomplish this by taking into account which variables appear in
  5565. \key{movq} instructions with which other variables.
  5566. \fi}
  5567. {\if\edition\pythonEd
  5568. %
  5569. To motivate the need for move biasing we return to the running example
  5570. and recall that in section~\ref{sec:patch-instructions} we were able to
  5571. remove three trivial move instructions from the running
  5572. example. However, we could remove another trivial move if we were able
  5573. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5574. We say that two variables $p$ and $q$ are \emph{move
  5575. related}\index{subject}{move related} if they participate together in
  5576. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5577. \key{movq} $q$\key{,} $p$. In deciding which variable to color next,
  5578. if there are multiple variables with the same saturation, prefer
  5579. variables that can be assigned to a color that is the same as the
  5580. color of a move-related variable. Furthermore, when the register
  5581. allocator chooses a color for a variable, it should prefer a color
  5582. that has already been used for a move-related variable (assuming that
  5583. they do not interfere). Of course, this preference should not override
  5584. the preference for registers over stack locations. So, this preference
  5585. should be used as a tie breaker in choosing between registers and
  5586. in choosing between stack locations.
  5587. We recommend representing the move relationships in a graph, similarly
  5588. to how we represented interference. The following is the \emph{move
  5589. graph} for our running example.
  5590. {\if\edition\racketEd
  5591. \[
  5592. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5593. \node (rax) at (0,0) {$\ttm{rax}$};
  5594. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5595. \node (t) at (0,2) {$\ttm{t}$};
  5596. \node (z) at (3,2) {$\ttm{z}$};
  5597. \node (x) at (6,2) {$\ttm{x}$};
  5598. \node (y) at (3,0) {$\ttm{y}$};
  5599. \node (w) at (6,0) {$\ttm{w}$};
  5600. \node (v) at (9,0) {$\ttm{v}$};
  5601. \draw (v) to (x);
  5602. \draw (x) to (y);
  5603. \draw (x) to (z);
  5604. \draw (y) to (t);
  5605. \end{tikzpicture}
  5606. \]
  5607. \fi}
  5608. %
  5609. {\if\edition\pythonEd
  5610. \[
  5611. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5612. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5613. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5614. \node (z) at (3,2) {$\ttm{z}$};
  5615. \node (x) at (6,2) {$\ttm{x}$};
  5616. \node (y) at (3,0) {$\ttm{y}$};
  5617. \node (w) at (6,0) {$\ttm{w}$};
  5618. \node (v) at (9,0) {$\ttm{v}$};
  5619. \draw (y) to (t0);
  5620. \draw (z) to (x);
  5621. \draw (z) to (t1);
  5622. \draw (x) to (y);
  5623. \draw (x) to (v);
  5624. \end{tikzpicture}
  5625. \]
  5626. \fi}
  5627. {\if\edition\racketEd
  5628. Now we replay the graph coloring, pausing to see the coloring of
  5629. \code{y}. Recall the following configuration. The most saturated vertices
  5630. were \code{w} and \code{y}.
  5631. \[
  5632. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5633. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5634. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5635. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5636. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5637. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5638. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5639. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5640. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5641. \draw (t1) to (rax);
  5642. \draw (t1) to (z);
  5643. \draw (z) to (y);
  5644. \draw (z) to (w);
  5645. \draw (x) to (w);
  5646. \draw (y) to (w);
  5647. \draw (v) to (w);
  5648. \draw (v) to (rsp);
  5649. \draw (w) to (rsp);
  5650. \draw (x) to (rsp);
  5651. \draw (y) to (rsp);
  5652. \path[-.,bend left=15] (z) edge node {} (rsp);
  5653. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5654. \draw (rax) to (rsp);
  5655. \end{tikzpicture}
  5656. \]
  5657. %
  5658. The last time, we chose to color \code{w} with $0$. This time, we see
  5659. that \code{w} is not move-related to any vertex, but \code{y} is
  5660. move-related to \code{t}. So we choose to color \code{y} with $0$,
  5661. the same color as \code{t}.
  5662. \[
  5663. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5664. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5665. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5666. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5667. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5668. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5669. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5670. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5671. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5672. \draw (t1) to (rax);
  5673. \draw (t1) to (z);
  5674. \draw (z) to (y);
  5675. \draw (z) to (w);
  5676. \draw (x) to (w);
  5677. \draw (y) to (w);
  5678. \draw (v) to (w);
  5679. \draw (v) to (rsp);
  5680. \draw (w) to (rsp);
  5681. \draw (x) to (rsp);
  5682. \draw (y) to (rsp);
  5683. \path[-.,bend left=15] (z) edge node {} (rsp);
  5684. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5685. \draw (rax) to (rsp);
  5686. \end{tikzpicture}
  5687. \]
  5688. Now \code{w} is the most saturated, so we color it $2$.
  5689. \[
  5690. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5691. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5692. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5693. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5694. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5695. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5696. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5697. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5698. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5699. \draw (t1) to (rax);
  5700. \draw (t1) to (z);
  5701. \draw (z) to (y);
  5702. \draw (z) to (w);
  5703. \draw (x) to (w);
  5704. \draw (y) to (w);
  5705. \draw (v) to (w);
  5706. \draw (v) to (rsp);
  5707. \draw (w) to (rsp);
  5708. \draw (x) to (rsp);
  5709. \draw (y) to (rsp);
  5710. \path[-.,bend left=15] (z) edge node {} (rsp);
  5711. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5712. \draw (rax) to (rsp);
  5713. \end{tikzpicture}
  5714. \]
  5715. At this point, vertices \code{x} and \code{v} are most saturated, but
  5716. \code{x} is move related to \code{y} and \code{z}, so we color
  5717. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5718. \[
  5719. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5720. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5721. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5722. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5723. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5724. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5725. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5726. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5727. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5728. \draw (t1) to (rax);
  5729. \draw (t) to (z);
  5730. \draw (z) to (y);
  5731. \draw (z) to (w);
  5732. \draw (x) to (w);
  5733. \draw (y) to (w);
  5734. \draw (v) to (w);
  5735. \draw (v) to (rsp);
  5736. \draw (w) to (rsp);
  5737. \draw (x) to (rsp);
  5738. \draw (y) to (rsp);
  5739. \path[-.,bend left=15] (z) edge node {} (rsp);
  5740. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5741. \draw (rax) to (rsp);
  5742. \end{tikzpicture}
  5743. \]
  5744. \fi}
  5745. %
  5746. {\if\edition\pythonEd
  5747. Now we replay the graph coloring, pausing before the coloring of
  5748. \code{w}. Recall the following configuration. The most saturated vertices
  5749. were \code{tmp\_1}, \code{w}, and \code{y}.
  5750. \[
  5751. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5752. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5753. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5754. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5755. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5756. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5757. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5758. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5759. \draw (t0) to (t1);
  5760. \draw (t0) to (z);
  5761. \draw (z) to (y);
  5762. \draw (z) to (w);
  5763. \draw (x) to (w);
  5764. \draw (y) to (w);
  5765. \draw (v) to (w);
  5766. \end{tikzpicture}
  5767. \]
  5768. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5769. or \code{y}, but note that \code{w} is not move related to any
  5770. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5771. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5772. \code{y} and color it $0$, we can delete another move instruction.
  5773. \[
  5774. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5775. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5776. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5777. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5778. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5779. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5780. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5781. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5782. \draw (t0) to (t1);
  5783. \draw (t0) to (z);
  5784. \draw (z) to (y);
  5785. \draw (z) to (w);
  5786. \draw (x) to (w);
  5787. \draw (y) to (w);
  5788. \draw (v) to (w);
  5789. \end{tikzpicture}
  5790. \]
  5791. Now \code{w} is the most saturated, so we color it $2$.
  5792. \[
  5793. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5794. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5795. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5796. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5797. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5798. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5799. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5800. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5801. \draw (t0) to (t1);
  5802. \draw (t0) to (z);
  5803. \draw (z) to (y);
  5804. \draw (z) to (w);
  5805. \draw (x) to (w);
  5806. \draw (y) to (w);
  5807. \draw (v) to (w);
  5808. \end{tikzpicture}
  5809. \]
  5810. To finish the coloring, \code{x} and \code{v} get $0$ and
  5811. \code{tmp\_1} gets $1$.
  5812. \[
  5813. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5814. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5815. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5816. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5817. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5818. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5819. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5820. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5821. \draw (t0) to (t1);
  5822. \draw (t0) to (z);
  5823. \draw (z) to (y);
  5824. \draw (z) to (w);
  5825. \draw (x) to (w);
  5826. \draw (y) to (w);
  5827. \draw (v) to (w);
  5828. \end{tikzpicture}
  5829. \]
  5830. \fi}
  5831. So, we have the following assignment of variables to registers.
  5832. {\if\edition\racketEd
  5833. \begin{gather*}
  5834. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5835. \ttm{w} \mapsto \key{\%rsi}, \,
  5836. \ttm{x} \mapsto \key{\%rcx}, \,
  5837. \ttm{y} \mapsto \key{\%rcx}, \,
  5838. \ttm{z} \mapsto \key{\%rdx}, \,
  5839. \ttm{t} \mapsto \key{\%rcx} \}
  5840. \end{gather*}
  5841. \fi}
  5842. {\if\edition\pythonEd
  5843. \begin{gather*}
  5844. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5845. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5846. \ttm{x} \mapsto \key{\%rcx}, \,
  5847. \ttm{y} \mapsto \key{\%rcx}, \\
  5848. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5849. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5850. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5851. \end{gather*}
  5852. \fi}
  5853. %
  5854. We apply this register assignment to the running example shown next,
  5855. on the left, to obtain the code in the middle. The
  5856. \code{patch\_instructions} then deletes the trivial moves to obtain
  5857. the code on the right.
  5858. {\if\edition\racketEd
  5859. \begin{minipage}{0.25\textwidth}
  5860. \begin{lstlisting}
  5861. movq $1, v
  5862. movq $42, w
  5863. movq v, x
  5864. addq $7, x
  5865. movq x, y
  5866. movq x, z
  5867. addq w, z
  5868. movq y, t
  5869. negq t
  5870. movq z, %rax
  5871. addq t, %rax
  5872. jmp conclusion
  5873. \end{lstlisting}
  5874. \end{minipage}
  5875. $\Rightarrow\qquad$
  5876. \begin{minipage}{0.25\textwidth}
  5877. \begin{lstlisting}
  5878. movq $1, %rcx
  5879. movq $42, %rsi
  5880. movq %rcx, %rcx
  5881. addq $7, %rcx
  5882. movq %rcx, %rcx
  5883. movq %rcx, %rdx
  5884. addq %rsi, %rdx
  5885. movq %rcx, %rcx
  5886. negq %rcx
  5887. movq %rdx, %rax
  5888. addq %rcx, %rax
  5889. jmp conclusion
  5890. \end{lstlisting}
  5891. \end{minipage}
  5892. $\Rightarrow\qquad$
  5893. \begin{minipage}{0.25\textwidth}
  5894. \begin{lstlisting}
  5895. movq $1, %rcx
  5896. movq $42, %rsi
  5897. addq $7, %rcx
  5898. movq %rcx, %rdx
  5899. addq %rsi, %rdx
  5900. negq %rcx
  5901. movq %rdx, %rax
  5902. addq %rcx, %rax
  5903. jmp conclusion
  5904. \end{lstlisting}
  5905. \end{minipage}
  5906. \fi}
  5907. {\if\edition\pythonEd
  5908. \begin{minipage}{0.20\textwidth}
  5909. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5910. movq $1, v
  5911. movq $42, w
  5912. movq v, x
  5913. addq $7, x
  5914. movq x, y
  5915. movq x, z
  5916. addq w, z
  5917. movq y, tmp_0
  5918. negq tmp_0
  5919. movq z, tmp_1
  5920. addq tmp_0, tmp_1
  5921. movq tmp_1, %rdi
  5922. callq _print_int
  5923. \end{lstlisting}
  5924. \end{minipage}
  5925. ${\Rightarrow\qquad}$
  5926. \begin{minipage}{0.30\textwidth}
  5927. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5928. movq $1, %rcx
  5929. movq $42, -16(%rbp)
  5930. movq %rcx, %rcx
  5931. addq $7, %rcx
  5932. movq %rcx, %rcx
  5933. movq %rcx, -8(%rbp)
  5934. addq -16(%rbp), -8(%rbp)
  5935. movq %rcx, %rcx
  5936. negq %rcx
  5937. movq -8(%rbp), -8(%rbp)
  5938. addq %rcx, -8(%rbp)
  5939. movq -8(%rbp), %rdi
  5940. callq _print_int
  5941. \end{lstlisting}
  5942. \end{minipage}
  5943. ${\Rightarrow\qquad}$
  5944. \begin{minipage}{0.20\textwidth}
  5945. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5946. movq $1, %rcx
  5947. movq $42, -16(%rbp)
  5948. addq $7, %rcx
  5949. movq %rcx, -8(%rbp)
  5950. movq -16(%rbp), %rax
  5951. addq %rax, -8(%rbp)
  5952. negq %rcx
  5953. addq %rcx, -8(%rbp)
  5954. movq -8(%rbp), %rdi
  5955. callq print_int
  5956. \end{lstlisting}
  5957. \end{minipage}
  5958. \fi}
  5959. \begin{exercise}\normalfont\normalsize
  5960. Change your implementation of \code{allocate\_registers} to take move
  5961. biasing into account. Create two new tests that include at least one
  5962. opportunity for move biasing, and visually inspect the output x86
  5963. programs to make sure that your move biasing is working properly. Make
  5964. sure that your compiler still passes all the tests.
  5965. \end{exercise}
  5966. %To do: another neat challenge would be to do
  5967. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5968. %% \subsection{Output of the Running Example}
  5969. %% \label{sec:reg-alloc-output}
  5970. % challenge: prioritize variables based on execution frequencies
  5971. % and the number of uses of a variable
  5972. % challenge: enhance the coloring algorithm using Chaitin's
  5973. % approach of prioritizing high-degree variables
  5974. % by removing low-degree variables (coloring them later)
  5975. % from the interference graph
  5976. \section{Further Reading}
  5977. \label{sec:register-allocation-further-reading}
  5978. Early register allocation algorithms were developed for Fortran
  5979. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5980. of graph coloring began in the late 1970s and early 1980s with the
  5981. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5982. algorithm is based on the following observation of
  5983. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5984. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5985. $v$ removed is also $k$ colorable. To see why, suppose that the
  5986. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  5987. different colors, but because there are fewer than $k$ neighbors, there
  5988. will be one or more colors left over to use for coloring $v$ in $G$.
  5989. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5990. less than $k$ from the graph and recursively colors the rest of the
  5991. graph. Upon returning from the recursion, it colors $v$ with one of
  5992. the available colors and returns. \citet{Chaitin:1982vn} augments
  5993. this algorithm to handle spilling as follows. If there are no vertices
  5994. of degree lower than $k$ then pick a vertex at random, spill it,
  5995. remove it from the graph, and proceed recursively to color the rest of
  5996. the graph.
  5997. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  5998. move-related and that don't interfere with each other, in a process
  5999. called \emph{coalescing}. Although coalescing decreases the number of
  6000. moves, it can make the graph more difficult to
  6001. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6002. which two variables are merged only if they have fewer than $k$
  6003. neighbors of high degree. \citet{George:1996aa} observed that
  6004. conservative coalescing is sometimes too conservative and made it more
  6005. aggressive by iterating the coalescing with the removal of low-degree
  6006. vertices.
  6007. %
  6008. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6009. also proposed \emph{biased coloring}, in which a variable is assigned to
  6010. the same color as another move-related variable if possible, as
  6011. discussed in section~\ref{sec:move-biasing}.
  6012. %
  6013. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6014. performs coalescing, graph coloring, and spill code insertion until
  6015. all variables have been assigned a location.
  6016. \citet{Briggs:1994kx} observed that \citet{Chaitin:1982vn} sometimes
  6017. spilled variables that don't have to be: a high-degree variable can be
  6018. colorable if many of its neighbors are assigned the same color.
  6019. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6020. high-degree vertex is not immediately spilled. Instead the decision is
  6021. deferred until after the recursive call, at which point it is apparent
  6022. whether there is actually an available color or not. We observe that
  6023. this algorithm is equivalent to the smallest-last ordering
  6024. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6025. be registers and the rest to be stack locations.
  6026. %% biased coloring
  6027. Earlier editions of the compiler course at Indiana University
  6028. \citep{Dybvig:2010aa} were based on the algorithm of
  6029. \citet{Briggs:1994kx}.
  6030. The smallest-last ordering algorithm is one of many \emph{greedy}
  6031. coloring algorithms. A greedy coloring algorithm visits all the
  6032. vertices in a particular order and assigns each one the first
  6033. available color. An \emph{offline} greedy algorithm chooses the
  6034. ordering up front, prior to assigning colors. The algorithm of
  6035. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6036. ordering does not depend on the colors assigned. Other orderings are
  6037. possible. For example, \citet{Chow:1984ys} ordered variables according
  6038. to an estimate of runtime cost.
  6039. An \emph{online} greedy coloring algorithm uses information about the
  6040. current assignment of colors to influence the order in which the
  6041. remaining vertices are colored. The saturation-based algorithm
  6042. described in this chapter is one such algorithm. We choose to use
  6043. saturation-based coloring because it is fun to introduce graph
  6044. coloring via sudoku!
  6045. A register allocator may choose to map each variable to just one
  6046. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6047. variable to one or more locations. The latter can be achieved by
  6048. \emph{live range splitting}, where a variable is replaced by several
  6049. variables that each handle part of its live
  6050. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6051. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6052. %% replacement algorithm, bottom-up local
  6053. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6054. %% Cooper: top-down (priority bassed), bottom-up
  6055. %% top-down
  6056. %% order variables by priority (estimated cost)
  6057. %% caveat: split variables into two groups:
  6058. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6059. %% color the constrained ones first
  6060. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6061. %% cite J. Cocke for an algorithm that colors variables
  6062. %% in a high-degree first ordering
  6063. %Register Allocation via Usage Counts, Freiburghouse CACM
  6064. \citet{Palsberg:2007si} observed that many of the interference graphs
  6065. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6066. that is, every cycle with four or more edges has an edge that is not
  6067. part of the cycle but that connects two vertices on the cycle. Such
  6068. graphs can be optimally colored by the greedy algorithm with a vertex
  6069. ordering determined by maximum cardinality search.
  6070. In situations in which compile time is of utmost importance, such as
  6071. in just-in-time compilers, graph coloring algorithms can be too
  6072. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6073. be more appropriate.
  6074. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6075. \chapter{Booleans and Conditionals}
  6076. \label{ch:Lif}
  6077. \index{subject}{Boolean}
  6078. \index{subject}{control flow}
  6079. \index{subject}{conditional expression}
  6080. \setcounter{footnote}{0}
  6081. The \LangVar{} language has only a single kind of value, the
  6082. integers. In this chapter we add a second kind of value, the Booleans,
  6083. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6084. the Boolean values \emph{true} and \emph{false} are written \TRUE{}
  6085. and \FALSE{}, respectively. The \LangIf{} language includes several
  6086. operations that involve Booleans (\key{and}, \key{not},
  6087. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6088. expression \python{and statement}. With the addition of \key{if},
  6089. programs can have nontrivial control flow which
  6090. %
  6091. \racket{impacts \code{explicate\_control} and liveness analysis}
  6092. %
  6093. \python{impacts liveness analysis and motivates a new pass named
  6094. \code{explicate\_control}}.
  6095. %
  6096. Also, because we now have two kinds of values, we need to handle
  6097. programs that apply an operation to the wrong kind of value, such as
  6098. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6099. There are two language design options for such situations. One option
  6100. is to signal an error and the other is to provide a wider
  6101. interpretation of the operation. \racket{The Racket
  6102. language}\python{Python} uses a mixture of these two options,
  6103. depending on the operation and the kind of value. For example, the
  6104. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6105. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6106. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6107. %
  6108. \racket{On the other hand, \code{(car 1)} results in a runtime error
  6109. in Racket because \code{car} expects a pair.}
  6110. %
  6111. \python{On the other hand, \code{1[0]} results in a runtime error
  6112. in Python because an ``\code{int} object is not subscriptable''.}
  6113. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6114. design choices as \racket{Racket}\python{Python}, except that much of the
  6115. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6116. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6117. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  6118. \python{MyPy} reports a compile-time error
  6119. %
  6120. \racket{because Racket expects the type of the argument to be of the form
  6121. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6122. %
  6123. \python{stating that a ``value of type \code{int} is not indexable''.}
  6124. The \LangIf{} language performs type checking during compilation just as
  6125. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  6126. the alternative choice, that is, a dynamically typed language like
  6127. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6128. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6129. restrictive, for example, rejecting \racket{\code{(not
  6130. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6131. fairly simple because the focus of this book is on compilation and not
  6132. type systems, about which there are already several excellent
  6133. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6134. This chapter is organized as follows. We begin by defining the syntax
  6135. and interpreter for the \LangIf{} language
  6136. (section~\ref{sec:lang-if}). We then introduce the idea of type
  6137. checking and define a type checker for \LangIf{}
  6138. (section~\ref{sec:type-check-Lif}).
  6139. %
  6140. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6141. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  6142. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  6143. %
  6144. The remaining sections of this chapter discuss how Booleans and
  6145. conditional control flow require changes to the existing compiler
  6146. passes and the addition of new ones. We introduce the \code{shrink}
  6147. pass to translate some operators into others, thereby reducing the
  6148. number of operators that need to be handled in later passes.
  6149. %
  6150. The main event of this chapter is the \code{explicate\_control} pass
  6151. that is responsible for translating \code{if}s into conditional
  6152. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  6153. %
  6154. Regarding register allocation, there is the interesting question of
  6155. how to handle conditional \code{goto}s during liveness analysis.
  6156. \section{The \LangIf{} Language}
  6157. \label{sec:lang-if}
  6158. Definitions of the concrete syntax and abstract syntax of the
  6159. \LangIf{} language are shown in Figures~\ref{fig:Lif-concrete-syntax}
  6160. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  6161. includes all of \LangVar{} {(shown in gray)}, the Boolean literals
  6162. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression
  6163. %
  6164. \python{, and the \code{if} statement}. We expand the set of
  6165. operators to include
  6166. \begin{enumerate}
  6167. \item the logical operators \key{and}, \key{or}, and \key{not},
  6168. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6169. for comparing integers or Booleans for equality, and
  6170. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6171. comparing integers.
  6172. \end{enumerate}
  6173. \racket{We reorganize the abstract syntax for the primitive
  6174. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  6175. rule for all of them. This means that the grammar no longer checks
  6176. whether the arity of an operators matches the number of
  6177. arguments. That responsibility is moved to the type checker for
  6178. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  6179. \newcommand{\LifGrammarRacket}{
  6180. \begin{array}{lcl}
  6181. \Type &::=& \key{Boolean} \\
  6182. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6183. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6184. \Exp &::=& \itm{bool}
  6185. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6186. \MID (\key{not}\;\Exp) \\
  6187. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6188. \end{array}
  6189. }
  6190. \newcommand{\LifASTRacket}{
  6191. \begin{array}{lcl}
  6192. \Type &::=& \key{Boolean} \\
  6193. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6194. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6195. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6196. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6197. \end{array}
  6198. }
  6199. \newcommand{\LintOpAST}{
  6200. \begin{array}{rcl}
  6201. \Type &::=& \key{Integer} \\
  6202. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6203. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6204. \end{array}
  6205. }
  6206. \newcommand{\LifGrammarPython}{
  6207. \begin{array}{rcl}
  6208. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6209. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6210. \MID \key{not}~\Exp \\
  6211. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6212. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6213. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6214. \end{array}
  6215. }
  6216. \newcommand{\LifASTPython}{
  6217. \begin{array}{lcl}
  6218. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6219. \itm{unaryop} &::=& \code{Not()} \\
  6220. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6221. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6222. \Exp &::=& \BOOL{\itm{bool}}
  6223. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6224. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6225. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6226. \end{array}
  6227. }
  6228. \begin{figure}[tp]
  6229. \centering
  6230. \begin{tcolorbox}[colback=white]
  6231. {\if\edition\racketEd
  6232. \[
  6233. \begin{array}{l}
  6234. \gray{\LintGrammarRacket{}} \\ \hline
  6235. \gray{\LvarGrammarRacket{}} \\ \hline
  6236. \LifGrammarRacket{} \\
  6237. \begin{array}{lcl}
  6238. \LangIfM{} &::=& \Exp
  6239. \end{array}
  6240. \end{array}
  6241. \]
  6242. \fi}
  6243. {\if\edition\pythonEd
  6244. \[
  6245. \begin{array}{l}
  6246. \gray{\LintGrammarPython} \\ \hline
  6247. \gray{\LvarGrammarPython} \\ \hline
  6248. \LifGrammarPython \\
  6249. \begin{array}{rcl}
  6250. \LangIfM{} &::=& \Stmt^{*}
  6251. \end{array}
  6252. \end{array}
  6253. \]
  6254. \fi}
  6255. \end{tcolorbox}
  6256. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6257. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6258. \label{fig:Lif-concrete-syntax}
  6259. \end{figure}
  6260. \begin{figure}[tp]
  6261. %\begin{minipage}{0.66\textwidth}
  6262. \begin{tcolorbox}[colback=white]
  6263. \centering
  6264. {\if\edition\racketEd
  6265. \[
  6266. \begin{array}{l}
  6267. \gray{\LintOpAST} \\ \hline
  6268. \gray{\LvarASTRacket{}} \\ \hline
  6269. \LifASTRacket{} \\
  6270. \begin{array}{lcl}
  6271. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6272. \end{array}
  6273. \end{array}
  6274. \]
  6275. \fi}
  6276. {\if\edition\pythonEd
  6277. \[
  6278. \begin{array}{l}
  6279. \gray{\LintASTPython} \\ \hline
  6280. \gray{\LvarASTPython} \\ \hline
  6281. \LifASTPython \\
  6282. \begin{array}{lcl}
  6283. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6284. \end{array}
  6285. \end{array}
  6286. \]
  6287. \fi}
  6288. \end{tcolorbox}
  6289. %\end{minipage}
  6290. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  6291. \index{subject}{IfExp@\IFNAME{}}
  6292. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  6293. \index{subject}{and@\ANDNAME{}}
  6294. \index{subject}{or@\ORNAME{}}
  6295. \index{subject}{not@\NOTNAME{}}
  6296. \index{subject}{equal@\EQNAME{}}
  6297. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  6298. \racket{
  6299. \index{subject}{lessthan@\texttt{<}}
  6300. \index{subject}{lessthaneq@\texttt{<=}}
  6301. \index{subject}{greaterthan@\texttt{>}}
  6302. \index{subject}{greaterthaneq@\texttt{>=}}
  6303. }
  6304. \python{
  6305. \index{subject}{BoolOp@\texttt{BoolOp}}
  6306. \index{subject}{Compare@\texttt{Compare}}
  6307. \index{subject}{Lt@\texttt{Lt}}
  6308. \index{subject}{LtE@\texttt{LtE}}
  6309. \index{subject}{Gt@\texttt{Gt}}
  6310. \index{subject}{GtE@\texttt{GtE}}
  6311. }
  6312. \caption{The abstract syntax of \LangIf{}.}
  6313. \label{fig:Lif-syntax}
  6314. \end{figure}
  6315. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  6316. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  6317. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6318. evaluate to the corresponding Boolean values. The conditional
  6319. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  6320. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  6321. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  6322. \code{or}, and \code{not} behave according to propositional logic. In
  6323. addition, the \code{and} and \code{or} operations perform
  6324. \emph{short-circuit evaluation}.
  6325. %
  6326. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6327. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6328. %
  6329. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6330. evaluated if $e_1$ evaluates to \TRUE{}.
  6331. \racket{With the increase in the number of primitive operations, the
  6332. interpreter would become repetitive without some care. We refactor
  6333. the case for \code{Prim}, moving the code that differs with each
  6334. operation into the \code{interp\_op} method shown in
  6335. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6336. \code{or} operations separately because of their short-circuiting
  6337. behavior.}
  6338. \begin{figure}[tbp]
  6339. \begin{tcolorbox}[colback=white]
  6340. {\if\edition\racketEd
  6341. \begin{lstlisting}
  6342. (define interp-Lif-class
  6343. (class interp-Lvar-class
  6344. (super-new)
  6345. (define/public (interp_op op) ...)
  6346. (define/override ((interp_exp env) e)
  6347. (define recur (interp_exp env))
  6348. (match e
  6349. [(Bool b) b]
  6350. [(If cnd thn els)
  6351. (match (recur cnd)
  6352. [#t (recur thn)]
  6353. [#f (recur els)])]
  6354. [(Prim 'and (list e1 e2))
  6355. (match (recur e1)
  6356. [#t (match (recur e2) [#t #t] [#f #f])]
  6357. [#f #f])]
  6358. [(Prim 'or (list e1 e2))
  6359. (define v1 (recur e1))
  6360. (match v1
  6361. [#t #t]
  6362. [#f (match (recur e2) [#t #t] [#f #f])])]
  6363. [(Prim op args)
  6364. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6365. [else ((super interp_exp env) e)]))
  6366. ))
  6367. (define (interp_Lif p)
  6368. (send (new interp-Lif-class) interp_program p))
  6369. \end{lstlisting}
  6370. \fi}
  6371. {\if\edition\pythonEd
  6372. \begin{lstlisting}
  6373. class InterpLif(InterpLvar):
  6374. def interp_exp(self, e, env):
  6375. match e:
  6376. case IfExp(test, body, orelse):
  6377. if self.interp_exp(test, env):
  6378. return self.interp_exp(body, env)
  6379. else:
  6380. return self.interp_exp(orelse, env)
  6381. case UnaryOp(Not(), v):
  6382. return not self.interp_exp(v, env)
  6383. case BoolOp(And(), values):
  6384. if self.interp_exp(values[0], env):
  6385. return self.interp_exp(values[1], env)
  6386. else:
  6387. return False
  6388. case BoolOp(Or(), values):
  6389. if self.interp_exp(values[0], env):
  6390. return True
  6391. else:
  6392. return self.interp_exp(values[1], env)
  6393. case Compare(left, [cmp], [right]):
  6394. l = self.interp_exp(left, env)
  6395. r = self.interp_exp(right, env)
  6396. return self.interp_cmp(cmp)(l, r)
  6397. case _:
  6398. return super().interp_exp(e, env)
  6399. def interp_stmts(self, ss, env):
  6400. if len(ss) == 0:
  6401. return
  6402. match ss[0]:
  6403. case If(test, body, orelse):
  6404. if self.interp_exp(test, env):
  6405. return self.interp_stmts(body + ss[1:], env)
  6406. else:
  6407. return self.interp_stmts(orelse + ss[1:], env)
  6408. case _:
  6409. return super().interp_stmts(ss, env)
  6410. ...
  6411. \end{lstlisting}
  6412. \fi}
  6413. \end{tcolorbox}
  6414. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6415. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6416. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6417. \label{fig:interp-Lif}
  6418. \end{figure}
  6419. {\if\edition\racketEd
  6420. \begin{figure}[tbp]
  6421. \begin{tcolorbox}[colback=white]
  6422. \begin{lstlisting}
  6423. (define/public (interp_op op)
  6424. (match op
  6425. ['+ fx+]
  6426. ['- fx-]
  6427. ['read read-fixnum]
  6428. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6429. ['eq? (lambda (v1 v2)
  6430. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6431. (and (boolean? v1) (boolean? v2))
  6432. (and (vector? v1) (vector? v2)))
  6433. (eq? v1 v2)]))]
  6434. ['< (lambda (v1 v2)
  6435. (cond [(and (fixnum? v1) (fixnum? v2))
  6436. (< v1 v2)]))]
  6437. ['<= (lambda (v1 v2)
  6438. (cond [(and (fixnum? v1) (fixnum? v2))
  6439. (<= v1 v2)]))]
  6440. ['> (lambda (v1 v2)
  6441. (cond [(and (fixnum? v1) (fixnum? v2))
  6442. (> v1 v2)]))]
  6443. ['>= (lambda (v1 v2)
  6444. (cond [(and (fixnum? v1) (fixnum? v2))
  6445. (>= v1 v2)]))]
  6446. [else (error 'interp_op "unknown operator")]))
  6447. \end{lstlisting}
  6448. \end{tcolorbox}
  6449. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6450. \label{fig:interp-op-Lif}
  6451. \end{figure}
  6452. \fi}
  6453. {\if\edition\pythonEd
  6454. \begin{figure}
  6455. \begin{tcolorbox}[colback=white]
  6456. \begin{lstlisting}
  6457. class InterpLif(InterpLvar):
  6458. ...
  6459. def interp_cmp(self, cmp):
  6460. match cmp:
  6461. case Lt():
  6462. return lambda x, y: x < y
  6463. case LtE():
  6464. return lambda x, y: x <= y
  6465. case Gt():
  6466. return lambda x, y: x > y
  6467. case GtE():
  6468. return lambda x, y: x >= y
  6469. case Eq():
  6470. return lambda x, y: x == y
  6471. case NotEq():
  6472. return lambda x, y: x != y
  6473. \end{lstlisting}
  6474. \end{tcolorbox}
  6475. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6476. \label{fig:interp-cmp-Lif}
  6477. \end{figure}
  6478. \fi}
  6479. \section{Type Checking \LangIf{} Programs}
  6480. \label{sec:type-check-Lif}
  6481. \index{subject}{type checking}
  6482. \index{subject}{semantic analysis}
  6483. It is helpful to think about type checking in two complementary
  6484. ways. A type checker predicts the type of value that will be produced
  6485. by each expression in the program. For \LangIf{}, we have just two types,
  6486. \INTTY{} and \BOOLTY{}. So, a type checker should predict that
  6487. {\if\edition\racketEd
  6488. \begin{lstlisting}
  6489. (+ 10 (- (+ 12 20)))
  6490. \end{lstlisting}
  6491. \fi}
  6492. {\if\edition\pythonEd
  6493. \begin{lstlisting}
  6494. 10 + -(12 + 20)
  6495. \end{lstlisting}
  6496. \fi}
  6497. \noindent produces a value of type \INTTY{}, whereas
  6498. {\if\edition\racketEd
  6499. \begin{lstlisting}
  6500. (and (not #f) #t)
  6501. \end{lstlisting}
  6502. \fi}
  6503. {\if\edition\pythonEd
  6504. \begin{lstlisting}
  6505. (not False) and True
  6506. \end{lstlisting}
  6507. \fi}
  6508. \noindent produces a value of type \BOOLTY{}.
  6509. A second way to think about type checking is that it enforces a set of
  6510. rules about which operators can be applied to which kinds of
  6511. values. For example, our type checker for \LangIf{} signals an error
  6512. for the following expression:
  6513. %
  6514. {\if\edition\racketEd
  6515. \begin{lstlisting}
  6516. (not (+ 10 (- (+ 12 20))))
  6517. \end{lstlisting}
  6518. \fi}
  6519. {\if\edition\pythonEd
  6520. \begin{lstlisting}
  6521. not (10 + -(12 + 20))
  6522. \end{lstlisting}
  6523. \fi}
  6524. \noindent The subexpression
  6525. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6526. \python{\code{(10 + -(12 + 20))}}
  6527. has type \INTTY{}, but the type checker enforces the rule that the
  6528. argument of \code{not} must be an expression of type \BOOLTY{}.
  6529. We implement type checking using classes and methods because they
  6530. provide the open recursion needed to reuse code as we extend the type
  6531. checker in subsequent chapters, analogous to the use of classes and methods
  6532. for the interpreters (section~\ref{sec:extensible-interp}).
  6533. We separate the type checker for the \LangVar{} subset into its own
  6534. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  6535. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  6536. from the type checker for \LangVar{}. These type checkers are in the
  6537. files
  6538. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6539. and
  6540. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6541. of the support code.
  6542. %
  6543. Each type checker is a structurally recursive function over the AST.
  6544. Given an input expression \code{e}, the type checker either signals an
  6545. error or returns \racket{an expression and} its type.
  6546. %
  6547. \racket{It returns an expression because there are situations in which
  6548. we want to change or update the expression.}
  6549. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  6550. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  6551. constant is \INTTY{}. To handle variables, the type checker uses the
  6552. environment \code{env} to map variables to types.
  6553. %
  6554. \racket{Consider the case for \key{let}. We type check the
  6555. initializing expression to obtain its type \key{T} and then
  6556. associate type \code{T} with the variable \code{x} in the
  6557. environment used to type check the body of the \key{let}. Thus,
  6558. when the type checker encounters a use of variable \code{x}, it can
  6559. find its type in the environment.}
  6560. %
  6561. \python{Consider the case for assignment. We type check the
  6562. initializing expression to obtain its type \key{t}. If the variable
  6563. \code{lhs.id} is already in the environment because there was a
  6564. prior assignment, we check that this initializer has the same type
  6565. as the prior one. If this is the first assignment to the variable,
  6566. we associate type \code{t} with the variable \code{lhs.id} in the
  6567. environment. Thus, when the type checker encounters a use of
  6568. variable \code{x}, it can find its type in the environment.}
  6569. %
  6570. \racket{Regarding primitive operators, we recursively analyze the
  6571. arguments and then invoke \code{type\_check\_op} to check whether
  6572. the argument types are allowed.}
  6573. %
  6574. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6575. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6576. \racket{Several auxiliary methods are used in the type checker. The
  6577. method \code{operator-types} defines a dictionary that maps the
  6578. operator names to their parameter and return types. The
  6579. \code{type-equal?} method determines whether two types are equal,
  6580. which for now simply dispatches to \code{equal?} (deep
  6581. equality). The \code{check-type-equal?} method triggers an error if
  6582. the two types are not equal. The \code{type-check-op} method looks
  6583. up the operator in the \code{operator-types} dictionary and then
  6584. checks whether the argument types are equal to the parameter types.
  6585. The result is the return type of the operator.}
  6586. %
  6587. \python{The auxiliary method \code{check\_type\_equal} triggers
  6588. an error if the two types are not equal.}
  6589. \begin{figure}[tbp]
  6590. \begin{tcolorbox}[colback=white]
  6591. {\if\edition\racketEd
  6592. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6593. (define type-check-Lvar-class
  6594. (class object%
  6595. (super-new)
  6596. (define/public (operator-types)
  6597. '((+ . ((Integer Integer) . Integer))
  6598. (- . ((Integer Integer) . Integer))
  6599. (read . (() . Integer))))
  6600. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6601. (define/public (check-type-equal? t1 t2 e)
  6602. (unless (type-equal? t1 t2)
  6603. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6604. (define/public (type-check-op op arg-types e)
  6605. (match (dict-ref (operator-types) op)
  6606. [`(,param-types . ,return-type)
  6607. (for ([at arg-types] [pt param-types])
  6608. (check-type-equal? at pt e))
  6609. return-type]
  6610. [else (error 'type-check-op "unrecognized ~a" op)]))
  6611. (define/public (type-check-exp env)
  6612. (lambda (e)
  6613. (match e
  6614. [(Int n) (values (Int n) 'Integer)]
  6615. [(Var x) (values (Var x) (dict-ref env x))]
  6616. [(Let x e body)
  6617. (define-values (e^ Te) ((type-check-exp env) e))
  6618. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6619. (values (Let x e^ b) Tb)]
  6620. [(Prim op es)
  6621. (define-values (new-es ts)
  6622. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6623. (values (Prim op new-es) (type-check-op op ts e))]
  6624. [else (error 'type-check-exp "couldn't match" e)])))
  6625. (define/public (type-check-program e)
  6626. (match e
  6627. [(Program info body)
  6628. (define-values (body^ Tb) ((type-check-exp '()) body))
  6629. (check-type-equal? Tb 'Integer body)
  6630. (Program info body^)]
  6631. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6632. ))
  6633. (define (type-check-Lvar p)
  6634. (send (new type-check-Lvar-class) type-check-program p))
  6635. \end{lstlisting}
  6636. \fi}
  6637. {\if\edition\pythonEd
  6638. \begin{lstlisting}[escapechar=`]
  6639. class TypeCheckLvar:
  6640. def check_type_equal(self, t1, t2, e):
  6641. if t1 != t2:
  6642. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6643. raise Exception(msg)
  6644. def type_check_exp(self, e, env):
  6645. match e:
  6646. case BinOp(left, (Add() | Sub()), right):
  6647. l = self.type_check_exp(left, env)
  6648. check_type_equal(l, int, left)
  6649. r = self.type_check_exp(right, env)
  6650. check_type_equal(r, int, right)
  6651. return int
  6652. case UnaryOp(USub(), v):
  6653. t = self.type_check_exp(v, env)
  6654. check_type_equal(t, int, v)
  6655. return int
  6656. case Name(id):
  6657. return env[id]
  6658. case Constant(value) if isinstance(value, int):
  6659. return int
  6660. case Call(Name('input_int'), []):
  6661. return int
  6662. def type_check_stmts(self, ss, env):
  6663. if len(ss) == 0:
  6664. return
  6665. match ss[0]:
  6666. case Assign([lhs], value):
  6667. t = self.type_check_exp(value, env)
  6668. if lhs.id in env:
  6669. check_type_equal(env[lhs.id], t, value)
  6670. else:
  6671. env[lhs.id] = t
  6672. return self.type_check_stmts(ss[1:], env)
  6673. case Expr(Call(Name('print'), [arg])):
  6674. t = self.type_check_exp(arg, env)
  6675. check_type_equal(t, int, arg)
  6676. return self.type_check_stmts(ss[1:], env)
  6677. case Expr(value):
  6678. self.type_check_exp(value, env)
  6679. return self.type_check_stmts(ss[1:], env)
  6680. def type_check_P(self, p):
  6681. match p:
  6682. case Module(body):
  6683. self.type_check_stmts(body, {})
  6684. \end{lstlisting}
  6685. \fi}
  6686. \end{tcolorbox}
  6687. \caption{Type checker for the \LangVar{} language.}
  6688. \label{fig:type-check-Lvar}
  6689. \end{figure}
  6690. \begin{figure}[tbp]
  6691. \begin{tcolorbox}[colback=white]
  6692. {\if\edition\racketEd
  6693. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6694. (define type-check-Lif-class
  6695. (class type-check-Lvar-class
  6696. (super-new)
  6697. (inherit check-type-equal?)
  6698. (define/override (operator-types)
  6699. (append '((and . ((Boolean Boolean) . Boolean))
  6700. (or . ((Boolean Boolean) . Boolean))
  6701. (< . ((Integer Integer) . Boolean))
  6702. (<= . ((Integer Integer) . Boolean))
  6703. (> . ((Integer Integer) . Boolean))
  6704. (>= . ((Integer Integer) . Boolean))
  6705. (not . ((Boolean) . Boolean)))
  6706. (super operator-types)))
  6707. (define/override (type-check-exp env)
  6708. (lambda (e)
  6709. (match e
  6710. [(Bool b) (values (Bool b) 'Boolean)]
  6711. [(Prim 'eq? (list e1 e2))
  6712. (define-values (e1^ T1) ((type-check-exp env) e1))
  6713. (define-values (e2^ T2) ((type-check-exp env) e2))
  6714. (check-type-equal? T1 T2 e)
  6715. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6716. [(If cnd thn els)
  6717. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6718. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6719. (define-values (els^ Te) ((type-check-exp env) els))
  6720. (check-type-equal? Tc 'Boolean e)
  6721. (check-type-equal? Tt Te e)
  6722. (values (If cnd^ thn^ els^) Te)]
  6723. [else ((super type-check-exp env) e)])))
  6724. ))
  6725. (define (type-check-Lif p)
  6726. (send (new type-check-Lif-class) type-check-program p))
  6727. \end{lstlisting}
  6728. \fi}
  6729. {\if\edition\pythonEd
  6730. \begin{lstlisting}
  6731. class TypeCheckLif(TypeCheckLvar):
  6732. def type_check_exp(self, e, env):
  6733. match e:
  6734. case Constant(value) if isinstance(value, bool):
  6735. return bool
  6736. case BinOp(left, Sub(), right):
  6737. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6738. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6739. return int
  6740. case UnaryOp(Not(), v):
  6741. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6742. return bool
  6743. case BoolOp(op, values):
  6744. left = values[0] ; right = values[1]
  6745. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6746. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6747. return bool
  6748. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6749. or isinstance(cmp, NotEq):
  6750. l = self.type_check_exp(left, env)
  6751. r = self.type_check_exp(right, env)
  6752. check_type_equal(l, r, e)
  6753. return bool
  6754. case Compare(left, [cmp], [right]):
  6755. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6756. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6757. return bool
  6758. case IfExp(test, body, orelse):
  6759. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6760. b = self.type_check_exp(body, env)
  6761. o = self.type_check_exp(orelse, env)
  6762. check_type_equal(b, o, e)
  6763. return b
  6764. case _:
  6765. return super().type_check_exp(e, env)
  6766. def type_check_stmts(self, ss, env):
  6767. if len(ss) == 0:
  6768. return
  6769. match ss[0]:
  6770. case If(test, body, orelse):
  6771. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6772. b = self.type_check_stmts(body, env)
  6773. o = self.type_check_stmts(orelse, env)
  6774. check_type_equal(b, o, ss[0])
  6775. return self.type_check_stmts(ss[1:], env)
  6776. case _:
  6777. return super().type_check_stmts(ss, env)
  6778. \end{lstlisting}
  6779. \fi}
  6780. \end{tcolorbox}
  6781. \caption{Type checker for the \LangIf{} language.}
  6782. \label{fig:type-check-Lif}
  6783. \end{figure}
  6784. The definition of the type checker for \LangIf{} is shown in
  6785. figure~\ref{fig:type-check-Lif}.
  6786. %
  6787. The type of a Boolean constant is \BOOLTY{}.
  6788. %
  6789. \racket{The \code{operator-types} function adds dictionary entries for
  6790. the new operators.}
  6791. %
  6792. \python{Logical not requires its argument to be a \BOOLTY{} and
  6793. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6794. %
  6795. The equality operator requires the two arguments to have the same type,
  6796. and therefore we handle it separately from the other operators.
  6797. %
  6798. \python{The other comparisons (less-than, etc.) require their
  6799. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6800. %
  6801. The condition of an \code{if} must
  6802. be of \BOOLTY{} type, and the two branches must have the same type.
  6803. \begin{exercise}\normalfont\normalsize
  6804. Create ten new test programs in \LangIf{}. Half the programs should
  6805. have a type error. For those programs, create an empty file with the
  6806. same base name and with file extension \code{.tyerr}. For example, if
  6807. the test
  6808. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6809. is expected to error, then create
  6810. an empty file named \code{cond\_test\_14.tyerr}.
  6811. %
  6812. \racket{This indicates to \code{interp-tests} and
  6813. \code{compiler-tests} that a type error is expected. }
  6814. %
  6815. The other half of the test programs should not have type errors.
  6816. %
  6817. \racket{In the \code{run-tests.rkt} script, change the second argument
  6818. of \code{interp-tests} and \code{compiler-tests} to
  6819. \code{type-check-Lif}, which causes the type checker to run prior to
  6820. the compiler passes. Temporarily change the \code{passes} to an
  6821. empty list and run the script, thereby checking that the new test
  6822. programs either type check or do not, as intended.}
  6823. %
  6824. Run the test script to check that these test programs type check as
  6825. expected.
  6826. \end{exercise}
  6827. \clearpage
  6828. \section{The \LangCIf{} Intermediate Language}
  6829. \label{sec:Cif}
  6830. {\if\edition\racketEd
  6831. %
  6832. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  6833. comparison operators to the \Exp{} nonterminal and the literals
  6834. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  6835. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  6836. \Tail{} nonterminal. The condition of an \code{if} statement is a
  6837. comparison operation and the branches are \code{goto} statements,
  6838. making it straightforward to compile \code{if} statements to x86. The
  6839. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  6840. expressions. A \code{goto} statement transfers control to the $\Tail$
  6841. expression corresponding to its label.
  6842. %
  6843. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6844. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  6845. defines its abstract syntax.
  6846. %
  6847. \fi}
  6848. %
  6849. {\if\edition\pythonEd
  6850. %
  6851. The output of \key{explicate\_control} is a language similar to the
  6852. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6853. \code{goto} statements, so we name it \LangCIf{}.
  6854. %
  6855. The \LangCIf{} language supports the same operators as \LangIf{} but
  6856. the arguments of operators are restricted to atomic expressions. The
  6857. \LangCIf{} language does not include \code{if} expressions but it does
  6858. include a restricted form of \code{if} statement. The condition must be
  6859. a comparison and the two branches may only contain \code{goto}
  6860. statements. These restrictions make it easier to translate \code{if}
  6861. statements to x86. The \LangCIf{} language also adds a \code{return}
  6862. statement to finish the program with a specified value.
  6863. %
  6864. The \key{CProgram} construct contains a dictionary mapping labels to
  6865. lists of statements that end with a \code{return} statement, a
  6866. \code{goto}, or a conditional \code{goto}.
  6867. %% Statement lists of this
  6868. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  6869. %% is a control transfer at the end and control only enters at the
  6870. %% beginning of the list, which is marked by the label.
  6871. %
  6872. A \code{goto} statement transfers control to the sequence of statements
  6873. associated with its label.
  6874. %
  6875. The concrete syntax for \LangCIf{} is defined in
  6876. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  6877. in figure~\ref{fig:c1-syntax}.
  6878. %
  6879. \fi}
  6880. %
  6881. \newcommand{\CifGrammarRacket}{
  6882. \begin{array}{lcl}
  6883. \Atm &::=& \itm{bool} \\
  6884. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6885. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6886. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6887. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6888. \end{array}
  6889. }
  6890. \newcommand{\CifASTRacket}{
  6891. \begin{array}{lcl}
  6892. \Atm &::=& \BOOL{\itm{bool}} \\
  6893. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6894. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6895. \Tail &::= & \GOTO{\itm{label}} \\
  6896. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6897. \end{array}
  6898. }
  6899. \newcommand{\CifGrammarPython}{
  6900. \begin{array}{lcl}
  6901. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6902. \Exp &::= & \Atm \MID \CREAD{}
  6903. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6904. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6905. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6906. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  6907. &\MID& \CASSIGN{\Var}{\Exp}
  6908. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6909. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6910. \end{array}
  6911. }
  6912. \newcommand{\CifASTPython}{
  6913. \begin{array}{lcl}
  6914. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6915. \Exp &::= & \Atm \MID \READ{} \\
  6916. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6917. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6918. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6919. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6920. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6921. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6922. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6923. \end{array}
  6924. }
  6925. \begin{figure}[tbp]
  6926. \begin{tcolorbox}[colback=white]
  6927. \small
  6928. {\if\edition\racketEd
  6929. \[
  6930. \begin{array}{l}
  6931. \gray{\CvarGrammarRacket} \\ \hline
  6932. \CifGrammarRacket \\
  6933. \begin{array}{lcl}
  6934. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6935. \end{array}
  6936. \end{array}
  6937. \]
  6938. \fi}
  6939. {\if\edition\pythonEd
  6940. \[
  6941. \begin{array}{l}
  6942. \CifGrammarPython \\
  6943. \begin{array}{lcl}
  6944. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6945. \end{array}
  6946. \end{array}
  6947. \]
  6948. \fi}
  6949. \end{tcolorbox}
  6950. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  6951. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  6952. \label{fig:c1-concrete-syntax}
  6953. \end{figure}
  6954. \begin{figure}[tp]
  6955. \begin{tcolorbox}[colback=white]
  6956. \small
  6957. {\if\edition\racketEd
  6958. \[
  6959. \begin{array}{l}
  6960. \gray{\CvarASTRacket} \\ \hline
  6961. \CifASTRacket \\
  6962. \begin{array}{lcl}
  6963. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6964. \end{array}
  6965. \end{array}
  6966. \]
  6967. \fi}
  6968. {\if\edition\pythonEd
  6969. \[
  6970. \begin{array}{l}
  6971. \CifASTPython \\
  6972. \begin{array}{lcl}
  6973. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6974. \end{array}
  6975. \end{array}
  6976. \]
  6977. \fi}
  6978. \end{tcolorbox}
  6979. \racket{
  6980. \index{subject}{IfStmt@\IFSTMTNAME{}}
  6981. }
  6982. \index{subject}{Goto@\texttt{Goto}}
  6983. \index{subject}{Return@\texttt{Return}}
  6984. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6985. (figure~\ref{fig:c0-syntax})}.}
  6986. \label{fig:c1-syntax}
  6987. \end{figure}
  6988. \section{The \LangXIf{} Language}
  6989. \label{sec:x86-if}
  6990. \index{subject}{x86} To implement the new logical operations, the
  6991. comparison operations, and the \key{if} expression\python{ and
  6992. statement}, we delve further into the x86
  6993. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  6994. the definitions of the concrete and abstract syntax for the \LangXIf{}
  6995. subset of x86, which includes instructions for logical operations,
  6996. comparisons, and \racket{conditional} jumps.
  6997. %
  6998. \python{The abstract syntax for an \LangXIf{} program contains a
  6999. dictionary mapping labels to sequences of instructions, each of
  7000. which we refer to as a \emph{basic block}\index{subject}{basic
  7001. block}.}
  7002. One challenge is that x86 does not provide an instruction that
  7003. directly implements logical negation (\code{not} in \LangIf{} and
  7004. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7005. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7006. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7007. bit of its arguments, and writes the results into its second argument.
  7008. Recall the following truth table for exclusive-or:
  7009. \begin{center}
  7010. \begin{tabular}{l|cc}
  7011. & 0 & 1 \\ \hline
  7012. 0 & 0 & 1 \\
  7013. 1 & 1 & 0
  7014. \end{tabular}
  7015. \end{center}
  7016. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7017. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7018. for the bit $1$, the result is the opposite of the second bit. Thus,
  7019. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7020. the first argument, as follows, where $\Arg$ is the translation of
  7021. $\Atm$ to x86:
  7022. \[
  7023. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7024. \qquad\Rightarrow\qquad
  7025. \begin{array}{l}
  7026. \key{movq}~ \Arg\key{,} \Var\\
  7027. \key{xorq}~ \key{\$1,} \Var
  7028. \end{array}
  7029. \]
  7030. \newcommand{\GrammarXIf}{
  7031. \begin{array}{lcl}
  7032. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7033. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7034. \Arg &::=& \key{\%}\itm{bytereg}\\
  7035. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7036. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7037. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7038. \MID \key{set}cc~\Arg
  7039. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7040. &\MID& \key{j}cc~\itm{label} \\
  7041. \end{array}
  7042. }
  7043. \begin{figure}[tp]
  7044. \begin{tcolorbox}[colback=white]
  7045. \[
  7046. \begin{array}{l}
  7047. \gray{\GrammarXInt} \\ \hline
  7048. \GrammarXIf \\
  7049. \begin{array}{lcl}
  7050. \LangXIfM{} &::= & \key{.globl main} \\
  7051. & & \key{main:} \; \Instr\ldots
  7052. \end{array}
  7053. \end{array}
  7054. \]
  7055. \end{tcolorbox}
  7056. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7057. \label{fig:x86-1-concrete}
  7058. \end{figure}
  7059. \newcommand{\ASTXIfRacket}{
  7060. \begin{array}{lcl}
  7061. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7062. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7063. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7064. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7065. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7066. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7067. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7068. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7069. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7070. \end{array}
  7071. }
  7072. \begin{figure}[tp]
  7073. \begin{tcolorbox}[colback=white]
  7074. \small
  7075. {\if\edition\racketEd
  7076. \[\arraycolsep=3pt
  7077. \begin{array}{l}
  7078. \gray{\ASTXIntRacket} \\ \hline
  7079. \ASTXIfRacket \\
  7080. \begin{array}{lcl}
  7081. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7082. \end{array}
  7083. \end{array}
  7084. \]
  7085. \fi}
  7086. %
  7087. {\if\edition\pythonEd
  7088. \[
  7089. \begin{array}{lcl}
  7090. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7091. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7092. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7093. \MID \BYTEREG{\itm{bytereg}} \\
  7094. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7095. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7096. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7097. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7098. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7099. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7100. \MID \PUSHQ{\Arg}} \\
  7101. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7102. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7103. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7104. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7105. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7106. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7107. \Block &::= & \Instr^{+} \\
  7108. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7109. \end{array}
  7110. \]
  7111. \fi}
  7112. \end{tcolorbox}
  7113. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-ast}).}
  7114. \label{fig:x86-1}
  7115. \end{figure}
  7116. Next we consider the x86 instructions that are relevant for compiling
  7117. the comparison operations. The \key{cmpq} instruction compares its two
  7118. arguments to determine whether one argument is less than, equal to, or
  7119. greater than the other argument. The \key{cmpq} instruction is unusual
  7120. regarding the order of its arguments and where the result is
  7121. placed. The argument order is backward: if you want to test whether
  7122. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7123. \key{cmpq} is placed in the special EFLAGS register. This register
  7124. cannot be accessed directly, but it can be queried by a number of
  7125. instructions, including the \key{set} instruction. The instruction
  7126. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  7127. depending on whether the contents of the EFLAGS register matches the
  7128. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7129. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7130. The \key{set} instruction has a quirk in that its destination argument
  7131. must be single byte register, such as \code{al} (L for lower bits) or
  7132. \code{ah} (H for higher bits), which are part of the \code{rax}
  7133. register. Thankfully, the \key{movzbq} instruction can be used to
  7134. move from a single byte register to a normal 64-bit register. The
  7135. abstract syntax for the \code{set} instruction differs from the
  7136. concrete syntax in that it separates the instruction name from the
  7137. condition code.
  7138. \python{The x86 instructions for jumping are relevant to the
  7139. compilation of \key{if} expressions.}
  7140. %
  7141. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7142. counter to the address of the instruction after the specified
  7143. label.}
  7144. %
  7145. \racket{The x86 instruction for conditional jump is relevant to the
  7146. compilation of \key{if} expressions.}
  7147. %
  7148. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7149. counter to point to the instruction after \itm{label} depending on
  7150. whether the result in the EFLAGS register matches the condition code
  7151. \itm{cc}, otherwise the jump instruction falls through to the next
  7152. instruction. Like the abstract syntax for \code{set}, the abstract
  7153. syntax for conditional jump separates the instruction name from the
  7154. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7155. corresponds to \code{jle foo}. Because the conditional jump instruction
  7156. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7157. a \key{cmpq} instruction to set the EFLAGS register.
  7158. \section{Shrink the \LangIf{} Language}
  7159. \label{sec:shrink-Lif}
  7160. The \LangIf{} language includes several features that are easily
  7161. expressible with other features. For example, \code{and} and \code{or}
  7162. are expressible using \code{if} as follows.
  7163. \begin{align*}
  7164. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7165. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7166. \end{align*}
  7167. By performing these translations in the front-end of the compiler,
  7168. subsequent passes of the compiler do not need to deal with these features,
  7169. making the passes shorter.
  7170. On the other hand, sometimes translations reduce the efficiency of the
  7171. generated code by increasing the number of instructions. For example,
  7172. expressing subtraction in terms of negation
  7173. \[
  7174. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7175. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7176. \]
  7177. produces code with two x86 instructions (\code{negq} and \code{addq})
  7178. instead of just one (\code{subq}).
  7179. \begin{exercise}\normalfont\normalsize
  7180. %
  7181. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7182. the language by translating them to \code{if} expressions in \LangIf{}.
  7183. %
  7184. Create four test programs that involve these operators.
  7185. %
  7186. {\if\edition\racketEd
  7187. In the \code{run-tests.rkt} script, add the following entry for
  7188. \code{shrink} to the list of passes (it should be the only pass at
  7189. this point).
  7190. \begin{lstlisting}
  7191. (list "shrink" shrink interp_Lif type-check-Lif)
  7192. \end{lstlisting}
  7193. This instructs \code{interp-tests} to run the interpreter
  7194. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7195. output of \code{shrink}.
  7196. \fi}
  7197. %
  7198. Run the script to test your compiler on all the test programs.
  7199. \end{exercise}
  7200. {\if\edition\racketEd
  7201. \section{Uniquify Variables}
  7202. \label{sec:uniquify-Lif}
  7203. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7204. \code{if} expressions.
  7205. \begin{exercise}\normalfont\normalsize
  7206. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7207. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7208. \begin{lstlisting}
  7209. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7210. \end{lstlisting}
  7211. Run the script to test your compiler.
  7212. \end{exercise}
  7213. \fi}
  7214. \section{Remove Complex Operands}
  7215. \label{sec:remove-complex-opera-Lif}
  7216. The output language of \code{remove\_complex\_operands} is
  7217. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  7218. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7219. but the \code{if} expression is not. All three sub-expressions of an
  7220. \code{if} are allowed to be complex expressions but the operands of
  7221. \code{not} and the comparisons must be atomic.
  7222. %
  7223. \python{We add a new language form, the \code{Begin} expression, to aid
  7224. in the translation of \code{if} expressions. When we recursively
  7225. process the two branches of the \code{if}, we generate temporary
  7226. variables and their initializing expressions. However, these
  7227. expressions may contain side effects and should only be executed
  7228. when the condition of the \code{if} is true (for the ``then''
  7229. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7230. a way to initialize the temporary variables within the two branches
  7231. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7232. form execute the statements $ss$ and then returns the result of
  7233. expression $e$.}
  7234. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7235. the new features in \LangIf{}. When recursively processing
  7236. subexpressions, recall that you should invoke \code{rco\_atom} when
  7237. the output needs to be an \Atm{} (as specified in the grammar for
  7238. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7239. \Exp{}. Regarding \code{if}, it is particularly important to
  7240. \textbf{not} replace its condition with a temporary variable because
  7241. that would interfere with the generation of high-quality output in the
  7242. upcoming \code{explicate\_control} pass.
  7243. \newcommand{\LifMonadASTRacket}{
  7244. \begin{array}{rcl}
  7245. \Atm &::=& \BOOL{\itm{bool}}\\
  7246. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7247. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7248. \MID \IF{\Exp}{\Exp}{\Exp}
  7249. \end{array}
  7250. }
  7251. \newcommand{\LifMonadASTPython}{
  7252. \begin{array}{rcl}
  7253. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7254. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7255. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7256. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7257. \Atm &::=& \BOOL{\itm{bool}}\\
  7258. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7259. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7260. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7261. \end{array}
  7262. }
  7263. \begin{figure}[tp]
  7264. \centering
  7265. \begin{tcolorbox}[colback=white]
  7266. {\if\edition\racketEd
  7267. \[
  7268. \begin{array}{l}
  7269. \gray{\LvarMonadASTRacket} \\ \hline
  7270. \LifMonadASTRacket \\
  7271. \begin{array}{rcl}
  7272. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7273. \end{array}
  7274. \end{array}
  7275. \]
  7276. \fi}
  7277. {\if\edition\pythonEd
  7278. \[
  7279. \begin{array}{l}
  7280. \gray{\LvarMonadASTPython} \\ \hline
  7281. \LifMonadASTPython \\
  7282. \begin{array}{rcl}
  7283. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7284. \end{array}
  7285. \end{array}
  7286. \]
  7287. \fi}
  7288. \end{tcolorbox}
  7289. \python{\index{subject}{Begin@\texttt{Begin}}}
  7290. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7291. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  7292. \label{fig:Lif-anf-syntax}
  7293. \end{figure}
  7294. \begin{exercise}\normalfont\normalsize
  7295. %
  7296. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7297. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7298. %
  7299. Create three new \LangIf{} programs that exercise the interesting
  7300. code in this pass.
  7301. %
  7302. {\if\edition\racketEd
  7303. In the \code{run-tests.rkt} script, add the following entry to the
  7304. list of \code{passes} and then run the script to test your compiler.
  7305. \begin{lstlisting}
  7306. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7307. \end{lstlisting}
  7308. \fi}
  7309. \end{exercise}
  7310. \section{Explicate Control}
  7311. \label{sec:explicate-control-Lif}
  7312. \racket{Recall that the purpose of \code{explicate\_control} is to
  7313. make the order of evaluation explicit in the syntax of the program.
  7314. With the addition of \key{if} this gets more interesting.}
  7315. %
  7316. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7317. %
  7318. The main challenge to overcome is that the condition of an \key{if}
  7319. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7320. condition must be a comparison.
  7321. As a motivating example, consider the following program that has an
  7322. \key{if} expression nested in the condition of another \key{if}.%
  7323. \python{\footnote{Programmers rarely write nested \code{if}
  7324. expressions, but it is not uncommon for the condition of an
  7325. \code{if} statement to be a call of a function that also contains an
  7326. \code{if} statement. When such a function is inlined, the result is
  7327. a nested \code{if} that requires the techniques discussed in this
  7328. section.}}
  7329. % cond_test_41.rkt, if_lt_eq.py
  7330. \begin{center}
  7331. \begin{minipage}{0.96\textwidth}
  7332. {\if\edition\racketEd
  7333. \begin{lstlisting}
  7334. (let ([x (read)])
  7335. (let ([y (read)])
  7336. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7337. (+ y 2)
  7338. (+ y 10))))
  7339. \end{lstlisting}
  7340. \fi}
  7341. {\if\edition\pythonEd
  7342. \begin{lstlisting}
  7343. x = input_int()
  7344. y = input_int()
  7345. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7346. \end{lstlisting}
  7347. \fi}
  7348. \end{minipage}
  7349. \end{center}
  7350. %
  7351. The naive way to compile \key{if} and the comparison operations would
  7352. be to handle each of them in isolation, regardless of their context.
  7353. Each comparison would be translated into a \key{cmpq} instruction
  7354. followed by several instructions to move the result from the EFLAGS
  7355. register into a general purpose register or stack location. Each
  7356. \key{if} would be translated into a \key{cmpq} instruction followed by
  7357. a conditional jump. The generated code for the inner \key{if} in the
  7358. above example would be as follows.
  7359. \begin{center}
  7360. \begin{minipage}{0.96\textwidth}
  7361. \begin{lstlisting}
  7362. cmpq $1, x
  7363. setl %al
  7364. movzbq %al, tmp
  7365. cmpq $1, tmp
  7366. je then_branch_1
  7367. jmp else_branch_1
  7368. \end{lstlisting}
  7369. \end{minipage}
  7370. \end{center}
  7371. Notice that the three instructions starting with \code{setl} are
  7372. redundant: the conditional jump could come immediately after the first
  7373. \code{cmpq}.
  7374. Our goal will be to compile \key{if} expressions so that the relevant
  7375. comparison instruction appears directly before the conditional jump.
  7376. For example, we want to generate the following code for the inner
  7377. \code{if}.
  7378. \begin{center}
  7379. \begin{minipage}{0.96\textwidth}
  7380. \begin{lstlisting}
  7381. cmpq $1, x
  7382. jl then_branch_1
  7383. jmp else_branch_1
  7384. \end{lstlisting}
  7385. \end{minipage}
  7386. \end{center}
  7387. One way to achieve this goal is to reorganize the code at the level of
  7388. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7389. the following code.
  7390. \begin{center}
  7391. \begin{minipage}{0.96\textwidth}
  7392. {\if\edition\racketEd
  7393. \begin{lstlisting}
  7394. (let ([x (read)])
  7395. (let ([y (read)])
  7396. (if (< x 1)
  7397. (if (eq? x 0)
  7398. (+ y 2)
  7399. (+ y 10))
  7400. (if (eq? x 2)
  7401. (+ y 2)
  7402. (+ y 10)))))
  7403. \end{lstlisting}
  7404. \fi}
  7405. {\if\edition\pythonEd
  7406. \begin{lstlisting}
  7407. x = input_int()
  7408. y = input_int()
  7409. print(((y + 2) if x == 0 else (y + 10)) \
  7410. if (x < 1) \
  7411. else ((y + 2) if (x == 2) else (y + 10)))
  7412. \end{lstlisting}
  7413. \fi}
  7414. \end{minipage}
  7415. \end{center}
  7416. Unfortunately, this approach duplicates the two branches from the
  7417. outer \code{if} and a compiler must never duplicate code! After all,
  7418. the two branches could be very large expressions.
  7419. How can we apply the above transformation but without duplicating
  7420. code? In other words, how can two different parts of a program refer
  7421. to one piece of code.
  7422. %
  7423. The answer is that we must move away from abstract syntax \emph{trees}
  7424. and instead use \emph{graphs}.
  7425. %
  7426. At the level of x86 assembly this is straightforward because we can
  7427. label the code for each branch and insert jumps in all the places that
  7428. need to execute the branch. In this way, jump instructions are edges
  7429. in the graph and the basic blocks are the nodes.
  7430. %
  7431. Likewise, our language \LangCIf{} provides the ability to label a
  7432. sequence of statements and to jump to a label via \code{goto}.
  7433. As a preview of what \code{explicate\_control} will do,
  7434. figure~\ref{fig:explicate-control-s1-38} shows the output of
  7435. \code{explicate\_control} on the above example. Note how the condition
  7436. of every \code{if} is a comparison operation and that we have not
  7437. duplicated any code, but instead used labels and \code{goto} to enable
  7438. sharing of code.
  7439. \begin{figure}[tbp]
  7440. \begin{tcolorbox}[colback=white]
  7441. {\if\edition\racketEd
  7442. \begin{tabular}{lll}
  7443. \begin{minipage}{0.4\textwidth}
  7444. % cond_test_41.rkt
  7445. \begin{lstlisting}
  7446. (let ([x (read)])
  7447. (let ([y (read)])
  7448. (if (if (< x 1)
  7449. (eq? x 0)
  7450. (eq? x 2))
  7451. (+ y 2)
  7452. (+ y 10))))
  7453. \end{lstlisting}
  7454. \end{minipage}
  7455. &
  7456. $\Rightarrow$
  7457. &
  7458. \begin{minipage}{0.55\textwidth}
  7459. \begin{lstlisting}
  7460. start:
  7461. x = (read);
  7462. y = (read);
  7463. if (< x 1)
  7464. goto block_4;
  7465. else
  7466. goto block_5;
  7467. block_4:
  7468. if (eq? x 0)
  7469. goto block_2;
  7470. else
  7471. goto block_3;
  7472. block_5:
  7473. if (eq? x 2)
  7474. goto block_2;
  7475. else
  7476. goto block_3;
  7477. block_2:
  7478. return (+ y 2);
  7479. block_3:
  7480. return (+ y 10);
  7481. \end{lstlisting}
  7482. \end{minipage}
  7483. \end{tabular}
  7484. \fi}
  7485. {\if\edition\pythonEd
  7486. \begin{tabular}{lll}
  7487. \begin{minipage}{0.4\textwidth}
  7488. % cond_test_41.rkt
  7489. \begin{lstlisting}
  7490. x = input_int()
  7491. y = input_int()
  7492. print(y + 2 \
  7493. if (x == 0 \
  7494. if x < 1 \
  7495. else x == 2) \
  7496. else y + 10)
  7497. \end{lstlisting}
  7498. \end{minipage}
  7499. &
  7500. $\Rightarrow$
  7501. &
  7502. \begin{minipage}{0.55\textwidth}
  7503. \begin{lstlisting}
  7504. start:
  7505. x = input_int()
  7506. y = input_int()
  7507. if x < 1:
  7508. goto block_8
  7509. else:
  7510. goto block_9
  7511. block_8:
  7512. if x == 0:
  7513. goto block_4
  7514. else:
  7515. goto block_5
  7516. block_9:
  7517. if x == 2:
  7518. goto block_6
  7519. else:
  7520. goto block_7
  7521. block_4:
  7522. goto block_2
  7523. block_5:
  7524. goto block_3
  7525. block_6:
  7526. goto block_2
  7527. block_7:
  7528. goto block_3
  7529. block_2:
  7530. tmp_0 = y + 2
  7531. goto block_1
  7532. block_3:
  7533. tmp_0 = y + 10
  7534. goto block_1
  7535. block_1:
  7536. print(tmp_0)
  7537. return 0
  7538. \end{lstlisting}
  7539. \end{minipage}
  7540. \end{tabular}
  7541. \fi}
  7542. \end{tcolorbox}
  7543. \caption{Translation from \LangIf{} to \LangCIf{}
  7544. via the \code{explicate\_control}.}
  7545. \label{fig:explicate-control-s1-38}
  7546. \end{figure}
  7547. {\if\edition\racketEd
  7548. %
  7549. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  7550. \code{explicate\_control} for \LangVar{} using two recursive
  7551. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7552. former function translates expressions in tail position whereas the
  7553. later function translates expressions on the right-hand side of a
  7554. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  7555. have a new kind of position to deal with: the predicate position of
  7556. the \key{if}. We need another function, \code{explicate\_pred}, that
  7557. decides how to compile an \key{if} by analyzing its condition. So
  7558. \code{explicate\_pred} takes an \LangIf{} expression and two
  7559. \LangCIf{} tails for the then-branch and else-branch and outputs a
  7560. tail. In the following paragraphs we discuss specific cases in the
  7561. \code{explicate\_tail}, \code{explicate\_assign}, and
  7562. \code{explicate\_pred} functions.
  7563. %
  7564. \fi}
  7565. %
  7566. {\if\edition\pythonEd
  7567. %
  7568. We recommend implementing \code{explicate\_control} using the
  7569. following four auxiliary functions.
  7570. \begin{description}
  7571. \item[\code{explicate\_effect}] generates code for expressions as
  7572. statements, so their result is ignored and only their side effects
  7573. matter.
  7574. \item[\code{explicate\_assign}] generates code for expressions
  7575. on the right-hand side of an assignment.
  7576. \item[\code{explicate\_pred}] generates code for an \code{if}
  7577. expression or statement by analyzing the condition expression.
  7578. \item[\code{explicate\_stmt}] generates code for statements.
  7579. \end{description}
  7580. These four functions should build the dictionary of basic blocks. The
  7581. following auxiliary function can be used to create a new basic block
  7582. from a list of statements. It returns a \code{goto} statement that
  7583. jumps to the new basic block.
  7584. \begin{center}
  7585. \begin{minipage}{\textwidth}
  7586. \begin{lstlisting}
  7587. def create_block(stmts, basic_blocks):
  7588. label = label_name(generate_name('block'))
  7589. basic_blocks[label] = stmts
  7590. return Goto(label)
  7591. \end{lstlisting}
  7592. \end{minipage}
  7593. \end{center}
  7594. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7595. \code{explicate\_control} pass.
  7596. The \code{explicate\_effect} function has three parameters: 1) the
  7597. expression to be compiled, 2) the already-compiled code for this
  7598. expression's \emph{continuation}, that is, the list of statements that
  7599. should execute after this expression, and 3) the dictionary of
  7600. generated basic blocks. The \code{explicate\_effect} function returns
  7601. a list of \LangCIf{} statements and it may add to the dictionary of
  7602. basic blocks.
  7603. %
  7604. Let's consider a few of the cases for the expression to be compiled.
  7605. If the expression to be compiled is a constant, then it can be
  7606. discarded because it has no side effects. If it's a \CREAD{}, then it
  7607. has a side-effect and should be preserved. So the expression should be
  7608. translated into a statement using the \code{Expr} AST class. If the
  7609. expression to be compiled is an \code{if} expression, we translate the
  7610. two branches using \code{explicate\_effect} and then translate the
  7611. condition expression using \code{explicate\_pred}, which generates
  7612. code for the entire \code{if}.
  7613. The \code{explicate\_assign} function has four parameters: 1) the
  7614. right-hand side of the assignment, 2) the left-hand side of the
  7615. assignment (the variable), 3) the continuation, and 4) the dictionary
  7616. of basic blocks. The \code{explicate\_assign} function returns a list
  7617. of \LangCIf{} statements and it may add to the dictionary of basic
  7618. blocks.
  7619. When the right-hand side is an \code{if} expression, there is some
  7620. work to do. In particular, the two branches should be translated using
  7621. \code{explicate\_assign} and the condition expression should be
  7622. translated using \code{explicate\_pred}. Otherwise we can simply
  7623. generate an assignment statement, with the given left and right-hand
  7624. sides, concatenated with its continuation.
  7625. \begin{figure}[tbp]
  7626. \begin{tcolorbox}[colback=white]
  7627. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7628. def explicate_effect(e, cont, basic_blocks):
  7629. match e:
  7630. case IfExp(test, body, orelse):
  7631. ...
  7632. case Call(func, args):
  7633. ...
  7634. case Begin(body, result):
  7635. ...
  7636. case _:
  7637. ...
  7638. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7639. match rhs:
  7640. case IfExp(test, body, orelse):
  7641. ...
  7642. case Begin(body, result):
  7643. ...
  7644. case _:
  7645. return [Assign([lhs], rhs)] + cont
  7646. def explicate_pred(cnd, thn, els, basic_blocks):
  7647. match cnd:
  7648. case Compare(left, [op], [right]):
  7649. goto_thn = create_block(thn, basic_blocks)
  7650. goto_els = create_block(els, basic_blocks)
  7651. return [If(cnd, [goto_thn], [goto_els])]
  7652. case Constant(True):
  7653. return thn;
  7654. case Constant(False):
  7655. return els;
  7656. case UnaryOp(Not(), operand):
  7657. ...
  7658. case IfExp(test, body, orelse):
  7659. ...
  7660. case Begin(body, result):
  7661. ...
  7662. case _:
  7663. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7664. [create_block(els, basic_blocks)],
  7665. [create_block(thn, basic_blocks)])]
  7666. def explicate_stmt(s, cont, basic_blocks):
  7667. match s:
  7668. case Assign([lhs], rhs):
  7669. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7670. case Expr(value):
  7671. return explicate_effect(value, cont, basic_blocks)
  7672. case If(test, body, orelse):
  7673. ...
  7674. def explicate_control(p):
  7675. match p:
  7676. case Module(body):
  7677. new_body = [Return(Constant(0))]
  7678. basic_blocks = {}
  7679. for s in reversed(body):
  7680. new_body = explicate_stmt(s, new_body, basic_blocks)
  7681. basic_blocks[label_name('start')] = new_body
  7682. return CProgram(basic_blocks)
  7683. \end{lstlisting}
  7684. \end{tcolorbox}
  7685. \caption{Skeleton for the \code{explicate\_control} pass.}
  7686. \label{fig:explicate-control-Lif}
  7687. \end{figure}
  7688. \fi}
  7689. {\if\edition\racketEd
  7690. \subsection{Explicate Tail and Assign}
  7691. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7692. additional cases for Boolean constants and \key{if}. The cases for
  7693. \code{if} should recursively compile the two branches using either
  7694. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7695. cases should then invoke \code{explicate\_pred} on the condition
  7696. expression, passing in the generated code for the two branches. For
  7697. example, consider the following program with an \code{if} in tail
  7698. position.
  7699. % cond_test_6.rkt
  7700. \begin{lstlisting}
  7701. (let ([x (read)])
  7702. (if (eq? x 0) 42 777))
  7703. \end{lstlisting}
  7704. The two branches are recursively compiled to return statements. We
  7705. then delegate to \code{explicate\_pred}, passing the condition
  7706. \code{(eq? x 0)} and the two return statements. We return to this
  7707. example shortly when we discuss \code{explicate\_pred}.
  7708. Next let us consider a program with an \code{if} on the right-hand
  7709. side of a \code{let}.
  7710. \begin{lstlisting}
  7711. (let ([y (read)])
  7712. (let ([x (if (eq? y 0) 40 777)])
  7713. (+ x 2)))
  7714. \end{lstlisting}
  7715. Note that the body of the inner \code{let} will have already been
  7716. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7717. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7718. to recursively process both branches of the \code{if}, and we do not
  7719. want to duplicate code, so we generate the following block using an
  7720. auxiliary function named \code{create\_block} that we discuss below.
  7721. \begin{lstlisting}
  7722. block_6:
  7723. return (+ x 2)
  7724. \end{lstlisting}
  7725. We then use \code{goto block\_6;} as the \code{cont} argument for
  7726. compiling the branches. So the two branches compile to
  7727. \begin{center}
  7728. \begin{minipage}{0.2\textwidth}
  7729. \begin{lstlisting}
  7730. x = 40;
  7731. goto block_6;
  7732. \end{lstlisting}
  7733. \end{minipage}
  7734. \hspace{0.5in} and \hspace{0.5in}
  7735. \begin{minipage}{0.2\textwidth}
  7736. \begin{lstlisting}
  7737. x = 777;
  7738. goto block_6;
  7739. \end{lstlisting}
  7740. \end{minipage}
  7741. \end{center}
  7742. Finally, we delegate to \code{explicate\_pred}, passing the condition
  7743. \code{(eq? y 0)} and the above code for the branches.
  7744. \subsection{Create Block}
  7745. We recommend implementing the \code{create\_block} auxiliary function
  7746. as follows, using a global variable \code{basic-blocks} to store a
  7747. dictionary that maps labels to $\Tail$ expressions. The main idea is
  7748. that \code{create\_block} generates a new label and then associates
  7749. the given \code{tail} with the new label in the \code{basic-blocks}
  7750. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  7751. new label. However, if the given \code{tail} is already a \code{Goto},
  7752. then there is no need to generate a new label and entry in
  7753. \code{basic-blocks}; we can simply return that \code{Goto}.
  7754. %
  7755. \begin{lstlisting}
  7756. (define (create_block tail)
  7757. (match tail
  7758. [(Goto label) (Goto label)]
  7759. [else
  7760. (let ([label (gensym 'block)])
  7761. (set! basic-blocks (cons (cons label tail) basic-blocks))
  7762. (Goto label))]))
  7763. \end{lstlisting}
  7764. \fi}
  7765. {\if\edition\racketEd
  7766. \subsection{Explicate Predicate}
  7767. \begin{figure}[tbp]
  7768. \begin{tcolorbox}[colback=white]
  7769. \begin{lstlisting}
  7770. (define (explicate_pred cnd thn els)
  7771. (match cnd
  7772. [(Var x) ___]
  7773. [(Let x rhs body) ___]
  7774. [(Prim 'not (list e)) ___]
  7775. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7776. (IfStmt (Prim op es) (create_block thn)
  7777. (create_block els))]
  7778. [(Bool b) (if b thn els)]
  7779. [(If cnd^ thn^ els^) ___]
  7780. [else (error "explicate_pred unhandled case" cnd)]))
  7781. \end{lstlisting}
  7782. \end{tcolorbox}
  7783. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7784. \label{fig:explicate-pred}
  7785. \end{figure}
  7786. \fi}
  7787. \racket{The skeleton for the \code{explicate\_pred} function is given
  7788. in figure~\ref{fig:explicate-pred}. It takes three parameters:
  7789. 1) \code{cnd}, the condition expression of the \code{if},
  7790. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7791. and 3) \code{els}, the code generated by
  7792. explicate for the ``else'' branch. The \code{explicate\_pred}
  7793. function should match on \code{cnd} with a case for
  7794. every kind of expression that can have type \BOOLTY{}.}
  7795. %
  7796. \python{The \code{explicate\_pred} function has four parameters: 1)
  7797. the condition expression, 2) the generated statements for the
  7798. ``then'' branch, 3) the generated statements for the ``else''
  7799. branch, and 4) the dictionary of basic blocks. The
  7800. \code{explicate\_pred} function returns a list of \LangCIf{}
  7801. statements and it may add to the dictionary of basic blocks.}
  7802. Consider the case for comparison operators. We translate the
  7803. comparison to an \code{if} statement whose branches are \code{goto}
  7804. statements created by applying \code{create\_block} to the code
  7805. generated for the \code{thn} and \code{els} branches. Let us
  7806. illustrate this translation by returning to the program with an
  7807. \code{if} expression in tail position, shown again below. We invoke
  7808. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  7809. \python{\code{x == 0}}.
  7810. %
  7811. {\if\edition\racketEd
  7812. \begin{lstlisting}
  7813. (let ([x (read)])
  7814. (if (eq? x 0) 42 777))
  7815. \end{lstlisting}
  7816. \fi}
  7817. %
  7818. {\if\edition\pythonEd
  7819. \begin{lstlisting}
  7820. x = input_int()
  7821. 42 if x == 0 else 777
  7822. \end{lstlisting}
  7823. \fi}
  7824. %
  7825. \noindent The two branches \code{42} and \code{777} were already
  7826. compiled to \code{return} statements, from which we now create the
  7827. following blocks.
  7828. %
  7829. \begin{center}
  7830. \begin{minipage}{\textwidth}
  7831. \begin{lstlisting}
  7832. block_1:
  7833. return 42;
  7834. block_2:
  7835. return 777;
  7836. \end{lstlisting}
  7837. \end{minipage}
  7838. \end{center}
  7839. %
  7840. After that, \code{explicate\_pred} compiles the comparison
  7841. \racket{\code{(eq? x 0)}}
  7842. \python{\code{x == 0}}
  7843. to the following \code{if} statement.
  7844. %
  7845. {\if\edition\racketEd
  7846. \begin{center}
  7847. \begin{minipage}{\textwidth}
  7848. \begin{lstlisting}
  7849. if (eq? x 0)
  7850. goto block_1;
  7851. else
  7852. goto block_2;
  7853. \end{lstlisting}
  7854. \end{minipage}
  7855. \end{center}
  7856. \fi}
  7857. {\if\edition\pythonEd
  7858. \begin{center}
  7859. \begin{minipage}{\textwidth}
  7860. \begin{lstlisting}
  7861. if x == 0:
  7862. goto block_1;
  7863. else
  7864. goto block_2;
  7865. \end{lstlisting}
  7866. \end{minipage}
  7867. \end{center}
  7868. \fi}
  7869. Next consider the case for Boolean constants. We perform a kind of
  7870. partial evaluation\index{subject}{partial evaluation} and output
  7871. either the \code{thn} or \code{els} branch depending on whether the
  7872. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7873. following program.
  7874. {\if\edition\racketEd
  7875. \begin{lstlisting}
  7876. (if #t 42 777)
  7877. \end{lstlisting}
  7878. \fi}
  7879. {\if\edition\pythonEd
  7880. \begin{lstlisting}
  7881. 42 if True else 777
  7882. \end{lstlisting}
  7883. \fi}
  7884. %
  7885. \noindent Again, the two branches \code{42} and \code{777} were
  7886. compiled to \code{return} statements, so \code{explicate\_pred}
  7887. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  7888. code for the ``then'' branch.
  7889. \begin{lstlisting}
  7890. return 42;
  7891. \end{lstlisting}
  7892. This case demonstrates that we sometimes discard the \code{thn} or
  7893. \code{els} blocks that are input to \code{explicate\_pred}.
  7894. The case for \key{if} expressions in \code{explicate\_pred} is
  7895. particularly illuminating because it deals with the challenges we
  7896. discussed above regarding nested \key{if} expressions
  7897. (figure~\ref{fig:explicate-control-s1-38}). The
  7898. \racket{\lstinline{thn^}}\python{\code{body}} and
  7899. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7900. \key{if} inherit their context from the current one, that is,
  7901. predicate context. So you should recursively apply
  7902. \code{explicate\_pred} to the
  7903. \racket{\lstinline{thn^}}\python{\code{body}} and
  7904. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7905. those recursive calls, pass \code{thn} and \code{els} as the extra
  7906. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7907. inside each recursive call. As discussed above, to avoid duplicating
  7908. code, we need to add them to the dictionary of basic blocks so that we
  7909. can instead refer to them by name and execute them with a \key{goto}.
  7910. {\if\edition\pythonEd
  7911. %
  7912. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7913. three parameters: 1) the statement to be compiled, 2) the code for its
  7914. continuation, and 3) the dictionary of basic blocks. The
  7915. \code{explicate\_stmt} returns a list of statements and it may add to
  7916. the dictionary of basic blocks. The cases for assignment and an
  7917. expression-statement are given in full in the skeleton code: they
  7918. simply dispatch to \code{explicate\_assign} and
  7919. \code{explicate\_effect}, respectively. The case for \code{if}
  7920. statements is not given, and is similar to the case for \code{if}
  7921. expressions.
  7922. The \code{explicate\_control} function itself is given in
  7923. figure~\ref{fig:explicate-control-Lif}. It applies
  7924. \code{explicate\_stmt} to each statement in the program, from back to
  7925. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7926. used as the continuation parameter in the next call to
  7927. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7928. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7929. the dictionary of basic blocks, labeling it as the ``start'' block.
  7930. %
  7931. \fi}
  7932. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7933. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7934. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7935. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7936. %% results from the two recursive calls. We complete the case for
  7937. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7938. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7939. %% the result $B_5$.
  7940. %% \[
  7941. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7942. %% \quad\Rightarrow\quad
  7943. %% B_5
  7944. %% \]
  7945. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7946. %% inherit the current context, so they are in tail position. Thus, the
  7947. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7948. %% \code{explicate\_tail}.
  7949. %% %
  7950. %% We need to pass $B_0$ as the accumulator argument for both of these
  7951. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7952. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7953. %% to the control-flow graph and obtain a promised goto $G_0$.
  7954. %% %
  7955. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7956. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7957. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7958. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7959. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7960. %% \[
  7961. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7962. %% \]
  7963. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7964. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7965. %% should not be confused with the labels for the blocks that appear in
  7966. %% the generated code. We initially construct unlabeled blocks; we only
  7967. %% attach labels to blocks when we add them to the control-flow graph, as
  7968. %% we see in the next case.
  7969. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7970. %% function. The context of the \key{if} is an assignment to some
  7971. %% variable $x$ and then the control continues to some promised block
  7972. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7973. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7974. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7975. %% branches of the \key{if} inherit the current context, so they are in
  7976. %% assignment positions. Let $B_2$ be the result of applying
  7977. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7978. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7979. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7980. %% the result of applying \code{explicate\_pred} to the predicate
  7981. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7982. %% translates to the promise $B_4$.
  7983. %% \[
  7984. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7985. %% \]
  7986. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7987. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7988. \code{remove\_complex\_operands} pass and then the
  7989. \code{explicate\_control} pass on the example program. We walk through
  7990. the output program.
  7991. %
  7992. Following the order of evaluation in the output of
  7993. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7994. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7995. in the predicate of the inner \key{if}. In the output of
  7996. \code{explicate\_control}, in the
  7997. block labeled \code{start}, are two assignment statements followed by a
  7998. \code{if} statement that branches to \code{block\_4} or
  7999. \code{block\_5}. The blocks associated with those labels contain the
  8000. translations of the code
  8001. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8002. and
  8003. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8004. respectively. In particular, we start \code{block\_4} with the
  8005. comparison
  8006. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8007. and then branch to \code{block\_2} or \code{block\_3},
  8008. which correspond to the two branches of the outer \key{if}, i.e.,
  8009. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8010. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8011. %
  8012. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8013. %
  8014. \python{The \code{block\_1} corresponds to the \code{print} statement
  8015. at the end of the program.}
  8016. {\if\edition\racketEd
  8017. \subsection{Interactions between Explicate and Shrink}
  8018. The way in which the \code{shrink} pass transforms logical operations
  8019. such as \code{and} and \code{or} can impact the quality of code
  8020. generated by \code{explicate\_control}. For example, consider the
  8021. following program.
  8022. % cond_test_21.rkt, and_eq_input.py
  8023. \begin{lstlisting}
  8024. (if (and (eq? (read) 0) (eq? (read) 1))
  8025. 0
  8026. 42)
  8027. \end{lstlisting}
  8028. The \code{and} operation should transform into something that the
  8029. \code{explicate\_pred} function can still analyze and descend through to
  8030. reach the underlying \code{eq?} conditions. Ideally, your
  8031. \code{explicate\_control} pass should generate code similar to the
  8032. following for the above program.
  8033. \begin{center}
  8034. \begin{lstlisting}
  8035. start:
  8036. tmp1 = (read);
  8037. if (eq? tmp1 0) goto block40;
  8038. else goto block39;
  8039. block40:
  8040. tmp2 = (read);
  8041. if (eq? tmp2 1) goto block38;
  8042. else goto block39;
  8043. block38:
  8044. return 0;
  8045. block39:
  8046. return 42;
  8047. \end{lstlisting}
  8048. \end{center}
  8049. \fi}
  8050. \begin{exercise}\normalfont\normalsize
  8051. \racket{
  8052. Implement the pass \code{explicate\_control} by adding the cases for
  8053. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8054. \code{explicate\_assign} functions. Implement the auxiliary function
  8055. \code{explicate\_pred} for predicate contexts.}
  8056. \python{Implement \code{explicate\_control} pass with its
  8057. four auxiliary functions.}
  8058. %
  8059. Create test cases that exercise all of the new cases in the code for
  8060. this pass.
  8061. %
  8062. {\if\edition\racketEd
  8063. Add the following entry to the list of \code{passes} in
  8064. \code{run-tests.rkt} and then run this script to test your compiler.
  8065. \begin{lstlisting}
  8066. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8067. \end{lstlisting}
  8068. \fi}
  8069. \end{exercise}
  8070. \clearpage
  8071. \section{Select Instructions}
  8072. \label{sec:select-Lif}
  8073. \index{subject}{instruction selection}
  8074. The \code{select\_instructions} pass translates \LangCIf{} to
  8075. \LangXIfVar{}.
  8076. %
  8077. \racket{Recall that we implement this pass using three auxiliary
  8078. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8079. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8080. %
  8081. \racket{For $\Atm$, we have new cases for the Booleans.}
  8082. %
  8083. \python{We begin with the Boolean constants.}
  8084. We take the usual approach of encoding them as integers.
  8085. \[
  8086. \TRUE{} \quad\Rightarrow\quad \key{1}
  8087. \qquad\qquad
  8088. \FALSE{} \quad\Rightarrow\quad \key{0}
  8089. \]
  8090. For translating statements, we discuss some of the cases. The
  8091. \code{not} operation can be implemented in terms of \code{xorq} as we
  8092. discussed at the beginning of this section. Given an assignment, if
  8093. the left-hand side variable is the same as the argument of \code{not},
  8094. then just the \code{xorq} instruction suffices.
  8095. \[
  8096. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8097. \quad\Rightarrow\quad
  8098. \key{xorq}~\key{\$}1\key{,}~\Var
  8099. \]
  8100. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8101. semantics of x86. In the following translation, let $\Arg$ be the
  8102. result of translating $\Atm$ to x86.
  8103. \[
  8104. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8105. \quad\Rightarrow\quad
  8106. \begin{array}{l}
  8107. \key{movq}~\Arg\key{,}~\Var\\
  8108. \key{xorq}~\key{\$}1\key{,}~\Var
  8109. \end{array}
  8110. \]
  8111. Next consider the cases for equality comparisons. Translating this
  8112. operation to x86 is slightly involved due to the unusual nature of the
  8113. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8114. We recommend translating an assignment with an equality on the
  8115. right-hand side into a sequence of three instructions. \\
  8116. \begin{tabular}{lll}
  8117. \begin{minipage}{0.4\textwidth}
  8118. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8119. \end{minipage}
  8120. &
  8121. $\Rightarrow$
  8122. &
  8123. \begin{minipage}{0.4\textwidth}
  8124. \begin{lstlisting}
  8125. cmpq |$\Arg_2$|, |$\Arg_1$|
  8126. sete %al
  8127. movzbq %al, |$\Var$|
  8128. \end{lstlisting}
  8129. \end{minipage}
  8130. \end{tabular} \\
  8131. The translations for the other comparison operators are similar to the
  8132. above but use different condition codes for the \code{set} instruction.
  8133. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  8134. \key{goto} and \key{if} statements. Both are straightforward to
  8135. translate to x86.}
  8136. %
  8137. A \key{goto} statement becomes a jump instruction.
  8138. \[
  8139. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8140. \]
  8141. %
  8142. An \key{if} statement becomes a compare instruction followed by a
  8143. conditional jump (for the ``then'' branch) and the fall-through is to
  8144. a regular jump (for the ``else'' branch).\\
  8145. \begin{tabular}{lll}
  8146. \begin{minipage}{0.4\textwidth}
  8147. \begin{lstlisting}
  8148. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8149. goto |$\ell_1$||$\racket{\key{;}}$|
  8150. else|$\python{\key{:}}$|
  8151. goto |$\ell_2$||$\racket{\key{;}}$|
  8152. \end{lstlisting}
  8153. \end{minipage}
  8154. &
  8155. $\Rightarrow$
  8156. &
  8157. \begin{minipage}{0.4\textwidth}
  8158. \begin{lstlisting}
  8159. cmpq |$\Arg_2$|, |$\Arg_1$|
  8160. je |$\ell_1$|
  8161. jmp |$\ell_2$|
  8162. \end{lstlisting}
  8163. \end{minipage}
  8164. \end{tabular} \\
  8165. Again, the translations for the other comparison operators are similar to the
  8166. above but use different condition codes for the conditional jump instruction.
  8167. \python{Regarding the \key{return} statement, we recommend treating it
  8168. as an assignment to the \key{rax} register followed by a jump to the
  8169. conclusion of the \code{main} function.}
  8170. \begin{exercise}\normalfont\normalsize
  8171. Expand your \code{select\_instructions} pass to handle the new
  8172. features of the \LangCIf{} language.
  8173. %
  8174. {\if\edition\racketEd
  8175. Add the following entry to the list of \code{passes} in
  8176. \code{run-tests.rkt}
  8177. \begin{lstlisting}
  8178. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8179. \end{lstlisting}
  8180. \fi}
  8181. %
  8182. Run the script to test your compiler on all the test programs.
  8183. \end{exercise}
  8184. \section{Register Allocation}
  8185. \label{sec:register-allocation-Lif}
  8186. \index{subject}{register allocation}
  8187. The changes required for compiling \LangIf{} affect liveness analysis,
  8188. building the interference graph, and assigning homes, but the graph
  8189. coloring algorithm itself does not change.
  8190. \subsection{Liveness Analysis}
  8191. \label{sec:liveness-analysis-Lif}
  8192. \index{subject}{liveness analysis}
  8193. Recall that for \LangVar{} we implemented liveness analysis for a
  8194. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  8195. the addition of \key{if} expressions to \LangIf{},
  8196. \code{explicate\_control} produces many basic blocks.
  8197. %% We recommend that you create a new auxiliary function named
  8198. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8199. %% control-flow graph.
  8200. The first question is: in what order should we process the basic blocks?
  8201. Recall that to perform liveness analysis on a basic block we need to
  8202. know the live-after set for the last instruction in the block. If a
  8203. basic block has no successors (i.e. contains no jumps to other
  8204. blocks), then it has an empty live-after set and we can immediately
  8205. apply liveness analysis to it. If a basic block has some successors,
  8206. then we need to complete liveness analysis on those blocks
  8207. first. These ordering constraints are the reverse of a
  8208. \emph{topological order}\index{subject}{topological order} on a graph
  8209. representation of the program. In particular, the \emph{control flow
  8210. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8211. of a program has a node for each basic block and an edge for each jump
  8212. from one block to another. It is straightforward to generate a CFG
  8213. from the dictionary of basic blocks. One then transposes the CFG and
  8214. applies the topological sort algorithm.
  8215. %
  8216. %
  8217. \racket{We recommend using the \code{tsort} and \code{transpose}
  8218. functions of the Racket \code{graph} package to accomplish this.}
  8219. %
  8220. \python{We provide implementations of \code{topological\_sort} and
  8221. \code{transpose} in the file \code{graph.py} of the support code.}
  8222. %
  8223. As an aside, a topological ordering is only guaranteed to exist if the
  8224. graph does not contain any cycles. This is the case for the
  8225. control-flow graphs that we generate from \LangIf{} programs.
  8226. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8227. and learn how to handle cycles in the control-flow graph.
  8228. \racket{You'll need to construct a directed graph to represent the
  8229. control-flow graph. Do not use the \code{directed-graph} of the
  8230. \code{graph} package because that only allows at most one edge
  8231. between each pair of vertices, but a control-flow graph may have
  8232. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8233. file in the support code implements a graph representation that
  8234. allows multiple edges between a pair of vertices.}
  8235. {\if\edition\racketEd
  8236. The next question is how to analyze jump instructions. Recall that in
  8237. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8238. \code{label->live} that maps each label to the set of live locations
  8239. at the beginning of its block. We use \code{label->live} to determine
  8240. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8241. that we have many basic blocks, \code{label->live} needs to be updated
  8242. as we process the blocks. In particular, after performing liveness
  8243. analysis on a block, we take the live-before set of its first
  8244. instruction and associate that with the block's label in the
  8245. \code{label->live} alist.
  8246. \fi}
  8247. %
  8248. {\if\edition\pythonEd
  8249. %
  8250. The next question is how to analyze jump instructions. The locations
  8251. that are live before a \code{jmp} should be the locations in
  8252. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  8253. maintaining a dictionary named \code{live\_before\_block} that maps each
  8254. label to the $L_{\mathsf{before}}$ for the first instruction in its
  8255. block. After performing liveness analysis on each block, we take the
  8256. live-before set of its first instruction and associate that with the
  8257. block's label in the \code{live\_before\_block} dictionary.
  8258. %
  8259. \fi}
  8260. In \LangXIfVar{} we also have the conditional jump
  8261. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8262. this instruction is particularly interesting because, during
  8263. compilation, we do not know which way a conditional jump will go. So
  8264. we do not know whether to use the live-before set for the block
  8265. associated with the $\itm{label}$ or the live-before set for the
  8266. following instruction. However, there is no harm to the correctness
  8267. of the generated code if we classify more locations as live than the
  8268. ones that are truly live during one particular execution of the
  8269. instruction. Thus, we can take the union of the live-before sets from
  8270. the following instruction and from the mapping for $\itm{label}$ in
  8271. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8272. The auxiliary functions for computing the variables in an
  8273. instruction's argument and for computing the variables read-from ($R$)
  8274. or written-to ($W$) by an instruction need to be updated to handle the
  8275. new kinds of arguments and instructions in \LangXIfVar{}.
  8276. \begin{exercise}\normalfont\normalsize
  8277. {\if\edition\racketEd
  8278. %
  8279. Update the \code{uncover\_live} pass to apply liveness analysis to
  8280. every basic block in the program.
  8281. %
  8282. Add the following entry to the list of \code{passes} in the
  8283. \code{run-tests.rkt} script.
  8284. \begin{lstlisting}
  8285. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8286. \end{lstlisting}
  8287. \fi}
  8288. {\if\edition\pythonEd
  8289. %
  8290. Update the \code{uncover\_live} function to perform liveness analysis,
  8291. in reverse topological order, on all of the basic blocks in the
  8292. program.
  8293. %
  8294. \fi}
  8295. % Check that the live-after sets that you generate for
  8296. % example X matches the following... -Jeremy
  8297. \end{exercise}
  8298. \subsection{Build the Interference Graph}
  8299. \label{sec:build-interference-Lif}
  8300. Many of the new instructions in \LangXIfVar{} can be handled in the
  8301. same way as the instructions in \LangXVar{}.
  8302. % Thus, if your code was
  8303. % already quite general, it will not need to be changed to handle the
  8304. % new instructions. If your code is not general enough, we recommend that
  8305. % you change your code to be more general. For example, you can factor
  8306. % out the computing of the the read and write sets for each kind of
  8307. % instruction into auxiliary functions.
  8308. %
  8309. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8310. similar to the \key{movq} instruction. See rule number 1 in
  8311. section~\ref{sec:build-interference}.
  8312. \begin{exercise}\normalfont\normalsize
  8313. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8314. {\if\edition\racketEd
  8315. Add the following entries to the list of \code{passes} in the
  8316. \code{run-tests.rkt} script.
  8317. \begin{lstlisting}
  8318. (list "build_interference" build_interference interp-pseudo-x86-1)
  8319. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8320. \end{lstlisting}
  8321. \fi}
  8322. % Check that the interference graph that you generate for
  8323. % example X matches the following graph G... -Jeremy
  8324. \end{exercise}
  8325. \section{Patch Instructions}
  8326. The new instructions \key{cmpq} and \key{movzbq} have some special
  8327. restrictions that need to be handled in the \code{patch\_instructions}
  8328. pass.
  8329. %
  8330. The second argument of the \key{cmpq} instruction must not be an
  8331. immediate value (such as an integer). So if you are comparing two
  8332. immediates, we recommend inserting a \key{movq} instruction to put the
  8333. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8334. one memory reference.
  8335. %
  8336. The second argument of the \key{movzbq} must be a register.
  8337. \begin{exercise}\normalfont\normalsize
  8338. %
  8339. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8340. %
  8341. {\if\edition\racketEd
  8342. Add the following entry to the list of \code{passes} in
  8343. \code{run-tests.rkt} and then run this script to test your compiler.
  8344. \begin{lstlisting}
  8345. (list "patch_instructions" patch_instructions interp-x86-1)
  8346. \end{lstlisting}
  8347. \fi}
  8348. \end{exercise}
  8349. {\if\edition\pythonEd
  8350. \section{Prelude and Conclusion}
  8351. \label{sec:prelude-conclusion-cond}
  8352. The generation of the \code{main} function with its prelude and
  8353. conclusion must change to accommodate how the program now consists of
  8354. one or more basic blocks. After the prelude in \code{main}, jump to
  8355. the \code{start} block. Place the conclusion in a basic block labeled
  8356. with \code{conclusion}.
  8357. \fi}
  8358. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8359. \LangIf{} translated to x86, showing the results of
  8360. \code{explicate\_control}, \code{select\_instructions}, and the final
  8361. x86 assembly.
  8362. \begin{figure}[tbp]
  8363. \begin{tcolorbox}[colback=white]
  8364. {\if\edition\racketEd
  8365. \begin{tabular}{lll}
  8366. \begin{minipage}{0.4\textwidth}
  8367. % cond_test_20.rkt, eq_input.py
  8368. \begin{lstlisting}
  8369. (if (eq? (read) 1) 42 0)
  8370. \end{lstlisting}
  8371. $\Downarrow$
  8372. \begin{lstlisting}
  8373. start:
  8374. tmp7951 = (read);
  8375. if (eq? tmp7951 1)
  8376. goto block7952;
  8377. else
  8378. goto block7953;
  8379. block7952:
  8380. return 42;
  8381. block7953:
  8382. return 0;
  8383. \end{lstlisting}
  8384. $\Downarrow$
  8385. \begin{lstlisting}
  8386. start:
  8387. callq read_int
  8388. movq %rax, tmp7951
  8389. cmpq $1, tmp7951
  8390. je block7952
  8391. jmp block7953
  8392. block7953:
  8393. movq $0, %rax
  8394. jmp conclusion
  8395. block7952:
  8396. movq $42, %rax
  8397. jmp conclusion
  8398. \end{lstlisting}
  8399. \end{minipage}
  8400. &
  8401. $\Rightarrow\qquad$
  8402. \begin{minipage}{0.4\textwidth}
  8403. \begin{lstlisting}
  8404. start:
  8405. callq read_int
  8406. movq %rax, %rcx
  8407. cmpq $1, %rcx
  8408. je block7952
  8409. jmp block7953
  8410. block7953:
  8411. movq $0, %rax
  8412. jmp conclusion
  8413. block7952:
  8414. movq $42, %rax
  8415. jmp conclusion
  8416. .globl main
  8417. main:
  8418. pushq %rbp
  8419. movq %rsp, %rbp
  8420. pushq %r13
  8421. pushq %r12
  8422. pushq %rbx
  8423. pushq %r14
  8424. subq $0, %rsp
  8425. jmp start
  8426. conclusion:
  8427. addq $0, %rsp
  8428. popq %r14
  8429. popq %rbx
  8430. popq %r12
  8431. popq %r13
  8432. popq %rbp
  8433. retq
  8434. \end{lstlisting}
  8435. \end{minipage}
  8436. \end{tabular}
  8437. \fi}
  8438. {\if\edition\pythonEd
  8439. \begin{tabular}{lll}
  8440. \begin{minipage}{0.4\textwidth}
  8441. % cond_test_20.rkt, eq_input.py
  8442. \begin{lstlisting}
  8443. print(42 if input_int() == 1 else 0)
  8444. \end{lstlisting}
  8445. $\Downarrow$
  8446. \begin{lstlisting}
  8447. start:
  8448. tmp_0 = input_int()
  8449. if tmp_0 == 1:
  8450. goto block_3
  8451. else:
  8452. goto block_4
  8453. block_3:
  8454. tmp_1 = 42
  8455. goto block_2
  8456. block_4:
  8457. tmp_1 = 0
  8458. goto block_2
  8459. block_2:
  8460. print(tmp_1)
  8461. return 0
  8462. \end{lstlisting}
  8463. $\Downarrow$
  8464. \begin{lstlisting}
  8465. start:
  8466. callq read_int
  8467. movq %rax, tmp_0
  8468. cmpq 1, tmp_0
  8469. je block_3
  8470. jmp block_4
  8471. block_3:
  8472. movq 42, tmp_1
  8473. jmp block_2
  8474. block_4:
  8475. movq 0, tmp_1
  8476. jmp block_2
  8477. block_2:
  8478. movq tmp_1, %rdi
  8479. callq print_int
  8480. movq 0, %rax
  8481. jmp conclusion
  8482. \end{lstlisting}
  8483. \end{minipage}
  8484. &
  8485. $\Rightarrow\qquad$
  8486. \begin{minipage}{0.4\textwidth}
  8487. \begin{lstlisting}
  8488. .globl main
  8489. main:
  8490. pushq %rbp
  8491. movq %rsp, %rbp
  8492. subq $0, %rsp
  8493. jmp start
  8494. start:
  8495. callq read_int
  8496. movq %rax, %rcx
  8497. cmpq $1, %rcx
  8498. je block_3
  8499. jmp block_4
  8500. block_3:
  8501. movq $42, %rcx
  8502. jmp block_2
  8503. block_4:
  8504. movq $0, %rcx
  8505. jmp block_2
  8506. block_2:
  8507. movq %rcx, %rdi
  8508. callq print_int
  8509. movq $0, %rax
  8510. jmp conclusion
  8511. conclusion:
  8512. addq $0, %rsp
  8513. popq %rbp
  8514. retq
  8515. \end{lstlisting}
  8516. \end{minipage}
  8517. \end{tabular}
  8518. \fi}
  8519. \end{tcolorbox}
  8520. \caption{Example compilation of an \key{if} expression to x86, showing
  8521. the results of \code{explicate\_control},
  8522. \code{select\_instructions}, and the final x86 assembly code. }
  8523. \label{fig:if-example-x86}
  8524. \end{figure}
  8525. \begin{figure}[tbp]
  8526. \begin{tcolorbox}[colback=white]
  8527. {\if\edition\racketEd
  8528. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8529. \node (Lif) at (0,2) {\large \LangIf{}};
  8530. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8531. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8532. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8533. \node (Lif-5) at (9,0) {\large \LangIfANF{}};
  8534. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8535. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8536. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8537. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8538. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8539. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8540. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8541. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8542. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8543. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8544. \path[->,bend left=15] (Lif-4) edge [right] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8545. \path[->,bend right=15] (Lif-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8546. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  8547. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8548. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8549. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8550. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8551. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8552. \end{tikzpicture}
  8553. \fi}
  8554. {\if\edition\pythonEd
  8555. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  8556. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8557. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8558. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8559. \node (C-1) at (3,0) {\large \LangCIf{}};
  8560. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8561. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8562. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8563. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8564. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8565. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8566. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8567. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8568. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8569. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8570. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8571. \end{tikzpicture}
  8572. \fi}
  8573. \end{tcolorbox}
  8574. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8575. \label{fig:Lif-passes}
  8576. \end{figure}
  8577. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8578. compilation of \LangIf{}.
  8579. \section{Challenge: Optimize Blocks and Remove Jumps}
  8580. \label{sec:opt-jumps}
  8581. We discuss two optional challenges that involve optimizing the
  8582. control-flow of the program.
  8583. \subsection{Optimize Blocks}
  8584. The algorithm for \code{explicate\_control} that we discussed in
  8585. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8586. blocks. It creates a basic block whenever a continuation \emph{might}
  8587. get used more than once (e.g., whenever the \code{cont} parameter is
  8588. passed into two or more recursive calls). However, some continuation
  8589. arguments may not be used at all. For example, consider the case for
  8590. the constant \TRUE{} in \code{explicate\_pred}, where we discard the
  8591. \code{els} continuation.
  8592. %
  8593. {\if\edition\racketEd
  8594. The following example program falls into this
  8595. case, and it creates two unused blocks.
  8596. \begin{center}
  8597. \begin{tabular}{lll}
  8598. \begin{minipage}{0.4\textwidth}
  8599. % cond_test_82.rkt
  8600. \begin{lstlisting}
  8601. (let ([y (if #t
  8602. (read)
  8603. (if (eq? (read) 0)
  8604. 777
  8605. (let ([x (read)])
  8606. (+ 1 x))))])
  8607. (+ y 2))
  8608. \end{lstlisting}
  8609. \end{minipage}
  8610. &
  8611. $\Rightarrow$
  8612. &
  8613. \begin{minipage}{0.55\textwidth}
  8614. \begin{lstlisting}
  8615. start:
  8616. y = (read);
  8617. goto block_5;
  8618. block_5:
  8619. return (+ y 2);
  8620. block_6:
  8621. y = 777;
  8622. goto block_5;
  8623. block_7:
  8624. x = (read);
  8625. y = (+ 1 x2);
  8626. goto block_5;
  8627. \end{lstlisting}
  8628. \end{minipage}
  8629. \end{tabular}
  8630. \end{center}
  8631. \fi}
  8632. So the question is how can we decide whether to create a basic block?
  8633. \emph{Lazy evaluation}\index{subject}{lazy
  8634. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  8635. delaying the creation of a basic block until the point in time where
  8636. we know it will be used.
  8637. %
  8638. {\if\edition\racketEd
  8639. %
  8640. Racket provides support for
  8641. lazy evaluation with the
  8642. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8643. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8644. \index{subject}{delay} creates a
  8645. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8646. expressions is postponed. When \key{(force}
  8647. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8648. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8649. result of $e_n$ is cached in the promise and returned. If \code{force}
  8650. is applied again to the same promise, then the cached result is
  8651. returned. If \code{force} is applied to an argument that is not a
  8652. promise, \code{force} simply returns the argument.
  8653. %
  8654. \fi}
  8655. %
  8656. {\if\edition\pythonEd
  8657. %
  8658. While Python does not provide direct support for lazy evaluation, it
  8659. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8660. by wrapping it inside a function with no parameters. We can
  8661. \emph{force} its evaluation by calling the function. However, in some
  8662. cases of \code{explicate\_pred}, etc., we will return a list of
  8663. statements and in other cases we will return a function that computes
  8664. a list of statements. We use the term \emph{promise} to refer to a
  8665. value that may be delayed. To uniformly deal with
  8666. promises, we define the following \code{force} function that checks
  8667. whether its input is delayed (i.e., whether it is a function) and then
  8668. either 1) calls the function, or 2) returns the input.
  8669. \begin{lstlisting}
  8670. def force(promise):
  8671. if isinstance(promise, types.FunctionType):
  8672. return promise()
  8673. else:
  8674. return promise
  8675. \end{lstlisting}
  8676. %
  8677. \fi}
  8678. We use promises for the input and output of the functions
  8679. \code{explicate\_pred}, \code{explicate\_assign},
  8680. %
  8681. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8682. %
  8683. So instead of taking and returning \racket{$\Tail$
  8684. expressions}\python{lists of statements}, they take and return
  8685. promises. Furthermore, when we come to a situation in which a
  8686. continuation might be used more than once, as in the case for
  8687. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8688. that creates a basic block for each continuation (if there is not
  8689. already one) and then returns a \code{goto} statement to that basic
  8690. block. When we come to a situation where we have a promise but need an
  8691. actual piece of code, e.g. to create a larger piece of code with a
  8692. constructor such as \code{Seq}, then insert a call to \code{force}.
  8693. %
  8694. {\if\edition\racketEd
  8695. %
  8696. Also we must modify the \code{create\_block} function to begin with
  8697. \code{delay} to create a promise. When forced, this promise forces the
  8698. original promise. If that returns a \code{Goto} (because the block was
  8699. already added to \code{basic-blocks}), then we return the
  8700. \code{Goto}. Otherwise we add the block to \code{basic-blocks} and
  8701. return a \code{Goto} to the new label.
  8702. \begin{center}
  8703. \begin{minipage}{\textwidth}
  8704. \begin{lstlisting}
  8705. (define (create_block tail)
  8706. (delay
  8707. (define t (force tail))
  8708. (match t
  8709. [(Goto label) (Goto label)]
  8710. [else
  8711. (let ([label (gensym 'block)])
  8712. (set! basic-blocks (cons (cons label t) basic-blocks))
  8713. (Goto label))]))
  8714. \end{lstlisting}
  8715. \end{minipage}
  8716. \end{center}
  8717. \fi}
  8718. {\if\edition\pythonEd
  8719. %
  8720. Here is the new version of the \code{create\_block} auxiliary function
  8721. that works on promises and that checks whether the block consists of a
  8722. solitary \code{goto} statement.\\
  8723. \begin{minipage}{\textwidth}
  8724. \begin{lstlisting}
  8725. def create_block(promise, basic_blocks):
  8726. stmts = force(promise)
  8727. match stmts:
  8728. case [Goto(l)]:
  8729. return Goto(l)
  8730. case _:
  8731. label = label_name(generate_name('block'))
  8732. basic_blocks[label] = stmts
  8733. return Goto(label)
  8734. \end{lstlisting}
  8735. \end{minipage}
  8736. \fi}
  8737. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8738. improved \code{explicate\_control} on the above example. As you can
  8739. see, the number of basic blocks has been reduced from 4 blocks (see
  8740. figure~\ref{fig:explicate-control-s1-38}) down to 2 blocks.
  8741. \begin{figure}[tbp]
  8742. \begin{tcolorbox}[colback=white]
  8743. {\if\edition\racketEd
  8744. \begin{tabular}{lll}
  8745. \begin{minipage}{0.4\textwidth}
  8746. % cond_test_82.rkt
  8747. \begin{lstlisting}
  8748. (let ([y (if #t
  8749. (read)
  8750. (if (eq? (read) 0)
  8751. 777
  8752. (let ([x (read)])
  8753. (+ 1 x))))])
  8754. (+ y 2))
  8755. \end{lstlisting}
  8756. \end{minipage}
  8757. &
  8758. $\Rightarrow$
  8759. &
  8760. \begin{minipage}{0.55\textwidth}
  8761. \begin{lstlisting}
  8762. start:
  8763. y = (read);
  8764. goto block_5;
  8765. block_5:
  8766. return (+ y 2);
  8767. \end{lstlisting}
  8768. \end{minipage}
  8769. \end{tabular}
  8770. \fi}
  8771. {\if\edition\pythonEd
  8772. \begin{tabular}{lll}
  8773. \begin{minipage}{0.4\textwidth}
  8774. % cond_test_41.rkt
  8775. \begin{lstlisting}
  8776. x = input_int()
  8777. y = input_int()
  8778. print(y + 2 \
  8779. if (x == 0 \
  8780. if x < 1 \
  8781. else x == 2) \
  8782. else y + 10)
  8783. \end{lstlisting}
  8784. \end{minipage}
  8785. &
  8786. $\Rightarrow$
  8787. &
  8788. \begin{minipage}{0.55\textwidth}
  8789. \begin{lstlisting}
  8790. start:
  8791. x = input_int()
  8792. y = input_int()
  8793. if x < 1:
  8794. goto block_4
  8795. else:
  8796. goto block_5
  8797. block_4:
  8798. if x == 0:
  8799. goto block_2
  8800. else:
  8801. goto block_3
  8802. block_5:
  8803. if x == 2:
  8804. goto block_2
  8805. else:
  8806. goto block_3
  8807. block_2:
  8808. tmp_0 = y + 2
  8809. goto block_1
  8810. block_3:
  8811. tmp_0 = y + 10
  8812. goto block_1
  8813. block_1:
  8814. print(tmp_0)
  8815. return 0
  8816. \end{lstlisting}
  8817. \end{minipage}
  8818. \end{tabular}
  8819. \fi}
  8820. \end{tcolorbox}
  8821. \caption{Translation from \LangIf{} to \LangCIf{}
  8822. via the improved \code{explicate\_control}.}
  8823. \label{fig:explicate-control-challenge}
  8824. \end{figure}
  8825. %% Recall that in the example output of \code{explicate\_control} in
  8826. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8827. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8828. %% block. The first goal of this challenge assignment is to remove those
  8829. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8830. %% \code{explicate\_control} on the left and shows the result of bypassing
  8831. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8832. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8833. %% \code{block55}. The optimized code on the right of
  8834. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8835. %% \code{then} branch jumping directly to \code{block55}. The story is
  8836. %% similar for the \code{else} branch, as well as for the two branches in
  8837. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8838. %% have been optimized in this way, there are no longer any jumps to
  8839. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8840. %% \begin{figure}[tbp]
  8841. %% \begin{tabular}{lll}
  8842. %% \begin{minipage}{0.4\textwidth}
  8843. %% \begin{lstlisting}
  8844. %% block62:
  8845. %% tmp54 = (read);
  8846. %% if (eq? tmp54 2) then
  8847. %% goto block59;
  8848. %% else
  8849. %% goto block60;
  8850. %% block61:
  8851. %% tmp53 = (read);
  8852. %% if (eq? tmp53 0) then
  8853. %% goto block57;
  8854. %% else
  8855. %% goto block58;
  8856. %% block60:
  8857. %% goto block56;
  8858. %% block59:
  8859. %% goto block55;
  8860. %% block58:
  8861. %% goto block56;
  8862. %% block57:
  8863. %% goto block55;
  8864. %% block56:
  8865. %% return (+ 700 77);
  8866. %% block55:
  8867. %% return (+ 10 32);
  8868. %% start:
  8869. %% tmp52 = (read);
  8870. %% if (eq? tmp52 1) then
  8871. %% goto block61;
  8872. %% else
  8873. %% goto block62;
  8874. %% \end{lstlisting}
  8875. %% \end{minipage}
  8876. %% &
  8877. %% $\Rightarrow$
  8878. %% &
  8879. %% \begin{minipage}{0.55\textwidth}
  8880. %% \begin{lstlisting}
  8881. %% block62:
  8882. %% tmp54 = (read);
  8883. %% if (eq? tmp54 2) then
  8884. %% goto block55;
  8885. %% else
  8886. %% goto block56;
  8887. %% block61:
  8888. %% tmp53 = (read);
  8889. %% if (eq? tmp53 0) then
  8890. %% goto block55;
  8891. %% else
  8892. %% goto block56;
  8893. %% block56:
  8894. %% return (+ 700 77);
  8895. %% block55:
  8896. %% return (+ 10 32);
  8897. %% start:
  8898. %% tmp52 = (read);
  8899. %% if (eq? tmp52 1) then
  8900. %% goto block61;
  8901. %% else
  8902. %% goto block62;
  8903. %% \end{lstlisting}
  8904. %% \end{minipage}
  8905. %% \end{tabular}
  8906. %% \caption{Optimize jumps by removing trivial blocks.}
  8907. %% \label{fig:optimize-jumps}
  8908. %% \end{figure}
  8909. %% The name of this pass is \code{optimize-jumps}. We recommend
  8910. %% implementing this pass in two phases. The first phrase builds a hash
  8911. %% table that maps labels to possibly improved labels. The second phase
  8912. %% changes the target of each \code{goto} to use the improved label. If
  8913. %% the label is for a trivial block, then the hash table should map the
  8914. %% label to the first non-trivial block that can be reached from this
  8915. %% label by jumping through trivial blocks. If the label is for a
  8916. %% non-trivial block, then the hash table should map the label to itself;
  8917. %% we do not want to change jumps to non-trivial blocks.
  8918. %% The first phase can be accomplished by constructing an empty hash
  8919. %% table, call it \code{short-cut}, and then iterating over the control
  8920. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8921. %% then update the hash table, mapping the block's source to the target
  8922. %% of the \code{goto}. Also, the hash table may already have mapped some
  8923. %% labels to the block's source, to you must iterate through the hash
  8924. %% table and update all of those so that they instead map to the target
  8925. %% of the \code{goto}.
  8926. %% For the second phase, we recommend iterating through the $\Tail$ of
  8927. %% each block in the program, updating the target of every \code{goto}
  8928. %% according to the mapping in \code{short-cut}.
  8929. \begin{exercise}\normalfont\normalsize
  8930. Implement the improvements to the \code{explicate\_control} pass.
  8931. Check that it removes trivial blocks in a few example programs. Then
  8932. check that your compiler still passes all of your tests.
  8933. \end{exercise}
  8934. \subsection{Remove Jumps}
  8935. There is an opportunity for removing jumps that is apparent in the
  8936. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  8937. ends with a jump to \code{block\_5} and there are no other jumps to
  8938. \code{block\_5} in the rest of the program. In this situation we can
  8939. avoid the runtime overhead of this jump by merging \code{block\_5}
  8940. into the preceding block, in this case the \code{start} block.
  8941. Figure~\ref{fig:remove-jumps} shows the output of
  8942. \code{allocate\_registers} on the left and the result of this
  8943. optimization on the right.
  8944. \begin{figure}[tbp]
  8945. \begin{tcolorbox}[colback=white]
  8946. {\if\edition\racketEd
  8947. \begin{tabular}{lll}
  8948. \begin{minipage}{0.5\textwidth}
  8949. % cond_test_82.rkt
  8950. \begin{lstlisting}
  8951. start:
  8952. callq read_int
  8953. movq %rax, %rcx
  8954. jmp block_5
  8955. block_5:
  8956. movq %rcx, %rax
  8957. addq $2, %rax
  8958. jmp conclusion
  8959. \end{lstlisting}
  8960. \end{minipage}
  8961. &
  8962. $\Rightarrow\qquad$
  8963. \begin{minipage}{0.4\textwidth}
  8964. \begin{lstlisting}
  8965. start:
  8966. callq read_int
  8967. movq %rax, %rcx
  8968. movq %rcx, %rax
  8969. addq $2, %rax
  8970. jmp conclusion
  8971. \end{lstlisting}
  8972. \end{minipage}
  8973. \end{tabular}
  8974. \fi}
  8975. {\if\edition\pythonEd
  8976. \begin{tabular}{lll}
  8977. \begin{minipage}{0.5\textwidth}
  8978. % cond_test_20.rkt
  8979. \begin{lstlisting}
  8980. start:
  8981. callq read_int
  8982. movq %rax, tmp_0
  8983. cmpq 1, tmp_0
  8984. je block_3
  8985. jmp block_4
  8986. block_3:
  8987. movq 42, tmp_1
  8988. jmp block_2
  8989. block_4:
  8990. movq 0, tmp_1
  8991. jmp block_2
  8992. block_2:
  8993. movq tmp_1, %rdi
  8994. callq print_int
  8995. movq 0, %rax
  8996. jmp conclusion
  8997. \end{lstlisting}
  8998. \end{minipage}
  8999. &
  9000. $\Rightarrow\qquad$
  9001. \begin{minipage}{0.4\textwidth}
  9002. \begin{lstlisting}
  9003. start:
  9004. callq read_int
  9005. movq %rax, tmp_0
  9006. cmpq 1, tmp_0
  9007. je block_3
  9008. movq 0, tmp_1
  9009. jmp block_2
  9010. block_3:
  9011. movq 42, tmp_1
  9012. jmp block_2
  9013. block_2:
  9014. movq tmp_1, %rdi
  9015. callq print_int
  9016. movq 0, %rax
  9017. jmp conclusion
  9018. \end{lstlisting}
  9019. \end{minipage}
  9020. \end{tabular}
  9021. \fi}
  9022. \end{tcolorbox}
  9023. \caption{Merging basic blocks by removing unnecessary jumps.}
  9024. \label{fig:remove-jumps}
  9025. \end{figure}
  9026. \begin{exercise}\normalfont\normalsize
  9027. %
  9028. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9029. into their preceding basic block, when there is only one preceding
  9030. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9031. %
  9032. {\if\edition\racketEd
  9033. In the \code{run-tests.rkt} script, add the following entry to the
  9034. list of \code{passes} between \code{allocate\_registers}
  9035. and \code{patch\_instructions}.
  9036. \begin{lstlisting}
  9037. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  9038. \end{lstlisting}
  9039. \fi}
  9040. %
  9041. Run the script to test your compiler.
  9042. %
  9043. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9044. blocks on several test programs.
  9045. \end{exercise}
  9046. \section{Further Reading}
  9047. \label{sec:cond-further-reading}
  9048. The algorithm for the \code{explicate\_control} pass is based on the
  9049. \code{expose-basic-blocks} pass in the course notes of
  9050. \citet{Dybvig:2010aa}.
  9051. %
  9052. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9053. \citet{Appel:2003fk}, and is related to translations into continuation
  9054. passing
  9055. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9056. %
  9057. The treatment of conditionals in the \code{explicate\_control} pass is
  9058. similar to short-cut boolean
  9059. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9060. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9061. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9062. \chapter{Loops and Dataflow Analysis}
  9063. \label{ch:Lwhile}
  9064. \setcounter{footnote}{0}
  9065. % TODO: define R'_8
  9066. % TODO: multi-graph
  9067. {\if\edition\racketEd
  9068. %
  9069. In this chapter we study two features that are the hallmarks of
  9070. imperative programming languages: loops and assignments to local
  9071. variables. The following example demonstrates these new features by
  9072. computing the sum of the first five positive integers.
  9073. % similar to loop_test_1.rkt
  9074. \begin{lstlisting}
  9075. (let ([sum 0])
  9076. (let ([i 5])
  9077. (begin
  9078. (while (> i 0)
  9079. (begin
  9080. (set! sum (+ sum i))
  9081. (set! i (- i 1))))
  9082. sum)))
  9083. \end{lstlisting}
  9084. The \code{while} loop consists of a condition and a
  9085. body\footnote{The \code{while} loop is not a built-in
  9086. feature of the Racket language, but Racket includes many looping
  9087. constructs and it is straightforward to define \code{while} as a
  9088. macro.}. The body is evaluated repeatedly so long as the condition
  9089. remains true.
  9090. %
  9091. The \code{set!} consists of a variable and a right-hand side
  9092. expression. The \code{set!} updates value of the variable to the
  9093. value of the right-hand side.
  9094. %
  9095. The primary purpose of both the \code{while} loop and \code{set!} is
  9096. to cause side effects, so they do not have a meaningful result
  9097. value. Instead their result is the \code{\#<void>} value. The
  9098. expression \code{(void)} is an explicit way to create the
  9099. \code{\#<void>} value and it has type \code{Void}. The
  9100. \code{\#<void>} value can be passed around just like other values
  9101. inside an \LangLoop{} program and it can be compared for equality with
  9102. another \code{\#<void>} value. However, there are no other operations
  9103. specific to the the \code{\#<void>} value in \LangLoop{}. In contrast,
  9104. Racket defines the \code{void?} predicate that returns \code{\#t}
  9105. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9106. %
  9107. \footnote{Racket's \code{Void} type corresponds to what is often
  9108. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9109. by a single value \code{\#<void>} which corresponds to \code{unit}
  9110. or \code{()} in the literature~\citep{Pierce:2002hj}.}.
  9111. %
  9112. With the addition of side-effecting features such as \code{while} loop
  9113. and \code{set!}, it is helpful to also include in a language feature
  9114. for sequencing side effects: the \code{begin} expression. It consists
  9115. of one or more subexpressions that are evaluated left-to-right.
  9116. %
  9117. \fi}
  9118. {\if\edition\pythonEd
  9119. %
  9120. In this chapter we study loops, one of the hallmarks of imperative
  9121. programming languages. The following example demonstrates the
  9122. \code{while} loop by computing the sum of the first five positive
  9123. integers.
  9124. \begin{lstlisting}
  9125. sum = 0
  9126. i = 5
  9127. while i > 0:
  9128. sum = sum + i
  9129. i = i - 1
  9130. print(sum)
  9131. \end{lstlisting}
  9132. The \code{while} loop consists of a condition expression and a body (a
  9133. sequence of statements). The body is evaluated repeatedly so long as
  9134. the condition remains true.
  9135. %
  9136. \fi}
  9137. \section{The \LangLoop{} Language}
  9138. \newcommand{\LwhileGrammarRacket}{
  9139. \begin{array}{lcl}
  9140. \Type &::=& \key{Void}\\
  9141. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9142. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9143. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9144. \end{array}
  9145. }
  9146. \newcommand{\LwhileASTRacket}{
  9147. \begin{array}{lcl}
  9148. \Type &::=& \key{Void}\\
  9149. \Exp &::=& \SETBANG{\Var}{\Exp}
  9150. \MID \BEGIN{\Exp^{*}}{\Exp}
  9151. \MID \WHILE{\Exp}{\Exp}
  9152. \MID \VOID{}
  9153. \end{array}
  9154. }
  9155. \newcommand{\LwhileGrammarPython}{
  9156. \begin{array}{rcl}
  9157. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9158. \end{array}
  9159. }
  9160. \newcommand{\LwhileASTPython}{
  9161. \begin{array}{lcl}
  9162. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9163. \end{array}
  9164. }
  9165. \begin{figure}[tp]
  9166. \centering
  9167. \begin{tcolorbox}[colback=white]
  9168. \small
  9169. {\if\edition\racketEd
  9170. \[
  9171. \begin{array}{l}
  9172. \gray{\LintGrammarRacket{}} \\ \hline
  9173. \gray{\LvarGrammarRacket{}} \\ \hline
  9174. \gray{\LifGrammarRacket{}} \\ \hline
  9175. \LwhileGrammarRacket \\
  9176. \begin{array}{lcl}
  9177. \LangLoopM{} &::=& \Exp
  9178. \end{array}
  9179. \end{array}
  9180. \]
  9181. \fi}
  9182. {\if\edition\pythonEd
  9183. \[
  9184. \begin{array}{l}
  9185. \gray{\LintGrammarPython} \\ \hline
  9186. \gray{\LvarGrammarPython} \\ \hline
  9187. \gray{\LifGrammarPython} \\ \hline
  9188. \LwhileGrammarPython \\
  9189. \begin{array}{rcl}
  9190. \LangLoopM{} &::=& \Stmt^{*}
  9191. \end{array}
  9192. \end{array}
  9193. \]
  9194. \fi}
  9195. \end{tcolorbox}
  9196. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  9197. \label{fig:Lwhile-concrete-syntax}
  9198. \end{figure}
  9199. \begin{figure}[tp]
  9200. \centering
  9201. \begin{tcolorbox}[colback=white]
  9202. \small
  9203. {\if\edition\racketEd
  9204. \[
  9205. \begin{array}{l}
  9206. \gray{\LintOpAST} \\ \hline
  9207. \gray{\LvarASTRacket{}} \\ \hline
  9208. \gray{\LifASTRacket{}} \\ \hline
  9209. \LwhileASTRacket{} \\
  9210. \begin{array}{lcl}
  9211. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9212. \end{array}
  9213. \end{array}
  9214. \]
  9215. \fi}
  9216. {\if\edition\pythonEd
  9217. \[
  9218. \begin{array}{l}
  9219. \gray{\LintASTPython} \\ \hline
  9220. \gray{\LvarASTPython} \\ \hline
  9221. \gray{\LifASTPython} \\ \hline
  9222. \LwhileASTPython \\
  9223. \begin{array}{lcl}
  9224. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9225. \end{array}
  9226. \end{array}
  9227. \]
  9228. \fi}
  9229. \end{tcolorbox}
  9230. \python{
  9231. \index{subject}{While@\texttt{While}}
  9232. }
  9233. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  9234. \label{fig:Lwhile-syntax}
  9235. \end{figure}
  9236. The concrete syntax of \LangLoop{} is defined in
  9237. figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9238. in figure~\ref{fig:Lwhile-syntax}.
  9239. %
  9240. The definitional interpreter for \LangLoop{} is shown in
  9241. figure~\ref{fig:interp-Lwhile}.
  9242. %
  9243. {\if\edition\racketEd
  9244. %
  9245. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9246. and \code{Void} and we make changes to the cases for \code{Var} and
  9247. \code{Let} regarding variables. To support assignment to variables and
  9248. to make their lifetimes indefinite (see the second example in
  9249. section~\ref{sec:assignment-scoping}), we box the value that is bound
  9250. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9251. value.
  9252. %
  9253. Now to discuss the new cases. For \code{SetBang}, we find the
  9254. variable in the environment to obtain a boxed value and then we change
  9255. it using \code{set-box!} to the result of evaluating the right-hand
  9256. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9257. %
  9258. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9259. if the result is true, 2) evaluate the body.
  9260. The result value of a \code{while} loop is also \code{\#<void>}.
  9261. %
  9262. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9263. subexpressions \itm{es} for their effects and then evaluates
  9264. and returns the result from \itm{body}.
  9265. %
  9266. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9267. %
  9268. \fi}
  9269. {\if\edition\pythonEd
  9270. %
  9271. We add a new case for \code{While} in the \code{interp\_stmts}
  9272. function, where we repeatedly interpret the \code{body} so long as the
  9273. \code{test} expression remains true.
  9274. %
  9275. \fi}
  9276. \begin{figure}[tbp]
  9277. \begin{tcolorbox}[colback=white]
  9278. {\if\edition\racketEd
  9279. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9280. (define interp-Lwhile-class
  9281. (class interp-Lif-class
  9282. (super-new)
  9283. (define/override ((interp-exp env) e)
  9284. (define recur (interp-exp env))
  9285. (match e
  9286. [(Let x e body)
  9287. (define new-env (dict-set env x (box (recur e))))
  9288. ((interp-exp new-env) body)]
  9289. [(Var x) (unbox (dict-ref env x))]
  9290. [(SetBang x rhs)
  9291. (set-box! (dict-ref env x) (recur rhs))]
  9292. [(WhileLoop cnd body)
  9293. (define (loop)
  9294. (cond [(recur cnd) (recur body) (loop)]
  9295. [else (void)]))
  9296. (loop)]
  9297. [(Begin es body)
  9298. (for ([e es]) (recur e))
  9299. (recur body)]
  9300. [(Void) (void)]
  9301. [else ((super interp-exp env) e)]))
  9302. ))
  9303. (define (interp-Lwhile p)
  9304. (send (new interp-Lwhile-class) interp-program p))
  9305. \end{lstlisting}
  9306. \fi}
  9307. {\if\edition\pythonEd
  9308. \begin{lstlisting}
  9309. class InterpLwhile(InterpLif):
  9310. def interp_stmts(self, ss, env):
  9311. if len(ss) == 0:
  9312. return
  9313. match ss[0]:
  9314. case While(test, body, []):
  9315. while self.interp_exp(test, env):
  9316. self.interp_stmts(body, env)
  9317. return self.interp_stmts(ss[1:], env)
  9318. case _:
  9319. return super().interp_stmts(ss, env)
  9320. \end{lstlisting}
  9321. \fi}
  9322. \end{tcolorbox}
  9323. \caption{Interpreter for \LangLoop{}.}
  9324. \label{fig:interp-Lwhile}
  9325. \end{figure}
  9326. The type checker for \LangLoop{} is defined in
  9327. figure~\ref{fig:type-check-Lwhile}.
  9328. %
  9329. {\if\edition\racketEd
  9330. %
  9331. The type checking of the \code{SetBang} expression requires the type
  9332. of the variable and the right-hand side to agree. The result type is
  9333. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  9334. and the result type is \code{Void}. For \code{Begin}, the result type
  9335. is the type of its last subexpression.
  9336. %
  9337. \fi}
  9338. %
  9339. {\if\edition\pythonEd
  9340. %
  9341. A \code{while} loop is well typed if the type of the \code{test}
  9342. expression is \code{bool} and the statements in the \code{body} are
  9343. well typed.
  9344. %
  9345. \fi}
  9346. \begin{figure}[tbp]
  9347. \begin{tcolorbox}[colback=white]
  9348. {\if\edition\racketEd
  9349. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9350. (define type-check-Lwhile-class
  9351. (class type-check-Lif-class
  9352. (super-new)
  9353. (inherit check-type-equal?)
  9354. (define/override (type-check-exp env)
  9355. (lambda (e)
  9356. (define recur (type-check-exp env))
  9357. (match e
  9358. [(SetBang x rhs)
  9359. (define-values (rhs^ rhsT) (recur rhs))
  9360. (define varT (dict-ref env x))
  9361. (check-type-equal? rhsT varT e)
  9362. (values (SetBang x rhs^) 'Void)]
  9363. [(WhileLoop cnd body)
  9364. (define-values (cnd^ Tc) (recur cnd))
  9365. (check-type-equal? Tc 'Boolean e)
  9366. (define-values (body^ Tbody) ((type-check-exp env) body))
  9367. (values (WhileLoop cnd^ body^) 'Void)]
  9368. [(Begin es body)
  9369. (define-values (es^ ts)
  9370. (for/lists (l1 l2) ([e es]) (recur e)))
  9371. (define-values (body^ Tbody) (recur body))
  9372. (values (Begin es^ body^) Tbody)]
  9373. [else ((super type-check-exp env) e)])))
  9374. ))
  9375. (define (type-check-Lwhile p)
  9376. (send (new type-check-Lwhile-class) type-check-program p))
  9377. \end{lstlisting}
  9378. \fi}
  9379. {\if\edition\pythonEd
  9380. \begin{lstlisting}
  9381. class TypeCheckLwhile(TypeCheckLif):
  9382. def type_check_stmts(self, ss, env):
  9383. if len(ss) == 0:
  9384. return
  9385. match ss[0]:
  9386. case While(test, body, []):
  9387. test_t = self.type_check_exp(test, env)
  9388. check_type_equal(bool, test_t, test)
  9389. body_t = self.type_check_stmts(body, env)
  9390. return self.type_check_stmts(ss[1:], env)
  9391. case _:
  9392. return super().type_check_stmts(ss, env)
  9393. \end{lstlisting}
  9394. \fi}
  9395. \end{tcolorbox}
  9396. \caption{Type checker for the \LangLoop{} language.}
  9397. \label{fig:type-check-Lwhile}
  9398. \end{figure}
  9399. {\if\edition\racketEd
  9400. %
  9401. At first glance, the translation of these language features to x86
  9402. seems straightforward because the \LangCIf{} intermediate language
  9403. already supports all of the ingredients that we need: assignment,
  9404. \code{goto}, conditional branching, and sequencing. However, there are
  9405. complications that arise which we discuss in the next section. After
  9406. that we introduce the changes necessary to the existing passes.
  9407. %
  9408. \fi}
  9409. {\if\edition\pythonEd
  9410. %
  9411. At first glance, the translation of \code{while} loops to x86 seems
  9412. straightforward because the \LangCIf{} intermediate language already
  9413. supports \code{goto} and conditional branching. However, there are
  9414. complications that arise which we discuss in the next section. After
  9415. that we introduce the changes necessary to the existing passes.
  9416. %
  9417. \fi}
  9418. \section{Cyclic Control Flow and Dataflow Analysis}
  9419. \label{sec:dataflow-analysis}
  9420. Up until this point the programs generated in
  9421. \code{explicate\_control} were guaranteed to be acyclic. However, each
  9422. \code{while} loop introduces a cycle. But does that matter?
  9423. %
  9424. Indeed it does. Recall that for register allocation, the compiler
  9425. performs liveness analysis to determine which variables can share the
  9426. same register. To accomplish this we analyzed the control-flow graph
  9427. in reverse topological order
  9428. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9429. only well-defined for acyclic graphs.
  9430. Let us return to the example of computing the sum of the first five
  9431. positive integers. Here is the program after instruction selection but
  9432. before register allocation.
  9433. \begin{center}
  9434. {\if\edition\racketEd
  9435. \begin{minipage}{0.45\textwidth}
  9436. \begin{lstlisting}
  9437. (define (main) : Integer
  9438. mainstart:
  9439. movq $0, sum
  9440. movq $5, i
  9441. jmp block5
  9442. block5:
  9443. movq i, tmp3
  9444. cmpq tmp3, $0
  9445. jl block7
  9446. jmp block8
  9447. \end{lstlisting}
  9448. \end{minipage}
  9449. \begin{minipage}{0.45\textwidth}
  9450. \begin{lstlisting}
  9451. block7:
  9452. addq i, sum
  9453. movq $1, tmp4
  9454. negq tmp4
  9455. addq tmp4, i
  9456. jmp block5
  9457. block8:
  9458. movq $27, %rax
  9459. addq sum, %rax
  9460. jmp mainconclusion
  9461. )
  9462. \end{lstlisting}
  9463. \end{minipage}
  9464. \fi}
  9465. {\if\edition\pythonEd
  9466. \begin{minipage}{0.45\textwidth}
  9467. \begin{lstlisting}
  9468. mainstart:
  9469. movq $0, sum
  9470. movq $5, i
  9471. jmp block5
  9472. block5:
  9473. cmpq $0, i
  9474. jg block7
  9475. jmp block8
  9476. \end{lstlisting}
  9477. \end{minipage}
  9478. \begin{minipage}{0.45\textwidth}
  9479. \begin{lstlisting}
  9480. block7:
  9481. addq i, sum
  9482. subq $1, i
  9483. jmp block5
  9484. block8:
  9485. movq sum, %rdi
  9486. callq print_int
  9487. movq $0, %rax
  9488. jmp mainconclusion
  9489. \end{lstlisting}
  9490. \end{minipage}
  9491. \fi}
  9492. \end{center}
  9493. Recall that liveness analysis works backwards, starting at the end
  9494. of each function. For this example we could start with \code{block8}
  9495. because we know what is live at the beginning of the conclusion,
  9496. just \code{rax} and \code{rsp}. So the live-before set
  9497. for \code{block8} is \code{\{rsp,sum\}}.
  9498. %
  9499. Next we might try to analyze \code{block5} or \code{block7}, but
  9500. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9501. we are stuck.
  9502. The way out of this impasse is to realize that we can compute an
  9503. under-approximation of each live-before set by starting with empty
  9504. live-after sets. By \emph{under-approximation}, we mean that the set
  9505. only contains variables that are live for some execution of the
  9506. program, but the set may be missing some variables that are live.
  9507. Next, the under-approximations for each block can be improved by 1)
  9508. updating the live-after set for each block using the approximate
  9509. live-before sets from the other blocks and 2) perform liveness
  9510. analysis again on each block. In fact, by iterating this process, the
  9511. under-approximations eventually become the correct solutions!
  9512. %
  9513. This approach of iteratively analyzing a control-flow graph is
  9514. applicable to many static analysis problems and goes by the name
  9515. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9516. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9517. Washington.
  9518. Let us apply this approach to the above example. We use the empty set
  9519. for the initial live-before set for each block. Let $m_0$ be the
  9520. following mapping from label names to sets of locations (variables and
  9521. registers).
  9522. \begin{center}
  9523. \begin{lstlisting}
  9524. mainstart: {}, block5: {}, block7: {}, block8: {}
  9525. \end{lstlisting}
  9526. \end{center}
  9527. Using the above live-before approximations, we determine the
  9528. live-after for each block and then apply liveness analysis to each
  9529. block. This produces our next approximation $m_1$ of the live-before
  9530. sets.
  9531. \begin{center}
  9532. \begin{lstlisting}
  9533. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9534. \end{lstlisting}
  9535. \end{center}
  9536. For the second round, the live-after for \code{mainstart} is the
  9537. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9538. liveness analysis for \code{mainstart} computes the empty set. The
  9539. live-after for \code{block5} is the union of the live-before sets for
  9540. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9541. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9542. sum\}}. The live-after for \code{block7} is the live-before for
  9543. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9544. So the liveness analysis for \code{block7} remains \code{\{i,
  9545. sum\}}. Together these yield the following approximation $m_2$ of
  9546. the live-before sets.
  9547. \begin{center}
  9548. \begin{lstlisting}
  9549. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9550. \end{lstlisting}
  9551. \end{center}
  9552. In the preceding iteration, only \code{block5} changed, so we can
  9553. limit our attention to \code{mainstart} and \code{block7}, the two
  9554. blocks that jump to \code{block5}. As a result, the live-before sets
  9555. for \code{mainstart} and \code{block7} are updated to include
  9556. \code{rsp}, yielding the following approximation $m_3$.
  9557. \begin{center}
  9558. \begin{lstlisting}
  9559. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9560. \end{lstlisting}
  9561. \end{center}
  9562. Because \code{block7} changed, we analyze \code{block5} once more, but
  9563. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9564. our approximations have converged, so $m_3$ is the solution.
  9565. This iteration process is guaranteed to converge to a solution by the
  9566. Kleene Fixed-Point Theorem, a general theorem about functions on
  9567. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9568. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9569. elements, a least element $\bot$ (pronounced bottom), and a join
  9570. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9571. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9572. working with join semi-lattices.} When two elements are ordered $m_i
  9573. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9574. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9575. approximation than $m_i$. The bottom element $\bot$ represents the
  9576. complete lack of information, i.e., the worst approximation. The join
  9577. operator takes two lattice elements and combines their information,
  9578. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9579. bound}
  9580. A dataflow analysis typically involves two lattices: one lattice to
  9581. represent abstract states and another lattice that aggregates the
  9582. abstract states of all the blocks in the control-flow graph. For
  9583. liveness analysis, an abstract state is a set of locations. We form
  9584. the lattice $L$ by taking its elements to be sets of locations, the
  9585. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9586. set, and the join operator to be set union.
  9587. %
  9588. We form a second lattice $M$ by taking its elements to be mappings
  9589. from the block labels to sets of locations (elements of $L$). We
  9590. order the mappings point-wise, using the ordering of $L$. So given any
  9591. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9592. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9593. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9594. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9595. We can think of one iteration of liveness analysis applied to the
  9596. whole program as being a function $f$ on the lattice $M$. It takes a
  9597. mapping as input and computes a new mapping.
  9598. \[
  9599. f(m_i) = m_{i+1}
  9600. \]
  9601. Next let us think for a moment about what a final solution $m_s$
  9602. should look like. If we perform liveness analysis using the solution
  9603. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9604. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9605. \[
  9606. f(m_s) = m_s
  9607. \]
  9608. Furthermore, the solution should only include locations that are
  9609. forced to be there by performing liveness analysis on the program, so
  9610. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9611. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9612. monotone (better inputs produce better outputs), then the least fixed
  9613. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9614. chain} obtained by starting at $\bot$ and iterating $f$ as
  9615. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9616. \[
  9617. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9618. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9619. \]
  9620. When a lattice contains only finitely-long ascending chains, then
  9621. every Kleene chain tops out at some fixed point after some number of
  9622. iterations of $f$.
  9623. \[
  9624. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9625. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9626. \]
  9627. The liveness analysis is indeed a monotone function and the lattice
  9628. $M$ only has finitely-long ascending chains because there are only a
  9629. finite number of variables and blocks in the program. Thus we are
  9630. guaranteed that iteratively applying liveness analysis to all blocks
  9631. in the program will eventually produce the least fixed point solution.
  9632. Next let us consider dataflow analysis in general and discuss the
  9633. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  9634. %
  9635. The algorithm has four parameters: the control-flow graph \code{G}, a
  9636. function \code{transfer} that applies the analysis to one block, the
  9637. \code{bottom} and \code{join} operator for the lattice of abstract
  9638. states. The \code{analyze\_dataflow} function is formulated as a
  9639. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9640. function come from the predecessor nodes in the control-flow
  9641. graph. However, liveness analysis is a \emph{backward} dataflow
  9642. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9643. function with the transpose of the control-flow graph.
  9644. The algorithm begins by creating the bottom mapping, represented by a
  9645. hash table. It then pushes all of the nodes in the control-flow graph
  9646. onto the work list (a queue). The algorithm repeats the \code{while}
  9647. loop as long as there are items in the work list. In each iteration, a
  9648. node is popped from the work list and processed. The \code{input} for
  9649. the node is computed by taking the join of the abstract states of all
  9650. the predecessor nodes. The \code{transfer} function is then applied to
  9651. obtain the \code{output} abstract state. If the output differs from
  9652. the previous state for this block, the mapping for this block is
  9653. updated and its successor nodes are pushed onto the work list.
  9654. \begin{figure}[tb]
  9655. \begin{tcolorbox}[colback=white]
  9656. {\if\edition\racketEd
  9657. \begin{lstlisting}
  9658. (define (analyze_dataflow G transfer bottom join)
  9659. (define mapping (make-hash))
  9660. (for ([v (in-vertices G)])
  9661. (dict-set! mapping v bottom))
  9662. (define worklist (make-queue))
  9663. (for ([v (in-vertices G)])
  9664. (enqueue! worklist v))
  9665. (define trans-G (transpose G))
  9666. (while (not (queue-empty? worklist))
  9667. (define node (dequeue! worklist))
  9668. (define input (for/fold ([state bottom])
  9669. ([pred (in-neighbors trans-G node)])
  9670. (join state (dict-ref mapping pred))))
  9671. (define output (transfer node input))
  9672. (cond [(not (equal? output (dict-ref mapping node)))
  9673. (dict-set! mapping node output)
  9674. (for ([v (in-neighbors G node)])
  9675. (enqueue! worklist v))]))
  9676. mapping)
  9677. \end{lstlisting}
  9678. \fi}
  9679. {\if\edition\pythonEd
  9680. \begin{lstlisting}
  9681. def analyze_dataflow(G, transfer, bottom, join):
  9682. trans_G = transpose(G)
  9683. mapping = dict((v, bottom) for v in G.vertices())
  9684. worklist = deque(G.vertices)
  9685. while worklist:
  9686. node = worklist.pop()
  9687. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  9688. input = reduce(join, inputs, bottom)
  9689. output = transfer(node, input)
  9690. if output != mapping[node]:
  9691. mapping[node] = output
  9692. worklist.extend(G.adjacent(node))
  9693. \end{lstlisting}
  9694. \fi}
  9695. \end{tcolorbox}
  9696. \caption{Generic work list algorithm for dataflow analysis}
  9697. \label{fig:generic-dataflow}
  9698. \end{figure}
  9699. {\if\edition\racketEd
  9700. \section{Mutable Variables and Remove Complex Operands}
  9701. There is a subtle interaction between the
  9702. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  9703. and the left-to-right order of evaluation of Racket. Consider the
  9704. following example.
  9705. \begin{lstlisting}
  9706. (let ([x 2])
  9707. (+ x (begin (set! x 40) x)))
  9708. \end{lstlisting}
  9709. The result of this program is \code{42} because the first read from
  9710. \code{x} produces \code{2} and the second produces \code{40}. However,
  9711. if we naively apply the \code{remove\_complex\_operands} pass to this
  9712. example we obtain the following program whose result is \code{80}!
  9713. \begin{lstlisting}
  9714. (let ([x 2])
  9715. (let ([tmp (begin (set! x 40) x)])
  9716. (+ x tmp)))
  9717. \end{lstlisting}
  9718. The problem is that, with mutable variables, the ordering between
  9719. reads and writes is important, and the
  9720. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9721. before the first read of \code{x}.
  9722. We recommend solving this problem by giving special treatment to reads
  9723. from mutable variables, that is, variables that occur on the left-hand
  9724. side of a \code{set!}. We mark each read from a mutable variable with
  9725. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9726. that the read operation is effectful in that it can produce different
  9727. results at different points in time. Let's apply this idea to the
  9728. following variation that also involves a variable that is not mutated.
  9729. % loop_test_24.rkt
  9730. \begin{lstlisting}
  9731. (let ([x 2])
  9732. (let ([y 0])
  9733. (+ y (+ x (begin (set! x 40) x)))))
  9734. \end{lstlisting}
  9735. We first analyze the above program to discover that variable \code{x}
  9736. is mutable but \code{y} is not. We then transform the program as
  9737. follows, replacing each occurrence of \code{x} with \code{(get! x)}.
  9738. \begin{lstlisting}
  9739. (let ([x 2])
  9740. (let ([y 0])
  9741. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9742. \end{lstlisting}
  9743. Now that we have a clear distinction between reads from mutable and
  9744. immutable variables, we can apply the \code{remove\_complex\_operands}
  9745. pass, where reads from immutable variables are still classified as
  9746. atomic expressions but reads from mutable variables are classified as
  9747. complex. Thus, \code{remove\_complex\_operands} yields the following
  9748. program.\\
  9749. \begin{minipage}{\textwidth}
  9750. \begin{lstlisting}
  9751. (let ([x 2])
  9752. (let ([y 0])
  9753. (+ y (let ([t1 (get! x)])
  9754. (let ([t2 (begin (set! x 40) (get! x))])
  9755. (+ t1 t2))))))
  9756. \end{lstlisting}
  9757. \end{minipage}
  9758. The temporary variable \code{t1} gets the value of \code{x} before the
  9759. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9760. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9761. do not generate a temporary variable for the occurrence of \code{y}
  9762. because it's an immutable variable. We want to avoid such unnecessary
  9763. extra temporaries because they would needless increase the number of
  9764. variables, making it more likely for some of them to be spilled. The
  9765. result of this program is \code{42}, the same as the result prior to
  9766. \code{remove\_complex\_operands}.
  9767. The approach that we've sketched above requires only a small
  9768. modification to \code{remove\_complex\_operands} to handle
  9769. \code{get!}. However, it requires a new pass, called
  9770. \code{uncover-get!}, that we discuss in
  9771. section~\ref{sec:uncover-get-bang}.
  9772. As an aside, this problematic interaction between \code{set!} and the
  9773. pass \code{remove\_complex\_operands} is particular to Racket and not
  9774. its predecessor, the Scheme language. The key difference is that
  9775. Scheme does not specify an order of evaluation for the arguments of an
  9776. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9777. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9778. would be correct results for the example program. Interestingly,
  9779. Racket is implemented on top of the Chez Scheme
  9780. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9781. presented in this section (using extra \code{let} bindings to control
  9782. the order of evaluation) is used in the translation from Racket to
  9783. Scheme~\citep{Flatt:2019tb}.
  9784. \fi} % racket
  9785. Having discussed the complications that arise from adding support for
  9786. assignment and loops, we turn to discussing the individual compilation
  9787. passes.
  9788. {\if\edition\racketEd
  9789. \section{Uncover \texttt{get!}}
  9790. \label{sec:uncover-get-bang}
  9791. The goal of this pass it to mark uses of mutable variables so that
  9792. \code{remove\_complex\_operands} can treat them as complex expressions
  9793. and thereby preserve their ordering relative to the side-effects in
  9794. other operands. So the first step is to collect all the mutable
  9795. variables. We recommend creating an auxiliary function for this,
  9796. named \code{collect-set!}, that recursively traverses expressions,
  9797. returning the set of all variables that occur on the left-hand side of a
  9798. \code{set!}. Here's an excerpt of its implementation.
  9799. \begin{center}
  9800. \begin{minipage}{\textwidth}
  9801. \begin{lstlisting}
  9802. (define (collect-set! e)
  9803. (match e
  9804. [(Var x) (set)]
  9805. [(Int n) (set)]
  9806. [(Let x rhs body)
  9807. (set-union (collect-set! rhs) (collect-set! body))]
  9808. [(SetBang var rhs)
  9809. (set-union (set var) (collect-set! rhs))]
  9810. ...))
  9811. \end{lstlisting}
  9812. \end{minipage}
  9813. \end{center}
  9814. By placing this pass after \code{uniquify}, we need not worry about
  9815. variable shadowing and our logic for \code{Let} can remain simple, as
  9816. in the excerpt above.
  9817. The second step is to mark the occurrences of the mutable variables
  9818. with the new \code{GetBang} AST node (\code{get!} in concrete
  9819. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  9820. function, which takes two parameters: the set of mutable variables
  9821. \code{set!-vars}, and the expression \code{e} to be processed. The
  9822. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9823. mutable variable or leaves it alone if not.
  9824. \begin{center}
  9825. \begin{minipage}{\textwidth}
  9826. \begin{lstlisting}
  9827. (define ((uncover-get!-exp set!-vars) e)
  9828. (match e
  9829. [(Var x)
  9830. (if (set-member? set!-vars x)
  9831. (GetBang x)
  9832. (Var x))]
  9833. ...))
  9834. \end{lstlisting}
  9835. \end{minipage}
  9836. \end{center}
  9837. To wrap things up, define the \code{uncover-get!} function for
  9838. processing a whole program, using \code{collect-set!} to obtain the
  9839. set of mutable variables and then \code{uncover-get!-exp} to replace
  9840. their occurrences with \code{GetBang}.
  9841. \fi}
  9842. \section{Remove Complex Operands}
  9843. \label{sec:rco-loop}
  9844. {\if\edition\racketEd
  9845. %
  9846. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9847. \code{while} are all complex expressions. The subexpressions of
  9848. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9849. %
  9850. \fi}
  9851. {\if\edition\pythonEd
  9852. %
  9853. The change needed for this pass is to add a case for the \code{while}
  9854. statement. The condition of a \code{while} loop is allowed to be a
  9855. complex expression, just like the condition of the \code{if}
  9856. statement.
  9857. %
  9858. \fi}
  9859. %
  9860. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  9861. \LangLoopANF{} of this pass.
  9862. \newcommand{\LwhileMonadASTRacket}{
  9863. \begin{array}{rcl}
  9864. \Atm &::=& \VOID{} \\
  9865. \Exp &::=& \GETBANG{\Var}
  9866. \MID \SETBANG{\Var}{\Exp}
  9867. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9868. &\MID& \WHILE{\Exp}{\Exp}
  9869. \end{array}
  9870. }
  9871. \newcommand{\LwhileMonadASTPython}{
  9872. \begin{array}{rcl}
  9873. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9874. \end{array}
  9875. }
  9876. \begin{figure}[tp]
  9877. \centering
  9878. \begin{tcolorbox}[colback=white]
  9879. \small
  9880. {\if\edition\racketEd
  9881. \[
  9882. \begin{array}{l}
  9883. \gray{\LvarMonadASTRacket} \\ \hline
  9884. \gray{\LifMonadASTRacket} \\ \hline
  9885. \LwhileMonadASTRacket \\
  9886. \begin{array}{rcl}
  9887. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  9888. \end{array}
  9889. \end{array}
  9890. \]
  9891. \fi}
  9892. {\if\edition\pythonEd
  9893. \[
  9894. \begin{array}{l}
  9895. \gray{\LvarMonadASTPython} \\ \hline
  9896. \gray{\LifMonadASTPython} \\ \hline
  9897. \LwhileMonadASTPython \\
  9898. \begin{array}{rcl}
  9899. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9900. \end{array}
  9901. \end{array}
  9902. %% \begin{array}{rcl}
  9903. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9904. %% \Exp &::=& \Atm \MID \READ{} \\
  9905. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9906. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9907. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9908. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9909. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9910. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9911. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9912. %% \end{array}
  9913. \]
  9914. \fi}
  9915. \end{tcolorbox}
  9916. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9917. \label{fig:Lwhile-anf-syntax}
  9918. \end{figure}
  9919. {\if\edition\racketEd
  9920. %
  9921. As usual, when a complex expression appears in a grammar position that
  9922. needs to be atomic, such as the argument of a primitive operator, we
  9923. must introduce a temporary variable and bind it to the complex
  9924. expression. This approach applies, unchanged, to handle the new
  9925. language forms. For example, in the following code there are two
  9926. \code{begin} expressions appearing as arguments to the \code{+}
  9927. operator. The output of \code{rco\_exp} is shown below, in which the
  9928. \code{begin} expressions have been bound to temporary
  9929. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  9930. allowed to have arbitrary expressions in their right-hand side
  9931. expression, so it is fine to place \code{begin} there.
  9932. %
  9933. \begin{center}
  9934. \begin{tabular}{lcl}
  9935. \begin{minipage}{0.4\textwidth}
  9936. \begin{lstlisting}
  9937. (let ([x2 10])
  9938. (let ([y3 0])
  9939. (+ (+ (begin
  9940. (set! y3 (read))
  9941. (get! x2))
  9942. (begin
  9943. (set! x2 (read))
  9944. (get! y3)))
  9945. (get! x2))))
  9946. \end{lstlisting}
  9947. \end{minipage}
  9948. &
  9949. $\Rightarrow$
  9950. &
  9951. \begin{minipage}{0.4\textwidth}
  9952. \begin{lstlisting}
  9953. (let ([x2 10])
  9954. (let ([y3 0])
  9955. (let ([tmp4 (begin
  9956. (set! y3 (read))
  9957. x2)])
  9958. (let ([tmp5 (begin
  9959. (set! x2 (read))
  9960. y3)])
  9961. (let ([tmp6 (+ tmp4 tmp5)])
  9962. (let ([tmp7 x2])
  9963. (+ tmp6 tmp7)))))))
  9964. \end{lstlisting}
  9965. \end{minipage}
  9966. \end{tabular}
  9967. \end{center}
  9968. \fi}
  9969. \section{Explicate Control \racket{and \LangCLoop{}}}
  9970. \label{sec:explicate-loop}
  9971. \newcommand{\CloopASTRacket}{
  9972. \begin{array}{lcl}
  9973. \Atm &::=& \VOID \\
  9974. \Stmt &::=& \READ{}
  9975. \end{array}
  9976. }
  9977. {\if\edition\racketEd
  9978. Recall that in the \code{explicate\_control} pass we define one helper
  9979. function for each kind of position in the program. For the \LangVar{}
  9980. language of integers and variables we needed assignment and tail
  9981. positions. The \code{if} expressions of \LangIf{} introduced predicate
  9982. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  9983. another kind of position: effect position. Except for the last
  9984. subexpression, the subexpressions inside a \code{begin} are evaluated
  9985. only for their effect. Their result values are discarded. We can
  9986. generate better code by taking this fact into account.
  9987. The output language of \code{explicate\_control} is \LangCLoop{}
  9988. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  9989. \LangCIf{}. The only syntactic difference is the addition of \VOID{}
  9990. and that \code{read} may appear as a statement. The most significant
  9991. difference between the programs generated by \code{explicate\_control}
  9992. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  9993. chapter is that the control-flow graphs of the later may contain
  9994. cycles.
  9995. \begin{figure}[tp]
  9996. \begin{tcolorbox}[colback=white]
  9997. \small
  9998. \[
  9999. \begin{array}{l}
  10000. \gray{\CvarASTRacket} \\ \hline
  10001. \gray{\CifASTRacket} \\ \hline
  10002. \CloopASTRacket \\
  10003. \begin{array}{lcl}
  10004. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10005. \end{array}
  10006. \end{array}
  10007. \]
  10008. \end{tcolorbox}
  10009. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10010. \label{fig:c7-syntax}
  10011. \end{figure}
  10012. The new auxiliary function \code{explicate\_effect} takes an
  10013. expression (in an effect position) and the code for its
  10014. continuation. The function returns a $\Tail$ that includes the
  10015. generated code for the input expression followed by the
  10016. continuation. If the expression is obviously pure, that is, never
  10017. causes side effects, then the expression can be removed, so the result
  10018. is just the continuation.
  10019. %
  10020. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10021. interesting; the generated code is depicted in the following diagram.
  10022. \begin{center}
  10023. \begin{minipage}{0.3\textwidth}
  10024. \xymatrix{
  10025. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10026. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10027. & *+[F]{\txt{\itm{cont}}} \\
  10028. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10029. }
  10030. \end{minipage}
  10031. \end{center}
  10032. We start by creating a fresh label $\itm{loop}$ for the top of the
  10033. loop. Next, recursively process the \itm{body} (in effect position)
  10034. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10035. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10036. \itm{body'} as the then-branch and the continuation block as the
  10037. else-branch. The result should be added to the dictionary of
  10038. \code{basic-blocks} with the label \itm{loop}. The result for the
  10039. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10040. The auxiliary functions for tail, assignment, and predicate positions
  10041. need to be updated. The three new language forms, \code{while},
  10042. \code{set!}, and \code{begin}, can appear in assignment and tail
  10043. positions. Only \code{begin} may appear in predicate positions; the
  10044. other two have result type \code{Void}.
  10045. \fi}
  10046. %
  10047. {\if\edition\pythonEd
  10048. %
  10049. The output of this pass is the language \LangCIf{}. No new language
  10050. features are needed in the output because a \code{while} loop can be
  10051. expressed in terms of \code{goto} and \code{if} statements, which are
  10052. already in \LangCIf{}.
  10053. %
  10054. Add a case for the \code{while} statement to the
  10055. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10056. the condition expression.
  10057. %
  10058. \fi}
  10059. {\if\edition\racketEd
  10060. \section{Select Instructions}
  10061. \label{sec:select-instructions-loop}
  10062. Only two small additions are needed in the \code{select\_instructions}
  10063. pass to handle the changes to \LangCLoop{}. First, to handle the
  10064. addition of \VOID{} we simply translate it to \code{0}. Second,
  10065. \code{read} may appear as a stand-alone statement instead of only
  10066. appearing on the right-hand side of an assignment statement. The code
  10067. generation is nearly identical to the one for assignment; just leave
  10068. off the instruction for moving the result into the left-hand side.
  10069. \fi}
  10070. \section{Register Allocation}
  10071. \label{sec:register-allocation-loop}
  10072. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10073. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10074. which complicates the liveness analysis needed for register
  10075. allocation.
  10076. %
  10077. We recommend using the generic \code{analyze\_dataflow} function that
  10078. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10079. perform liveness analysis, replacing the code in
  10080. \code{uncover\_live} that processed the basic blocks in topological
  10081. order (section~\ref{sec:liveness-analysis-Lif}).
  10082. The \code{analyze\_dataflow} function has four parameters.
  10083. \begin{enumerate}
  10084. \item The first parameter \code{G} should be passed the transpose
  10085. of the control-flow graph.
  10086. \item The second parameter \code{transfer} should be passed a function
  10087. that applies liveness analysis to a basic block. It takes two
  10088. parameters: the label for the block to analyze and the live-after
  10089. set for that block. The transfer function should return the
  10090. live-before set for the block.
  10091. %
  10092. \racket{Also, as a side-effect, it should update the block's
  10093. $\itm{info}$ with the liveness information for each instruction.}
  10094. %
  10095. \python{Also, as a side-effect, it should update the live-before and
  10096. live-after sets for each instruction.}
  10097. %
  10098. To implement the \code{transfer} function, you should be able to
  10099. reuse the code you already have for analyzing basic blocks.
  10100. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10101. \code{bottom} and \code{join} for the lattice of abstract states,
  10102. i.e. sets of locations. For liveness analysis, the bottom of the
  10103. lattice is the empty set and the join operator is set union.
  10104. \end{enumerate}
  10105. \begin{figure}[p]
  10106. \begin{tcolorbox}[colback=white]
  10107. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10108. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10109. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10110. %\node (Lfun-3) at (6,2) {\large \LangLoop{}};
  10111. %\node (Lfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10112. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10113. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10114. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10115. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10116. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10117. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10118. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10119. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  10120. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  10121. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  10122. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  10123. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  10124. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  10125. %% \path[->,bend left=15] (Lfun) edge [above] node
  10126. %% {\ttfamily\footnotesize type-check} (Lfun-2);
  10127. \path[->,bend left=15] (Lfun) edge [above] node
  10128. {\ttfamily\footnotesize shrink} (Lfun-2);
  10129. \path[->,bend left=15] (Lfun-2) edge [above] node
  10130. {\ttfamily\footnotesize uniquify} (F1-4);
  10131. %% \path[->,bend left=15] (Lfun-3) edge [above] node
  10132. %% {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  10133. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10134. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  10135. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10136. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  10137. %% \path[->,bend right=15] (F1-2) edge [above] node
  10138. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  10139. %% \path[->,bend right=15] (F1-3) edge [above] node
  10140. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10141. \path[->,bend left=15] (F1-4) edge [above] node
  10142. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10143. \path[->,bend left=15] (F1-5) edge [right] node
  10144. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  10145. \path[->,bend right=15] (F1-6) edge [above] node
  10146. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10147. \path[->,bend left=15] (C3-2) edge [left] node
  10148. {\ttfamily\footnotesize select\_instr.} (x86-2);
  10149. \path[->,bend right=15] (x86-2) edge [left] node
  10150. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10151. \path[->,bend right=15] (x86-2-1) edge [below] node
  10152. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  10153. \path[->,bend right=15] (x86-2-2) edge [left] node
  10154. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  10155. \path[->,bend left=15] (x86-3) edge [above] node
  10156. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  10157. \path[->,bend left=15] (x86-4) edge [right] node
  10158. {\ttfamily\footnotesize pre.\_and\_concl.} (x86-5);
  10159. \end{tikzpicture}
  10160. \end{tcolorbox}
  10161. \caption{Diagram of the passes for \LangLoop{}.}
  10162. \label{fig:Lwhile-passes}
  10163. \end{figure}
  10164. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10165. for the compilation of \LangLoop{}.
  10166. % Further Reading: dataflow analysis
  10167. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10168. \chapter{Tuples and Garbage Collection}
  10169. \label{ch:Lvec}
  10170. \index{subject}{tuple}
  10171. \index{subject}{vector}
  10172. \index{subject}{allocate}
  10173. \index{subject}{heap allocate}
  10174. \setcounter{footnote}{0}
  10175. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10176. %% all the IR grammars are spelled out! \\ --Jeremy}
  10177. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10178. %% the root stack. \\ --Jeremy}
  10179. In this chapter we study the implementation of tuples\racket{, called
  10180. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10181. where each element may have a different type.
  10182. %
  10183. This language feature is the first to use the computer's
  10184. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  10185. indefinite, that is, a tuple lives forever from the programmer's
  10186. viewpoint. Of course, from an implementer's viewpoint, it is important
  10187. to reclaim the space associated with a tuple when it is no longer
  10188. needed, which is why we also study \emph{garbage collection}
  10189. \index{subject}{garbage collection} techniques in this chapter.
  10190. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  10191. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10192. language of chapter~\ref{ch:Lwhile} with tuples.
  10193. %
  10194. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10195. copying live tuples back and forth between two halves of the heap. The
  10196. garbage collector requires coordination with the compiler so that it
  10197. can find all of the live tuples.
  10198. %
  10199. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10200. discuss the necessary changes and additions to the compiler passes,
  10201. including a new compiler pass named \code{expose\_allocation}.
  10202. \section{The \LangVec{} Language}
  10203. \label{sec:r3}
  10204. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  10205. \LangVec{} and figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  10206. %
  10207. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10208. creating a tuple, \code{vector-ref} for reading an element of a
  10209. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10210. \code{vector-length} for obtaining the number of elements of a
  10211. tuple.}
  10212. %
  10213. \python{The \LangVec{} language adds 1) tuple creation via a
  10214. comma-separated list of expressions, 2) accessing an element of a
  10215. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10216. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10217. operator, and 4) obtaining the number of elements (the length) of a
  10218. tuple. In this chapter, we restrict access indices to constant
  10219. integers.}
  10220. %
  10221. The program below shows an example use of tuples. It creates a tuple
  10222. \code{t} containing the elements \code{40},
  10223. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10224. contains just \code{2}. The element at index $1$ of \code{t} is
  10225. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  10226. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10227. to which we add \code{2}, the element at index $0$ of the tuple. So
  10228. the result of the program is \code{42}.
  10229. %
  10230. {\if\edition\racketEd
  10231. \begin{lstlisting}
  10232. (let ([t (vector 40 #t (vector 2))])
  10233. (if (vector-ref t 1)
  10234. (+ (vector-ref t 0)
  10235. (vector-ref (vector-ref t 2) 0))
  10236. 44))
  10237. \end{lstlisting}
  10238. \fi}
  10239. {\if\edition\pythonEd
  10240. \begin{lstlisting}
  10241. t = 40, True, (2,)
  10242. print( t[0] + t[2][0] if t[1] else 44 )
  10243. \end{lstlisting}
  10244. \fi}
  10245. \newcommand{\LtupGrammarRacket}{
  10246. \begin{array}{lcl}
  10247. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10248. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  10249. \MID \LP\key{vector-length}\;\Exp\RP \\
  10250. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10251. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10252. \end{array}
  10253. }
  10254. \newcommand{\LtupASTRacket}{
  10255. \begin{array}{lcl}
  10256. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10257. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10258. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10259. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10260. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10261. \end{array}
  10262. }
  10263. \newcommand{\LtupGrammarPython}{
  10264. \begin{array}{rcl}
  10265. \itm{cmp} &::= & \key{is} \\
  10266. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10267. \end{array}
  10268. }
  10269. \newcommand{\LtupASTPython}{
  10270. \begin{array}{lcl}
  10271. \itm{cmp} &::= & \code{Is()} \\
  10272. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10273. &\MID& \LEN{\Exp}
  10274. \end{array}
  10275. }
  10276. \begin{figure}[tbp]
  10277. \centering
  10278. \begin{tcolorbox}[colback=white]
  10279. \small
  10280. {\if\edition\racketEd
  10281. \[
  10282. \begin{array}{l}
  10283. \gray{\LintGrammarRacket{}} \\ \hline
  10284. \gray{\LvarGrammarRacket{}} \\ \hline
  10285. \gray{\LifGrammarRacket{}} \\ \hline
  10286. \gray{\LwhileGrammarRacket} \\ \hline
  10287. \LtupGrammarRacket \\
  10288. \begin{array}{lcl}
  10289. \LangVecM{} &::=& \Exp
  10290. \end{array}
  10291. \end{array}
  10292. \]
  10293. \fi}
  10294. {\if\edition\pythonEd
  10295. \[
  10296. \begin{array}{l}
  10297. \gray{\LintGrammarPython{}} \\ \hline
  10298. \gray{\LvarGrammarPython{}} \\ \hline
  10299. \gray{\LifGrammarPython{}} \\ \hline
  10300. \gray{\LwhileGrammarPython} \\ \hline
  10301. \LtupGrammarPython \\
  10302. \begin{array}{rcl}
  10303. \LangVecM{} &::=& \Stmt^{*}
  10304. \end{array}
  10305. \end{array}
  10306. \]
  10307. \fi}
  10308. \end{tcolorbox}
  10309. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10310. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  10311. \label{fig:Lvec-concrete-syntax}
  10312. \end{figure}
  10313. \begin{figure}[tp]
  10314. \centering
  10315. \begin{tcolorbox}[colback=white]
  10316. \small
  10317. {\if\edition\racketEd
  10318. \[
  10319. \begin{array}{l}
  10320. \gray{\LintOpAST} \\ \hline
  10321. \gray{\LvarASTRacket{}} \\ \hline
  10322. \gray{\LifASTRacket{}} \\ \hline
  10323. \gray{\LwhileASTRacket{}} \\ \hline
  10324. \LtupASTRacket{} \\
  10325. \begin{array}{lcl}
  10326. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10327. \end{array}
  10328. \end{array}
  10329. \]
  10330. \fi}
  10331. {\if\edition\pythonEd
  10332. \[
  10333. \begin{array}{l}
  10334. \gray{\LintASTPython} \\ \hline
  10335. \gray{\LvarASTPython} \\ \hline
  10336. \gray{\LifASTPython} \\ \hline
  10337. \gray{\LwhileASTPython} \\ \hline
  10338. \LtupASTPython \\
  10339. \begin{array}{lcl}
  10340. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10341. \end{array}
  10342. \end{array}
  10343. \]
  10344. \fi}
  10345. \end{tcolorbox}
  10346. \caption{The abstract syntax of \LangVec{}.}
  10347. \label{fig:Lvec-syntax}
  10348. \end{figure}
  10349. Tuples raise several interesting new issues. First, variable binding
  10350. performs a shallow-copy when dealing with tuples, which means that
  10351. different variables can refer to the same tuple, that is, two
  10352. variables can be \emph{aliases}\index{subject}{alias} for the same
  10353. entity. Consider the following example in which both \code{t1} and
  10354. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10355. different tuple value but with equal elements. The result of the
  10356. program is \code{42}.
  10357. \begin{center}
  10358. \begin{minipage}{0.96\textwidth}
  10359. {\if\edition\racketEd
  10360. \begin{lstlisting}
  10361. (let ([t1 (vector 3 7)])
  10362. (let ([t2 t1])
  10363. (let ([t3 (vector 3 7)])
  10364. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10365. 42
  10366. 0))))
  10367. \end{lstlisting}
  10368. \fi}
  10369. {\if\edition\pythonEd
  10370. \begin{lstlisting}
  10371. t1 = 3, 7
  10372. t2 = t1
  10373. t3 = 3, 7
  10374. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10375. \end{lstlisting}
  10376. \fi}
  10377. \end{minipage}
  10378. \end{center}
  10379. {\if\edition\racketEd
  10380. Whether two variables are aliased or not affects what happens
  10381. when the underlying tuple is mutated\index{subject}{mutation}.
  10382. Consider the following example in which \code{t1} and \code{t2}
  10383. again refer to the same tuple value.
  10384. \begin{center}
  10385. \begin{minipage}{0.96\textwidth}
  10386. \begin{lstlisting}
  10387. (let ([t1 (vector 3 7)])
  10388. (let ([t2 t1])
  10389. (let ([_ (vector-set! t2 0 42)])
  10390. (vector-ref t1 0))))
  10391. \end{lstlisting}
  10392. \end{minipage}
  10393. \end{center}
  10394. The mutation through \code{t2} is visible when referencing the tuple
  10395. from \code{t1}, so the result of this program is \code{42}.
  10396. \fi}
  10397. The next issue concerns the lifetime of tuples. When does their
  10398. lifetime end? Notice that \LangVec{} does not include an operation
  10399. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10400. to any notion of static scoping.
  10401. %
  10402. {\if\edition\racketEd
  10403. %
  10404. For example, the following program returns \code{42} even though the
  10405. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10406. that reads from the vector it was bound to.
  10407. \begin{center}
  10408. \begin{minipage}{0.96\textwidth}
  10409. \begin{lstlisting}
  10410. (let ([v (vector (vector 44))])
  10411. (let ([x (let ([w (vector 42)])
  10412. (let ([_ (vector-set! v 0 w)])
  10413. 0))])
  10414. (+ x (vector-ref (vector-ref v 0) 0))))
  10415. \end{lstlisting}
  10416. \end{minipage}
  10417. \end{center}
  10418. \fi}
  10419. %
  10420. {\if\edition\pythonEd
  10421. %
  10422. For example, the following program returns \code{42} even though the
  10423. variable \code{x} goes out of scope when the function returns, prior
  10424. to reading the tuple element at index zero. (We study the compilation
  10425. of functions in chapter~\ref{ch:Lfun}.)
  10426. %
  10427. \begin{center}
  10428. \begin{minipage}{0.96\textwidth}
  10429. \begin{lstlisting}
  10430. def f():
  10431. x = 42, 43
  10432. return x
  10433. t = f()
  10434. print( t[0] )
  10435. \end{lstlisting}
  10436. \end{minipage}
  10437. \end{center}
  10438. \fi}
  10439. %
  10440. From the perspective of programmer-observable behavior, tuples live
  10441. forever. However, if they really lived forever then many long-running
  10442. programs would run out of memory. To solve this problem, the
  10443. language's runtime system performs automatic garbage collection.
  10444. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10445. \LangVec{} language.
  10446. %
  10447. \racket{We define the \code{vector}, \code{vector-ref},
  10448. \code{vector-set!}, and \code{vector-length} operations for
  10449. \LangVec{} in terms of the corresponding operations in Racket. One
  10450. subtle point is that the \code{vector-set!} operation returns the
  10451. \code{\#<void>} value.}
  10452. %
  10453. \python{We represent tuples with Python lists in the interpreter
  10454. because we need to write to them
  10455. (section~\ref{sec:expose-allocation}). (Python tuples are
  10456. immutable.) We define element access, the \code{is} operator, and
  10457. the \code{len} operator for \LangVec{} in terms of the corresponding
  10458. operations in Python.}
  10459. \begin{figure}[tbp]
  10460. \begin{tcolorbox}[colback=white]
  10461. {\if\edition\racketEd
  10462. \begin{lstlisting}
  10463. (define interp-Lvec-class
  10464. (class interp-Lwhile-class
  10465. (super-new)
  10466. (define/override (interp-op op)
  10467. (match op
  10468. ['eq? (lambda (v1 v2)
  10469. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10470. (and (boolean? v1) (boolean? v2))
  10471. (and (vector? v1) (vector? v2))
  10472. (and (void? v1) (void? v2)))
  10473. (eq? v1 v2)]))]
  10474. ['vector vector]
  10475. ['vector-length vector-length]
  10476. ['vector-ref vector-ref]
  10477. ['vector-set! vector-set!]
  10478. [else (super interp-op op)]
  10479. ))
  10480. (define/override ((interp-exp env) e)
  10481. (match e
  10482. [(HasType e t) ((interp-exp env) e)]
  10483. [else ((super interp-exp env) e)]
  10484. ))
  10485. ))
  10486. (define (interp-Lvec p)
  10487. (send (new interp-Lvec-class) interp-program p))
  10488. \end{lstlisting}
  10489. \fi}
  10490. %
  10491. {\if\edition\pythonEd
  10492. \begin{lstlisting}
  10493. class InterpLtup(InterpLwhile):
  10494. def interp_cmp(self, cmp):
  10495. match cmp:
  10496. case Is():
  10497. return lambda x, y: x is y
  10498. case _:
  10499. return super().interp_cmp(cmp)
  10500. def interp_exp(self, e, env):
  10501. match e:
  10502. case Tuple(es, Load()):
  10503. return tuple([self.interp_exp(e, env) for e in es])
  10504. case Subscript(tup, index, Load()):
  10505. t = self.interp_exp(tup, env)
  10506. n = self.interp_exp(index, env)
  10507. return t[n]
  10508. case _:
  10509. return super().interp_exp(e, env)
  10510. \end{lstlisting}
  10511. \fi}
  10512. \end{tcolorbox}
  10513. \caption{Interpreter for the \LangVec{} language.}
  10514. \label{fig:interp-Lvec}
  10515. \end{figure}
  10516. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10517. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10518. we need to know which elements of the tuple are themselves tuples for
  10519. the purposes of garbage collection. We can obtain this information
  10520. during type checking. The type checker in
  10521. figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10522. expression, it also
  10523. %
  10524. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10525. where $T$ is the tuple's type.
  10526. To create the s-expression for the \code{Vector} type in
  10527. figure~\ref{fig:type-check-Lvec}, we use the
  10528. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10529. operator} \code{,@} to insert the list \code{t*} without its usual
  10530. start and end parentheses. \index{subject}{unquote-slicing}}
  10531. %
  10532. \python{records the type of each tuple expression in a new field
  10533. named \code{has\_type}. Because the type checker has to compute the type
  10534. of each tuple access, the index must be a constant.}
  10535. \begin{figure}[tp]
  10536. \begin{tcolorbox}[colback=white]
  10537. {\if\edition\racketEd
  10538. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10539. (define type-check-Lvec-class
  10540. (class type-check-Lif-class
  10541. (super-new)
  10542. (inherit check-type-equal?)
  10543. (define/override (type-check-exp env)
  10544. (lambda (e)
  10545. (define recur (type-check-exp env))
  10546. (match e
  10547. [(Prim 'vector es)
  10548. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10549. (define t `(Vector ,@t*))
  10550. (values (HasType (Prim 'vector e*) t) t)]
  10551. [(Prim 'vector-ref (list e1 (Int i)))
  10552. (define-values (e1^ t) (recur e1))
  10553. (match t
  10554. [`(Vector ,ts ...)
  10555. (unless (and (0 . <= . i) (i . < . (length ts)))
  10556. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10557. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10558. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10559. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10560. (define-values (e-vec t-vec) (recur e1))
  10561. (define-values (e-arg^ t-arg) (recur arg))
  10562. (match t-vec
  10563. [`(Vector ,ts ...)
  10564. (unless (and (0 . <= . i) (i . < . (length ts)))
  10565. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10566. (check-type-equal? (list-ref ts i) t-arg e)
  10567. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10568. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10569. [(Prim 'vector-length (list e))
  10570. (define-values (e^ t) (recur e))
  10571. (match t
  10572. [`(Vector ,ts ...)
  10573. (values (Prim 'vector-length (list e^)) 'Integer)]
  10574. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10575. [(Prim 'eq? (list arg1 arg2))
  10576. (define-values (e1 t1) (recur arg1))
  10577. (define-values (e2 t2) (recur arg2))
  10578. (match* (t1 t2)
  10579. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10580. [(other wise) (check-type-equal? t1 t2 e)])
  10581. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10582. [(HasType (Prim 'vector es) t)
  10583. ((type-check-exp env) (Prim 'vector es))]
  10584. [(HasType e1 t)
  10585. (define-values (e1^ t^) (recur e1))
  10586. (check-type-equal? t t^ e)
  10587. (values (HasType e1^ t) t)]
  10588. [else ((super type-check-exp env) e)]
  10589. )))
  10590. ))
  10591. (define (type-check-Lvec p)
  10592. (send (new type-check-Lvec-class) type-check-program p))
  10593. \end{lstlisting}
  10594. \fi}
  10595. {\if\edition\pythonEd
  10596. \begin{lstlisting}
  10597. class TypeCheckLtup(TypeCheckLwhile):
  10598. def type_check_exp(self, e, env):
  10599. match e:
  10600. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10601. l = self.type_check_exp(left, env)
  10602. r = self.type_check_exp(right, env)
  10603. check_type_equal(l, r, e)
  10604. return bool
  10605. case Tuple(es, Load()):
  10606. ts = [self.type_check_exp(e, env) for e in es]
  10607. e.has_type = tuple(ts)
  10608. return e.has_type
  10609. case Subscript(tup, Constant(index), Load()):
  10610. tup_ty = self.type_check_exp(tup, env)
  10611. index_ty = self.type_check_exp(Constant(index), env)
  10612. check_type_equal(index_ty, int, index)
  10613. match tup_ty:
  10614. case tuple(ts):
  10615. return ts[index]
  10616. case _:
  10617. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10618. case _:
  10619. return super().type_check_exp(e, env)
  10620. \end{lstlisting}
  10621. \fi}
  10622. \end{tcolorbox}
  10623. \caption{Type checker for the \LangVec{} language.}
  10624. \label{fig:type-check-Lvec}
  10625. \end{figure}
  10626. \section{Garbage Collection}
  10627. \label{sec:GC}
  10628. Garbage collection is a runtime technique for reclaiming space on the
  10629. heap that will not be used in the future of the running program. We
  10630. use the term \emph{object}\index{subject}{object} to refer to any
  10631. value that is stored in the heap, which for now only includes
  10632. tuples.%
  10633. %
  10634. \footnote{The term ``object'' as it is used in the context of
  10635. object-oriented programming has a more specific meaning than how we
  10636. are using the term here.}
  10637. %
  10638. Unfortunately, it is impossible to know precisely which objects will
  10639. be accessed in the future and which will not. Instead, garbage
  10640. collectors over approximate the set of objects that will be accessed by
  10641. identifying which objects can possibly be accessed. The running
  10642. program can directly access objects that are in registers and on the
  10643. procedure call stack. It can also transitively access the elements of
  10644. tuples, starting with a tuple whose address is in a register or on the
  10645. procedure call stack. We define the \emph{root
  10646. set}\index{subject}{root set} to be all the tuple addresses that are
  10647. in registers or on the procedure call stack. We define the \emph{live
  10648. objects}\index{subject}{live objects} to be the objects that are
  10649. reachable from the root set. Garbage collectors reclaim the space that
  10650. is allocated to objects that are no longer live. That means that some
  10651. objects may not get reclaimed as soon as they could be, but at least
  10652. garbage collectors do not reclaim the space dedicated to objects that
  10653. will be accessed in the future! The programmer can influence which
  10654. objects get reclaimed by causing them to become unreachable.
  10655. So the goal of the garbage collector is twofold:
  10656. \begin{enumerate}
  10657. \item preserve all the live objects, and
  10658. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10659. \end{enumerate}
  10660. \subsection{Two-Space Copying Collector}
  10661. Here we study a relatively simple algorithm for garbage collection
  10662. that is the basis of many state-of-the-art garbage
  10663. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10664. particular, we describe a two-space copying
  10665. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10666. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10667. collector} \index{subject}{two-space copying collector}
  10668. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10669. what happens in a two-space collector, showing two time steps, prior
  10670. to garbage collection (on the top) and after garbage collection (on
  10671. the bottom). In a two-space collector, the heap is divided into two
  10672. parts named the FromSpace\index{subject}{FromSpace} and the
  10673. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10674. FromSpace until there is not enough room for the next allocation
  10675. request. At that point, the garbage collector goes to work to make
  10676. room for the next allocation.
  10677. A copying collector makes more room by copying all of the live objects
  10678. from the FromSpace into the ToSpace and then performs a sleight of
  10679. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10680. as the new ToSpace. In the example of
  10681. figure~\ref{fig:copying-collector}, the root set consists of three
  10682. pointers, one in a register and two on the stack. All of the live
  10683. objects have been copied to the ToSpace (the right-hand side of
  10684. figure~\ref{fig:copying-collector}) in a way that preserves the
  10685. pointer relationships. For example, the pointer in the register still
  10686. points to a tuple that in turn points to two other tuples. There are
  10687. four tuples that are not reachable from the root set and therefore do
  10688. not get copied into the ToSpace.
  10689. The exact situation in figure~\ref{fig:copying-collector} cannot be
  10690. created by a well-typed program in \LangVec{} because it contains a
  10691. cycle. However, creating cycles will be possible once we get to
  10692. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  10693. to deal with cycles to begin with so we will not need to revisit this
  10694. issue.
  10695. \begin{figure}[tbp]
  10696. \centering
  10697. \begin{tcolorbox}[colback=white]
  10698. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10699. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10700. \\[5ex]
  10701. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10702. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10703. \end{tcolorbox}
  10704. \caption{A copying collector in action.}
  10705. \label{fig:copying-collector}
  10706. \end{figure}
  10707. \subsection{Graph Copying via Cheney's Algorithm}
  10708. \label{sec:cheney}
  10709. \index{subject}{Cheney's algorithm}
  10710. Let us take a closer look at the copying of the live objects. The
  10711. allocated objects and pointers can be viewed as a graph and we need to
  10712. copy the part of the graph that is reachable from the root set. To
  10713. make sure we copy all of the reachable vertices in the graph, we need
  10714. an exhaustive graph traversal algorithm, such as depth-first search or
  10715. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10716. such algorithms take into account the possibility of cycles by marking
  10717. which vertices have already been visited, so as to ensure termination
  10718. of the algorithm. These search algorithms also use a data structure
  10719. such as a stack or queue as a to-do list to keep track of the vertices
  10720. that need to be visited. We use breadth-first search and a trick
  10721. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10722. and copying tuples into the ToSpace.
  10723. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10724. copy progresses. The queue is represented by a chunk of contiguous
  10725. memory at the beginning of the ToSpace, using two pointers to track
  10726. the front and the back of the queue, called the \emph{free pointer}
  10727. and the \emph{scan pointer} respectively. The algorithm starts by
  10728. copying all tuples that are immediately reachable from the root set
  10729. into the ToSpace to form the initial queue. When we copy a tuple, we
  10730. mark the old tuple to indicate that it has been visited. We discuss
  10731. how this marking is accomplish in section~\ref{sec:data-rep-gc}. Note
  10732. that any pointers inside the copied tuples in the queue still point
  10733. back to the FromSpace. Once the initial queue has been created, the
  10734. algorithm enters a loop in which it repeatedly processes the tuple at
  10735. the front of the queue and pops it off the queue. To process a tuple,
  10736. the algorithm copies all the objects that are directly reachable from it
  10737. to the ToSpace, placing them at the back of the queue. The algorithm
  10738. then updates the pointers in the popped tuple so they point to the
  10739. newly copied objects.
  10740. \begin{figure}[tbp]
  10741. \centering
  10742. \begin{tcolorbox}[colback=white]
  10743. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10744. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10745. \end{tcolorbox}
  10746. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10747. \label{fig:cheney}
  10748. \end{figure}
  10749. Getting back to figure~\ref{fig:cheney}, in the first step we copy the
  10750. tuple whose second element is $42$ to the back of the queue. The other
  10751. pointer goes to a tuple that has already been copied, so we do not
  10752. need to copy it again, but we do need to update the pointer to the new
  10753. location. This can be accomplished by storing a \emph{forwarding
  10754. pointer}\index{subject}{forwarding pointer} to the new location in the
  10755. old tuple, back when we initially copied the tuple into the
  10756. ToSpace. This completes one step of the algorithm. The algorithm
  10757. continues in this way until the queue is empty, that is, when the scan
  10758. pointer catches up with the free pointer.
  10759. \subsection{Data Representation}
  10760. \label{sec:data-rep-gc}
  10761. The garbage collector places some requirements on the data
  10762. representations used by our compiler. First, the garbage collector
  10763. needs to distinguish between pointers and other kinds of data such as
  10764. integers. There are several ways to accomplish this.
  10765. \begin{enumerate}
  10766. \item Attached a tag to each object that identifies what type of
  10767. object it is~\citep{McCarthy:1960dz}.
  10768. \item Store different types of objects in different
  10769. regions~\citep{Steele:1977ab}.
  10770. \item Use type information from the program to either (a) generate
  10771. type-specific code for collecting or (b) generate tables that
  10772. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10773. \end{enumerate}
  10774. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10775. need to tag objects anyways, so option 1 is a natural choice for those
  10776. languages. However, \LangVec{} is a statically typed language, so it
  10777. would be unfortunate to require tags on every object, especially small
  10778. and pervasive objects like integers and Booleans. Option 3 is the
  10779. best-performing choice for statically typed languages, but comes with
  10780. a relatively high implementation complexity. To keep this chapter
  10781. within a reasonable time budget, we recommend a combination of options
  10782. 1 and 2, using separate strategies for the stack and the heap.
  10783. Regarding the stack, we recommend using a separate stack for pointers,
  10784. which we call the \emph{root stack}\index{subject}{root stack}
  10785. (a.k.a. ``shadow
  10786. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10787. is, when a local variable needs to be spilled and is of type
  10788. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10789. root stack instead of putting it on the procedure call
  10790. stack. Furthermore, we always spill tuple-typed variables if they are
  10791. live during a call to the collector, thereby ensuring that no pointers
  10792. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10793. reproduces the example from figure~\ref{fig:copying-collector} and
  10794. contrasts it with the data layout using a root stack. The root stack
  10795. contains the two pointers from the regular stack and also the pointer
  10796. in the second register.
  10797. \begin{figure}[tbp]
  10798. \centering
  10799. \begin{tcolorbox}[colback=white]
  10800. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10801. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10802. \end{tcolorbox}
  10803. \caption{Maintaining a root stack to facilitate garbage collection.}
  10804. \label{fig:shadow-stack}
  10805. \end{figure}
  10806. The problem of distinguishing between pointers and other kinds of data
  10807. also arises inside of each tuple on the heap. We solve this problem by
  10808. attaching a tag, an extra 64-bits, to each
  10809. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10810. tuples in the example from figure~\ref{fig:copying-collector}. Note
  10811. that we have drawn the bits in a big-endian way, from right-to-left,
  10812. with bit location 0 (the least significant bit) on the far right,
  10813. which corresponds to the direction of the x86 shifting instructions
  10814. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10815. is dedicated to specifying which elements of the tuple are pointers,
  10816. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10817. indicates there is a pointer and a 0 bit indicates some other kind of
  10818. data. The pointer mask starts at bit location 7. We limit tuples to a
  10819. maximum size of 50 elements, so we just need 50 bits for the pointer
  10820. mask.%
  10821. %
  10822. \footnote{A production-quality compiler would handle
  10823. arbitrary-sized tuples and use a more complex approach.}
  10824. %
  10825. The tag also contains two other pieces of information. The length of
  10826. the tuple (number of elements) is stored in bits location 1 through
  10827. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10828. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10829. has not yet been copied. If the bit has value 0 then the entire tag
  10830. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10831. zero anyways because our tuples are 8-byte aligned.)
  10832. \begin{figure}[tbp]
  10833. \centering
  10834. \begin{tcolorbox}[colback=white]
  10835. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10836. \end{tcolorbox}
  10837. \caption{Representation of tuples in the heap.}
  10838. \label{fig:tuple-rep}
  10839. \end{figure}
  10840. \subsection{Implementation of the Garbage Collector}
  10841. \label{sec:organize-gz}
  10842. \index{subject}{prelude}
  10843. An implementation of the copying collector is provided in the
  10844. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10845. interface to the garbage collector that is used by the compiler. The
  10846. \code{initialize} function creates the FromSpace, ToSpace, and root
  10847. stack and should be called in the prelude of the \code{main}
  10848. function. The arguments of \code{initialize} are the root stack size
  10849. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10850. good choice for both. The \code{initialize} function puts the address
  10851. of the beginning of the FromSpace into the global variable
  10852. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10853. the address that is 1-past the last element of the FromSpace. We use
  10854. half-open intervals to represent chunks of
  10855. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  10856. points to the first element of the root stack.
  10857. As long as there is room left in the FromSpace, your generated code
  10858. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10859. %
  10860. The amount of room left in the FromSpace is the difference between the
  10861. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10862. function should be called when there is not enough room left in the
  10863. FromSpace for the next allocation. The \code{collect} function takes
  10864. a pointer to the current top of the root stack (one past the last item
  10865. that was pushed) and the number of bytes that need to be
  10866. allocated. The \code{collect} function performs the copying collection
  10867. and leaves the heap in a state such that there is enough room for the
  10868. next allocation.
  10869. \begin{figure}[tbp]
  10870. \begin{tcolorbox}[colback=white]
  10871. \begin{lstlisting}
  10872. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10873. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10874. int64_t* free_ptr;
  10875. int64_t* fromspace_begin;
  10876. int64_t* fromspace_end;
  10877. int64_t** rootstack_begin;
  10878. \end{lstlisting}
  10879. \end{tcolorbox}
  10880. \caption{The compiler's interface to the garbage collector.}
  10881. \label{fig:gc-header}
  10882. \end{figure}
  10883. %% \begin{exercise}
  10884. %% In the file \code{runtime.c} you will find the implementation of
  10885. %% \code{initialize} and a partial implementation of \code{collect}.
  10886. %% The \code{collect} function calls another function, \code{cheney},
  10887. %% to perform the actual copy, and that function is left to the reader
  10888. %% to implement. The following is the prototype for \code{cheney}.
  10889. %% \begin{lstlisting}
  10890. %% static void cheney(int64_t** rootstack_ptr);
  10891. %% \end{lstlisting}
  10892. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10893. %% rootstack (which is an array of pointers). The \code{cheney} function
  10894. %% also communicates with \code{collect} through the global
  10895. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10896. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  10897. %% the ToSpace:
  10898. %% \begin{lstlisting}
  10899. %% static int64_t* tospace_begin;
  10900. %% static int64_t* tospace_end;
  10901. %% \end{lstlisting}
  10902. %% The job of the \code{cheney} function is to copy all the live
  10903. %% objects (reachable from the root stack) into the ToSpace, update
  10904. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10905. %% update the root stack so that it points to the objects in the
  10906. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10907. %% and ToSpace.
  10908. %% \end{exercise}
  10909. The introduction of garbage collection has a non-trivial impact on our
  10910. compiler passes. We introduce a new compiler pass named
  10911. \code{expose\_allocation} that elaborates the code for allocating
  10912. tuples. We also make significant changes to
  10913. \code{select\_instructions}, \code{build\_interference},
  10914. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10915. make minor changes in several more passes.
  10916. The following program will serve as our running example. It creates
  10917. two tuples, one nested inside the other. Both tuples have length
  10918. one. The program accesses the element in the inner tuple.
  10919. % tests/vectors_test_17.rkt
  10920. {\if\edition\racketEd
  10921. \begin{lstlisting}
  10922. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10923. \end{lstlisting}
  10924. \fi}
  10925. {\if\edition\pythonEd
  10926. \begin{lstlisting}
  10927. print( ((42,),)[0][0] )
  10928. \end{lstlisting}
  10929. \fi}
  10930. {\if\edition\racketEd
  10931. \section{Shrink}
  10932. \label{sec:shrink-Lvec}
  10933. Recall that the \code{shrink} pass translates the primitives operators
  10934. into a smaller set of primitives.
  10935. %
  10936. This pass comes after type checking and the type checker adds a
  10937. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10938. need to add a case for \code{HasType} to the \code{shrink} pass.
  10939. \fi}
  10940. \section{Expose Allocation}
  10941. \label{sec:expose-allocation}
  10942. The pass \code{expose\_allocation} lowers tuple creation into a
  10943. conditional call to the collector followed by allocating the
  10944. appropriate amount of memory and initializing it. We choose to place
  10945. the \code{expose\_allocation} pass before
  10946. \code{remove\_complex\_operands} because it generates
  10947. code that contains complex operands.
  10948. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10949. replaces tuple creation with new lower-level forms that we use in the
  10950. translation of tuple creation.
  10951. %
  10952. {\if\edition\racketEd
  10953. \[
  10954. \begin{array}{lcl}
  10955. \Exp &::=& \cdots
  10956. \MID (\key{collect} \,\itm{int})
  10957. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10958. \MID (\key{global-value} \,\itm{name})
  10959. \end{array}
  10960. \]
  10961. \fi}
  10962. {\if\edition\pythonEd
  10963. \[
  10964. \begin{array}{lcl}
  10965. \Exp &::=& \cdots\\
  10966. &\MID& \key{collect}(\itm{int})
  10967. \MID \key{allocate}(\itm{int},\itm{type})
  10968. \MID \key{global\_value}(\itm{name}) \\
  10969. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10970. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10971. \end{array}
  10972. \]
  10973. \fi}
  10974. %
  10975. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10976. make sure that there are $n$ bytes ready to be allocated. During
  10977. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10978. the \code{collect} function in \code{runtime.c}.
  10979. %
  10980. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10981. space at the front for the 64 bit tag), but the elements are not
  10982. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10983. of the tuple:
  10984. %
  10985. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10986. %
  10987. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10988. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10989. as \code{free\_ptr}.
  10990. %
  10991. \python{The \code{begin} form is an expression that executes a
  10992. sequence of statements and then produces the value of the expression
  10993. at the end.}
  10994. The following shows the transformation of tuple creation into 1) a
  10995. sequence of temporary variable bindings for the initializing
  10996. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10997. \code{allocate}, and 4) the initialization of the tuple. The
  10998. \itm{len} placeholder refers to the length of the tuple and
  10999. \itm{bytes} is how many total bytes need to be allocated for the
  11000. tuple, which is 8 for the tag plus \itm{len} times 8.
  11001. %
  11002. \python{The \itm{type} needed for the second argument of the
  11003. \code{allocate} form can be obtained from the \code{has\_type} field
  11004. of the tuple AST node, which is stored there by running the type
  11005. checker for \LangVec{} immediately before this pass.}
  11006. %
  11007. \begin{center}
  11008. \begin{minipage}{\textwidth}
  11009. {\if\edition\racketEd
  11010. \begin{lstlisting}
  11011. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11012. |$\Longrightarrow$|
  11013. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11014. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11015. (global-value fromspace_end))
  11016. (void)
  11017. (collect |\itm{bytes}|))])
  11018. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11019. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11020. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11021. |$v$|) ... )))) ...)
  11022. \end{lstlisting}
  11023. \fi}
  11024. {\if\edition\pythonEd
  11025. \begin{lstlisting}
  11026. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11027. |$\Longrightarrow$|
  11028. begin:
  11029. |$x_0$| = |$e_0$|
  11030. |$\vdots$|
  11031. |$x_{n-1}$| = |$e_{n-1}$|
  11032. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11033. 0
  11034. else:
  11035. collect(|\itm{bytes}|)
  11036. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11037. |$v$|[0] = |$x_0$|
  11038. |$\vdots$|
  11039. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11040. |$v$|
  11041. \end{lstlisting}
  11042. \fi}
  11043. \end{minipage}
  11044. \end{center}
  11045. %
  11046. \noindent The sequencing of the initializing expressions
  11047. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  11048. they may trigger garbage collection and we cannot have an allocated
  11049. but uninitialized tuple on the heap during a collection.
  11050. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11051. \code{expose\_allocation} pass on our running example.
  11052. \begin{figure}[tbp]
  11053. \begin{tcolorbox}[colback=white]
  11054. % tests/s2_17.rkt
  11055. {\if\edition\racketEd
  11056. \begin{lstlisting}
  11057. (vector-ref
  11058. (vector-ref
  11059. (let ([vecinit6
  11060. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11061. (global-value fromspace_end))
  11062. (void)
  11063. (collect 16))])
  11064. (let ([alloc2 (allocate 1 (Vector Integer))])
  11065. (let ([_3 (vector-set! alloc2 0 42)])
  11066. alloc2)))])
  11067. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11068. (global-value fromspace_end))
  11069. (void)
  11070. (collect 16))])
  11071. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11072. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11073. alloc5))))
  11074. 0)
  11075. 0)
  11076. \end{lstlisting}
  11077. \fi}
  11078. {\if\edition\pythonEd
  11079. \begin{lstlisting}
  11080. print( |$T_1$|[0][0] )
  11081. \end{lstlisting}
  11082. where $T_1$ is
  11083. \begin{lstlisting}
  11084. begin:
  11085. tmp.1 = |$T_2$|
  11086. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11087. 0
  11088. else:
  11089. collect(16)
  11090. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11091. tmp.2[0] = tmp.1
  11092. tmp.2
  11093. \end{lstlisting}
  11094. and $T_2$ is
  11095. \begin{lstlisting}
  11096. begin:
  11097. tmp.3 = 42
  11098. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11099. 0
  11100. else:
  11101. collect(16)
  11102. tmp.4 = allocate(1, TupleType([int]))
  11103. tmp.4[0] = tmp.3
  11104. tmp.4
  11105. \end{lstlisting}
  11106. \fi}
  11107. \end{tcolorbox}
  11108. \caption{Output of the \code{expose\_allocation} pass.}
  11109. \label{fig:expose-alloc-output}
  11110. \end{figure}
  11111. \section{Remove Complex Operands}
  11112. \label{sec:remove-complex-opera-Lvec}
  11113. {\if\edition\racketEd
  11114. %
  11115. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11116. should be treated as complex operands.
  11117. %
  11118. \fi}
  11119. %
  11120. {\if\edition\pythonEd
  11121. %
  11122. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11123. and tuple access should be treated as complex operands. The
  11124. sub-expressions of tuple access must be atomic.
  11125. %
  11126. \fi}
  11127. %% A new case for
  11128. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11129. %% handled carefully to prevent the \code{Prim} node from being separated
  11130. %% from its enclosing \code{HasType}.
  11131. Figure~\ref{fig:Lvec-anf-syntax}
  11132. shows the grammar for the output language \LangAllocANF{} of this
  11133. pass, which is \LangAlloc{} in monadic normal form.
  11134. \newcommand{\LtupMonadASTRacket}{
  11135. \begin{array}{rcl}
  11136. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11137. \MID \GLOBALVALUE{\Var}
  11138. \end{array}
  11139. }
  11140. \newcommand{\LtupMonadASTPython}{
  11141. \begin{array}{rcl}
  11142. \Exp &::=& \GET{\Atm}{\Atm} \\
  11143. &\MID& \LEN{\Atm}\\
  11144. &\MID& \ALLOCATE{\Int}{\Type}
  11145. \MID \GLOBALVALUE{\Var} \\
  11146. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11147. &\MID& \COLLECT{\Int}
  11148. \end{array}
  11149. }
  11150. \begin{figure}[tp]
  11151. \centering
  11152. \begin{tcolorbox}[colback=white]
  11153. \small
  11154. {\if\edition\racketEd
  11155. \[
  11156. \begin{array}{l}
  11157. \gray{\LvarMonadASTRacket} \\ \hline
  11158. \gray{\LifMonadASTRacket} \\ \hline
  11159. \gray{\LwhileMonadASTRacket} \\ \hline
  11160. \LtupMonadASTRacket \\
  11161. \begin{array}{rcl}
  11162. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11163. \end{array}
  11164. \end{array}
  11165. \]
  11166. \fi}
  11167. {\if\edition\pythonEd
  11168. \[
  11169. \begin{array}{l}
  11170. \gray{\LvarMonadASTPython} \\ \hline
  11171. \gray{\LifMonadASTPython} \\ \hline
  11172. \gray{\LwhileMonadASTPython} \\ \hline
  11173. \LtupMonadASTPython \\
  11174. \begin{array}{rcl}
  11175. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11176. \end{array}
  11177. \end{array}
  11178. \]
  11179. \fi}
  11180. \end{tcolorbox}
  11181. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11182. \label{fig:Lvec-anf-syntax}
  11183. \end{figure}
  11184. \section{Explicate Control and the \LangCVec{} language}
  11185. \label{sec:explicate-control-r3}
  11186. \newcommand{\CtupASTRacket}{
  11187. \begin{array}{lcl}
  11188. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11189. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11190. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11191. &\MID& \VECLEN{\Atm} \\
  11192. &\MID& \GLOBALVALUE{\Var} \\
  11193. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11194. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11195. \end{array}
  11196. }
  11197. \newcommand{\CtupASTPython}{
  11198. \begin{array}{lcl}
  11199. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11200. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11201. \Stmt &::=& \COLLECT{\Int} \\
  11202. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11203. \end{array}
  11204. }
  11205. \begin{figure}[tp]
  11206. \begin{tcolorbox}[colback=white]
  11207. \small
  11208. {\if\edition\racketEd
  11209. \[
  11210. \begin{array}{l}
  11211. \gray{\CvarASTRacket} \\ \hline
  11212. \gray{\CifASTRacket} \\ \hline
  11213. \gray{\CloopASTRacket} \\ \hline
  11214. \CtupASTRacket \\
  11215. \begin{array}{lcl}
  11216. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11217. \end{array}
  11218. \end{array}
  11219. \]
  11220. \fi}
  11221. {\if\edition\pythonEd
  11222. \[
  11223. \begin{array}{l}
  11224. \gray{\CifASTPython} \\ \hline
  11225. \CtupASTPython \\
  11226. \begin{array}{lcl}
  11227. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11228. \end{array}
  11229. \end{array}
  11230. \]
  11231. \fi}
  11232. \end{tcolorbox}
  11233. \caption{The abstract syntax of \LangCVec{}, extending
  11234. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11235. (figure~\ref{fig:c1-syntax})}.}
  11236. \label{fig:c2-syntax}
  11237. \end{figure}
  11238. The output of \code{explicate\_control} is a program in the
  11239. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11240. figure~\ref{fig:c2-syntax}.
  11241. %
  11242. %% \racket{(The concrete syntax is defined in
  11243. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11244. %
  11245. The new expressions of \LangCVec{} include \key{allocate},
  11246. %
  11247. \racket{\key{vector-ref}, and \key{vector-set!},}
  11248. %
  11249. \python{accessing tuple elements,}
  11250. %
  11251. and \key{global\_value}.
  11252. %
  11253. \python{\LangCVec{} also includes the \code{collect} statement and
  11254. assignment to a tuple element.}
  11255. %
  11256. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11257. %
  11258. The \code{explicate\_control} pass can treat these new forms much like
  11259. the other forms that we've already encountered. The output of the
  11260. \code{explicate\_control} pass on the running example is shown on the
  11261. left-side of figure~\ref{fig:select-instr-output-gc} in the next
  11262. section.
  11263. \section{Select Instructions and the \LangXGlobal{} Language}
  11264. \label{sec:select-instructions-gc}
  11265. \index{subject}{instruction selection}
  11266. %% void (rep as zero)
  11267. %% allocate
  11268. %% collect (callq collect)
  11269. %% vector-ref
  11270. %% vector-set!
  11271. %% vector-length
  11272. %% global (postpone)
  11273. In this pass we generate x86 code for most of the new operations that
  11274. were needed to compile tuples, including \code{Allocate},
  11275. \code{Collect}, and accessing tuple elements.
  11276. %
  11277. We compile \code{GlobalValue} to \code{Global} because the later has a
  11278. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11279. \ref{fig:x86-2}). \index{subject}{x86}
  11280. The tuple read and write forms translate into \code{movq}
  11281. instructions. (The $+1$ in the offset is to move past the tag at the
  11282. beginning of the tuple representation.)
  11283. %
  11284. \begin{center}
  11285. \begin{minipage}{\textwidth}
  11286. {\if\edition\racketEd
  11287. \begin{lstlisting}
  11288. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11289. |$\Longrightarrow$|
  11290. movq |$\itm{tup}'$|, %r11
  11291. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11292. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11293. |$\Longrightarrow$|
  11294. movq |$\itm{tup}'$|, %r11
  11295. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11296. movq $0, |$\itm{lhs'}$|
  11297. \end{lstlisting}
  11298. \fi}
  11299. {\if\edition\pythonEd
  11300. \begin{lstlisting}
  11301. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11302. |$\Longrightarrow$|
  11303. movq |$\itm{tup}'$|, %r11
  11304. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11305. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11306. |$\Longrightarrow$|
  11307. movq |$\itm{tup}'$|, %r11
  11308. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11309. \end{lstlisting}
  11310. \fi}
  11311. \end{minipage}
  11312. \end{center}
  11313. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11314. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11315. are obtained by translating from \LangCVec{} to x86.
  11316. %
  11317. The move of $\itm{tup}'$ to
  11318. register \code{r11} ensures that offset expression
  11319. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  11320. removing \code{r11} from consideration by the register allocating.
  11321. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11322. \code{rax}. Then the generated code for tuple assignment would be
  11323. \begin{lstlisting}
  11324. movq |$\itm{tup}'$|, %rax
  11325. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11326. \end{lstlisting}
  11327. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11328. \code{patch\_instructions} would insert a move through \code{rax}
  11329. as follows.
  11330. \begin{lstlisting}
  11331. movq |$\itm{tup}'$|, %rax
  11332. movq |$\itm{rhs}'$|, %rax
  11333. movq %rax, |$8(n+1)$|(%rax)
  11334. \end{lstlisting}
  11335. But the above sequence of instructions does not work because we're
  11336. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11337. $\itm{rhs}'$) at the same time!
  11338. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11339. be translated into a sequence of instructions that read the tag of the
  11340. tuple and extract the six bits that represent the tuple length, which
  11341. are the bits starting at index 1 and going up to and including bit 6.
  11342. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11343. (shift right) can be used to accomplish this.
  11344. We compile the \code{allocate} form to operations on the
  11345. \code{free\_ptr}, as shown below. This approach is called
  11346. \emph{inline allocation} as it implements allocation without a
  11347. function call, by simply bumping the allocation pointer. It is much
  11348. more efficient than calling a function for each allocation. The
  11349. address in the \code{free\_ptr} is the next free address in the
  11350. FromSpace, so we copy it into \code{r11} and then move it forward by
  11351. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  11352. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  11353. the tag. We then initialize the \itm{tag} and finally copy the
  11354. address in \code{r11} to the left-hand side. Refer to
  11355. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  11356. %
  11357. \racket{We recommend using the Racket operations
  11358. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11359. during compilation.}
  11360. %
  11361. \python{We recommend using the bitwise-or operator \code{|} and the
  11362. shift-left operator \code{<<} to compute the tag during
  11363. compilation.}
  11364. %
  11365. The type annotation in the \code{allocate} form is used to determine
  11366. the pointer mask region of the tag.
  11367. %
  11368. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11369. address of the \code{free\_ptr} global variable but uses a special
  11370. instruction-pointer relative addressing mode of the x86-64 processor.
  11371. In particular, the assembler computes the distance $d$ between the
  11372. address of \code{free\_ptr} and where the \code{rip} would be at that
  11373. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11374. \code{$d$(\%rip)}, which at runtime will compute the address of
  11375. \code{free\_ptr}.
  11376. %
  11377. {\if\edition\racketEd
  11378. \begin{lstlisting}
  11379. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11380. |$\Longrightarrow$|
  11381. movq free_ptr(%rip), %r11
  11382. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11383. movq $|$\itm{tag}$|, 0(%r11)
  11384. movq %r11, |$\itm{lhs}'$|
  11385. \end{lstlisting}
  11386. \fi}
  11387. {\if\edition\pythonEd
  11388. \begin{lstlisting}
  11389. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11390. |$\Longrightarrow$|
  11391. movq free_ptr(%rip), %r11
  11392. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11393. movq $|$\itm{tag}$|, 0(%r11)
  11394. movq %r11, |$\itm{lhs}'$|
  11395. \end{lstlisting}
  11396. \fi}
  11397. The \code{collect} form is compiled to a call to the \code{collect}
  11398. function in the runtime. The arguments to \code{collect} are 1) the
  11399. top of the root stack and 2) the number of bytes that need to be
  11400. allocated. We use another dedicated register, \code{r15}, to
  11401. store the pointer to the top of the root stack. So \code{r15} is not
  11402. available for use by the register allocator.
  11403. {\if\edition\racketEd
  11404. \begin{lstlisting}
  11405. (collect |$\itm{bytes}$|)
  11406. |$\Longrightarrow$|
  11407. movq %r15, %rdi
  11408. movq $|\itm{bytes}|, %rsi
  11409. callq collect
  11410. \end{lstlisting}
  11411. \fi}
  11412. {\if\edition\pythonEd
  11413. \begin{lstlisting}
  11414. collect(|$\itm{bytes}$|)
  11415. |$\Longrightarrow$|
  11416. movq %r15, %rdi
  11417. movq $|\itm{bytes}|, %rsi
  11418. callq collect
  11419. \end{lstlisting}
  11420. \fi}
  11421. \newcommand{\GrammarXGlobal}{
  11422. \begin{array}{lcl}
  11423. \Arg &::=& \itm{label} \key{(\%rip)}
  11424. \end{array}
  11425. }
  11426. \newcommand{\ASTXGlobalRacket}{
  11427. \begin{array}{lcl}
  11428. \Arg &::=& \GLOBAL{\itm{label}}
  11429. \end{array}
  11430. }
  11431. \begin{figure}[tp]
  11432. \begin{tcolorbox}[colback=white]
  11433. \[
  11434. \begin{array}{l}
  11435. \gray{\GrammarXInt} \\ \hline
  11436. \gray{\GrammarXIf} \\ \hline
  11437. \GrammarXGlobal \\
  11438. \begin{array}{lcl}
  11439. \LangXGlobalM{} &::= & \key{.globl main} \\
  11440. & & \key{main:} \; \Instr^{*}
  11441. \end{array}
  11442. \end{array}
  11443. \]
  11444. \end{tcolorbox}
  11445. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of figure~\ref{fig:x86-1-concrete}).}
  11446. \label{fig:x86-2-concrete}
  11447. \end{figure}
  11448. \begin{figure}[tp]
  11449. \begin{tcolorbox}[colback=white]
  11450. \small
  11451. \[
  11452. \begin{array}{l}
  11453. \gray{\ASTXIntRacket} \\ \hline
  11454. \gray{\ASTXIfRacket} \\ \hline
  11455. \ASTXGlobalRacket \\
  11456. \begin{array}{lcl}
  11457. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  11458. \end{array}
  11459. \end{array}
  11460. \]
  11461. \end{tcolorbox}
  11462. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of figure~\ref{fig:x86-1}).}
  11463. \label{fig:x86-2}
  11464. \end{figure}
  11465. The concrete and abstract syntax of the \LangXGlobal{} language is
  11466. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11467. differs from \LangXIf{} just in the addition of global variables.
  11468. %
  11469. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11470. \code{select\_instructions} pass on the running example.
  11471. \begin{figure}[tbp]
  11472. \centering
  11473. \begin{tcolorbox}[colback=white]
  11474. % tests/s2_17.rkt
  11475. \begin{tabular}{lll}
  11476. \begin{minipage}{0.5\textwidth}
  11477. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11478. start:
  11479. tmp9 = (global-value free_ptr);
  11480. tmp0 = (+ tmp9 16);
  11481. tmp1 = (global-value fromspace_end);
  11482. if (< tmp0 tmp1)
  11483. goto block0;
  11484. else
  11485. goto block1;
  11486. block0:
  11487. _4 = (void);
  11488. goto block9;
  11489. block1:
  11490. (collect 16)
  11491. goto block9;
  11492. block9:
  11493. alloc2 = (allocate 1 (Vector Integer));
  11494. _3 = (vector-set! alloc2 0 42);
  11495. vecinit6 = alloc2;
  11496. tmp2 = (global-value free_ptr);
  11497. tmp3 = (+ tmp2 16);
  11498. tmp4 = (global-value fromspace_end);
  11499. if (< tmp3 tmp4)
  11500. goto block7;
  11501. else
  11502. goto block8;
  11503. block7:
  11504. _8 = (void);
  11505. goto block6;
  11506. block8:
  11507. (collect 16)
  11508. goto block6;
  11509. block6:
  11510. alloc5 = (allocate 1 (Vector (Vector Integer)));
  11511. _7 = (vector-set! alloc5 0 vecinit6);
  11512. tmp5 = (vector-ref alloc5 0);
  11513. return (vector-ref tmp5 0);
  11514. \end{lstlisting}
  11515. \end{minipage}
  11516. &$\Rightarrow$&
  11517. \begin{minipage}{0.4\textwidth}
  11518. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11519. start:
  11520. movq free_ptr(%rip), tmp9
  11521. movq tmp9, tmp0
  11522. addq $16, tmp0
  11523. movq fromspace_end(%rip), tmp1
  11524. cmpq tmp1, tmp0
  11525. jl block0
  11526. jmp block1
  11527. block0:
  11528. movq $0, _4
  11529. jmp block9
  11530. block1:
  11531. movq %r15, %rdi
  11532. movq $16, %rsi
  11533. callq collect
  11534. jmp block9
  11535. block9:
  11536. movq free_ptr(%rip), %r11
  11537. addq $16, free_ptr(%rip)
  11538. movq $3, 0(%r11)
  11539. movq %r11, alloc2
  11540. movq alloc2, %r11
  11541. movq $42, 8(%r11)
  11542. movq $0, _3
  11543. movq alloc2, vecinit6
  11544. movq free_ptr(%rip), tmp2
  11545. movq tmp2, tmp3
  11546. addq $16, tmp3
  11547. movq fromspace_end(%rip), tmp4
  11548. cmpq tmp4, tmp3
  11549. jl block7
  11550. jmp block8
  11551. block7:
  11552. movq $0, _8
  11553. jmp block6
  11554. block8:
  11555. movq %r15, %rdi
  11556. movq $16, %rsi
  11557. callq collect
  11558. jmp block6
  11559. block6:
  11560. movq free_ptr(%rip), %r11
  11561. addq $16, free_ptr(%rip)
  11562. movq $131, 0(%r11)
  11563. movq %r11, alloc5
  11564. movq alloc5, %r11
  11565. movq vecinit6, 8(%r11)
  11566. movq $0, _7
  11567. movq alloc5, %r11
  11568. movq 8(%r11), tmp5
  11569. movq tmp5, %r11
  11570. movq 8(%r11), %rax
  11571. jmp conclusion
  11572. \end{lstlisting}
  11573. \end{minipage}
  11574. \end{tabular}
  11575. \end{tcolorbox}
  11576. \caption{Output of the \code{explicate\_control} (left)
  11577. and \code{select\_instructions} (right) passes on the running example.}
  11578. \label{fig:select-instr-output-gc}
  11579. \end{figure}
  11580. \clearpage
  11581. \section{Register Allocation}
  11582. \label{sec:reg-alloc-gc}
  11583. \index{subject}{register allocation}
  11584. As discussed earlier in this chapter, the garbage collector needs to
  11585. access all the pointers in the root set, that is, all variables that
  11586. are tuples. It will be the responsibility of the register allocator
  11587. to make sure that:
  11588. \begin{enumerate}
  11589. \item the root stack is used for spilling tuple-typed variables, and
  11590. \item if a tuple-typed variable is live during a call to the
  11591. collector, it must be spilled to ensure it is visible to the
  11592. collector.
  11593. \end{enumerate}
  11594. The later responsibility can be handled during construction of the
  11595. interference graph, by adding interference edges between the call-live
  11596. tuple-typed variables and all the callee-saved registers. (They
  11597. already interfere with the caller-saved registers.)
  11598. %
  11599. \racket{The type information for variables is in the \code{Program}
  11600. form, so we recommend adding another parameter to the
  11601. \code{build\_interference} function to communicate this alist.}
  11602. %
  11603. \python{The type information for variables is generated by the type
  11604. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11605. the \code{CProgram} AST mode. You'll need to propagate that
  11606. information so that it is available in this pass.}
  11607. The spilling of tuple-typed variables to the root stack can be handled
  11608. after graph coloring, when choosing how to assign the colors
  11609. (integers) to registers and stack locations. The
  11610. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11611. changes to also record the number of spills to the root stack.
  11612. % build-interference
  11613. %
  11614. % callq
  11615. % extra parameter for var->type assoc. list
  11616. % update 'program' and 'if'
  11617. % allocate-registers
  11618. % allocate spilled vectors to the rootstack
  11619. % don't change color-graph
  11620. % TODO:
  11621. %\section{Patch Instructions}
  11622. %[mention that global variables are memory references]
  11623. \section{Prelude and Conclusion}
  11624. \label{sec:print-x86-gc}
  11625. \label{sec:prelude-conclusion-x86-gc}
  11626. \index{subject}{prelude}\index{subject}{conclusion}
  11627. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11628. \code{prelude\_and\_conclusion} pass on the running example. In the
  11629. prelude and conclusion of the \code{main} function, we allocate space
  11630. on the root stack to make room for the spills of tuple-typed
  11631. variables. We do so by bumping the root stack pointer (\code{r15})
  11632. taking care that the root stack grows up instead of down. For the
  11633. running example, there was just one spill so we increment \code{r15}
  11634. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  11635. One issue that deserves special care is that there may be a call to
  11636. \code{collect} prior to the initializing assignments for all the
  11637. variables in the root stack. We do not want the garbage collector to
  11638. accidentally think that some uninitialized variable is a pointer that
  11639. needs to be followed. Thus, we zero-out all locations on the root
  11640. stack in the prelude of \code{main}. In
  11641. figure~\ref{fig:print-x86-output-gc}, the instruction
  11642. %
  11643. \lstinline{movq $0, 0(%r15)}
  11644. %
  11645. is sufficient to accomplish this task because there is only one spill.
  11646. In general, we have to clear as many words as there are spills of
  11647. tuple-typed variables. The garbage collector tests each root to see
  11648. if it is null prior to dereferencing it.
  11649. \begin{figure}[htbp]
  11650. % TODO: Python Version -Jeremy
  11651. \begin{tcolorbox}[colback=white]
  11652. \begin{minipage}[t]{0.5\textwidth}
  11653. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11654. .globl main
  11655. main:
  11656. pushq %rbp
  11657. movq %rsp, %rbp
  11658. subq $0, %rsp
  11659. movq $65536, %rdi
  11660. movq $65536, %rsi
  11661. callq initialize
  11662. movq rootstack_begin(%rip), %r15
  11663. movq $0, 0(%r15)
  11664. addq $8, %r15
  11665. jmp start
  11666. conclusion:
  11667. subq $8, %r15
  11668. addq $0, %rsp
  11669. popq %rbp
  11670. retq
  11671. \end{lstlisting}
  11672. \end{minipage}
  11673. \end{tcolorbox}
  11674. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  11675. \label{fig:print-x86-output-gc}
  11676. \end{figure}
  11677. \begin{figure}[tbp]
  11678. \begin{tcolorbox}[colback=white]
  11679. {\if\edition\racketEd
  11680. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11681. \node (Lvec) at (0,2) {\large \LangVec{}};
  11682. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11683. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11684. \node (Lvec-4) at (9,2) {\large \LangAlloc{}};
  11685. \node (Lvec-5) at (9,0) {\large \LangAlloc{}};
  11686. \node (Lvec-6) at (6,0) {\large \LangAllocANF{}};
  11687. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11688. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11689. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11690. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11691. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11692. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11693. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11694. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11695. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11696. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11697. \path[->,bend left=15] (Lvec-4) edge [right] node
  11698. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  11699. \path[->,bend left=15] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex.} (Lvec-6);
  11700. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11701. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11702. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11703. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11704. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11705. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11706. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  11707. \end{tikzpicture}
  11708. \fi}
  11709. {\if\edition\pythonEd
  11710. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11711. \node (Lvec) at (0,2) {\large \LangVec{}};
  11712. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11713. \node (Lvec-5) at (6,2) {\large \LangAlloc{}};
  11714. \node (Lvec-6) at (9,2) {\large \LangAllocANF{}};
  11715. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11716. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11717. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11718. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11719. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11720. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11721. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11722. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11723. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-5);
  11724. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-6);
  11725. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11726. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11727. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11728. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11729. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11730. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11731. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  11732. \end{tikzpicture}
  11733. \fi}
  11734. \end{tcolorbox}
  11735. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11736. \label{fig:Lvec-passes}
  11737. \end{figure}
  11738. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11739. for the compilation of \LangVec{}.
  11740. \clearpage
  11741. {\if\edition\racketEd
  11742. \section{Challenge: Simple Structures}
  11743. \label{sec:simple-structures}
  11744. \index{subject}{struct}
  11745. \index{subject}{structure}
  11746. The language \LangStruct{} extends \LangVec{} with support for simple
  11747. structures. Its concrete syntax is defined in
  11748. figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11749. figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11750. Racket is a user-defined data type that contains named fields and that
  11751. is heap allocated, similar to a vector. The following is an example of
  11752. a structure definition, in this case the definition of a \code{point}
  11753. type.
  11754. \begin{lstlisting}
  11755. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11756. \end{lstlisting}
  11757. \newcommand{\LstructGrammarRacket}{
  11758. \begin{array}{lcl}
  11759. \Type &::=& \Var \\
  11760. \Exp &::=& (\Var\;\Exp \ldots)\\
  11761. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11762. \end{array}
  11763. }
  11764. \newcommand{\LstructASTRacket}{
  11765. \begin{array}{lcl}
  11766. \Type &::=& \VAR{\Var} \\
  11767. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11768. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11769. \end{array}
  11770. }
  11771. \begin{figure}[tbp]
  11772. \centering
  11773. \begin{tcolorbox}[colback=white]
  11774. \[
  11775. \begin{array}{l}
  11776. \gray{\LintGrammarRacket{}} \\ \hline
  11777. \gray{\LvarGrammarRacket{}} \\ \hline
  11778. \gray{\LifGrammarRacket{}} \\ \hline
  11779. \gray{\LwhileGrammarRacket} \\ \hline
  11780. \gray{\LtupGrammarRacket} \\ \hline
  11781. \LstructGrammarRacket \\
  11782. \begin{array}{lcl}
  11783. \LangStruct{} &::=& \Def \ldots \; \Exp
  11784. \end{array}
  11785. \end{array}
  11786. \]
  11787. \end{tcolorbox}
  11788. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11789. (figure~\ref{fig:Lvec-concrete-syntax}).}
  11790. \label{fig:Lstruct-concrete-syntax}
  11791. \end{figure}
  11792. \begin{figure}[tbp]
  11793. \centering
  11794. \begin{tcolorbox}[colback=white]
  11795. \small
  11796. \[
  11797. \begin{array}{l}
  11798. \gray{\LintASTRacket{}} \\ \hline
  11799. \gray{\LvarASTRacket{}} \\ \hline
  11800. \gray{\LifASTRacket{}} \\ \hline
  11801. \gray{\LwhileASTRacket} \\ \hline
  11802. \gray{\LtupASTRacket} \\ \hline
  11803. \LstructASTRacket \\
  11804. \begin{array}{lcl}
  11805. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11806. \end{array}
  11807. \end{array}
  11808. \]
  11809. \end{tcolorbox}
  11810. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11811. (figure~\ref{fig:Lvec-syntax}).}
  11812. \label{fig:Lstruct-syntax}
  11813. \end{figure}
  11814. An instance of a structure is created using function call syntax, with
  11815. the name of the structure in the function position:
  11816. \begin{lstlisting}
  11817. (point 7 12)
  11818. \end{lstlisting}
  11819. Function-call syntax is also used to read a field of a structure. The
  11820. function name is formed by the structure name, a dash, and the field
  11821. name. The following example uses \code{point-x} and \code{point-y} to
  11822. access the \code{x} and \code{y} fields of two point instances.
  11823. \begin{center}
  11824. \begin{lstlisting}
  11825. (let ([pt1 (point 7 12)])
  11826. (let ([pt2 (point 4 3)])
  11827. (+ (- (point-x pt1) (point-x pt2))
  11828. (- (point-y pt1) (point-y pt2)))))
  11829. \end{lstlisting}
  11830. \end{center}
  11831. Similarly, to write to a field of a structure, use its set function,
  11832. whose name starts with \code{set-}, followed by the structure name,
  11833. then a dash, then the field name, and concluded with an exclamation
  11834. mark. The following example uses \code{set-point-x!} to change the
  11835. \code{x} field from \code{7} to \code{42}.
  11836. \begin{center}
  11837. \begin{lstlisting}
  11838. (let ([pt (point 7 12)])
  11839. (let ([_ (set-point-x! pt 42)])
  11840. (point-x pt)))
  11841. \end{lstlisting}
  11842. \end{center}
  11843. \begin{exercise}\normalfont\normalsize
  11844. Create a type checker for \LangStruct{} by extending the type
  11845. checker for \LangVec{}. Extend your compiler with support for simple
  11846. structures, compiling \LangStruct{} to x86 assembly code. Create
  11847. five new test cases that use structures and test your compiler.
  11848. \end{exercise}
  11849. % TODO: create an interpreter for L_struct
  11850. \clearpage
  11851. \fi}
  11852. \section{Challenge: Arrays}
  11853. \label{sec:arrays}
  11854. In this chapter we have studied tuples, that is, a heterogeneous
  11855. sequences of elements whose length is determined at compile-time. This
  11856. challenge is also about sequences, but this time the length is
  11857. determined at run-time and all the elements have the same type (they
  11858. are homogeneous). We use the term ``array'' for this later kind of
  11859. sequence.
  11860. %
  11861. \racket{
  11862. The Racket language does not distinguish between tuples and arrays,
  11863. they are both represented by vectors. However, Typed Racket
  11864. distinguishes between tuples and arrays: the \code{Vector} type is for
  11865. tuples and the \code{Vectorof} type is for arrays.}
  11866. \python{
  11867. Arrays correspond to the \code{list} type in Python language.
  11868. }
  11869. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11870. for \LangArray{} and figure~\ref{fig:Lvecof-syntax} defines the
  11871. abstract syntax, extending \LangVec{} with the
  11872. \racket{\code{Vectorof}}\python{\code{list}} type and the
  11873. %
  11874. \racket{\code{make-vector} primitive operator for creating an array,
  11875. whose arguments are the length of the array and an initial value for
  11876. all the elements in the array.}
  11877. \python{bracket notation for creating an array literal.}
  11878. \racket{
  11879. The \code{vector-length},
  11880. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11881. for tuples become overloaded for use with arrays.}
  11882. \python{
  11883. The subscript operator becomes overloaded for use with arrays and tuples
  11884. and now may appear on the left-hand side of an assignment.
  11885. Note that the index of the subscript, when applied to an array, may be an
  11886. arbitrary expression and not just a constant integer.
  11887. The \code{len} function is also applicable to arrays.
  11888. }
  11889. %
  11890. We include integer multiplication in \LangArray{}, as it is
  11891. useful in many examples involving arrays such as computing the
  11892. inner product of two arrays (figure~\ref{fig:inner_product}).
  11893. \newcommand{\LarrayGrammarRacket}{
  11894. \begin{array}{lcl}
  11895. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11896. \Exp &::=& \CMUL{\Exp}{\Exp}
  11897. \MID \CMAKEVEC{\Exp}{\Exp}
  11898. \end{array}
  11899. }
  11900. \newcommand{\LarrayASTRacket}{
  11901. \begin{array}{lcl}
  11902. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11903. \Exp &::=& \MUL{\Exp}{\Exp}
  11904. \MID \MAKEVEC{\Exp}{\Exp}
  11905. \end{array}
  11906. }
  11907. \newcommand{\LarrayGrammarPython}{
  11908. \begin{array}{lcl}
  11909. \Type &::=& \key{list}\LS\Type\RS \\
  11910. \Exp &::=& \CMUL{\Exp}{\Exp}
  11911. \MID \CGET{\Exp}{\Exp}
  11912. \MID \LS \Exp \code{,} \ldots \RS \\
  11913. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  11914. \end{array}
  11915. }
  11916. \newcommand{\LarrayASTPython}{
  11917. \begin{array}{lcl}
  11918. \Type &::=& \key{ListType}\LP\Type\RP \\
  11919. \Exp &::=& \MUL{\Exp}{\Exp}
  11920. \MID \GET{\Exp}{\Exp} \\
  11921. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  11922. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  11923. \end{array}
  11924. }
  11925. \begin{figure}[tp]
  11926. \centering
  11927. \begin{tcolorbox}[colback=white]
  11928. \small
  11929. {\if\edition\racketEd
  11930. \[
  11931. \begin{array}{l}
  11932. \gray{\LintGrammarRacket{}} \\ \hline
  11933. \gray{\LvarGrammarRacket{}} \\ \hline
  11934. \gray{\LifGrammarRacket{}} \\ \hline
  11935. \gray{\LwhileGrammarRacket} \\ \hline
  11936. \gray{\LtupGrammarRacket} \\ \hline
  11937. \LarrayGrammarRacket \\
  11938. \begin{array}{lcl}
  11939. \LangArray{} &::=& \Exp
  11940. \end{array}
  11941. \end{array}
  11942. \]
  11943. \fi}
  11944. {\if\edition\pythonEd
  11945. \[
  11946. \begin{array}{l}
  11947. \gray{\LintGrammarPython{}} \\ \hline
  11948. \gray{\LvarGrammarPython{}} \\ \hline
  11949. \gray{\LifGrammarPython{}} \\ \hline
  11950. \gray{\LwhileGrammarPython} \\ \hline
  11951. \gray{\LtupGrammarPython} \\ \hline
  11952. \LarrayGrammarPython \\
  11953. \begin{array}{rcl}
  11954. \LangArrayM{} &::=& \Stmt^{*}
  11955. \end{array}
  11956. \end{array}
  11957. \]
  11958. \fi}
  11959. \end{tcolorbox}
  11960. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  11961. \label{fig:Lvecof-concrete-syntax}
  11962. \end{figure}
  11963. \begin{figure}[tp]
  11964. \centering
  11965. \begin{tcolorbox}[colback=white]
  11966. \small
  11967. {\if\edition\racketEd
  11968. \[
  11969. \begin{array}{l}
  11970. \gray{\LintASTRacket{}} \\ \hline
  11971. \gray{\LvarASTRacket{}} \\ \hline
  11972. \gray{\LifASTRacket{}} \\ \hline
  11973. \gray{\LwhileASTRacket} \\ \hline
  11974. \gray{\LtupASTRacket} \\ \hline
  11975. \LarrayASTRacket \\
  11976. \begin{array}{lcl}
  11977. \LangArray{} &::=& \Exp
  11978. \end{array}
  11979. \end{array}
  11980. \]
  11981. \fi}
  11982. {\if\edition\pythonEd
  11983. \[
  11984. \begin{array}{l}
  11985. \gray{\LintASTPython{}} \\ \hline
  11986. \gray{\LvarASTPython{}} \\ \hline
  11987. \gray{\LifASTPython{}} \\ \hline
  11988. \gray{\LwhileASTPython} \\ \hline
  11989. \gray{\LtupASTPython} \\ \hline
  11990. \LarrayASTPython \\
  11991. \begin{array}{rcl}
  11992. \LangArrayM{} &::=& \Stmt^{*}
  11993. \end{array}
  11994. \end{array}
  11995. \]
  11996. \fi}
  11997. \end{tcolorbox}
  11998. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  11999. \label{fig:Lvecof-syntax}
  12000. \end{figure}
  12001. \begin{figure}[tp]
  12002. \begin{tcolorbox}[colback=white]
  12003. {\if\edition\racketEd
  12004. % TODO: remove the function from the following example, like the python version -Jeremy
  12005. \begin{lstlisting}
  12006. (let ([A (make-vector 2 2)])
  12007. (let ([B (make-vector 2 3)])
  12008. (let ([i 0])
  12009. (let ([prod 0])
  12010. (begin
  12011. (while (< i n)
  12012. (begin
  12013. (set! prod (+ prod (* (vector-ref A i)
  12014. (vector-ref B i))))
  12015. (set! i (+ i 1))))
  12016. prod)))))
  12017. \end{lstlisting}
  12018. \fi}
  12019. {\if\edition\pythonEd
  12020. \begin{lstlisting}
  12021. A = [2, 2]
  12022. B = [3, 3]
  12023. i = 0
  12024. prod = 0
  12025. while i != len(A):
  12026. prod = prod + A[i] * B[i]
  12027. i = i + 1
  12028. print( prod )
  12029. \end{lstlisting}
  12030. \fi}
  12031. \end{tcolorbox}
  12032. \caption{Example program that computes the inner product.}
  12033. \label{fig:inner_product}
  12034. \end{figure}
  12035. {\if\edition\racketEd
  12036. The type checker for \LangArray{} is defined in
  12037. figure~\ref{fig:type-check-Lvecof}. The result type of
  12038. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  12039. of the initializing expression. The length expression is required to
  12040. have type \code{Integer}. The type checking of the operators
  12041. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12042. updated to handle the situation where the vector has type
  12043. \code{Vectorof}. In these cases we translate the operators to their
  12044. \code{vectorof} form so that later passes can easily distinguish
  12045. between operations on tuples versus arrays. We override the
  12046. \code{operator-types} method to provide the type signature for
  12047. multiplication: it takes two integers and returns an integer.
  12048. \fi}
  12049. {\if\edition\pythonEd
  12050. %
  12051. The type checker for \LangArray{} is defined in
  12052. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12053. is \code{list[T]} where \code{T} is the type of the initializing
  12054. expressions. The type checking of the \code{len} function and the
  12055. subscript operator is updated to handle lists. The type checker now
  12056. also handles a subscript on the left-hand side of an assignment.
  12057. Regarding multiplication, it takes two integers and returns an
  12058. integer.
  12059. %
  12060. \fi}
  12061. \begin{figure}[tbp]
  12062. \begin{tcolorbox}[colback=white]
  12063. {\if\edition\racketEd
  12064. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12065. (define type-check-Lvecof-class
  12066. (class type-check-Lvec-class
  12067. (super-new)
  12068. (inherit check-type-equal?)
  12069. (define/override (operator-types)
  12070. (append '((* . ((Integer Integer) . Integer)))
  12071. (super operator-types)))
  12072. (define/override (type-check-exp env)
  12073. (lambda (e)
  12074. (define recur (type-check-exp env))
  12075. (match e
  12076. [(Prim 'make-vector (list e1 e2))
  12077. (define-values (e1^ t1) (recur e1))
  12078. (define-values (e2^ elt-type) (recur e2))
  12079. (define vec-type `(Vectorof ,elt-type))
  12080. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  12081. vec-type)]
  12082. [(Prim 'vector-ref (list e1 e2))
  12083. (define-values (e1^ t1) (recur e1))
  12084. (define-values (e2^ t2) (recur e2))
  12085. (match* (t1 t2)
  12086. [(`(Vectorof ,elt-type) 'Integer)
  12087. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12088. [(other wise) ((super type-check-exp env) e)])]
  12089. [(Prim 'vector-set! (list e1 e2 e3) )
  12090. (define-values (e-vec t-vec) (recur e1))
  12091. (define-values (e2^ t2) (recur e2))
  12092. (define-values (e-arg^ t-arg) (recur e3))
  12093. (match t-vec
  12094. [`(Vectorof ,elt-type)
  12095. (check-type-equal? elt-type t-arg e)
  12096. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12097. [else ((super type-check-exp env) e)])]
  12098. [(Prim 'vector-length (list e1))
  12099. (define-values (e1^ t1) (recur e1))
  12100. (match t1
  12101. [`(Vectorof ,t)
  12102. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12103. [else ((super type-check-exp env) e)])]
  12104. [else ((super type-check-exp env) e)])))
  12105. ))
  12106. (define (type-check-Lvecof p)
  12107. (send (new type-check-Lvecof-class) type-check-program p))
  12108. \end{lstlisting}
  12109. \fi}
  12110. {\if\edition\pythonEd
  12111. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12112. class TypeCheckLarray(TypeCheckLtup):
  12113. def type_check_exp(self, e, env):
  12114. match e:
  12115. case ast.List(es, Load()):
  12116. ts = [self.type_check_exp(e, env) for e in es]
  12117. elt_ty = ts[0]
  12118. for (ty, elt) in zip(ts, es):
  12119. self.check_type_equal(elt_ty, ty, elt)
  12120. e.has_type = ListType(elt_ty)
  12121. return e.has_type
  12122. case Call(Name('len'), [tup]):
  12123. tup_t = self.type_check_exp(tup, env)
  12124. tup.has_type = tup_t
  12125. match tup_t:
  12126. case TupleType(ts):
  12127. return IntType()
  12128. case ListType(ty):
  12129. return IntType()
  12130. case _:
  12131. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12132. case Subscript(tup, index, Load()):
  12133. tup_ty = self.type_check_exp(tup, env)
  12134. index_ty = self.type_check_exp(index, env)
  12135. self.check_type_equal(index_ty, IntType(), index)
  12136. match tup_ty:
  12137. case TupleType(ts):
  12138. match index:
  12139. case Constant(i):
  12140. return ts[i]
  12141. case _:
  12142. raise Exception('subscript required constant integer index')
  12143. case ListType(ty):
  12144. return ty
  12145. case _:
  12146. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12147. case BinOp(left, Mult(), right):
  12148. l = self.type_check_exp(left, env)
  12149. self.check_type_equal(l, IntType(), left)
  12150. r = self.type_check_exp(right, env)
  12151. self.check_type_equal(r, IntType(), right)
  12152. return IntType()
  12153. case _:
  12154. return super().type_check_exp(e, env)
  12155. def type_check_stmts(self, ss, env):
  12156. if len(ss) == 0:
  12157. return VoidType()
  12158. match ss[0]:
  12159. case Assign([Subscript(tup, index, Store())], value):
  12160. tup_t = self.type_check_exp(tup, env)
  12161. value_t = self.type_check_exp(value, env)
  12162. index_ty = self.type_check_exp(index, env)
  12163. self.check_type_equal(index_ty, IntType(), index)
  12164. match tup_t:
  12165. case ListType(ty):
  12166. self.check_type_equal(ty, value_t, ss[0])
  12167. case TupleType(ts):
  12168. return self.type_check_stmts(ss, env)
  12169. case _:
  12170. raise Exception('type_check_stmts: '
  12171. 'expected tuple or list, not ' + repr(tup_t))
  12172. return self.type_check_stmts(ss[1:], env)
  12173. case _:
  12174. return super().type_check_stmts(ss, env)
  12175. \end{lstlisting}
  12176. \fi}
  12177. \end{tcolorbox}
  12178. \caption{Type checker for the \LangArray{} language.}
  12179. \label{fig:type-check-Lvecof}
  12180. \end{figure}
  12181. The interpreter for \LangArray{} is defined in
  12182. figure~\ref{fig:interp-Lvecof}.
  12183. \racket{The \code{make-vector} operator is
  12184. implemented with Racket's \code{make-vector} function and
  12185. multiplication is \code{fx*}, multiplication for \code{fixnum}
  12186. integers.}
  12187. %
  12188. \python{We implement list creation with a Python list comprehension
  12189. and multiplication is implemented with Python multiplication. We
  12190. add a case to handle a subscript on the left-hand side of
  12191. assignment. Other uses of subscript can be handled by the existing
  12192. code for tuples.}
  12193. \begin{figure}[tbp]
  12194. \begin{tcolorbox}[colback=white]
  12195. {\if\edition\racketEd
  12196. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12197. (define interp-Lvecof-class
  12198. (class interp-Lvec-class
  12199. (super-new)
  12200. (define/override (interp-op op)
  12201. (match op
  12202. ['make-vector make-vector]
  12203. ['* fx*]
  12204. [else (super interp-op op)]))
  12205. ))
  12206. (define (interp-Lvecof p)
  12207. (send (new interp-Lvecof-class) interp-program p))
  12208. \end{lstlisting}
  12209. \fi}
  12210. {\if\edition\pythonEd
  12211. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12212. class InterpLarray(InterpLtup):
  12213. def interp_exp(self, e, env):
  12214. match e:
  12215. case ast.List(es, Load()):
  12216. return [self.interp_exp(e, env) for e in es]
  12217. case BinOp(left, Mult(), right):
  12218. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  12219. return l * r
  12220. case _:
  12221. return super().interp_exp(e, env)
  12222. def interp_stmts(self, ss, env):
  12223. if len(ss) == 0:
  12224. return
  12225. match ss[0]:
  12226. case Assign([Subscript(lst, index)], value):
  12227. lst = self.interp_exp(lst, env)
  12228. index = self.interp_exp(index, env)
  12229. lst[index] = self.interp_exp(value, env)
  12230. return self.interp_stmts(ss[1:], env)
  12231. case _:
  12232. return super().interp_stmts(ss, env)
  12233. \end{lstlisting}
  12234. \fi}
  12235. \end{tcolorbox}
  12236. \caption{Interpreter for \LangArray{}.}
  12237. \label{fig:interp-Lvecof}
  12238. \end{figure}
  12239. \subsection{Data Representation}
  12240. \label{sec:array-rep}
  12241. Just like tuples, we store arrays on the heap which means that the
  12242. garbage collector will need to inspect arrays. An immediate thought is
  12243. to use the same representation for arrays that we use for tuples.
  12244. However, we limit tuples to a length of $50$ so that their length and
  12245. pointer mask can fit into the 64-bit tag at the beginning of each
  12246. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12247. millions of elements, so we need more bits to store the length.
  12248. However, because arrays are homogeneous, we only need one bit for the
  12249. pointer mask instead of one bit per array element. Finally, the
  12250. garbage collector must be able to distinguish between tuples
  12251. and arrays, so we need to reserve one bit for that purpose. We
  12252. arrive at the following layout for the 64-bit tag at the beginning of
  12253. an array:
  12254. \begin{itemize}
  12255. \item The right-most bit is the forwarding bit, just like in a tuple.
  12256. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  12257. it is not.
  12258. \item The next bit to the left is the pointer mask. A $0$ indicates
  12259. that none of the elements are pointers to the heap and a $1$
  12260. indicates that all of the elements are pointers.
  12261. \item The next $60$ bits store the length of the array.
  12262. \item The bit at position $62$ distinguishes between a tuple ($0$)
  12263. versus an array ($1$).
  12264. \item The left-most bit is reserved for use in chapter~\ref{ch:Lgrad}.
  12265. \end{itemize}
  12266. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  12267. %% differentiate the kinds of values that have been injected into the
  12268. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12269. %% to indicate that the value is an array.
  12270. In the following subsections we provide hints regarding how to update
  12271. the passes to handle arrays.
  12272. \subsection{Overload Resolution}
  12273. \label{sec:array-resolution}
  12274. As noted above, with the addition of arrays, several operators have
  12275. become \emph{overloaded}, that is, they can be applied to values of
  12276. more than one type. In this case, the element access and \code{len}
  12277. operators can be applied to both tuples and arrays. This kind of
  12278. overloading is quite common in programming languages, so many
  12279. compilers perform \emph{overload resolution}\index{subject}{overload resolution}
  12280. to handle it. The idea is to translate each overloaded
  12281. operator into different operators for the different types.
  12282. Implement a new pass named \code{resolve}.
  12283. Translate the reading of an array element
  12284. into a call to
  12285. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  12286. and the writing of an array element to
  12287. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  12288. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  12289. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  12290. When these operators are applied to tuples, leave them as-is.
  12291. %
  12292. \python{The type checker for \LangArray{} adds a \code{has\_type}
  12293. field which can be inspected to determine whether the operator
  12294. is applied to a tuple or an array.}
  12295. \subsection{Bounds Checking}
  12296. We recommend inserting a new pass named \code{check\_bounds} that
  12297. inserts code around each \racket{\code{vector-ref} and \code{vector-set!}}
  12298. \python{subscript} operation to ensure that the index is greater than or
  12299. equal to zero and less than the array's length.
  12300. %% \subsection{Reveal Casts}
  12301. %% The array-access operators \code{vectorof-ref} and
  12302. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12303. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  12304. %% that the type checker cannot tell whether the index will be in bounds,
  12305. %% so the bounds check must be performed at run time. Recall that the
  12306. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  12307. %% an \code{If} arround a vector reference for update to check whether
  12308. %% the index is less than the length. You should do the same for
  12309. %% \code{vectorof-ref} and \code{vectorof-set!} .
  12310. %% In addition, the handling of the \code{any-vector} operators in
  12311. %% \code{reveal-casts} needs to be updated to account for arrays that are
  12312. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  12313. %% generated code should test whether the tag is for tuples (\code{010})
  12314. %% or arrays (\code{110}) and then dispatch to either
  12315. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12316. %% we add a case in \code{select\_instructions} to generate the
  12317. %% appropriate instructions for accessing the array length from the
  12318. %% header of an array.
  12319. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12320. %% the generated code needs to check that the index is less than the
  12321. %% vector length, so like the code for \code{any-vector-length}, check
  12322. %% the tag to determine whether to use \code{any-vector-length} or
  12323. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  12324. %% is complete, the generated code can use \code{any-vector-ref} and
  12325. %% \code{any-vector-set!} for both tuples and arrays because the
  12326. %% instructions used for those operators do not look at the tag at the
  12327. %% front of the tuple or array.
  12328. \subsection{Expose Allocation}
  12329. This pass should translate array creation into lower-level
  12330. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  12331. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  12332. argument must be \ARRAYTY{T} where $T$ is the element type for the
  12333. array. The \code{AllocateArray} AST node allocates an array of the
  12334. length specified by the $\Exp$ (of type \INTTY), but does not initialize the elements of
  12335. the array. Generate code in this pass to initialize the elements
  12336. analogous to the case for tuples.
  12337. \subsection{Remove Complex Operands}
  12338. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  12339. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12340. complex and its subexpression must be atomic.
  12341. \subsection{Explicate Control}
  12342. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  12343. \code{explicate\_assign}.
  12344. \subsection{Select Instructions}
  12345. Generate instructions for \code{AllocateArray} similar to those for
  12346. \code{Allocate} in section~\ref{sec:select-instructions-gc} except
  12347. that the tag at the front of the array should instead use the
  12348. representation discussed in section~\ref{sec:array-rep}.
  12349. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  12350. extract the length from the tag according to the representation discussed in
  12351. section~\ref{sec:array-rep}.
  12352. The instructions generated for accessing an element of an array differ
  12353. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  12354. that the index is not a constant so the offset must be computed at
  12355. runtime.
  12356. %% Also, note that assignment to an array element may appear in
  12357. %% as a stand-alone statement, so make sure to handle that situation in
  12358. %% this pass.
  12359. %% Finally, the instructions for \code{any-vectorof-length} should be
  12360. %% similar to those for \code{vectorof-length}, except that one must
  12361. %% first project the array by writing zeroes into the $3$-bit tag
  12362. \begin{exercise}\normalfont\normalsize
  12363. Implement a compiler for the \LangArray{} language by extending your
  12364. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12365. programs, including the one in figure~\ref{fig:inner_product} and also
  12366. a program that multiplies two matrices. Note that although matrices
  12367. are 2-dimensional arrays, they can be encoded into 1-dimensional
  12368. arrays by laying out each row in the array, one after the next.
  12369. \end{exercise}
  12370. {\if\edition\racketEd
  12371. \section{Challenge: Generational Collection}
  12372. The copying collector described in section~\ref{sec:GC} can incur
  12373. significant runtime overhead because the call to \code{collect} takes
  12374. time proportional to all of the live data. One way to reduce this
  12375. overhead is to reduce how much data is inspected in each call to
  12376. \code{collect}. In particular, researchers have observed that recently
  12377. allocated data is more likely to become garbage then data that has
  12378. survived one or more previous calls to \code{collect}. This insight
  12379. motivated the creation of \emph{generational garbage collectors}
  12380. \index{subject}{generational garbage collector} that
  12381. 1) segregates data according to its age into two or more generations,
  12382. 2) allocates less space for younger generations, so collecting them is
  12383. faster, and more space for the older generations, and 3) performs
  12384. collection on the younger generations more frequently then for older
  12385. generations~\citep{Wilson:1992fk}.
  12386. For this challenge assignment, the goal is to adapt the copying
  12387. collector implemented in \code{runtime.c} to use two generations, one
  12388. for young data and one for old data. Each generation consists of a
  12389. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  12390. \code{collect} function to use the two generations.
  12391. \begin{enumerate}
  12392. \item Copy the young generation's FromSpace to its ToSpace then switch
  12393. the role of the ToSpace and FromSpace
  12394. \item If there is enough space for the requested number of bytes in
  12395. the young FromSpace, then return from \code{collect}.
  12396. \item If there is not enough space in the young FromSpace for the
  12397. requested bytes, then move the data from the young generation to the
  12398. old one with the following steps:
  12399. \begin{enumerate}
  12400. \item If there is enough room in the old FromSpace, copy the young
  12401. FromSpace to the old FromSpace and then return.
  12402. \item If there is not enough room in the old FromSpace, then collect
  12403. the old generation by copying the old FromSpace to the old ToSpace
  12404. and swap the roles of the old FromSpace and ToSpace.
  12405. \item If there is enough room now, copy the young FromSpace to the
  12406. old FromSpace and return. Otherwise, allocate a larger FromSpace
  12407. and ToSpace for the old generation. Copy the young FromSpace and
  12408. the old FromSpace into the larger FromSpace for the old
  12409. generation and then return.
  12410. \end{enumerate}
  12411. \end{enumerate}
  12412. We recommend that you generalize the \code{cheney} function so that it
  12413. can be used for all the copies mentioned above: between the young
  12414. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  12415. between the young FromSpace and old FromSpace. This can be
  12416. accomplished by adding parameters to \code{cheney} that replace its
  12417. use of the global variables \code{fromspace\_begin},
  12418. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  12419. Note that the collection of the young generation does not traverse the
  12420. old generation. This introduces a potential problem: there may be
  12421. young data that is only reachable through pointers in the old
  12422. generation. If these pointers are not taken into account, the
  12423. collector could throw away young data that is live! One solution,
  12424. called \emph{pointer recording}, is to maintain a set of all the
  12425. pointers from the old generation into the new generation and consider
  12426. this set as part of the root set. To maintain this set, the compiler
  12427. must insert extra instructions around every \code{vector-set!}. If the
  12428. vector being modified is in the old generation, and if the value being
  12429. written is a pointer into the new generation, than that pointer must
  12430. be added to the set. Also, if the value being overwritten was a
  12431. pointer into the new generation, then that pointer should be removed
  12432. from the set.
  12433. \begin{exercise}\normalfont\normalsize
  12434. Adapt the \code{collect} function in \code{runtime.c} to implement
  12435. generational garbage collection, as outlined in this section.
  12436. Update the code generation for \code{vector-set!} to implement
  12437. pointer recording. Make sure that your new compiler and runtime
  12438. passes your test suite.
  12439. \end{exercise}
  12440. \fi}
  12441. \section{Further Reading}
  12442. \citet{Appel90} describes many data representation approaches,
  12443. including the ones used in the compilation of Standard ML.
  12444. There are many alternatives to copying collectors (and their bigger
  12445. siblings, the generational collectors) when its comes to garbage
  12446. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12447. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12448. collectors are that allocation is fast (just a comparison and pointer
  12449. increment), there is no fragmentation, cyclic garbage is collected,
  12450. and the time complexity of collection only depends on the amount of
  12451. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12452. main disadvantages of a two-space copying collector is that it uses a
  12453. lot of extra space and takes a long time to perform the copy, though
  12454. these problems are ameliorated in generational collectors.
  12455. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12456. small objects and generate a lot of garbage, so copying and
  12457. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12458. Garbage collection is an active research topic, especially concurrent
  12459. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12460. developing new techniques and revisiting old
  12461. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12462. meet every year at the International Symposium on Memory Management to
  12463. present these findings.
  12464. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12465. \chapter{Functions}
  12466. \label{ch:Lfun}
  12467. \index{subject}{function}
  12468. \setcounter{footnote}{0}
  12469. This chapter studies the compilation of a subset of \racket{Typed
  12470. Racket}\python{Python} in which only top-level function definitions
  12471. are allowed. This kind of function appears in the C programming
  12472. language and it serves as an important stepping stone to implementing
  12473. lexically-scoped functions in the form of \key{lambda} abstractions,
  12474. which is the topic of chapter~\ref{ch:Llambda}.
  12475. \section{The \LangFun{} Language}
  12476. The concrete and abstract syntax for function definitions and function
  12477. application is shown in Figures~\ref{fig:Lfun-concrete-syntax} and
  12478. \ref{fig:Lfun-syntax}, where we define the \LangFun{} language.
  12479. Programs in \LangFun{} begin with zero or more function definitions.
  12480. The function names from these definitions are in-scope for the entire
  12481. program, including all of the function definitions (so the ordering of
  12482. function definitions does not matter).
  12483. %
  12484. \python{The abstract syntax for function parameters in
  12485. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  12486. consists of a parameter name and its type. This design differs from
  12487. Python's \code{ast} module, which has a more complex structure for
  12488. function parameters to handle keyword parameters,
  12489. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12490. complex Python abstract syntax into the simpler syntax of
  12491. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  12492. \code{FunctionDef} constructor are for decorators and a type
  12493. comment, neither of which are used by our compiler. We recommend
  12494. replacing them with \code{None} in the \code{shrink} pass.
  12495. }
  12496. %
  12497. The concrete syntax for function application\index{subject}{function
  12498. application} is
  12499. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12500. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12501. where the first expression
  12502. must evaluate to a function and the remaining expressions are the arguments. The
  12503. abstract syntax for function application is
  12504. $\APPLY{\Exp}{\Exp^*}$.
  12505. %% The syntax for function application does not include an explicit
  12506. %% keyword, which is error prone when using \code{match}. To alleviate
  12507. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12508. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12509. Functions are first-class in the sense that a function pointer
  12510. \index{subject}{function pointer} is data and can be stored in memory or passed
  12511. as a parameter to another function. Thus, there is a function
  12512. type, written
  12513. {\if\edition\racketEd
  12514. \begin{lstlisting}
  12515. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12516. \end{lstlisting}
  12517. \fi}
  12518. {\if\edition\pythonEd
  12519. \begin{lstlisting}
  12520. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12521. \end{lstlisting}
  12522. \fi}
  12523. %
  12524. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12525. through $\Type_n$ and whose return type is $\Type_R$. The main
  12526. limitation of these functions (with respect to
  12527. \racket{Racket}\python{Python} functions) is that they are not
  12528. lexically scoped. That is, the only external entities that can be
  12529. referenced from inside a function body are other globally-defined
  12530. functions. The syntax of \LangFun{} prevents function definitions from being
  12531. nested inside each other.
  12532. \newcommand{\LfunGrammarRacket}{
  12533. \begin{array}{lcl}
  12534. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12535. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12536. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12537. \end{array}
  12538. }
  12539. \newcommand{\LfunASTRacket}{
  12540. \begin{array}{lcl}
  12541. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12542. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12543. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12544. \end{array}
  12545. }
  12546. \newcommand{\LfunGrammarPython}{
  12547. \begin{array}{lcl}
  12548. \Type &::=& \key{int}
  12549. \MID \key{bool} \MID \key{void}
  12550. \MID \key{tuple}\LS \Type^+ \RS
  12551. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12552. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12553. \Stmt &::=& \CRETURN{\Exp} \\
  12554. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12555. \end{array}
  12556. }
  12557. \newcommand{\LfunASTPython}{
  12558. \begin{array}{lcl}
  12559. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  12560. \MID \key{TupleType}\LS\Type^+\RS\\
  12561. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12562. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12563. \Stmt &::=& \RETURN{\Exp} \\
  12564. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  12565. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12566. \end{array}
  12567. }
  12568. \begin{figure}[tp]
  12569. \centering
  12570. \begin{tcolorbox}[colback=white]
  12571. \small
  12572. {\if\edition\racketEd
  12573. \[
  12574. \begin{array}{l}
  12575. \gray{\LintGrammarRacket{}} \\ \hline
  12576. \gray{\LvarGrammarRacket{}} \\ \hline
  12577. \gray{\LifGrammarRacket{}} \\ \hline
  12578. \gray{\LwhileGrammarRacket} \\ \hline
  12579. \gray{\LtupGrammarRacket} \\ \hline
  12580. \LfunGrammarRacket \\
  12581. \begin{array}{lcl}
  12582. \LangFunM{} &::=& \Def \ldots \; \Exp
  12583. \end{array}
  12584. \end{array}
  12585. \]
  12586. \fi}
  12587. {\if\edition\pythonEd
  12588. \[
  12589. \begin{array}{l}
  12590. \gray{\LintGrammarPython{}} \\ \hline
  12591. \gray{\LvarGrammarPython{}} \\ \hline
  12592. \gray{\LifGrammarPython{}} \\ \hline
  12593. \gray{\LwhileGrammarPython} \\ \hline
  12594. \gray{\LtupGrammarPython} \\ \hline
  12595. \LfunGrammarPython \\
  12596. \begin{array}{rcl}
  12597. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12598. \end{array}
  12599. \end{array}
  12600. \]
  12601. \fi}
  12602. \end{tcolorbox}
  12603. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12604. \label{fig:Lfun-concrete-syntax}
  12605. \end{figure}
  12606. \begin{figure}[tp]
  12607. \centering
  12608. \begin{tcolorbox}[colback=white]
  12609. \small
  12610. {\if\edition\racketEd
  12611. \[
  12612. \begin{array}{l}
  12613. \gray{\LintOpAST} \\ \hline
  12614. \gray{\LvarASTRacket{}} \\ \hline
  12615. \gray{\LifASTRacket{}} \\ \hline
  12616. \gray{\LwhileASTRacket{}} \\ \hline
  12617. \gray{\LtupASTRacket{}} \\ \hline
  12618. \LfunASTRacket \\
  12619. \begin{array}{lcl}
  12620. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12621. \end{array}
  12622. \end{array}
  12623. \]
  12624. \fi}
  12625. {\if\edition\pythonEd
  12626. \[
  12627. \begin{array}{l}
  12628. \gray{\LintASTPython{}} \\ \hline
  12629. \gray{\LvarASTPython{}} \\ \hline
  12630. \gray{\LifASTPython{}} \\ \hline
  12631. \gray{\LwhileASTPython} \\ \hline
  12632. \gray{\LtupASTPython} \\ \hline
  12633. \LfunASTPython \\
  12634. \begin{array}{rcl}
  12635. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12636. \end{array}
  12637. \end{array}
  12638. \]
  12639. \fi}
  12640. \end{tcolorbox}
  12641. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12642. \label{fig:Lfun-syntax}
  12643. \end{figure}
  12644. The program in figure~\ref{fig:Lfun-function-example} is a
  12645. representative example of defining and using functions in \LangFun{}.
  12646. We define a function \code{map} that applies some other function
  12647. \code{f} to both elements of a tuple and returns a new tuple
  12648. containing the results. We also define a function \code{inc}. The
  12649. program applies \code{map} to \code{inc} and
  12650. %
  12651. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12652. %
  12653. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12654. %
  12655. from which we return \code{42}.
  12656. \begin{figure}[tbp]
  12657. \begin{tcolorbox}[colback=white]
  12658. {\if\edition\racketEd
  12659. \begin{lstlisting}
  12660. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12661. : (Vector Integer Integer)
  12662. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12663. (define (inc [x : Integer]) : Integer
  12664. (+ x 1))
  12665. (vector-ref (map inc (vector 0 41)) 1)
  12666. \end{lstlisting}
  12667. \fi}
  12668. {\if\edition\pythonEd
  12669. \begin{lstlisting}
  12670. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12671. return f(v[0]), f(v[1])
  12672. def inc(x : int) -> int:
  12673. return x + 1
  12674. print( map(inc, (0, 41))[1] )
  12675. \end{lstlisting}
  12676. \fi}
  12677. \end{tcolorbox}
  12678. \caption{Example of using functions in \LangFun{}.}
  12679. \label{fig:Lfun-function-example}
  12680. \end{figure}
  12681. The definitional interpreter for \LangFun{} is in
  12682. figure~\ref{fig:interp-Lfun}. The case for the
  12683. %
  12684. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12685. %
  12686. AST is responsible for setting up the mutual recursion between the
  12687. top-level function definitions.
  12688. %
  12689. \racket{We use the classic back-patching
  12690. \index{subject}{back-patching} approach that uses mutable variables
  12691. and makes two passes over the function
  12692. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12693. top-level environment using a mutable cons cell for each function
  12694. definition. Note that the \code{lambda} value for each function is
  12695. incomplete; it does not yet include the environment. Once the
  12696. top-level environment is constructed, we then iterate over it and
  12697. update the \code{lambda} values to use the top-level environment.}
  12698. %
  12699. \python{We create a dictionary named \code{env} and fill it in
  12700. by mapping each function name to a new \code{Function} value,
  12701. each of which stores a reference to the \code{env}.
  12702. (We define the class \code{Function} for this purpose.)}
  12703. %
  12704. To interpret a function \racket{application}\python{call}, we match
  12705. the result of the function expression to obtain a function value. We
  12706. then extend the function's environment with the mapping of parameters to
  12707. argument values. Finally, we interpret the body of the function in
  12708. this extended environment.
  12709. \begin{figure}[tp]
  12710. \begin{tcolorbox}[colback=white]
  12711. {\if\edition\racketEd
  12712. \begin{lstlisting}
  12713. (define interp-Lfun-class
  12714. (class interp-Lvec-class
  12715. (super-new)
  12716. (define/override ((interp-exp env) e)
  12717. (define recur (interp-exp env))
  12718. (match e
  12719. [(Apply fun args)
  12720. (define fun-val (recur fun))
  12721. (define arg-vals (for/list ([e args]) (recur e)))
  12722. (match fun-val
  12723. [`(function (,xs ...) ,body ,fun-env)
  12724. (define params-args (for/list ([x xs] [arg arg-vals])
  12725. (cons x (box arg))))
  12726. (define new-env (append params-args fun-env))
  12727. ((interp-exp new-env) body)]
  12728. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12729. [else ((super interp-exp env) e)]
  12730. ))
  12731. (define/public (interp-def d)
  12732. (match d
  12733. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12734. (cons f (box `(function ,xs ,body ())))]))
  12735. (define/override (interp-program p)
  12736. (match p
  12737. [(ProgramDefsExp info ds body)
  12738. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12739. (for/list ([f (in-dict-values top-level)])
  12740. (set-box! f (match (unbox f)
  12741. [`(function ,xs ,body ())
  12742. `(function ,xs ,body ,top-level)])))
  12743. ((interp-exp top-level) body))]))
  12744. ))
  12745. (define (interp-Lfun p)
  12746. (send (new interp-Lfun-class) interp-program p))
  12747. \end{lstlisting}
  12748. \fi}
  12749. {\if\edition\pythonEd
  12750. \begin{lstlisting}
  12751. class InterpLfun(InterpLtup):
  12752. def apply_fun(self, fun, args, e):
  12753. match fun:
  12754. case Function(name, xs, body, env):
  12755. new_env = env.copy().update(zip(xs, args))
  12756. return self.interp_stmts(body, new_env)
  12757. case _:
  12758. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12759. def interp_exp(self, e, env):
  12760. match e:
  12761. case Call(Name('input_int'), []):
  12762. return super().interp_exp(e, env)
  12763. case Call(func, args):
  12764. f = self.interp_exp(func, env)
  12765. vs = [self.interp_exp(arg, env) for arg in args]
  12766. return self.apply_fun(f, vs, e)
  12767. case _:
  12768. return super().interp_exp(e, env)
  12769. def interp_stmts(self, ss, env):
  12770. if len(ss) == 0:
  12771. return
  12772. match ss[0]:
  12773. case Return(value):
  12774. return self.interp_exp(value, env)
  12775. case FunctionDef(name, params, bod, dl, returns, comment):
  12776. ps = [x for (x,t) in params]
  12777. env[name] = Function(name, ps, bod, env)
  12778. return self.interp_stmts(ss[1:], env)
  12779. case _:
  12780. return super().interp_stmts(ss, env)
  12781. def interp(self, p):
  12782. match p:
  12783. case Module(ss):
  12784. env = {}
  12785. self.interp_stmts(ss, env)
  12786. if 'main' in env.keys():
  12787. self.apply_fun(env['main'], [], None)
  12788. case _:
  12789. raise Exception('interp: unexpected ' + repr(p))
  12790. \end{lstlisting}
  12791. \fi}
  12792. \end{tcolorbox}
  12793. \caption{Interpreter for the \LangFun{} language.}
  12794. \label{fig:interp-Lfun}
  12795. \end{figure}
  12796. %\margincomment{TODO: explain type checker}
  12797. The type checker for \LangFun{} is in
  12798. figure~\ref{fig:type-check-Lfun}.
  12799. %
  12800. \python{(We omit the code that parses function parameters into the
  12801. simpler abstract syntax.)}
  12802. %
  12803. Similar to the interpreter, the case for the
  12804. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12805. %
  12806. AST is responsible for setting up the mutual recursion between the
  12807. top-level function definitions. We begin by create a mapping
  12808. \code{env} from every function name to its type. We then type check
  12809. the program using this mapping.
  12810. %
  12811. In the case for function \racket{application}\python{call}, we match
  12812. the type of the function expression to a function type and check that
  12813. the types of the argument expressions are equal to the function's
  12814. parameter types. The type of the \racket{application}\python{call} as
  12815. a whole is the return type from the function type.
  12816. \begin{figure}[tp]
  12817. \begin{tcolorbox}[colback=white]
  12818. {\if\edition\racketEd
  12819. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12820. (define type-check-Lfun-class
  12821. (class type-check-Lvec-class
  12822. (super-new)
  12823. (inherit check-type-equal?)
  12824. (define/public (type-check-apply env e es)
  12825. (define-values (e^ ty) ((type-check-exp env) e))
  12826. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12827. ((type-check-exp env) e)))
  12828. (match ty
  12829. [`(,ty^* ... -> ,rt)
  12830. (for ([arg-ty ty*] [param-ty ty^*])
  12831. (check-type-equal? arg-ty param-ty (Apply e es)))
  12832. (values e^ e* rt)]))
  12833. (define/override (type-check-exp env)
  12834. (lambda (e)
  12835. (match e
  12836. [(FunRef f n)
  12837. (values (FunRef f n) (dict-ref env f))]
  12838. [(Apply e es)
  12839. (define-values (e^ es^ rt) (type-check-apply env e es))
  12840. (values (Apply e^ es^) rt)]
  12841. [(Call e es)
  12842. (define-values (e^ es^ rt) (type-check-apply env e es))
  12843. (values (Call e^ es^) rt)]
  12844. [else ((super type-check-exp env) e)])))
  12845. (define/public (type-check-def env)
  12846. (lambda (e)
  12847. (match e
  12848. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12849. (define new-env (append (map cons xs ps) env))
  12850. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12851. (check-type-equal? ty^ rt body)
  12852. (Def f p:t* rt info body^)])))
  12853. (define/public (fun-def-type d)
  12854. (match d
  12855. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12856. (define/override (type-check-program e)
  12857. (match e
  12858. [(ProgramDefsExp info ds body)
  12859. (define env (for/list ([d ds])
  12860. (cons (Def-name d) (fun-def-type d))))
  12861. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12862. (define-values (body^ ty) ((type-check-exp env) body))
  12863. (check-type-equal? ty 'Integer body)
  12864. (ProgramDefsExp info ds^ body^)]))))
  12865. (define (type-check-Lfun p)
  12866. (send (new type-check-Lfun-class) type-check-program p))
  12867. \end{lstlisting}
  12868. \fi}
  12869. {\if\edition\pythonEd
  12870. \begin{lstlisting}
  12871. class TypeCheckLfun(TypeCheckLtup):
  12872. def type_check_exp(self, e, env):
  12873. match e:
  12874. case Call(Name('input_int'), []):
  12875. return super().type_check_exp(e, env)
  12876. case Call(func, args):
  12877. func_t = self.type_check_exp(func, env)
  12878. args_t = [self.type_check_exp(arg, env) for arg in args]
  12879. match func_t:
  12880. case FunctionType(params_t, return_t):
  12881. for (arg_t, param_t) in zip(args_t, params_t):
  12882. check_type_equal(param_t, arg_t, e)
  12883. return return_t
  12884. case _:
  12885. raise Exception('type_check_exp: in call, unexpected ' +
  12886. repr(func_t))
  12887. case _:
  12888. return super().type_check_exp(e, env)
  12889. def type_check_stmts(self, ss, env):
  12890. if len(ss) == 0:
  12891. return
  12892. match ss[0]:
  12893. case FunctionDef(name, params, body, dl, returns, comment):
  12894. new_env = env.copy().update(params)
  12895. rt = self.type_check_stmts(body, new_env)
  12896. check_type_equal(returns, rt, ss[0])
  12897. return self.type_check_stmts(ss[1:], env)
  12898. case Return(value):
  12899. return self.type_check_exp(value, env)
  12900. case _:
  12901. return super().type_check_stmts(ss, env)
  12902. def type_check(self, p):
  12903. match p:
  12904. case Module(body):
  12905. env = {}
  12906. for s in body:
  12907. match s:
  12908. case FunctionDef(name, params, bod, dl, returns, comment):
  12909. if name in env:
  12910. raise Exception('type_check: function ' +
  12911. repr(name) + ' defined twice')
  12912. params_t = [t for (x,t) in params]
  12913. env[name] = FunctionType(params_t, returns)
  12914. self.type_check_stmts(body, env)
  12915. case _:
  12916. raise Exception('type_check: unexpected ' + repr(p))
  12917. \end{lstlisting}
  12918. \fi}
  12919. \end{tcolorbox}
  12920. \caption{Type checker for the \LangFun{} language.}
  12921. \label{fig:type-check-Lfun}
  12922. \end{figure}
  12923. \clearpage
  12924. \section{Functions in x86}
  12925. \label{sec:fun-x86}
  12926. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12927. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12928. %% \margincomment{\tiny Talk about the return address on the
  12929. %% stack and what callq and retq does.\\ --Jeremy }
  12930. The x86 architecture provides a few features to support the
  12931. implementation of functions. We have already seen that there are
  12932. labels in x86 so that one can refer to the location of an instruction,
  12933. as is needed for jump instructions. Labels can also be used to mark
  12934. the beginning of the instructions for a function. Going further, we
  12935. can obtain the address of a label by using the \key{leaq}
  12936. instruction. For example, the following puts the address of the
  12937. \code{inc} label into the \code{rbx} register.
  12938. \begin{lstlisting}
  12939. leaq inc(%rip), %rbx
  12940. \end{lstlisting}
  12941. Recall from section~\ref{sec:select-instructions-gc} that
  12942. \verb!inc(%rip)! is an example of instruction-pointer relative
  12943. addressing.
  12944. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12945. to functions whose locations were given by a label, such as
  12946. \code{read\_int}. To support function calls in this chapter we instead
  12947. will be jumping to functions whose location are given by an address in
  12948. a register, that is, we shall use \emph{indirect function calls}. The
  12949. x86 syntax for this is a \code{callq} instruction but with an asterisk
  12950. before the register name.\index{subject}{indirect function call}
  12951. \begin{lstlisting}
  12952. callq *%rbx
  12953. \end{lstlisting}
  12954. \subsection{Calling Conventions}
  12955. \label{sec:calling-conventions-fun}
  12956. \index{subject}{calling conventions}
  12957. The \code{callq} instruction provides partial support for implementing
  12958. functions: it pushes the return address on the stack and it jumps to
  12959. the target. However, \code{callq} does not handle
  12960. \begin{enumerate}
  12961. \item parameter passing,
  12962. \item pushing frames on the procedure call stack and popping them off,
  12963. or
  12964. \item determining how registers are shared by different functions.
  12965. \end{enumerate}
  12966. Regarding parameter passing, recall that the x86-64 calling
  12967. convention for Unix-based system uses the following six registers to
  12968. pass arguments to a function, in this order.
  12969. \begin{lstlisting}
  12970. rdi rsi rdx rcx r8 r9
  12971. \end{lstlisting}
  12972. If there are more than six arguments, then the calling convention
  12973. mandates using space on the frame of the caller for the rest of the
  12974. arguments. However, to ease the implementation of efficient tail calls
  12975. (section~\ref{sec:tail-call}), we arrange never to need more than six
  12976. arguments.
  12977. %
  12978. The return value of the function is stored in register \code{rax}.
  12979. \index{subject}{prelude}\index{subject}{conclusion}
  12980. Regarding frames \index{subject}{frame} and the procedure call stack,
  12981. \index{subject}{procedure call stack} recall from
  12982. section~\ref{sec:x86} that the stack grows down and each function call
  12983. uses a chunk of space on the stack called a frame. The caller sets the
  12984. stack pointer, register \code{rsp}, to the last data item in its
  12985. frame. The callee must not change anything in the caller's frame, that
  12986. is, anything that is at or above the stack pointer. The callee is free
  12987. to use locations that are below the stack pointer.
  12988. Recall that we store variables of tuple type on the root stack. So
  12989. the prelude of a function needs to move the root stack pointer
  12990. \code{r15} up according to the number of variables of tuple type and
  12991. the conclusion needs to move the root stack pointer back down. Also,
  12992. the prelude must initialize to \code{0} this frame's slots in the root
  12993. stack to signal to the garbage collector that those slots do not yet
  12994. contain a valid pointer. Otherwise the garbage collector will
  12995. interpret the garbage bits in those slots as memory addresses and try
  12996. to traverse them, causing serious mayhem!
  12997. Regarding the sharing of registers between different functions, recall
  12998. from section~\ref{sec:calling-conventions} that the registers are
  12999. divided into two groups, the caller-saved registers and the
  13000. callee-saved registers. The caller should assume that all the
  13001. caller-saved registers get overwritten with arbitrary values by the
  13002. callee. For that reason we recommend in
  13003. section~\ref{sec:calling-conventions} that variables that are live
  13004. during a function call should not be assigned to caller-saved
  13005. registers.
  13006. On the flip side, if the callee wants to use a callee-saved register,
  13007. the callee must save the contents of those registers on their stack
  13008. frame and then put them back prior to returning to the caller. For
  13009. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13010. the register allocator assigns a variable to a callee-saved register,
  13011. then the prelude of the \code{main} function must save that register
  13012. to the stack and the conclusion of \code{main} must restore it. This
  13013. recommendation now generalizes to all functions.
  13014. Recall that the base pointer, register \code{rbp}, is used as a
  13015. point-of-reference within a frame, so that each local variable can be
  13016. accessed at a fixed offset from the base pointer
  13017. (section~\ref{sec:x86}).
  13018. %
  13019. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13020. and callee frames.
  13021. \begin{figure}[tbp]
  13022. \centering
  13023. \begin{tcolorbox}[colback=white]
  13024. \begin{tabular}{r|r|l|l} \hline
  13025. Caller View & Callee View & Contents & Frame \\ \hline
  13026. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13027. 0(\key{\%rbp}) & & old \key{rbp} \\
  13028. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13029. \ldots & & \ldots \\
  13030. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13031. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13032. \ldots & & \ldots \\
  13033. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13034. %% & & \\
  13035. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13036. %% & \ldots & \ldots \\
  13037. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13038. \hline
  13039. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13040. & 0(\key{\%rbp}) & old \key{rbp} \\
  13041. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13042. & \ldots & \ldots \\
  13043. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13044. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13045. & \ldots & \ldots \\
  13046. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13047. \end{tabular}
  13048. \end{tcolorbox}
  13049. \caption{Memory layout of caller and callee frames.}
  13050. \label{fig:call-frames}
  13051. \end{figure}
  13052. %% Recall from section~\ref{sec:x86} that the stack is also used for
  13053. %% local variables and for storing the values of callee-saved registers
  13054. %% (we shall refer to all of these collectively as ``locals''), and that
  13055. %% at the beginning of a function we move the stack pointer \code{rsp}
  13056. %% down to make room for them.
  13057. %% We recommend storing the local variables
  13058. %% first and then the callee-saved registers, so that the local variables
  13059. %% can be accessed using \code{rbp} the same as before the addition of
  13060. %% functions.
  13061. %% To make additional room for passing arguments, we shall
  13062. %% move the stack pointer even further down. We count how many stack
  13063. %% arguments are needed for each function call that occurs inside the
  13064. %% body of the function and find their maximum. Adding this number to the
  13065. %% number of locals gives us how much the \code{rsp} should be moved at
  13066. %% the beginning of the function. In preparation for a function call, we
  13067. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13068. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13069. %% so on.
  13070. %% Upon calling the function, the stack arguments are retrieved by the
  13071. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13072. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13073. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13074. %% the layout of the caller and callee frames. Notice how important it is
  13075. %% that we correctly compute the maximum number of arguments needed for
  13076. %% function calls; if that number is too small then the arguments and
  13077. %% local variables will smash into each other!
  13078. \subsection{Efficient Tail Calls}
  13079. \label{sec:tail-call}
  13080. In general, the amount of stack space used by a program is determined
  13081. by the longest chain of nested function calls. That is, if function
  13082. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13083. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13084. large if functions are recursive. However, in some cases we can
  13085. arrange to use only a constant amount of space for a long chain of
  13086. nested function calls.
  13087. A \emph{tail call}\index{subject}{tail call} is a function call that
  13088. happens as the last action in a function body.
  13089. For example, in the following
  13090. program, the recursive call to \code{tail\_sum} is a tail call.
  13091. \begin{center}
  13092. {\if\edition\racketEd
  13093. \begin{lstlisting}
  13094. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13095. (if (eq? n 0)
  13096. r
  13097. (tail_sum (- n 1) (+ n r))))
  13098. (+ (tail_sum 3 0) 36)
  13099. \end{lstlisting}
  13100. \fi}
  13101. {\if\edition\pythonEd
  13102. \begin{lstlisting}
  13103. def tail_sum(n : int, r : int) -> int:
  13104. if n == 0:
  13105. return r
  13106. else:
  13107. return tail_sum(n - 1, n + r)
  13108. print( tail_sum(3, 0) + 36)
  13109. \end{lstlisting}
  13110. \fi}
  13111. \end{center}
  13112. At a tail call, the frame of the caller is no longer needed, so we can
  13113. pop the caller's frame before making the tail call. With this
  13114. approach, a recursive function that only makes tail calls ends up
  13115. using a constant amount of stack space. Functional languages like
  13116. Racket rely heavily on recursive functions, so the definition of
  13117. Racket \emph{requires} that all tail calls be optimized in this way.
  13118. \index{subject}{frame}
  13119. Some care is needed with regards to argument passing in tail calls.
  13120. As mentioned above, for arguments beyond the sixth, the convention is
  13121. to use space in the caller's frame for passing arguments. But for a
  13122. tail call we pop the caller's frame and can no longer use it. An
  13123. alternative is to use space in the callee's frame for passing
  13124. arguments. However, this option is also problematic because the caller
  13125. and callee's frames overlap in memory. As we begin to copy the
  13126. arguments from their sources in the caller's frame, the target
  13127. locations in the callee's frame might collide with the sources for
  13128. later arguments! We solve this problem by using the heap instead of
  13129. the stack for passing more than six arguments
  13130. (section~\ref{sec:limit-functions-r4}).
  13131. As mentioned above, for a tail call we pop the caller's frame prior to
  13132. making the tail call. The instructions for popping a frame are the
  13133. instructions that we usually place in the conclusion of a
  13134. function. Thus, we also need to place such code immediately before
  13135. each tail call. These instructions include restoring the callee-saved
  13136. registers, so it is fortunate that the argument passing registers are
  13137. all caller-saved registers!
  13138. One last note regarding which instruction to use to make the tail
  13139. call. When the callee is finished, it should not return to the current
  13140. function, but it should return to the function that called the current
  13141. one. Thus, the return address that is already on the stack is the
  13142. right one and we should not use \key{callq} to make the tail call, as
  13143. that would overwrite the return address. Instead we simply use the
  13144. \key{jmp} instruction. Like the indirect function call, we write an
  13145. \emph{indirect jump}\index{subject}{indirect jump} with a register
  13146. prefixed with an asterisk. We recommend using \code{rax} to hold the
  13147. jump target because the conclusion can overwrite just about everything
  13148. else.
  13149. \begin{lstlisting}
  13150. jmp *%rax
  13151. \end{lstlisting}
  13152. \section{Shrink \LangFun{}}
  13153. \label{sec:shrink-r4}
  13154. The \code{shrink} pass performs a minor modification to ease the
  13155. later passes. This pass introduces an explicit \code{main} function
  13156. that gobbles up all the top-level statements of the module.
  13157. %
  13158. \racket{It also changes the top \code{ProgramDefsExp} form to
  13159. \code{ProgramDefs}.}
  13160. {\if\edition\racketEd
  13161. \begin{lstlisting}
  13162. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  13163. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  13164. \end{lstlisting}
  13165. where $\itm{mainDef}$ is
  13166. \begin{lstlisting}
  13167. (Def 'main '() 'Integer '() |$\Exp'$|)
  13168. \end{lstlisting}
  13169. \fi}
  13170. {\if\edition\pythonEd
  13171. \begin{lstlisting}
  13172. Module(|$\Def\ldots\Stmt\ldots$|)
  13173. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  13174. \end{lstlisting}
  13175. where $\itm{mainDef}$ is
  13176. \begin{lstlisting}
  13177. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  13178. \end{lstlisting}
  13179. \fi}
  13180. \section{Reveal Functions and the \LangFunRef{} language}
  13181. \label{sec:reveal-functions-r4}
  13182. The syntax of \LangFun{} is inconvenient for purposes of compilation
  13183. in that it conflates the use of function names and local
  13184. variables. This is a problem because we need to compile the use of a
  13185. function name differently than the use of a local variable. In
  13186. particular, we use \code{leaq} to convert the function name (a label
  13187. in x86) to an address in a register. Thus, we create a new pass that
  13188. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  13189. $n$ is the arity of the function.\python{\footnote{The arity is not
  13190. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  13191. This pass is named \code{reveal\_functions} and the output language
  13192. is \LangFunRef{}.
  13193. %is defined in figure~\ref{fig:f1-syntax}.
  13194. %% The concrete syntax for a
  13195. %% function reference is $\CFUNREF{f}$.
  13196. %% \begin{figure}[tp]
  13197. %% \centering
  13198. %% \fbox{
  13199. %% \begin{minipage}{0.96\textwidth}
  13200. %% {\if\edition\racketEd
  13201. %% \[
  13202. %% \begin{array}{lcl}
  13203. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  13204. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13205. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  13206. %% \end{array}
  13207. %% \]
  13208. %% \fi}
  13209. %% {\if\edition\pythonEd
  13210. %% \[
  13211. %% \begin{array}{lcl}
  13212. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  13213. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  13214. %% \end{array}
  13215. %% \]
  13216. %% \fi}
  13217. %% \end{minipage}
  13218. %% }
  13219. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  13220. %% (figure~\ref{fig:Lfun-syntax}).}
  13221. %% \label{fig:f1-syntax}
  13222. %% \end{figure}
  13223. %% Distinguishing between calls in tail position and non-tail position
  13224. %% requires the pass to have some notion of context. We recommend using
  13225. %% two mutually recursive functions, one for processing expressions in
  13226. %% tail position and another for the rest.
  13227. \racket{Placing this pass after \code{uniquify} will make sure that
  13228. there are no local variables and functions that share the same
  13229. name.}
  13230. %
  13231. The \code{reveal\_functions} pass should come before the
  13232. \code{remove\_complex\_operands} pass because function references
  13233. should be categorized as complex expressions.
  13234. \section{Limit Functions}
  13235. \label{sec:limit-functions-r4}
  13236. Recall that we wish to limit the number of function parameters to six
  13237. so that we do not need to use the stack for argument passing, which
  13238. makes it easier to implement efficient tail calls. However, because
  13239. the input language \LangFun{} supports arbitrary numbers of function
  13240. arguments, we have some work to do! The \code{limit\_functions} pass
  13241. transforms functions and function calls that involve more than six
  13242. arguments to pass the first five arguments as usual, but it packs the
  13243. rest of the arguments into a tuple and passes it as the sixth
  13244. argument.\footnote{The implementation this pass can be postponed to
  13245. last because you can test the rest of the passes on functions with
  13246. six or fewer parameters.}
  13247. Each function definition with seven or more parameters is transformed as
  13248. follows.
  13249. {\if\edition\racketEd
  13250. \begin{lstlisting}
  13251. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  13252. |$\Rightarrow$|
  13253. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  13254. \end{lstlisting}
  13255. \fi}
  13256. {\if\edition\pythonEd
  13257. \begin{lstlisting}
  13258. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  13259. |$\Rightarrow$|
  13260. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  13261. |$T_r$|, None, |$\itm{body}'$|, None)
  13262. \end{lstlisting}
  13263. \fi}
  13264. %
  13265. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  13266. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  13267. the $k$th element of the tuple, where $k = i - 6$.
  13268. %
  13269. {\if\edition\racketEd
  13270. \begin{lstlisting}
  13271. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  13272. \end{lstlisting}
  13273. \fi}
  13274. {\if\edition\pythonEd
  13275. \begin{lstlisting}
  13276. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  13277. \end{lstlisting}
  13278. \fi}
  13279. For function calls with too many arguments, the \code{limit\_functions}
  13280. pass transforms them in the following way.
  13281. \begin{tabular}{lll}
  13282. \begin{minipage}{0.3\textwidth}
  13283. {\if\edition\racketEd
  13284. \begin{lstlisting}
  13285. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  13286. \end{lstlisting}
  13287. \fi}
  13288. {\if\edition\pythonEd
  13289. \begin{lstlisting}
  13290. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  13291. \end{lstlisting}
  13292. \fi}
  13293. \end{minipage}
  13294. &
  13295. $\Rightarrow$
  13296. &
  13297. \begin{minipage}{0.5\textwidth}
  13298. {\if\edition\racketEd
  13299. \begin{lstlisting}
  13300. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  13301. \end{lstlisting}
  13302. \fi}
  13303. {\if\edition\pythonEd
  13304. \begin{lstlisting}
  13305. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  13306. \end{lstlisting}
  13307. \fi}
  13308. \end{minipage}
  13309. \end{tabular}
  13310. \section{Remove Complex Operands}
  13311. \label{sec:rco-r4}
  13312. The primary decisions to make for this pass are whether to classify
  13313. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  13314. atomic or complex expressions. Recall that an atomic expression will
  13315. end up as an immediate argument of an x86 instruction. Function
  13316. application will be translated to a sequence of instructions, so
  13317. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  13318. complex expression. On the other hand, the arguments of
  13319. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  13320. expressions.
  13321. %
  13322. Regarding \code{FunRef}, as discussed above, the function label needs
  13323. to be converted to an address using the \code{leaq} instruction. Thus,
  13324. even though \code{FunRef} seems rather simple, it needs to be
  13325. classified as a complex expression so that we generate an assignment
  13326. statement with a left-hand side that can serve as the target of the
  13327. \code{leaq}.
  13328. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  13329. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  13330. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  13331. and augments programs to include a list of function definitions.
  13332. %
  13333. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  13334. \newcommand{\LfunMonadASTRacket}{
  13335. \begin{array}{lcl}
  13336. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13337. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13338. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13339. \end{array}
  13340. }
  13341. \newcommand{\LfunMonadASTPython}{
  13342. \begin{array}{lcl}
  13343. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  13344. \MID \key{TupleType}\LS\Type^+\RS\\
  13345. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13346. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  13347. \Stmt &::=& \RETURN{\Exp} \\
  13348. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13349. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13350. \end{array}
  13351. }
  13352. \begin{figure}[tp]
  13353. \centering
  13354. \begin{tcolorbox}[colback=white]
  13355. \small
  13356. {\if\edition\racketEd
  13357. \[
  13358. \begin{array}{l}
  13359. \gray{\LvarMonadASTRacket} \\ \hline
  13360. \gray{\LifMonadASTRacket} \\ \hline
  13361. \gray{\LwhileMonadASTRacket} \\ \hline
  13362. \gray{\LtupMonadASTRacket} \\ \hline
  13363. \LfunMonadASTRacket \\
  13364. \begin{array}{rcl}
  13365. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13366. \end{array}
  13367. \end{array}
  13368. \]
  13369. \fi}
  13370. {\if\edition\pythonEd
  13371. \[
  13372. \begin{array}{l}
  13373. \gray{\LvarMonadASTPython} \\ \hline
  13374. \gray{\LifMonadASTPython} \\ \hline
  13375. \gray{\LwhileMonadASTPython} \\ \hline
  13376. \gray{\LtupMonadASTPython} \\ \hline
  13377. \LfunMonadASTPython \\
  13378. \begin{array}{rcl}
  13379. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13380. \end{array}
  13381. \end{array}
  13382. \]
  13383. \fi}
  13384. \end{tcolorbox}
  13385. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  13386. \label{fig:Lfun-anf-syntax}
  13387. \end{figure}
  13388. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  13389. %% \LangFunANF{} of this pass.
  13390. %% \begin{figure}[tp]
  13391. %% \centering
  13392. %% \fbox{
  13393. %% \begin{minipage}{0.96\textwidth}
  13394. %% \small
  13395. %% \[
  13396. %% \begin{array}{rcl}
  13397. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  13398. %% \MID \VOID{} } \\
  13399. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  13400. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  13401. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  13402. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  13403. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  13404. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  13405. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  13406. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13407. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13408. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  13409. %% \end{array}
  13410. %% \]
  13411. %% \end{minipage}
  13412. %% }
  13413. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  13414. %% \label{fig:Lfun-anf-syntax}
  13415. %% \end{figure}
  13416. \section{Explicate Control and the \LangCFun{} language}
  13417. \label{sec:explicate-control-r4}
  13418. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  13419. output of \code{explicate\_control}.
  13420. %
  13421. %% \racket{(The concrete syntax is given in
  13422. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  13423. %
  13424. The auxiliary functions for assignment\racket{ and tail contexts} should
  13425. be updated with cases for
  13426. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  13427. function for predicate context should be updated for
  13428. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  13429. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  13430. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  13431. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  13432. auxiliary function for processing function definitions. This code is
  13433. similar to the case for \code{Program} in \LangVec{}. The top-level
  13434. \code{explicate\_control} function that handles the \code{ProgramDefs}
  13435. form of \LangFun{} can then apply this new function to all the
  13436. function definitions.
  13437. {\if\edition\pythonEd
  13438. The translation of \code{Return} statements requires a new auxiliary
  13439. function to handle expressions in tail context, called
  13440. \code{explicate\_tail}. The function should take an expression and the
  13441. dictionary of basic blocks and produce a list of statements in the
  13442. \LangCFun{} language. The \code{explicate\_tail} function should
  13443. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  13444. and a default case for other kinds of expressions. The default case
  13445. should produce a \code{Return} statement. The case for \code{Call}
  13446. should change it into \code{TailCall}. The other cases should
  13447. recursively process their subexpressions and statements, choosing the
  13448. appropriate explicate functions for the various contexts.
  13449. \fi}
  13450. \newcommand{\CfunASTRacket}{
  13451. \begin{array}{lcl}
  13452. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  13453. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  13454. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  13455. \end{array}
  13456. }
  13457. \newcommand{\CfunASTPython}{
  13458. \begin{array}{lcl}
  13459. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  13460. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  13461. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  13462. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  13463. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  13464. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  13465. \end{array}
  13466. }
  13467. \begin{figure}[tp]
  13468. \begin{tcolorbox}[colback=white]
  13469. \small
  13470. {\if\edition\racketEd
  13471. \[
  13472. \begin{array}{l}
  13473. \gray{\CvarASTRacket} \\ \hline
  13474. \gray{\CifASTRacket} \\ \hline
  13475. \gray{\CloopASTRacket} \\ \hline
  13476. \gray{\CtupASTRacket} \\ \hline
  13477. \CfunASTRacket \\
  13478. \begin{array}{lcl}
  13479. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13480. \end{array}
  13481. \end{array}
  13482. \]
  13483. \fi}
  13484. {\if\edition\pythonEd
  13485. \[
  13486. \begin{array}{l}
  13487. \gray{\CifASTPython} \\ \hline
  13488. \gray{\CtupASTPython} \\ \hline
  13489. \CfunASTPython \\
  13490. \begin{array}{lcl}
  13491. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13492. \end{array}
  13493. \end{array}
  13494. \]
  13495. \fi}
  13496. \end{tcolorbox}
  13497. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  13498. \label{fig:c3-syntax}
  13499. \end{figure}
  13500. \clearpage
  13501. \section{Select Instructions and the \LangXIndCall{} Language}
  13502. \label{sec:select-r4}
  13503. \index{subject}{instruction selection}
  13504. The output of select instructions is a program in the \LangXIndCall{}
  13505. language, whose concrete syntax is defined in
  13506. figure~\ref{fig:x86-3-concrete} and abstract syntax is defined in
  13507. figure~\ref{fig:x86-3}. We use the \code{align} directive on the
  13508. labels of function definitions to make sure the bottom three bits are
  13509. zero, which we make use of in chapter~\ref{ch:Ldyn}. We discuss the
  13510. new instructions as needed in this section. \index{subject}{x86}
  13511. \newcommand{\GrammarXIndCall}{
  13512. \begin{array}{lcl}
  13513. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13514. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13515. \Block &::= & \Instr^{+} \\
  13516. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  13517. \end{array}
  13518. }
  13519. \newcommand{\ASTXIndCallRacket}{
  13520. \begin{array}{lcl}
  13521. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  13522. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13523. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13524. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13525. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  13526. \end{array}
  13527. }
  13528. \begin{figure}[tp]
  13529. \begin{tcolorbox}[colback=white]
  13530. \small
  13531. \[
  13532. \begin{array}{l}
  13533. \gray{\GrammarXInt} \\ \hline
  13534. \gray{\GrammarXIf} \\ \hline
  13535. \gray{\GrammarXGlobal} \\ \hline
  13536. \GrammarXIndCall \\
  13537. \begin{array}{lcl}
  13538. \LangXIndCallM{} &::= & \Def^{*}
  13539. \end{array}
  13540. \end{array}
  13541. \]
  13542. \end{tcolorbox}
  13543. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  13544. \label{fig:x86-3-concrete}
  13545. \end{figure}
  13546. \begin{figure}[tp]
  13547. \begin{tcolorbox}[colback=white]
  13548. \small
  13549. {\if\edition\racketEd
  13550. \[\arraycolsep=3pt
  13551. \begin{array}{l}
  13552. \gray{\ASTXIntRacket} \\ \hline
  13553. \gray{\ASTXIfRacket} \\ \hline
  13554. \gray{\ASTXGlobalRacket} \\ \hline
  13555. \ASTXIndCallRacket \\
  13556. \begin{array}{lcl}
  13557. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13558. \end{array}
  13559. \end{array}
  13560. \]
  13561. \fi}
  13562. {\if\edition\pythonEd
  13563. \[
  13564. \begin{array}{lcl}
  13565. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13566. \MID \BYTEREG{\Reg} } \\
  13567. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  13568. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13569. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13570. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13571. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13572. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13573. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13574. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13575. \end{array}
  13576. \]
  13577. \fi}
  13578. \end{tcolorbox}
  13579. \caption{The abstract syntax of \LangXIndCall{} (extends
  13580. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  13581. \label{fig:x86-3}
  13582. \end{figure}
  13583. An assignment of a function reference to a variable becomes a
  13584. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  13585. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  13586. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  13587. node, whose concrete syntax is instruction-pointer relative
  13588. addressing.
  13589. \begin{center}
  13590. \begin{tabular}{lcl}
  13591. \begin{minipage}{0.35\textwidth}
  13592. {\if\edition\racketEd
  13593. \begin{lstlisting}
  13594. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13595. \end{lstlisting}
  13596. \fi}
  13597. {\if\edition\pythonEd
  13598. \begin{lstlisting}
  13599. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  13600. \end{lstlisting}
  13601. \fi}
  13602. \end{minipage}
  13603. &
  13604. $\Rightarrow$\qquad\qquad
  13605. &
  13606. \begin{minipage}{0.3\textwidth}
  13607. \begin{lstlisting}
  13608. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13609. \end{lstlisting}
  13610. \end{minipage}
  13611. \end{tabular}
  13612. \end{center}
  13613. Regarding function definitions, we need to remove the parameters and
  13614. instead perform parameter passing using the conventions discussed in
  13615. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13616. registers. We recommend turning the parameters into local variables
  13617. and generating instructions at the beginning of the function to move
  13618. from the argument passing registers
  13619. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  13620. {\if\edition\racketEd
  13621. \begin{lstlisting}
  13622. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13623. |$\Rightarrow$|
  13624. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13625. \end{lstlisting}
  13626. \fi}
  13627. {\if\edition\pythonEd
  13628. \begin{lstlisting}
  13629. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13630. |$\Rightarrow$|
  13631. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13632. \end{lstlisting}
  13633. \fi}
  13634. The basic blocks $B'$ are the same as $B$ except that the
  13635. \code{start} block is modified to add the instructions for moving from
  13636. the argument registers to the parameter variables. So the \code{start}
  13637. block of $B$ shown on the left is changed to the code on the right.
  13638. \begin{center}
  13639. \begin{minipage}{0.3\textwidth}
  13640. \begin{lstlisting}
  13641. start:
  13642. |$\itm{instr}_1$|
  13643. |$\cdots$|
  13644. |$\itm{instr}_n$|
  13645. \end{lstlisting}
  13646. \end{minipage}
  13647. $\Rightarrow$
  13648. \begin{minipage}{0.3\textwidth}
  13649. \begin{lstlisting}
  13650. |$f$|start:
  13651. movq %rdi, |$x_1$|
  13652. movq %rsi, |$x_2$|
  13653. |$\cdots$|
  13654. |$\itm{instr}_1$|
  13655. |$\cdots$|
  13656. |$\itm{instr}_n$|
  13657. \end{lstlisting}
  13658. \end{minipage}
  13659. \end{center}
  13660. Recall that we use the label \code{start} for the initial block of a
  13661. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  13662. the conclusion of the program with \code{conclusion}, so that
  13663. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13664. by a jump to \code{conclusion}. With the addition of function
  13665. definitions, there is a start block and conclusion for each function,
  13666. but their labels need to be unique. We recommend prepending the
  13667. function's name to \code{start} and \code{conclusion}, respectively,
  13668. to obtain unique labels.
  13669. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13670. parameters the function expects, but the parameters are no longer in
  13671. the syntax of function definitions. Instead, add an entry to
  13672. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13673. to construct $\itm{info}'$.}
  13674. By changing the parameters to local variables, we are giving the
  13675. register allocator control over which registers or stack locations to
  13676. use for them. If you implemented the move-biasing challenge
  13677. (section~\ref{sec:move-biasing}), the register allocator will try to
  13678. assign the parameter variables to the corresponding argument register,
  13679. in which case the \code{patch\_instructions} pass will remove the
  13680. \code{movq} instruction. This happens in the example translation in
  13681. figure~\ref{fig:add-fun} of section~\ref{sec:functions-example}, in
  13682. the \code{add} function.
  13683. %
  13684. Also, note that the register allocator will perform liveness analysis
  13685. on this sequence of move instructions and build the interference
  13686. graph. So, for example, $x_1$ will be marked as interfering with
  13687. \code{rsi} and that will prevent the assignment of $x_1$ to
  13688. \code{rsi}, which is good, because that would overwrite the argument
  13689. that needs to move into $x_2$.
  13690. Next, consider the compilation of function calls. In the mirror image
  13691. of the handling of parameters in function definitions, the arguments
  13692. are moved to the argument passing registers. Note that the function
  13693. is not given as a label, but its address is produced by the argument
  13694. $\itm{arg}_0$. So we translate the call into an indirect function
  13695. call. The return value from the function is stored in \code{rax}, so
  13696. it needs to be moved into the \itm{lhs}.
  13697. \begin{lstlisting}
  13698. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  13699. |$\Rightarrow$|
  13700. movq |$\itm{arg}_1$|, %rdi
  13701. movq |$\itm{arg}_2$|, %rsi
  13702. |$\vdots$|
  13703. callq *|$\itm{arg}_0$|
  13704. movq %rax, |$\itm{lhs}$|
  13705. \end{lstlisting}
  13706. The \code{IndirectCallq} AST node includes an integer for the arity of
  13707. the function, i.e., the number of parameters. That information is
  13708. useful in the \code{uncover\_live} pass for determining which
  13709. argument-passing registers are potentially read during the call.
  13710. For tail calls, the parameter passing is the same as non-tail calls:
  13711. generate instructions to move the arguments into the argument
  13712. passing registers. After that we need to pop the frame from the
  13713. procedure call stack. However, we do not yet know how big the frame
  13714. is; that gets determined during register allocation. So instead of
  13715. generating those instructions here, we invent a new instruction that
  13716. means ``pop the frame and then do an indirect jump'', which we name
  13717. \code{TailJmp}. The abstract syntax for this instruction includes an
  13718. argument that specifies where to jump and an integer that represents
  13719. the arity of the function being called.
  13720. \section{Register Allocation}
  13721. \label{sec:register-allocation-r4}
  13722. The addition of functions requires some changes to all three aspects
  13723. of register allocation, which we discuss in the following subsections.
  13724. \subsection{Liveness Analysis}
  13725. \label{sec:liveness-analysis-r4}
  13726. \index{subject}{liveness analysis}
  13727. %% The rest of the passes need only minor modifications to handle the new
  13728. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13729. %% \code{leaq}.
  13730. The \code{IndirectCallq} instruction should be treated like
  13731. \code{Callq} regarding its written locations $W$, in that they should
  13732. include all the caller-saved registers. Recall that the reason for
  13733. that is to force variables that are live across a function call to be assigned to callee-saved
  13734. registers or to be spilled to the stack.
  13735. Regarding the set of read locations $R$, the arity field of
  13736. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13737. argument-passing registers should be considered as read by those
  13738. instructions. Also, the target field of \code{TailJmp} and
  13739. \code{IndirectCallq} should be included in the set of read locations
  13740. $R$.
  13741. \subsection{Build Interference Graph}
  13742. \label{sec:build-interference-r4}
  13743. With the addition of function definitions, we compute a separate interference
  13744. graph for each function (not just one for the whole program).
  13745. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  13746. spill tuple-typed variables that are live during a call to
  13747. \code{collect}, the garbage collector. With the addition of functions
  13748. to our language, we need to revisit this issue. Functions that perform
  13749. allocation contain calls to the collector. Thus, we should not only
  13750. spill a tuple-typed variable when it is live during a call to
  13751. \code{collect}, but we should spill the variable if it is live during
  13752. call to any user-defined function. Thus, in the
  13753. \code{build\_interference} pass, we recommend adding interference
  13754. edges between call-live tuple-typed variables and the callee-saved
  13755. registers (in addition to the usual addition of edges between
  13756. call-live variables and the caller-saved registers).
  13757. \subsection{Allocate Registers}
  13758. The primary change to the \code{allocate\_registers} pass is adding an
  13759. auxiliary function for handling definitions (the \Def{} nonterminal
  13760. in figure~\ref{fig:x86-3}) with one case for function definitions. The
  13761. logic is the same as described in
  13762. chapter~\ref{ch:register-allocation-Lvar}, except now register
  13763. allocation is performed many times, once for each function definition,
  13764. instead of just once for the whole program.
  13765. \section{Patch Instructions}
  13766. In \code{patch\_instructions}, you should deal with the x86
  13767. idiosyncrasy that the destination argument of \code{leaq} must be a
  13768. register. Additionally, you should ensure that the argument of
  13769. \code{TailJmp} is \itm{rax}, our reserved register---because we
  13770. trample many other registers before the tail call (as explained in the
  13771. next section).
  13772. \section{Prelude and Conclusion}
  13773. Now that register allocation is complete, we can translate the
  13774. \code{TailJmp} into a sequence of instructions. A naive translation of
  13775. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  13776. before the jump we need to pop the current frame to achieve efficient
  13777. tail calls. This sequence of instructions is the same as the code for
  13778. the conclusion of a function, except the \code{retq} is replaced with
  13779. \code{jmp *$\itm{arg}$}.
  13780. Regarding function definitions, we generate a prelude and conclusion
  13781. for each one. This code is similar to the prelude and conclusion
  13782. generated for the \code{main} function in chapter~\ref{ch:Lvec}. To
  13783. review, the prelude of every function should carry out the following
  13784. steps.
  13785. % TODO: .align the functions!
  13786. \begin{enumerate}
  13787. %% \item Start with \code{.global} and \code{.align} directives followed
  13788. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  13789. %% example.)
  13790. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13791. pointer.
  13792. \item Push to the stack all of the callee-saved registers that were
  13793. used for register allocation.
  13794. \item Move the stack pointer \code{rsp} down to make room for the
  13795. regular spills. (Aligned to 16 bytes.)
  13796. \item Move the root stack pointer \code{r15} up by the size of the
  13797. root-stack frame for this function, which depends on the number of
  13798. spilled tuple-typed variables. \label{root-stack-init}
  13799. \item Initialize to zero all new entries in the root-stack frame.
  13800. \item Jump to the start block.
  13801. \end{enumerate}
  13802. The prelude of the \code{main} function has an additional task: call
  13803. the \code{initialize} function to set up the garbage collector and
  13804. then move the value of the global \code{rootstack\_begin} in
  13805. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13806. above, which depends on \code{r15}.
  13807. The conclusion of every function should do the following.
  13808. \begin{enumerate}
  13809. \item Move the stack pointer back up past the regular spills.
  13810. \item Restore the callee-saved registers by popping them from the
  13811. stack.
  13812. \item Move the root stack pointer back down by the size of the
  13813. root-stack frame for this function.
  13814. \item Restore \code{rbp} by popping it from the stack.
  13815. \item Return to the caller with the \code{retq} instruction.
  13816. \end{enumerate}
  13817. The output of this pass is \LangXIndCallFlat{}, which differs from
  13818. \LangXIndCall{} in that there is no longer an AST node for function
  13819. definitions. Instead, a program is just an association list of basic
  13820. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  13821. \[
  13822. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  13823. \]
  13824. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  13825. compiling \LangFun{} to x86.
  13826. \begin{exercise}\normalfont\normalsize
  13827. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13828. Create 8 new programs that use functions, including examples that pass
  13829. functions and return functions from other functions, recursive
  13830. functions, functions that create vectors, and functions that make tail
  13831. calls. Test your compiler on these new programs and all of your
  13832. previously created test programs.
  13833. \end{exercise}
  13834. \begin{figure}[tbp]
  13835. \begin{tcolorbox}[colback=white]
  13836. {\if\edition\racketEd
  13837. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13838. \node (Lfun) at (0,2) {\large \LangFun{}};
  13839. \node (Lfun-1) at (3,2) {\large \LangFun{}};
  13840. \node (Lfun-2) at (6,2) {\large \LangFun{}};
  13841. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13842. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13843. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13844. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13845. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13846. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13847. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13848. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13849. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13850. \node (x86-5) at (9,-6) {\large \LangXIndCallFlat{}};
  13851. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13852. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13853. \path[->,bend left=15] (Lfun) edge [above] node
  13854. {\ttfamily\footnotesize shrink} (Lfun-1);
  13855. \path[->,bend left=15] (Lfun-1) edge [above] node
  13856. {\ttfamily\footnotesize uniquify} (Lfun-2);
  13857. \path[->,bend left=15] (Lfun-2) edge [above] node
  13858. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13859. \path[->,bend left=15] (F1-1) edge [left] node
  13860. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13861. \path[->,bend left=15] (F1-2) edge [below] node
  13862. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13863. \path[->,bend left=15] (F1-3) edge [below] node
  13864. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  13865. \path[->,bend right=15] (F1-4) edge [above] node
  13866. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13867. \path[->,bend right=15] (F1-5) edge [left] node
  13868. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13869. \path[->,bend right=15] (C3-2) edge [left] node
  13870. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13871. \path[->,bend left=15] (x86-2) edge [left] node
  13872. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13873. \path[->,bend right=15] (x86-2-1) edge [below] node
  13874. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13875. \path[->,bend right=15] (x86-2-2) edge [left] node
  13876. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13877. \path[->,bend left=15] (x86-3) edge [above] node
  13878. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13879. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize prelude.} (x86-5);
  13880. \end{tikzpicture}
  13881. \fi}
  13882. {\if\edition\pythonEd
  13883. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13884. \node (Lfun) at (0,2) {\large \LangFun{}};
  13885. \node (Lfun-2) at (3,2) {\large \LangFun{}};
  13886. \node (F1-1) at (6,2) {\large \LangFunRef{}};
  13887. \node (F1-2) at (9,2) {\large \LangFunRef{}};
  13888. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13889. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13890. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  13891. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  13892. \node (x86-3) at (3,-4) {\large \LangXIndCallVar{}};
  13893. \node (x86-4) at (6,-4) {\large \LangXIndCall{}};
  13894. \node (x86-5) at (6,-6) {\large \LangXIndCallFlat{}};
  13895. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  13896. \node (x86-2-2) at (3,-6) {\large \LangXIndCallVar{}};
  13897. \path[->,bend left=15] (Lfun) edge [above] node
  13898. {\ttfamily\footnotesize shrink} (Lfun-2);
  13899. \path[->,bend left=15] (Lfun-2) edge [above] node
  13900. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13901. \path[->,bend left=15] (F1-1) edge [above] node
  13902. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13903. \path[->,bend left=15] (F1-2) edge [right] node
  13904. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  13905. \path[->,bend right=15] (F1-4) edge [above] node
  13906. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13907. \path[->,bend right=15] (F1-5) edge [right] node
  13908. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13909. \path[->,bend left=15] (C3-2) edge [right] node
  13910. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13911. \path[->,bend right=15] (x86-2) edge [right] node
  13912. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13913. \path[->,bend right=15] (x86-2-1) edge [below] node
  13914. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13915. \path[->,bend right=15] (x86-2-2) edge [right] node
  13916. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13917. \path[->,bend left=15] (x86-3) edge [above] node
  13918. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13919. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude.} (x86-5);
  13920. \end{tikzpicture}
  13921. \fi}
  13922. \end{tcolorbox}
  13923. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13924. \label{fig:Lfun-passes}
  13925. \end{figure}
  13926. \section{An Example Translation}
  13927. \label{sec:functions-example}
  13928. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13929. function in \LangFun{} to x86. The figure also includes the results of the
  13930. \code{explicate\_control} and \code{select\_instructions} passes.
  13931. \begin{figure}[htbp]
  13932. \begin{tcolorbox}[colback=white]
  13933. \begin{tabular}{ll}
  13934. \begin{minipage}{0.4\textwidth}
  13935. % s3_2.rkt
  13936. {\if\edition\racketEd
  13937. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13938. (define (add [x : Integer]
  13939. [y : Integer])
  13940. : Integer
  13941. (+ x y))
  13942. (add 40 2)
  13943. \end{lstlisting}
  13944. \fi}
  13945. {\if\edition\pythonEd
  13946. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13947. def add(x:int, y:int) -> int:
  13948. return x + y
  13949. print(add(40, 2))
  13950. \end{lstlisting}
  13951. \fi}
  13952. $\Downarrow$
  13953. {\if\edition\racketEd
  13954. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13955. (define (add86 [x87 : Integer]
  13956. [y88 : Integer])
  13957. : Integer
  13958. add86start:
  13959. return (+ x87 y88);
  13960. )
  13961. (define (main) : Integer ()
  13962. mainstart:
  13963. tmp89 = (fun-ref add86 2);
  13964. (tail-call tmp89 40 2)
  13965. )
  13966. \end{lstlisting}
  13967. \fi}
  13968. {\if\edition\pythonEd
  13969. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13970. def add(x:int, y:int) -> int:
  13971. addstart:
  13972. return x + y
  13973. def main() -> int:
  13974. mainstart:
  13975. fun.0 = add
  13976. tmp.1 = fun.0(40, 2)
  13977. print(tmp.1)
  13978. return 0
  13979. \end{lstlisting}
  13980. \fi}
  13981. \end{minipage}
  13982. &
  13983. $\Rightarrow$
  13984. \begin{minipage}{0.5\textwidth}
  13985. {\if\edition\racketEd
  13986. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13987. (define (add86) : Integer
  13988. add86start:
  13989. movq %rdi, x87
  13990. movq %rsi, y88
  13991. movq x87, %rax
  13992. addq y88, %rax
  13993. jmp inc1389conclusion
  13994. )
  13995. (define (main) : Integer
  13996. mainstart:
  13997. leaq (fun-ref add86 2), tmp89
  13998. movq $40, %rdi
  13999. movq $2, %rsi
  14000. tail-jmp tmp89
  14001. )
  14002. \end{lstlisting}
  14003. \fi}
  14004. {\if\edition\pythonEd
  14005. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14006. def add() -> int:
  14007. addstart:
  14008. movq %rdi, x
  14009. movq %rsi, y
  14010. movq x, %rax
  14011. addq y, %rax
  14012. jmp addconclusion
  14013. def main() -> int:
  14014. mainstart:
  14015. leaq add, fun.0
  14016. movq $40, %rdi
  14017. movq $2, %rsi
  14018. callq *fun.0
  14019. movq %rax, tmp.1
  14020. movq tmp.1, %rdi
  14021. callq print_int
  14022. movq $0, %rax
  14023. jmp mainconclusion
  14024. \end{lstlisting}
  14025. \fi}
  14026. $\Downarrow$
  14027. \end{minipage}
  14028. \end{tabular}
  14029. \begin{tabular}{ll}
  14030. \begin{minipage}{0.3\textwidth}
  14031. {\if\edition\racketEd
  14032. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14033. .globl add86
  14034. .align 8
  14035. add86:
  14036. pushq %rbp
  14037. movq %rsp, %rbp
  14038. jmp add86start
  14039. add86start:
  14040. movq %rdi, %rax
  14041. addq %rsi, %rax
  14042. jmp add86conclusion
  14043. add86conclusion:
  14044. popq %rbp
  14045. retq
  14046. \end{lstlisting}
  14047. \fi}
  14048. {\if\edition\pythonEd
  14049. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14050. .align 8
  14051. add:
  14052. pushq %rbp
  14053. movq %rsp, %rbp
  14054. subq $0, %rsp
  14055. jmp addstart
  14056. addstart:
  14057. movq %rdi, %rdx
  14058. movq %rsi, %rcx
  14059. movq %rdx, %rax
  14060. addq %rcx, %rax
  14061. jmp addconclusion
  14062. addconclusion:
  14063. subq $0, %r15
  14064. addq $0, %rsp
  14065. popq %rbp
  14066. retq
  14067. \end{lstlisting}
  14068. \fi}
  14069. \end{minipage}
  14070. &
  14071. \begin{minipage}{0.5\textwidth}
  14072. {\if\edition\racketEd
  14073. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14074. .globl main
  14075. .align 8
  14076. main:
  14077. pushq %rbp
  14078. movq %rsp, %rbp
  14079. movq $16384, %rdi
  14080. movq $16384, %rsi
  14081. callq initialize
  14082. movq rootstack_begin(%rip), %r15
  14083. jmp mainstart
  14084. mainstart:
  14085. leaq add86(%rip), %rcx
  14086. movq $40, %rdi
  14087. movq $2, %rsi
  14088. movq %rcx, %rax
  14089. popq %rbp
  14090. jmp *%rax
  14091. mainconclusion:
  14092. popq %rbp
  14093. retq
  14094. \end{lstlisting}
  14095. \fi}
  14096. {\if\edition\pythonEd
  14097. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14098. .globl main
  14099. .align 8
  14100. main:
  14101. pushq %rbp
  14102. movq %rsp, %rbp
  14103. subq $0, %rsp
  14104. movq $65536, %rdi
  14105. movq $65536, %rsi
  14106. callq initialize
  14107. movq rootstack_begin(%rip), %r15
  14108. jmp mainstart
  14109. mainstart:
  14110. leaq add(%rip), %rcx
  14111. movq $40, %rdi
  14112. movq $2, %rsi
  14113. callq *%rcx
  14114. movq %rax, %rcx
  14115. movq %rcx, %rdi
  14116. callq print_int
  14117. movq $0, %rax
  14118. jmp mainconclusion
  14119. mainconclusion:
  14120. subq $0, %r15
  14121. addq $0, %rsp
  14122. popq %rbp
  14123. retq
  14124. \end{lstlisting}
  14125. \fi}
  14126. \end{minipage}
  14127. \end{tabular}
  14128. \end{tcolorbox}
  14129. \caption{Example compilation of a simple function to x86.}
  14130. \label{fig:add-fun}
  14131. \end{figure}
  14132. % Challenge idea: inlining! (simple version)
  14133. % Further Reading
  14134. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14135. \chapter{Lexically Scoped Functions}
  14136. \label{ch:Llambda}
  14137. \index{subject}{lambda}
  14138. \index{subject}{lexical scoping}
  14139. \setcounter{footnote}{0}
  14140. This chapter studies lexically scoped functions. Lexical scoping means
  14141. that a function's body may refer to variables whose binding site is
  14142. outside of the function, in an enclosing scope.
  14143. %
  14144. Consider the example in figure~\ref{fig:lexical-scoping} written in
  14145. \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  14146. creating lexically scoped functions. The body of the \key{lambda}
  14147. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  14148. binding sites for \code{x} and \code{y} are outside of the
  14149. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  14150. \key{let}}\python{a local variable of function \code{f}} and
  14151. \code{x} is a parameter of function \code{f}. Note that function
  14152. \code{f} returns the \key{lambda} as its result value. The main
  14153. expression of the program includes two calls to \code{f} with
  14154. different arguments for \code{x}, first \code{5} then \code{3}. The
  14155. functions returned from \code{f} are bound to variables \code{g} and
  14156. \code{h}. Even though these two functions were created by the same
  14157. \code{lambda}, they are really different functions because they use
  14158. different values for \code{x}. Applying \code{g} to \code{11} produces
  14159. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  14160. so the result of the program is \code{42}.
  14161. \begin{figure}[btp]
  14162. \begin{tcolorbox}[colback=white]
  14163. {\if\edition\racketEd
  14164. % lambda_test_21.rkt
  14165. \begin{lstlisting}
  14166. (define (f [x : Integer]) : (Integer -> Integer)
  14167. (let ([y 4])
  14168. (lambda: ([z : Integer]) : Integer
  14169. (+ x (+ y z)))))
  14170. (let ([g (f 5)])
  14171. (let ([h (f 3)])
  14172. (+ (g 11) (h 15))))
  14173. \end{lstlisting}
  14174. \fi}
  14175. {\if\edition\pythonEd
  14176. \begin{lstlisting}
  14177. def f(x : int) -> Callable[[int], int]:
  14178. y = 4
  14179. return lambda z: x + y + z
  14180. g = f(5)
  14181. h = f(3)
  14182. print( g(11) + h(15) )
  14183. \end{lstlisting}
  14184. \fi}
  14185. \end{tcolorbox}
  14186. \caption{Example of a lexically scoped function.}
  14187. \label{fig:lexical-scoping}
  14188. \end{figure}
  14189. The approach that we take for implementing lexically scoped functions
  14190. is to compile them into top-level function definitions, translating
  14191. from \LangLam{} into \LangFun{}. However, the compiler must give
  14192. special treatment to variable occurrences such as \code{x} and
  14193. \code{y} in the body of the \code{lambda} of
  14194. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  14195. may not refer to variables defined outside of it. To identify such
  14196. variable occurrences, we review the standard notion of free variable.
  14197. \begin{definition}
  14198. A variable is \textbf{free in expression} $e$ if the variable occurs
  14199. inside $e$ but does not have an enclosing definition that is also in
  14200. $e$.\index{subject}{free variable}
  14201. \end{definition}
  14202. For example, in the expression
  14203. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  14204. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  14205. only \code{x} and \code{y} are free in the following expression
  14206. because \code{z} is defined by the \code{lambda}.
  14207. {\if\edition\racketEd
  14208. \begin{lstlisting}
  14209. (lambda: ([z : Integer]) : Integer
  14210. (+ x (+ y z)))
  14211. \end{lstlisting}
  14212. \fi}
  14213. {\if\edition\pythonEd
  14214. \begin{lstlisting}
  14215. lambda z: x + y + z
  14216. \end{lstlisting}
  14217. \fi}
  14218. %
  14219. So the free variables of a \code{lambda} are the ones that need
  14220. special treatment. We need to transport, at runtime, the values of
  14221. those variables from the point where the \code{lambda} was created to
  14222. the point where the \code{lambda} is applied. An efficient solution to
  14223. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  14224. of the free variables together with a function pointer into a tuple,
  14225. an arrangement called a \emph{flat closure} (which we shorten to just
  14226. ``closure'').\index{subject}{closure}\index{subject}{flat closure}
  14227. %
  14228. By design, we have all the ingredients to make closures:
  14229. chapter~\ref{ch:Lvec} gave us tuples and chapter~\ref{ch:Lfun} gave us
  14230. function pointers. The function pointer resides at index $0$ and the
  14231. values for the free variables fill in the rest of the tuple.
  14232. Let us revisit the example in figure~\ref{fig:lexical-scoping} to see
  14233. how closures work. It is a three-step dance. The program calls
  14234. function \code{f}, which creates a closure for the \code{lambda}. The
  14235. closure is a tuple whose first element is a pointer to the top-level
  14236. function that we will generate for the \code{lambda}, the second
  14237. element is the value of \code{x}, which is \code{5}, and the third
  14238. element is \code{4}, the value of \code{y}. The closure does not
  14239. contain an element for \code{z} because \code{z} is not a free
  14240. variable of the \code{lambda}. Creating the closure is step 1 of the
  14241. dance. The closure is returned from \code{f} and bound to \code{g}, as
  14242. shown in figure~\ref{fig:closures}.
  14243. %
  14244. The second call to \code{f} creates another closure, this time with
  14245. \code{3} in the second slot (for \code{x}). This closure is also
  14246. returned from \code{f} but bound to \code{h}, which is also shown in
  14247. figure~\ref{fig:closures}.
  14248. \begin{figure}[tbp]
  14249. \centering
  14250. \begin{minipage}{0.65\textwidth}
  14251. \begin{tcolorbox}[colback=white]
  14252. \includegraphics[width=\textwidth]{figs/closures}
  14253. \end{tcolorbox}
  14254. \end{minipage}
  14255. \caption{Flat closure representations for the two functions
  14256. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  14257. \label{fig:closures}
  14258. \end{figure}
  14259. Continuing with the example, consider the application of \code{g} to
  14260. \code{11} in figure~\ref{fig:lexical-scoping}. To apply a closure, we
  14261. obtain the function pointer from the first element of the closure and
  14262. call it, passing in the closure itself and then the regular arguments,
  14263. in this case \code{11}. This technique for applying a closure is step
  14264. 2 of the dance.
  14265. %
  14266. But doesn't this \code{lambda} only take 1 argument, for parameter
  14267. \code{z}? The third and final step of the dance is generating a
  14268. top-level function for a \code{lambda}. We add an additional
  14269. parameter for the closure and we insert an initialization at the beginning
  14270. of the function for each free variable, to bind those variables to the
  14271. appropriate elements from the closure parameter.
  14272. %
  14273. This three-step dance is known as \emph{closure conversion}. We
  14274. discuss the details of closure conversion in
  14275. section~\ref{sec:closure-conversion} and show the code generated from
  14276. the example in section~\ref{sec:example-lambda}. But first we define
  14277. the syntax and semantics of \LangLam{} in section~\ref{sec:r5}.
  14278. \section{The \LangLam{} Language}
  14279. \label{sec:r5}
  14280. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  14281. functions and lexical scoping, is defined in
  14282. Figures~\ref{fig:Llam-concrete-syntax} and \ref{fig:Llam-syntax}. It adds
  14283. the \key{lambda} form to the grammar for \LangFun{}, which already has
  14284. syntax for function application.
  14285. %
  14286. \python{The syntax also includes an assignment statement that includes
  14287. a type annotation for the variable on the left-hand side, which
  14288. facilitates the type checking of \code{lambda} expressions that we
  14289. discuss later in this section.}
  14290. %
  14291. \racket{The \code{procedure-arity} operation returns the number of parameters
  14292. of a given function, an operation that we need for the translation
  14293. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  14294. %
  14295. \python{The \code{arity} operation returns the number of parameters of
  14296. a given function, an operation that we need for the translation
  14297. of dynamic typing in chapter~\ref{ch:Ldyn}.
  14298. The \code{arity} operation is not in Python, but the same functionality
  14299. is available in a more complex form. We include \code{arity} in the
  14300. \LangLam{} source language to enable testing.}
  14301. \newcommand{\LlambdaGrammarRacket}{
  14302. \begin{array}{lcl}
  14303. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  14304. &\MID& \LP \key{procedure-arity}~\Exp\RP
  14305. \end{array}
  14306. }
  14307. \newcommand{\LlambdaASTRacket}{
  14308. \begin{array}{lcl}
  14309. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  14310. \itm{op} &::=& \code{procedure-arity}
  14311. \end{array}
  14312. }
  14313. \newcommand{\LlambdaGrammarPython}{
  14314. \begin{array}{lcl}
  14315. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  14316. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  14317. \end{array}
  14318. }
  14319. \newcommand{\LlambdaASTPython}{
  14320. \begin{array}{lcl}
  14321. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  14322. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  14323. \end{array}
  14324. }
  14325. % include AnnAssign in ASTPython
  14326. \begin{figure}[tp]
  14327. \centering
  14328. \begin{tcolorbox}[colback=white]
  14329. \small
  14330. {\if\edition\racketEd
  14331. \[
  14332. \begin{array}{l}
  14333. \gray{\LintGrammarRacket{}} \\ \hline
  14334. \gray{\LvarGrammarRacket{}} \\ \hline
  14335. \gray{\LifGrammarRacket{}} \\ \hline
  14336. \gray{\LwhileGrammarRacket} \\ \hline
  14337. \gray{\LtupGrammarRacket} \\ \hline
  14338. \gray{\LfunGrammarRacket} \\ \hline
  14339. \LlambdaGrammarRacket \\
  14340. \begin{array}{lcl}
  14341. \LangLamM{} &::=& \Def\ldots \; \Exp
  14342. \end{array}
  14343. \end{array}
  14344. \]
  14345. \fi}
  14346. {\if\edition\pythonEd
  14347. \[
  14348. \begin{array}{l}
  14349. \gray{\LintGrammarPython{}} \\ \hline
  14350. \gray{\LvarGrammarPython{}} \\ \hline
  14351. \gray{\LifGrammarPython{}} \\ \hline
  14352. \gray{\LwhileGrammarPython} \\ \hline
  14353. \gray{\LtupGrammarPython} \\ \hline
  14354. \gray{\LfunGrammarPython} \\ \hline
  14355. \LlambdaGrammarPython \\
  14356. \begin{array}{lcl}
  14357. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  14358. \end{array}
  14359. \end{array}
  14360. \]
  14361. \fi}
  14362. \end{tcolorbox}
  14363. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  14364. with \key{lambda}.}
  14365. \label{fig:Llam-concrete-syntax}
  14366. \end{figure}
  14367. \begin{figure}[tp]
  14368. \centering
  14369. \begin{tcolorbox}[colback=white]
  14370. \small
  14371. {\if\edition\racketEd
  14372. \[\arraycolsep=3pt
  14373. \begin{array}{l}
  14374. \gray{\LintOpAST} \\ \hline
  14375. \gray{\LvarASTRacket{}} \\ \hline
  14376. \gray{\LifASTRacket{}} \\ \hline
  14377. \gray{\LwhileASTRacket{}} \\ \hline
  14378. \gray{\LtupASTRacket{}} \\ \hline
  14379. \gray{\LfunASTRacket} \\ \hline
  14380. \LlambdaASTRacket \\
  14381. \begin{array}{lcl}
  14382. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14383. \end{array}
  14384. \end{array}
  14385. \]
  14386. \fi}
  14387. {\if\edition\pythonEd
  14388. \[
  14389. \begin{array}{l}
  14390. \gray{\LintASTPython} \\ \hline
  14391. \gray{\LvarASTPython{}} \\ \hline
  14392. \gray{\LifASTPython{}} \\ \hline
  14393. \gray{\LwhileASTPython{}} \\ \hline
  14394. \gray{\LtupASTPython{}} \\ \hline
  14395. \gray{\LfunASTPython} \\ \hline
  14396. \LlambdaASTPython \\
  14397. \begin{array}{lcl}
  14398. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14399. \end{array}
  14400. \end{array}
  14401. \]
  14402. \fi}
  14403. \end{tcolorbox}
  14404. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  14405. \label{fig:Llam-syntax}
  14406. \end{figure}
  14407. \index{subject}{interpreter}
  14408. \label{sec:interp-Llambda}
  14409. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  14410. \LangLam{}. The case for \key{Lambda} saves the current environment
  14411. inside the returned function value. Recall that during function
  14412. application, the environment stored in the function value, extended
  14413. with the mapping of parameters to argument values, is used to
  14414. interpret the body of the function.
  14415. \begin{figure}[tbp]
  14416. \begin{tcolorbox}[colback=white]
  14417. {\if\edition\racketEd
  14418. \begin{lstlisting}
  14419. (define interp-Llambda-class
  14420. (class interp-Lfun-class
  14421. (super-new)
  14422. (define/override (interp-op op)
  14423. (match op
  14424. ['procedure-arity
  14425. (lambda (v)
  14426. (match v
  14427. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  14428. [else (error 'interp-op "expected a function, not ~a" v)]))]
  14429. [else (super interp-op op)]))
  14430. (define/override ((interp-exp env) e)
  14431. (define recur (interp-exp env))
  14432. (match e
  14433. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  14434. `(function ,xs ,body ,env)]
  14435. [else ((super interp-exp env) e)]))
  14436. ))
  14437. (define (interp-Llambda p)
  14438. (send (new interp-Llambda-class) interp-program p))
  14439. \end{lstlisting}
  14440. \fi}
  14441. {\if\edition\pythonEd
  14442. \begin{lstlisting}
  14443. class InterpLlambda(InterpLfun):
  14444. def arity(self, v):
  14445. match v:
  14446. case Function(name, params, body, env):
  14447. return len(params)
  14448. case _:
  14449. raise Exception('Llambda arity unexpected ' + repr(v))
  14450. def interp_exp(self, e, env):
  14451. match e:
  14452. case Call(Name('arity'), [fun]):
  14453. f = self.interp_exp(fun, env)
  14454. return self.arity(f)
  14455. case Lambda(params, body):
  14456. return Function('lambda', params, [Return(body)], env)
  14457. case _:
  14458. return super().interp_exp(e, env)
  14459. def interp_stmts(self, ss, env):
  14460. if len(ss) == 0:
  14461. return
  14462. match ss[0]:
  14463. case AnnAssign(lhs, typ, value, simple):
  14464. env[lhs.id] = self.interp_exp(value, env)
  14465. return self.interp_stmts(ss[1:], env)
  14466. case _:
  14467. return super().interp_stmts(ss, env)
  14468. \end{lstlisting}
  14469. \fi}
  14470. \end{tcolorbox}
  14471. \caption{Interpreter for \LangLam{}.}
  14472. \label{fig:interp-Llambda}
  14473. \end{figure}
  14474. \label{sec:type-check-r5}
  14475. \index{subject}{type checking}
  14476. {\if\edition\racketEd
  14477. %
  14478. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  14479. \key{lambda} form. The body of the \key{lambda} is checked in an
  14480. environment that includes the current environment (because it is
  14481. lexically scoped) and also includes the \key{lambda}'s parameters. We
  14482. require the body's type to match the declared return type.
  14483. %
  14484. \fi}
  14485. {\if\edition\pythonEd
  14486. %
  14487. Figures~\ref{fig:type-check-Llambda} and
  14488. \ref{fig:type-check-Llambda-part2} define the type checker for
  14489. \LangLam{}, which is more complex than one might expect. The reason
  14490. for the added complexity is that the syntax of \key{lambda} does not
  14491. include type annotations for the parameters or return type. Instead
  14492. they must be inferred. There are many approaches of type inference to
  14493. choose from of varying degrees of complexity. We choose one of the
  14494. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  14495. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  14496. this book is compilation, not type inference.
  14497. The main idea of bidirectional type inference is to add an auxiliary
  14498. function, here named \code{check\_exp}, that takes an expected type
  14499. and checks whether the given expression is of that type. Thus, in
  14500. \code{check\_exp}, type information flows in a top-down manner with
  14501. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  14502. function, where type information flows in a primarily bottom-up
  14503. manner.
  14504. %
  14505. The idea then is to use \code{check\_exp} in all the places where we
  14506. already know what the type of an expression should be, such as in the
  14507. \code{return} statement of a top-level function definition, or on the
  14508. right-hand side of an annotated assignment statement.
  14509. Getting back to \code{lambda}, it is straightforward to check a
  14510. \code{lambda} inside \code{check\_exp} because the expected type
  14511. provides the parameter types and the return type. On the other hand,
  14512. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  14513. that we do not allow \code{lambda} in contexts where we don't already
  14514. know its type. This restriction does not incur a loss of
  14515. expressiveness for \LangLam{} because it is straightforward to modify
  14516. a program to sidestep the restriction, for example, by using an
  14517. annotated assignment statement to assign the \code{lambda} to a
  14518. temporary variable.
  14519. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  14520. checker records their type in a \code{has\_type} field. This type
  14521. information is used later in this chapter.
  14522. %
  14523. \fi}
  14524. \begin{figure}[tbp]
  14525. \begin{tcolorbox}[colback=white]
  14526. {\if\edition\racketEd
  14527. \begin{lstlisting}
  14528. (define (type-check-Llambda env)
  14529. (lambda (e)
  14530. (match e
  14531. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  14532. (define-values (new-body bodyT)
  14533. ((type-check-exp (append (map cons xs Ts) env)) body))
  14534. (define ty `(,@Ts -> ,rT))
  14535. (cond
  14536. [(equal? rT bodyT)
  14537. (values (HasType (Lambda params rT new-body) ty) ty)]
  14538. [else
  14539. (error "mismatch in return type" bodyT rT)])]
  14540. ...
  14541. )))
  14542. \end{lstlisting}
  14543. \fi}
  14544. {\if\edition\pythonEd
  14545. \begin{lstlisting}
  14546. class TypeCheckLlambda(TypeCheckLfun):
  14547. def type_check_exp(self, e, env):
  14548. match e:
  14549. case Name(id):
  14550. e.has_type = env[id]
  14551. return env[id]
  14552. case Lambda(params, body):
  14553. raise Exception('cannot synthesize a type for a lambda')
  14554. case Call(Name('arity'), [func]):
  14555. func_t = self.type_check_exp(func, env)
  14556. match func_t:
  14557. case FunctionType(params_t, return_t):
  14558. return IntType()
  14559. case _:
  14560. raise Exception('in arity, unexpected ' + repr(func_t))
  14561. case _:
  14562. return super().type_check_exp(e, env)
  14563. def check_exp(self, e, ty, env):
  14564. match e:
  14565. case Lambda(params, body):
  14566. e.has_type = ty
  14567. match ty:
  14568. case FunctionType(params_t, return_t):
  14569. new_env = env.copy().update(zip(params, params_t))
  14570. self.check_exp(body, return_t, new_env)
  14571. case _:
  14572. raise Exception('lambda does not have type ' + str(ty))
  14573. case Call(func, args):
  14574. func_t = self.type_check_exp(func, env)
  14575. match func_t:
  14576. case FunctionType(params_t, return_t):
  14577. for (arg, param_t) in zip(args, params_t):
  14578. self.check_exp(arg, param_t, env)
  14579. self.check_type_equal(return_t, ty, e)
  14580. case _:
  14581. raise Exception('type_check_exp: in call, unexpected ' + \
  14582. repr(func_t))
  14583. case _:
  14584. t = self.type_check_exp(e, env)
  14585. self.check_type_equal(t, ty, e)
  14586. \end{lstlisting}
  14587. \fi}
  14588. \end{tcolorbox}
  14589. \caption{Type checking \LangLam{}\python{, part 1}.}
  14590. \label{fig:type-check-Llambda}
  14591. \end{figure}
  14592. {\if\edition\pythonEd
  14593. \begin{figure}[tbp]
  14594. \begin{tcolorbox}[colback=white]
  14595. \begin{lstlisting}
  14596. def check_stmts(self, ss, return_ty, env):
  14597. if len(ss) == 0:
  14598. return
  14599. match ss[0]:
  14600. case FunctionDef(name, params, body, dl, returns, comment):
  14601. new_env = env.copy().update(params)
  14602. rt = self.check_stmts(body, returns, new_env)
  14603. self.check_stmts(ss[1:], return_ty, env)
  14604. case Return(value):
  14605. self.check_exp(value, return_ty, env)
  14606. case Assign([Name(id)], value):
  14607. if id in env:
  14608. self.check_exp(value, env[id], env)
  14609. else:
  14610. env[id] = self.type_check_exp(value, env)
  14611. self.check_stmts(ss[1:], return_ty, env)
  14612. case Assign([Subscript(tup, Constant(index), Store())], value):
  14613. tup_t = self.type_check_exp(tup, env)
  14614. match tup_t:
  14615. case TupleType(ts):
  14616. self.check_exp(value, ts[index], env)
  14617. case _:
  14618. raise Exception('expected a tuple, not ' + repr(tup_t))
  14619. self.check_stmts(ss[1:], return_ty, env)
  14620. case AnnAssign(Name(id), ty_annot, value, simple):
  14621. ss[0].annotation = ty_annot
  14622. if id in env:
  14623. self.check_type_equal(env[id], ty_annot)
  14624. else:
  14625. env[id] = ty_annot
  14626. self.check_exp(value, ty_annot, env)
  14627. self.check_stmts(ss[1:], return_ty, env)
  14628. case _:
  14629. self.type_check_stmts(ss, env)
  14630. def type_check(self, p):
  14631. match p:
  14632. case Module(body):
  14633. env = {}
  14634. for s in body:
  14635. match s:
  14636. case FunctionDef(name, params, bod, dl, returns, comment):
  14637. params_t = [t for (x,t) in params]
  14638. env[name] = FunctionType(params_t, returns)
  14639. self.check_stmts(body, int, env)
  14640. \end{lstlisting}
  14641. \end{tcolorbox}
  14642. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14643. \label{fig:type-check-Llambda-part2}
  14644. \end{figure}
  14645. \fi}
  14646. \clearpage
  14647. \section{Assignment and Lexically Scoped Functions}
  14648. \label{sec:assignment-scoping}
  14649. The combination of lexically-scoped functions and assignment to
  14650. variables raises a challenge with the flat-closure approach to
  14651. implementing lexically-scoped functions. Consider the following
  14652. example in which function \code{f} has a free variable \code{x} that
  14653. is changed after \code{f} is created but before the call to \code{f}.
  14654. % loop_test_11.rkt
  14655. {\if\edition\racketEd
  14656. \begin{lstlisting}
  14657. (let ([x 0])
  14658. (let ([y 0])
  14659. (let ([z 20])
  14660. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14661. (begin
  14662. (set! x 10)
  14663. (set! y 12)
  14664. (f y))))))
  14665. \end{lstlisting}
  14666. \fi}
  14667. {\if\edition\pythonEd
  14668. % box_free_assign.py
  14669. \begin{lstlisting}
  14670. def g(z : int) -> int:
  14671. x = 0
  14672. y = 0
  14673. f : Callable[[int],int] = lambda a: a + x + z
  14674. x = 10
  14675. y = 12
  14676. return f(y)
  14677. print( g(20) )
  14678. \end{lstlisting}
  14679. \fi} The correct output for this example is \code{42} because the call
  14680. to \code{f} is required to use the current value of \code{x} (which is
  14681. \code{10}). Unfortunately, the closure conversion pass
  14682. (section~\ref{sec:closure-conversion}) generates code for the
  14683. \code{lambda} that copies the old value of \code{x} into a
  14684. closure. Thus, if we naively apply closure conversion, the output of
  14685. this program would be \code{32}.
  14686. A first attempt at solving this problem would be to save a pointer to
  14687. \code{x} in the closure and change the occurrences of \code{x} inside
  14688. the lambda to dereference the pointer. Of course, this would require
  14689. assigning \code{x} to the stack and not to a register. However, the
  14690. problem goes a bit deeper.
  14691. Consider the following example that returns a function that refers to
  14692. a local variable of the enclosing function.
  14693. \begin{center}
  14694. \begin{minipage}{\textwidth}
  14695. {\if\edition\racketEd
  14696. \begin{lstlisting}
  14697. (define (f []) : Integer
  14698. (let ([x 0])
  14699. (let ([g (lambda: () : Integer x)])
  14700. (begin
  14701. (set! x 42)
  14702. g))))
  14703. ((f))
  14704. \end{lstlisting}
  14705. \fi}
  14706. {\if\edition\pythonEd
  14707. % counter.py
  14708. \begin{lstlisting}
  14709. def f():
  14710. x = 0
  14711. g = lambda: x
  14712. x = 42
  14713. return g
  14714. print( f()() )
  14715. \end{lstlisting}
  14716. \fi}
  14717. \end{minipage}
  14718. \end{center}
  14719. In this example, the lifetime of \code{x} extends beyond the lifetime
  14720. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14721. stack frame for the call to \code{f}, it would be gone by the time we
  14722. call \code{g}, leaving us with dangling pointers for
  14723. \code{x}. This example demonstrates that when a variable occurs free
  14724. inside a function, its lifetime becomes indefinite. Thus, the value of
  14725. the variable needs to live on the heap. The verb
  14726. \emph{box}\index{subject}{box} is often used for allocating a single
  14727. value on the heap, producing a pointer, and
  14728. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14729. %
  14730. We introduce a new pass named \code{convert\_assignments} to address
  14731. this challenge.
  14732. %
  14733. \python{But before diving into that, we have one more
  14734. problem to discuss.}
  14735. \if\edition\pythonEd
  14736. \section{Uniquify Variables}
  14737. \label{sec:uniquify-lambda}
  14738. With the addition of \code{lambda} we have a complication to deal
  14739. with: name shadowing. Consider the following program with a function
  14740. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14741. \code{lambda} expressions. The first \code{lambda} has a parameter
  14742. that is also named \code{x}.
  14743. \begin{lstlisting}
  14744. def f(x:int, y:int) -> Callable[[int], int]:
  14745. g : Callable[[int],int] = (lambda x: x + y)
  14746. h : Callable[[int],int] = (lambda y: x + y)
  14747. x = input_int()
  14748. return g
  14749. print(f(0, 10)(32))
  14750. \end{lstlisting}
  14751. Many of our compiler passes rely on being able to connect variable
  14752. uses with their definitions using just the name of the variable,
  14753. including new passes in this chapter. However, in the above example
  14754. the name of the variable does not uniquely determine its
  14755. definition. To solve this problem we recommend implementing a pass
  14756. named \code{uniquify} that renames every variable in the program to
  14757. make sure they are all unique.
  14758. The following shows the result of \code{uniquify} for the above
  14759. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14760. and the \code{x} parameter of the \code{lambda} is renamed to
  14761. \code{x\_4}.
  14762. \begin{lstlisting}
  14763. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14764. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14765. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14766. x_0 = input_int()
  14767. return g_2
  14768. def main() -> int :
  14769. print(f(0, 10)(32))
  14770. return 0
  14771. \end{lstlisting}
  14772. \fi
  14773. %% \section{Reveal Functions}
  14774. %% \label{sec:reveal-functions-r5}
  14775. %% \racket{To support the \code{procedure-arity} operator we need to
  14776. %% communicate the arity of a function to the point of closure
  14777. %% creation.}
  14778. %% %
  14779. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  14780. %% function at runtime. Thus, we need to communicate the arity of a
  14781. %% function to the point of closure creation.}
  14782. %% %
  14783. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14784. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14785. %% \[
  14786. %% \begin{array}{lcl}
  14787. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14788. %% \end{array}
  14789. %% \]
  14790. \section{Assignment Conversion}
  14791. \label{sec:convert-assignments}
  14792. The purpose of the \code{convert\_assignments} pass is to address the
  14793. challenge regarding the interaction between variable assignments and
  14794. closure conversion. First we identify which variables need to be
  14795. boxed, then we transform the program to box those variables. In
  14796. general, boxing introduces runtime overhead that we would like to
  14797. avoid, so we should box as few variables as possible. We recommend
  14798. boxing the variables in the intersection of the following two sets of
  14799. variables:
  14800. \begin{enumerate}
  14801. \item The variables that are free in a \code{lambda}.
  14802. \item The variables that appear on the left-hand side of an
  14803. assignment.
  14804. \end{enumerate}
  14805. The first condition is a must but the second condition is
  14806. conservative. It is possible to develop a more liberal condition using
  14807. static program analysis.
  14808. Consider again the first example from
  14809. section~\ref{sec:assignment-scoping}:
  14810. %
  14811. {\if\edition\racketEd
  14812. \begin{lstlisting}
  14813. (let ([x 0])
  14814. (let ([y 0])
  14815. (let ([z 20])
  14816. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14817. (begin
  14818. (set! x 10)
  14819. (set! y 12)
  14820. (f y))))))
  14821. \end{lstlisting}
  14822. \fi}
  14823. {\if\edition\pythonEd
  14824. \begin{lstlisting}
  14825. def g(z : int) -> int:
  14826. x = 0
  14827. y = 0
  14828. f : Callable[[int],int] = lambda a: a + x + z
  14829. x = 10
  14830. y = 12
  14831. return f(y)
  14832. print( g(20) )
  14833. \end{lstlisting}
  14834. \fi}
  14835. %
  14836. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14837. variables \code{x} and \code{z} occur free inside the
  14838. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14839. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14840. transformations: initialize \code{x} with a tuple whose elements are uninitialized,
  14841. replace reads from \code{x} with tuple reads, and replace each assignment to \code{x}
  14842. with a tuple write. The output of \code{convert\_assignments} for
  14843. this example is as follows.
  14844. %
  14845. {\if\edition\racketEd
  14846. \begin{lstlisting}
  14847. (define (main) : Integer
  14848. (let ([x0 (vector 0)])
  14849. (let ([y1 0])
  14850. (let ([z2 20])
  14851. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14852. (+ a3 (+ (vector-ref x0 0) z2)))])
  14853. (begin
  14854. (vector-set! x0 0 10)
  14855. (set! y1 12)
  14856. (f4 y1)))))))
  14857. \end{lstlisting}
  14858. \fi}
  14859. %
  14860. {\if\edition\pythonEd
  14861. \begin{lstlisting}
  14862. def g(z : int)-> int:
  14863. x = (uninitialized(int),)
  14864. x[0] = 0
  14865. y = 0
  14866. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14867. x[0] = 10
  14868. y = 12
  14869. return f(y)
  14870. def main() -> int:
  14871. print(g(20))
  14872. return 0
  14873. \end{lstlisting}
  14874. \fi}
  14875. To compute the free variables of all the \code{lambda} expressions, we
  14876. recommend defining two auxiliary functions:
  14877. \begin{enumerate}
  14878. \item \code{free\_variables} computes the free variables of an expression, and
  14879. \item \code{free\_in\_lambda} collects all of the variables that are
  14880. free in any of the \code{lambda} expressions, using
  14881. \code{free\_variables} in the case for each \code{lambda}.
  14882. \end{enumerate}
  14883. {\if\edition\racketEd
  14884. %
  14885. To compute the variables that are assigned-to, we recommend using the
  14886. \code{collect-set!} function that we introduced in
  14887. section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14888. forms such as \code{Lambda}.
  14889. %
  14890. \fi}
  14891. {\if\edition\pythonEd
  14892. %
  14893. To compute the variables that are assigned-to, we recommend defining
  14894. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14895. the set of variables that occur in the left-hand side of an assignment
  14896. statement, and otherwise returns the empty set.
  14897. %
  14898. \fi}
  14899. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14900. free in a \code{lambda} and that are assigned-to in the enclosing
  14901. function definition.
  14902. Next we discuss the \code{convert\_assignments} pass. In the case for
  14903. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14904. $\VAR{x}$ to a tuple read.
  14905. %
  14906. {\if\edition\racketEd
  14907. \begin{lstlisting}
  14908. (Var |$x$|)
  14909. |$\Rightarrow$|
  14910. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14911. \end{lstlisting}
  14912. \fi}
  14913. %
  14914. {\if\edition\pythonEd
  14915. \begin{lstlisting}
  14916. Name(|$x$|)
  14917. |$\Rightarrow$|
  14918. Subscript(Name(|$x$|), Constant(0), Load())
  14919. \end{lstlisting}
  14920. \fi}
  14921. %
  14922. \noindent In the case for assignment, recursively process the
  14923. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  14924. $x$ is in $\mathit{AF}$, translate the assignment into a tuple-write
  14925. as follows.
  14926. %
  14927. {\if\edition\racketEd
  14928. \begin{lstlisting}
  14929. (SetBang |$x$| |$\itm{rhs}$|)
  14930. |$\Rightarrow$|
  14931. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14932. \end{lstlisting}
  14933. \fi}
  14934. {\if\edition\pythonEd
  14935. \begin{lstlisting}
  14936. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14937. |$\Rightarrow$|
  14938. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14939. \end{lstlisting}
  14940. \fi}
  14941. %
  14942. {\if\edition\racketEd
  14943. The case for \code{Lambda} is non-trivial, but it is similar to the
  14944. case for function definitions, which we discuss next.
  14945. \fi}
  14946. %
  14947. To translate a function definition, we first compute $\mathit{AF}$,
  14948. the intersection of the variables that are free in a \code{lambda} and
  14949. that are assigned-to. We then apply assignment conversion to the body
  14950. of the function definition. Finally, we box the parameters of this
  14951. function definition that are in $\mathit{AF}$. For example,
  14952. the parameter \code{x} of the following function \code{g}
  14953. needs to be boxed.
  14954. {\if\edition\racketEd
  14955. \begin{lstlisting}
  14956. (define (g [x : Integer]) : Integer
  14957. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14958. (begin
  14959. (set! x 10)
  14960. (f 32))))
  14961. \end{lstlisting}
  14962. \fi}
  14963. %
  14964. {\if\edition\pythonEd
  14965. \begin{lstlisting}
  14966. def g(x : int) -> int:
  14967. f : Callable[[int],int] = lambda a: a + x
  14968. x = 10
  14969. return f(32)
  14970. \end{lstlisting}
  14971. \fi}
  14972. %
  14973. \noindent We box parameter \code{x} by creating a local variable named
  14974. \code{x} that is initialized to a tuple whose contents is the value of
  14975. the parameter, which has been renamed to \code{x\_0}.
  14976. %
  14977. {\if\edition\racketEd
  14978. \begin{lstlisting}
  14979. (define (g [x_0 : Integer]) : Integer
  14980. (let ([x (vector x_0)])
  14981. (let ([f (lambda: ([a : Integer]) : Integer
  14982. (+ a (vector-ref x 0)))])
  14983. (begin
  14984. (vector-set! x 0 10)
  14985. (f 32)))))
  14986. \end{lstlisting}
  14987. \fi}
  14988. %
  14989. {\if\edition\pythonEd
  14990. \begin{lstlisting}
  14991. def g(x_0 : int)-> int:
  14992. x = (x_0,)
  14993. f : Callable[[int], int] = (lambda a: a + x[0])
  14994. x[0] = 10
  14995. return f(32)
  14996. \end{lstlisting}
  14997. \fi}
  14998. \section{Closure Conversion}
  14999. \label{sec:closure-conversion}
  15000. \index{subject}{closure conversion}
  15001. The compiling of lexically-scoped functions into top-level function
  15002. definitions and flat closures is accomplished in the pass
  15003. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15004. and before \code{limit\_functions}.
  15005. As usual, we implement the pass as a recursive function over the
  15006. AST. The interesting cases are the ones for \key{lambda} and function
  15007. application. We transform a \key{lambda} expression into an expression
  15008. that creates a closure, that is, a tuple whose first element is a
  15009. function pointer and the rest of the elements are the values of the
  15010. free variables of the \key{lambda}.
  15011. %
  15012. However, we use the \code{Closure} AST node instead of using a tuple
  15013. so that we can record the arity.
  15014. %
  15015. In the generated code below, \itm{fvs} is the free variables of the
  15016. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  15017. %
  15018. \racket{The \itm{arity} is the number of parameters (the length of
  15019. \itm{ps}).}
  15020. %
  15021. {\if\edition\racketEd
  15022. \begin{lstlisting}
  15023. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15024. |$\Rightarrow$|
  15025. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15026. \end{lstlisting}
  15027. \fi}
  15028. %
  15029. {\if\edition\pythonEd
  15030. \begin{lstlisting}
  15031. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15032. |$\Rightarrow$|
  15033. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15034. \end{lstlisting}
  15035. \fi}
  15036. %
  15037. In addition to transforming each \key{Lambda} AST node into a
  15038. tuple, we create a top-level function definition for each
  15039. \key{Lambda}, as shown below.\\
  15040. \begin{minipage}{0.8\textwidth}
  15041. {\if\edition\racketEd
  15042. \begin{lstlisting}
  15043. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15044. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15045. ...
  15046. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15047. |\itm{body'}|)...))
  15048. \end{lstlisting}
  15049. \fi}
  15050. {\if\edition\pythonEd
  15051. \begin{lstlisting}
  15052. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15053. |$\itm{fvs}_1$| = clos[1]
  15054. |$\ldots$|
  15055. |$\itm{fvs}_n$| = clos[|$n$|]
  15056. |\itm{body'}|
  15057. \end{lstlisting}
  15058. \fi}
  15059. \end{minipage}\\
  15060. The \code{clos} parameter refers to the closure. Translate the type
  15061. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15062. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15063. \itm{closTy} is a tuple type whose first element type is
  15064. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15065. the element types are the types of the free variables in the
  15066. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15067. is non-trivial to give a type to the function in the closure's type.%
  15068. %
  15069. \footnote{To give an accurate type to a closure, we would need to add
  15070. existential types to the type checker~\citep{Minamide:1996ys}.}
  15071. %
  15072. %% The dummy type is considered to be equal to any other type during type
  15073. %% checking.
  15074. The free variables become local variables that are initialized with
  15075. their values in the closure.
  15076. Closure conversion turns every function into a tuple, so the type
  15077. annotations in the program must also be translated. We recommend
  15078. defining an auxiliary recursive function for this purpose. Function
  15079. types should be translated as follows.
  15080. %
  15081. {\if\edition\racketEd
  15082. \begin{lstlisting}
  15083. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15084. |$\Rightarrow$|
  15085. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15086. \end{lstlisting}
  15087. \fi}
  15088. {\if\edition\pythonEd
  15089. \begin{lstlisting}
  15090. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15091. |$\Rightarrow$|
  15092. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15093. \end{lstlisting}
  15094. \fi}
  15095. %
  15096. The above type says that the first thing in the tuple is a
  15097. function. The first parameter of the function is a tuple (a closure)
  15098. and the rest of the parameters are the ones from the original
  15099. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15100. omits the types of the free variables because 1) those types are not
  15101. available in this context and 2) we do not need them in the code that
  15102. is generated for function application. So this type only describes the
  15103. first component of the closure tuple. At runtime the tuple may have
  15104. more components, but we ignore them at this point.
  15105. We transform function application into code that retrieves the
  15106. function from the closure and then calls the function, passing the
  15107. closure as the first argument. We place $e'$ in a temporary variable
  15108. to avoid code duplication.
  15109. \begin{center}
  15110. \begin{minipage}{\textwidth}
  15111. {\if\edition\racketEd
  15112. \begin{lstlisting}
  15113. (Apply |$e$| |$\itm{es}$|)
  15114. |$\Rightarrow$|
  15115. (Let |$\itm{tmp}$| |$e'$|
  15116. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  15117. \end{lstlisting}
  15118. \fi}
  15119. %
  15120. {\if\edition\pythonEd
  15121. \begin{lstlisting}
  15122. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  15123. |$\Rightarrow$|
  15124. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  15125. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  15126. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  15127. \end{lstlisting}
  15128. \fi}
  15129. \end{minipage}
  15130. \end{center}
  15131. There is also the question of what to do with references to top-level
  15132. function definitions. To maintain a uniform translation of function
  15133. application, we turn function references into closures.
  15134. \begin{tabular}{lll}
  15135. \begin{minipage}{0.3\textwidth}
  15136. {\if\edition\racketEd
  15137. \begin{lstlisting}
  15138. (FunRef |$f$| |$n$|)
  15139. \end{lstlisting}
  15140. \fi}
  15141. {\if\edition\pythonEd
  15142. \begin{lstlisting}
  15143. FunRef(|$f$|, |$n$|)
  15144. \end{lstlisting}
  15145. \fi}
  15146. \end{minipage}
  15147. &
  15148. $\Rightarrow$
  15149. &
  15150. \begin{minipage}{0.5\textwidth}
  15151. {\if\edition\racketEd
  15152. \begin{lstlisting}
  15153. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  15154. \end{lstlisting}
  15155. \fi}
  15156. {\if\edition\pythonEd
  15157. \begin{lstlisting}
  15158. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  15159. \end{lstlisting}
  15160. \fi}
  15161. \end{minipage}
  15162. \end{tabular} \\
  15163. We no longer need the annotated assignment statement \code{AnnAssign}
  15164. to support the type checking of \code{lambda} expressions, so we
  15165. translate it to a regular \code{Assign} statement.
  15166. The top-level function definitions need to be updated to take an extra
  15167. closure parameter but that parameter is ignored in the body of those
  15168. functions.
  15169. \section{An Example Translation}
  15170. \label{sec:example-lambda}
  15171. Figure~\ref{fig:lexical-functions-example} shows the result of
  15172. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  15173. program demonstrating lexical scoping that we discussed at the
  15174. beginning of this chapter.
  15175. \begin{figure}[tbp]
  15176. \begin{tcolorbox}[colback=white]
  15177. \begin{minipage}{0.8\textwidth}
  15178. {\if\edition\racketEd
  15179. % tests/lambda_test_6.rkt
  15180. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15181. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  15182. (let ([y8 4])
  15183. (lambda: ([z9 : Integer]) : Integer
  15184. (+ x7 (+ y8 z9)))))
  15185. (define (main) : Integer
  15186. (let ([g0 ((fun-ref f6 1) 5)])
  15187. (let ([h1 ((fun-ref f6 1) 3)])
  15188. (+ (g0 11) (h1 15)))))
  15189. \end{lstlisting}
  15190. $\Rightarrow$
  15191. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15192. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  15193. (let ([y8 4])
  15194. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  15195. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  15196. (let ([x7 (vector-ref fvs3 1)])
  15197. (let ([y8 (vector-ref fvs3 2)])
  15198. (+ x7 (+ y8 z9)))))
  15199. (define (main) : Integer
  15200. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  15201. ((vector-ref clos5 0) clos5 5))])
  15202. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  15203. ((vector-ref clos6 0) clos6 3))])
  15204. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  15205. \end{lstlisting}
  15206. \fi}
  15207. %
  15208. {\if\edition\pythonEd
  15209. % free_var.py
  15210. \begin{lstlisting}
  15211. def f(x : int) -> Callable[[int], int]:
  15212. y = 4
  15213. return lambda z: x + y + z
  15214. g = f(5)
  15215. h = f(3)
  15216. print( g(11) + h(15) )
  15217. \end{lstlisting}
  15218. $\Rightarrow$
  15219. \begin{lstlisting}
  15220. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  15221. x = fvs_1[1]
  15222. y = fvs_1[2]
  15223. return x + y[0] + z
  15224. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  15225. y = (777,)
  15226. y[0] = 4
  15227. return (lambda_0, x, y)
  15228. def main() -> int:
  15229. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  15230. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  15231. print((let clos_5 = g in clos_5[0](clos_5, 11))
  15232. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  15233. return 0
  15234. \end{lstlisting}
  15235. \fi}
  15236. \end{minipage}
  15237. \end{tcolorbox}
  15238. \caption{Example of closure conversion.}
  15239. \label{fig:lexical-functions-example}
  15240. \end{figure}
  15241. \begin{exercise}\normalfont\normalsize
  15242. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  15243. Create 5 new programs that use \key{lambda} functions and make use of
  15244. lexical scoping. Test your compiler on these new programs and all of
  15245. your previously created test programs.
  15246. \end{exercise}
  15247. \section{Expose Allocation}
  15248. \label{sec:expose-allocation-r5}
  15249. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  15250. that allocates and initializes a tuple, similar to the translation of
  15251. the tuple creation in section~\ref{sec:expose-allocation}.
  15252. The only difference is replacing the use of
  15253. \ALLOC{\itm{len}}{\itm{type}} with
  15254. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  15255. \section{Explicate Control and \LangCLam{}}
  15256. \label{sec:explicate-r5}
  15257. The output language of \code{explicate\_control} is \LangCLam{} whose
  15258. abstract syntax is defined in figure~\ref{fig:Clam-syntax}.
  15259. %
  15260. \racket{The only differences with respect to \LangCFun{} is the
  15261. addition of the \code{AllocateClosure} form to the grammar for
  15262. $\Exp$ and the \code{procedure-arity} operator. The handling of
  15263. \code{AllocateClosure} in the \code{explicate\_control} pass is
  15264. similar to the handling of other expressions such as primitive
  15265. operators.}
  15266. %
  15267. \python{The differences with respect to \LangCFun{} are the
  15268. additions of \code{Uninitialized}, \code{AllocateClosure},
  15269. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  15270. \code{explicate\_control} pass is similar to the handling of other
  15271. expressions such as primitive operators.}
  15272. \newcommand{\ClambdaASTRacket}{
  15273. \begin{array}{lcl}
  15274. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  15275. \itm{op} &::= & \code{procedure-arity}
  15276. \end{array}
  15277. }
  15278. \newcommand{\ClambdaASTPython}{
  15279. \begin{array}{lcl}
  15280. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  15281. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  15282. &\MID& \ARITY{\Atm}
  15283. \end{array}
  15284. }
  15285. \begin{figure}[tp]
  15286. \begin{tcolorbox}[colback=white]
  15287. \small
  15288. {\if\edition\racketEd
  15289. \[
  15290. \begin{array}{l}
  15291. \gray{\CvarASTRacket} \\ \hline
  15292. \gray{\CifASTRacket} \\ \hline
  15293. \gray{\CloopASTRacket} \\ \hline
  15294. \gray{\CtupASTRacket} \\ \hline
  15295. \gray{\CfunASTRacket} \\ \hline
  15296. \ClambdaASTRacket \\
  15297. \begin{array}{lcl}
  15298. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  15299. \end{array}
  15300. \end{array}
  15301. \]
  15302. \fi}
  15303. {\if\edition\pythonEd
  15304. \[
  15305. \begin{array}{l}
  15306. \gray{\CifASTPython} \\ \hline
  15307. \gray{\CtupASTPython} \\ \hline
  15308. \gray{\CfunASTPython} \\ \hline
  15309. \ClambdaASTPython \\
  15310. \begin{array}{lcl}
  15311. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  15312. \end{array}
  15313. \end{array}
  15314. \]
  15315. \fi}
  15316. \end{tcolorbox}
  15317. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  15318. \label{fig:Clam-syntax}
  15319. \end{figure}
  15320. \section{Select Instructions}
  15321. \label{sec:select-instructions-Llambda}
  15322. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  15323. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  15324. (section~\ref{sec:select-instructions-gc}). The only difference is
  15325. that you should place the \itm{arity} in the tag that is stored at
  15326. position $0$ of the vector. Recall that in
  15327. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  15328. was not used. We store the arity in the $5$ bits starting at position
  15329. $58$.
  15330. \racket{Compile the \code{procedure-arity} operator into a sequence of
  15331. instructions that access the tag from position $0$ of the vector and
  15332. extract the $5$-bits starting at position $58$ from the tag.}
  15333. %
  15334. \python{Compile a call to the \code{arity} operator to a sequence of
  15335. instructions that access the tag from position $0$ of the tuple
  15336. (representing a closure) and extract the $5$-bits starting at position
  15337. $58$ from the tag.}
  15338. \begin{figure}[p]
  15339. \begin{tcolorbox}[colback=white]
  15340. {\if\edition\racketEd
  15341. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15342. \node (Lfun) at (0,2) {\large \LangLam{}};
  15343. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  15344. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  15345. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  15346. \node (F1-1) at (12,2) {\large \LangLamFunRef{}};
  15347. \node (F1-2) at (12,0) {\large \LangFunRef{}};
  15348. \node (F1-3) at (9,0) {\large \LangFunRef{}};
  15349. \node (F1-4) at (6,0) {\large \LangFunRefAlloc{}};
  15350. \node (F1-5) at (3,0) {\large \LangFunRefAlloc{}};
  15351. \node (F1-6) at (0,0) {\large \LangFunANF{}};
  15352. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  15353. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15354. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15355. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15356. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15357. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15358. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15359. \path[->,bend left=15] (Lfun) edge [above] node
  15360. {\ttfamily\footnotesize shrink} (Lfun-2);
  15361. \path[->,bend left=15] (Lfun-2) edge [above] node
  15362. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15363. \path[->,bend left=15] (Lfun-3) edge [above] node
  15364. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15365. \path[->,bend left=15] (F1-0) edge [above] node
  15366. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  15367. \path[->,bend left=15] (F1-1) edge [left] node
  15368. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15369. \path[->,bend left=15] (F1-2) edge [below] node
  15370. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15371. \path[->,bend right=15] (F1-3) edge [above] node
  15372. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15373. \path[->,bend left=15] (F1-4) edge [below] node
  15374. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  15375. \path[->,bend right=15] (F1-5) edge [above] node
  15376. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  15377. \path[->,bend right=15] (F1-6) edge [right] node
  15378. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15379. \path[->,bend left=15] (C3-2) edge [left] node
  15380. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15381. \path[->,bend right=15] (x86-2) edge [left] node
  15382. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15383. \path[->,bend right=15] (x86-2-1) edge [below] node
  15384. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15385. \path[->,bend right=15] (x86-2-2) edge [left] node
  15386. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15387. \path[->,bend left=15] (x86-3) edge [above] node
  15388. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15389. \path[->,bend left=15] (x86-4) edge [right] node
  15390. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  15391. \end{tikzpicture}
  15392. \fi}
  15393. {\if\edition\pythonEd
  15394. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15395. \node (Lfun) at (0,2) {\large \LangLam{}};
  15396. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  15397. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  15398. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  15399. \node (F1-1) at (12,2) {\large \LangLamFunRef{}};
  15400. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  15401. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  15402. \node (F1-5) at (3,0) {\large \LangFunRefAlloc{}};
  15403. \node (F1-6) at (0,0) {\large \LangFunANF{}};
  15404. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15405. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15406. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15407. \node (x86-2-2) at (3,-6) {\large \LangXIndCallVar{}};
  15408. \node (x86-3) at (3,-4) {\large \LangXIndCallVar{}};
  15409. \node (x86-4) at (6,-4) {\large \LangXIndCall{}};
  15410. \node (x86-5) at (6,-6) {\large \LangXIndCall{}};
  15411. \path[->,bend left=15] (Lfun) edge [above] node
  15412. {\ttfamily\footnotesize shrink} (Lfun-2);
  15413. \path[->,bend left=15] (Lfun-2) edge [above] node
  15414. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15415. \path[->,bend left=15] (Lfun-3) edge [above] node
  15416. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15417. \path[->,bend left=15] (F1-0) edge [above] node
  15418. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  15419. \path[->,bend left=15] (F1-1) edge [left] node
  15420. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15421. \path[->,bend left=15] (F1-2) edge [below] node
  15422. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15423. \path[->,bend right=15] (F1-3) edge [above] node
  15424. {\ttfamily\footnotesize expose\_alloc.} (F1-5);
  15425. \path[->,bend right=15] (F1-5) edge [above] node
  15426. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  15427. \path[->,bend right=15] (F1-6) edge [right] node
  15428. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15429. \path[->,bend left=15] (C3-2) edge [right] node
  15430. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15431. \path[->,bend right=15] (x86-2) edge [right] node
  15432. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15433. \path[->,bend right=15] (x86-2-1) edge [below] node
  15434. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15435. \path[->,bend right=15] (x86-2-2) edge [right] node
  15436. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15437. \path[->,bend left=15] (x86-3) edge [above] node
  15438. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15439. \path[->,bend left=15] (x86-4) edge [right] node
  15440. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15441. \end{tikzpicture}
  15442. \fi}
  15443. \end{tcolorbox}
  15444. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  15445. functions.}
  15446. \label{fig:Llambda-passes}
  15447. \end{figure}
  15448. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  15449. needed for the compilation of \LangLam{}.
  15450. \clearpage
  15451. \section{Challenge: Optimize Closures}
  15452. \label{sec:optimize-closures}
  15453. In this chapter we compiled lexically-scoped functions into a
  15454. relatively efficient representation: flat closures. However, even this
  15455. representation comes with some overhead. For example, consider the
  15456. following program with a function \code{tail\_sum} that does not have
  15457. any free variables and where all the uses of \code{tail\_sum} are in
  15458. applications where we know that only \code{tail\_sum} is being applied
  15459. (and not any other functions).
  15460. \begin{center}
  15461. \begin{minipage}{0.95\textwidth}
  15462. {\if\edition\racketEd
  15463. \begin{lstlisting}
  15464. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  15465. (if (eq? n 0)
  15466. s
  15467. (tail_sum (- n 1) (+ n s))))
  15468. (+ (tail_sum 3 0) 36)
  15469. \end{lstlisting}
  15470. \fi}
  15471. {\if\edition\pythonEd
  15472. \begin{lstlisting}
  15473. def tail_sum(n : int, s : int) -> int:
  15474. if n == 0:
  15475. return s
  15476. else:
  15477. return tail_sum(n - 1, n + s)
  15478. print( tail_sum(3, 0) + 36)
  15479. \end{lstlisting}
  15480. \fi}
  15481. \end{minipage}
  15482. \end{center}
  15483. As described in this chapter, we uniformly apply closure conversion to
  15484. all functions, obtaining the following output for this program.
  15485. \begin{center}
  15486. \begin{minipage}{0.95\textwidth}
  15487. {\if\edition\racketEd
  15488. \begin{lstlisting}
  15489. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  15490. (if (eq? n2 0)
  15491. s3
  15492. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  15493. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  15494. (define (main) : Integer
  15495. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  15496. ((vector-ref clos6 0) clos6 3 0)) 27))
  15497. \end{lstlisting}
  15498. \fi}
  15499. {\if\edition\pythonEd
  15500. \begin{lstlisting}
  15501. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  15502. if n_0 == 0:
  15503. return s_1
  15504. else:
  15505. return (let clos_2 = (tail_sum,)
  15506. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  15507. def main() -> int :
  15508. print((let clos_4 = (tail_sum,)
  15509. in clos_4[0](clos_4, 3, 0)) + 36)
  15510. return 0
  15511. \end{lstlisting}
  15512. \fi}
  15513. \end{minipage}
  15514. \end{center}
  15515. In the previous chapter, there would be no allocation in the program
  15516. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  15517. the above program allocates memory for each closure and the calls to
  15518. \code{tail\_sum} are indirect. These two differences incur
  15519. considerable overhead in a program such as this one, where the
  15520. allocations and indirect calls occur inside a tight loop.
  15521. One might think that this problem is trivial to solve: can't we just
  15522. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  15523. and compile them to direct calls instead of treating it like a call to
  15524. a closure? We would also drop the new \code{fvs} parameter of
  15525. \code{tail\_sum}.
  15526. %
  15527. However, this problem is not so trivial because a global function may
  15528. ``escape'' and become involved in applications that also involve
  15529. closures. Consider the following example in which the application
  15530. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  15531. application, because the \code{lambda} may flow into \code{f}, but the
  15532. \code{inc} function might also flow into \code{f}.
  15533. \begin{center}
  15534. \begin{minipage}{\textwidth}
  15535. % lambda_test_30.rkt
  15536. {\if\edition\racketEd
  15537. \begin{lstlisting}
  15538. (define (inc [x : Integer]) : Integer
  15539. (+ x 1))
  15540. (let ([y (read)])
  15541. (let ([f (if (eq? (read) 0)
  15542. inc
  15543. (lambda: ([x : Integer]) : Integer (- x y)))])
  15544. (f 41)))
  15545. \end{lstlisting}
  15546. \fi}
  15547. {\if\edition\pythonEd
  15548. \begin{lstlisting}
  15549. def add1(x : int) -> int:
  15550. return x + 1
  15551. y = input_int()
  15552. g : Callable[[int], int] = lambda x: x - y
  15553. f = add1 if input_int() == 0 else g
  15554. print( f(41) )
  15555. \end{lstlisting}
  15556. \fi}
  15557. \end{minipage}
  15558. \end{center}
  15559. If a global function name is used in any way other than as the
  15560. operator in a direct call, then we say that the function
  15561. \emph{escapes}. If a global function does not escape, then we do not
  15562. need to perform closure conversion on the function.
  15563. \begin{exercise}\normalfont\normalsize
  15564. Implement an auxiliary function for detecting which global
  15565. functions escape. Using that function, implement an improved version
  15566. of closure conversion that does not apply closure conversion to
  15567. global functions that do not escape but instead compiles them as
  15568. regular functions. Create several new test cases that check whether
  15569. you properly detect whether global functions escape or not.
  15570. \end{exercise}
  15571. So far we have reduced the overhead of calling global functions, but
  15572. it would also be nice to reduce the overhead of calling a
  15573. \code{lambda} when we can determine at compile time which
  15574. \code{lambda} will be called. We refer to such calls as \emph{known
  15575. calls}. Consider the following example in which a \code{lambda} is
  15576. bound to \code{f} and then applied.
  15577. {\if\edition\racketEd
  15578. % lambda_test_9.rkt
  15579. \begin{lstlisting}
  15580. (let ([y (read)])
  15581. (let ([f (lambda: ([x : Integer]) : Integer
  15582. (+ x y))])
  15583. (f 21)))
  15584. \end{lstlisting}
  15585. \fi}
  15586. {\if\edition\pythonEd
  15587. \begin{lstlisting}
  15588. y = input_int()
  15589. f : Callable[[int],int] = lambda x: x + y
  15590. print( f(21) )
  15591. \end{lstlisting}
  15592. \fi}
  15593. %
  15594. \noindent Closure conversion compiles the application
  15595. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  15596. %
  15597. {\if\edition\racketEd
  15598. \begin{lstlisting}
  15599. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15600. (let ([y2 (vector-ref fvs6 1)])
  15601. (+ x3 y2)))
  15602. (define (main) : Integer
  15603. (let ([y2 (read)])
  15604. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15605. ((vector-ref f4 0) f4 21))))
  15606. \end{lstlisting}
  15607. \fi}
  15608. {\if\edition\pythonEd
  15609. \begin{lstlisting}
  15610. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15611. y_1 = fvs_4[1]
  15612. return x_2 + y_1[0]
  15613. def main() -> int:
  15614. y_1 = (777,)
  15615. y_1[0] = input_int()
  15616. f_0 = (lambda_3, y_1)
  15617. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15618. return 0
  15619. \end{lstlisting}
  15620. \fi}
  15621. %
  15622. \noindent but we can instead compile the application
  15623. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  15624. %
  15625. {\if\edition\racketEd
  15626. \begin{lstlisting}
  15627. (define (main) : Integer
  15628. (let ([y2 (read)])
  15629. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15630. ((fun-ref lambda5 1) f4 21))))
  15631. \end{lstlisting}
  15632. \fi}
  15633. {\if\edition\pythonEd
  15634. \begin{lstlisting}
  15635. def main() -> int:
  15636. y_1 = (777,)
  15637. y_1[0] = input_int()
  15638. f_0 = (lambda_3, y_1)
  15639. print(lambda_3(f_0, 21))
  15640. return 0
  15641. \end{lstlisting}
  15642. \fi}
  15643. The problem of determining which \code{lambda} will be called from a
  15644. particular application is quite challenging in general and the topic
  15645. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15646. following exercise we recommend that you compile an application to a
  15647. direct call when the operator is a variable and \racket{the variable
  15648. is \code{let}-bound to a closure}\python{the previous assignment to
  15649. the variable is a closure}. This can be accomplished by maintaining
  15650. an environment mapping variables to function names. Extend the
  15651. environment whenever you encounter a closure on the right-hand side of
  15652. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15653. name of the global function for the closure. This pass should come
  15654. after closure conversion.
  15655. \begin{exercise}\normalfont\normalsize
  15656. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15657. compiles known calls into direct calls. Verify that your compiler is
  15658. successful in this regard on several example programs.
  15659. \end{exercise}
  15660. These exercises only scratches the surface of optimizing of
  15661. closures. A good next step for the interested reader is to look at the
  15662. work of \citet{Keep:2012ab}.
  15663. \section{Further Reading}
  15664. The notion of lexically scoped functions predates modern computers by
  15665. about a decade. They were invented by \citet{Church:1932aa}, who
  15666. proposed the lambda calculus as a foundation for logic. Anonymous
  15667. functions were included in the LISP~\citep{McCarthy:1960dz}
  15668. programming language but were initially dynamically scoped. The Scheme
  15669. dialect of LISP adopted lexical scoping and
  15670. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15671. Scheme programs. However, environments were represented as linked
  15672. lists, so variable look-up was linear in the size of the
  15673. environment. \citet{Appel91} gives a detailed description of several
  15674. closure representations. In this chapter we represent environments
  15675. using flat closures, which were invented by
  15676. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15677. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15678. closures, variable look-up is constant time but the time to create a
  15679. closure is proportional to the number of its free variables. Flat
  15680. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  15681. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15682. % todo: related work on assignment conversion (e.g. orbit and rabbit
  15683. % compilers)
  15684. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15685. \chapter{Dynamic Typing}
  15686. \label{ch:Ldyn}
  15687. \index{subject}{dynamic typing}
  15688. \setcounter{footnote}{0}
  15689. In this chapter we learn how to compile \LangDyn{}, a dynamically
  15690. typed language that is a subset of \racket{Racket}\python{Python}. The
  15691. focus on dynamic typing is in contrast to the previous chapters, which
  15692. have studied the compilation of statically typed languages. In
  15693. dynamically typed languages such as \LangDyn{}, a particular
  15694. expression may produce a value of a different type each time it is
  15695. executed. Consider the following example with a conditional \code{if}
  15696. expression that may return a Boolean or an integer depending on the
  15697. input to the program.
  15698. % part of dynamic_test_25.rkt
  15699. {\if\edition\racketEd
  15700. \begin{lstlisting}
  15701. (not (if (eq? (read) 1) #f 0))
  15702. \end{lstlisting}
  15703. \fi}
  15704. {\if\edition\pythonEd
  15705. \begin{lstlisting}
  15706. not (False if input_int() == 1 else 0)
  15707. \end{lstlisting}
  15708. \fi}
  15709. Languages that allow expressions to produce different kinds of values
  15710. are called \emph{polymorphic}, a word composed of the Greek roots
  15711. ``poly'', meaning ``many'', and ``morph'', meaning ``form''. There
  15712. are several kinds of polymorphism in programming languages, such as
  15713. subtype polymorphism and parametric polymorphism
  15714. (aka. generics)~\citep{Cardelli:1985kx}. The kind of polymorphism we
  15715. study in this chapter does not have a special name but it is the kind
  15716. that arises in dynamically typed languages.
  15717. Another characteristic of dynamically typed languages is that
  15718. primitive operations, such as \code{not}, are often defined to operate
  15719. on many different types of values. In fact, in
  15720. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15721. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15722. given anything else it returns \FALSE{}.
  15723. Furthermore, even when primitive operations restrict their inputs to
  15724. values of a certain type, this restriction is enforced at runtime
  15725. instead of during compilation. For example, the tuple read
  15726. operation
  15727. \racket{\code{(vector-ref \#t 0)}}
  15728. \python{\code{True[0]}}
  15729. results in a run-time error because the first argument must
  15730. be a tuple, not a Boolean.
  15731. \section{The \LangDyn{} Language}
  15732. \newcommand{\LdynGrammarRacket}{
  15733. \begin{array}{rcl}
  15734. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  15735. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15736. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15737. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15738. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  15739. \end{array}
  15740. }
  15741. \newcommand{\LdynASTRacket}{
  15742. \begin{array}{lcl}
  15743. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  15744. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15745. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  15746. \end{array}
  15747. }
  15748. \begin{figure}[tp]
  15749. \centering
  15750. \begin{tcolorbox}[colback=white]
  15751. \small
  15752. {\if\edition\racketEd
  15753. \[
  15754. \begin{array}{l}
  15755. \gray{\LintGrammarRacket{}} \\ \hline
  15756. \gray{\LvarGrammarRacket{}} \\ \hline
  15757. \gray{\LifGrammarRacket{}} \\ \hline
  15758. \gray{\LwhileGrammarRacket} \\ \hline
  15759. \gray{\LtupGrammarRacket} \\ \hline
  15760. \LdynGrammarRacket \\
  15761. \begin{array}{rcl}
  15762. \LangDynM{} &::=& \Def\ldots\; \Exp
  15763. \end{array}
  15764. \end{array}
  15765. \]
  15766. \fi}
  15767. {\if\edition\pythonEd
  15768. \[
  15769. \begin{array}{rcl}
  15770. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15771. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15772. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15773. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15774. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15775. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15776. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15777. \MID \CLEN{\Exp} \\
  15778. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15779. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15780. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15781. \MID \Var\mathop{\key{=}}\Exp \\
  15782. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15783. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15784. &\MID& \CRETURN{\Exp} \\
  15785. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15786. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15787. \end{array}
  15788. \]
  15789. \fi}
  15790. \end{tcolorbox}
  15791. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15792. \label{fig:r7-concrete-syntax}
  15793. \end{figure}
  15794. \begin{figure}[tp]
  15795. \centering
  15796. \begin{tcolorbox}[colback=white]
  15797. \small
  15798. {\if\edition\racketEd
  15799. \[
  15800. \begin{array}{l}
  15801. \gray{\LintASTRacket{}} \\ \hline
  15802. \gray{\LvarASTRacket{}} \\ \hline
  15803. \gray{\LifASTRacket{}} \\ \hline
  15804. \gray{\LwhileASTRacket} \\ \hline
  15805. \gray{\LtupASTRacket} \\ \hline
  15806. \LdynASTRacket \\
  15807. \begin{array}{lcl}
  15808. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15809. \end{array}
  15810. \end{array}
  15811. \]
  15812. \fi}
  15813. {\if\edition\pythonEd
  15814. \[
  15815. \begin{array}{rcl}
  15816. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15817. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15818. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15819. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15820. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15821. &\MID & \code{Is()} \\
  15822. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15823. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15824. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15825. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  15826. \MID \VAR{\Var{}} \\
  15827. &\MID& \BOOL{\itm{bool}}
  15828. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15829. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15830. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15831. &\MID& \LEN{\Exp} \\
  15832. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15833. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15834. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15835. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15836. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15837. &\MID& \RETURN{\Exp} \\
  15838. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15839. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  15840. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15841. \end{array}
  15842. \]
  15843. \fi}
  15844. \end{tcolorbox}
  15845. \caption{The abstract syntax of \LangDyn{}.}
  15846. \label{fig:r7-syntax}
  15847. \end{figure}
  15848. The concrete and abstract syntax of \LangDyn{} is defined in
  15849. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15850. %
  15851. There is no type checker for \LangDyn{} because it only checks types
  15852. at runtime.
  15853. The definitional interpreter for \LangDyn{} is presented in
  15854. \racket{figure~\ref{fig:interp-Ldyn}}
  15855. \python{Figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}
  15856. and its auxiliary functions are defined in
  15857. figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15858. \INT{n}. Instead of simply returning the integer \code{n} (as
  15859. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  15860. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15861. value} that combines an underlying value with a tag that identifies
  15862. what kind of value it is. We define the following \racket{struct}\python{class}
  15863. to represented tagged values.
  15864. %
  15865. {\if\edition\racketEd
  15866. \begin{lstlisting}
  15867. (struct Tagged (value tag) #:transparent)
  15868. \end{lstlisting}
  15869. \fi}
  15870. {\if\edition\pythonEd
  15871. \begin{minipage}{\textwidth}
  15872. \begin{lstlisting}
  15873. @dataclass(eq=True)
  15874. class Tagged(Value):
  15875. value : Value
  15876. tag : str
  15877. def __str__(self):
  15878. return str(self.value)
  15879. \end{lstlisting}
  15880. \end{minipage}
  15881. \fi}
  15882. %
  15883. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  15884. \code{Vector}, and \code{Procedure}.}
  15885. %
  15886. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15887. \code{'tuple'}, and \code{'function'}.}
  15888. %
  15889. Tags are closely related to types but don't always capture all the
  15890. information that a type does.
  15891. %
  15892. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15893. tagged with \code{Vector} and a procedure of type \code{(Any Any ->
  15894. Any)} is tagged with \code{Procedure}.}
  15895. %
  15896. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15897. is tagged with \code{'tuple'} and a function of type
  15898. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15899. is tagged with \code{'function'}.}
  15900. Next consider the match case for accessing the element of a tuple.
  15901. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15902. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15903. argument is a tuple and the second is an integer.
  15904. \racket{
  15905. If they are not, a \code{trapped-error} is raised. Recall from
  15906. section~\ref{sec:interp_Lint} that when a definition interpreter
  15907. raises a \code{trapped-error} error, the compiled code must also
  15908. signal an error by exiting with return code \code{255}. A
  15909. \code{trapped-error} is also raised if the index is not less than the
  15910. length of the vector.
  15911. }
  15912. %
  15913. \python{If they are not, an exception is raised. The compiled code
  15914. must also signal an error by exiting with return code \code{255}. A
  15915. exception is also raised if the index is not less than the length of the
  15916. tuple or if it is negative.}
  15917. \begin{figure}[tbp]
  15918. \begin{tcolorbox}[colback=white]
  15919. {\if\edition\racketEd
  15920. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15921. (define ((interp-Ldyn-exp env) ast)
  15922. (define recur (interp-Ldyn-exp env))
  15923. (match ast
  15924. [(Var x) (dict-ref env x)]
  15925. [(Int n) (Tagged n 'Integer)]
  15926. [(Bool b) (Tagged b 'Boolean)]
  15927. [(Lambda xs rt body)
  15928. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15929. [(Prim 'vector es)
  15930. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15931. [(Prim 'vector-ref (list e1 e2))
  15932. (define vec (recur e1)) (define i (recur e2))
  15933. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15934. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15935. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15936. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15937. [(Prim 'vector-set! (list e1 e2 e3))
  15938. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15939. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15940. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15941. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15942. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15943. (Tagged (void) 'Void)]
  15944. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  15945. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15946. [(Prim 'or (list e1 e2))
  15947. (define v1 (recur e1))
  15948. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15949. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15950. [(Prim op (list e1))
  15951. #:when (set-member? type-predicates op)
  15952. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15953. [(Prim op es)
  15954. (define args (map recur es))
  15955. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15956. (unless (for/or ([expected-tags (op-tags op)])
  15957. (equal? expected-tags tags))
  15958. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15959. (tag-value
  15960. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15961. [(If q t f)
  15962. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15963. [(Apply f es)
  15964. (define new-f (recur f)) (define args (map recur es))
  15965. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15966. (match f-val
  15967. [`(function ,xs ,body ,lam-env)
  15968. (unless (eq? (length xs) (length args))
  15969. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15970. (define new-env (append (map cons xs args) lam-env))
  15971. ((interp-Ldyn-exp new-env) body)]
  15972. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  15973. \end{lstlisting}
  15974. \fi}
  15975. {\if\edition\pythonEd
  15976. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15977. class InterpLdyn(InterpLlambda):
  15978. def interp_exp(self, e, env):
  15979. match e:
  15980. case Constant(n):
  15981. return self.tag(super().interp_exp(e, env))
  15982. case Tuple(es, Load()):
  15983. return self.tag(super().interp_exp(e, env))
  15984. case Lambda(params, body):
  15985. return self.tag(super().interp_exp(e, env))
  15986. case Call(Name('input_int'), []):
  15987. return self.tag(super().interp_exp(e, env))
  15988. case BinOp(left, Add(), right):
  15989. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15990. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  15991. case BinOp(left, Sub(), right):
  15992. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15993. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  15994. case UnaryOp(USub(), e1):
  15995. v = self.interp_exp(e1, env)
  15996. return self.tag(- self.untag(v, 'int', e))
  15997. case IfExp(test, body, orelse):
  15998. v = self.interp_exp(test, env)
  15999. if self.untag(v, 'bool', e):
  16000. return self.interp_exp(body, env)
  16001. else:
  16002. return self.interp_exp(orelse, env)
  16003. case UnaryOp(Not(), e1):
  16004. v = self.interp_exp(e1, env)
  16005. return self.tag(not self.untag(v, 'bool', e))
  16006. case BoolOp(And(), values):
  16007. left = values[0]; right = values[1]
  16008. l = self.interp_exp(left, env)
  16009. if self.untag(l, 'bool', e):
  16010. return self.interp_exp(right, env)
  16011. else:
  16012. return self.tag(False)
  16013. case BoolOp(Or(), values):
  16014. left = values[0]; right = values[1]
  16015. l = self.interp_exp(left, env)
  16016. if self.untag(l, 'bool', e):
  16017. return self.tag(True)
  16018. else:
  16019. return self.interp_exp(right, env)
  16020. case Compare(left, [cmp], [right]):
  16021. l = self.interp_exp(left, env)
  16022. r = self.interp_exp(right, env)
  16023. if l.tag == r.tag:
  16024. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16025. else:
  16026. raise Exception('interp Compare unexpected '
  16027. + repr(l) + ' ' + repr(r))
  16028. case Subscript(tup, index, Load()):
  16029. t = self.interp_exp(tup, env)
  16030. n = self.interp_exp(index, env)
  16031. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16032. case Call(Name('len'), [tup]):
  16033. t = self.interp_exp(tup, env)
  16034. return self.tag(len(self.untag(t, 'tuple', e)))
  16035. case _:
  16036. return self.tag(super().interp_exp(e, env))
  16037. \end{lstlisting}
  16038. \fi}
  16039. \end{tcolorbox}
  16040. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16041. \label{fig:interp-Ldyn}
  16042. \end{figure}
  16043. {\if\edition\pythonEd
  16044. \begin{figure}[tbp]
  16045. \begin{tcolorbox}[colback=white]
  16046. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16047. class InterpLdyn(InterpLlambda):
  16048. def interp_stmts(self, ss, env):
  16049. if len(ss) == 0:
  16050. return
  16051. match ss[0]:
  16052. case If(test, body, orelse):
  16053. v = self.interp_exp(test, env)
  16054. if self.untag(v, 'bool', ss[0]):
  16055. return self.interp_stmts(body + ss[1:], env)
  16056. else:
  16057. return self.interp_stmts(orelse + ss[1:], env)
  16058. case While(test, body, []):
  16059. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16060. self.interp_stmts(body, env)
  16061. return self.interp_stmts(ss[1:], env)
  16062. case Assign([Subscript(tup, index)], value):
  16063. tup = self.interp_exp(tup, env)
  16064. index = self.interp_exp(index, env)
  16065. tup_v = self.untag(tup, 'tuple', ss[0])
  16066. index_v = self.untag(index, 'int', ss[0])
  16067. tup_v[index_v] = self.interp_exp(value, env)
  16068. return self.interp_stmts(ss[1:], env)
  16069. case FunctionDef(name, params, bod, dl, returns, comment):
  16070. ps = [x for (x,t) in params]
  16071. env[name] = self.tag(Function(name, ps, bod, env))
  16072. return self.interp_stmts(ss[1:], env)
  16073. case _:
  16074. return super().interp_stmts(ss, env)
  16075. \end{lstlisting}
  16076. \end{tcolorbox}
  16077. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16078. \label{fig:interp-Ldyn-2}
  16079. \end{figure}
  16080. \fi}
  16081. \begin{figure}[tbp]
  16082. \begin{tcolorbox}[colback=white]
  16083. {\if\edition\racketEd
  16084. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16085. (define (interp-op op)
  16086. (match op
  16087. ['+ fx+]
  16088. ['- fx-]
  16089. ['read read-fixnum]
  16090. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16091. ['< (lambda (v1 v2)
  16092. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16093. ['<= (lambda (v1 v2)
  16094. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16095. ['> (lambda (v1 v2)
  16096. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16097. ['>= (lambda (v1 v2)
  16098. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16099. ['boolean? boolean?]
  16100. ['integer? fixnum?]
  16101. ['void? void?]
  16102. ['vector? vector?]
  16103. ['vector-length vector-length]
  16104. ['procedure? (match-lambda
  16105. [`(functions ,xs ,body ,env) #t] [else #f])]
  16106. [else (error 'interp-op "unknown operator" op)]))
  16107. (define (op-tags op)
  16108. (match op
  16109. ['+ '((Integer Integer))]
  16110. ['- '((Integer Integer) (Integer))]
  16111. ['read '(())]
  16112. ['not '((Boolean))]
  16113. ['< '((Integer Integer))]
  16114. ['<= '((Integer Integer))]
  16115. ['> '((Integer Integer))]
  16116. ['>= '((Integer Integer))]
  16117. ['vector-length '((Vector))]))
  16118. (define type-predicates
  16119. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16120. (define (tag-value v)
  16121. (cond [(boolean? v) (Tagged v 'Boolean)]
  16122. [(fixnum? v) (Tagged v 'Integer)]
  16123. [(procedure? v) (Tagged v 'Procedure)]
  16124. [(vector? v) (Tagged v 'Vector)]
  16125. [(void? v) (Tagged v 'Void)]
  16126. [else (error 'tag-value "unidentified value ~a" v)]))
  16127. (define (check-tag val expected ast)
  16128. (define tag (Tagged-tag val))
  16129. (unless (eq? tag expected)
  16130. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  16131. \end{lstlisting}
  16132. \fi}
  16133. {\if\edition\pythonEd
  16134. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16135. class InterpLdyn(InterpLlambda):
  16136. def tag(self, v):
  16137. if v is True or v is False:
  16138. return Tagged(v, 'bool')
  16139. elif isinstance(v, int):
  16140. return Tagged(v, 'int')
  16141. elif isinstance(v, Function):
  16142. return Tagged(v, 'function')
  16143. elif isinstance(v, tuple):
  16144. return Tagged(v, 'tuple')
  16145. elif isinstance(v, type(None)):
  16146. return Tagged(v, 'none')
  16147. else:
  16148. raise Exception('tag: unexpected ' + repr(v))
  16149. def untag(self, v, expected_tag, ast):
  16150. match v:
  16151. case Tagged(val, tag) if tag == expected_tag:
  16152. return val
  16153. case _:
  16154. raise Exception('expected Tagged value with '
  16155. + expected_tag + ', not ' + ' ' + repr(v))
  16156. def apply_fun(self, fun, args, e):
  16157. f = self.untag(fun, 'function', e)
  16158. return super().apply_fun(f, args, e)
  16159. \end{lstlisting}
  16160. \fi}
  16161. \end{tcolorbox}
  16162. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  16163. \label{fig:interp-Ldyn-aux}
  16164. \end{figure}
  16165. \clearpage
  16166. \section{Representation of Tagged Values}
  16167. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  16168. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  16169. values at the bit level. Because almost every operation in \LangDyn{}
  16170. involves manipulating tagged values, the representation must be
  16171. efficient. Recall that all of our values are 64 bits. We shall steal
  16172. the 3 right-most bits to encode the tag. We use $001$ to identify
  16173. integers, $100$ for Booleans, $010$ for tuples, $011$ for procedures,
  16174. and $101$ for the void value\python{, \key{None}}. We define the following auxiliary
  16175. function for mapping types to tag codes.
  16176. {\if\edition\racketEd
  16177. \begin{align*}
  16178. \itm{tagof}(\key{Integer}) &= 001 \\
  16179. \itm{tagof}(\key{Boolean}) &= 100 \\
  16180. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  16181. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  16182. \itm{tagof}(\key{Void}) &= 101
  16183. \end{align*}
  16184. \fi}
  16185. {\if\edition\pythonEd
  16186. \begin{align*}
  16187. \itm{tagof}(\key{IntType()}) &= 001 \\
  16188. \itm{tagof}(\key{BoolType()}) &= 100 \\
  16189. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  16190. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  16191. \itm{tagof}(\key{type(None)}) &= 101
  16192. \end{align*}
  16193. \fi}
  16194. This stealing of 3 bits comes at some price: integers are now restricted
  16195. to the range from $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  16196. affect tuples and procedures because those values are addresses, and
  16197. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  16198. they are always $000$. Thus, we do not lose information by overwriting
  16199. the rightmost 3 bits with the tag and we can simply zero-out the tag
  16200. to recover the original address.
  16201. To make tagged values into first-class entities, we can give them a
  16202. type, called \racket{\code{Any}}\python{\code{AnyType()}}, and define
  16203. operations such as \code{Inject} and \code{Project} for creating and
  16204. using them, yielding the statically typed \LangAny{} intermediate
  16205. language. We describe how to compile \LangDyn{} to \LangAny{} in
  16206. section~\ref{sec:compile-r7} but first we describe the \LangAny{}
  16207. language in greater detail.
  16208. \section{The \LangAny{} Language}
  16209. \label{sec:Rany-lang}
  16210. \newcommand{\LanyASTRacket}{
  16211. \begin{array}{lcl}
  16212. \Type &::= & \ANYTY \\
  16213. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  16214. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  16215. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  16216. \itm{op} &::= & \code{any-vector-length}
  16217. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  16218. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  16219. \MID \code{procedure?} \MID \code{void?} \\
  16220. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  16221. \end{array}
  16222. }
  16223. \newcommand{\LanyASTPython}{
  16224. \begin{array}{lcl}
  16225. \Type &::= & \key{AnyType()} \\
  16226. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  16227. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  16228. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  16229. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  16230. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  16231. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  16232. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  16233. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  16234. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  16235. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  16236. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  16237. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  16238. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  16239. \end{array}
  16240. }
  16241. \begin{figure}[tp]
  16242. \centering
  16243. \begin{tcolorbox}[colback=white]
  16244. \small
  16245. {\if\edition\racketEd
  16246. \[
  16247. \begin{array}{l}
  16248. \gray{\LintOpAST} \\ \hline
  16249. \gray{\LvarASTRacket{}} \\ \hline
  16250. \gray{\LifASTRacket{}} \\ \hline
  16251. \gray{\LwhileASTRacket{}} \\ \hline
  16252. \gray{\LtupASTRacket{}} \\ \hline
  16253. \gray{\LfunASTRacket} \\ \hline
  16254. \gray{\LlambdaASTRacket} \\ \hline
  16255. \LanyASTRacket \\
  16256. \begin{array}{lcl}
  16257. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16258. \end{array}
  16259. \end{array}
  16260. \]
  16261. \fi}
  16262. {\if\edition\pythonEd
  16263. \[
  16264. \begin{array}{l}
  16265. \gray{\LintASTPython} \\ \hline
  16266. \gray{\LvarASTPython{}} \\ \hline
  16267. \gray{\LifASTPython{}} \\ \hline
  16268. \gray{\LwhileASTPython{}} \\ \hline
  16269. \gray{\LtupASTPython{}} \\ \hline
  16270. \gray{\LfunASTPython} \\ \hline
  16271. \gray{\LlambdaASTPython} \\ \hline
  16272. \LanyASTPython \\
  16273. \begin{array}{lcl}
  16274. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16275. \end{array}
  16276. \end{array}
  16277. \]
  16278. \fi}
  16279. \end{tcolorbox}
  16280. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  16281. \label{fig:Lany-syntax}
  16282. \end{figure}
  16283. The abstract syntax of \LangAny{} is defined in figure~\ref{fig:Lany-syntax}.
  16284. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  16285. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  16286. The $\INJECT{e}{T}$ form
  16287. converts the value produced by expression $e$ of type $T$ into a
  16288. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  16289. produced by expression $e$ into a value of type $T$ or halts the
  16290. program if the type tag does not match $T$.
  16291. %
  16292. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  16293. restricted to a flat type $\FType$, which simplifies the
  16294. implementation and corresponds with the needs for compiling \LangDyn{}.
  16295. The \racket{\code{any-vector}} operators
  16296. \python{\code{any\_tuple\_load} and \code{any\_len}}
  16297. adapt the tuple operations so that they can be applied to a value of
  16298. type \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  16299. tuple operations in that the index is not restricted to be a literal
  16300. integer in the grammar but is allowed to be any expression.
  16301. \racket{The type predicates such as
  16302. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  16303. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  16304. the predicate and they return {\FALSE} otherwise.}
  16305. The type checker for \LangAny{} is shown in
  16306. figure~\ref{fig:type-check-Lany}
  16307. %
  16308. \racket{ and uses the auxiliary functions in
  16309. figure~\ref{fig:type-check-Lany-aux}}.
  16310. %
  16311. The interpreter for \LangAny{} is in figure~\ref{fig:interp-Lany} and
  16312. its auxiliary functions are in figure~\ref{fig:interp-Lany-aux}.
  16313. \begin{figure}[btp]
  16314. \begin{tcolorbox}[colback=white]
  16315. {\if\edition\racketEd
  16316. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16317. (define type-check-Lany-class
  16318. (class type-check-Llambda-class
  16319. (super-new)
  16320. (inherit check-type-equal?)
  16321. (define/override (type-check-exp env)
  16322. (lambda (e)
  16323. (define recur (type-check-exp env))
  16324. (match e
  16325. [(Inject e1 ty)
  16326. (unless (flat-ty? ty)
  16327. (error 'type-check "may only inject from flat type, not ~a" ty))
  16328. (define-values (new-e1 e-ty) (recur e1))
  16329. (check-type-equal? e-ty ty e)
  16330. (values (Inject new-e1 ty) 'Any)]
  16331. [(Project e1 ty)
  16332. (unless (flat-ty? ty)
  16333. (error 'type-check "may only project to flat type, not ~a" ty))
  16334. (define-values (new-e1 e-ty) (recur e1))
  16335. (check-type-equal? e-ty 'Any e)
  16336. (values (Project new-e1 ty) ty)]
  16337. [(Prim 'any-vector-length (list e1))
  16338. (define-values (e1^ t1) (recur e1))
  16339. (check-type-equal? t1 'Any e)
  16340. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  16341. [(Prim 'any-vector-ref (list e1 e2))
  16342. (define-values (e1^ t1) (recur e1))
  16343. (define-values (e2^ t2) (recur e2))
  16344. (check-type-equal? t1 'Any e)
  16345. (check-type-equal? t2 'Integer e)
  16346. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  16347. [(Prim 'any-vector-set! (list e1 e2 e3))
  16348. (define-values (e1^ t1) (recur e1))
  16349. (define-values (e2^ t2) (recur e2))
  16350. (define-values (e3^ t3) (recur e3))
  16351. (check-type-equal? t1 'Any e)
  16352. (check-type-equal? t2 'Integer e)
  16353. (check-type-equal? t3 'Any e)
  16354. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  16355. [(Prim pred (list e1))
  16356. #:when (set-member? (type-predicates) pred)
  16357. (define-values (new-e1 e-ty) (recur e1))
  16358. (check-type-equal? e-ty 'Any e)
  16359. (values (Prim pred (list new-e1)) 'Boolean)]
  16360. [(Prim 'eq? (list arg1 arg2))
  16361. (define-values (e1 t1) (recur arg1))
  16362. (define-values (e2 t2) (recur arg2))
  16363. (match* (t1 t2)
  16364. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  16365. [(other wise) (check-type-equal? t1 t2 e)])
  16366. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  16367. [else ((super type-check-exp env) e)])))
  16368. ))
  16369. \end{lstlisting}
  16370. \fi}
  16371. {\if\edition\pythonEd
  16372. \begin{lstlisting}
  16373. class TypeCheckLany(TypeCheckLlambda):
  16374. def type_check_exp(self, e, env):
  16375. match e:
  16376. case Inject(value, typ):
  16377. self.check_exp(value, typ, env)
  16378. return AnyType()
  16379. case Project(value, typ):
  16380. self.check_exp(value, AnyType(), env)
  16381. return typ
  16382. case Call(Name('any_tuple_load'), [tup, index]):
  16383. self.check_exp(tup, AnyType(), env)
  16384. self.check_exp(index, IntType(), env)
  16385. return AnyType()
  16386. case Call(Name('any_len'), [tup]):
  16387. self.check_exp(tup, AnyType(), env)
  16388. return IntType()
  16389. case Call(Name('arity'), [fun]):
  16390. ty = self.type_check_exp(fun, env)
  16391. match ty:
  16392. case FunctionType(ps, rt):
  16393. return IntType()
  16394. case TupleType([FunctionType(ps,rs)]):
  16395. return IntType()
  16396. case _:
  16397. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  16398. case Call(Name('make_any'), [value, tag]):
  16399. self.type_check_exp(value, env)
  16400. self.check_exp(tag, IntType(), env)
  16401. return AnyType()
  16402. case AnnLambda(params, returns, body):
  16403. new_env = {x:t for (x,t) in env.items()}
  16404. for (x,t) in params:
  16405. new_env[x] = t
  16406. return_t = self.type_check_exp(body, new_env)
  16407. self.check_type_equal(returns, return_t, e)
  16408. return FunctionType([t for (x,t) in params], return_t)
  16409. case _:
  16410. return super().type_check_exp(e, env)
  16411. \end{lstlisting}
  16412. \fi}
  16413. \end{tcolorbox}
  16414. \caption{Type checker for the \LangAny{} language.}
  16415. \label{fig:type-check-Lany}
  16416. \end{figure}
  16417. {\if\edition\racketEd
  16418. \begin{figure}[tbp]
  16419. \begin{tcolorbox}[colback=white]
  16420. \begin{lstlisting}
  16421. (define/override (operator-types)
  16422. (append
  16423. '((integer? . ((Any) . Boolean))
  16424. (vector? . ((Any) . Boolean))
  16425. (procedure? . ((Any) . Boolean))
  16426. (void? . ((Any) . Boolean)))
  16427. (super operator-types)))
  16428. (define/public (type-predicates)
  16429. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16430. (define/public (flat-ty? ty)
  16431. (match ty
  16432. [(or `Integer `Boolean `Void) #t]
  16433. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  16434. ['(Vectorof Any) #t]
  16435. [`(,ts ... -> ,rt)
  16436. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  16437. [else #f]))
  16438. \end{lstlisting}
  16439. \end{tcolorbox}
  16440. \caption{Auxiliary methods for type checking \LangAny{}.}
  16441. \label{fig:type-check-Lany-aux}
  16442. \end{figure}
  16443. \fi}
  16444. \begin{figure}[btp]
  16445. \begin{tcolorbox}[colback=white]
  16446. {\if\edition\racketEd
  16447. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16448. (define interp-Lany-class
  16449. (class interp-Llambda-class
  16450. (super-new)
  16451. (define/override (interp-op op)
  16452. (match op
  16453. ['boolean? (match-lambda
  16454. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  16455. [else #f])]
  16456. ['integer? (match-lambda
  16457. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  16458. [else #f])]
  16459. ['vector? (match-lambda
  16460. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  16461. [else #f])]
  16462. ['procedure? (match-lambda
  16463. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  16464. [else #f])]
  16465. ['eq? (match-lambda*
  16466. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  16467. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  16468. [ls (apply (super interp-op op) ls)])]
  16469. ['any-vector-ref (lambda (v i)
  16470. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  16471. ['any-vector-set! (lambda (v i a)
  16472. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  16473. ['any-vector-length (lambda (v)
  16474. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  16475. [else (super interp-op op)]))
  16476. (define/override ((interp-exp env) e)
  16477. (define recur (interp-exp env))
  16478. (match e
  16479. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  16480. [(Project e ty2) (apply-project (recur e) ty2)]
  16481. [else ((super interp-exp env) e)]))
  16482. ))
  16483. (define (interp-Lany p)
  16484. (send (new interp-Lany-class) interp-program p))
  16485. \end{lstlisting}
  16486. \fi}
  16487. {\if\edition\pythonEd
  16488. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16489. class InterpLany(InterpLlambda):
  16490. def interp_exp(self, e, env):
  16491. match e:
  16492. case Inject(value, typ):
  16493. v = self.interp_exp(value, env)
  16494. return Tagged(v, self.type_to_tag(typ))
  16495. case Project(value, typ):
  16496. v = self.interp_exp(value, env)
  16497. match v:
  16498. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  16499. return val
  16500. case _:
  16501. raise Exception('interp project to ' + repr(typ)
  16502. + ' unexpected ' + repr(v))
  16503. case Call(Name('any_tuple_load'), [tup, index]):
  16504. tv = self.interp_exp(tup, env)
  16505. n = self.interp_exp(index, env)
  16506. match tv:
  16507. case Tagged(v, tag):
  16508. return v[n]
  16509. case _:
  16510. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  16511. case Call(Name('any_len'), [value]):
  16512. v = self.interp_exp(value, env)
  16513. match v:
  16514. case Tagged(value, tag):
  16515. return len(value)
  16516. case _:
  16517. raise Exception('interp any_len unexpected ' + repr(v))
  16518. case Call(Name('arity'), [fun]):
  16519. f = self.interp_exp(fun, env)
  16520. return self.arity(f)
  16521. case _:
  16522. return super().interp_exp(e, env)
  16523. \end{lstlisting}
  16524. \fi}
  16525. \end{tcolorbox}
  16526. \caption{Interpreter for \LangAny{}.}
  16527. \label{fig:interp-Lany}
  16528. \end{figure}
  16529. \begin{figure}[tbp]
  16530. \begin{tcolorbox}[colback=white]
  16531. {\if\edition\racketEd
  16532. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16533. (define/public (apply-inject v tg) (Tagged v tg))
  16534. (define/public (apply-project v ty2)
  16535. (define tag2 (any-tag ty2))
  16536. (match v
  16537. [(Tagged v1 tag1)
  16538. (cond
  16539. [(eq? tag1 tag2)
  16540. (match ty2
  16541. [`(Vector ,ts ...)
  16542. (define l1 ((interp-op 'vector-length) v1))
  16543. (cond
  16544. [(eq? l1 (length ts)) v1]
  16545. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  16546. l1 (length ts))])]
  16547. [`(,ts ... -> ,rt)
  16548. (match v1
  16549. [`(function ,xs ,body ,env)
  16550. (cond [(eq? (length xs) (length ts)) v1]
  16551. [else
  16552. (error 'apply-project "arity mismatch ~a != ~a"
  16553. (length xs) (length ts))])]
  16554. [else (error 'apply-project "expected function not ~a" v1)])]
  16555. [else v1])]
  16556. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16557. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16558. \end{lstlisting}
  16559. \fi}
  16560. {\if\edition\pythonEd
  16561. \begin{lstlisting}
  16562. class InterpLany(InterpLlambda):
  16563. def type_to_tag(self, typ):
  16564. match typ:
  16565. case FunctionType(params, rt):
  16566. return 'function'
  16567. case TupleType(fields):
  16568. return 'tuple'
  16569. case t if t == int:
  16570. return 'int'
  16571. case t if t == bool:
  16572. return 'bool'
  16573. case IntType():
  16574. return 'int'
  16575. case BoolType():
  16576. return 'int'
  16577. case _:
  16578. raise Exception('type_to_tag unexpected ' + repr(typ))
  16579. def arity(self, v):
  16580. match v:
  16581. case Function(name, params, body, env):
  16582. return len(params)
  16583. case ClosureTuple(args, arity):
  16584. return arity
  16585. case _:
  16586. raise Exception('Lany arity unexpected ' + repr(v))
  16587. \end{lstlisting}
  16588. \fi}
  16589. \end{tcolorbox}
  16590. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16591. \label{fig:interp-Lany-aux}
  16592. \end{figure}
  16593. \clearpage
  16594. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16595. \label{sec:compile-r7}
  16596. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16597. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  16598. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  16599. is that given any subexpression $e$ in the \LangDyn{} program, the
  16600. pass will produce an expression $e'$ in \LangAny{} that has type
  16601. \ANYTY{}. For example, the first row in
  16602. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  16603. \TRUE{}, which must be injected to produce an expression of type
  16604. \ANYTY{}.
  16605. %
  16606. The second row of figure~\ref{fig:compile-r7-Lany}, the compilation of
  16607. addition, is representative of compilation for many primitive
  16608. operations: the arguments have type \ANYTY{} and must be projected to
  16609. \INTTYPE{} before the addition can be performed.
  16610. The compilation of \key{lambda} (third row of
  16611. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  16612. produce type annotations: we simply use \ANYTY{}.
  16613. %
  16614. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16615. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16616. this pass has to account for some differences in behavior between
  16617. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16618. permissive than \LangAny{} regarding what kind of values can be used
  16619. in various places. For example, the condition of an \key{if} does
  16620. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16621. of the same type (in that case the result is \code{\#f}).}
  16622. \begin{figure}[btp]
  16623. \centering
  16624. \begin{tcolorbox}[colback=white]
  16625. {\if\edition\racketEd
  16626. \begin{tabular}{lll}
  16627. \begin{minipage}{0.27\textwidth}
  16628. \begin{lstlisting}
  16629. #t
  16630. \end{lstlisting}
  16631. \end{minipage}
  16632. &
  16633. $\Rightarrow$
  16634. &
  16635. \begin{minipage}{0.65\textwidth}
  16636. \begin{lstlisting}
  16637. (inject #t Boolean)
  16638. \end{lstlisting}
  16639. \end{minipage}
  16640. \\[2ex]\hline
  16641. \begin{minipage}{0.27\textwidth}
  16642. \begin{lstlisting}
  16643. (+ |$e_1$| |$e_2$|)
  16644. \end{lstlisting}
  16645. \end{minipage}
  16646. &
  16647. $\Rightarrow$
  16648. &
  16649. \begin{minipage}{0.65\textwidth}
  16650. \begin{lstlisting}
  16651. (inject
  16652. (+ (project |$e'_1$| Integer)
  16653. (project |$e'_2$| Integer))
  16654. Integer)
  16655. \end{lstlisting}
  16656. \end{minipage}
  16657. \\[2ex]\hline
  16658. \begin{minipage}{0.27\textwidth}
  16659. \begin{lstlisting}
  16660. (lambda (|$x_1 \ldots$|) |$e$|)
  16661. \end{lstlisting}
  16662. \end{minipage}
  16663. &
  16664. $\Rightarrow$
  16665. &
  16666. \begin{minipage}{0.65\textwidth}
  16667. \begin{lstlisting}
  16668. (inject
  16669. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  16670. (Any|$\ldots$|Any -> Any))
  16671. \end{lstlisting}
  16672. \end{minipage}
  16673. \\[2ex]\hline
  16674. \begin{minipage}{0.27\textwidth}
  16675. \begin{lstlisting}
  16676. (|$e_0$| |$e_1 \ldots e_n$|)
  16677. \end{lstlisting}
  16678. \end{minipage}
  16679. &
  16680. $\Rightarrow$
  16681. &
  16682. \begin{minipage}{0.65\textwidth}
  16683. \begin{lstlisting}
  16684. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16685. \end{lstlisting}
  16686. \end{minipage}
  16687. \\[2ex]\hline
  16688. \begin{minipage}{0.27\textwidth}
  16689. \begin{lstlisting}
  16690. (vector-ref |$e_1$| |$e_2$|)
  16691. \end{lstlisting}
  16692. \end{minipage}
  16693. &
  16694. $\Rightarrow$
  16695. &
  16696. \begin{minipage}{0.65\textwidth}
  16697. \begin{lstlisting}
  16698. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  16699. \end{lstlisting}
  16700. \end{minipage}
  16701. \\[2ex]\hline
  16702. \begin{minipage}{0.27\textwidth}
  16703. \begin{lstlisting}
  16704. (if |$e_1$| |$e_2$| |$e_3$|)
  16705. \end{lstlisting}
  16706. \end{minipage}
  16707. &
  16708. $\Rightarrow$
  16709. &
  16710. \begin{minipage}{0.65\textwidth}
  16711. \begin{lstlisting}
  16712. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16713. \end{lstlisting}
  16714. \end{minipage}
  16715. \\[2ex]\hline
  16716. \begin{minipage}{0.27\textwidth}
  16717. \begin{lstlisting}
  16718. (eq? |$e_1$| |$e_2$|)
  16719. \end{lstlisting}
  16720. \end{minipage}
  16721. &
  16722. $\Rightarrow$
  16723. &
  16724. \begin{minipage}{0.65\textwidth}
  16725. \begin{lstlisting}
  16726. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16727. \end{lstlisting}
  16728. \end{minipage}
  16729. \\[2ex]\hline
  16730. \begin{minipage}{0.27\textwidth}
  16731. \begin{lstlisting}
  16732. (not |$e_1$|)
  16733. \end{lstlisting}
  16734. \end{minipage}
  16735. &
  16736. $\Rightarrow$
  16737. &
  16738. \begin{minipage}{0.65\textwidth}
  16739. \begin{lstlisting}
  16740. (if (eq? |$e'_1$| (inject #f Boolean))
  16741. (inject #t Boolean) (inject #f Boolean))
  16742. \end{lstlisting}
  16743. \end{minipage}
  16744. \end{tabular}
  16745. \fi}
  16746. {\if\edition\pythonEd
  16747. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  16748. \begin{minipage}{0.23\textwidth}
  16749. \begin{lstlisting}
  16750. True
  16751. \end{lstlisting}
  16752. \end{minipage}
  16753. &
  16754. $\Rightarrow$
  16755. &
  16756. \begin{minipage}{0.7\textwidth}
  16757. \begin{lstlisting}
  16758. Inject(True, BoolType())
  16759. \end{lstlisting}
  16760. \end{minipage}
  16761. \\[2ex]\hline
  16762. \begin{minipage}{0.23\textwidth}
  16763. \begin{lstlisting}
  16764. |$e_1$| + |$e_2$|
  16765. \end{lstlisting}
  16766. \end{minipage}
  16767. &
  16768. $\Rightarrow$
  16769. &
  16770. \begin{minipage}{0.7\textwidth}
  16771. \begin{lstlisting}
  16772. Inject(Project(|$e'_1$|, IntType())
  16773. + Project(|$e'_2$|, IntType()),
  16774. IntType())
  16775. \end{lstlisting}
  16776. \end{minipage}
  16777. \\[2ex]\hline
  16778. \begin{minipage}{0.23\textwidth}
  16779. \begin{lstlisting}
  16780. lambda |$x_1 \ldots$|: |$e$|
  16781. \end{lstlisting}
  16782. \end{minipage}
  16783. &
  16784. $\Rightarrow$
  16785. &
  16786. \begin{minipage}{0.7\textwidth}
  16787. \begin{lstlisting}
  16788. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  16789. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16790. \end{lstlisting}
  16791. \end{minipage}
  16792. \\[2ex]\hline
  16793. \begin{minipage}{0.23\textwidth}
  16794. \begin{lstlisting}
  16795. |$e_0$|(|$e_1 \ldots e_n$|)
  16796. \end{lstlisting}
  16797. \end{minipage}
  16798. &
  16799. $\Rightarrow$
  16800. &
  16801. \begin{minipage}{0.7\textwidth}
  16802. \begin{lstlisting}
  16803. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16804. AnyType())), |$e'_1, \ldots, e'_n$|)
  16805. \end{lstlisting}
  16806. \end{minipage}
  16807. \\[2ex]\hline
  16808. \begin{minipage}{0.23\textwidth}
  16809. \begin{lstlisting}
  16810. |$e_1$|[|$e_2$|]
  16811. \end{lstlisting}
  16812. \end{minipage}
  16813. &
  16814. $\Rightarrow$
  16815. &
  16816. \begin{minipage}{0.7\textwidth}
  16817. \begin{lstlisting}
  16818. Call(Name('any_tuple_load'),
  16819. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  16820. \end{lstlisting}
  16821. \end{minipage}
  16822. %% \begin{minipage}{0.23\textwidth}
  16823. %% \begin{lstlisting}
  16824. %% |$e_2$| if |$e_1$| else |$e_3$|
  16825. %% \end{lstlisting}
  16826. %% \end{minipage}
  16827. %% &
  16828. %% $\Rightarrow$
  16829. %% &
  16830. %% \begin{minipage}{0.7\textwidth}
  16831. %% \begin{lstlisting}
  16832. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16833. %% \end{lstlisting}
  16834. %% \end{minipage}
  16835. %% \\[2ex]\hline
  16836. %% \begin{minipage}{0.23\textwidth}
  16837. %% \begin{lstlisting}
  16838. %% (eq? |$e_1$| |$e_2$|)
  16839. %% \end{lstlisting}
  16840. %% \end{minipage}
  16841. %% &
  16842. %% $\Rightarrow$
  16843. %% &
  16844. %% \begin{minipage}{0.7\textwidth}
  16845. %% \begin{lstlisting}
  16846. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16847. %% \end{lstlisting}
  16848. %% \end{minipage}
  16849. %% \\[2ex]\hline
  16850. %% \begin{minipage}{0.23\textwidth}
  16851. %% \begin{lstlisting}
  16852. %% (not |$e_1$|)
  16853. %% \end{lstlisting}
  16854. %% \end{minipage}
  16855. %% &
  16856. %% $\Rightarrow$
  16857. %% &
  16858. %% \begin{minipage}{0.7\textwidth}
  16859. %% \begin{lstlisting}
  16860. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16861. %% (inject #t Boolean) (inject #f Boolean))
  16862. %% \end{lstlisting}
  16863. %% \end{minipage}
  16864. %% \\[2ex]\hline
  16865. \\\hline
  16866. \end{tabular}
  16867. \fi}
  16868. \end{tcolorbox}
  16869. \caption{Cast Insertion}
  16870. \label{fig:compile-r7-Lany}
  16871. \end{figure}
  16872. \section{Reveal Casts}
  16873. \label{sec:reveal-casts-Lany}
  16874. % TODO: define R'_6
  16875. In the \code{reveal\_casts} pass we recommend compiling \code{Project}
  16876. into a conditional expression that checks whether the value's tag
  16877. matches the target type; if it does, the value is converted to a value
  16878. of the target type by removing the tag; if it does not, the program
  16879. exits.
  16880. %
  16881. {\if\edition\racketEd
  16882. %
  16883. To perform these actions we need a new primitive operation,
  16884. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16885. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16886. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16887. underlying value from a tagged value. The \code{ValueOf} form
  16888. includes the type for the underlying value which is used by the type
  16889. checker. Finally, the \code{Exit} form ends the execution of the
  16890. program.
  16891. %
  16892. \fi}
  16893. %
  16894. {\if\edition\pythonEd
  16895. %
  16896. To perform these actions we need the \code{exit} function (from the C
  16897. standard library) and two new AST classes: \code{TagOf} and
  16898. \code{ValueOf}. The \code{exit} function ends the execution of the
  16899. program. The \code{TagOf} operation retrieves the type tag from a
  16900. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16901. the underlying value from a tagged value. The \code{ValueOf}
  16902. operation includes the type for the underlying value which is used by
  16903. the type checker.
  16904. %
  16905. \fi}
  16906. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16907. \code{Project} can be translated as follows.
  16908. \begin{center}
  16909. \begin{minipage}{1.0\textwidth}
  16910. {\if\edition\racketEd
  16911. \begin{lstlisting}
  16912. (Project |$e$| |$\FType$|)
  16913. |$\Rightarrow$|
  16914. (Let |$\itm{tmp}$| |$e'$|
  16915. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16916. (Int |$\itm{tagof}(\FType)$|)))
  16917. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16918. (Exit)))
  16919. \end{lstlisting}
  16920. \fi}
  16921. {\if\edition\pythonEd
  16922. \begin{lstlisting}
  16923. Project(|$e$|, |$\FType$|)
  16924. |$\Rightarrow$|
  16925. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16926. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16927. [Constant(|$\itm{tagof}(\FType)$|)]),
  16928. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16929. Call(Name('exit'), [])))
  16930. \end{lstlisting}
  16931. \fi}
  16932. \end{minipage}
  16933. \end{center}
  16934. If the target type of the projection is a tuple or function type, then
  16935. there is a bit more work to do. For tuples, check that the length of
  16936. the tuple type matches the length of the tuple. For functions, check
  16937. that the number of parameters in the function type matches the
  16938. function's arity.
  16939. Regarding \code{Inject}, we recommend compiling it to a slightly
  16940. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  16941. takes a tag instead of a type.
  16942. \begin{center}
  16943. \begin{minipage}{1.0\textwidth}
  16944. {\if\edition\racketEd
  16945. \begin{lstlisting}
  16946. (Inject |$e$| |$\FType$|)
  16947. |$\Rightarrow$|
  16948. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16949. \end{lstlisting}
  16950. \fi}
  16951. {\if\edition\pythonEd
  16952. \begin{lstlisting}
  16953. Inject(|$e$|, |$\FType$|)
  16954. |$\Rightarrow$|
  16955. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16956. \end{lstlisting}
  16957. \fi}
  16958. \end{minipage}
  16959. \end{center}
  16960. {\if\edition\pythonEd
  16961. %
  16962. The introduction of \code{make\_any} makes it difficult to use
  16963. bidirectional type checking because we no longer have an expected type
  16964. to use for type checking the expression $e'$. Thus, we run into
  16965. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16966. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16967. annotated lambda) whose parameters have type annotations and that
  16968. records the return type.
  16969. %
  16970. \fi}
  16971. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16972. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16973. translation of \code{Project}.}
  16974. {\if\edition\racketEd
  16975. The \code{any-vector-ref} and \code{any-vector-set!} operations
  16976. combine the projection action with the vector operation. Also, the
  16977. read and write operations allow arbitrary expressions for the index so
  16978. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  16979. cannot guarantee that the index is within bounds. Thus, we insert code
  16980. to perform bounds checking at runtime. The translation for
  16981. \code{any-vector-ref} is as follows and the other two operations are
  16982. translated in a similar way.
  16983. \begin{center}
  16984. \begin{minipage}{0.95\textwidth}
  16985. \begin{lstlisting}
  16986. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  16987. |$\Rightarrow$|
  16988. (Let |$v$| |$e'_1$|
  16989. (Let |$i$| |$e'_2$|
  16990. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  16991. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  16992. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  16993. (Exit))
  16994. (Exit))))
  16995. \end{lstlisting}
  16996. \end{minipage}
  16997. \end{center}
  16998. \fi}
  16999. %
  17000. {\if\edition\pythonEd
  17001. %
  17002. The \code{any\_tuple\_load} operation combines the projection action
  17003. with the load operation. Also, the load operation allows arbitrary
  17004. expressions for the index so the type checker for \LangAny{}
  17005. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17006. within bounds. Thus, we insert code to perform bounds checking at
  17007. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17008. \begin{lstlisting}
  17009. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17010. |$\Rightarrow$|
  17011. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17012. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17013. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17014. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17015. Call(Name('exit'), [])),
  17016. Call(Name('exit'), [])))
  17017. \end{lstlisting}
  17018. \fi}
  17019. {\if\edition\pythonEd
  17020. \section{Assignment Conversion}
  17021. \label{sec:convert-assignments-Lany}
  17022. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17023. \code{AnnLambda} AST classes.
  17024. \section{Closure Conversion}
  17025. \label{sec:closure-conversion-Lany}
  17026. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17027. \code{AnnLambda} AST classes.
  17028. \fi}
  17029. \section{Remove Complex Operands}
  17030. \label{sec:rco-Lany}
  17031. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17032. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17033. %
  17034. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17035. complex expressions. Their subexpressions must be atomic.}
  17036. \section{Explicate Control and \LangCAny{}}
  17037. \label{sec:explicate-Lany}
  17038. The output of \code{explicate\_control} is the \LangCAny{} language
  17039. whose syntax is defined in figure~\ref{fig:c5-syntax}.
  17040. %
  17041. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17042. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17043. note that the index argument of \code{vector-ref} and
  17044. \code{vector-set!} is an $\Atm$ instead of an integer, as it was in
  17045. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17046. %
  17047. \python{
  17048. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17049. and \code{explicate\_pred} as appropriately to handle the new expressions
  17050. in \LangCAny{}.
  17051. }
  17052. \newcommand{\CanyASTPython}{
  17053. \begin{array}{lcl}
  17054. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17055. &\MID& \key{TagOf}\LP \Atm \RP
  17056. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17057. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17058. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17059. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17060. \end{array}
  17061. }
  17062. \newcommand{\CanyASTRacket}{
  17063. \begin{array}{lcl}
  17064. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17065. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17066. &\MID& \VALUEOF{\Atm}{\FType} \\
  17067. \Tail &::= & \LP\key{Exit}\RP
  17068. \end{array}
  17069. }
  17070. \begin{figure}[tp]
  17071. \begin{tcolorbox}[colback=white]
  17072. \small
  17073. {\if\edition\racketEd
  17074. \[
  17075. \begin{array}{l}
  17076. \gray{\CvarASTRacket} \\ \hline
  17077. \gray{\CifASTRacket} \\ \hline
  17078. \gray{\CloopASTRacket} \\ \hline
  17079. \gray{\CtupASTRacket} \\ \hline
  17080. \gray{\CfunASTRacket} \\ \hline
  17081. \gray{\ClambdaASTRacket} \\ \hline
  17082. \CanyASTRacket \\
  17083. \begin{array}{lcl}
  17084. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17085. \end{array}
  17086. \end{array}
  17087. \]
  17088. \fi}
  17089. {\if\edition\pythonEd
  17090. \[
  17091. \begin{array}{l}
  17092. \gray{\CifASTPython} \\ \hline
  17093. \gray{\CtupASTPython} \\ \hline
  17094. \gray{\CfunASTPython} \\ \hline
  17095. \gray{\ClambdaASTPython} \\ \hline
  17096. \CanyASTPython \\
  17097. \begin{array}{lcl}
  17098. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17099. \end{array}
  17100. \end{array}
  17101. \]
  17102. \fi}
  17103. \end{tcolorbox}
  17104. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  17105. \label{fig:c5-syntax}
  17106. \end{figure}
  17107. \section{Select Instructions}
  17108. \label{sec:select-Lany}
  17109. In the \code{select\_instructions} pass we translate the primitive
  17110. operations on the \ANYTY{} type to x86 instructions that manipulate
  17111. the 3 tag bits of the tagged value. In the following descriptions,
  17112. given an atom $e$ we use a primed variable $e'$ to refer to the result
  17113. of translating $e$ into an x86 argument.
  17114. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  17115. We recommend compiling the
  17116. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  17117. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  17118. shifts the destination to the left by the number of bits specified its
  17119. source argument (in this case $3$, the length of the tag) and it
  17120. preserves the sign of the integer. We use the \key{orq} instruction to
  17121. combine the tag and the value to form the tagged value. \\
  17122. %
  17123. {\if\edition\racketEd
  17124. \begin{lstlisting}
  17125. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17126. |$\Rightarrow$|
  17127. movq |$e'$|, |\itm{lhs'}|
  17128. salq $3, |\itm{lhs'}|
  17129. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17130. \end{lstlisting}
  17131. \fi}
  17132. %
  17133. {\if\edition\pythonEd
  17134. \begin{lstlisting}
  17135. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17136. |$\Rightarrow$|
  17137. movq |$e'$|, |\itm{lhs'}|
  17138. salq $3, |\itm{lhs'}|
  17139. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17140. \end{lstlisting}
  17141. \fi}
  17142. %
  17143. The instruction selection for tuples and procedures is different
  17144. because their is no need to shift them to the left. The rightmost 3
  17145. bits are already zeros so we simply combine the value and the tag
  17146. using \key{orq}. \\
  17147. %
  17148. {\if\edition\racketEd
  17149. \begin{center}
  17150. \begin{minipage}{\textwidth}
  17151. \begin{lstlisting}
  17152. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17153. |$\Rightarrow$|
  17154. movq |$e'$|, |\itm{lhs'}|
  17155. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17156. \end{lstlisting}
  17157. \end{minipage}
  17158. \end{center}
  17159. \fi}
  17160. %
  17161. {\if\edition\pythonEd
  17162. \begin{lstlisting}
  17163. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17164. |$\Rightarrow$|
  17165. movq |$e'$|, |\itm{lhs'}|
  17166. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17167. \end{lstlisting}
  17168. \fi}
  17169. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  17170. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  17171. operation extracts the type tag from a value of type \ANYTY{}. The
  17172. type tag is the bottom three bits, so we obtain the tag by taking the
  17173. bitwise-and of the value with $111$ ($7$ in decimal).
  17174. %
  17175. {\if\edition\racketEd
  17176. \begin{lstlisting}
  17177. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  17178. |$\Rightarrow$|
  17179. movq |$e'$|, |\itm{lhs'}|
  17180. andq $7, |\itm{lhs'}|
  17181. \end{lstlisting}
  17182. \fi}
  17183. %
  17184. {\if\edition\pythonEd
  17185. \begin{lstlisting}
  17186. Assign([|\itm{lhs}|], TagOf(|$e$|))
  17187. |$\Rightarrow$|
  17188. movq |$e'$|, |\itm{lhs'}|
  17189. andq $7, |\itm{lhs'}|
  17190. \end{lstlisting}
  17191. \fi}
  17192. \paragraph{\code{ValueOf}}
  17193. The instructions for \key{ValueOf} also differ depending on whether
  17194. the type $T$ is a pointer (tuple or function) or not (integer or
  17195. Boolean). The following shows the instruction selection for integers
  17196. and Booleans. We produce an untagged value by shifting it to the
  17197. right by 3 bits.
  17198. %
  17199. {\if\edition\racketEd
  17200. \begin{lstlisting}
  17201. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17202. |$\Rightarrow$|
  17203. movq |$e'$|, |\itm{lhs'}|
  17204. sarq $3, |\itm{lhs'}|
  17205. \end{lstlisting}
  17206. \fi}
  17207. %
  17208. {\if\edition\pythonEd
  17209. \begin{lstlisting}
  17210. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17211. |$\Rightarrow$|
  17212. movq |$e'$|, |\itm{lhs'}|
  17213. sarq $3, |\itm{lhs'}|
  17214. \end{lstlisting}
  17215. \fi}
  17216. %
  17217. In the case for tuples and procedures, we zero-out the rightmost 3
  17218. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  17219. ($7$ in decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  17220. in decimal) which we \code{movq} into the destination $\itm{lhs'}$.
  17221. Finally, we apply \code{andq} with the tagged value to get the desired
  17222. result.
  17223. %
  17224. {\if\edition\racketEd
  17225. \begin{lstlisting}
  17226. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17227. |$\Rightarrow$|
  17228. movq $|$-8$|, |\itm{lhs'}|
  17229. andq |$e'$|, |\itm{lhs'}|
  17230. \end{lstlisting}
  17231. \fi}
  17232. %
  17233. {\if\edition\pythonEd
  17234. \begin{lstlisting}
  17235. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17236. |$\Rightarrow$|
  17237. movq $|$-8$|, |\itm{lhs'}|
  17238. andq |$e'$|, |\itm{lhs'}|
  17239. \end{lstlisting}
  17240. \fi}
  17241. %% \paragraph{Type Predicates} We leave it to the reader to
  17242. %% devise a sequence of instructions to implement the type predicates
  17243. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  17244. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  17245. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  17246. operation combines the effect of \code{ValueOf} with accessing the
  17247. length of a tuple from the tag stored at the zero index of the tuple.
  17248. {\if\edition\racketEd
  17249. \begin{lstlisting}
  17250. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  17251. |$\Longrightarrow$|
  17252. movq $|$-8$|, %r11
  17253. andq |$e_1'$|, %r11
  17254. movq 0(%r11), %r11
  17255. andq $126, %r11
  17256. sarq $1, %r11
  17257. movq %r11, |$\itm{lhs'}$|
  17258. \end{lstlisting}
  17259. \fi}
  17260. {\if\edition\pythonEd
  17261. \begin{lstlisting}
  17262. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  17263. |$\Longrightarrow$|
  17264. movq $|$-8$|, %r11
  17265. andq |$e_1'$|, %r11
  17266. movq 0(%r11), %r11
  17267. andq $126, %r11
  17268. sarq $1, %r11
  17269. movq %r11, |$\itm{lhs'}$|
  17270. \end{lstlisting}
  17271. \fi}
  17272. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  17273. This operation combines the effect of \code{ValueOf} with reading an
  17274. element of the tuple (see
  17275. section~\ref{sec:select-instructions-gc}). However, the index may be
  17276. an arbitrary atom so instead of computing the offset at compile time,
  17277. we must generate instructions to compute the offset at runtime as
  17278. follows. Note the use of the new instruction \code{imulq}.
  17279. \begin{center}
  17280. \begin{minipage}{0.96\textwidth}
  17281. {\if\edition\racketEd
  17282. \begin{lstlisting}
  17283. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17284. |$\Longrightarrow$|
  17285. movq |$\neg 111$|, %r11
  17286. andq |$e_1'$|, %r11
  17287. movq |$e_2'$|, %rax
  17288. addq $1, %rax
  17289. imulq $8, %rax
  17290. addq %rax, %r11
  17291. movq 0(%r11) |$\itm{lhs'}$|
  17292. \end{lstlisting}
  17293. \fi}
  17294. %
  17295. {\if\edition\pythonEd
  17296. \begin{lstlisting}
  17297. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  17298. |$\Longrightarrow$|
  17299. movq $|$-8$|, %r11
  17300. andq |$e_1'$|, %r11
  17301. movq |$e_2'$|, %rax
  17302. addq $1, %rax
  17303. imulq $8, %rax
  17304. addq %rax, %r11
  17305. movq 0(%r11) |$\itm{lhs'}$|
  17306. \end{lstlisting}
  17307. \fi}
  17308. \end{minipage}
  17309. \end{center}
  17310. % $ pacify font lock
  17311. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  17312. %% The code generation for
  17313. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  17314. %% analogous to the above translation for reading from a tuple.
  17315. \section{Register Allocation for \LangAny{}}
  17316. \label{sec:register-allocation-Lany}
  17317. \index{subject}{register allocation}
  17318. There is an interesting interaction between tagged values and garbage
  17319. collection that has an impact on register allocation. A variable of
  17320. type \ANYTY{} might refer to a tuple and therefore it might be a root
  17321. that needs to be inspected and copied during garbage collection. Thus,
  17322. we need to treat variables of type \ANYTY{} in a similar way to
  17323. variables of tuple type for purposes of register allocation. In
  17324. particular,
  17325. \begin{itemize}
  17326. \item If a variable of type \ANYTY{} is live during a function call,
  17327. then it must be spilled. This can be accomplished by changing
  17328. \code{build\_interference} to mark all variables of type \ANYTY{}
  17329. that are live after a \code{callq} as interfering with all the
  17330. registers.
  17331. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  17332. the root stack instead of the normal procedure call stack.
  17333. \end{itemize}
  17334. Another concern regarding the root stack is that the garbage collector
  17335. needs to differentiate between (1) plain old pointers to tuples, (2) a
  17336. tagged value that points to a tuple, and (3) a tagged value that is
  17337. not a tuple. We enable this differentiation by choosing not to use the
  17338. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  17339. reserved for identifying plain old pointers to tuples. That way, if
  17340. one of the first three bits is set, then we have a tagged value and
  17341. inspecting the tag can differentiate between tuples ($010$) and the
  17342. other kinds of values.
  17343. %% \begin{exercise}\normalfont
  17344. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  17345. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  17346. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  17347. %% compiler on these new programs and all of your previously created test
  17348. %% programs.
  17349. %% \end{exercise}
  17350. \begin{exercise}\normalfont\normalsize
  17351. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  17352. Create tests for \LangDyn{} by adapting ten of your previous test programs
  17353. by removing type annotations. Add 5 more tests programs that
  17354. specifically rely on the language being dynamically typed. That is,
  17355. they should not be legal programs in a statically typed language, but
  17356. nevertheless, they should be valid \LangDyn{} programs that run to
  17357. completion without error.
  17358. \end{exercise}
  17359. \begin{figure}[p]
  17360. \begin{tcolorbox}[colback=white]
  17361. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  17362. \node (Lfun) at (0,4) {\large \LangDyn{}};
  17363. \node (Lfun-2) at (3,4) {\large \LangDyn{}};
  17364. \node (Lfun-3) at (6,4) {\large \LangDyn{}};
  17365. \node (Lfun-4) at (9,4) {\large \LangDynFunRef{}};
  17366. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  17367. \node (Lfun-6) at (9,2) {\large \LangAnyFunRef{}};
  17368. \node (Lfun-7) at (6,2) {\large \LangAnyFunRef{}};
  17369. \node (F1-2) at (3,2) {\large \LangAnyFunRef{}};
  17370. \node (F1-3) at (0,2) {\large \LangAnyFunRef{}};
  17371. \node (F1-4) at (0,0) {\large \LangAnyAlloc{}};
  17372. \node (F1-5) at (3,0) {\large \LangAnyAlloc{}};
  17373. \node (F1-6) at (6,0) {\large \LangAnyAlloc{}};
  17374. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  17375. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17376. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17377. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17378. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17379. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17380. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17381. \path[->,bend left=15] (Lfun) edge [above] node
  17382. {\ttfamily\footnotesize shrink} (Lfun-2);
  17383. \path[->,bend left=15] (Lfun-2) edge [above] node
  17384. {\ttfamily\footnotesize uniquify} (Lfun-3);
  17385. \path[->,bend left=15] (Lfun-3) edge [above] node
  17386. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  17387. \path[->,bend left=15] (Lfun-4) edge [left] node
  17388. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  17389. \path[->,bend left=15] (Lfun-5) edge [below] node
  17390. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  17391. \path[->,bend left=15] (Lfun-6) edge [below] node
  17392. {\ttfamily\footnotesize convert\_assign.} (Lfun-7);
  17393. \path[->,bend right=15] (Lfun-7) edge [above] node
  17394. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17395. \path[->,bend right=15] (F1-2) edge [above] node
  17396. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17397. \path[->,bend right=15] (F1-3) edge [right] node
  17398. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17399. \path[->,bend right=15] (F1-4) edge [below] node
  17400. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  17401. \path[->,bend left=15] (F1-5) edge [above] node
  17402. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  17403. \path[->,bend left=15] (F1-6) edge [right] node
  17404. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17405. \path[->,bend left=15] (C3-2) edge [left] node
  17406. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17407. \path[->,bend right=15] (x86-2) edge [left] node
  17408. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17409. \path[->,bend right=15] (x86-2-1) edge [below] node
  17410. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17411. \path[->,bend right=15] (x86-2-2) edge [left] node
  17412. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17413. \path[->,bend left=15] (x86-3) edge [above] node
  17414. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17415. \path[->,bend left=15] (x86-4) edge [right] node
  17416. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  17417. \end{tikzpicture}
  17418. \end{tcolorbox}
  17419. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  17420. \label{fig:Ldyn-passes}
  17421. \end{figure}
  17422. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  17423. for the compilation of \LangDyn{}.
  17424. % Further Reading
  17425. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17426. %% {\if\edition\pythonEd
  17427. %% \chapter{Objects}
  17428. %% \label{ch:Lobject}
  17429. %% \index{subject}{objects}
  17430. %% \index{subject}{classes}
  17431. %% \setcounter{footnote}{0}
  17432. %% \fi}
  17433. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17434. \chapter{Gradual Typing}
  17435. \label{ch:Lgrad}
  17436. \index{subject}{gradual typing}
  17437. \setcounter{footnote}{0}
  17438. This chapter studies a language, \LangGrad{}, in which the programmer
  17439. can choose between static and dynamic type checking in different parts
  17440. of a program, thereby mixing the statically typed \LangLam{} language
  17441. with the dynamically typed \LangDyn{}. There are several approaches to
  17442. mixing static and dynamic typing, including multi-language
  17443. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  17444. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  17445. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  17446. programmer controls the amount of static versus dynamic checking by
  17447. adding or removing type annotations on parameters and
  17448. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  17449. %
  17450. The concrete syntax of \LangGrad{} is defined in
  17451. figure~\ref{fig:Lgrad-concrete-syntax} and its abstract syntax is
  17452. defined in figure~\ref{fig:Lgrad-syntax}. The main syntactic
  17453. difference between \LangLam{} and \LangGrad{} is that type annotations
  17454. are optional, which is specified in the grammar using the \Param{} and
  17455. \itm{ret} nonterminals. In the abstract syntax, type annotations are
  17456. not optional but we use the \CANYTY{} type when a type annotation is
  17457. absent.
  17458. \newcommand{\LgradGrammarRacket}{
  17459. \begin{array}{lcl}
  17460. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  17461. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17462. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  17463. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  17464. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  17465. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  17466. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  17467. \end{array}
  17468. }
  17469. \newcommand{\LgradASTRacket}{
  17470. \begin{array}{lcl}
  17471. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  17472. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17473. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17474. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  17475. \itm{op} &::=& \code{procedure-arity} \\
  17476. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  17477. \end{array}
  17478. }
  17479. \newcommand{\LgradGrammarPython}{
  17480. \begin{array}{lcl}
  17481. \Type &::=& \key{Any}
  17482. \MID \key{int}
  17483. \MID \key{bool}
  17484. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  17485. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  17486. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17487. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  17488. \MID \CARITY{\Exp} \\
  17489. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  17490. \Param &::=& \Var \MID \Var \key{:} \Type \\
  17491. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  17492. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  17493. \end{array}
  17494. }
  17495. \newcommand{\LgradASTPython}{
  17496. \begin{array}{lcl}
  17497. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  17498. &\MID& \key{TupleType}\LP\Type^{*}\RP
  17499. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  17500. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  17501. &\MID& \ARITY{\Exp} \\
  17502. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  17503. \MID \RETURN{\Exp} \\
  17504. \Param &::=& \LP\Var\key{,}\Type\RP \\
  17505. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  17506. \end{array}
  17507. }
  17508. \begin{figure}[tp]
  17509. \centering
  17510. \begin{tcolorbox}[colback=white]
  17511. \small
  17512. {\if\edition\racketEd
  17513. \[
  17514. \begin{array}{l}
  17515. \gray{\LintGrammarRacket{}} \\ \hline
  17516. \gray{\LvarGrammarRacket{}} \\ \hline
  17517. \gray{\LifGrammarRacket{}} \\ \hline
  17518. \gray{\LwhileGrammarRacket} \\ \hline
  17519. \gray{\LtupGrammarRacket} \\ \hline
  17520. \LgradGrammarRacket \\
  17521. \begin{array}{lcl}
  17522. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  17523. \end{array}
  17524. \end{array}
  17525. \]
  17526. \fi}
  17527. {\if\edition\pythonEd
  17528. \[
  17529. \begin{array}{l}
  17530. \gray{\LintGrammarPython{}} \\ \hline
  17531. \gray{\LvarGrammarPython{}} \\ \hline
  17532. \gray{\LifGrammarPython{}} \\ \hline
  17533. \gray{\LwhileGrammarPython} \\ \hline
  17534. \gray{\LtupGrammarPython} \\ \hline
  17535. \LgradGrammarPython \\
  17536. \begin{array}{lcl}
  17537. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  17538. \end{array}
  17539. \end{array}
  17540. \]
  17541. \fi}
  17542. \end{tcolorbox}
  17543. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  17544. \label{fig:Lgrad-concrete-syntax}
  17545. \end{figure}
  17546. \begin{figure}[tp]
  17547. \centering
  17548. \begin{tcolorbox}[colback=white]
  17549. \small
  17550. {\if\edition\racketEd
  17551. \[
  17552. \begin{array}{l}
  17553. \gray{\LintOpAST} \\ \hline
  17554. \gray{\LvarASTRacket{}} \\ \hline
  17555. \gray{\LifASTRacket{}} \\ \hline
  17556. \gray{\LwhileASTRacket{}} \\ \hline
  17557. \gray{\LtupASTRacket{}} \\ \hline
  17558. \LgradASTRacket \\
  17559. \begin{array}{lcl}
  17560. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17561. \end{array}
  17562. \end{array}
  17563. \]
  17564. \fi}
  17565. {\if\edition\pythonEd
  17566. \[
  17567. \begin{array}{l}
  17568. \gray{\LintASTPython{}} \\ \hline
  17569. \gray{\LvarASTPython{}} \\ \hline
  17570. \gray{\LifASTPython{}} \\ \hline
  17571. \gray{\LwhileASTPython} \\ \hline
  17572. \gray{\LtupASTPython} \\ \hline
  17573. \LgradASTPython \\
  17574. \begin{array}{lcl}
  17575. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17576. \end{array}
  17577. \end{array}
  17578. \]
  17579. \fi}
  17580. \end{tcolorbox}
  17581. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  17582. \label{fig:Lgrad-syntax}
  17583. \end{figure}
  17584. Both the type checker and the interpreter for \LangGrad{} require some
  17585. interesting changes to enable gradual typing, which we discuss in the
  17586. next two sections.
  17587. % TODO: more road map -Jeremy
  17588. %\clearpage
  17589. \section{Type Checking \LangGrad{}}
  17590. \label{sec:gradual-type-check}
  17591. We begin by discussing the type checking of a partially-typed variant
  17592. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  17593. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  17594. statically typed, so there is nothing special happening there with
  17595. respect to type checking. On the other hand, the \code{inc} function
  17596. does not have type annotations, so parameter \code{x} is given the
  17597. type \CANYTY{} and the return type of \code{inc} is \CANYTY{}. Now
  17598. consider the \code{+} operator inside \code{inc}. It expects both
  17599. arguments to have type \INTTY{}, but its first argument \code{x}
  17600. has type \CANYTY{}. In a gradually typed language, such differences
  17601. are allowed so long as the types are \emph{consistent}, that is, they
  17602. are equal except in places where there is an \CANYTY{} type. That is,
  17603. the type \CANYTY{} is consistent with every other type.
  17604. Figure~\ref{fig:consistent} defines the
  17605. \racket{\code{consistent?}}\python{\code{consistent}} method.
  17606. %
  17607. So the type checker allows the \code{+} operator to be applied
  17608. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  17609. %
  17610. Next consider the call to the \code{map} function in
  17611. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  17612. tuple. The \code{inc} function has type
  17613. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17614. but parameter \code{f} of \code{map} has type
  17615. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17616. The type checker for \LangGrad{} accepts this call because the two types are
  17617. consistent.
  17618. \begin{figure}[btp]
  17619. % gradual_test_9.rkt
  17620. \begin{tcolorbox}[colback=white]
  17621. {\if\edition\racketEd
  17622. \begin{lstlisting}
  17623. (define (map [f : (Integer -> Integer)]
  17624. [v : (Vector Integer Integer)])
  17625. : (Vector Integer Integer)
  17626. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17627. (define (inc x) (+ x 1))
  17628. (vector-ref (map inc (vector 0 41)) 1)
  17629. \end{lstlisting}
  17630. \fi}
  17631. {\if\edition\pythonEd
  17632. \begin{lstlisting}
  17633. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17634. return f(v[0]), f(v[1])
  17635. def inc(x):
  17636. return x + 1
  17637. t = map(inc, (0, 41))
  17638. print(t[1])
  17639. \end{lstlisting}
  17640. \fi}
  17641. \end{tcolorbox}
  17642. \caption{A partially-typed version of the \code{map} example.}
  17643. \label{fig:gradual-map}
  17644. \end{figure}
  17645. \begin{figure}[tbp]
  17646. \begin{tcolorbox}[colback=white]
  17647. {\if\edition\racketEd
  17648. \begin{lstlisting}
  17649. (define/public (consistent? t1 t2)
  17650. (match* (t1 t2)
  17651. [('Integer 'Integer) #t]
  17652. [('Boolean 'Boolean) #t]
  17653. [('Void 'Void) #t]
  17654. [('Any t2) #t]
  17655. [(t1 'Any) #t]
  17656. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17657. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  17658. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17659. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  17660. (consistent? rt1 rt2))]
  17661. [(other wise) #f]))
  17662. \end{lstlisting}
  17663. \fi}
  17664. {\if\edition\pythonEd
  17665. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17666. def consistent(self, t1, t2):
  17667. match (t1, t2):
  17668. case (AnyType(), _):
  17669. return True
  17670. case (_, AnyType()):
  17671. return True
  17672. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17673. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  17674. case (TupleType(ts1), TupleType(ts2)):
  17675. return all(map(self.consistent, ts1, ts2))
  17676. case (_, _):
  17677. return t1 == t2
  17678. \end{lstlisting}
  17679. \fi}
  17680. \end{tcolorbox}
  17681. \caption{The consistency method on types.}
  17682. \label{fig:consistent}
  17683. \end{figure}
  17684. It is also helpful to consider how gradual typing handles programs with an
  17685. error, such as applying \code{map} to a function that sometimes
  17686. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  17687. type checker for \LangGrad{} accepts this program because the type of
  17688. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  17689. \code{map}, that is,
  17690. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17691. is consistent with
  17692. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17693. One might say that a gradual type checker is optimistic in that it
  17694. accepts programs that might execute without a runtime type error.
  17695. %
  17696. The type checker for \LangGrad{} is defined in
  17697. Figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  17698. and \ref{fig:type-check-Lgradual-3}.
  17699. %% \begin{figure}[tp]
  17700. %% \centering
  17701. %% \fbox{
  17702. %% \begin{minipage}{0.96\textwidth}
  17703. %% \small
  17704. %% \[
  17705. %% \begin{array}{lcl}
  17706. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17707. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17708. %% \end{array}
  17709. %% \]
  17710. %% \end{minipage}
  17711. %% }
  17712. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  17713. %% \label{fig:Lgrad-prime-syntax}
  17714. %% \end{figure}
  17715. \begin{figure}[tbp]
  17716. \begin{tcolorbox}[colback=white]
  17717. {\if\edition\racketEd
  17718. \begin{lstlisting}
  17719. (define (map [f : (Integer -> Integer)]
  17720. [v : (Vector Integer Integer)])
  17721. : (Vector Integer Integer)
  17722. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17723. (define (inc x) (+ x 1))
  17724. (define (true) #t)
  17725. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  17726. (vector-ref (map maybe_inc (vector 0 41)) 0)
  17727. \end{lstlisting}
  17728. \fi}
  17729. {\if\edition\pythonEd
  17730. \begin{lstlisting}
  17731. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17732. return f(v[0]), f(v[1])
  17733. def inc(x):
  17734. return x + 1
  17735. def true():
  17736. return True
  17737. def maybe_inc(x):
  17738. return inc(x) if input_int() == 0 else true()
  17739. t = map(maybe_inc, (0, 41))
  17740. print( t[1] )
  17741. \end{lstlisting}
  17742. \fi}
  17743. \end{tcolorbox}
  17744. \caption{A variant of the \code{map} example with an error.}
  17745. \label{fig:map-maybe_inc}
  17746. \end{figure}
  17747. Running this program with input \code{1} triggers an
  17748. error when the \code{maybe\_inc} function returns
  17749. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  17750. performs checking at runtime to ensure the integrity of the static
  17751. types, such as the
  17752. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  17753. annotation on
  17754. parameter \code{f} of \code{map}.
  17755. Here we give a preview of how the runtime checking is accomplished;
  17756. the following sections provide the details.
  17757. The runtime checking is carried out by a new \code{Cast} AST node that
  17758. is generate in a new pass named \code{cast\_insert}. The output of
  17759. \code{cast\_insert} is a program in the \LangCast{} language, which
  17760. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  17761. %
  17762. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  17763. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  17764. inserted every time the type checker sees two types that are
  17765. consistent but not equal. In the \code{inc} function, \code{x} is
  17766. cast to \INTTY{} and the result of the \code{+} is cast to
  17767. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  17768. is cast from
  17769. \racket{\code{(Any -> Any)}}
  17770. \python{\code{Callable[[Any], Any]}}
  17771. to
  17772. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17773. %
  17774. In the next section we see how to interpret the \code{Cast} node.
  17775. \begin{figure}[btp]
  17776. \begin{tcolorbox}[colback=white]
  17777. {\if\edition\racketEd
  17778. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17779. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17780. : (Vector Integer Integer)
  17781. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17782. (define (inc [x : Any]) : Any
  17783. (cast (+ (cast x Any Integer) 1) Integer Any))
  17784. (define (true) : Any (cast #t Boolean Any))
  17785. (define (maybe_inc [x : Any]) : Any
  17786. (if (eq? 0 (read)) (inc x) (true)))
  17787. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  17788. (vector 0 41)) 0)
  17789. \end{lstlisting}
  17790. \fi}
  17791. {\if\edition\pythonEd
  17792. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17793. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17794. return f(v[0]), f(v[1])
  17795. def inc(x : Any) -> Any:
  17796. return Cast(Cast(x, Any, int) + 1, int, Any)
  17797. def true() -> Any:
  17798. return Cast(True, bool, Any)
  17799. def maybe_inc(x : Any) -> Any:
  17800. return inc(x) if input_int() == 0 else true()
  17801. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  17802. (0, 41))
  17803. print(t[1])
  17804. \end{lstlisting}
  17805. \fi}
  17806. \end{tcolorbox}
  17807. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  17808. and \code{maybe\_inc} example.}
  17809. \label{fig:map-cast}
  17810. \end{figure}
  17811. {\if\edition\pythonEd
  17812. \begin{figure}[tbp]
  17813. \begin{tcolorbox}[colback=white]
  17814. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17815. class TypeCheckLgrad(TypeCheckLlambda):
  17816. def type_check_exp(self, e, env) -> Type:
  17817. match e:
  17818. case Name(id):
  17819. return env[id]
  17820. case Constant(value) if isinstance(value, bool):
  17821. return BoolType()
  17822. case Constant(value) if isinstance(value, int):
  17823. return IntType()
  17824. case Call(Name('input_int'), []):
  17825. return IntType()
  17826. case BinOp(left, op, right):
  17827. left_type = self.type_check_exp(left, env)
  17828. self.check_consistent(left_type, IntType(), left)
  17829. right_type = self.type_check_exp(right, env)
  17830. self.check_consistent(right_type, IntType(), right)
  17831. return IntType()
  17832. case IfExp(test, body, orelse):
  17833. test_t = self.type_check_exp(test, env)
  17834. self.check_consistent(test_t, BoolType(), test)
  17835. body_t = self.type_check_exp(body, env)
  17836. orelse_t = self.type_check_exp(orelse, env)
  17837. self.check_consistent(body_t, orelse_t, e)
  17838. return self.join_types(body_t, orelse_t)
  17839. case Call(func, args):
  17840. func_t = self.type_check_exp(func, env)
  17841. args_t = [self.type_check_exp(arg, env) for arg in args]
  17842. match func_t:
  17843. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  17844. for (arg_t, param_t) in zip(args_t, params_t):
  17845. self.check_consistent(param_t, arg_t, e)
  17846. return return_t
  17847. case AnyType():
  17848. return AnyType()
  17849. case _:
  17850. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  17851. ...
  17852. case _:
  17853. raise Exception('type_check_exp: unexpected ' + repr(e))
  17854. \end{lstlisting}
  17855. \end{tcolorbox}
  17856. \caption{Type checking expressions in the \LangGrad{} language.}
  17857. \label{fig:type-check-Lgradual-1}
  17858. \end{figure}
  17859. \begin{figure}[tbp]
  17860. \begin{tcolorbox}[colback=white]
  17861. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17862. def check_exp(self, e, expected_ty, env):
  17863. match e:
  17864. case Lambda(params, body):
  17865. match expected_ty:
  17866. case FunctionType(params_t, return_t):
  17867. new_env = env.copy().update(zip(params, params_t))
  17868. e.has_type = expected_ty
  17869. body_ty = self.type_check_exp(body, new_env)
  17870. self.check_consistent(body_ty, return_t)
  17871. case AnyType():
  17872. new_env = env.copy().update((p, AnyType()) for p in params)
  17873. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  17874. body_ty = self.type_check_exp(body, new_env)
  17875. case _:
  17876. raise Exception('lambda does not have type ' + str(expected_ty))
  17877. case _:
  17878. e_ty = self.type_check_exp(e, env)
  17879. self.check_consistent(e_ty, expected_ty, e)
  17880. \end{lstlisting}
  17881. \end{tcolorbox}
  17882. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  17883. \label{fig:type-check-Lgradual-2}
  17884. \end{figure}
  17885. \begin{figure}[tbp]
  17886. \begin{tcolorbox}[colback=white]
  17887. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17888. def type_check_stmt(self, s, env, return_type):
  17889. match s:
  17890. case Assign([Name(id)], value):
  17891. value_ty = self.type_check_exp(value, env)
  17892. if id in env:
  17893. self.check_consistent(env[id], value_ty, value)
  17894. else:
  17895. env[id] = value_ty
  17896. ...
  17897. case _:
  17898. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  17899. def type_check_stmts(self, ss, env, return_type):
  17900. for s in ss:
  17901. self.type_check_stmt(s, env, return_type)
  17902. \end{lstlisting}
  17903. \end{tcolorbox}
  17904. \caption{Type checking statements in the \LangGrad{} language.}
  17905. \label{fig:type-check-Lgradual-3}
  17906. \end{figure}
  17907. \begin{figure}[tbp]
  17908. \begin{tcolorbox}[colback=white]
  17909. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17910. def join_types(self, t1, t2):
  17911. match (t1, t2):
  17912. case (AnyType(), _):
  17913. return t2
  17914. case (_, AnyType()):
  17915. return t1
  17916. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17917. return FunctionType(list(map(self.join_types, ps1, ps2)),
  17918. self.join_types(rt1,rt2))
  17919. case (TupleType(ts1), TupleType(ts2)):
  17920. return TupleType(list(map(self.join_types, ts1, ts2)))
  17921. case (_, _):
  17922. return t1
  17923. def check_consistent(self, t1, t2, e):
  17924. if not self.consistent(t1, t2):
  17925. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  17926. + ' in ' + repr(e))
  17927. \end{lstlisting}
  17928. \end{tcolorbox}
  17929. \caption{Auxiliary methods for type checking \LangGrad{}.}
  17930. \label{fig:type-check-Lgradual-aux}
  17931. \end{figure}
  17932. \fi}
  17933. {\if\edition\racketEd
  17934. \begin{figure}[tbp]
  17935. \begin{tcolorbox}[colback=white]
  17936. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17937. (define type-check-gradual-class
  17938. (class type-check-Llambda-class
  17939. (super-new)
  17940. (inherit operator-types type-predicates)
  17941. (define/override (type-check-exp env)
  17942. (lambda (e)
  17943. (define recur (type-check-exp env))
  17944. (match e
  17945. [(Prim 'vector-length (list e1))
  17946. (define-values (e1^ t) (recur e1))
  17947. (match t
  17948. [`(Vector ,ts ...)
  17949. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17950. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17951. [(Prim 'vector-ref (list e1 e2))
  17952. (define-values (e1^ t1) (recur e1))
  17953. (define-values (e2^ t2) (recur e2))
  17954. (check-consistent? t2 'Integer e)
  17955. (match t1
  17956. [`(Vector ,ts ...)
  17957. (match e2^
  17958. [(Int i)
  17959. (unless (and (0 . <= . i) (i . < . (length ts)))
  17960. (error 'type-check "invalid index ~a in ~a" i e))
  17961. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17962. [else (define e1^^ (make-cast e1^ t1 'Any))
  17963. (define e2^^ (make-cast e2^ t2 'Integer))
  17964. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17965. ['Any
  17966. (define e2^^ (make-cast e2^ t2 'Integer))
  17967. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17968. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17969. [(Prim 'vector-set! (list e1 e2 e3) )
  17970. (define-values (e1^ t1) (recur e1))
  17971. (define-values (e2^ t2) (recur e2))
  17972. (define-values (e3^ t3) (recur e3))
  17973. (check-consistent? t2 'Integer e)
  17974. (match t1
  17975. [`(Vector ,ts ...)
  17976. (match e2^
  17977. [(Int i)
  17978. (unless (and (0 . <= . i) (i . < . (length ts)))
  17979. (error 'type-check "invalid index ~a in ~a" i e))
  17980. (check-consistent? (list-ref ts i) t3 e)
  17981. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  17982. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  17983. [else
  17984. (define e1^^ (make-cast e1^ t1 'Any))
  17985. (define e2^^ (make-cast e2^ t2 'Integer))
  17986. (define e3^^ (make-cast e3^ t3 'Any))
  17987. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  17988. ['Any
  17989. (define e2^^ (make-cast e2^ t2 'Integer))
  17990. (define e3^^ (make-cast e3^ t3 'Any))
  17991. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  17992. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17993. \end{lstlisting}
  17994. \end{tcolorbox}
  17995. \caption{Type checker for the \LangGrad{} language, part 1.}
  17996. \label{fig:type-check-Lgradual-1}
  17997. \end{figure}
  17998. \begin{figure}[tbp]
  17999. \begin{tcolorbox}[colback=white]
  18000. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18001. [(Prim 'eq? (list e1 e2))
  18002. (define-values (e1^ t1) (recur e1))
  18003. (define-values (e2^ t2) (recur e2))
  18004. (check-consistent? t1 t2 e)
  18005. (define T (meet t1 t2))
  18006. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  18007. 'Boolean)]
  18008. [(Prim 'not (list e1))
  18009. (define-values (e1^ t1) (recur e1))
  18010. (match t1
  18011. ['Any
  18012. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  18013. (Bool #t) (Bool #f)))]
  18014. [else
  18015. (define-values (t-ret new-es^)
  18016. (type-check-op 'not (list t1) (list e1^) e))
  18017. (values (Prim 'not new-es^) t-ret)])]
  18018. [(Prim 'and (list e1 e2))
  18019. (recur (If e1 e2 (Bool #f)))]
  18020. [(Prim 'or (list e1 e2))
  18021. (define tmp (gensym 'tmp))
  18022. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18023. [(Prim op es)
  18024. #:when (not (set-member? explicit-prim-ops op))
  18025. (define-values (new-es ts)
  18026. (for/lists (exprs types) ([e es])
  18027. (recur e)))
  18028. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  18029. (values (Prim op new-es^) t-ret)]
  18030. [(If e1 e2 e3)
  18031. (define-values (e1^ T1) (recur e1))
  18032. (define-values (e2^ T2) (recur e2))
  18033. (define-values (e3^ T3) (recur e3))
  18034. (check-consistent? T2 T3 e)
  18035. (match T1
  18036. ['Boolean
  18037. (define Tif (join T2 T3))
  18038. (values (If e1^ (make-cast e2^ T2 Tif)
  18039. (make-cast e3^ T3 Tif)) Tif)]
  18040. ['Any
  18041. (define Tif (meet T2 T3))
  18042. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  18043. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  18044. Tif)]
  18045. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  18046. [(HasType e1 T)
  18047. (define-values (e1^ T1) (recur e1))
  18048. (check-consistent? T1 T)
  18049. (values (make-cast e1^ T1 T) T)]
  18050. [(SetBang x e1)
  18051. (define-values (e1^ T1) (recur e1))
  18052. (define varT (dict-ref env x))
  18053. (check-consistent? T1 varT e)
  18054. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  18055. [(WhileLoop e1 e2)
  18056. (define-values (e1^ T1) (recur e1))
  18057. (check-consistent? T1 'Boolean e)
  18058. (define-values (e2^ T2) ((type-check-exp env) e2))
  18059. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  18060. \end{lstlisting}
  18061. \end{tcolorbox}
  18062. \caption{Type checker for the \LangGrad{} language, part 2.}
  18063. \label{fig:type-check-Lgradual-2}
  18064. \end{figure}
  18065. \begin{figure}[tbp]
  18066. \begin{tcolorbox}[colback=white]
  18067. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18068. [(Apply e1 e2s)
  18069. (define-values (e1^ T1) (recur e1))
  18070. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18071. (match T1
  18072. [`(,T1ps ... -> ,T1rt)
  18073. (for ([T2 T2s] [Tp T1ps])
  18074. (check-consistent? T2 Tp e))
  18075. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  18076. (make-cast e2 src tgt)))
  18077. (values (Apply e1^ e2s^^) T1rt)]
  18078. [`Any
  18079. (define e1^^ (make-cast e1^ 'Any
  18080. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  18081. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  18082. (make-cast e2 src 'Any)))
  18083. (values (Apply e1^^ e2s^^) 'Any)]
  18084. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18085. [(Lambda params Tr e1)
  18086. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18087. (match p
  18088. [`[,x : ,T] (values x T)]
  18089. [(? symbol? x) (values x 'Any)])))
  18090. (define-values (e1^ T1)
  18091. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18092. (check-consistent? Tr T1 e)
  18093. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  18094. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  18095. [else ((super type-check-exp env) e)]
  18096. )))
  18097. \end{lstlisting}
  18098. \end{tcolorbox}
  18099. \caption{Type checker for the \LangGrad{} language, part 3.}
  18100. \label{fig:type-check-Lgradual-3}
  18101. \end{figure}
  18102. \begin{figure}[tbp]
  18103. \begin{tcolorbox}[colback=white]
  18104. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18105. (define/public (join t1 t2)
  18106. (match* (t1 t2)
  18107. [('Integer 'Integer) 'Integer]
  18108. [('Boolean 'Boolean) 'Boolean]
  18109. [('Void 'Void) 'Void]
  18110. [('Any t2) t2]
  18111. [(t1 'Any) t1]
  18112. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18113. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  18114. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18115. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  18116. -> ,(join rt1 rt2))]))
  18117. (define/public (meet t1 t2)
  18118. (match* (t1 t2)
  18119. [('Integer 'Integer) 'Integer]
  18120. [('Boolean 'Boolean) 'Boolean]
  18121. [('Void 'Void) 'Void]
  18122. [('Any t2) 'Any]
  18123. [(t1 'Any) 'Any]
  18124. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18125. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  18126. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18127. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  18128. -> ,(meet rt1 rt2))]))
  18129. (define/public (make-cast e src tgt)
  18130. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  18131. (define/public (check-consistent? t1 t2 e)
  18132. (unless (consistent? t1 t2)
  18133. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  18134. (define/override (type-check-op op arg-types args e)
  18135. (match (dict-ref (operator-types) op)
  18136. [`(,param-types . ,return-type)
  18137. (for ([at arg-types] [pt param-types])
  18138. (check-consistent? at pt e))
  18139. (values return-type
  18140. (for/list ([e args] [s arg-types] [t param-types])
  18141. (make-cast e s t)))]
  18142. [else (error 'type-check-op "unrecognized ~a" op)]))
  18143. (define explicit-prim-ops
  18144. (set-union
  18145. (type-predicates)
  18146. (set 'procedure-arity 'eq?
  18147. 'vector 'vector-length 'vector-ref 'vector-set!
  18148. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  18149. (define/override (fun-def-type d)
  18150. (match d
  18151. [(Def f params rt info body)
  18152. (define ps
  18153. (for/list ([p params])
  18154. (match p
  18155. [`[,x : ,T] T]
  18156. [(? symbol?) 'Any]
  18157. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  18158. `(,@ps -> ,rt)]
  18159. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  18160. \end{lstlisting}
  18161. \end{tcolorbox}
  18162. \caption{Auxiliary functions for type checking \LangGrad{}.}
  18163. \label{fig:type-check-Lgradual-aux}
  18164. \end{figure}
  18165. \fi}
  18166. \clearpage
  18167. \section{Interpreting \LangCast{}}
  18168. \label{sec:interp-casts}
  18169. The runtime behavior of casts involving simple types such as
  18170. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  18171. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  18172. \code{Inject} operator of \LangAny{}, which puts the integer into a
  18173. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  18174. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  18175. operator, that is, by checking the value's tag and either retrieving
  18176. the underlying integer or signalling an error if the tag is not the
  18177. one for integers (figure~\ref{fig:interp-Lany-aux}).
  18178. %
  18179. Things get more interesting for casts involving function, tuple, or array
  18180. types.
  18181. Consider the cast of the function \code{maybe\_inc} from
  18182. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  18183. to
  18184. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  18185. in figure~\ref{fig:map-maybe_inc}.
  18186. When the \code{maybe\_inc} function flows through
  18187. this cast at runtime, we don't know whether it will return
  18188. an integer, as that depends on the input from the user.
  18189. The \LangCast{} interpreter therefore delays the checking
  18190. of the cast until the function is applied. To do so it
  18191. wraps \code{maybe\_inc} in a new function that casts its parameter
  18192. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  18193. casts the return value from \CANYTY{} to \INTTY{}.
  18194. {\if\edition\pythonEd
  18195. %
  18196. There are further complicatons regarding casts on mutable data
  18197. such as the \code{list} type introduced in
  18198. the challenge assignment of section~\ref{sec:arrays}.
  18199. %
  18200. \fi}
  18201. %
  18202. Consider the example in figure~\ref{fig:map-bang} that
  18203. defines a partially-typed version of \code{map} whose parameter
  18204. \code{v} has type
  18205. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  18206. and that updates \code{v} in place
  18207. instead of returning a new tuple. So we name this function
  18208. \code{map\_inplace}. We apply \code{map\_inplace} to an
  18209. \racket{tuple}\python{array} of integers, so the type checker inserts a
  18210. cast from
  18211. \racket{\code{(Vector Integer Integer)}}
  18212. \python{\code{list[int]}}
  18213. to
  18214. \racket{\code{(Vector Any Any)}}
  18215. \python{\code{list[Any]}}.
  18216. A naive way for the \LangCast{} interpreter to cast between
  18217. \racket{tuple}\python{array} types would be a build a new
  18218. \racket{tuple}\python{array}
  18219. whose elements are the result
  18220. of casting each of the original elements to the appropriate target
  18221. type.
  18222. However, this approach is not valid for mutable data structures.
  18223. In the example of figure~\ref{fig:map-bang},
  18224. if the cast created a new \racket{tuple}\python{array}, then the updates inside of
  18225. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  18226. the original one.
  18227. \begin{figure}[tbp]
  18228. \begin{tcolorbox}[colback=white]
  18229. % gradual_test_11.rkt
  18230. {\if\edition\racketEd
  18231. \begin{lstlisting}
  18232. (define (map_inplace [f : (Any -> Any)]
  18233. [v : (Vector Any Any)]) : Void
  18234. (begin
  18235. (vector-set! v 0 (f (vector-ref v 0)))
  18236. (vector-set! v 1 (f (vector-ref v 1)))))
  18237. (define (inc x) (+ x 1))
  18238. (let ([v (vector 0 41)])
  18239. (begin (map_inplace inc v) (vector-ref v 1)))
  18240. \end{lstlisting}
  18241. \fi}
  18242. {\if\edition\pythonEd
  18243. \begin{lstlisting}
  18244. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  18245. i = 0
  18246. while i != len(v):
  18247. v[i] = f(v[i])
  18248. i = i + 1
  18249. def inc(x : int) -> int:
  18250. return x + 1
  18251. v = [0, 41]
  18252. map_inplace(inc, v)
  18253. print( v[1] )
  18254. \end{lstlisting}
  18255. \fi}
  18256. \end{tcolorbox}
  18257. \caption{An example involving casts on arrays.}
  18258. \label{fig:map-bang}
  18259. \end{figure}
  18260. Instead the interpreter needs to create a new kind of value, a
  18261. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  18262. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  18263. and then applies a
  18264. cast to the resulting value. On a write, the proxy casts the argument
  18265. value and then performs the write to the underlying \racket{tuple}\python{array}.
  18266. \racket{
  18267. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  18268. \code{0} from \INTTY{} to \CANYTY{}.
  18269. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  18270. from \CANYTY{} to \INTTY{}.
  18271. }
  18272. \python{
  18273. For the subscript \code{v[i]} in \code{f([v[i])} of \code{map\_inplace},
  18274. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  18275. For the subscript on the left of the assignment,
  18276. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  18277. }
  18278. The final category of cast that we need to consider are casts between
  18279. the \CANYTY{} type and higher-order types such as functions or
  18280. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  18281. variant of \code{map\_inplace} in which parameter \code{v} does not
  18282. have a type annotation, so it is given type \CANYTY{}. In the call to
  18283. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  18284. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  18285. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  18286. \code{Inject}, but that doesn't work because
  18287. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  18288. a flat type. Instead, we must first cast to
  18289. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}} (which is flat)
  18290. and then inject to \CANYTY{}.
  18291. \begin{figure}[tbp]
  18292. \begin{tcolorbox}[colback=white]
  18293. {\if\edition\racketEd
  18294. \begin{lstlisting}
  18295. (define (map_inplace [f : (Any -> Any)] v) : Void
  18296. (begin
  18297. (vector-set! v 0 (f (vector-ref v 0)))
  18298. (vector-set! v 1 (f (vector-ref v 1)))))
  18299. (define (inc x) (+ x 1))
  18300. (let ([v (vector 0 41)])
  18301. (begin (map_inplace inc v) (vector-ref v 1)))
  18302. \end{lstlisting}
  18303. \fi}
  18304. {\if\edition\pythonEd
  18305. \begin{lstlisting}
  18306. def map_inplace(f : Callable[[Any], Any], v) -> None:
  18307. i = 0
  18308. while i != len(v):
  18309. v[i] = f(v[i])
  18310. i = i + 1
  18311. def inc(x):
  18312. return x + 1
  18313. v = [0, 41]
  18314. map_inplace(inc, v)
  18315. print( v[1] )
  18316. \end{lstlisting}
  18317. \fi}
  18318. \end{tcolorbox}
  18319. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  18320. \label{fig:map-any}
  18321. \end{figure}
  18322. \begin{figure}[tbp]
  18323. \begin{tcolorbox}[colback=white]
  18324. {\if\edition\racketEd
  18325. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18326. (define/public (apply_cast v s t)
  18327. (match* (s t)
  18328. [(t1 t2) #:when (equal? t1 t2) v]
  18329. [('Any t2)
  18330. (match t2
  18331. [`(,ts ... -> ,rt)
  18332. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18333. (define v^ (apply-project v any->any))
  18334. (apply_cast v^ any->any `(,@ts -> ,rt))]
  18335. [`(Vector ,ts ...)
  18336. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18337. (define v^ (apply-project v vec-any))
  18338. (apply_cast v^ vec-any `(Vector ,@ts))]
  18339. [else (apply-project v t2)])]
  18340. [(t1 'Any)
  18341. (match t1
  18342. [`(,ts ... -> ,rt)
  18343. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18344. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  18345. (apply-inject v^ (any-tag any->any))]
  18346. [`(Vector ,ts ...)
  18347. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18348. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  18349. (apply-inject v^ (any-tag vec-any))]
  18350. [else (apply-inject v (any-tag t1))])]
  18351. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18352. (define x (gensym 'x))
  18353. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  18354. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  18355. (define cast-writes
  18356. (for/list ([t1 ts1] [t2 ts2])
  18357. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  18358. `(vector-proxy ,(vector v (apply vector cast-reads)
  18359. (apply vector cast-writes)))]
  18360. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18361. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  18362. `(function ,xs ,(Cast
  18363. (Apply (Value v)
  18364. (for/list ([x xs][t1 ts1][t2 ts2])
  18365. (Cast (Var x) t2 t1)))
  18366. rt1 rt2) ())]
  18367. ))
  18368. \end{lstlisting}
  18369. \fi}
  18370. {\if\edition\pythonEd
  18371. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18372. def apply_cast(self, value, src, tgt):
  18373. match (src, tgt):
  18374. case (AnyType(), FunctionType(ps2, rt2)):
  18375. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  18376. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  18377. case (AnyType(), TupleType(ts2)):
  18378. anytup = TupleType([AnyType() for t1 in ts2])
  18379. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  18380. case (AnyType(), ListType(t2)):
  18381. anylist = ListType([AnyType() for t1 in ts2])
  18382. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  18383. case (AnyType(), AnyType()):
  18384. return value
  18385. case (AnyType(), _):
  18386. return self.apply_project(value, tgt)
  18387. case (FunctionType(ps1,rt1), AnyType()):
  18388. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  18389. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  18390. case (TupleType(ts1), AnyType()):
  18391. anytup = TupleType([AnyType() for t1 in ts1])
  18392. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  18393. case (ListType(t1), AnyType()):
  18394. anylist = ListType(AnyType())
  18395. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  18396. case (_, AnyType()):
  18397. return self.apply_inject(value, src)
  18398. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18399. params = [generate_name('x') for p in ps2]
  18400. args = [Cast(Name(x), t2, t1)
  18401. for (x,t1,t2) in zip(params, ps1, ps2)]
  18402. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  18403. return Function('cast', params, [Return(body)], {})
  18404. case (TupleType(ts1), TupleType(ts2)):
  18405. x = generate_name('x')
  18406. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18407. for (t1,t2) in zip(ts1,ts2)]
  18408. return ProxiedTuple(value, reads)
  18409. case (ListType(t1), ListType(t2)):
  18410. x = generate_name('x')
  18411. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18412. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  18413. return ProxiedList(value, read, write)
  18414. case (t1, t2) if t1 == t2:
  18415. return value
  18416. case (t1, t2):
  18417. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  18418. def apply_inject(self, value, src):
  18419. return Tagged(value, self.type_to_tag(src))
  18420. def apply_project(self, value, tgt):
  18421. match value:
  18422. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  18423. return val
  18424. case _:
  18425. raise Exception('apply_project, unexpected ' + repr(value))
  18426. \end{lstlisting}
  18427. \fi}
  18428. \end{tcolorbox}
  18429. \caption{The \code{apply\_cast} auxiliary method.}
  18430. \label{fig:apply_cast}
  18431. \end{figure}
  18432. The \LangCast{} interpreter uses an auxiliary function named
  18433. \code{apply\_cast} to cast a value from a source type to a target type,
  18434. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  18435. of the kinds of casts that we've discussed in this section.
  18436. %
  18437. The interpreter for \LangCast{} is defined in
  18438. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  18439. dispatching to \code{apply\_cast}.
  18440. \racket{To handle the addition of tuple
  18441. proxies, we update the tuple primitives in \code{interp-op} using the
  18442. functions in figure~\ref{fig:guarded-tuple}.}
  18443. Next we turn to the individual passes needed for compiling \LangGrad{}.
  18444. \begin{figure}[tbp]
  18445. \begin{tcolorbox}[colback=white]
  18446. {\if\edition\racketEd
  18447. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18448. (define interp-Lcast-class
  18449. (class interp-Llambda-class
  18450. (super-new)
  18451. (inherit apply-fun apply-inject apply-project)
  18452. (define/override (interp-op op)
  18453. (match op
  18454. ['vector-length guarded-vector-length]
  18455. ['vector-ref guarded-vector-ref]
  18456. ['vector-set! guarded-vector-set!]
  18457. ['any-vector-ref (lambda (v i)
  18458. (match v [`(tagged ,v^ ,tg)
  18459. (guarded-vector-ref v^ i)]))]
  18460. ['any-vector-set! (lambda (v i a)
  18461. (match v [`(tagged ,v^ ,tg)
  18462. (guarded-vector-set! v^ i a)]))]
  18463. ['any-vector-length (lambda (v)
  18464. (match v [`(tagged ,v^ ,tg)
  18465. (guarded-vector-length v^)]))]
  18466. [else (super interp-op op)]
  18467. ))
  18468. (define/override ((interp-exp env) e)
  18469. (define (recur e) ((interp-exp env) e))
  18470. (match e
  18471. [(Value v) v]
  18472. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  18473. [else ((super interp-exp env) e)]))
  18474. ))
  18475. (define (interp-Lcast p)
  18476. (send (new interp-Lcast-class) interp-program p))
  18477. \end{lstlisting}
  18478. \fi}
  18479. {\if\edition\pythonEd
  18480. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18481. class InterpLcast(InterpLany):
  18482. def interp_exp(self, e, env):
  18483. match e:
  18484. case Cast(value, src, tgt):
  18485. v = self.interp_exp(value, env)
  18486. return self.apply_cast(v, src, tgt)
  18487. case ValueExp(value):
  18488. return value
  18489. ...
  18490. case _:
  18491. return super().interp_exp(e, env)
  18492. \end{lstlisting}
  18493. \fi}
  18494. \end{tcolorbox}
  18495. \caption{The interpreter for \LangCast{}.}
  18496. \label{fig:interp-Lcast}
  18497. \end{figure}
  18498. {\if\edition\racketEd
  18499. \begin{figure}[tbp]
  18500. \begin{tcolorbox}[colback=white]
  18501. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18502. (define (guarded-vector-ref vec i)
  18503. (match vec
  18504. [`(vector-proxy ,proxy)
  18505. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  18506. (define rd (vector-ref (vector-ref proxy 1) i))
  18507. (apply-fun rd (list val) 'guarded-vector-ref)]
  18508. [else (vector-ref vec i)]))
  18509. (define (guarded-vector-set! vec i arg)
  18510. (match vec
  18511. [`(vector-proxy ,proxy)
  18512. (define wr (vector-ref (vector-ref proxy 2) i))
  18513. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  18514. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  18515. [else (vector-set! vec i arg)]))
  18516. (define (guarded-vector-length vec)
  18517. (match vec
  18518. [`(vector-proxy ,proxy)
  18519. (guarded-vector-length (vector-ref proxy 0))]
  18520. [else (vector-length vec)]))
  18521. \end{lstlisting}
  18522. %% {\if\edition\pythonEd
  18523. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18524. %% UNDER CONSTRUCTION
  18525. %% \end{lstlisting}
  18526. %% \fi}
  18527. \end{tcolorbox}
  18528. \caption{The \code{guarded-vector} auxiliary functions.}
  18529. \label{fig:guarded-tuple}
  18530. \end{figure}
  18531. \fi}
  18532. {\if\edition\pythonEd
  18533. \section{Overload Resolution}
  18534. \label{sec:gradual-resolution}
  18535. Recall that when we added support for arrays in
  18536. section~\ref{sec:arrays}, the syntax for the array operations were the
  18537. same as for tuple operations (e.g., accessing an element, getting the
  18538. length). So we performed overload resolution, with a pass named
  18539. \code{resolve}, to separate the array and tuple operations. In
  18540. particular, we introduced the primitives \code{array\_load},
  18541. \code{array\_store}, and \code{array\_len}.
  18542. For gradual typing, we further overload these operators to work on
  18543. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  18544. updated with new cases for the \CANYTY{} type, translating the element
  18545. access and length operations to the primitives \code{any\_load},
  18546. \code{any\_store}, and \code{any\_len}.
  18547. \section{Cast Insertion}
  18548. \label{sec:gradual-insert-casts}
  18549. In our discussion of type checking of \LangGrad{}, we mentioned how
  18550. the runtime aspect of type checking is carried out by the \code{Cast}
  18551. AST node, which is added to the program by a new pass named
  18552. \code{cast\_insert}. The target of this pass is the \LangCast{}
  18553. language. We now discuss the details of this pass.
  18554. The \code{cast\_insert} pass is closely related to the type checker
  18555. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  18556. In particular, the type checker allows implicit casts between
  18557. consistent types. The job of the \code{cast\_insert} pass is to make
  18558. those casts explicit. It does so by inserting
  18559. \code{Cast} nodes into the AST.
  18560. %
  18561. For the most part, the implicit casts occur in places where the type
  18562. checker checks two types for consistency. Consider the case for
  18563. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  18564. checker requires that the type of the left operand is consistent with
  18565. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  18566. \code{Cast} around the left operand, converting from its type to
  18567. \INTTY{}. The story is similar for the right operand. It is not always
  18568. necessary to insert a cast, e.g., if the left operand already has type
  18569. \INTTY{} then there is no need for a \code{Cast}.
  18570. Some of the implicit casts are not as straightforward. One such case
  18571. arises with the
  18572. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  18573. see that the type checker requires that the two branches have
  18574. consistent types and that type of the conditional expression is the
  18575. join of the branches' types. In the target language \LangCast{}, both
  18576. branches will need to have the same type, and that type
  18577. will be the type of the conditional expression. Thus, each branch requires
  18578. a \code{Cast} to convert from its type to the join type.
  18579. The case for the function call exhibits another interesting situation. If
  18580. the function expression is of type \CANYTY{}, then it needs to be cast
  18581. to a function type so that it can be used in a function call in
  18582. \LangCast{}. Which function type should it be cast to? The parameter
  18583. and return types are unknown, so we can simply use \CANYTY{} for all
  18584. of them. Futhermore, in \LangCast{} the argument types will need to
  18585. exactly match the parameter types, so we must cast all the arguments
  18586. to type \CANYTY{} (if they are not already of that type).
  18587. \fi}
  18588. \section{Lower Casts}
  18589. \label{sec:lower_casts}
  18590. The next step in the journey towards x86 is the \code{lower\_casts}
  18591. pass that translates the casts in \LangCast{} to the lower-level
  18592. \code{Inject} and \code{Project} operators and new operators for
  18593. proxies, extending the \LangLam{} language to \LangProxy{}.
  18594. The \LangProxy{} language can also be described as an extension of
  18595. \LangAny{}, with the addition of proxies. We recommend creating an
  18596. auxiliary function named \code{lower\_cast} that takes an expression
  18597. (in \LangCast{}), a source type, and a target type, and translates it
  18598. to expression in \LangProxy{}.
  18599. The \code{lower\_cast} function can follow a code structure similar to
  18600. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  18601. the interpreter for \LangCast{} because it must handle the same cases
  18602. as \code{apply\_cast} and it needs to mimic the behavior of
  18603. \code{apply\_cast}. The most interesting cases are those concerning
  18604. the casts involving tuple, array, and function types.
  18605. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  18606. type to another array type is accomplished by creating a proxy that
  18607. intercepts the operations on the underlying array. Here we make the
  18608. creation of the proxy explicit with the
  18609. \racket{\code{vectorof-proxy}}\python{\code{ListProxy}} AST node. It
  18610. takes fives arguments, the first is an expression for the array, the
  18611. second is a function for casting an element that is being read from
  18612. the array, the third is a function for casting an element that is
  18613. being written to the array, the fourth is the type of the underlying
  18614. array, and the fifth is the type of the proxied array. You can create
  18615. the functions for reading and writing using lambda expressions.
  18616. A cast between two tuple types can be handled in a similar manner.
  18617. We create a proxy with the
  18618. \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST node.
  18619. \python{Tuples are immutable, so there is no
  18620. need for a function to cast the value during a write.}
  18621. Because there is a separate element type for each slot in the tuple,
  18622. we need not just one function for casting during a read, but instead a tuple
  18623. of functions.
  18624. %
  18625. Also, as we shall see in the next section, we need to differentiate
  18626. these tuples from the user-created ones, so we recommend using a new
  18627. AST node named \racket{\code{raw-vector}}\python{\code{RawTuple}}
  18628. instead of \racket{\code{vector}}\python{\code{Tuple}} to create the
  18629. tuples of functions.
  18630. %
  18631. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  18632. \code{lower\_casts} on the example in figure~\ref{fig:map-bang} that
  18633. involved casting an array of integers to an array of \CANYTY{}.
  18634. \begin{figure}[tbp]
  18635. \begin{tcolorbox}[colback=white]
  18636. {\if\edition\racketEd
  18637. \begin{lstlisting}
  18638. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  18639. (begin
  18640. (vector-set! v 0 (f (vector-ref v 0)))
  18641. (vector-set! v 1 (f (vector-ref v 1)))))
  18642. (define (inc [x : Any]) : Any
  18643. (inject (+ (project x Integer) 1) Integer))
  18644. (let ([v (vector 0 41)])
  18645. (begin
  18646. (map_inplace inc (vector-proxy v
  18647. (raw-vector (lambda: ([x9 : Integer]) : Any
  18648. (inject x9 Integer))
  18649. (lambda: ([x9 : Integer]) : Any
  18650. (inject x9 Integer)))
  18651. (raw-vector (lambda: ([x9 : Any]) : Integer
  18652. (project x9 Integer))
  18653. (lambda: ([x9 : Any]) : Integer
  18654. (project x9 Integer)))))
  18655. (vector-ref v 1)))
  18656. \end{lstlisting}
  18657. \fi}
  18658. {\if\edition\pythonEd
  18659. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18660. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  18661. i = 0
  18662. while i != array_len(v):
  18663. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  18664. i = (i + 1)
  18665. def inc(x : int) -> int:
  18666. return (x + 1)
  18667. def main() -> int:
  18668. v = [0, 41]
  18669. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  18670. print(array_load(v, 1))
  18671. return 0
  18672. \end{lstlisting}
  18673. \fi}
  18674. \end{tcolorbox}
  18675. \caption{Output of \code{lower\_casts} on the example in
  18676. figure~\ref{fig:map-bang}.}
  18677. \label{fig:map-bang-lower-cast}
  18678. \end{figure}
  18679. A cast from one function type to another function type is accomplished
  18680. by generating a \code{lambda} whose parameter and return types match
  18681. the target function type. The body of the \code{lambda} should cast
  18682. the parameters from the target type to the source type. (Yes,
  18683. backwards! Functions are contravariant\index{subject}{contravariant}
  18684. in the parameters.). Afterwards, call the underlying function and then
  18685. cast the result from the source return type to the target return type.
  18686. Figure~\ref{fig:map-lower-cast} shows the output of the
  18687. \code{lower\_casts} pass on the \code{map} example in
  18688. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  18689. call to \code{map} is wrapped in a \code{lambda}.
  18690. \begin{figure}[tbp]
  18691. \begin{tcolorbox}[colback=white]
  18692. {\if\edition\racketEd
  18693. \begin{lstlisting}
  18694. (define (map [f : (Integer -> Integer)]
  18695. [v : (Vector Integer Integer)])
  18696. : (Vector Integer Integer)
  18697. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18698. (define (inc [x : Any]) : Any
  18699. (inject (+ (project x Integer) 1) Integer))
  18700. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  18701. (project (inc (inject x9 Integer)) Integer))
  18702. (vector 0 41)) 1)
  18703. \end{lstlisting}
  18704. \fi}
  18705. {\if\edition\pythonEd
  18706. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18707. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18708. return (f(v[0]), f(v[1]),)
  18709. def inc(x : any) -> any:
  18710. return inject((project(x, int) + 1), int)
  18711. def main() -> int:
  18712. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  18713. print(t[1])
  18714. return 0
  18715. \end{lstlisting}
  18716. \fi}
  18717. \end{tcolorbox}
  18718. \caption{Output of \code{lower\_casts} on the example in
  18719. figure~\ref{fig:gradual-map}.}
  18720. \label{fig:map-lower-cast}
  18721. \end{figure}
  18722. \section{Differentiate Proxies}
  18723. \label{sec:differentiate-proxies}
  18724. So far the responsibility of differentiating tuples and tuple proxies
  18725. has been the job of the interpreter.
  18726. %
  18727. \racket{For example, the interpreter for \LangCast{} implements
  18728. \code{vector-ref} using the \code{guarded-vector-ref} function in
  18729. figure~\ref{fig:guarded-tuple}.}
  18730. %
  18731. In the \code{differentiate\_proxies} pass we shift this responsibility
  18732. to the generated code.
  18733. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  18734. we used the type \TUPLETYPENAME{} for both
  18735. real tuples and tuple proxies.
  18736. \python{Similarly, we use the type \code{list} for both arrays and
  18737. array proxies.}
  18738. In \LangPVec{} we return the
  18739. \TUPLETYPENAME{} type to its original
  18740. meaning, as the type of just tuples, and we introduce a new type,
  18741. \PTUPLETYNAME{}, whose values
  18742. can be either real tuples or tuple
  18743. proxies.
  18744. Likewise, we return the
  18745. \ARRAYTYPENAME{} type to its original
  18746. meaning, as the type of arrays, and we introduce a new type,
  18747. \PARRAYTYNAME{}, whose values
  18748. can be either arrays or array proxies.
  18749. These new types come with a suite of new primitive operations.
  18750. {\if\edition\racketEd
  18751. A tuple proxy is represented by a tuple containing three things: 1) the
  18752. underlying tuple, 2) a tuple of functions for casting elements that
  18753. are read from the tuple, and 3) a tuple of functions for casting
  18754. values to be written to the tuple. So we define the following
  18755. abbreviation for the type of a tuple proxy:
  18756. \[
  18757. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  18758. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  18759. \]
  18760. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  18761. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  18762. %
  18763. Next we describe each of the new primitive operations.
  18764. \begin{description}
  18765. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  18766. (\key{PVector} $T \ldots$)]\ \\
  18767. %
  18768. This operation brands a vector as a value of the \code{PVector} type.
  18769. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  18770. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  18771. %
  18772. This operation brands a vector proxy as value of the \code{PVector} type.
  18773. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  18774. \BOOLTY{}] \ \\
  18775. %
  18776. This returns true if the value is a tuple proxy and false if it is a
  18777. real tuple.
  18778. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  18779. (\key{Vector} $T \ldots$)]\ \\
  18780. %
  18781. Assuming that the input is a tuple, this operation returns the
  18782. tuple.
  18783. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  18784. $\to$ \BOOLTY{}]\ \\
  18785. %
  18786. Given a tuple proxy, this operation returns the length of the tuple.
  18787. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  18788. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  18789. %
  18790. Given a tuple proxy, this operation returns the $i$th element of the
  18791. tuple.
  18792. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  18793. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  18794. Given a tuple proxy, this operation writes a value to the $i$th element
  18795. of the tuple.
  18796. \end{description}
  18797. \fi}
  18798. {\if\edition\pythonEd
  18799. %
  18800. A tuple proxy is represented by a tuple containing 1) the underlying
  18801. tuple and 2) a tuple of functions for casting elements that are read
  18802. from the tuple. The \LangPVec{} language includes the following AST
  18803. classes and primitive functions.
  18804. \begin{description}
  18805. \item[\code{InjectTuple}] \ \\
  18806. %
  18807. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  18808. \item[\code{InjectTupleProxy}]\ \\
  18809. %
  18810. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  18811. \item[\code{is\_tuple\_proxy}]\ \\
  18812. %
  18813. This primitive returns true if the value is a tuple proxy and false
  18814. if it is a tuple.
  18815. \item[\code{project\_tuple}]\ \\
  18816. %
  18817. Converts a tuple that is branded as \PTUPLETYNAME{}
  18818. back to a tuple.
  18819. \item[\code{proxy\_tuple\_len}]\ \\
  18820. %
  18821. Given a tuple proxy, returns the length of the underlying tuple.
  18822. \item[\code{proxy\_tuple\_load}]\ \\
  18823. %
  18824. Given a tuple proxy, returns the $i$th element of the underlying
  18825. tuple.
  18826. \end{description}
  18827. An array proxy is represented by a tuple containing 1) the underlying
  18828. array, 2) a function for casting elements that are read from the
  18829. array, and 3) a function for casting elements that are written to the
  18830. array. The \LangPVec{} language includes the following AST classes
  18831. and primitive functions.
  18832. \begin{description}
  18833. \item[\code{InjectList}]\ \\
  18834. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  18835. \item[\code{InjectListProxy}]\ \\
  18836. %
  18837. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  18838. \item[\code{is\_array\_proxy}]\ \\
  18839. %
  18840. Returns true if the value is a array proxy and false if it is an
  18841. array.
  18842. \item[\code{project\_array}]\ \\
  18843. %
  18844. Converts an array that is branded as \PARRAYTYNAME{} back to an
  18845. array.
  18846. \item[\code{proxy\_array\_len}]\ \\
  18847. %
  18848. Given a array proxy, returns the length of the underlying array.
  18849. \item[\code{proxy\_array\_load}]\ \\
  18850. %
  18851. Given a array proxy, returns the $i$th element of the underlying
  18852. array.
  18853. \item[\code{proxy\_array\_store}]\ \\
  18854. %
  18855. Given an array proxy, writes a value to the $i$th element of the
  18856. underlying array.
  18857. \end{description}
  18858. \fi}
  18859. Now we discuss the translation that differentiates tuples and arrays
  18860. from proxies. First, every type annotation in the program is
  18861. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  18862. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  18863. places. For example, we wrap every tuple creation with an
  18864. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  18865. {\if\edition\racketEd
  18866. \begin{lstlisting}
  18867. (vector |$e_1 \ldots e_n$|)
  18868. |$\Rightarrow$|
  18869. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  18870. \end{lstlisting}
  18871. \fi}
  18872. {\if\edition\pythonEd
  18873. \begin{lstlisting}
  18874. Tuple(|$e_1, \ldots, e_n$|)
  18875. |$\Rightarrow$|
  18876. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  18877. \end{lstlisting}
  18878. \fi}
  18879. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  18880. AST node that we introduced in the previous
  18881. section does not get injected.
  18882. {\if\edition\racketEd
  18883. \begin{lstlisting}
  18884. (raw-vector |$e_1 \ldots e_n$|)
  18885. |$\Rightarrow$|
  18886. (vector |$e'_1 \ldots e'_n$|)
  18887. \end{lstlisting}
  18888. \fi}
  18889. {\if\edition\pythonEd
  18890. \begin{lstlisting}
  18891. RawTuple(|$e_1, \ldots, e_n$|)
  18892. |$\Rightarrow$|
  18893. Tuple(|$e'_1, \ldots, e'_n$|)
  18894. \end{lstlisting}
  18895. \fi}
  18896. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST translates as follows.
  18897. {\if\edition\racketEd
  18898. \begin{lstlisting}
  18899. (vector-proxy |$e_1~e_2~e_3$|)
  18900. |$\Rightarrow$|
  18901. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  18902. \end{lstlisting}
  18903. \fi}
  18904. {\if\edition\pythonEd
  18905. \begin{lstlisting}
  18906. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  18907. |$\Rightarrow$|
  18908. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  18909. \end{lstlisting}
  18910. \fi}
  18911. We translate the element access operations into conditional
  18912. expressions that check whether the value is a proxy and then dispatch
  18913. to either the appropriate proxy tuple operation or the regular tuple
  18914. operation.
  18915. {\if\edition\racketEd
  18916. \begin{lstlisting}
  18917. (vector-ref |$e_1$| |$i$|)
  18918. |$\Rightarrow$|
  18919. (let ([|$v~e_1$|])
  18920. (if (proxy? |$v$|)
  18921. (proxy-vector-ref |$v$| |$i$|)
  18922. (vector-ref (project-vector |$v$|) |$i$|)
  18923. \end{lstlisting}
  18924. \fi}
  18925. %
  18926. Note that in the branch for a tuple, we must apply
  18927. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  18928. from the tuple.
  18929. The translation of array operations is similar to the ones for tuples.
  18930. \section{Reveal Casts}
  18931. \label{sec:reveal-casts-gradual}
  18932. {\if\edition\racketEd
  18933. Recall that the \code{reveal\_casts} pass
  18934. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  18935. \code{Inject} and \code{Project} into lower-level operations.
  18936. %
  18937. In particular, \code{Project} turns into a conditional expression that
  18938. inspects the tag and retrieves the underlying value. Here we need to
  18939. augment the translation of \code{Project} to handle the situation when
  18940. the target type is \code{PVector}. Instead of using
  18941. \code{vector-length} we need to use \code{proxy-vector-length}.
  18942. \begin{lstlisting}
  18943. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  18944. |$\Rightarrow$|
  18945. (let |$\itm{tmp}$| |$e'$|
  18946. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  18947. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  18948. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  18949. (exit)))
  18950. \end{lstlisting}
  18951. \fi}
  18952. %
  18953. {\if\edition\pythonEd
  18954. Recall that the $\itm{tagof}$ function determines the bits used to
  18955. identify values of different types and it is used in the \code{reveal\_casts}
  18956. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  18957. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  18958. decimal), just like the tuple and array types.
  18959. \fi}
  18960. %
  18961. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  18962. \section{Closure Conversion}
  18963. \label{sec:closure-conversion-gradual}
  18964. The auxiliary function that translates type annotations needs to be
  18965. updated to handle the \PTUPLETYNAME{} and \PARRAYTYNAME{} types.
  18966. %
  18967. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  18968. \section{Select Instructions}
  18969. \label{sec:select-instructions-gradual}
  18970. Recall that the \code{select\_instructions} pass is responsible for
  18971. lowering the primitive operations into x86 instructions. So we need
  18972. to translate the new operations on \PTUPLETYNAME{} and \PARRAYTYNAME{}
  18973. to x86. To do so, the first question we need to answer is how to
  18974. differentiate between tuple and tuples proxies, and likewise for
  18975. arrays and array proxies. We need just one bit to accomplish this,
  18976. and use the bit in position $63$ of the 64-bit tag at the front of
  18977. every tuple (see figure~\ref{fig:tuple-rep}) or array
  18978. (section~\ref{sec:array-rep}). So far, this bit has been set to $0$,
  18979. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  18980. it that way.
  18981. {\if\edition\racketEd
  18982. \begin{lstlisting}
  18983. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  18984. |$\Rightarrow$|
  18985. movq |$e'_1$|, |$\itm{lhs'}$|
  18986. \end{lstlisting}
  18987. \fi}
  18988. {\if\edition\pythonEd
  18989. \begin{lstlisting}
  18990. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  18991. |$\Rightarrow$|
  18992. movq |$e'_1$|, |$\itm{lhs'}$|
  18993. \end{lstlisting}
  18994. \fi}
  18995. \python{The translation for \code{InjectList} is also a move instruction.}
  18996. \noindent On the other hand,
  18997. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  18998. $63$ to $1$.
  18999. %
  19000. {\if\edition\racketEd
  19001. \begin{lstlisting}
  19002. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  19003. |$\Rightarrow$|
  19004. movq |$e'_1$|, %r11
  19005. movq |$(1 << 63)$|, %rax
  19006. orq 0(%r11), %rax
  19007. movq %rax, 0(%r11)
  19008. movq %r11, |$\itm{lhs'}$|
  19009. \end{lstlisting}
  19010. \fi}
  19011. {\if\edition\pythonEd
  19012. \begin{lstlisting}
  19013. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  19014. |$\Rightarrow$|
  19015. movq |$e'_1$|, %r11
  19016. movq |$(1 << 63)$|, %rax
  19017. orq 0(%r11), %rax
  19018. movq %rax, 0(%r11)
  19019. movq %r11, |$\itm{lhs'}$|
  19020. \end{lstlisting}
  19021. \fi}
  19022. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19023. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19024. The \racket{\code{proxy?} operation consumes}
  19025. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations consume}
  19026. the information so carefully
  19027. stashed away by the injections. It
  19028. isolates the $63$rd bit to tell whether the value is a tuple/array or
  19029. a proxy.
  19030. %
  19031. {\if\edition\racketEd
  19032. \begin{lstlisting}
  19033. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19034. |$\Rightarrow$|
  19035. movq |$e_1'$|, %r11
  19036. movq 0(%r11), %rax
  19037. sarq $63, %rax
  19038. andq $1, %rax
  19039. movq %rax, |$\itm{lhs'}$|
  19040. \end{lstlisting}
  19041. \fi}%
  19042. %
  19043. {\if\edition\pythonEd
  19044. \begin{lstlisting}
  19045. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19046. |$\Rightarrow$|
  19047. movq |$e_1'$|, %r11
  19048. movq 0(%r11), %rax
  19049. sarq $63, %rax
  19050. andq $1, %rax
  19051. movq %rax, |$\itm{lhs'}$|
  19052. \end{lstlisting}
  19053. \fi}%
  19054. %
  19055. The \racket{\code{project-vector} operation is}
  19056. \python{\code{project\_tuple} and \code{project\_array} operations are}
  19057. straightforward to translate, so we leave that to the reader.
  19058. Regarding the element access operations for tuples and arrays, the
  19059. runtime provides procedures that implement them (they are recursive
  19060. functions!) so here we simply need to translate these tuple
  19061. operations into the appropriate function call. For example, here is
  19062. the translation for
  19063. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  19064. {\if\edition\racketEd
  19065. \begin{lstlisting}
  19066. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  19067. |$\Rightarrow$|
  19068. movq |$e_1'$|, %rdi
  19069. movq |$e_2'$|, %rsi
  19070. callq proxy_vector_ref
  19071. movq %rax, |$\itm{lhs'}$|
  19072. \end{lstlisting}
  19073. \fi}
  19074. {\if\edition\pythonEd
  19075. \begin{lstlisting}
  19076. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  19077. |$\Rightarrow$|
  19078. movq |$e_1'$|, %rdi
  19079. movq |$e_2'$|, %rsi
  19080. callq proxy_vector_ref
  19081. movq %rax, |$\itm{lhs'}$|
  19082. \end{lstlisting}
  19083. \fi}
  19084. We translate
  19085. \racket{\code{proxy-vectof-ref}}\python{\code{proxy\_array\_load}}
  19086. to \code{proxy\_vecof\_ref},
  19087. \racket{\code{proxy-vectof-set!}}\python{\code{proxy\_array\_store}}
  19088. to \code{proxy\_vecof\_set}, and
  19089. \racket{\code{proxy-vectof-length}}\python{\code{proxy\_array\_len}}
  19090. to \code{proxy\_vecof\_length}.
  19091. We have another batch of operations to deal with, those for the
  19092. \CANYTY{} type. Recall that overload resolution
  19093. (section~\ref{sec:gradual-resolution}) generates an
  19094. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  19095. there is a element access on something of type \CANYTY{}, and
  19096. similarly for
  19097. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  19098. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  19099. section~\ref{sec:select-Lany} we selected instructions for these
  19100. operations based on the idea that the underlying value was a tuple or
  19101. array. But in the current setting, the underlying value is of type
  19102. \PTUPLETYNAME{} or \PARRAYTYNAME{}. We have added two runtime
  19103. functions to deal with this: \code{proxy\_vec\_ref},
  19104. \code{proxy\_vec\_set}, and
  19105. \code{proxy\_vec\_length}, that inspect bit $62$ of the tag
  19106. to determine whether the value is a tuple or array, and then
  19107. dispatches to the the appropriate function for
  19108. tuples (e.g. \code{proxy\_vector\_ref}) or arrays
  19109. (e.g. \code{proxy\_vecof\_ref}).
  19110. %
  19111. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  19112. can be translated follows.
  19113. We begin by projecting the underlying value out of the tagged value and
  19114. then call the \code{proxy\_vec\_ref} procedure in the runtime.
  19115. {\if\edition\racketEd
  19116. \begin{lstlisting}
  19117. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  19118. |$\Rightarrow$|
  19119. movq |$\neg 111$|, %rdi
  19120. andq |$e_1'$|, %rdi
  19121. movq |$e_2'$|, %rsi
  19122. callq proxy_vec_ref
  19123. movq %rax, |$\itm{lhs'}$|
  19124. \end{lstlisting}
  19125. \fi}
  19126. {\if\edition\pythonEd
  19127. \begin{lstlisting}
  19128. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  19129. |$\Rightarrow$|
  19130. movq |$\neg 111$|, %rdi
  19131. andq |$e_1'$|, %rdi
  19132. movq |$e_2'$|, %rsi
  19133. callq proxy_vec_ref
  19134. movq %rax, |$\itm{lhs'}$|
  19135. \end{lstlisting}
  19136. \fi}
  19137. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  19138. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  19139. are translated in a similar way. Alternatively, you could generate
  19140. instructions to open-code
  19141. the \code{proxy\_vec\_ref}, \code{proxy\_vec\_set},
  19142. and \code{proxy\_vec\_length} functions.
  19143. \begin{exercise}\normalfont\normalsize
  19144. Implement a compiler for the gradually-typed \LangGrad{} language by
  19145. extending and adapting your compiler for \LangLam{}. Create 10 new
  19146. partially-typed test programs. In addition to testing with these
  19147. new programs, also test your compiler on all the tests for \LangLam{}
  19148. and for \LangDyn{}.
  19149. %
  19150. \racket{Sometimes you may get a type checking error on the
  19151. \LangDyn{} programs but you can adapt them by inserting a cast to
  19152. the \CANYTY{} type around each subexpression causing a type
  19153. error. While \LangDyn{} does not have explicit casts, you can
  19154. induce one by wrapping the subexpression \code{e} with a call to
  19155. an un-annotated identity function, like this: \code{((lambda (x) x) e)}.}
  19156. %
  19157. \python{Sometimes you may get a type checking error on the
  19158. \LangDyn{} programs but you can adapt them by inserting a
  19159. temporary variable of type \CANYTY{} that is initialized with the
  19160. troublesome expression.}
  19161. \end{exercise}
  19162. \begin{figure}[p]
  19163. \begin{tcolorbox}[colback=white]
  19164. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  19165. \node (Lgradual) at (12,4) {\large \LangGrad{}};
  19166. \node (Lgradual2) at (9,4) {\large \LangGrad{}};
  19167. \node (Lgradual3) at (6,4) {\large \LangCast{}};
  19168. \node (Lgradual4) at (3,4) {\large \LangProxy{}};
  19169. \node (Lgradualr) at (0,4) {\large \LangPVec{}};
  19170. \node (Lgradualp) at (0,2) {\large \LangPVec{}};
  19171. \node (Llambdapp) at (3,2) {\large \LangPVec{}};
  19172. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  19173. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  19174. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  19175. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  19176. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  19177. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  19178. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  19179. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  19180. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  19181. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  19182. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  19183. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  19184. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  19185. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  19186. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  19187. \path[->,bend right=15] (Lgradual) edge [above] node
  19188. {\ttfamily\footnotesize shrink} (Lgradual2);
  19189. \path[->,bend right=15] (Lgradual2) edge [above] node
  19190. {\ttfamily\footnotesize uniquify} (Lgradual3);
  19191. \path[->,bend right=15] (Lgradual3) edge [above] node
  19192. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  19193. \path[->,bend right=15] (Lgradual4) edge [above] node
  19194. {\ttfamily\footnotesize resolve} (Lgradualr);
  19195. \path[->,bend right=15] (Lgradualr) edge [right] node
  19196. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  19197. \path[->,bend right=15] (Lgradualp) edge [below] node
  19198. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  19199. \path[->,bend left=15] (Llambdapp) edge [above] node
  19200. {\ttfamily\footnotesize differentiate.} (Llambdaproxy-4);
  19201. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  19202. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  19203. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  19204. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  19205. \path[->,bend left=15] (F1-1) edge [left] node
  19206. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  19207. \path[->,bend left=15] (F1-2) edge [below] node
  19208. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  19209. \path[->,bend right=15] (F1-3) edge [above] node
  19210. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  19211. \path[->,bend right=15] (F1-4) edge [above] node
  19212. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  19213. \path[->,bend right=15] (F1-5) edge [above] node
  19214. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  19215. \path[->,bend right=15] (F1-6) edge [right] node
  19216. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19217. \path[->,bend left=15] (C3-2) edge [left] node
  19218. {\ttfamily\footnotesize select\_instr.} (x86-2);
  19219. \path[->,bend right=15] (x86-2) edge [left] node
  19220. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  19221. \path[->,bend right=15] (x86-2-1) edge [below] node
  19222. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  19223. \path[->,bend right=15] (x86-2-2) edge [left] node
  19224. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  19225. \path[->,bend left=15] (x86-3) edge [above] node
  19226. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  19227. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  19228. \end{tikzpicture}
  19229. \end{tcolorbox}
  19230. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  19231. \label{fig:Lgradual-passes}
  19232. \end{figure}
  19233. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  19234. needed for the compilation of \LangGrad{}.
  19235. \section{Further Reading}
  19236. This chapter just scratches the surface of gradual typing. The basic
  19237. approach described here is missing two key ingredients that one would
  19238. want in a implementation of gradual typing: blame
  19239. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  19240. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  19241. problem addressed by blame tracking is that when a cast on a
  19242. higher-order value fails, it often does so at a point in the program
  19243. that is far removed from the original cast. Blame tracking is a
  19244. technique for propagating extra information through casts and proxies
  19245. so that when a cast fails, the error message can point back to the
  19246. original location of the cast in the source program.
  19247. The problem addressed by space-efficient casts also relates to
  19248. higher-order casts. It turns out that in partially typed programs, a
  19249. function or tuple can flow through very many casts at runtime. With
  19250. the approach described in this chapter, each cast adds another
  19251. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  19252. considerable space, but it also makes the function calls and tuple
  19253. operations slow. For example, a partially-typed version of quicksort
  19254. could, in the worst case, build a chain of proxies of length $O(n)$
  19255. around the tuple, changing the overall time complexity of the
  19256. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  19257. solution to this problem by representing casts using the coercion
  19258. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  19259. long chains of proxies by compressing them into a concise normal
  19260. form. \citet{Siek:2015ab} give an algorithm for compressing coercions
  19261. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  19262. the Grift compiler.
  19263. \begin{center}
  19264. \url{https://github.com/Gradual-Typing/Grift}
  19265. \end{center}
  19266. There are also interesting interactions between gradual typing and
  19267. other language features, such as generics, information-flow types, and
  19268. type inference, to name a few. We recommend the reader to consult the
  19269. online gradual typing bibliography for more material:
  19270. \begin{center}
  19271. \url{http://samth.github.io/gradual-typing-bib/}
  19272. \end{center}
  19273. % TODO: challenge problem:
  19274. % type analysis and type specialization?
  19275. % coercions?
  19276. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  19277. \chapter{Generics}
  19278. \label{ch:Lpoly}
  19279. \index{subject}{parametric polymorphism}
  19280. \index{subject}{generics}
  19281. \setcounter{footnote}{0}
  19282. This chapter studies the compilation of
  19283. generics\index{subject}{generics} (aka. parametric
  19284. polymorphism\index{subject}{parametric polymorphism}), compiling the
  19285. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  19286. enable programmers to make code more reusable by parameterizing
  19287. functions and data structures with respect to the types that they
  19288. operate on. For example, figure~\ref{fig:map-poly} revisits the
  19289. \code{map} example but this time gives it a more fitting type. This
  19290. \code{map} function is parameterized with respect to the element type
  19291. of the tuple. The type of \code{map} is the following generic type
  19292. specified by the \code{All} type with parameter \code{T}.
  19293. \if\edition\racketEd
  19294. \begin{lstlisting}
  19295. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  19296. \end{lstlisting}
  19297. \fi
  19298. \if\edition\pythonEd
  19299. \begin{lstlisting}
  19300. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  19301. \end{lstlisting}
  19302. \fi
  19303. %
  19304. The idea is that \code{map} can be used at \emph{all} choices of a
  19305. type for parameter \code{T}. In figure~\ref{fig:map-poly} we apply
  19306. \code{map} to a tuple of integers, implicitly choosing
  19307. \racket{\code{Integer}}\python{\code{int}} for \code{T}, but we could
  19308. have just as well applied \code{map} to a tuple of Booleans.
  19309. %
  19310. A \emph{monomorphic} function is simply one that is not generic.
  19311. %
  19312. We use the term \emph{instantiation} for the process (within the
  19313. language implementation) of turning a generic function into a
  19314. monomorphic one, where the type parameters have been replaced by
  19315. types.
  19316. \if\edition\pythonEd
  19317. %
  19318. In Python, when writing a generic function such as \code{map}, one
  19319. does not explicitly write down its generic type (using \code{All}).
  19320. Instead, the fact that it is generic is implied by the use of type
  19321. variables (such as \code{T}) in the type annotations of its
  19322. parameters.
  19323. %
  19324. \fi
  19325. \begin{figure}[tbp]
  19326. % poly_test_2.rkt
  19327. \begin{tcolorbox}[colback=white]
  19328. \if\edition\racketEd
  19329. \begin{lstlisting}
  19330. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  19331. (define (map f v)
  19332. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19333. (define (inc [x : Integer]) : Integer (+ x 1))
  19334. (vector-ref (map inc (vector 0 41)) 1)
  19335. \end{lstlisting}
  19336. \fi
  19337. \if\edition\pythonEd
  19338. \begin{lstlisting}
  19339. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  19340. return (f(tup[0]), f(tup[1]))
  19341. def add1(x : int) -> int:
  19342. return x + 1
  19343. t = map(add1, (0, 41))
  19344. print(t[1])
  19345. \end{lstlisting}
  19346. \fi
  19347. \end{tcolorbox}
  19348. \caption{A generic version of hte \code{map} function.}
  19349. \label{fig:map-poly}
  19350. \end{figure}
  19351. Figure~\ref{fig:Lpoly-concrete-syntax} defines the concrete syntax of
  19352. \LangPoly{} and figure~\ref{fig:Lpoly-syntax} defines the abstract
  19353. syntax.
  19354. %
  19355. \if\edition\racketEd
  19356. We add a second form for function definitions in which a type
  19357. declaration comes before the \code{define}. In the abstract syntax,
  19358. the return type in the \code{Def} is \CANYTY{}, but that should be
  19359. ignored in favor of the return type in the type declaration. (The
  19360. \CANYTY{} comes from using the same parser as in
  19361. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  19362. enables the use of an \code{All} type for a function, thereby making
  19363. it generic.
  19364. \fi
  19365. %
  19366. The grammar for types is extended to include the type of a generic
  19367. (\code{All}) and type variables\python{ (\code{GenericVar} in the
  19368. abstract syntax)}.
  19369. \newcommand{\LpolyGrammarRacket}{
  19370. \begin{array}{lcl}
  19371. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19372. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  19373. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  19374. \end{array}
  19375. }
  19376. \newcommand{\LpolyASTRacket}{
  19377. \begin{array}{lcl}
  19378. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19379. \Def &::=& \DECL{\Var}{\Type} \\
  19380. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  19381. \end{array}
  19382. }
  19383. \newcommand{\LpolyGrammarPython}{
  19384. \begin{array}{lcl}
  19385. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  19386. \end{array}
  19387. }
  19388. \newcommand{\LpolyASTPython}{
  19389. \begin{array}{lcl}
  19390. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  19391. \MID \key{GenericVar}\LP\Var\RP
  19392. \end{array}
  19393. }
  19394. \begin{figure}[tp]
  19395. \centering
  19396. \begin{tcolorbox}[colback=white]
  19397. \footnotesize
  19398. \if\edition\racketEd
  19399. \[
  19400. \begin{array}{l}
  19401. \gray{\LintGrammarRacket{}} \\ \hline
  19402. \gray{\LvarGrammarRacket{}} \\ \hline
  19403. \gray{\LifGrammarRacket{}} \\ \hline
  19404. \gray{\LwhileGrammarRacket} \\ \hline
  19405. \gray{\LtupGrammarRacket} \\ \hline
  19406. \gray{\LfunGrammarRacket} \\ \hline
  19407. \gray{\LlambdaGrammarRacket} \\ \hline
  19408. \LpolyGrammarRacket \\
  19409. \begin{array}{lcl}
  19410. \LangPoly{} &::=& \Def \ldots ~ \Exp
  19411. \end{array}
  19412. \end{array}
  19413. \]
  19414. \fi
  19415. \if\edition\pythonEd
  19416. \[
  19417. \begin{array}{l}
  19418. \gray{\LintGrammarPython{}} \\ \hline
  19419. \gray{\LvarGrammarPython{}} \\ \hline
  19420. \gray{\LifGrammarPython{}} \\ \hline
  19421. \gray{\LwhileGrammarPython} \\ \hline
  19422. \gray{\LtupGrammarPython} \\ \hline
  19423. \gray{\LfunGrammarPython} \\ \hline
  19424. \gray{\LlambdaGrammarPython} \\\hline
  19425. \LpolyGrammarPython \\
  19426. \begin{array}{lcl}
  19427. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  19428. \end{array}
  19429. \end{array}
  19430. \]
  19431. \fi
  19432. \end{tcolorbox}
  19433. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  19434. (figure~\ref{fig:Llam-concrete-syntax}).}
  19435. \label{fig:Lpoly-concrete-syntax}
  19436. \end{figure}
  19437. \begin{figure}[tp]
  19438. \centering
  19439. \begin{tcolorbox}[colback=white]
  19440. \footnotesize
  19441. \if\edition\racketEd
  19442. \[
  19443. \begin{array}{l}
  19444. \gray{\LintOpAST} \\ \hline
  19445. \gray{\LvarASTRacket{}} \\ \hline
  19446. \gray{\LifASTRacket{}} \\ \hline
  19447. \gray{\LwhileASTRacket{}} \\ \hline
  19448. \gray{\LtupASTRacket{}} \\ \hline
  19449. \gray{\LfunASTRacket} \\ \hline
  19450. \gray{\LlambdaASTRacket} \\ \hline
  19451. \LpolyASTRacket \\
  19452. \begin{array}{lcl}
  19453. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  19454. \end{array}
  19455. \end{array}
  19456. \]
  19457. \fi
  19458. \if\edition\pythonEd
  19459. \[
  19460. \begin{array}{l}
  19461. \gray{\LintASTPython} \\ \hline
  19462. \gray{\LvarASTPython{}} \\ \hline
  19463. \gray{\LifASTPython{}} \\ \hline
  19464. \gray{\LwhileASTPython{}} \\ \hline
  19465. \gray{\LtupASTPython{}} \\ \hline
  19466. \gray{\LfunASTPython} \\ \hline
  19467. \gray{\LlambdaASTPython} \\ \hline
  19468. \LpolyASTPython \\
  19469. \begin{array}{lcl}
  19470. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  19471. \end{array}
  19472. \end{array}
  19473. \]
  19474. \fi
  19475. \end{tcolorbox}
  19476. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  19477. (figure~\ref{fig:Llam-syntax}).}
  19478. \label{fig:Lpoly-syntax}
  19479. \end{figure}
  19480. By including the \code{All} type in the $\Type$ nonterminal of the
  19481. grammar we choose to make generics first-class, which has interesting
  19482. repercussions on the compiler.\footnote{The Python \code{typing} library does
  19483. not include syntax for the \code{All} type. It is inferred for functions whose
  19484. type annotations contain type variables.} Many languages with generics, such as
  19485. C++~\citep{stroustrup88:_param_types} and Standard
  19486. ML~\citep{Milner:1990fk}, only support second-class generics, so it
  19487. may be helpful to see an example of first-class generics in action. In
  19488. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  19489. whose parameter is a generic function. Indeed, because the grammar for
  19490. $\Type$ includes the \code{All} type, a generic function may also be
  19491. returned from a function or stored inside a tuple. The body of
  19492. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  19493. and also to an integer, which would not be possible if \code{f} were
  19494. not generic.
  19495. \begin{figure}[tbp]
  19496. \begin{tcolorbox}[colback=white]
  19497. \if\edition\racketEd
  19498. \begin{lstlisting}
  19499. (: apply_twice ((All (U) (U -> U)) -> Integer))
  19500. (define (apply_twice f)
  19501. (if (f #t) (f 42) (f 777)))
  19502. (: id (All (T) (T -> T)))
  19503. (define (id x) x)
  19504. (apply_twice id)
  19505. \end{lstlisting}
  19506. \fi
  19507. \if\edition\pythonEd
  19508. \begin{lstlisting}
  19509. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  19510. if f(True):
  19511. return f(42)
  19512. else:
  19513. return f(777)
  19514. def id(x: T) -> T:
  19515. return x
  19516. print(apply_twice(id))
  19517. \end{lstlisting}
  19518. \fi
  19519. \end{tcolorbox}
  19520. \caption{An example illustrating first-class generics.}
  19521. \label{fig:apply-twice}
  19522. \end{figure}
  19523. The type checker for \LangPoly{} in figure~\ref{fig:type-check-Lpoly}
  19524. has several new responsibilities (compared to \LangLam{}) which we
  19525. discuss in the following paragraphs.
  19526. \if\edition\racketEd
  19527. %
  19528. TODO: function definitions
  19529. %
  19530. \fi
  19531. \if\edition\pythonEd
  19532. %
  19533. Regarding function definitions, if the type annotations on its
  19534. parameters contain generic variables, then the function is generic and
  19535. therefore its type is an \code{All} type wrapped around a function
  19536. type. Otherwise the function is monomorphic and its type is simply
  19537. a function type.
  19538. %
  19539. \fi
  19540. The type checking of function application is extended to handle the
  19541. case where the operator expression is a generic function. In that case
  19542. the type arguments are deduced by matching the type of the parameters
  19543. with the types of the arguments.
  19544. %
  19545. The \code{match\_types} auxiliary function
  19546. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  19547. recursively descending through a parameter type \code{param\_ty} and
  19548. the corresponding argument type \code{arg\_ty}, making sure that they
  19549. are equal except when there is a type parameter in the parameter
  19550. type. Upon encouterning a type parameter for the first time, the
  19551. algorithm deduces an association of the type parameter to the
  19552. corresponding part of the argument type. If it is not the first time
  19553. that the type parameter has been encountered, the algorithm looks up
  19554. its deduced type and makes sure that it is equal to the corresponding
  19555. part of the argument type. The return type of the application is the
  19556. return type of the generic function, but with the type parameters
  19557. replaced by the deduced type arguments, using the
  19558. \code{substitute\_type} auxiliary function, which is also listed in
  19559. figure~\ref{fig:type-check-Lpoly-aux}.
  19560. The type checker extends type equality to handle the \code{All} type.
  19561. This is not quite as simple as for other types, such as function and
  19562. tuple types, because two \code{All} types can be syntactically
  19563. different even though they are equivalent. For example,
  19564. %
  19565. \racket{\code{(All (T) (T -> T))}}
  19566. \python{\code{All[[T], Callable[[T], T]]}}
  19567. is equivalent to
  19568. \racket{\code{(All (U) (U -> U))}}
  19569. \python{\code{All[[U], Callable[[U], U]]}}.
  19570. %
  19571. Two generic types should be considered equal if they differ only in
  19572. the choice of the names of the type parameters. The definition of type
  19573. equality in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  19574. parameters in one type to match the type parameters of the other type.
  19575. \if\edition\racketEd
  19576. %
  19577. The type checker also ensures that only defined type variables appear
  19578. in type annotations. The \code{check\_well\_formed} function defined
  19579. in figure~\ref{fig:well-formed-types} recursively inspects a type,
  19580. making sure that each type variable has been defined.
  19581. %
  19582. \fi
  19583. \begin{figure}[tbp]
  19584. \begin{tcolorbox}[colback=white]
  19585. \if\edition\racketEd
  19586. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19587. (define type-check-poly-class
  19588. (class type-check-Llambda-class
  19589. (super-new)
  19590. (inherit check-type-equal?)
  19591. (define/override (type-check-apply env e1 es)
  19592. (define-values (e^ ty) ((type-check-exp env) e1))
  19593. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  19594. ((type-check-exp env) e)))
  19595. (match ty
  19596. [`(,ty^* ... -> ,rt)
  19597. (for ([arg-ty ty*] [param-ty ty^*])
  19598. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  19599. (values e^ es^ rt)]
  19600. [`(All ,xs (,tys ... -> ,rt))
  19601. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19602. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  19603. (match_types env^^ param-ty arg-ty)))
  19604. (define targs
  19605. (for/list ([x xs])
  19606. (match (dict-ref env^^ x (lambda () #f))
  19607. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  19608. x (Apply e1 es))]
  19609. [ty ty])))
  19610. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  19611. [else (error 'type-check "expected a function, not ~a" ty)]))
  19612. (define/override ((type-check-exp env) e)
  19613. (match e
  19614. [(Lambda `([,xs : ,Ts] ...) rT body)
  19615. (for ([T Ts]) ((check_well_formed env) T))
  19616. ((check_well_formed env) rT)
  19617. ((super type-check-exp env) e)]
  19618. [(HasType e1 ty)
  19619. ((check_well_formed env) ty)
  19620. ((super type-check-exp env) e)]
  19621. [else ((super type-check-exp env) e)]))
  19622. (define/override ((type-check-def env) d)
  19623. (verbose 'type-check "poly/def" d)
  19624. (match d
  19625. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  19626. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  19627. (for ([p ps]) ((check_well_formed ts-env) p))
  19628. ((check_well_formed ts-env) rt)
  19629. (define new-env (append ts-env (map cons xs ps) env))
  19630. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19631. (check-type-equal? ty^ rt body)
  19632. (Generic ts (Def f p:t* rt info body^))]
  19633. [else ((super type-check-def env) d)]))
  19634. (define/override (type-check-program p)
  19635. (match p
  19636. [(Program info body)
  19637. (type-check-program (ProgramDefsExp info '() body))]
  19638. [(ProgramDefsExp info ds body)
  19639. (define ds^ (combine-decls-defs ds))
  19640. (define new-env (for/list ([d ds^])
  19641. (cons (def-name d) (fun-def-type d))))
  19642. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  19643. (define-values (body^ ty) ((type-check-exp new-env) body))
  19644. (check-type-equal? ty 'Integer body)
  19645. (ProgramDefsExp info ds^^ body^)]))
  19646. ))
  19647. \end{lstlisting}
  19648. \fi
  19649. \if\edition\pythonEd
  19650. \begin{lstlisting}[basicstyle=\ttfamily\small]
  19651. def type_check_exp(self, e, env):
  19652. match e:
  19653. case Call(Name(f), args) if f in builtin_functions:
  19654. return super().type_check_exp(e, env)
  19655. case Call(func, args):
  19656. func_t = self.type_check_exp(func, env)
  19657. func.has_type = func_t
  19658. match func_t:
  19659. case AllType(ps, FunctionType(p_tys, rt)):
  19660. for arg in args:
  19661. arg.has_type = self.type_check_exp(arg, env)
  19662. arg_tys = [arg.has_type for arg in args]
  19663. deduced = {}
  19664. for (p, a) in zip(p_tys, arg_tys):
  19665. self.match_types(p, a, deduced, e)
  19666. return self.substitute_type(rt, deduced)
  19667. case _:
  19668. return super().type_check_exp(e, env)
  19669. case _:
  19670. return super().type_check_exp(e, env)
  19671. def type_check(self, p):
  19672. match p:
  19673. case Module(body):
  19674. env = {}
  19675. for s in body:
  19676. match s:
  19677. case FunctionDef(name, params, bod, dl, returns, comment):
  19678. params_t = [t for (x,t) in params]
  19679. ty_params = set()
  19680. for t in params_t:
  19681. ty_params |$\mid$|= self.generic_variables(t)
  19682. ty = FunctionType(params_t, returns)
  19683. if len(ty_params) > 0:
  19684. ty = AllType(list(ty_params), ty)
  19685. env[name] = ty
  19686. self.check_stmts(body, IntType(), env)
  19687. case _:
  19688. raise Exception('type_check: unexpected ' + repr(p))
  19689. \end{lstlisting}
  19690. \fi
  19691. \end{tcolorbox}
  19692. \caption{Type checker for the \LangPoly{} language.}
  19693. \label{fig:type-check-Lpoly}
  19694. \end{figure}
  19695. \begin{figure}[tbp]
  19696. \begin{tcolorbox}[colback=white]
  19697. \if\edition\racketEd
  19698. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19699. (define/override (type-equal? t1 t2)
  19700. (match* (t1 t2)
  19701. [(`(All ,xs ,T1) `(All ,ys ,T2))
  19702. (define env (map cons xs ys))
  19703. (type-equal? (substitute_type env T1) T2)]
  19704. [(other wise)
  19705. (super type-equal? t1 t2)]))
  19706. (define/public (match_types env pt at)
  19707. (match* (pt at)
  19708. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  19709. [('Void 'Void) env] [('Any 'Any) env]
  19710. [(`(Vector ,pts ...) `(Vector ,ats ...))
  19711. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  19712. (match_types env^ pt1 at1))]
  19713. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  19714. (define env^ (match_types env prt art))
  19715. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  19716. (match_types env^^ pt1 at1))]
  19717. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  19718. (define env^ (append (map cons pxs axs) env))
  19719. (match_types env^ pt1 at1)]
  19720. [((? symbol? x) at)
  19721. (match (dict-ref env x (lambda () #f))
  19722. [#f (error 'type-check "undefined type variable ~a" x)]
  19723. ['Type (cons (cons x at) env)]
  19724. [t^ (check-type-equal? at t^ 'matching) env])]
  19725. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  19726. (define/public (substitute_type env pt)
  19727. (match pt
  19728. ['Integer 'Integer] ['Boolean 'Boolean]
  19729. ['Void 'Void] ['Any 'Any]
  19730. [`(Vector ,ts ...)
  19731. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  19732. [`(,ts ... -> ,rt)
  19733. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  19734. [`(All ,xs ,t)
  19735. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  19736. [(? symbol? x) (dict-ref env x)]
  19737. [else (error 'type-check "expected a type not ~a" pt)]))
  19738. (define/public (combine-decls-defs ds)
  19739. (match ds
  19740. ['() '()]
  19741. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  19742. (unless (equal? name f)
  19743. (error 'type-check "name mismatch, ~a != ~a" name f))
  19744. (match type
  19745. [`(All ,xs (,ps ... -> ,rt))
  19746. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19747. (cons (Generic xs (Def name params^ rt info body))
  19748. (combine-decls-defs ds^))]
  19749. [`(,ps ... -> ,rt)
  19750. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19751. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  19752. [else (error 'type-check "expected a function type, not ~a" type) ])]
  19753. [`(,(Def f params rt info body) . ,ds^)
  19754. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  19755. \end{lstlisting}
  19756. \fi
  19757. \if\edition\pythonEd
  19758. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19759. def match_types(self, param_ty, arg_ty, deduced, e):
  19760. match (param_ty, arg_ty):
  19761. case (GenericVar(id), _):
  19762. if id in deduced:
  19763. self.check_type_equal(arg_ty, deduced[id], e)
  19764. else:
  19765. deduced[id] = arg_ty
  19766. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  19767. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  19768. new_arg_ty = self.substitute_type(arg_ty, rename)
  19769. self.match_types(ty, new_arg_ty, deduced, e)
  19770. case (TupleType(ps), TupleType(ts)):
  19771. for (p, a) in zip(ps, ts):
  19772. self.match_types(p, a, deduced, e)
  19773. case (ListType(p), ListType(a)):
  19774. self.match_types(p, a, deduced, e)
  19775. case (FunctionType(pps, prt), FunctionType(aps, art)):
  19776. for (pp, ap) in zip(pps, aps):
  19777. self.match_types(pp, ap, deduced, e)
  19778. self.match_types(prt, art, deduced, e)
  19779. case (IntType(), IntType()):
  19780. pass
  19781. case (BoolType(), BoolType()):
  19782. pass
  19783. case _:
  19784. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  19785. def substitute_type(self, ty, var_map):
  19786. match ty:
  19787. case GenericVar(id):
  19788. return var_map[id]
  19789. case AllType(ps, ty):
  19790. new_map = copy.deepcopy(var_map)
  19791. for p in ps:
  19792. new_map[p] = GenericVar(p)
  19793. return AllType(ps, self.substitute_type(ty, new_map))
  19794. case TupleType(ts):
  19795. return TupleType([self.substitute_type(t, var_map) for t in ts])
  19796. case ListType(ty):
  19797. return ListType(self.substitute_type(ty, var_map))
  19798. case FunctionType(pts, rt):
  19799. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  19800. self.substitute_type(rt, var_map))
  19801. case IntType():
  19802. return IntType()
  19803. case BoolType():
  19804. return BoolType()
  19805. case _:
  19806. raise Exception('substitute_type: unexpected ' + repr(ty))
  19807. def check_type_equal(self, t1, t2, e):
  19808. match (t1, t2):
  19809. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  19810. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  19811. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  19812. case (_, _):
  19813. return super().check_type_equal(t1, t2, e)
  19814. \end{lstlisting}
  19815. \fi
  19816. \end{tcolorbox}
  19817. \caption{Auxiliary functions for type checking \LangPoly{}.}
  19818. \label{fig:type-check-Lpoly-aux}
  19819. \end{figure}
  19820. \if\edition\racketEd
  19821. \begin{figure}[tbp]
  19822. \begin{tcolorbox}[colback=white]
  19823. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  19824. (define/public ((check_well_formed env) ty)
  19825. (match ty
  19826. ['Integer (void)]
  19827. ['Boolean (void)]
  19828. ['Void (void)]
  19829. [(? symbol? a)
  19830. (match (dict-ref env a (lambda () #f))
  19831. ['Type (void)]
  19832. [else (error 'type-check "undefined type variable ~a" a)])]
  19833. [`(Vector ,ts ...)
  19834. (for ([t ts]) ((check_well_formed env) t))]
  19835. [`(,ts ... -> ,t)
  19836. (for ([t ts]) ((check_well_formed env) t))
  19837. ((check_well_formed env) t)]
  19838. [`(All ,xs ,t)
  19839. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19840. ((check_well_formed env^) t)]
  19841. [else (error 'type-check "unrecognized type ~a" ty)]))
  19842. \end{lstlisting}
  19843. \end{tcolorbox}
  19844. \caption{Well-formed types.}
  19845. \label{fig:well-formed-types}
  19846. \end{figure}
  19847. \fi
  19848. % TODO: interpreter for R'_10
  19849. \clearpage
  19850. \section{Compiling Generics}
  19851. \label{sec:compiling-poly}
  19852. Broadly speaking, there are four approaches to compiling generics,
  19853. which we describe below.
  19854. \begin{description}
  19855. \item[Monomorphization] generates a different version of a generic
  19856. function for each set of type arguments that it is used with,
  19857. producing type-specialized code. This approach results in the most
  19858. efficient code but requires whole-program compilation (no separate
  19859. compilation) and may increase code size. Unfortunately,
  19860. monomorphization is incompatible with first-class generics
  19861. because it is not always possible to determine which generic
  19862. functions are used with which type arguments during compilation. (It
  19863. can be done at runtime, with just-in-time compilation.)
  19864. Monomorphization is used to compile C++
  19865. templates~\citep{stroustrup88:_param_types} and generic functions in
  19866. NESL~\citep{Blelloch:1993aa} and ML~\citep{Weeks:2006aa}.
  19867. \item[Uniform representation] generates one version of each generic
  19868. function and requires all values to have a common ``boxed'' format,
  19869. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  19870. generic and monomorphic code is compiled similarly to code in a
  19871. dynamically typed language (like \LangDyn{}), in which primitive
  19872. operators require their arguments to be projected from \CANYTY{} and
  19873. their results are injected into \CANYTY{}. (In object-oriented
  19874. languages, the projection is accomplished via virtual method
  19875. dispatch.) The uniform representation approach is compatible with
  19876. separate compilation and with first-class generics. However, it
  19877. produces the least-efficient code because it introduces overhead in
  19878. the entire program. This approach is used in
  19879. Java~\citep{Bracha:1998fk},
  19880. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  19881. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  19882. \item[Mixed representation] generates one version of each generic
  19883. function, using a boxed representation for type variables. However,
  19884. monomorphic code is compiled as usual (as in \LangLam{}) and
  19885. conversions are performed at the boundaries between monomorphic code
  19886. and polymorphic code (e.g. when a generic function is instantiated
  19887. and called). This approach is compatible with separate compilation
  19888. and first-class generics and maintains efficiency in monomorphic
  19889. code. The trade off is increased overhead at the boundary between
  19890. monomorphic and generic code. This approach is used in
  19891. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  19892. Java 5 with the addition of autoboxing.
  19893. \item[Type passing] uses the unboxed representation in both
  19894. monomorphic and generic code. Each generic function is compiled to a
  19895. single function with extra parameters that describe the type
  19896. arguments. The type information is used by the generated code to
  19897. know how to access the unboxed values at runtime. This approach is
  19898. used in implementation of Napier88~\citep{Morrison:1991aa} and
  19899. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  19900. compilation and first-class generics and maintains the
  19901. efficiency for monomorphic code. There is runtime overhead in
  19902. polymorphic code from dispatching on type information.
  19903. \end{description}
  19904. In this chapter we use the mixed representation approach, partly
  19905. because of its favorable attributes, and partly because it is
  19906. straightforward to implement using the tools that we have already
  19907. built to support gradual typing. The work of compiling generic
  19908. functions is performed in two passes, \code{resolve} and
  19909. \code{erase\_types}, that we discuss next. The output of
  19910. \code{erase\_types} is \LangCast{}
  19911. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  19912. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  19913. \section{Resolve Types}
  19914. \label{sec:generic-resolve}
  19915. Recall that the type checker for \LangPoly{} deduces the type
  19916. arguments at call sites to a generic function. The purpose of the
  19917. \code{resolve} pass is to turn this implicit instantiation into an
  19918. explicit one, by adding \code{inst} nodes to the syntax of the
  19919. intermediate language. An \code{inst} node records the mapping of
  19920. type parameters to type arguments. The semantics of the \code{inst}
  19921. node is to instantiate the result of its first argument, a generic
  19922. function, to produce a monomorphic function. However, because the
  19923. interpreter never analyzes type annotations, instantiation can be a
  19924. no-op and simply return the generic function.
  19925. %
  19926. The output language of the \code{resolve} pass is \LangInst{}, defined
  19927. in figure~\ref{fig:Lpoly-prime-syntax}.
  19928. \if\edition\racketEd
  19929. The \code{resolve} pass combines the type declaration and polymorphic
  19930. function into a single definition, using the \code{Poly} form, to make
  19931. polymorphic functions more convenient to process in the next pass of the
  19932. compiler.
  19933. \fi
  19934. \newcommand{\LinstASTRacket}{
  19935. \begin{array}{lcl}
  19936. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19937. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  19938. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  19939. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  19940. \end{array}
  19941. }
  19942. \newcommand{\LinstASTPython}{
  19943. \begin{array}{lcl}
  19944. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  19945. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  19946. \end{array}
  19947. }
  19948. \begin{figure}[tp]
  19949. \centering
  19950. \begin{tcolorbox}[colback=white]
  19951. \small
  19952. \if\edition\racketEd
  19953. \[
  19954. \begin{array}{l}
  19955. \gray{\LintOpAST} \\ \hline
  19956. \gray{\LvarASTRacket{}} \\ \hline
  19957. \gray{\LifASTRacket{}} \\ \hline
  19958. \gray{\LwhileASTRacket{}} \\ \hline
  19959. \gray{\LtupASTRacket{}} \\ \hline
  19960. \gray{\LfunASTRacket} \\ \hline
  19961. \gray{\LlambdaASTRacket} \\ \hline
  19962. \LinstASTRacket \\
  19963. \begin{array}{lcl}
  19964. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  19965. \end{array}
  19966. \end{array}
  19967. \]
  19968. \fi
  19969. \if\edition\pythonEd
  19970. \[
  19971. \begin{array}{l}
  19972. \gray{\LintASTPython} \\ \hline
  19973. \gray{\LvarASTPython{}} \\ \hline
  19974. \gray{\LifASTPython{}} \\ \hline
  19975. \gray{\LwhileASTPython{}} \\ \hline
  19976. \gray{\LtupASTPython{}} \\ \hline
  19977. \gray{\LfunASTPython} \\ \hline
  19978. \gray{\LlambdaASTPython} \\ \hline
  19979. \LinstASTPython \\
  19980. \begin{array}{lcl}
  19981. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  19982. \end{array}
  19983. \end{array}
  19984. \]
  19985. \fi
  19986. \end{tcolorbox}
  19987. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  19988. (figure~\ref{fig:Llam-syntax}).}
  19989. \label{fig:Lpoly-prime-syntax}
  19990. \end{figure}
  19991. The output of the \code{resolve} pass on the generic \code{map}
  19992. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  19993. of \code{map} is wrapped in an \code{inst} node, with the parameter
  19994. \code{T} chosen to be \racket{\code{Integer}} \python{\code{int}}.
  19995. \begin{figure}[tbp]
  19996. % poly_test_2.rkt
  19997. \begin{tcolorbox}[colback=white]
  19998. \if\edition\racketEd
  19999. \begin{lstlisting}
  20000. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  20001. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  20002. (define (inc [x : Integer]) : Integer (+ x 1))
  20003. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20004. (Integer))
  20005. inc (vector 0 41)) 1)
  20006. \end{lstlisting}
  20007. \fi
  20008. \if\edition\pythonEd
  20009. \begin{lstlisting}
  20010. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20011. return (f(tup[0]), f(tup[1]))
  20012. def add1(x : int) -> int:
  20013. return x + 1
  20014. t = inst(map, {T: int})(add1, (0, 41))
  20015. print(t[1])
  20016. \end{lstlisting}
  20017. \fi
  20018. \end{tcolorbox}
  20019. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  20020. \label{fig:map-resolve}
  20021. \end{figure}
  20022. \section{Erase Types}
  20023. \label{sec:erase_types}
  20024. We use the \CANYTY{} type from chapter~\ref{ch:Ldyn} to
  20025. represent type variables. For example, figure~\ref{fig:map-erase}
  20026. shows the output of the \code{erase\_types} pass on the polymorphic
  20027. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  20028. type parameter \code{a} are replaced by \CANYTY{} and the polymorphic
  20029. \code{All} types are removed from the type of \code{map}.
  20030. \begin{figure}[tbp]
  20031. \begin{tcolorbox}[colback=white]
  20032. \if\edition\racketEd
  20033. \begin{lstlisting}
  20034. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  20035. : (Vector Any Any)
  20036. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20037. (define (inc [x : Integer]) : Integer (+ x 1))
  20038. (vector-ref ((cast map
  20039. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20040. ((Integer -> Integer) (Vector Integer Integer)
  20041. -> (Vector Integer Integer)))
  20042. inc (vector 0 41)) 1)
  20043. \end{lstlisting}
  20044. \fi
  20045. \if\edition\pythonEd
  20046. \begin{lstlisting}
  20047. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  20048. return (f(tup[0]), f(tup[1]))
  20049. def add1(x : int) -> int:
  20050. return (x + 1)
  20051. def main() -> int:
  20052. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  20053. print(t[1])
  20054. return 0
  20055. \end{lstlisting}
  20056. {\small
  20057. where\\
  20058. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  20059. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  20060. }
  20061. \fi
  20062. \end{tcolorbox}
  20063. \caption{The generic \code{map} example after type erasure.}
  20064. \label{fig:map-erase}
  20065. \end{figure}
  20066. This process of type erasure creates a challenge at points of
  20067. instantiation. For example, consider the instantiation of
  20068. \code{map} in figure~\ref{fig:map-resolve}.
  20069. The type of \code{map} is
  20070. %
  20071. \if\edition\racketEd
  20072. \begin{lstlisting}
  20073. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20074. \end{lstlisting}
  20075. \fi
  20076. \if\edition\pythonEd
  20077. \begin{lstlisting}
  20078. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  20079. \end{lstlisting}
  20080. \fi
  20081. %
  20082. and it is instantiated to
  20083. %
  20084. \if\edition\racketEd
  20085. \begin{lstlisting}
  20086. ((Integer -> Integer) (Vector Integer Integer)
  20087. -> (Vector Integer Integer))
  20088. \end{lstlisting}
  20089. \fi
  20090. \if\edition\pythonEd
  20091. \begin{lstlisting}
  20092. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  20093. \end{lstlisting}
  20094. \fi
  20095. %
  20096. After erasure, the type of \code{map} is
  20097. %
  20098. \if\edition\racketEd
  20099. \begin{lstlisting}
  20100. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20101. \end{lstlisting}
  20102. \fi
  20103. \if\edition\pythonEd
  20104. \begin{lstlisting}
  20105. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  20106. \end{lstlisting}
  20107. \fi
  20108. %
  20109. but we need to convert it to the instantiated type. This is easy to
  20110. do in the language \LangCast{} with a single \code{cast}. In
  20111. figure~\ref{fig:map-erase}, the instantiation of \code{map} has been
  20112. compiled to a \code{cast} from the type of \code{map} to the
  20113. instantiated type. The source and target type of a cast must be
  20114. consistent (figure~\ref{fig:consistent}), which indeed is the case
  20115. because both the source and target are obtained from the same generic
  20116. type of \code{map}, replacing the type parameters with \CANYTY{} in
  20117. the former and with the deduced type arguments in the later. (Recall
  20118. that the \CANYTY{} type is consistent with any type.)
  20119. To implement the \code{erase\_types} pass, we first recommend defining
  20120. a recursive function that translates types, named
  20121. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  20122. follows.
  20123. %
  20124. \if\edition\racketEd
  20125. \begin{lstlisting}
  20126. |$T$|
  20127. |$\Rightarrow$|
  20128. Any
  20129. \end{lstlisting}
  20130. \fi
  20131. \if\edition\pythonEd
  20132. \begin{lstlisting}
  20133. GenericVar(|$T$|)
  20134. |$\Rightarrow$|
  20135. Any
  20136. \end{lstlisting}
  20137. \fi
  20138. %
  20139. \noindent The \code{erase\_type} function also removes the generic
  20140. \code{All} types.
  20141. %
  20142. \if\edition\racketEd
  20143. \begin{lstlisting}
  20144. (All |$xs$| |$T_1$|)
  20145. |$\Rightarrow$|
  20146. |$T'_1$|
  20147. \end{lstlisting}
  20148. \fi
  20149. \if\edition\pythonEd
  20150. \begin{lstlisting}
  20151. AllType(|$xs$|, |$T_1$|)
  20152. |$\Rightarrow$|
  20153. |$T'_1$|
  20154. \end{lstlisting}
  20155. \fi
  20156. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  20157. %
  20158. In this compiler pass, apply the \code{erase\_type} function to all of
  20159. the type annotations in the program.
  20160. Regarding the translation of expressions, the case for \code{Inst} is
  20161. the interesting one. We translate it into a \code{Cast}, as shown
  20162. below.
  20163. The type of hte subexpression $e$ is a generic type of the form
  20164. \racket{$\LP\key{All}~\itm{xs}~T\RP$}
  20165. \python{$\key{AllType}\LP\itm{xs}, T\RP$}. The source type of the
  20166. cast is the erasure of $T$, the type $T_s$.
  20167. %
  20168. \if\edition\racketEd
  20169. %
  20170. The target type $T_t$ is the result of substituting the argument types
  20171. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  20172. erasure.
  20173. %
  20174. \begin{lstlisting}
  20175. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  20176. |$\Rightarrow$|
  20177. (Cast |$e'$| |$T_s$| |$T_t$|)
  20178. \end{lstlisting}
  20179. %
  20180. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$
  20181. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  20182. \fi
  20183. \if\edition\pythonEd
  20184. %
  20185. The target type $T_t$ is the result of substituting the deduced
  20186. argument types $d$ in $T$ followed by doing type erasure.
  20187. %
  20188. \begin{lstlisting}
  20189. Inst(|$e$|, |$d$|)
  20190. |$\Rightarrow$|
  20191. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  20192. \end{lstlisting}
  20193. %
  20194. where
  20195. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  20196. \fi
  20197. Finally, each generic function is translated to a regular
  20198. function in which type erasure has been applied to all the type
  20199. annotations and the body.
  20200. %% \begin{lstlisting}
  20201. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  20202. %% |$\Rightarrow$|
  20203. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  20204. %% \end{lstlisting}
  20205. \begin{exercise}\normalfont\normalsize
  20206. Implement a compiler for the polymorphic language \LangPoly{} by
  20207. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  20208. programs that use polymorphic functions. Some of them should make
  20209. use of first-class generics.
  20210. \end{exercise}
  20211. \begin{figure}[p]
  20212. \begin{tcolorbox}[colback=white]
  20213. \if\edition\racketEd
  20214. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20215. \node (Lpoly) at (12,4) {\large \LangPoly{}};
  20216. \node (Lpolyp) at (9,4) {\large \LangInst{}};
  20217. \node (Lgradualp) at (6,4) {\large \LangCast{}};
  20218. \node (Llambdapp) at (3,4) {\large \LangProxy{}};
  20219. \node (Llambdaproxy) at (0,4) {\large \LangPVec{}};
  20220. \node (Llambdaproxy-2) at (0,2) {\large \LangPVec{}};
  20221. \node (Llambdaproxy-3) at (3,2) {\large \LangPVec{}};
  20222. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  20223. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  20224. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  20225. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  20226. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  20227. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  20228. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  20229. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  20230. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  20231. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  20232. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  20233. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  20234. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  20235. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  20236. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  20237. \path[->,bend right=15] (Lpoly) edge [above] node
  20238. {\ttfamily\footnotesize type\_check} (Lpolyp);
  20239. \path[->,bend right=15] (Lpolyp) edge [above] node
  20240. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  20241. \path[->,bend right=15] (Lgradualp) edge [above] node
  20242. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20243. \path[->,bend right=15] (Llambdapp) edge [above] node
  20244. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  20245. \path[->,bend right=15] (Llambdaproxy) edge [right] node
  20246. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  20247. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  20248. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  20249. \path[->,bend left=15] (Llambdaproxy-3) edge [above] node
  20250. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  20251. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  20252. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20253. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  20254. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20255. \path[->,bend left=15] (F1-1) edge [left] node
  20256. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  20257. \path[->,bend left=15] (F1-2) edge [below] node
  20258. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  20259. \path[->,bend right=15] (F1-3) edge [above] node
  20260. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  20261. \path[->,bend right=15] (F1-4) edge [above] node
  20262. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20263. \path[->,bend right=15] (F1-5) edge [above] node
  20264. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  20265. \path[->,bend right=15] (F1-6) edge [right] node
  20266. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20267. \path[->,bend left=15] (C3-2) edge [left] node
  20268. {\ttfamily\footnotesize select\_instr.} (x86-2);
  20269. \path[->,bend right=15] (x86-2) edge [left] node
  20270. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20271. \path[->,bend right=15] (x86-2-1) edge [below] node
  20272. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  20273. \path[->,bend right=15] (x86-2-2) edge [left] node
  20274. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  20275. \path[->,bend left=15] (x86-3) edge [above] node
  20276. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  20277. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  20278. \end{tikzpicture}
  20279. \fi
  20280. \if\edition\pythonEd
  20281. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20282. \node (Lgradual) at (12,4) {\large \LangPoly{}};
  20283. \node (Lgradual2) at (9,4) {\large \LangPoly{}};
  20284. \node (Lgradual3) at (6,4) {\large \LangPoly{}};
  20285. \node (Lgradual4) at (3,4) {\large \LangPoly{}};
  20286. \node (Lgradualr) at (0,4) {\large \LangInst{}};
  20287. \node (Llambdapp) at (0,2) {\large \LangCast{}};
  20288. \node (Llambdaproxy-4) at (3,2) {\large \LangPVec{}};
  20289. \node (Llambdaproxy-5) at (6,2) {\large \LangPVec{}};
  20290. \node (F1-1) at (9,2) {\large \LangPVec{}};
  20291. \node (F1-2) at (12,0) {\large \LangPVec{}};
  20292. \node (F1-3) at (9,0) {\large \LangPVec{}};
  20293. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  20294. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  20295. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  20296. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  20297. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  20298. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  20299. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  20300. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  20301. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  20302. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  20303. \path[->,bend right=15] (Lgradual) edge [above] node
  20304. {\ttfamily\footnotesize shrink} (Lgradual2);
  20305. \path[->,bend right=15] (Lgradual2) edge [above] node
  20306. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20307. \path[->,bend right=15] (Lgradual3) edge [above] node
  20308. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20309. \path[->,bend right=15] (Lgradual4) edge [above] node
  20310. {\ttfamily\footnotesize resolve} (Lgradualr);
  20311. \path[->,bend right=15] (Lgradualr) edge [right] node
  20312. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  20313. \path[->,bend right=15] (Llambdapp) edge [below] node
  20314. {\ttfamily\footnotesize differentiate.} (Llambdaproxy-4);
  20315. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  20316. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20317. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  20318. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20319. \path[->,bend left=15] (F1-1) edge [left] node
  20320. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  20321. \path[->,bend left=15] (F1-2) edge [below] node
  20322. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  20323. \path[->,bend right=15] (F1-3) edge [above] node
  20324. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  20325. \path[->,bend right=15] (F1-4) edge [above] node
  20326. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20327. \path[->,bend right=15] (F1-5) edge [above] node
  20328. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  20329. \path[->,bend right=15] (F1-6) edge [right] node
  20330. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20331. \path[->,bend left=15] (C3-2) edge [left] node
  20332. {\ttfamily\footnotesize select\_instr.} (x86-2);
  20333. \path[->,bend right=15] (x86-2) edge [left] node
  20334. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20335. \path[->,bend right=15] (x86-2-1) edge [below] node
  20336. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  20337. \path[->,bend right=15] (x86-2-2) edge [left] node
  20338. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  20339. \path[->,bend left=15] (x86-3) edge [above] node
  20340. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  20341. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  20342. \end{tikzpicture}
  20343. \fi
  20344. \end{tcolorbox}
  20345. \caption{Diagram of the passes for \LangPoly{} (generics).}
  20346. \label{fig:Lpoly-passes}
  20347. \end{figure}
  20348. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  20349. needed to compile \LangPoly{}.
  20350. % TODO: challenge problem: specialization of instantiations
  20351. % Further Reading
  20352. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20353. \clearpage
  20354. \appendix
  20355. \chapter{Appendix}
  20356. \setcounter{footnote}{0}
  20357. \if\edition\racketEd
  20358. \section{Interpreters}
  20359. \label{appendix:interp}
  20360. \index{subject}{interpreter}
  20361. We provide interpreters for each of the source languages \LangInt{},
  20362. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  20363. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  20364. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  20365. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  20366. and x86 are in the \key{interp.rkt} file.
  20367. \section{Utility Functions}
  20368. \label{appendix:utilities}
  20369. The utility functions described in this section are in the
  20370. \key{utilities.rkt} file of the support code.
  20371. \paragraph{\code{interp-tests}}
  20372. The \key{interp-tests} function runs the compiler passes and the
  20373. interpreters on each of the specified tests to check whether each pass
  20374. is correct. The \key{interp-tests} function has the following
  20375. parameters:
  20376. \begin{description}
  20377. \item[name (a string)] a name to identify the compiler,
  20378. \item[typechecker] a function of exactly one argument that either
  20379. raises an error using the \code{error} function when it encounters a
  20380. type error, or returns \code{\#f} when it encounters a type
  20381. error. If there is no type error, the type checker returns the
  20382. program.
  20383. \item[passes] a list with one entry per pass. An entry is a list with
  20384. four things:
  20385. \begin{enumerate}
  20386. \item a string giving the name of the pass,
  20387. \item the function that implements the pass (a translator from AST
  20388. to AST),
  20389. \item a function that implements the interpreter (a function from
  20390. AST to result value) for the output language,
  20391. \item and a type checker for the output language. Type checkers for
  20392. the $R$ and $C$ languages are provided in the support code. For
  20393. example, the type checkers for \LangVar{} and \LangCVar{} are in
  20394. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  20395. type checker entry is optional. The support code does not provide
  20396. type checkers for the x86 languages.
  20397. \end{enumerate}
  20398. \item[source-interp] an interpreter for the source language. The
  20399. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  20400. \item[test-family (a string)] for example, \code{"var"}, \code{"cond"}, etc.
  20401. \item[tests] a list of test numbers that specifies which tests to
  20402. run. (see below)
  20403. \end{description}
  20404. %
  20405. The \key{interp-tests} function assumes that the subdirectory
  20406. \key{tests} has a collection of Racket programs whose names all start
  20407. with the family name, followed by an underscore and then the test
  20408. number, ending with the file extension \key{.rkt}. Also, for each test
  20409. program that calls \code{read} one or more times, there is a file with
  20410. the same name except that the file extension is \key{.in} that
  20411. provides the input for the Racket program. If the test program is
  20412. expected to fail type checking, then there should be an empty file of
  20413. the same name but with extension \key{.tyerr}.
  20414. \paragraph{\code{compiler-tests}}
  20415. runs the compiler passes to generate x86 (a \key{.s} file) and then
  20416. runs the GNU C compiler (gcc) to generate machine code. It runs the
  20417. machine code and checks that the output is $42$. The parameters to the
  20418. \code{compiler-tests} function are similar to those of the
  20419. \code{interp-tests} function, and consist of
  20420. \begin{itemize}
  20421. \item a compiler name (a string),
  20422. \item a type checker,
  20423. \item description of the passes,
  20424. \item name of a test-family, and
  20425. \item a list of test numbers.
  20426. \end{itemize}
  20427. \paragraph{\code{compile-file}}
  20428. takes a description of the compiler passes (see the comment for
  20429. \key{interp-tests}) and returns a function that, given a program file
  20430. name (a string ending in \key{.rkt}), applies all of the passes and
  20431. writes the output to a file whose name is the same as the program file
  20432. name but with \key{.rkt} replaced with \key{.s}.
  20433. \paragraph{\code{read-program}}
  20434. takes a file path and parses that file (it must be a Racket program)
  20435. into an abstract syntax tree.
  20436. \paragraph{\code{parse-program}}
  20437. takes an S-expression representation of an abstract syntax tree and converts it into
  20438. the struct-based representation.
  20439. \paragraph{\code{assert}}
  20440. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  20441. and displays the message \key{msg} if the Boolean \key{bool} is false.
  20442. \paragraph{\code{lookup}}
  20443. % remove discussion of lookup? -Jeremy
  20444. takes a key and an alist, and returns the first value that is
  20445. associated with the given key, if there is one. If not, an error is
  20446. triggered. The alist may contain both immutable pairs (built with
  20447. \key{cons}) and mutable pairs (built with \key{mcons}).
  20448. %The \key{map2} function ...
  20449. \fi %\racketEd
  20450. \section{x86 Instruction Set Quick-Reference}
  20451. \label{sec:x86-quick-reference}
  20452. \index{subject}{x86}
  20453. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  20454. do. We write $A \to B$ to mean that the value of $A$ is written into
  20455. location $B$. Address offsets are given in bytes. The instruction
  20456. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  20457. registers (such as \code{\%rax}), or memory references (such as
  20458. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  20459. reference per instruction. Other operands must be immediates or
  20460. registers.
  20461. \begin{table}[tbp]
  20462. \centering
  20463. \begin{tabular}{l|l}
  20464. \textbf{Instruction} & \textbf{Operation} \\ \hline
  20465. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  20466. \texttt{negq} $A$ & $- A \to A$ \\
  20467. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  20468. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  20469. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  20470. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  20471. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  20472. \texttt{retq} & Pops the return address and jumps to it \\
  20473. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  20474. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  20475. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  20476. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  20477. be an immediate) \\
  20478. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  20479. matches the condition code of the instruction, otherwise go to the
  20480. next instructions. The condition codes are \key{e} for ``equal'',
  20481. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  20482. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  20483. \texttt{jl} $L$ & \\
  20484. \texttt{jle} $L$ & \\
  20485. \texttt{jg} $L$ & \\
  20486. \texttt{jge} $L$ & \\
  20487. \texttt{jmp} $L$ & Jump to label $L$ \\
  20488. \texttt{movq} $A$, $B$ & $A \to B$ \\
  20489. \texttt{movzbq} $A$, $B$ &
  20490. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  20491. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  20492. and the extra bytes of $B$ are set to zero.} \\
  20493. & \\
  20494. & \\
  20495. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  20496. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  20497. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  20498. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  20499. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  20500. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  20501. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  20502. description of the condition codes. $A$ must be a single byte register
  20503. (e.g., \texttt{al} or \texttt{cl}).} \\
  20504. \texttt{setl} $A$ & \\
  20505. \texttt{setle} $A$ & \\
  20506. \texttt{setg} $A$ & \\
  20507. \texttt{setge} $A$ &
  20508. \end{tabular}
  20509. \vspace{5pt}
  20510. \caption{Quick-reference for the x86 instructions used in this book.}
  20511. \label{tab:x86-instr}
  20512. \end{table}
  20513. %% \if\edition\racketEd
  20514. %% \cleardoublepage
  20515. %% \section{Concrete Syntax for Intermediate Languages}
  20516. %% The concrete syntax of \LangAny{} is defined in
  20517. %% figure~\ref{fig:Lany-concrete-syntax}.
  20518. %% \begin{figure}[tp]
  20519. %% \centering
  20520. %% \fbox{
  20521. %% \begin{minipage}{0.97\textwidth}\small
  20522. %% \[
  20523. %% \begin{array}{lcl}
  20524. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  20525. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  20526. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  20527. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  20528. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  20529. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  20530. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  20531. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  20532. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  20533. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  20534. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  20535. %% \MID \LP\key{void?}\;\Exp\RP \\
  20536. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  20537. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  20538. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  20539. %% \end{array}
  20540. %% \]
  20541. %% \end{minipage}
  20542. %% }
  20543. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  20544. %% (figure~\ref{fig:Llam-syntax}).}
  20545. %% \label{fig:Lany-concrete-syntax}
  20546. %% \end{figure}
  20547. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  20548. %% \LangCFun{} is defined in Figures~\ref{fig:c0-concrete-syntax},
  20549. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  20550. %% \ref{fig:c3-concrete-syntax}, respectively.
  20551. %% \begin{figure}[tbp]
  20552. %% \fbox{
  20553. %% \begin{minipage}{0.96\textwidth}
  20554. %% \small
  20555. %% \[
  20556. %% \begin{array}{lcl}
  20557. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  20558. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20559. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  20560. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  20561. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  20562. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  20563. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  20564. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  20565. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  20566. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  20567. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  20568. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  20569. %% \end{array}
  20570. %% \]
  20571. %% \end{minipage}
  20572. %% }
  20573. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  20574. %% \label{fig:c2-concrete-syntax}
  20575. %% \end{figure}
  20576. %% \begin{figure}[tp]
  20577. %% \fbox{
  20578. %% \begin{minipage}{0.96\textwidth}
  20579. %% \small
  20580. %% \[
  20581. %% \begin{array}{lcl}
  20582. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  20583. %% \\
  20584. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20585. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  20586. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  20587. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  20588. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  20589. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  20590. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  20591. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  20592. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  20593. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  20594. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  20595. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  20596. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  20597. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  20598. %% \LangCFunM{} & ::= & \Def\ldots
  20599. %% \end{array}
  20600. %% \]
  20601. %% \end{minipage}
  20602. %% }
  20603. %% \caption{The \LangCFun{} language, extending \LangCVec{} (figure~\ref{fig:c2-concrete-syntax}) with functions.}
  20604. %% \label{fig:c3-concrete-syntax}
  20605. %% \end{figure}
  20606. %% \fi % racketEd
  20607. \backmatter
  20608. \addtocontents{toc}{\vspace{11pt}}
  20609. %% \addtocontents{toc}{\vspace{11pt}}
  20610. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  20611. \nocite{*}\let\bibname\refname
  20612. \addcontentsline{toc}{fmbm}{\refname}
  20613. \printbibliography
  20614. %\printindex{authors}{Author Index}
  20615. \printindex{subject}{Index}
  20616. \end{document}
  20617. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  20618. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  20619. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  20620. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  20621. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  20622. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  20623. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  20624. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  20625. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  20626. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  20627. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  20628. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  20629. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  20630. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  20631. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  20632. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  20633. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  20634. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  20635. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  20636. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  20637. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  20638. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  20639. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  20640. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  20641. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  20642. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  20643. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  20644. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  20645. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  20646. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  20647. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  20648. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  20649. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  20650. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  20651. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  20652. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  20653. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  20654. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  20655. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  20656. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  20657. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  20658. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  20659. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  20660. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  20661. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  20662. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  20663. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  20664. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  20665. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  20666. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  20667. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  20668. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  20669. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  20670. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  20671. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  20672. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  20673. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  20674. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  20675. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  20676. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  20677. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  20678. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  20679. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  20680. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  20681. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  20682. % LocalWords: notq setle setg setge