12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624 |
- struct irProcedure;
- struct irBlock;
- struct irValue;
- struct irDebugInfo;
- struct irModule {
- CheckerInfo * info;
- gbArena arena;
- gbArena tmp_arena;
- gbAllocator allocator;
- gbAllocator tmp_allocator;
- // bool generate_debug_info;
- u64 stmt_state_flags;
- // String source_filename;
- String layout;
- // String triple;
- PtrSet<Entity *> min_dep_set;
- Map<irValue *> values; // Key: Entity *
- Map<irValue *> members; // Key: String
- Map<String> entity_names; // Key: Entity * of the typename
- Map<irDebugInfo *> debug_info; // Key: Unique pointer
- Map<irValue *> anonymous_proc_lits; // Key: AstNode *
- i32 global_string_index;
- i32 global_array_index; // For ConstantSlice
- i32 global_generated_index;
- irValue * global_default_context;
- // NOTE(bill): To prevent strings from being copied a lot
- // Mainly used for file names
- Map<irValue *> const_strings; // Key: String
- Entity * entry_point_entity;
- Array<irProcedure *> procs; // NOTE(bill): All procedures with bodies
- Array<irValue *> procs_to_generate; // NOTE(bill): Procedures to generate
- Array<String> foreign_library_paths; // Only the ones that were used
- };
- // NOTE(bill): For more info, see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
- struct irDomNode {
- irBlock * idom; // Parent (Immediate Dominator)
- Array<irBlock *> children;
- i32 pre, post; // Ordering in tree
- };
- struct irBlock {
- i32 index;
- String label;
- irProcedure *parent;
- AstNode * node; // Can be nullptr
- Scope * scope;
- isize scope_index;
- irDomNode dom;
- i32 gaps;
- Array<irValue *> instrs;
- Array<irValue *> locals;
- Array<irBlock *> preds;
- Array<irBlock *> succs;
- };
- struct irTargetList {
- irTargetList *prev;
- irBlock * break_;
- irBlock * continue_;
- irBlock * fallthrough_;
- };
- enum irDeferExitKind {
- irDeferExit_Default,
- irDeferExit_Return,
- irDeferExit_Branch,
- };
- enum irDeferKind {
- irDefer_Node,
- irDefer_Instr,
- };
- struct irDefer {
- irDeferKind kind;
- isize scope_index;
- irBlock * block;
- union {
- AstNode *stmt;
- // NOTE(bill): `instr` will be copied every time to create a new one
- irValue *instr;
- };
- };
- struct irBranchBlocks {
- AstNode *label;
- irBlock *break_;
- irBlock *continue_;
- };
- struct irProcedure {
- irProcedure * parent;
- Array<irProcedure *> children;
- Entity * entity;
- irModule * module;
- String name;
- Type * type;
- AstNode * type_expr;
- AstNode * body;
- u64 tags;
- ProcInlining inlining;
- bool is_foreign;
- bool is_export;
- bool is_entry_point;
- irValue * return_ptr;
- Array<irValue *> params;
- Array<irDefer> defer_stmts;
- Array<irBlock *> blocks;
- i32 scope_index;
- irBlock * decl_block;
- irBlock * entry_block;
- irBlock * curr_block;
- irTargetList * target_list;
- Array<irValue *> referrers;
- Array<irValue *> context_stack;
- Array<irBranchBlocks> branch_blocks;
- i32 local_count;
- i32 instr_count;
- i32 block_count;
- };
- #define IR_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime"
- #define IR_TYPE_INFO_DATA_NAME "__$type_info_data"
- #define IR_TYPE_INFO_TYPES_NAME "__$type_info_types_data"
- #define IR_TYPE_INFO_NAMES_NAME "__$type_info_names_data"
- #define IR_TYPE_INFO_OFFSETS_NAME "__$type_info_offsets_data"
- #define IR_TYPE_INFO_USINGS_NAME "__$type_info_usings_data"
- #define IR_INSTR_KINDS \
- IR_INSTR_KIND(Comment, struct { String text; }) \
- IR_INSTR_KIND(Local, struct { \
- Entity * entity; \
- Type * type; \
- bool zero_initialized; \
- Array<irValue *> referrers; \
- i64 alignment; \
- }) \
- IR_INSTR_KIND(ZeroInit, struct { irValue *address; }) \
- IR_INSTR_KIND(Store, struct { \
- irValue *address, *value; bool atomic; \
- }) \
- IR_INSTR_KIND(Load, struct { Type *type; irValue *address; }) \
- IR_INSTR_KIND(PtrOffset, struct { \
- irValue *address; \
- irValue *offset; \
- }) \
- IR_INSTR_KIND(ArrayElementPtr, struct { \
- irValue *address; \
- Type * result_type; \
- irValue *elem_index; \
- }) \
- IR_INSTR_KIND(StructElementPtr, struct { \
- irValue *address; \
- Type * result_type; \
- i32 elem_index; \
- }) \
- IR_INSTR_KIND(StructExtractValue, struct { \
- irValue *address; \
- Type * result_type; \
- i32 index; \
- }) \
- IR_INSTR_KIND(UnionTagPtr, struct { \
- irValue *address; \
- Type *type; /* ^int */ \
- }) \
- IR_INSTR_KIND(UnionTagValue, struct { \
- irValue *address; \
- Type *type; /* int */ \
- }) \
- IR_INSTR_KIND(Conv, struct { \
- irConvKind kind; \
- irValue *value; \
- Type *from, *to; \
- }) \
- IR_INSTR_KIND(Jump, struct { irBlock *block; }) \
- IR_INSTR_KIND(If, struct { \
- irValue *cond; \
- irBlock *true_block; \
- irBlock *false_block; \
- }) \
- IR_INSTR_KIND(Return, struct { irValue *value; }) \
- IR_INSTR_KIND(Select, struct { \
- irValue *cond; \
- irValue *true_value; \
- irValue *false_value; \
- }) \
- IR_INSTR_KIND(Phi, struct { Array<irValue *> edges; Type *type; })\
- IR_INSTR_KIND(Unreachable, i32) \
- IR_INSTR_KIND(UnaryOp, struct { \
- Type * type; \
- TokenKind op; \
- irValue * expr; \
- }) \
- IR_INSTR_KIND(BinaryOp, struct { \
- Type * type; \
- TokenKind op; \
- irValue * left, *right; \
- }) \
- IR_INSTR_KIND(Call, struct { \
- Type * type; /* return type */ \
- irValue * value; \
- irValue * return_ptr; \
- irValue **args; \
- isize arg_count; \
- irValue * context_ptr; \
- }) \
- IR_INSTR_KIND(StartupRuntime, i32) \
- IR_INSTR_KIND(DebugDeclare, struct { \
- irDebugInfo *debug_info; \
- AstNode * expr; \
- Entity * entity; \
- bool is_addr; \
- irValue * value; \
- }) \
- // IR_INSTR_KIND(BoundsCheck, struct { \
- // TokenPos pos; \
- // irValue *index; \
- // irValue *len; \
- // }) \
- // IR_INSTR_KIND(SliceBoundsCheck, struct { \
- // TokenPos pos; \
- // irValue *low; \
- // irValue *high; \
- // irValue *max; \
- // bool is_substring; \
- // }) \
- #define IR_CONV_KINDS \
- IR_CONV_KIND(trunc) \
- IR_CONV_KIND(zext) \
- IR_CONV_KIND(sext) \
- IR_CONV_KIND(fptrunc) \
- IR_CONV_KIND(fpext) \
- IR_CONV_KIND(fptoui) \
- IR_CONV_KIND(fptosi) \
- IR_CONV_KIND(uitofp) \
- IR_CONV_KIND(sitofp) \
- IR_CONV_KIND(ptrtoint) \
- IR_CONV_KIND(inttoptr) \
- IR_CONV_KIND(bitcast)
- enum irInstrKind {
- irInstr_Invalid,
- #define IR_INSTR_KIND(x, ...) GB_JOIN2(irInstr_, x),
- IR_INSTR_KINDS
- #undef IR_INSTR_KIND
- };
- String const ir_instr_strings[] = {
- {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
- #define IR_INSTR_KIND(x, ...) {cast(u8 *)#x, gb_size_of(#x)-1},
- IR_INSTR_KINDS
- #undef IR_INSTR_KIND
- };
- enum irConvKind {
- irConv_Invalid,
- #define IR_CONV_KIND(x) GB_JOIN2(irConv_, x),
- IR_CONV_KINDS
- #undef IR_CONV_KIND
- };
- String const ir_conv_strings[] = {
- {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
- #define IR_CONV_KIND(x) {cast(u8 *)#x, gb_size_of(#x)-1},
- IR_CONV_KINDS
- #undef IR_CONV_KIND
- };
- #define IR_INSTR_KIND(k, ...) typedef __VA_ARGS__ GB_JOIN2(irInstr, k);
- IR_INSTR_KINDS
- #undef IR_INSTR_KIND
- struct irInstr {
- irInstrKind kind;
- irBlock *parent;
- Type *type;
- union {
- #define IR_INSTR_KIND(k, ...) GB_JOIN2(irInstr, k) k;
- IR_INSTR_KINDS
- #undef IR_INSTR_KIND
- };
- };
- enum irValueKind {
- irValue_Invalid,
- irValue_Constant,
- irValue_ConstantSlice,
- irValue_Nil,
- irValue_Undef,
- irValue_TypeName,
- irValue_Global,
- irValue_Param,
- irValue_Proc,
- irValue_Block,
- irValue_Instr,
- irValue_Count,
- };
- struct irValueConstant {
- Type * type;
- ExactValue value;
- };
- struct irValueConstantSlice {
- Type * type;
- irValue *backing_array;
- i64 count;
- };
- struct irValueNil {
- Type *type;
- };
- struct irValueUndef {
- Type *type;
- };
- struct irValueTypeName {
- Type * type;
- String name;
- };
- struct irValueGlobal {
- String name;
- Entity * entity;
- Type * type;
- irValue * value;
- Array<irValue *> referrers;
- bool is_constant;
- bool is_export;
- bool is_private;
- String thread_local_model;
- bool is_foreign;
- bool is_unnamed_addr;
- };
- enum irParamPasskind {
- irParamPass_Value, // Pass by value
- irParamPass_Pointer, // Pass as a pointer rather than by value
- irParamPass_Integer, // Pass as an integer of the same size
- };
- struct irValueParam {
- irParamPasskind kind;
- irProcedure * parent;
- Entity * entity;
- Type * type;
- Type * original_type;
- Array<irValue *> referrers;
- };
- struct irValue {
- irValueKind kind;
- i32 index;
- bool index_set;
- union {
- irValueConstant Constant;
- irValueConstantSlice ConstantSlice;
- irValueNil Nil;
- irValueUndef Undef;
- irValueTypeName TypeName;
- irValueGlobal Global;
- irValueParam Param;
- irProcedure Proc;
- irBlock Block;
- irInstr Instr;
- };
- };
- gb_global irValue *v_zero = nullptr;
- gb_global irValue *v_one = nullptr;
- gb_global irValue *v_zero32 = nullptr;
- gb_global irValue *v_one32 = nullptr;
- gb_global irValue *v_two32 = nullptr;
- gb_global irValue *v_false = nullptr;
- gb_global irValue *v_true = nullptr;
- gb_global irValue *v_raw_nil = nullptr;
- enum irAddrKind {
- irAddr_Default,
- // irAddr_Vector,
- irAddr_Map,
- irAddr_BitField,
- };
- struct irAddr {
- irAddrKind kind;
- irValue * addr;
- union {
- struct {
- irValue *map_key;
- Type * map_type;
- Type * map_result;
- };
- struct {
- i32 bit_field_value_index;
- };
- };
- // union {
- // struct { irValue *index; } Vector;
- // };
- };
- irAddr ir_addr(irValue *addr) {
- irAddr v = {irAddr_Default, addr};
- return v;
- }
- irAddr ir_addr_map(irValue *addr, irValue *map_key, Type *map_type, Type *map_result) {
- irAddr v = {irAddr_Map, addr};
- v.map_key = map_key;
- v.map_type = map_type;
- v.map_result = map_result;
- return v;
- }
- irAddr ir_addr_bit_field(irValue *addr, i32 bit_field_value_index) {
- irAddr v = {irAddr_BitField, addr};
- v.bit_field_value_index = bit_field_value_index;
- return v;
- }
- enum irDebugEncoding {
- irDebugBasicEncoding_Invalid = 0,
- irDebugBasicEncoding_address = 1,
- irDebugBasicEncoding_boolean = 2,
- irDebugBasicEncoding_float = 3,
- irDebugBasicEncoding_signed = 4,
- irDebugBasicEncoding_signed_char = 5,
- irDebugBasicEncoding_unsigned = 6,
- irDebugBasicEncoding_unsigned_char = 7,
- irDebugBasicEncoding_member = 13,
- irDebugBasicEncoding_pointer_type = 15,
- irDebugBasicEncoding_typedef = 22,
- irDebugBasicEncoding_array_type = 1,
- irDebugBasicEncoding_enumeration_type = 4,
- irDebugBasicEncoding_structure_type = 19,
- irDebugBasicEncoding_union_type = 23,
- };
- enum irDebugInfoKind {
- irDebugInfo_Invalid,
- irDebugInfo_CompileUnit,
- irDebugInfo_File,
- irDebugInfo_Scope,
- irDebugInfo_Proc,
- irDebugInfo_AllProcs,
- irDebugInfo_BasicType, // basic types
- irDebugInfo_ProcType,
- irDebugInfo_DerivedType, // pointer, typedef
- irDebugInfo_CompositeType, // array, struct, enum, (raw_)union
- irDebugInfo_Enumerator, // For irDebugInfo_CompositeType if enum
- irDebugInfo_GlobalVariable,
- irDebugInfo_LocalVariable,
- irDebugInfo_Count,
- };
- struct irDebugInfo {
- irDebugInfoKind kind;
- i32 id;
- union {
- struct {
- AstFile * file;
- String producer;
- irDebugInfo *all_procs;
- } CompileUnit;
- struct {
- AstFile *file;
- String filename;
- String directory;
- } File;
- struct {
- irDebugInfo *parent;
- irDebugInfo *file;
- TokenPos pos;
- Scope * scope; // Actual scope
- } Scope;
- struct {
- Entity * entity;
- String name;
- irDebugInfo *file;
- TokenPos pos;
- } Proc;
- struct {
- Array<irDebugInfo *> procs;
- } AllProcs;
- struct {
- String name;
- i32 size;
- i32 align;
- irDebugEncoding encoding;
- } BasicType;
- struct {
- irDebugInfo * return_type;
- Array<irDebugInfo *> param_types;
- } ProcType;
- struct {
- irDebugInfo * base_type;
- irDebugEncoding encoding;
- } DerivedType;
- struct {
- irDebugEncoding encoding;
- String name;
- String identifier;
- irDebugInfo * file;
- TokenPos pos;
- i32 size;
- i32 align;
- Array<irDebugInfo *> elements;
- } CompositeType;
- struct {
- String name;
- i64 value;
- } Enumerator;
- struct {
- String name;
- String linkage_name;
- irDebugInfo *scope;
- irDebugInfo *file;
- TokenPos pos;
- irValue *variable;
- irDebugInfo *declaration;
- } GlobalVariable;
- struct {
- String name;
- irDebugInfo *scope;
- irDebugInfo *file;
- TokenPos pos;
- i32 arg; // Non-zero if proc parameter
- irDebugInfo *type;
- } LocalVariable;
- };
- };
- struct irGen {
- irModule module;
- gbFile output_file;
- bool opt_called;
- String output_base;
- String output_name;
- };
- Type *ir_type(irValue *value);
- Type *ir_instr_type(irInstr *instr) {
- switch (instr->kind) {
- case irInstr_Local:
- return instr->Local.type;
- case irInstr_Load:
- return instr->Load.type;
- case irInstr_StructElementPtr:
- return instr->StructElementPtr.result_type;
- case irInstr_ArrayElementPtr:
- return instr->ArrayElementPtr.result_type;
- case irInstr_PtrOffset:
- return ir_type(instr->PtrOffset.address);
- case irInstr_Phi:
- return instr->Phi.type;
- case irInstr_StructExtractValue:
- return instr->StructExtractValue.result_type;
- case irInstr_UnionTagPtr:
- return instr->UnionTagPtr.type;
- case irInstr_UnionTagValue:
- return instr->UnionTagValue.type;
- case irInstr_UnaryOp:
- return instr->UnaryOp.type;
- case irInstr_BinaryOp:
- return instr->BinaryOp.type;
- case irInstr_Conv:
- return instr->Conv.to;
- case irInstr_Select:
- return ir_type(instr->Select.true_value);
- case irInstr_Call: {
- Type *pt = base_type(instr->Call.type);
- if (pt != nullptr) {
- if (pt->kind == Type_Tuple && pt->Tuple.variables.count == 1) {
- return pt->Tuple.variables[0]->type;
- }
- return pt;
- }
- return nullptr;
- }
- }
- return nullptr;
- }
- Type *ir_type(irValue *value) {
- switch (value->kind) {
- case irValue_Constant:
- return value->Constant.type;
- case irValue_ConstantSlice:
- return value->ConstantSlice.type;
- case irValue_Nil:
- return value->Nil.type;
- case irValue_Undef:
- return value->Undef.type;
- case irValue_TypeName:
- return value->TypeName.type;
- case irValue_Global:
- return value->Global.type;
- case irValue_Param:
- return value->Param.type;
- case irValue_Proc:
- return value->Proc.type;
- case irValue_Instr:
- return ir_instr_type(&value->Instr);
- }
- return nullptr;
- }
- bool ir_type_has_default_values(Type *t) {
- switch (t->kind) {
- case Type_Named:
- return ir_type_has_default_values(t->Named.base);
- case Type_Array:
- return ir_type_has_default_values(t->Array.elem);
- case Type_Struct:
- if (t->Struct.is_raw_union) return false;
- for_array(i, t->Struct.fields) {
- Entity *f = t->Struct.fields_in_src_order[i];
- if (f->kind != Entity_Variable) continue;
- if (f->Variable.default_is_nil) {
- // NOTE(bill): This is technically zero
- continue;
- } else if (f->Variable.default_value.kind != ExactValue_Invalid) {
- return true;
- } else if (f->Variable.default_is_undef) {
- return true;
- }
- bool sub = ir_type_has_default_values(f->type);
- if (sub) return true;
- }
- break;
- }
- return false;
- }
- irInstr *ir_get_last_instr(irBlock *block) {
- if (block != nullptr) {
- isize len = block->instrs.count;
- if (len > 0) {
- irValue *v = block->instrs[len-1];
- GB_ASSERT(v->kind == irValue_Instr);
- return &v->Instr;
- }
- }
- return nullptr;
- }
- bool ir_is_instr_terminating(irInstr *i) {
- if (i != nullptr) {
- switch (i->kind) {
- case irInstr_Return:
- case irInstr_Unreachable:
- return true;
- }
- }
- return false;
- }
- void ir_add_edge(irBlock *from, irBlock *to) {
- GB_ASSERT(from->instrs.count > 0);
- if (!ir_is_instr_terminating(ir_get_last_instr(from))) {
- array_add(&from->succs, to);
- array_add(&to->preds, from);
- }
- }
- void ir_set_instr_parent(irValue *instr, irBlock *parent) {
- if (instr->kind == irValue_Instr) {
- instr->Instr.parent = parent;
- }
- }
- Array<irValue *> *ir_value_referrers(irValue *v) {
- switch (v->kind) {
- case irValue_Global:
- return &v->Global.referrers;
- case irValue_Param:
- return &v->Param.referrers;
- case irValue_Proc: {
- if (v->Proc.parent != nullptr) {
- return &v->Proc.referrers;
- }
- return nullptr;
- }
- case irValue_Instr: {
- irInstr *i = &v->Instr;
- switch (i->kind) {
- case irInstr_Local:
- return &i->Local.referrers;
- }
- break;
- }
- }
- return nullptr;
- }
- ////////////////////////////////////////////////////////////////
- //
- // @Make
- //
- ////////////////////////////////////////////////////////////////
- void ir_module_add_value (irModule *m, Entity *e, irValue *v);
- irValue *ir_emit_zero_init (irProcedure *p, irValue *address);
- irValue *ir_emit_comment (irProcedure *p, String text);
- irValue *ir_emit_store (irProcedure *p, irValue *address, irValue *value);
- irValue *ir_emit_load (irProcedure *p, irValue *address);
- void ir_emit_jump (irProcedure *proc, irBlock *block);
- irValue *ir_emit_conv (irProcedure *proc, irValue *value, Type *t);
- irValue *ir_type_info (irProcedure *proc, Type *type);
- irValue *ir_build_expr (irProcedure *proc, AstNode *expr);
- void ir_build_stmt (irProcedure *proc, AstNode *node);
- irValue *ir_build_cond (irProcedure *proc, AstNode *cond, irBlock *true_block, irBlock *false_block);
- void ir_build_defer_stmt (irProcedure *proc, irDefer d);
- irAddr ir_build_addr (irProcedure *proc, AstNode *expr);
- void ir_build_proc (irValue *value, irProcedure *parent);
- void ir_gen_global_type_name(irModule *m, Entity *e, String name);
- irValue *ir_get_type_info_ptr (irProcedure *proc, Type *type);
- irValue *ir_alloc_value(gbAllocator a, irValueKind kind) {
- irValue *v = gb_alloc_item(a, irValue);
- v->kind = kind;
- return v;
- }
- irValue *ir_alloc_instr(irProcedure *proc, irInstrKind kind) {
- irValue *v = ir_alloc_value(proc->module->allocator, irValue_Instr);
- v->Instr.kind = kind;
- proc->instr_count++;
- return v;
- }
- irDebugInfo *ir_alloc_debug_info(gbAllocator a, irDebugInfoKind kind) {
- irDebugInfo *di = gb_alloc_item(a, irDebugInfo);
- di->kind = kind;
- return di;
- }
- irValue *ir_value_type_name(gbAllocator a, String name, Type *type) {
- irValue *v = ir_alloc_value(a, irValue_TypeName);
- v->TypeName.name = name;
- v->TypeName.type = type;
- return v;
- }
- irValue *ir_value_global(gbAllocator a, Entity *e, irValue *value) {
- irValue *v = ir_alloc_value(a, irValue_Global);
- v->Global.entity = e;
- v->Global.type = make_type_pointer(a, e->type);
- v->Global.value = value;
- array_init(&v->Global.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
- return v;
- }
- irValue *ir_value_param(gbAllocator a, irProcedure *parent, Entity *e, Type *abi_type) {
- irValue *v = ir_alloc_value(a, irValue_Param);
- v->Param.kind = irParamPass_Value;
- v->Param.parent = parent;
- v->Param.entity = e;
- v->Param.original_type = e->type;
- v->Param.type = abi_type;
- if (abi_type != e->type) {
- if (is_type_pointer(abi_type)) {
- v->Param.kind = irParamPass_Pointer;
- } else if (is_type_integer(abi_type)) {
- v->Param.kind = irParamPass_Integer;
- } else {
- GB_PANIC("Invalid abi type pass kind");
- }
- }
- array_init(&v->Param.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
- return v;
- }
- irValue *ir_value_nil(gbAllocator a, Type *type) {
- irValue *v = ir_alloc_value(a, irValue_Nil);
- v->Nil.type = type;
- return v;
- }
- irValue *ir_value_undef(gbAllocator a, Type *type) {
- irValue *v = ir_alloc_value(a, irValue_Undef);
- v->Undef.type = type;
- return v;
- }
- String ir_get_global_name(irModule *m, irValue *v) {
- if (v->kind != irValue_Global) {
- return str_lit("");
- }
- irValueGlobal *g = &v->Global;
- Entity *e = g->entity;
- String name = e->token.string;
- String *found = map_get(&m->entity_names, hash_entity(e));
- if (found != nullptr) {
- name = *found;
- } else {
- GB_ASSERT(name.len > 0);
- }
- return name;
- }
- void ir_add_entity_name(irModule *m, Entity *e, String name) {
- GB_ASSERT(name.len > 0);
- map_set(&m->entity_names, hash_entity(e), name);
- }
- irValue *ir_instr_local(irProcedure *p, Entity *e, bool zero_initialized) {
- irValue *v = ir_alloc_instr(p, irInstr_Local);
- irInstr *i = &v->Instr;
- i->Local.entity = e;
- i->Local.type = make_type_pointer(p->module->allocator, e->type);
- i->Local.zero_initialized = zero_initialized;
- i->Local.alignment = type_align_of(p->module->allocator, e->type);
- array_init(&i->Local.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
- ir_module_add_value(p->module, e, v);
- return v;
- }
- irValue *ir_instr_store(irProcedure *p, irValue *address, irValue *value, bool atomic) {
- irValue *v = ir_alloc_instr(p, irInstr_Store);
- irInstr *i = &v->Instr;
- i->Store.address = address;
- i->Store.value = value;
- i->Store.atomic = atomic;
- return v;
- }
- irValue *ir_instr_zero_init(irProcedure *p, irValue *address) {
- irValue *v = ir_alloc_instr(p, irInstr_ZeroInit);
- irInstr *i = &v->Instr;
- i->ZeroInit.address = address;
- return v;
- }
- irValue *ir_instr_load(irProcedure *p, irValue *address) {
- irValue *v = ir_alloc_instr(p, irInstr_Load);
- irInstr *i = &v->Instr;
- i->Load.address = address;
- i->Load.type = type_deref(ir_type(address));
- return v;
- }
- irValue *ir_instr_array_element_ptr(irProcedure *p, irValue *address, irValue *elem_index) {
- irValue *v = ir_alloc_instr(p, irInstr_ArrayElementPtr);
- irInstr *i = &v->Instr;
- Type *t = ir_type(address);
- GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
- t = base_type(type_deref(t));
- GB_ASSERT(is_type_array(t) || is_type_vector(t));
- Type *result_type = make_type_pointer(p->module->allocator, t->Array.elem);
- i->ArrayElementPtr.address = address;
- i->ArrayElementPtr.elem_index = elem_index;
- i->ArrayElementPtr.result_type = result_type;
- GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
- "%s", type_to_string(ir_type(address)));
- return v;
- }
- irValue *ir_instr_struct_element_ptr(irProcedure *p, irValue *address, i32 elem_index, Type *result_type) {
- irValue *v = ir_alloc_instr(p, irInstr_StructElementPtr);
- irInstr *i = &v->Instr;
- i->StructElementPtr.address = address;
- i->StructElementPtr.elem_index = elem_index;
- i->StructElementPtr.result_type = result_type;
- GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
- "%s", type_to_string(ir_type(address)));
- return v;
- }
- irValue *ir_instr_ptr_offset(irProcedure *p, irValue *address, irValue *offset) {
- irValue *v = ir_alloc_instr(p, irInstr_PtrOffset);
- irInstr *i = &v->Instr;
- i->PtrOffset.address = address;
- i->PtrOffset.offset = offset;
- GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
- "%s", type_to_string(ir_type(address)));
- GB_ASSERT_MSG(is_type_integer(ir_type(offset)),
- "%s", type_to_string(ir_type(address)));
- return v;
- }
- irValue *ir_instr_struct_extract_value(irProcedure *p, irValue *address, i32 index, Type *result_type) {
- irValue *v = ir_alloc_instr(p, irInstr_StructExtractValue);
- irInstr *i = &v->Instr;
- i->StructExtractValue.address = address;
- i->StructExtractValue.index = index;
- i->StructExtractValue.result_type = result_type;
- return v;
- }
- irValue *ir_instr_union_tag_ptr(irProcedure *p, irValue *address) {
- irValue *v = ir_alloc_instr(p, irInstr_UnionTagPtr);
- irInstr *i = &v->Instr;
- i->UnionTagPtr.address = address;
- // i->UnionTagPtr.type = make_type_pointer(p->module->allocator, t_type_info_ptr);
- Type *u = type_deref(ir_type(address));
- i->UnionTagPtr.type = make_type_pointer(p->module->allocator, union_tag_type(u));
- return v;
- }
- irValue *ir_instr_union_tag_value(irProcedure *p, irValue *address) {
- irValue *v = ir_alloc_instr(p, irInstr_UnionTagValue);
- irInstr *i = &v->Instr;
- i->UnionTagValue.address = address;
- // i->UnionTagValue.type = t_type_info_ptr;
- // i->UnionTagValue.type = t_int;
- Type *u = type_deref(ir_type(address));
- i->UnionTagPtr.type = union_tag_type(u);
- return v;
- }
- irValue *ir_instr_unary_op(irProcedure *p, TokenKind op, irValue *expr, Type *type) {
- irValue *v = ir_alloc_instr(p, irInstr_UnaryOp);
- irInstr *i = &v->Instr;
- i->UnaryOp.op = op;
- i->UnaryOp.expr = expr;
- i->UnaryOp.type = type;
- return v;
- }
- irValue *ir_instr_binary_op(irProcedure *p, TokenKind op, irValue *left, irValue *right, Type *type) {
- irValue *v = ir_alloc_instr(p, irInstr_BinaryOp);
- irInstr *i = &v->Instr;
- i->BinaryOp.op = op;
- i->BinaryOp.left = left;
- i->BinaryOp.right = right;
- i->BinaryOp.type = type;
- return v;
- }
- irValue *ir_instr_jump(irProcedure *p, irBlock *block) {
- irValue *v = ir_alloc_instr(p, irInstr_Jump);
- irInstr *i = &v->Instr;
- i->Jump.block = block;
- return v;
- }
- irValue *ir_instr_if(irProcedure *p, irValue *cond, irBlock *true_block, irBlock *false_block) {
- irValue *v = ir_alloc_instr(p, irInstr_If);
- irInstr *i = &v->Instr;
- i->If.cond = cond;
- i->If.true_block = true_block;
- i->If.false_block = false_block;
- return v;
- }
- irValue *ir_instr_phi(irProcedure *p, Array<irValue *> edges, Type *type) {
- irValue *v = ir_alloc_instr(p, irInstr_Phi);
- irInstr *i = &v->Instr;
- i->Phi.edges = edges;
- i->Phi.type = type;
- return v;
- }
- irValue *ir_instr_unreachable(irProcedure *p) {
- irValue *v = ir_alloc_instr(p, irInstr_Unreachable);
- return v;
- }
- irValue *ir_instr_return(irProcedure *p, irValue *value) {
- irValue *v = ir_alloc_instr(p, irInstr_Return);
- v->Instr.Return.value = value;
- return v;
- }
- irValue *ir_instr_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
- irValue *v = ir_alloc_instr(p, irInstr_Select);
- v->Instr.Select.cond = cond;
- v->Instr.Select.true_value = t;
- v->Instr.Select.false_value = f;
- return v;
- }
- irValue *ir_instr_call(irProcedure *p, irValue *value, irValue *return_ptr, irValue **args, isize arg_count, Type *result_type, irValue *context_ptr) {
- irValue *v = ir_alloc_instr(p, irInstr_Call);
- v->Instr.Call.value = value;
- v->Instr.Call.return_ptr = return_ptr;
- v->Instr.Call.args = args;
- v->Instr.Call.arg_count = arg_count;
- v->Instr.Call.type = result_type;
- v->Instr.Call.context_ptr = context_ptr;
- return v;
- }
- irValue *ir_instr_conv(irProcedure *p, irConvKind kind, irValue *value, Type *from, Type *to) {
- irValue *v = ir_alloc_instr(p, irInstr_Conv);
- v->Instr.Conv.kind = kind;
- v->Instr.Conv.value = value;
- v->Instr.Conv.from = from;
- v->Instr.Conv.to = to;
- return v;
- }
- irValue *ir_instr_comment(irProcedure *p, String text) {
- irValue *v = ir_alloc_instr(p, irInstr_Comment);
- v->Instr.Comment.text = text;
- return v;
- }
- irValue *ir_instr_debug_declare(irProcedure *p, irDebugInfo *debug_info, AstNode *expr, Entity *entity, bool is_addr, irValue *value) {
- irValue *v = ir_alloc_instr(p, irInstr_DebugDeclare);
- v->Instr.DebugDeclare.debug_info = debug_info;
- v->Instr.DebugDeclare.expr = expr;
- v->Instr.DebugDeclare.entity = entity;
- v->Instr.DebugDeclare.is_addr = is_addr;
- v->Instr.DebugDeclare.value = value;
- return v;
- }
- irValue *ir_value_constant(gbAllocator a, Type *type, ExactValue value) {
- irValue *v = ir_alloc_value(a, irValue_Constant);
- v->Constant.type = type;
- v->Constant.value = value;
- return v;
- }
- irValue *ir_value_constant_slice(gbAllocator a, Type *type, irValue *backing_array, i64 count) {
- irValue *v = ir_alloc_value(a, irValue_ConstantSlice);
- v->ConstantSlice.type = type;
- v->ConstantSlice.backing_array = backing_array;
- v->ConstantSlice.count = count;
- return v;
- }
- irValue *ir_emit(irProcedure *proc, irValue *instr) {
- GB_ASSERT(instr->kind == irValue_Instr);
- irBlock *b = proc->curr_block;
- instr->Instr.parent = b;
- if (b != nullptr) {
- irInstr *i = ir_get_last_instr(b);
- if (!ir_is_instr_terminating(i)) {
- array_add(&b->instrs, instr);
- }
- } else if (instr->Instr.kind != irInstr_Unreachable) {
- GB_PANIC("ir_emit: Instruction missing parent block");
- }
- return instr;
- }
- irValue *ir_const_int(gbAllocator a, i64 i) {
- return ir_value_constant(a, t_int, exact_value_i64(i));
- }
- irValue *ir_const_i32(gbAllocator a, i32 i) {
- return ir_value_constant(a, t_i32, exact_value_i64(i));
- }
- irValue *ir_const_u32(gbAllocator a, u32 i) {
- return ir_value_constant(a, t_u32, exact_value_i64(i));
- }
- irValue *ir_const_i64(gbAllocator a, i64 i) {
- return ir_value_constant(a, t_i64, exact_value_i64(i));
- }
- irValue *ir_const_u64(gbAllocator a, u64 i) {
- return ir_value_constant(a, t_u64, exact_value_i64(i));
- }
- irValue *ir_const_f32(gbAllocator a, f32 f) {
- return ir_value_constant(a, t_f32, exact_value_float(f));
- }
- irValue *ir_const_f64(gbAllocator a, f64 f) {
- return ir_value_constant(a, t_f64, exact_value_float(f));
- }
- irValue *ir_const_bool(gbAllocator a, bool b) {
- return ir_value_constant(a, t_bool, exact_value_bool(b != 0));
- }
- irValue *ir_const_string(gbAllocator a, String s) {
- return ir_value_constant(a, t_string, exact_value_string(s));
- }
- irValue *ir_value_procedure(gbAllocator a, irModule *m, Entity *entity, Type *type, AstNode *type_expr, AstNode *body, String name) {
- irValue *v = ir_alloc_value(a, irValue_Proc);
- v->Proc.module = m;
- v->Proc.entity = entity;
- v->Proc.type = type;
- v->Proc.type_expr = type_expr;
- v->Proc.body = body;
- v->Proc.name = name;
- array_init(&v->Proc.referrers, heap_allocator()); // TODO(bill): replace heap allocator
- Type *t = base_type(type);
- GB_ASSERT(is_type_proc(t));
- array_init(&v->Proc.params, heap_allocator(), t->Proc.param_count);
- return v;
- }
- irValue *ir_generate_array(irModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
- gbAllocator a = m->allocator;
- Token token = {Token_Ident};
- isize name_len = prefix.len + 10;
- char *text = gb_alloc_array(a, char, name_len);
- gb_snprintf(text, name_len,
- "%.*s-%llx", LIT(prefix), cast(unsigned long long)id);
- String s = make_string_c(text);
- Entity *e = make_entity_variable(a, nullptr,
- make_token_ident(s),
- make_type_array(a, elem_type, count),
- false);
- irValue *value = ir_value_global(a, e, nullptr);
- value->Global.is_private = true;
- ir_module_add_value(m, e, value);
- map_set(&m->members, hash_string(s), value);
- return value;
- }
- irBlock *ir_new_block(irProcedure *proc, AstNode *node, char *label) {
- Scope *scope = nullptr;
- if (node != nullptr) {
- scope = scope_of_node(proc->module->info, node);
- GB_ASSERT_MSG(scope != nullptr, "Block scope not found for %.*s", LIT(ast_node_strings[node->kind]));
- }
- irValue *v = ir_alloc_value(proc->module->allocator, irValue_Block);
- v->Block.label = make_string_c(label);
- v->Block.node = node;
- v->Block.scope = scope;
- v->Block.parent = proc;
- // TODO(bill): Is this correct or even needed?
- v->Block.scope_index = proc->scope_index;
- array_init(&v->Block.instrs, heap_allocator());
- array_init(&v->Block.locals, heap_allocator());
- array_init(&v->Block.preds, heap_allocator());
- array_init(&v->Block.succs, heap_allocator());
- irBlock *block = &v->Block;
- return block;
- }
- void ir_add_block_to_proc(irProcedure *proc, irBlock *b) {
- for_array(i, proc->blocks) {
- if (proc->blocks[i] == b) {
- return;
- }
- }
- array_add(&proc->blocks, b);
- b->index = proc->block_count++;
- }
- void ir_start_block(irProcedure *proc, irBlock *block) {
- proc->curr_block = block;
- if (block != nullptr) {
- ir_add_block_to_proc(proc, block);
- }
- }
- irDefer ir_add_defer_node(irProcedure *proc, isize scope_index, AstNode *stmt) {
- irDefer d = {irDefer_Node};
- d.scope_index = scope_index;
- d.block = proc->curr_block;
- d.stmt = stmt;
- array_add(&proc->defer_stmts, d);
- return d;
- }
- irDefer ir_add_defer_instr(irProcedure *proc, isize scope_index, irValue *instr) {
- irDefer d = {irDefer_Instr};
- d.scope_index = proc->scope_index;
- d.block = proc->curr_block;
- d.instr = instr; // NOTE(bill): It will make a copy everytime it is called
- array_add(&proc->defer_stmts, d);
- return d;
- }
- irValue *ir_add_module_constant(irModule *m, Type *type, ExactValue value) {
- gbAllocator a = m->allocator;
- // gbAllocator a = gb_heap_allocator();
- if (is_type_slice(type)) {
- ast_node(cl, CompoundLit, value.value_compound);
- isize count = cl->elems.count;
- if (count == 0) {
- return ir_value_nil(a, type);
- }
- Type *elem = base_type(type)->Slice.elem;
- Type *t = make_type_array(a, elem, count);
- irValue *backing_array = ir_add_module_constant(m, t, value);
- isize max_len = 7+8+1;
- u8 *str = cast(u8 *)gb_alloc_array(a, u8, max_len);
- isize len = gb_snprintf(cast(char *)str, max_len, "__csba$%x", m->global_array_index);
- m->global_array_index++;
- String name = make_string(str, len-1);
- Entity *e = make_entity_constant(a, nullptr, make_token_ident(name), t, value);
- irValue *g = ir_value_global(a, e, backing_array);
- ir_module_add_value(m, e, g);
- map_set(&m->members, hash_string(name), g);
- return ir_value_constant_slice(a, type, g, count);
- }
- return ir_value_constant(a, type, value);
- }
- irValue *ir_add_global_string_array(irModule *m, String string) {
- // TODO(bill): Should this use the arena allocator or the heap allocator?
- // Strings could be huge!
- // gbAllocator a = m->allocator;
- gbAllocator a = gb_heap_allocator();
- isize max_len = 6+8+1;
- u8 *str = cast(u8 *)gb_alloc_array(a, u8, max_len);
- isize len = gb_snprintf(cast(char *)str, max_len, "__str$%x", m->global_string_index);
- m->global_string_index++;
- String name = make_string(str, len-1);
- Token token = {Token_String};
- token.string = name;
- Type *type = make_type_array(a, t_u8, string.len+1);
- ExactValue ev = exact_value_string(string);
- Entity *entity = make_entity_constant(a, nullptr, token, type, ev);
- irValue *g = ir_value_global(a, entity, ir_add_module_constant(m, type, ev));
- g->Global.is_private = true;
- g->Global.is_unnamed_addr = true;
- // g->Global.is_constant = true;
- ir_module_add_value(m, entity, g);
- map_set(&m->members, hash_string(name), g);
- return g;
- }
- irValue *ir_add_local(irProcedure *proc, Entity *e, AstNode *expr, bool zero_initialized) {
- irBlock *b = proc->decl_block; // all variables must be in the first block
- irValue *instr = ir_instr_local(proc, e, true);
- instr->Instr.parent = b;
- array_add(&b->instrs, instr);
- array_add(&b->locals, instr);
- proc->local_count++;
- if (zero_initialized) {
- ir_emit_zero_init(proc, instr);
- }
- if (expr != nullptr && proc->entity != nullptr) {
- irDebugInfo *di = *map_get(&proc->module->debug_info, hash_entity(proc->entity));
- ir_emit(proc, ir_instr_debug_declare(proc, di, expr, e, true, instr));
- }
- return instr;
- }
- irValue *ir_add_local_for_identifier(irProcedure *proc, AstNode *ident, bool zero_initialized) {
- Entity *e = entity_of_ident(proc->module->info, ident);
- if (e != nullptr) {
- String name = e->token.string;
- ir_emit_comment(proc, name);
- if (e->kind == Entity_Variable &&
- e->Variable.is_foreign) {
- HashKey key = hash_string(name);
- irValue **prev_value = map_get(&proc->module->members, key);
- if (prev_value == nullptr) {
- // NOTE(bill): Don't do mutliple declarations in the IR
- irValue *g = ir_value_global(proc->module->allocator, e, nullptr);
- g->Global.name = name;
- g->Global.is_foreign = true;
- ir_module_add_value(proc->module, e, g);
- map_set(&proc->module->members, key, g);
- return g;
- } else {
- return *prev_value;
- }
- }
- return ir_add_local(proc, e, ident, zero_initialized);
- }
- return nullptr;
- }
- irValue *ir_add_local_generated(irProcedure *proc, Type *type, bool zero_initialized = true) {
- GB_ASSERT(type != nullptr);
- Scope *scope = nullptr;
- if (proc->curr_block) {
- scope = proc->curr_block->scope;
- }
- Entity *e = make_entity_variable(proc->module->allocator,
- scope,
- empty_token,
- type, false);
- return ir_add_local(proc, e, nullptr, zero_initialized);
- }
- irValue *ir_add_global_generated(irModule *m, Type *type, irValue *value) {
- GB_ASSERT(type != nullptr);
- gbAllocator a = m->allocator;
- isize max_len = 7+8+1;
- u8 *str = cast(u8 *)gb_alloc_array(a, u8, max_len);
- isize len = gb_snprintf(cast(char *)str, max_len, "__ggv$%x", m->global_generated_index);
- m->global_generated_index++;
- String name = make_string(str, len-1);
- Scope *scope = nullptr;
- Entity *e = make_entity_variable(a,
- scope,
- make_token_ident(name),
- type, false);
- irValue *g = ir_value_global(a, e, value);
- ir_module_add_value(m, e, g);
- map_set(&m->members, hash_string(name), g);
- return g;
- }
- irValue *ir_add_param(irProcedure *proc, Entity *e, AstNode *expr, Type *abi_type) {
- irValue *v = ir_value_param(proc->module->allocator, proc, e, abi_type);
- irValueParam *p = &v->Param;
- switch (p->kind) {
- case irParamPass_Value: {
- irValue *l = ir_add_local(proc, e, expr, false);
- ir_emit_store(proc, l, v);
- return v;
- }
- case irParamPass_Pointer: {
- ir_module_add_value(proc->module, e, v);
- return ir_emit_load(proc, v);
- }
- case irParamPass_Integer: {
- irValue *l = ir_add_local(proc, e, expr, false);
- irValue *iptr = ir_emit_conv(proc, l, make_type_pointer(proc->module->allocator, p->type));
- ir_emit_store(proc, iptr, v);
- return ir_emit_load(proc, l);
- }
- }
- GB_PANIC("Unreachable");
- return nullptr;
- }
- ////////////////////////////////////////////////////////////////
- //
- // @Debug
- //
- ////////////////////////////////////////////////////////////////
- irDebugInfo *ir_add_debug_info_file(irProcedure *proc, AstFile *file) {
- // if (!proc->module->generate_debug_info) {
- // return nullptr;
- // }
- GB_ASSERT(file != nullptr);
- irDebugInfo *di = ir_alloc_debug_info(proc->module->allocator, irDebugInfo_File);
- di->File.file = file;
- String filename = file->tokenizer.fullpath;
- String directory = filename;
- isize slash_index = 0;
- for (isize i = filename.len-1; i >= 0; i--) {
- if (filename[i] == '\\' ||
- filename[i] == '/') {
- break;
- }
- slash_index = i;
- }
- directory.len = slash_index-1;
- filename.text = filename.text + slash_index;
- filename.len -= slash_index;
- di->File.filename = filename;
- di->File.directory = directory;
- map_set(&proc->module->debug_info, hash_ast_file(file), di);
- return di;
- }
- irDebugInfo *ir_add_debug_info_proc(irProcedure *proc, Entity *entity, String name, irDebugInfo *file) {
- // if (!proc->module->generate_debug_info) {
- // return nullptr;
- // }
- GB_ASSERT(entity != nullptr);
- irDebugInfo *di = ir_alloc_debug_info(proc->module->allocator, irDebugInfo_Proc);
- di->Proc.entity = entity;
- di->Proc.name = name;
- di->Proc.file = file;
- di->Proc.pos = entity->token.pos;
- map_set(&proc->module->debug_info, hash_entity(entity), di);
- return di;
- }
- ////////////////////////////////////////////////////////////////
- //
- // @Emit
- //
- ////////////////////////////////////////////////////////////////
- irValue *ir_emit_store(irProcedure *p, irValue *address, irValue *value) {
- #if 1
- // NOTE(bill): Sanity check
- Type *a = type_deref(ir_type(address));
- Type *b = ir_type(value);
- if (!is_type_untyped(b)) {
- GB_ASSERT_MSG(are_types_identical(core_type(a), core_type(b)), "%s %s", type_to_string(a), type_to_string(b));
- }
- #endif
- return ir_emit(p, ir_instr_store(p, address, value, false));
- }
- irValue *ir_emit_load(irProcedure *p, irValue *address) {
- GB_ASSERT(address != nullptr);
- return ir_emit(p, ir_instr_load(p, address));
- }
- irValue *ir_emit_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
- return ir_emit(p, ir_instr_select(p, cond, t, f));
- }
- irValue *ir_emit_zero_init(irProcedure *p, irValue *address) {
- return ir_emit(p, ir_instr_zero_init(p, address));
- }
- irValue *ir_emit_comment(irProcedure *p, String text) {
- return ir_emit(p, ir_instr_comment(p, text));
- }
- irValue *ir_copy_value_to_ptr(irProcedure *proc, irValue *val, Type *new_type, i64 alignment) {
- i64 type_alignment = type_align_of(proc->module->allocator, new_type);
- if (alignment < type_alignment) {
- alignment = type_alignment;
- }
- irValue *ptr = ir_add_local_generated(proc, new_type);
- ptr->Instr.Local.alignment = alignment;
- ir_emit_store(proc, ptr, val);
- return ptr;
- }
- irValue *ir_emit_bitcast(irProcedure *proc, irValue *data, Type *type) {
- return ir_emit(proc, ir_instr_conv(proc, irConv_bitcast, data, ir_type(data), type));
- }
- irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t);
- irValue *ir_emit_global_call(irProcedure *proc, char *name_, irValue **args, isize arg_count);
- irValue *ir_find_or_generate_context_ptr(irProcedure *proc) {
- if (proc->context_stack.count > 0) {
- return proc->context_stack[proc->context_stack.count-1];
- }
- irValue *c = ir_add_local_generated(proc, t_context);
- ir_emit_store(proc, c, ir_emit_load(proc, proc->module->global_default_context));
- array_add(&proc->context_stack, c);
- return c;
- }
- irValue *ir_emit_call(irProcedure *p, irValue *value, irValue **args, isize arg_count) {
- Type *pt = base_type(ir_type(value));
- GB_ASSERT(pt->kind == Type_Proc);
- Type *results = pt->Proc.results;
- irValue *context_ptr = nullptr;
- if (pt->Proc.calling_convention == ProcCC_Odin) {
- context_ptr = ir_find_or_generate_context_ptr(p);
- }
- isize param_count = pt->Proc.param_count;
- if (pt->Proc.c_vararg) {
- GB_ASSERT(param_count-1 <= arg_count);
- } else {
- GB_ASSERT(param_count == arg_count);
- }
- for (isize i = 0; i < param_count; i++) {
- Entity *e = pt->Proc.params->Tuple.variables[i];
- if (e->kind != Entity_Variable) {
- continue;
- }
- Type *original_type = e->type;
- Type *new_type = pt->Proc.abi_compat_params[i];
- if (original_type != new_type) {
- if (is_type_pointer(new_type)) {
- args[i] = ir_copy_value_to_ptr(p, args[i], original_type, 16);
- } else if (is_type_integer(new_type)) {
- args[i] = ir_emit_transmute(p, args[i], new_type);
- }
- }
- }
- Type *abi_rt = pt->Proc.abi_compat_result_type;
- Type *rt = reduce_tuple_to_single_type(results);
- if (pt->Proc.return_by_pointer) {
- irValue *return_ptr = ir_add_local_generated(p, rt);
- GB_ASSERT(is_type_pointer(ir_type(return_ptr)));
- ir_emit(p, ir_instr_call(p, value, return_ptr, args, arg_count, nullptr, context_ptr));
- return ir_emit_load(p, return_ptr);
- }
- irValue *result = ir_emit(p, ir_instr_call(p, value, nullptr, args, arg_count, abi_rt, context_ptr));
- if (abi_rt != results) {
- result = ir_emit_transmute(p, result, rt);
- }
- return result;
- }
- irValue *ir_emit_global_call(irProcedure *proc, char *name_, irValue **args, isize arg_count) {
- String name = make_string_c(name_);
- irValue **found = map_get(&proc->module->members, hash_string(name));
- GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(name));
- irValue *gp = *found;
- return ir_emit_call(proc, gp, args, arg_count);
- }
- void ir_emit_defer_stmts(irProcedure *proc, irDeferExitKind kind, irBlock *block) {
- isize count = proc->defer_stmts.count;
- isize i = count;
- while (i --> 0) {
- irDefer d = proc->defer_stmts[i];
- if (kind == irDeferExit_Default) {
- if (proc->scope_index == d.scope_index &&
- d.scope_index > 1) {
- ir_build_defer_stmt(proc, d);
- array_pop(&proc->defer_stmts);
- continue;
- } else {
- break;
- }
- } else if (kind == irDeferExit_Return) {
- ir_build_defer_stmt(proc, d);
- } else if (kind == irDeferExit_Branch) {
- GB_ASSERT(block != nullptr);
- isize lower_limit = block->scope_index+1;
- if (lower_limit < d.scope_index) {
- ir_build_defer_stmt(proc, d);
- }
- }
- }
- }
- void ir_open_scope(irProcedure *proc) {
- proc->scope_index++;
- }
- void ir_close_scope(irProcedure *proc, irDeferExitKind kind, irBlock *block) {
- ir_emit_defer_stmts(proc, kind, block);
- GB_ASSERT(proc->scope_index > 0);
- proc->scope_index--;
- }
- void ir_emit_unreachable(irProcedure *proc) {
- ir_emit(proc, ir_instr_unreachable(proc));
- }
- void ir_emit_return(irProcedure *proc, irValue *v) {
- ir_emit_defer_stmts(proc, irDeferExit_Return, nullptr);
- if (proc->type->Proc.return_by_pointer) {
- ir_emit_store(proc, proc->return_ptr, v);
- ir_emit(proc, ir_instr_return(proc, nullptr));
- } else {
- Type *abi_rt = proc->type->Proc.abi_compat_result_type;
- if (abi_rt != proc->type->Proc.results) {
- v = ir_emit_transmute(proc, v, abi_rt);
- }
- ir_emit(proc, ir_instr_return(proc, v));
- }
- }
- void ir_emit_jump(irProcedure *proc, irBlock *target_block) {
- irBlock *b = proc->curr_block;
- if (b == nullptr) {
- return;
- }
- ir_emit(proc, ir_instr_jump(proc, target_block));
- ir_add_edge(b, target_block);
- ir_start_block(proc, nullptr);
- }
- void ir_emit_if(irProcedure *proc, irValue *cond, irBlock *true_block, irBlock *false_block) {
- irBlock *b = proc->curr_block;
- if (b == nullptr) {
- return;
- }
- ir_emit(proc, ir_instr_if(proc, cond, true_block, false_block));
- ir_add_edge(b, true_block);
- ir_add_edge(b, false_block);
- ir_start_block(proc, nullptr);
- }
- void ir_emit_startup_runtime(irProcedure *proc) {
- GB_ASSERT(proc->parent == nullptr && proc->name == "main");
- ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
- }
- irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index);
- irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right);
- irValue *ir_gen_map_header(irProcedure *proc, irValue *map_val, Type *map_type) {
- GB_ASSERT_MSG(is_type_pointer(ir_type(map_val)), "%s", type_to_string(ir_type(map_val)));
- gbAllocator a = proc->module->allocator;
- irValue *h = ir_add_local_generated(proc, t_map_header);
- map_type = base_type(map_type);
- Type *key_type = map_type->Map.key;
- Type *val_type = map_type->Map.value;
- // NOTE(bill): Removes unnecessary allocation if split gep
- irValue *gep0 = ir_emit_struct_ep(proc, h, 0);
- irValue *m = ir_emit_conv(proc, map_val, type_deref(ir_type(gep0)));
- ir_emit_store(proc, gep0, m);
- if (is_type_string(key_type)) {
- ir_emit_store(proc, ir_emit_struct_ep(proc, h, 1), v_true);
- }
- i64 entry_size = type_size_of(a, map_type->Map.entry_type);
- i64 entry_align = type_align_of(a, map_type->Map.entry_type);
- i64 value_offset = type_offset_of(a, map_type->Map.entry_type, 2);
- i64 value_size = type_size_of(a, map_type->Map.value);
- ir_emit_store(proc, ir_emit_struct_ep(proc, h, 2), ir_const_int(a, entry_size));
- ir_emit_store(proc, ir_emit_struct_ep(proc, h, 3), ir_const_int(a, entry_align));
- ir_emit_store(proc, ir_emit_struct_ep(proc, h, 4), ir_const_int(a, value_offset));
- ir_emit_store(proc, ir_emit_struct_ep(proc, h, 5), ir_const_int(a, value_size));
- return ir_emit_load(proc, h);
- }
- irValue *ir_gen_map_key(irProcedure *proc, irValue *key, Type *key_type) {
- Type *hash_type = t_u128;
- irValue *v = ir_add_local_generated(proc, t_map_key);
- Type *t = base_type(ir_type(key));
- key = ir_emit_conv(proc, key, key_type);
- if (is_type_integer(t)) {
- ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, key, hash_type));
- } else if (is_type_pointer(t)) {
- irValue *p = ir_emit_conv(proc, key, t_uint);
- ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, p, hash_type));
- } else if (is_type_float(t)) {
- irValue *bits = nullptr;
- i64 size = type_size_of(proc->module->allocator, t);
- switch (8*size) {
- case 32: bits = ir_emit_transmute(proc, key, t_u32); break;
- case 64: bits = ir_emit_transmute(proc, key, t_u64); break;
- default: GB_PANIC("Unhandled float size: %lld bits", size); break;
- }
- ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, bits, hash_type));
- } else if (is_type_string(t)) {
- irValue *str = ir_emit_conv(proc, key, t_string);
- irValue *hashed_str = nullptr;
- if (str->kind == irValue_Constant) {
- ExactValue ev = str->Constant.value;
- GB_ASSERT(ev.kind == ExactValue_String);
- u128 hs = fnv128a(ev.value_string.text, ev.value_string.len);
- hashed_str = ir_value_constant(proc->module->allocator, t_u128, exact_value_u128(hs));
- } else {
- irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 1);
- args[0] = str;
- hashed_str = ir_emit_global_call(proc, "__default_hash_string", args, 1);
- }
- ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), hashed_str);
- ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), str);
- } else {
- GB_PANIC("Unhandled map key type");
- }
- return ir_emit_load(proc, v);
- }
- // NOTE(bill): Returns nullptr if not possible
- irValue *ir_address_from_load_or_generate_local(irProcedure *proc, irValue *val) {
- if (val->kind == irValue_Instr) {
- if (val->Instr.kind == irInstr_Load) {
- return val->Instr.Load.address;
- }
- }
- Type *type = ir_type(val);
- irValue *local = ir_add_local_generated(proc, type);
- ir_emit_store(proc, local, val);
- return local;
- }
- Type *ir_addr_type(irAddr addr) {
- if (addr.addr == nullptr) {
- return nullptr;
- }
- if (addr.kind == irAddr_Map) {
- Type *t = base_type(addr.map_type);
- GB_ASSERT(is_type_map(t));
- return t->Map.value;
- }
- Type *t = ir_type(addr.addr);
- GB_ASSERT(is_type_pointer(t));
- return type_deref(t);
- }
- irValue *ir_insert_dynamic_map_key_and_value(irProcedure *proc, irValue *addr, Type *map_type,
- irValue *map_key, irValue *map_value) {
- map_type = base_type(map_type);
- irValue *h = ir_gen_map_header(proc, addr, map_type);
- irValue *key = ir_gen_map_key(proc, map_key, map_type->Map.key);
- irValue *v = ir_emit_conv(proc, map_value, map_type->Map.value);
- irValue *ptr = ir_add_local_generated(proc, ir_type(v));
- ir_emit_store(proc, ptr, v);
- irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 3);
- args[0] = h;
- args[1] = key;
- args[2] = ir_emit_conv(proc, ptr, t_rawptr);
- return ir_emit_global_call(proc, "__dynamic_map_set", args, 3);
- }
- irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset);
- irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type);
- irValue *ir_addr_store(irProcedure *proc, irAddr addr, irValue *value) {
- if (addr.addr == nullptr) {
- return nullptr;
- }
- if (addr.kind == irAddr_Map) {
- return ir_insert_dynamic_map_key_and_value(proc, addr.addr, addr.map_type, addr.map_key, value);
- } else if (addr.kind == irAddr_BitField) {
- gbAllocator a = proc->module->allocator;
- Type *bft = base_type(type_deref(ir_type(addr.addr)));
- GB_ASSERT(is_type_bit_field(bft));
- i32 value_index = addr.bit_field_value_index;
- i32 offset = bft->BitField.offsets[value_index];
- i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
- i32 byte_index = offset / 8;
- i32 bit_inset = offset % 8;
- i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
- if (size_in_bytes == 0) {
- GB_ASSERT(size_in_bits == 0);
- return nullptr;
- }
- Type *int_type = nullptr;
- switch (size_in_bytes) {
- case 1: int_type = t_u8; break;
- case 2: int_type = t_u16; break;
- case 4: int_type = t_u32; break;
- case 8: int_type = t_u64; break;
- case 16: int_type = t_u128; break;
- }
- GB_ASSERT(int_type != nullptr);
- value = ir_emit_conv(proc, value, int_type);
- irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
- bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(a, byte_index));
- if (bit_inset == 0) {
- irValue *v = value;
- i32 sa = 8*size_in_bytes - size_in_bits;
- if (sa > 0) {
- irValue *shift_amount = ir_const_int(a, sa);
- v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
- v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
- }
- irValue *ptr = ir_emit_conv(proc, bytes, make_type_pointer(a, int_type));
- v = ir_emit_arith(proc, Token_Or, ir_emit_load(proc, ptr), v, int_type);
- return ir_emit_store(proc, ptr, v);
- }
- // First byte
- {
- i32 sa = 8 - bit_inset;
- irValue *shift_amount = ir_const_int(a, sa);
- irValue *v = ir_emit_conv(proc, value, t_u8);
- v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
- v = ir_emit_arith(proc, Token_Or, ir_emit_load(proc, bytes), v, int_type);
- ir_emit_store(proc, bytes, v);
- }
- // Remaining bytes
- {
- irValue *shift_amount = ir_const_int(a, bit_inset);
- irValue *ptr = ir_emit_conv(proc, ir_emit_ptr_offset(proc, bytes, v_one), make_type_pointer(a, int_type));
- irValue *v = ir_emit_arith(proc, Token_Shr, value, shift_amount, int_type);
- v = ir_emit_arith(proc, Token_Or, ir_emit_load(proc, ptr), v, int_type);
- return ir_emit_store(proc, ptr, v);
- }
- }
- irValue *v = ir_emit_conv(proc, value, ir_addr_type(addr));
- return ir_emit_store(proc, addr.addr, v);
- }
- irValue *ir_addr_load(irProcedure *proc, irAddr addr) {
- if (addr.addr == nullptr) {
- GB_PANIC("Illegal addr load");
- return nullptr;
- }
- if (addr.kind == irAddr_Map) {
- // TODO(bill): map lookup
- Type *map_type = base_type(addr.map_type);
- irValue *v = ir_add_local_generated(proc, map_type->Map.lookup_result_type);
- irValue *h = ir_gen_map_header(proc, addr.addr, map_type);
- irValue *key = ir_gen_map_key(proc, addr.map_key, map_type->Map.key);
- irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 2);
- args[0] = h;
- args[1] = key;
- irValue *ptr = ir_emit_global_call(proc, "__dynamic_map_get", args, 2);
- irValue *ok = ir_emit_comp(proc, Token_NotEq, ptr, v_raw_nil);
- ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), ok);
- irBlock *then = ir_new_block(proc, nullptr, "map.get.then");
- irBlock *done = ir_new_block(proc, nullptr, "map.get.done");
- ir_emit_if(proc, ok, then, done);
- ir_start_block(proc, then);
- {
- // TODO(bill): mem copy it instead?
- irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
- irValue *value = ir_emit_conv(proc, ptr, ir_type(gep0));
- ir_emit_store(proc, gep0, ir_emit_load(proc, value));
- }
- ir_emit_jump(proc, done);
- ir_start_block(proc, done);
- if (is_type_tuple(addr.map_result)) {
- return ir_emit_load(proc, v);
- } else {
- irValue *single = ir_emit_struct_ep(proc, v, 0);
- return ir_emit_load(proc, single);
- }
- } else if (addr.kind == irAddr_BitField) {
- gbAllocator a = proc->module->allocator;
- Type *bft = base_type(type_deref(ir_type(addr.addr)));
- GB_ASSERT(is_type_bit_field(bft));
- i32 value_index = addr.bit_field_value_index;
- i32 offset = bft->BitField.offsets[value_index];
- i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
- i32 byte_index = offset / 8;
- i32 bit_inset = offset % 8;
- i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
- if (size_in_bytes == 0) {
- GB_ASSERT(size_in_bits == 0);
- return ir_const_i32(a, 0);
- }
- Type *int_type = nullptr;
- switch (size_in_bytes) {
- case 1: int_type = t_u8; break;
- case 2: int_type = t_u16; break;
- case 4: int_type = t_u32; break;
- case 8: int_type = t_u64; break;
- case 16: int_type = t_u128; break;
- }
- GB_ASSERT(int_type != nullptr);
- irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
- bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(a, byte_index));
- Type *int_ptr = make_type_pointer(a, int_type);
- if (bit_inset == 0) {
- irValue *v = ir_emit_load(proc, ir_emit_conv(proc, bytes, int_ptr));
- i32 sa = 8*size_in_bytes - size_in_bits;
- if (sa > 0) {
- irValue *shift_amount = ir_const_int(a, sa);
- v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
- v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
- }
- return v;
- }
- GB_ASSERT(8 > bit_inset);
- irValue *shift_amount = ir_value_constant(a, int_type, exact_value_i64(bit_inset));
- irValue *first_byte = ir_emit_load(proc, bytes);
- irValue *res = ir_emit_arith(proc, Token_Shr, first_byte, shift_amount, int_type);
- irValue *remaining_bytes = ir_emit_load(proc, ir_emit_conv(proc, ir_emit_ptr_offset(proc, bytes, v_one), int_ptr));
- remaining_bytes = ir_emit_arith(proc, Token_Shl, remaining_bytes, shift_amount, int_type);
- return ir_emit_arith(proc, Token_Or, res, remaining_bytes, int_type);
- }
- Type *t = base_type(ir_type(addr.addr));
- if (t->kind == Type_Proc) {
- // NOTE(bill): Imported procedures don't require a load as they are pointers
- return addr.addr;
- }
- return ir_emit_load(proc, addr.addr);
- }
- irValue *ir_addr_get_ptr(irProcedure *proc, irAddr addr) {
- if (addr.addr == nullptr) {
- GB_PANIC("Illegal addr -> nullptr");
- return nullptr;
- }
- switch (addr.kind) {
- case irAddr_Map:
- case irAddr_BitField: {
- irValue *v = ir_addr_load(proc, addr);
- return ir_address_from_load_or_generate_local(proc, v);
- }
- }
- return addr.addr;
- }
- irValue *ir_build_addr_ptr(irProcedure *proc, AstNode *expr) {
- irAddr addr = ir_build_addr(proc, expr);
- return ir_addr_get_ptr(proc, addr);
- }
- irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index);
- irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index);
- irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset) {
- offset = ir_emit_conv(proc, offset, t_int);
- return ir_emit(proc, ir_instr_ptr_offset(proc, ptr, offset));
- }
- irValue *ir_emit_unary_arith(irProcedure *proc, TokenKind op, irValue *x, Type *type) {
- switch (op) {
- case Token_Add:
- return x;
- case Token_Not: // Boolean not
- case Token_Xor: // Bitwise not
- case Token_Sub: // Bitwise Not
- break;
- case Token_Pointer:
- GB_PANIC("This should be handled elsewhere");
- break;
- }
- if (is_type_vector(ir_type(x))) {
- ir_emit_comment(proc, str_lit("vector.arith.begin"));
- // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
- Type *tl = base_type(ir_type(x));
- irValue *val = ir_address_from_load_or_generate_local(proc, x);
- GB_ASSERT(is_type_vector(type));
- Type *elem_type = base_type(type)->Vector.elem;
- irValue *res = ir_add_local_generated(proc, type);
- for (i32 i = 0; i < tl->Vector.count; i++) {
- irValue *e = ir_emit_load(proc, ir_emit_array_epi(proc, val, i));
- irValue *z = ir_emit_unary_arith(proc, op, e, elem_type);
- ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
- }
- ir_emit_comment(proc, str_lit("vector.arith.end"));
- return ir_emit_load(proc, res);
- }
- return ir_emit(proc, ir_instr_unary_op(proc, op, x, type));
- }
- irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type) {
- Type *t_left = ir_type(left);
- Type *t_right = ir_type(right);
- if (is_type_vector(t_left) || is_type_vector(t_right)) {
- ir_emit_comment(proc, str_lit("vector.arith.begin"));
- // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
- left = ir_emit_conv(proc, left, type);
- right = ir_emit_conv(proc, right, type);
- irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
- irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
- GB_ASSERT(is_type_vector(type));
- Type *elem_type = base_type(type)->Vector.elem;
- irValue *res = ir_add_local_generated(proc, type);
- i64 count = base_type(type)->Vector.count;
- for (i32 i = 0; i < count; i++) {
- irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
- irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
- irValue *z = ir_emit_arith(proc, op, x, y, elem_type);
- ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
- }
- ir_emit_comment(proc, str_lit("vector.arith.end"));
- return ir_emit_load(proc, res);
- }
- if (is_type_complex(t_left)) {
- ir_emit_comment(proc, str_lit("complex.arith.begin"));
- Type *ft = base_complex_elem_type(t_left);
- irValue *res = ir_add_local_generated(proc, type);
- irValue *a = ir_emit_struct_ev(proc, left, 0);
- irValue *b = ir_emit_struct_ev(proc, left, 1);
- irValue *c = ir_emit_struct_ev(proc, right, 0);
- irValue *d = ir_emit_struct_ev(proc, right, 1);
- irValue *real = nullptr;
- irValue *imag = nullptr;
- switch (op) {
- case Token_Add:
- real = ir_emit_arith(proc, Token_Add, a, c, ft);
- imag = ir_emit_arith(proc, Token_Add, b, d, ft);
- break;
- case Token_Sub:
- real = ir_emit_arith(proc, Token_Sub, a, c, ft);
- imag = ir_emit_arith(proc, Token_Sub, b, d, ft);
- break;
- case Token_Mul: {
- irValue *x = ir_emit_arith(proc, Token_Mul, a, c, ft);
- irValue *y = ir_emit_arith(proc, Token_Mul, b, d, ft);
- real = ir_emit_arith(proc, Token_Sub, x, y, ft);
- irValue *z = ir_emit_arith(proc, Token_Mul, b, c, ft);
- irValue *w = ir_emit_arith(proc, Token_Mul, a, d, ft);
- imag = ir_emit_arith(proc, Token_Add, z, w, ft);
- break;
- }
- case Token_Quo: {
- irValue *s1 = ir_emit_arith(proc, Token_Mul, c, c, ft);
- irValue *s2 = ir_emit_arith(proc, Token_Mul, d, d, ft);
- irValue *s = ir_emit_arith(proc, Token_Add, s1, s2, ft);
- irValue *x = ir_emit_arith(proc, Token_Mul, a, c, ft);
- irValue *y = ir_emit_arith(proc, Token_Mul, b, d, ft);
- real = ir_emit_arith(proc, Token_Add, x, y, ft);
- real = ir_emit_arith(proc, Token_Quo, real, s, ft);
- irValue *z = ir_emit_arith(proc, Token_Mul, b, c, ft);
- irValue *w = ir_emit_arith(proc, Token_Mul, a, d, ft);
- imag = ir_emit_arith(proc, Token_Sub, z, w, ft);
- imag = ir_emit_arith(proc, Token_Quo, imag, s, ft);
- break;
- }
- }
- ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
- ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
- ir_emit_comment(proc, str_lit("complex.end.begin"));
- return ir_emit_load(proc, res);
- }
- if (op == Token_Add) {
- if (is_type_pointer(t_left)) {
- irValue *ptr = ir_emit_conv(proc, left, type);
- irValue *offset = right;
- return ir_emit_ptr_offset(proc, ptr, offset);
- } else if (is_type_pointer(ir_type(right))) {
- irValue *ptr = ir_emit_conv(proc, right, type);
- irValue *offset = left;
- return ir_emit_ptr_offset(proc, ptr, offset);
- }
- } else if (op == Token_Sub) {
- if (is_type_pointer(t_left) && is_type_integer(t_right)) {
- // ptr - int
- irValue *ptr = ir_emit_conv(proc, left, type);
- irValue *offset = ir_emit_unary_arith(proc, Token_Sub, right, t_int);
- return ir_emit_ptr_offset(proc, ptr, offset);
- } else if (is_type_pointer(t_left) && is_type_pointer(t_right)) {
- GB_ASSERT(is_type_integer(type));
- irModule *m = proc->module;
- Type *ptr_type = base_type(t_left);
- GB_ASSERT(!is_type_rawptr(ptr_type));
- irValue *elem_size = ir_const_int(m->allocator, type_size_of(m->allocator, ptr_type->Pointer.elem));
- irValue *x = ir_emit_conv(proc, ir_emit_conv(proc, left, t_uintptr), type);
- irValue *y = ir_emit_conv(proc, ir_emit_conv(proc, right, t_uintptr), type);
- irValue *diff = ir_emit_arith(proc, op, x, y, type);
- return ir_emit_arith(proc, Token_Quo, diff, elem_size, type);
- }
- }
- switch (op) {
- case Token_Shl:
- case Token_Shr:
- left = ir_emit_conv(proc, left, type);
- right = ir_emit_conv(proc, right, type);
- break;
- case Token_AndNot: {
- // NOTE(bill): x &~ y == x & (~y) == x & (y ~ -1)
- // NOTE(bill): "not" `x` == `x` "xor" `-1`
- irValue *neg = ir_add_module_constant(proc->module, type, exact_value_i64(-1));
- op = Token_Xor;
- right = ir_emit_arith(proc, op, right, neg, type);
- GB_ASSERT(right->Instr.kind == irInstr_BinaryOp);
- right->Instr.BinaryOp.type = type;
- op = Token_And;
- } /* fallthrough */
- case Token_Add:
- case Token_Sub:
- case Token_Mul:
- case Token_Quo:
- case Token_Mod:
- case Token_ModMod:
- case Token_And:
- case Token_Or:
- case Token_Xor:
- left = ir_emit_conv(proc, left, type);
- right = ir_emit_conv(proc, right, type);
- break;
- }
- if (op == Token_ModMod) {
- irValue *n = left;
- irValue *m = right;
- if (is_type_unsigned(type)) {
- return ir_emit_arith(proc, Token_Mod, n, m, type);
- }
- irValue *a = ir_emit_arith(proc, Token_Mod, n, m, type);
- irValue *b = ir_emit_arith(proc, Token_Add, a, m, type);
- return ir_emit_arith(proc, Token_Mod, b, m, type);
- }
- if (is_type_i128_or_u128(type)) {
- // IMPORTANT NOTE(bill): LLVM is goddamn buggy!
- bool is_unsigned = is_type_unsigned(type);
- char *name = nullptr;
- if (op == Token_Quo) {
- name = cast(char *)(is_unsigned ? "__udivti3" : "__divti3");
- } else if (op == Token_Mod) {
- name = cast(char *)(is_unsigned ? "__umodti3" : "__modti3");
- }
- if (name != nullptr) {
- irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 2);
- args[0] = left;
- args[1] = right;
- return ir_emit_global_call(proc, name, args, 2);
- }
- }
- return ir_emit(proc, ir_instr_binary_op(proc, op, left, right, type));
- }
- irValue *ir_emit_union_tag_ptr(irProcedure *proc, irValue *u) {
- Type *t = ir_type(u);
- GB_ASSERT_MSG(is_type_pointer(t) &&
- is_type_union(type_deref(t)), "%s", type_to_string(t));
- irValue *tag_ptr = ir_emit(proc, ir_instr_union_tag_ptr(proc, u));
- return tag_ptr;
- }
- irValue *ir_emit_union_tag_value(irProcedure *proc, irValue *u) {
- Type *t = ir_type(u);
- GB_ASSERT(is_type_union(t));
- GB_ASSERT(are_types_identical(t, ir_type(u)));
- return ir_emit(proc, ir_instr_union_tag_value(proc, u));
- }
- irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right);
- irValue *ir_emit_comp_against_nil(irProcedure *proc, TokenKind op_kind, irValue *x) {
- Type *t = ir_type(x);
- if (is_type_any(t)) {
- irValue *data = ir_emit_struct_ev(proc, x, 0);
- irValue *ti = ir_emit_struct_ev(proc, x, 1);
- if (op_kind == Token_CmpEq) {
- irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
- irValue *b = ir_emit_comp(proc, Token_CmpEq, ti, v_raw_nil);
- return ir_emit_arith(proc, Token_Or, a, b, t_bool);
- } else if (op_kind == Token_NotEq) {
- irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
- irValue *b = ir_emit_comp(proc, Token_NotEq, ti, v_raw_nil);
- return ir_emit_arith(proc, Token_And, a, b, t_bool);
- }
- } else if (is_type_slice(t)) {
- irValue *data = ir_emit_struct_ev(proc, x, 0);
- irValue *cap = ir_emit_struct_ev(proc, x, 2);
- if (op_kind == Token_CmpEq) {
- irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
- irValue *b = ir_emit_comp(proc, Token_CmpEq, cap, v_zero);
- return ir_emit_arith(proc, Token_Or, a, b, t_bool);
- } else if (op_kind == Token_NotEq) {
- irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
- irValue *b = ir_emit_comp(proc, Token_NotEq, cap, v_zero);
- return ir_emit_arith(proc, Token_And, a, b, t_bool);
- }
- } else if (is_type_dynamic_array(t)) {
- irValue *data = ir_emit_struct_ev(proc, x, 0);
- irValue *cap = ir_emit_struct_ev(proc, x, 2);
- if (op_kind == Token_CmpEq) {
- irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
- irValue *b = ir_emit_comp(proc, Token_CmpEq, cap, v_zero);
- return ir_emit_arith(proc, Token_Or, a, b, t_bool);
- } else if (op_kind == Token_NotEq) {
- irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
- irValue *b = ir_emit_comp(proc, Token_NotEq, cap, v_zero);
- return ir_emit_arith(proc, Token_And, a, b, t_bool);
- }
- } else if (is_type_map(t)) {
- irValue *hashes = ir_emit_struct_ev(proc, x, 0);
- irValue *entries = ir_emit_struct_ev(proc, x, 1);
- irValue *a = ir_emit_comp_against_nil(proc, op_kind, hashes);
- irValue *b = ir_emit_comp_against_nil(proc, op_kind, entries);
- if (op_kind == Token_CmpEq) {
- return ir_emit_arith(proc, Token_Or, a, b, t_bool);
- } else if (op_kind == Token_NotEq) {
- return ir_emit_arith(proc, Token_And, a, b, t_bool);
- }
- } else if (is_type_union(t)) {
- irValue *tag = ir_emit_union_tag_value(proc, x);
- return ir_emit_comp(proc, op_kind, tag, v_zero);
- }
- return nullptr;
- }
- irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right) {
- Type *a = base_type(ir_type(left));
- Type *b = base_type(ir_type(right));
- GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
- irValue *nil_check = nullptr;
- if (left->kind == irValue_Nil) {
- nil_check = ir_emit_comp_against_nil(proc, op_kind, right);
- } else if (right->kind == irValue_Nil) {
- nil_check = ir_emit_comp_against_nil(proc, op_kind, left);
- }
- if (nil_check != nullptr) {
- return nil_check;
- }
- if (are_types_identical(a, b)) {
- // NOTE(bill): No need for a conversion
- } else if (left->kind == irValue_Constant || left->kind == irValue_Nil) {
- left = ir_emit_conv(proc, left, ir_type(right));
- } else if (right->kind == irValue_Constant || right->kind == irValue_Nil) {
- right = ir_emit_conv(proc, right, ir_type(left));
- } else {
- gbAllocator a = proc->module->allocator;
- i64 ls = type_size_of(a, ir_type(left));
- i64 rs = type_size_of(a, ir_type(right));
- if (ls < rs) {
- left = ir_emit_conv(proc, left, ir_type(right));
- } else if (ls > rs) {
- right = ir_emit_conv(proc, right, ir_type(left));
- } else {
- right = ir_emit_conv(proc, right, ir_type(left));
- }
- }
- Type *result = t_bool;
- if (is_type_vector(a)) {
- result = make_type_vector(proc->module->allocator, t_bool, a->Vector.count);
- }
- if (is_type_vector(a)) {
- ir_emit_comment(proc, str_lit("vector.comp.begin"));
- Type *tl = base_type(a);
- irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
- irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
- GB_ASSERT(is_type_vector(result));
- Type *elem_type = base_type(result)->Vector.elem;
- irValue *res = ir_add_local_generated(proc, result);
- for (i32 i = 0; i < tl->Vector.count; i++) {
- irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
- irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
- irValue *z = ir_emit_comp(proc, op_kind, x, y);
- ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
- }
- ir_emit_comment(proc, str_lit("vector.comp.end"));
- return ir_emit_load(proc, res);
- }
- return ir_emit(proc, ir_instr_binary_op(proc, op_kind, left, right, result));
- }
- irValue *ir_emit_array_ep(irProcedure *proc, irValue *s, irValue *index) {
- GB_ASSERT(index != nullptr);
- Type *t = ir_type(s);
- GB_ASSERT(is_type_pointer(t));
- Type *st = base_type(type_deref(t));
- GB_ASSERT_MSG(is_type_array(st) || is_type_vector(st), "%s", type_to_string(st));
- // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
- index = ir_emit_conv(proc, index, t_i32);
- return ir_emit(proc, ir_instr_array_element_ptr(proc, s, index));
- }
- irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index) {
- return ir_emit_array_ep(proc, s, ir_const_i32(proc->module->allocator, index));
- }
- irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index) {
- gbAllocator a = proc->module->allocator;
- Type *t = base_type(type_deref(ir_type(s)));
- Type *result_type = nullptr;
- if (is_type_struct(t)) {
- result_type = make_type_pointer(a, t->Struct.fields[index]->type);
- } else if (is_type_union(t)) {
- GB_ASSERT(index == -1);
- return ir_emit_union_tag_ptr(proc, s);
- } else if (is_type_tuple(t)) {
- GB_ASSERT(t->Tuple.variables.count > 0);
- result_type = make_type_pointer(a, t->Tuple.variables[index]->type);
- } else if (is_type_complex(t)) {
- Type *ft = base_complex_elem_type(t);
- switch (index) {
- case 0: result_type = make_type_pointer(a, ft); break;
- case 1: result_type = make_type_pointer(a, ft); break;
- }
- } else if (is_type_slice(t)) {
- switch (index) {
- case 0: result_type = make_type_pointer(a, make_type_pointer(a, t->Slice.elem)); break;
- case 1: result_type = make_type_pointer(a, t_int); break;
- case 2: result_type = make_type_pointer(a, t_int); break;
- }
- } else if (is_type_string(t)) {
- switch (index) {
- case 0: result_type = make_type_pointer(a, t_u8_ptr); break;
- case 1: result_type = make_type_pointer(a, t_int); break;
- }
- } else if (is_type_any(t)) {
- switch (index) {
- case 0: result_type = make_type_pointer(a, t_rawptr); break;
- case 1: result_type = make_type_pointer(a, t_type_info_ptr); break;
- }
- } else if (is_type_dynamic_array(t)) {
- switch (index) {
- case 0: result_type = make_type_pointer(a, make_type_pointer(a, t->DynamicArray.elem)); break;
- case 1: result_type = t_int_ptr; break;
- case 2: result_type = t_int_ptr; break;
- case 3: result_type = t_allocator_ptr; break;
- }
- } else if (is_type_map(t)) {
- generate_map_internal_types(a, t);
- Type *gst = t->Map.generated_struct_type;
- switch (index) {
- case 0: result_type = make_type_pointer(a, gst->Struct.fields[0]->type); break;
- case 1: result_type = make_type_pointer(a, gst->Struct.fields[1]->type); break;
- }
- }else {
- GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(ir_type(s)), index);
- }
- GB_ASSERT(result_type != nullptr);
- return ir_emit(proc, ir_instr_struct_element_ptr(proc, s, index, result_type));
- }
- irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index) {
- // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
- gbAllocator a = proc->module->allocator;
- Type *t = base_type(ir_type(s));
- Type *result_type = nullptr;
- switch (t->kind) {
- case Type_Basic:
- switch (t->Basic.kind) {
- case Basic_string:
- switch (index) {
- case 0: result_type = t_u8_ptr; break;
- case 1: result_type = t_int; break;
- }
- break;
- case Basic_any:
- switch (index) {
- case 0: result_type = t_rawptr; break;
- case 1: result_type = t_type_info_ptr; break;
- }
- break;
- case Basic_complex64: case Basic_complex128:
- {
- Type *ft = base_complex_elem_type(t);
- switch (index) {
- case 0: result_type = ft; break;
- case 1: result_type = ft; break;
- }
- break;
- }
- }
- break;
- case Type_Struct:
- result_type = t->Struct.fields[index]->type;
- break;
- case Type_Union:
- GB_ASSERT(index == -1);
- return ir_emit_union_tag_value(proc, s);
- case Type_Tuple:
- GB_ASSERT(t->Tuple.variables.count > 0);
- result_type = t->Tuple.variables[index]->type;
- break;
- case Type_Slice:
- switch (index) {
- case 0: result_type = make_type_pointer(a, t->Slice.elem); break;
- case 1: result_type = t_int; break;
- case 2: result_type = t_int; break;
- }
- break;
- case Type_DynamicArray:
- switch (index) {
- case 0: result_type = make_type_pointer(a, t->DynamicArray.elem); break;
- case 1: result_type = t_int; break;
- case 2: result_type = t_int; break;
- case 3: result_type = t_allocator; break;
- }
- break;
- case Type_Map: {
- generate_map_internal_types(a, t);
- Type *gst = t->Map.generated_struct_type;
- switch (index) {
- case 0: result_type = gst->Struct.fields[0]->type; break;
- case 1: result_type = gst->Struct.fields[1]->type; break;
- }
- break;
- }
- default:
- GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(ir_type(s)), index);
- break;
- }
- GB_ASSERT(result_type != nullptr);
- return ir_emit(proc, ir_instr_struct_extract_value(proc, s, index, result_type));
- }
- irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel) {
- GB_ASSERT(sel.index.count > 0);
- Type *type = type_deref(ir_type(e));
- gbAllocator a = proc->module->allocator;
- for_array(i, sel.index) {
- i32 index = cast(i32)sel.index[i];
- if (is_type_pointer(type)) {
- type = type_deref(type);
- e = ir_emit_load(proc, e);
- e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
- }
- type = core_type(type);
- if (is_type_raw_union(type)) {
- type = type->Struct.fields[index]->type;
- e = ir_emit_conv(proc, e, make_type_pointer(a, type));
- } else if (is_type_struct(type)) {
- type = type->Struct.fields[index]->type;
- e = ir_emit_struct_ep(proc, e, index);
- } else if (type->kind == Type_Union) {
- GB_ASSERT(index == -1);
- type = t_type_info_ptr;
- e = ir_emit_struct_ep(proc, e, index);
- } else if (type->kind == Type_Tuple) {
- type = type->Tuple.variables[index]->type;
- e = ir_emit_struct_ep(proc, e, index);
- } else if (type->kind == Type_Basic) {
- switch (type->Basic.kind) {
- case Basic_any: {
- if (index == 0) {
- type = t_rawptr;
- } else if (index == 1) {
- type = t_type_info_ptr;
- }
- e = ir_emit_struct_ep(proc, e, index);
- break;
- }
- case Basic_string:
- e = ir_emit_struct_ep(proc, e, index);
- break;
- default:
- GB_PANIC("un-gep-able type");
- break;
- }
- } else if (type->kind == Type_Slice) {
- e = ir_emit_struct_ep(proc, e, index);
- } else if (type->kind == Type_DynamicArray) {
- e = ir_emit_struct_ep(proc, e, index);
- } else if (type->kind == Type_Vector) {
- e = ir_emit_array_epi(proc, e, index);
- } else if (type->kind == Type_Array) {
- e = ir_emit_array_epi(proc, e, index);
- } else if (type->kind == Type_Map) {
- e = ir_emit_struct_ep(proc, e, 1);
- switch (index) {
- case 0: e = ir_emit_struct_ep(proc, e, 1); break; // count
- case 1: e = ir_emit_struct_ep(proc, e, 2); break; // capacity
- case 2: e = ir_emit_struct_ep(proc, e, 3); break; // allocator
- }
- } else {
- GB_PANIC("un-gep-able type %s", type_to_string(type));
- }
- }
- return e;
- }
- irValue *ir_emit_deep_field_ev(irProcedure *proc, irValue *e, Selection sel) {
- GB_ASSERT(sel.index.count > 0);
- Type *type = ir_type(e);
- for_array(i, sel.index) {
- i32 index = cast(i32)sel.index[i];
- if (is_type_pointer(type)) {
- type = type_deref(type);
- e = ir_emit_load(proc, e);
- e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
- }
- type = base_type(type);
- if (is_type_raw_union(type)) {
- GB_PANIC("TODO(bill): IS THIS EVEN CORRECT?");
- type = type->Struct.fields[index]->type;
- e = ir_emit_conv(proc, e, type);
- } else if (type->kind == Type_Map) {
- e = ir_emit_struct_ev(proc, e, 1);
- switch (index) {
- case 0: e = ir_emit_struct_ev(proc, e, 1); break; // count
- case 1: e = ir_emit_struct_ev(proc, e, 2); break; // capacity
- case 2: e = ir_emit_struct_ev(proc, e, 3); break; // allocator
- }
- } else {
- e = ir_emit_struct_ev(proc, e, index);
- }
- }
- return e;
- }
- irValue *ir_array_elem(irProcedure *proc, irValue *array) {
- return ir_emit_array_ep(proc, array, v_zero32);
- }
- irValue *ir_array_len(irProcedure *proc, irValue *array) {
- Type *t = base_type(ir_type(array));
- GB_ASSERT(t->kind == Type_Array);
- return ir_const_int(proc->module->allocator, t->Array.count);
- }
- irValue *ir_vector_elem(irProcedure *proc, irValue *vector) {
- return ir_emit_array_ep(proc, vector, v_one32);
- }
- irValue *ir_slice_elem(irProcedure *proc, irValue *slice) {
- Type *t = base_type(ir_type(slice));
- GB_ASSERT(t->kind == Type_Slice);
- return ir_emit_struct_ev(proc, slice, 0);
- }
- irValue *ir_slice_count(irProcedure *proc, irValue *slice) {
- Type *t = base_type(ir_type(slice));
- GB_ASSERT(t->kind == Type_Slice);
- return ir_emit_struct_ev(proc, slice, 1);
- }
- irValue *ir_slice_capacity(irProcedure *proc, irValue *slice) {
- Type *t = base_type(ir_type(slice));
- GB_ASSERT(t->kind == Type_Slice);
- return ir_emit_struct_ev(proc, slice, 2);
- }
- irValue *ir_dynamic_array_elem(irProcedure *proc, irValue *da) {
- Type *t = ir_type(da);
- GB_ASSERT(t->kind == Type_DynamicArray);
- return ir_emit_struct_ev(proc, da, 0);
- }
- irValue *ir_dynamic_array_count(irProcedure *proc, irValue *da) {
- Type *t = base_type(ir_type(da));
- GB_ASSERT_MSG(t->kind == Type_DynamicArray, "%s", type_to_string(t));
- return ir_emit_struct_ev(proc, da, 1);
- }
- irValue *ir_dynamic_array_capacity(irProcedure *proc, irValue *da) {
- Type *t = base_type(ir_type(da));
- GB_ASSERT(t->kind == Type_DynamicArray);
- return ir_emit_struct_ev(proc, da, 2);
- }
- irValue *ir_dynamic_array_allocator(irProcedure *proc, irValue *da) {
- Type *t = base_type(ir_type(da));
- GB_ASSERT(t->kind == Type_DynamicArray);
- return ir_emit_struct_ev(proc, da, 3);
- }
- irValue *ir_string_elem(irProcedure *proc, irValue *string) {
- Type *t = base_type(ir_type(string));
- GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
- return ir_emit_struct_ev(proc, string, 0);
- }
- irValue *ir_string_len(irProcedure *proc, irValue *string) {
- Type *t = base_type(ir_type(string));
- GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
- return ir_emit_struct_ev(proc, string, 1);
- }
- void ir_fill_slice(irProcedure *proc, irValue *slice_ptr, irValue *data, irValue *len, irValue *cap) {
- Type *t = ir_type(slice_ptr);
- GB_ASSERT(is_type_pointer(t));
- t = type_deref(t);
- GB_ASSERT(is_type_slice(t));
- ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 0), data);
- ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 1), len);
- ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 2), cap);
- }
- void ir_fill_string(irProcedure *proc, irValue *string_ptr, irValue *data, irValue *len) {
- Type *t = ir_type(string_ptr);
- GB_ASSERT(is_type_pointer(t));
- t = type_deref(t);
- GB_ASSERT(is_type_string(t));
- ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 0), data);
- ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 1), len);
- }
- irValue *ir_emit_string(irProcedure *proc, irValue *elem, irValue *len) {
- irValue *str = ir_add_local_generated(proc, t_string);
- ir_fill_string(proc, str, elem, len);
- return ir_emit_load(proc, str);
- }
- irValue *ir_add_local_slice(irProcedure *proc, Type *slice_type, irValue *base, irValue *low, irValue *high, irValue *max) {
- // TODO(bill): array bounds checking for slice creation
- // TODO(bill): check that low < high <= max
- gbAllocator a = proc->module->allocator;
- Type *bt = base_type(ir_type(base));
- if (low == nullptr) {
- low = v_zero;
- }
- if (high == nullptr) {
- switch (bt->kind) {
- case Type_Array: high = ir_array_len(proc, base); break;
- case Type_Slice: high = ir_slice_count(proc, base); break;
- case Type_Pointer: high = v_one; break;
- }
- }
- if (max == nullptr) {
- switch (bt->kind) {
- case Type_Array: high = ir_array_len(proc, base); break;
- case Type_Slice: high = ir_slice_capacity(proc, base); break;
- case Type_Pointer: high = v_one; break;
- }
- }
- irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
- irValue *cap = ir_emit_arith(proc, Token_Sub, max, low, t_int);
- irValue *elem = nullptr;
- switch (bt->kind) {
- case Type_Array: elem = ir_array_elem(proc, base); break;
- case Type_Slice: elem = ir_slice_elem(proc, base); break;
- case Type_Pointer: elem = ir_emit_load(proc, base); break;
- }
- elem = ir_emit_ptr_offset(proc, elem, low);
- irValue *slice = ir_add_local_generated(proc, slice_type);
- ir_fill_slice(proc, slice, elem, len, cap);
- return slice;
- }
- irValue *ir_find_or_add_entity_string(irModule *m, String str) {
- irValue **found = map_get(&m->const_strings, hash_string(str));
- if (found != nullptr) {
- return *found;
- }
- irValue *v = ir_const_string(m->allocator, str);
- map_set(&m->const_strings, hash_string(str), v);
- return v;
- }
- irValue *ir_const_union_tag(gbAllocator a, Type *u, Type *v) {
- return ir_value_constant(a, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
- }
- String ir_lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
- Type *prev_src = src;
- // Type *prev_dst = dst;
- src = base_type(type_deref(src));
- // dst = base_type(type_deref(dst));
- bool src_is_ptr = src != prev_src;
- // bool dst_is_ptr = dst != prev_dst;
- GB_ASSERT(is_type_struct(src) || is_type_union(src));
- for_array(i, src->Struct.fields) {
- Entity *f = src->Struct.fields[i];
- if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
- if (are_types_identical(dst, f->type)) {
- return f->token.string;
- }
- if (src_is_ptr && is_type_pointer(dst)) {
- if (are_types_identical(type_deref(dst), f->type)) {
- return f->token.string;
- }
- }
- if (is_type_struct(f->type)) {
- String name = ir_lookup_subtype_polymorphic_field(info, dst, f->type);
- if (name.len > 0) {
- return name;
- }
- }
- }
- }
- return str_lit("");
- }
- irValue *ir_emit_ptr_to_uintptr(irProcedure *proc, irValue *value, Type *t, bool allow_type_type = false) {
- Type *vt = core_type(ir_type(value));
- GB_ASSERT(is_type_pointer(vt));
- if (allow_type_type) {
- GB_ASSERT(is_type_uintptr(core_type(t)));
- } else {
- GB_ASSERT(is_type_uintptr(core_type(t)));
- }
- return ir_emit(proc, ir_instr_conv(proc, irConv_ptrtoint, value, vt, t));
- }
- irValue *ir_emit_uintptr_to_ptr(irProcedure *proc, irValue *value, Type *t) {
- Type *vt = core_type(ir_type(value));
- GB_ASSERT(is_type_uintptr(vt));
- GB_ASSERT(is_type_pointer(core_type(t)));
- return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, value, vt, t));
- }
- irValue *ir_emit_conv(irProcedure *proc, irValue *value, Type *t) {
- Type *src_type = ir_type(value);
- if (are_types_identical(t, src_type)) {
- return value;
- }
- Type *src = core_type(src_type);
- Type *dst = core_type(t);
- // if (is_type_untyped_nil(src) && type_has_nil(dst)) {
- if (is_type_untyped_nil(src)) {
- return ir_value_nil(proc->module->allocator, t);
- }
- if (is_type_untyped_undef(src)) {
- return ir_value_undef(proc->module->allocator, t);
- }
- if (value->kind == irValue_Constant) {
- if (is_type_any(dst)) {
- irValue *default_value = ir_add_local_generated(proc, default_type(src_type));
- ir_emit_store(proc, default_value, value);
- return ir_emit_conv(proc, ir_emit_load(proc, default_value), t_any);
- } else if (dst->kind == Type_Basic) {
- ExactValue ev = value->Constant.value;
- if (is_type_float(dst)) {
- ev = exact_value_to_float(ev);
- } else if (is_type_complex(dst)) {
- ev = exact_value_to_complex(ev);
- } else if (is_type_string(dst)) {
- // Handled elsewhere
- GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
- } else if (is_type_integer(dst)) {
- ev = exact_value_to_integer(ev);
- } else if (is_type_pointer(dst)) {
- // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect `null`
- irValue *i = ir_add_module_constant(proc->module, t_uint, ev);
- return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, i, t_uint, dst));
- }
- return ir_add_module_constant(proc->module, t, ev);
- }
- }
- if (are_types_identical(src, dst)) {
- if (!are_types_identical(src_type, t)) {
- return ir_emit_transmute(proc, value, t);
- }
- return value;
- }
- // integer -> integer
- if (is_type_integer(src) && is_type_integer(dst)) {
- GB_ASSERT(src->kind == Type_Basic &&
- dst->kind == Type_Basic);
- i64 sz = type_size_of(proc->module->allocator, default_type(src));
- i64 dz = type_size_of(proc->module->allocator, default_type(dst));
- irConvKind kind = irConv_trunc;
- if (dz < sz) {
- kind = irConv_trunc;
- } else if (dz == sz) {
- // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
- // NOTE(bill): Copy the value just for type correctness
- kind = irConv_bitcast;
- } else if (dz > sz) {
- if (is_type_unsigned(src)) {
- kind = irConv_zext; // zero extent
- } else {
- kind = irConv_sext; // sign extent
- }
- }
- return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
- }
- // boolean -> integer
- if (is_type_boolean(src) && is_type_integer(dst)) {
- return ir_emit(proc, ir_instr_conv(proc, irConv_zext, value, src_type, t));
- }
- // integer -> boolean
- if (is_type_integer(src) && is_type_boolean(dst)) {
- return ir_emit_comp(proc, Token_NotEq, value, v_zero);
- }
- // float -> float
- if (is_type_float(src) && is_type_float(dst)) {
- gbAllocator a = proc->module->allocator;
- i64 sz = type_size_of(proc->module->allocator, src);
- i64 dz = type_size_of(proc->module->allocator, dst);
- if (sz == 2) {
- switch (dz) {
- case 2: return value;
- case 4: {
- irValue **args = gb_alloc_array(a, irValue *, 1);
- args[0] = value;
- return ir_emit_global_call(proc, "__gnu_h2f_ieee", args, 1);
- break;
- }
- case 8: {
- irValue **args = gb_alloc_array(a, irValue *, 1);
- args[0] = value;
- return ir_emit_global_call(proc, "__f16_to_f64", args, 1);
- break;
- }
- }
- } else if (dz == 2) {
- switch (sz) {
- case 2: return value;
- case 4: {
- irValue **args = gb_alloc_array(a, irValue *, 1);
- args[0] = value;
- return ir_emit_global_call(proc, "__gnu_f2h_ieee", args, 1);
- break;
- }
- case 8: {
- irValue **args = gb_alloc_array(a, irValue *, 1);
- args[0] = value;
- return ir_emit_global_call(proc, "__truncdfhf2", args, 1);
- break;
- }
- }
- }
- irConvKind kind = irConv_fptrunc;
- if (dz >= sz) {
- kind = irConv_fpext;
- }
- return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
- }
- if (is_type_complex(src) && is_type_complex(dst)) {
- Type *ft = base_complex_elem_type(dst);
- irValue *gen = ir_add_local_generated(proc, dst);
- irValue *real = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
- irValue *imag = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
- ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), real);
- ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 1), imag);
- return ir_emit_load(proc, gen);
- }
- // float <-> integer
- if (is_type_float(src) && is_type_integer(dst)) {
- irConvKind kind = irConv_fptosi;
- if (is_type_unsigned(dst)) {
- kind = irConv_fptoui;
- }
- return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
- }
- if (is_type_integer(src) && is_type_float(dst)) {
- irConvKind kind = irConv_sitofp;
- if (is_type_unsigned(src)) {
- kind = irConv_uitofp;
- }
- return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
- }
- // Pointer <-> uintptr
- if (is_type_pointer(src) && is_type_uintptr(dst)) {
- return ir_emit_ptr_to_uintptr(proc, value, t);
- }
- if (is_type_uintptr(src) && is_type_pointer(dst)) {
- return ir_emit_uintptr_to_ptr(proc, value, t);
- }
- if (is_type_union(dst)) {
- for_array(i, dst->Union.variants) {
- Type *vt = dst->Union.variants[i];
- if (are_types_identical(vt, src_type)) {
- ir_emit_comment(proc, str_lit("union - child to parent"));
- gbAllocator a = proc->module->allocator;
- irValue *parent = ir_add_local_generated(proc, t);
- irValue *underlying = ir_emit_conv(proc, parent, make_type_pointer(a, vt));
- ir_emit_store(proc, underlying, value);
- irValue *tag_ptr = ir_emit_union_tag_ptr(proc, parent);
- ir_emit_store(proc, tag_ptr, ir_const_union_tag(a, t, src_type));
- return ir_emit_load(proc, parent);
- }
- }
- }
- // NOTE(bill): This has to be done before `Pointer <-> Pointer` as it's
- // subtype polymorphism casting
- if (check_is_assignable_to_using_subtype(src_type, t)) {
- Type *st = type_deref(src_type);
- Type *pst = st;
- st = type_deref(st);
- bool st_is_ptr = st != pst;
- st = base_type(st);
- Type *dt = t;
- bool dt_is_ptr = is_type_pointer(dt);
- GB_ASSERT(is_type_struct(st) || is_type_union(st));
- String field_name = ir_lookup_subtype_polymorphic_field(proc->module->info, t, st);
- // gb_printf("field_name: %.*s\n", LIT(field_name));
- if (field_name.len > 0) {
- // NOTE(bill): It can be casted
- Selection sel = lookup_field(proc->module->allocator, st, field_name, false);
- if (sel.entity != nullptr) {
- ir_emit_comment(proc, str_lit("cast - polymorphism"));
- if (st_is_ptr) {
- irValue *res = ir_emit_deep_field_gep(proc, value, sel);
- if (!dt_is_ptr) {
- res = ir_emit_load(proc, res);
- }
- return res;
- } else {
- if (is_type_pointer(ir_type(value))) {
- if (!dt_is_ptr) {
- value = ir_emit_load(proc, value);
- } else {
- value = ir_emit_deep_field_gep(proc, value, sel);
- return ir_emit_load(proc, value);
- }
- }
- return ir_emit_deep_field_ev(proc, value, sel);
- }
- }
- }
- }
- // Pointer <-> Pointer
- if (is_type_pointer(src) && is_type_pointer(dst)) {
- return ir_emit_bitcast(proc, value, t);
- }
- // proc <-> proc
- if (is_type_proc(src) && is_type_proc(dst)) {
- return ir_emit_bitcast(proc, value, t);
- }
- // pointer -> proc
- if (is_type_pointer(src) && is_type_proc(dst)) {
- return ir_emit_bitcast(proc, value, t);
- }
- // proc -> pointer
- if (is_type_proc(src) && is_type_pointer(dst)) {
- return ir_emit_bitcast(proc, value, t);
- }
- // []byte/[]u8 <-> string
- if (is_type_u8_slice(src) && is_type_string(dst)) {
- irValue *elem = ir_slice_elem(proc, value);
- irValue *len = ir_slice_count(proc, value);
- return ir_emit_string(proc, elem, len);
- }
- if (is_type_string(src) && is_type_u8_slice(dst)) {
- irValue *elem = ir_string_elem(proc, value);
- irValue *elem_ptr = ir_add_local_generated(proc, ir_type(elem));
- ir_emit_store(proc, elem_ptr, elem);
- irValue *len = ir_string_len(proc, value);
- irValue *cap = len;
- irValue *slice = ir_add_local_slice(proc, t, elem_ptr, v_zero, len, cap);
- return ir_emit_load(proc, slice);
- }
- if (is_type_vector(dst)) {
- Type *dst_elem = dst->Vector.elem;
- value = ir_emit_conv(proc, value, dst_elem);
- irValue *v = ir_add_local_generated(proc, t);
- isize index_count = dst->Vector.count;
- for (i32 i = 0; i < index_count; i++) {
- irValue *elem = ir_emit_array_epi(proc, v, i);
- ir_emit_store(proc, elem, value);
- }
- return ir_emit_load(proc, v);
- }
- if (is_type_any(dst)) {
- irValue *result = ir_add_local_generated(proc, t_any);
- if (is_type_untyped_nil(src)) {
- return ir_emit_load(proc, result);
- }
- Type *st = default_type(src_type);
- irValue *data = nullptr;
- if (value->kind == irValue_Instr &&
- value->Instr.kind == irInstr_Load) {
- // NOTE(bill): Addreirble value
- data = value->Instr.Load.address;
- } else {
- // NOTE(bill): Non-addreirble value
- data = ir_add_local_generated(proc, st);
- ir_emit_store(proc, data, value);
- }
- GB_ASSERT(is_type_pointer(ir_type(data)));
- GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
- data = ir_emit_conv(proc, data, t_rawptr);
- irValue *ti = ir_type_info(proc, st);
- ir_emit_store(proc, ir_emit_struct_ep(proc, result, 0), data);
- ir_emit_store(proc, ir_emit_struct_ep(proc, result, 1), ti);
- return ir_emit_load(proc, result);
- }
- gb_printf_err("ir_emit_conv: src -> dst\n");
- gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
- gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
- GB_PANIC("Invalid type conversion: `%s` to `%s` for procedure `%.*s`",
- type_to_string(src_type), type_to_string(t),
- LIT(proc->name));
- return nullptr;
- }
- bool ir_is_type_aggregate(Type *t) {
- t = base_type(t);
- switch (t->kind) {
- case Type_Basic:
- switch (t->Basic.kind) {
- case Basic_string:
- case Basic_any:
- return true;
- // case Basic_complex32:
- case Basic_complex64:
- case Basic_complex128:
- return true;
- }
- break;
- case Type_Pointer:
- return false;
- case Type_Vector:
- case Type_Array:
- case Type_Slice:
- case Type_Struct:
- case Type_Tuple:
- case Type_DynamicArray:
- case Type_Map:
- case Type_BitField:
- return true;
- case Type_Named:
- return ir_is_type_aggregate(t->Named.base);
- }
- return false;
- }
- irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t) {
- Type *src_type = ir_type(value);
- if (are_types_identical(t, src_type)) {
- return value;
- }
- Type *src = base_type(src_type);
- Type *dst = base_type(t);
- irModule *m = proc->module;
- i64 sz = type_size_of(m->allocator, src);
- i64 dz = type_size_of(m->allocator, dst);
- GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: `%s` to `%s`", type_to_string(src_type), type_to_string(t));
- // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
- if (is_type_uintptr(src) && is_type_pointer(dst)) {
- return ir_emit_uintptr_to_ptr(proc, value, t);
- }
- if (is_type_pointer(src) && is_type_uintptr(dst)) {
- return ir_emit_ptr_to_uintptr(proc, value, t);
- }
- if (ir_is_type_aggregate(src) || ir_is_type_aggregate(dst)) {
- irValue *s = ir_address_from_load_or_generate_local(proc, value);
- irValue *d = ir_emit_bitcast(proc, s, make_type_pointer(m->allocator, t));
- return ir_emit_load(proc, d);
- }
- // TODO(bill): Actually figure out what the conversion needs to be correctly 'cause LLVM
- return ir_emit_bitcast(proc, value, dst);
- }
- irValue *ir_emit_union_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos, bool do_conversion_check=true) {
- gbAllocator a = proc->module->allocator;
- Type *src_type = ir_type(value);
- bool is_ptr = is_type_pointer(src_type);
- bool is_tuple = true;
- Type *tuple = type;
- if (type->kind != Type_Tuple) {
- is_tuple = false;
- tuple = make_optional_ok_type(a, type);
- }
- irValue *v = ir_add_local_generated(proc, tuple);
- if (is_ptr) {
- value = ir_emit_load(proc, value);
- }
- Type *src = base_type(type_deref(src_type));
- GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
- Type *dst = tuple->Tuple.variables[0]->type;
- irValue *value_ = ir_address_from_load_or_generate_local(proc, value);
- irValue *tag = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, value_));
- irValue *dst_tag = ir_const_union_tag(a, src, dst);
- irBlock *ok_block = ir_new_block(proc, nullptr, "union_cast.ok");
- irBlock *end_block = ir_new_block(proc, nullptr, "union_cast.end");
- irValue *cond = ir_emit_comp(proc, Token_CmpEq, tag, dst_tag);
- ir_emit_if(proc, cond, ok_block, end_block);
- ir_start_block(proc, ok_block);
- irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
- irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
- irValue *data = ir_emit_load(proc, ir_emit_conv(proc, value_, ir_type(gep0)));
- ir_emit_store(proc, gep0, data);
- ir_emit_store(proc, gep1, v_true);
- ir_emit_jump(proc, end_block);
- ir_start_block(proc, end_block);
- if (!is_tuple) {
- if (do_conversion_check) {
- // NOTE(bill): Panic on invalid conversion
- Type *dst_type = tuple->Tuple.variables[0]->type;
- irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
- irValue **args = gb_alloc_array(a, irValue *, 6);
- args[0] = ok;
- args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
- args[2] = ir_const_int(a, pos.line);
- args[3] = ir_const_int(a, pos.column);
- args[4] = ir_type_info(proc, src_type);
- args[5] = ir_type_info(proc, dst_type);
- ir_emit_global_call(proc, "__type_assertion_check", args, 6);
- }
- return ir_emit_load(proc, ir_emit_struct_ep(proc, v, 0));
- }
- return ir_emit_load(proc, v);
- }
- irAddr ir_emit_any_cast_addr(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
- gbAllocator a = proc->module->allocator;
- Type *src_type = ir_type(value);
- if (is_type_pointer(src_type)) {
- value = ir_emit_load(proc, value);
- }
- bool is_tuple = true;
- Type *tuple = type;
- if (type->kind != Type_Tuple) {
- is_tuple = false;
- tuple = make_optional_ok_type(a, type);
- }
- Type *dst_type = tuple->Tuple.variables[0]->type;
- irValue *v = ir_add_local_generated(proc, tuple);
- irValue *ti_ptr = ir_type_info(proc, dst_type);
- irValue *any_ti = ir_emit_struct_ev(proc, value, 1);
- irBlock *ok_block = ir_new_block(proc, nullptr, "any_cast.ok");
- irBlock *end_block = ir_new_block(proc, nullptr, "any_cast.end");
- irValue *cond = ir_emit_comp(proc, Token_CmpEq, any_ti, ti_ptr);
- ir_emit_if(proc, cond, ok_block, end_block);
- ir_start_block(proc, ok_block);
- irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
- irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
- irValue *any_data = ir_emit_struct_ev(proc, value, 0);
- irValue *ptr = ir_emit_conv(proc, any_data, make_type_pointer(a, dst_type));
- ir_emit_store(proc, gep0, ir_emit_load(proc, ptr));
- ir_emit_store(proc, gep1, v_true);
- ir_emit_jump(proc, end_block);
- ir_start_block(proc, end_block);
- if (!is_tuple) {
- // NOTE(bill): Panic on invalid conversion
- irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
- irValue **args = gb_alloc_array(a, irValue *, 6);
- args[0] = ok;
- args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
- args[2] = ir_const_int(a, pos.line);
- args[3] = ir_const_int(a, pos.column);
- args[4] = any_ti;
- args[5] = ti_ptr;
- ir_emit_global_call(proc, "__type_assertion_check", args, 6);
- return ir_addr(ir_emit_struct_ep(proc, v, 0));
- }
- return ir_addr(v);
- }
- irValue *ir_emit_any_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
- return ir_addr_load(proc, ir_emit_any_cast_addr(proc, value, type, pos));
- }
- // TODO(bill): Try and make a lot of this constant aggregate literals in LLVM IR
- gb_global irValue *ir_global_type_info_data = nullptr;
- gb_global irValue *ir_global_type_info_member_types = nullptr;
- gb_global irValue *ir_global_type_info_member_names = nullptr;
- gb_global irValue *ir_global_type_info_member_offsets = nullptr;
- gb_global irValue *ir_global_type_info_member_usings = nullptr;
- gb_global i32 ir_global_type_info_data_index = 0;
- gb_global i32 ir_global_type_info_member_types_index = 0;
- gb_global i32 ir_global_type_info_member_names_index = 0;
- gb_global i32 ir_global_type_info_member_offsets_index = 0;
- gb_global i32 ir_global_type_info_member_usings_index = 0;
- irValue *ir_type_info(irProcedure *proc, Type *type) {
- CheckerInfo *info = proc->module->info;
- type = default_type(type);
- i32 entry_index = cast(i32)type_info_index(info, type);
- GB_ASSERT(entry_index >= 0);
- // gb_printf_err("%d %s\n", entry_index, type_to_string(type));
- return ir_emit_array_ep(proc, ir_global_type_info_data, ir_const_i32(proc->module->allocator, entry_index));
- }
- irValue *ir_emit_logical_binary_expr(irProcedure *proc, AstNode *expr) {
- ast_node(be, BinaryExpr, expr);
- #if 0
- irBlock *true_ = ir_new_block(proc, nullptr, "logical.cmp.true");
- irBlock *false_ = ir_new_block(proc, nullptr, "logical.cmp.false");
- irBlock *done = ir_new_block(proc, nullptr, "logical.cmp.done");
- irValue *result = ir_add_local_generated(proc, t_bool);
- ir_build_cond(proc, expr, true_, false_);
- ir_start_block(proc, true_);
- ir_emit_store(proc, result, v_true);
- ir_emit_jump(proc, done);
- ir_start_block(proc, false_);
- ir_emit_store(proc, result, v_false);
- ir_emit_jump(proc, done);
- ir_start_block(proc, done);
- return ir_emit_load(proc, result);
- #else
- irBlock *rhs = ir_new_block(proc, nullptr, "logical.cmp.rhs");
- irBlock *done = ir_new_block(proc, nullptr, "logical.cmp.done");
- Type *type = type_of_expr(proc->module->info, expr);
- type = default_type(type);
- irValue *short_circuit = nullptr;
- if (be->op.kind == Token_CmpAnd) {
- ir_build_cond(proc, be->left, rhs, done);
- short_circuit = v_false;
- } else if (be->op.kind == Token_CmpOr) {
- ir_build_cond(proc, be->left, done, rhs);
- short_circuit = v_true;
- }
- if (rhs->preds.count == 0) {
- ir_start_block(proc, done);
- return short_circuit;
- }
- if (done->preds.count == 0) {
- ir_start_block(proc, rhs);
- return ir_build_expr(proc, be->right);
- }
- Array<irValue *> edges = {};
- array_init(&edges, proc->module->allocator, done->preds.count+1);
- for_array(i, done->preds) {
- array_add(&edges, short_circuit);
- }
- ir_start_block(proc, rhs);
- array_add(&edges, ir_build_expr(proc, be->right));
- ir_emit_jump(proc, done);
- ir_start_block(proc, done);
- return ir_emit(proc, ir_instr_phi(proc, edges, type));
- #endif
- }
- void ir_emit_bounds_check(irProcedure *proc, Token token, irValue *index, irValue *len) {
- if ((proc->module->stmt_state_flags & StmtStateFlag_no_bounds_check) != 0) {
- return;
- }
- index = ir_emit_conv(proc, index, t_int);
- len = ir_emit_conv(proc, len, t_int);
- gbAllocator a = proc->module->allocator;
- irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
- irValue *line = ir_const_int(a, token.pos.line);
- irValue *column = ir_const_int(a, token.pos.column);
- irValue **args = gb_alloc_array(a, irValue *, 5);
- args[0] = file;
- args[1] = line;
- args[2] = column;
- args[3] = index;
- args[4] = len;
- ir_emit_global_call(proc, "__bounds_check_error", args, 5);
- // ir_emit(proc, ir_instr_bounds_check(proc, token.pos, index, len));
- }
- void ir_emit_slice_bounds_check(irProcedure *proc, Token token, irValue *low, irValue *high, irValue *max, bool is_substring) {
- if ((proc->module->stmt_state_flags & StmtStateFlag_no_bounds_check) != 0) {
- return;
- }
- gbAllocator a = proc->module->allocator;
- irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
- irValue *line = ir_const_int(a, token.pos.line);
- irValue *column = ir_const_int(a, token.pos.column);
- low = ir_emit_conv(proc, low, t_int);
- high = ir_emit_conv(proc, high, t_int);
- irValue **args = gb_alloc_array(a, irValue *, 6);
- args[0] = file;
- args[1] = line;
- args[2] = column;
- args[3] = low;
- args[4] = high;
- args[5] = max;
- if (is_substring) {
- ir_emit_global_call(proc, "__substring_expr_error", args, 5);
- } else {
- ir_emit_global_call(proc, "__slice_expr_error", args, 6);
- }
- // ir_emit(proc, ir_instr_slice_bounds_check(proc, token.pos, low, high, max, is_substring));
- }
- ////////////////////////////////////////////////////////////////
- //
- // @Build
- //
- ////////////////////////////////////////////////////////////////
- String ir_mangle_name(irGen *s, String path, Entity *e) {
- // NOTE(bill): prefix names not in the init scope
- // TODO(bill): make robust and not just rely on the file's name
- String name = e->token.string;
- irModule *m = &s->module;
- CheckerInfo *info = m->info;
- gbAllocator a = m->allocator;
- AstFile *file = ast_file_of_filename(info, path);
- char *str = gb_alloc_array(a, char, path.len+1);
- gb_memmove(str, path.text, path.len);
- str[path.len] = 0;
- for (isize i = 0; i < path.len; i++) {
- if (str[i] == '\\') {
- str[i] = '/';
- }
- }
- char const *base = gb_path_base_name(str);
- char const *ext = gb_path_extension(base);
- isize base_len = ext-1-base;
- isize max_len = base_len + 1 + 1 + 10 + 1 + name.len;
- bool require_suffix_id = check_is_entity_overloaded(e) || is_type_polymorphic(e->type);
- if (require_suffix_id) {
- max_len += 21;
- }
- u8 *new_name = gb_alloc_array(a, u8, max_len);
- isize new_name_len = 0;
- if ((base_len > 0 && gb_char_is_digit(base[0])) ||
- base_len == 0) {
- new_name_len = gb_snprintf(
- cast(char *)new_name, max_len,
- "_%.*s-%u.%.*s",
- cast(int)base_len, base,
- cast(u32)file->id,
- LIT(name));
- } else {
- new_name_len = gb_snprintf(
- cast(char *)new_name, max_len,
- "%.*s-%u.%.*s",
- cast(int)base_len, base,
- cast(u32)file->id,
- LIT(name));
- }
- if (require_suffix_id) {
- char *str = cast(char *)new_name + new_name_len-1;
- isize len = max_len-new_name_len;
- isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
- new_name_len += extra-1;
- }
- return make_string(new_name, new_name_len-1);
- }
- void ir_mangle_add_sub_type_name(irModule *m, Entity *field, String parent) {
- if (field->kind != Entity_TypeName) {
- return;
- }
- String cn = field->token.string;
- isize len = parent.len + 1 + 16 + 1 + cn.len;
- u8 *text = gb_alloc_array(m->allocator, u8, len);
- isize new_name_len = gb_snprintf(cast(char *)text, len,
- "%.*s.%.*s", LIT(parent), LIT(cn));
- String child = {text, new_name_len-1};
- GB_ASSERT(child.len > 0);
- ir_add_entity_name(m, field, child);
- ir_gen_global_type_name(m, field, child);
- }
- irBranchBlocks ir_lookup_branch_blocks(irProcedure *proc, AstNode *ident) {
- GB_ASSERT(ident->kind == AstNode_Ident);
- Entity *e = entity_of_ident(proc->module->info, ident);
- GB_ASSERT(e->kind == Entity_Label);
- for_array(i, proc->branch_blocks) {
- irBranchBlocks *b = &proc->branch_blocks[i];
- if (b->label == e->Label.node) {
- return *b;
- }
- }
- GB_PANIC("Unreachable");
- irBranchBlocks empty = {};
- return empty;
- }
- void ir_push_target_list(irProcedure *proc, AstNode *label, irBlock *break_, irBlock *continue_, irBlock *fallthrough_) {
- irTargetList *tl = gb_alloc_item(proc->module->allocator, irTargetList);
- tl->prev = proc->target_list;
- tl->break_ = break_;
- tl->continue_ = continue_;
- tl->fallthrough_ = fallthrough_;
- proc->target_list = tl;
- if (label != nullptr) { // Set label blocks
- GB_ASSERT(label->kind == AstNode_Label);
- for_array(i, proc->branch_blocks) {
- irBranchBlocks *b = &proc->branch_blocks[i];
- GB_ASSERT(b->label != nullptr && label != nullptr);
- GB_ASSERT(b->label->kind == AstNode_Label);
- if (b->label == label) {
- b->break_ = break_;
- b->continue_ = continue_;
- return;
- }
- }
- GB_PANIC("ir_set_label_blocks: Unreachable");
- }
- }
- void ir_pop_target_list(irProcedure *proc) {
- proc->target_list = proc->target_list->prev;
- }
- irValue *ir_gen_anonymous_proc_lit(irModule *m, String prefix_name, AstNode *expr, irProcedure *proc = nullptr) {
- ast_node(pl, ProcLit, expr);
- // NOTE(bill): Generate a new name
- // parent$count
- isize name_len = prefix_name.len + 1 + 8 + 1;
- u8 *name_text = gb_alloc_array(m->allocator, u8, name_len);
- i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
- name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
- String name = make_string(name_text, name_len-1);
- Type *type = type_of_expr(m->info, expr);
- irValue *value = ir_value_procedure(m->allocator,
- m, nullptr, type, pl->type, pl->body, name);
- value->Proc.tags = pl->tags;
- value->Proc.inlining = pl->inlining;
- value->Proc.parent = proc;
- array_add(&m->procs_to_generate, value);
- if (proc != nullptr) {
- array_add(&proc->children, &value->Proc);
- } else {
- map_set(&m->members, hash_string(name), value);
- }
- map_set(&m->anonymous_proc_lits, hash_pointer(expr), value);
- return value;
- }
- void ir_check_type_and_gen_for_proc_lit(irProcedure *proc, Type *t) {
- if (t == nullptr) return;
- if (t->kind == Type_Struct && t->Struct.has_proc_default_values) {
- for_array(i, t->Struct.fields) {
- Entity *f = t->Struct.fields[i];
- if (f->kind == Entity_Variable && f->Variable.default_value.kind == ExactValue_Procedure) {
- AstNode *expr = f->Variable.default_value.value_procedure;
- GB_ASSERT(expr != nullptr);
- if (expr->kind == AstNode_ProcLit) {
- ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
- }
- }
- }
- }
- }
- void ir_check_type_and_gen_for_proc_lit(irModule *m, String prefix_name, Type *t) {
- if (t == nullptr) return;
- if (t->kind == Type_Struct && t->Struct.has_proc_default_values) {
- for_array(i, t->Struct.fields) {
- Entity *f = t->Struct.fields[i];
- if (f->kind == Entity_Variable && f->Variable.default_value.kind == ExactValue_Procedure) {
- AstNode *expr = f->Variable.default_value.value_procedure;
- GB_ASSERT(expr != nullptr);
- if (expr->kind == AstNode_ProcLit) {
- ir_gen_anonymous_proc_lit(m, prefix_name, expr);
- }
- }
- }
- }
- }
- void ir_gen_global_type_name(irModule *m, Entity *e, String name) {
- if (e->type == nullptr) return;
- if (e->kind == Entity_TypeName && e->type->kind == Type_Named) {
- if (e != e->type->Named.type_name) {
- // NOTE(bill): Is alias
- return;
- }
- }
- Type *bt = base_type(e->type);
- bool is_poly = is_type_polymorphic(bt);
- if (!is_poly) {
- if (bt->kind == Type_Struct &&
- bt->Struct.is_polymorphic &&
- !bt->Struct.is_poly_specialized) {
- is_poly = true;
- }
- }
- if (is_poly) {
- auto found = map_get(&m->info->gen_types, hash_pointer(e->type));
- if (found != nullptr) {
- for_array(i, *found) {
- Entity *sub = (*found)[i];
- // gb_printf_err("--> %.*s\n", LIT(sub->token.string));
- if (ptr_set_exists(&m->min_dep_set, sub)) {
- ir_mangle_add_sub_type_name(m, sub, name);
- }
- }
- }
- return;
- }
- if (!ptr_set_exists(&m->min_dep_set, e)) return;
- irValue *t = ir_value_type_name(m->allocator, name, e->type);
- ir_module_add_value(m, e, t);
- map_set(&m->members, hash_string(name), t);
- #if 0
- if (is_type_union(e->type)) {
- Type *bt = base_type(e->type);
- // NOTE(bill): Zeroth entry is null (for `match type` stmts)
- for (isize j = 1; j < bt->Struct.variant_count; j++) {
- ir_mangle_add_sub_type_name(m, bt->Struct.variants[j], name);
- }
- }
- #endif
- // if (bt->kind == Type_Struct) {
- // Scope *s = bt->Struct.scope;
- // if (s != nullptr) {
- // for_array(i, s->elements.entries) {
- // Entity *e = s->elements.entries[i].value;
- // if (e->kind == Entity_TypeName) {
- // ir_mangle_add_sub_type_name(m, e, name);
- // }
- // }
- // }
- // }
- ir_check_type_and_gen_for_proc_lit(m, e->token.string, bt);
- }
- void ir_build_defer_stmt(irProcedure *proc, irDefer d) {
- irBlock *b = ir_new_block(proc, nullptr, "defer");
- // NOTE(bill): The prev block may defer injection before it's terminator
- irInstr *last_instr = ir_get_last_instr(proc->curr_block);
- if (last_instr == nullptr || !ir_is_instr_terminating(last_instr)) {
- ir_emit_jump(proc, b);
- }
- ir_start_block(proc, b);
- ir_emit_comment(proc, str_lit("defer"));
- if (d.kind == irDefer_Node) {
- ir_build_stmt(proc, d.stmt);
- } else if (d.kind == irDefer_Instr) {
- // NOTE(bill): Need to make a new copy
- irValue *instr = cast(irValue *)gb_alloc_copy(proc->module->allocator, d.instr, gb_size_of(irValue));
- ir_emit(proc, instr);
- }
- }
- irValue *ir_emit_clamp(irProcedure *proc, Type *t, irValue *x, irValue *min, irValue *max) {
- irValue *cond = nullptr;
- ir_emit_comment(proc, str_lit("clamp"));
- x = ir_emit_conv(proc, x, t);
- min = ir_emit_conv(proc, min, t);
- max = ir_emit_conv(proc, max, t);
- cond = ir_emit_comp(proc, Token_Gt, min, x);
- x = ir_emit_select(proc, cond, min, x);
- cond = ir_emit_comp(proc, Token_Lt, max, x);
- x = ir_emit_select(proc, cond, max, x);
- return x;
- }
- irValue *ir_find_global_variable(irProcedure *proc, String name) {
- irValue **value = map_get(&proc->module->members, hash_string(name));
- GB_ASSERT_MSG(value != nullptr, "Unable to find global variable `%.*s`", LIT(name));
- return *value;
- }
- void ir_build_stmt_list(irProcedure *proc, Array<AstNode *> stmts);
- bool is_double_pointer(Type *t) {
- if (!is_type_pointer(t)) {
- return false;
- }
- Type *td = type_deref(t);
- if (td == nullptr || td == t) {
- return false;
- }
- return is_type_pointer(td);
- }
- irValue *ir_emit_source_code_location(irProcedure *proc, String procedure, TokenPos pos) {
- gbAllocator a = proc->module->allocator;
- irValue **args = gb_alloc_array(a, irValue *, 4);
- args[0] = ir_find_or_add_entity_string(proc->module, pos.file);
- args[1] = ir_const_i64(a, pos.line);
- args[2] = ir_const_i64(a, pos.column);
- args[3] = ir_find_or_add_entity_string(proc->module, procedure);
- return ir_emit_global_call(proc, "make_source_code_location", args, 4);
- }
- void ir_emit_increment(irProcedure *proc, irValue *addr) {
- GB_ASSERT(is_type_pointer(ir_type(addr)));
- Type *type = type_deref(ir_type(addr));
- ir_emit_store(proc, addr, ir_emit_arith(proc, Token_Add, ir_emit_load(proc, addr), v_one, type));
- }
- void ir_init_data_with_defaults(irProcedure *proc, irValue *ptr, irValue *count) {
- Type *elem_type = type_deref(ir_type(ptr));
- GB_ASSERT(is_type_struct(elem_type) || is_type_array(elem_type));
- irValue *index = ir_add_local_generated(proc, t_int);
- ir_emit_store(proc, index, ir_const_int(proc->module->allocator, 0));
- irBlock *loop = nullptr;
- irBlock *done = nullptr;
- irBlock *body = nullptr;
- loop = ir_new_block(proc, nullptr, "make.init.loop");
- ir_emit_jump(proc, loop);
- ir_start_block(proc, loop);
- body = ir_new_block(proc, nullptr, "make.init.body");
- done = ir_new_block(proc, nullptr, "make.init.done");
- irValue *cond = ir_emit_comp(proc, Token_Lt, ir_emit_load(proc, index), count);
- ir_emit_if(proc, cond, body, done);
- ir_start_block(proc, body);
- irValue *offset_ptr = ir_emit_ptr_offset(proc, ptr, ir_emit_load(proc, index));
- ir_emit_zero_init(proc, offset_ptr);
- ir_emit_increment(proc, index);
- ir_emit_jump(proc, loop);
- ir_start_block(proc, done);
- }
- irValue *ir_build_builtin_proc(irProcedure *proc, AstNode *expr, TypeAndValue tv, BuiltinProcId id) {
- ast_node(ce, CallExpr, expr);
- switch (id) {
- case BuiltinProc_DIRECTIVE: {
- ast_node(bd, BasicDirective, ce->proc);
- String name = bd->name;
- GB_ASSERT(name == "location");
- String procedure = proc->entity->token.string;
- TokenPos pos = ast_node_token(ce->proc).pos;
- if (ce->args.count > 0) {
- AstNode *ident = ce->args[0];;
- while (ident->kind == AstNode_SelectorExpr) {
- ident = ident->SelectorExpr.selector;
- }
- Entity *e = entity_of_ident(proc->module->info, ident);
- GB_ASSERT(e != nullptr);
- if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity_count > 0) {
- procedure = e->parent_proc_decl->entities[0]->token.string;
- } else {
- procedure = str_lit("");
- }
- pos = e->token.pos;
- }
- return ir_emit_source_code_location(proc, procedure, pos);
- break;
- }
- case BuiltinProc_type_info_of: {
- Type *t = default_type(type_of_expr(proc->module->info, ce->args[0]));
- return ir_type_info(proc, t);
- break;
- }
- case BuiltinProc_len: {
- irValue *v = ir_build_expr(proc, ce->args[0]);
- Type *t = base_type(ir_type(v));
- if (is_type_pointer(t)) {
- // IMPORTANT TODO(bill): Should there be a nil pointer check?
- v = ir_emit_load(proc, v);
- t = type_deref(t);
- }
- if (is_type_string(t)) {
- return ir_string_len(proc, v);
- } else if (is_type_array(t)) {
- GB_PANIC("Array lengths are constant");
- } else if (is_type_vector(t)) {
- GB_PANIC("Vector lengths are constant");
- } else if (is_type_slice(t)) {
- return ir_slice_count(proc, v);
- } else if (is_type_dynamic_array(t)) {
- return ir_dynamic_array_count(proc, v);
- } else if (is_type_map(t)) {
- ir_emit_comment(proc, str_lit("len: map"));
- irValue *entries = ir_emit_struct_ev(proc, v, 1);
- return ir_dynamic_array_count(proc, entries);
- }
- GB_PANIC("Unreachable");
- break;
- }
- case BuiltinProc_cap: {
- irValue *v = ir_build_expr(proc, ce->args[0]);
- Type *t = base_type(ir_type(v));
- if (is_type_pointer(t)) {
- // IMPORTANT TODO(bill): Should there be a nil pointer check?
- v = ir_emit_load(proc, v);
- t = type_deref(t);
- }
- if (is_type_string(t)) {
- GB_PANIC("Unreachable");
- } else if (is_type_array(t)) {
- GB_PANIC("Array lengths are constant");
- } else if (is_type_vector(t)) {
- GB_PANIC("Unreachable");
- } else if (is_type_slice(t)) {
- return ir_slice_capacity(proc, v);
- } else if (is_type_dynamic_array(t)) {
- return ir_dynamic_array_capacity(proc, v);
- } else if (is_type_map(t)) {
- irValue *entries = ir_emit_struct_ev(proc, v, 1);
- return ir_dynamic_array_capacity(proc, entries);
- }
- GB_PANIC("Unreachable");
- break;
- }
- #if 0
- case BuiltinProc_new: {
- ir_emit_comment(proc, str_lit("new"));
- // proc new(Type) -> ^Type
- gbAllocator a = proc->module->allocator;
- Type *type = type_of_expr(proc->module->info, ce->args[0]);
- Type *allocation_type = type;
- i32 variant_index = 0;
- if (is_type_struct(type)) {
- Type *st = base_type(type);
- if (st->Struct.variant_parent != nullptr) {
- allocation_type = st->Struct.variant_parent;
- variant_index = st->Struct.variant_index;
- GB_ASSERT(allocation_type != nullptr);
- }
- }
- Type *ptr_type = make_type_pointer(a, type);
- i64 size = type_size_of(a, allocation_type);
- i64 align = type_align_of(a, allocation_type);
- irValue **args = gb_alloc_array(a, irValue *, 2);
- args[0] = ir_const_int(a, size);
- args[1] = ir_const_int(a, align);
- irValue *call = ir_emit_global_call(proc, "alloc", args, 2);
- irValue *v = ir_emit_conv(proc, call, ptr_type);
- if (type != allocation_type) {
- Type *u = base_type(allocation_type);
- Type *uptr_type = make_type_pointer(a, u);
- irValue *parent = ir_emit_conv(proc, call, uptr_type);
- irValue *tag_ptr = ir_emit_union_tag_ptr(proc, parent);
- ir_emit_store(proc, tag_ptr, ir_const_int(a, variant_index));
- }
- return v;
- break;
- }
- #endif
- case BuiltinProc_make: {
- ir_emit_comment(proc, str_lit("make"));
- gbAllocator a = proc->module->allocator;
- Type *type = type_of_expr(proc->module->info, ce->args[0]);
- if (is_type_slice(type)) {
- Type *elem_type = core_type(type)->Slice.elem;
- Type *elem_ptr_type = make_type_pointer(a, elem_type);
- irValue *elem_size = ir_const_int(a, type_size_of(a, elem_type));
- irValue *elem_align = ir_const_int(a, type_align_of(a, elem_type));
- irValue *count = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int);
- irValue *capacity = count;
- if (ce->args.count == 3) {
- capacity = ir_emit_conv(proc, ir_build_expr(proc, ce->args[2]), t_int);
- }
- ir_emit_slice_bounds_check(proc, ast_node_token(ce->args[1]), v_zero, count, capacity, false);
- irValue *slice_size = ir_emit_arith(proc, Token_Mul, elem_size, capacity, t_int);
- irValue **args = gb_alloc_array(a, irValue *, 2);
- args[0] = slice_size;
- args[1] = elem_align;
- irValue *call = ir_emit_global_call(proc, "alloc", args, 2);
- irValue *ptr = ir_emit_conv(proc, call, elem_ptr_type);
- if (ir_type_has_default_values(elem_type)) {
- ir_init_data_with_defaults(proc, ptr, count);
- }
- irValue *slice = ir_add_local_generated(proc, type);
- ir_fill_slice(proc, slice, ptr, count, capacity);
- return ir_emit_load(proc, slice);
- } else if (is_type_map(type)) {
- irValue *int_16 = ir_const_int(a, 16);
- irValue *cap = int_16;
- if (ce->args.count == 2) {
- cap = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int);
- }
- irValue *cond = ir_emit_comp(proc, Token_Gt, cap, v_zero);
- cap = ir_emit_select(proc, cond, cap, int_16);
- irValue *map = ir_add_local_generated(proc, type);
- irValue *header = ir_gen_map_header(proc, map, base_type(type));
- irValue **args = gb_alloc_array(a, irValue *, 2);
- args[0] = header;
- args[1] = cap;
- ir_emit_global_call(proc, "__dynamic_map_reserve", args, 2);
- return ir_emit_load(proc, map);
- } else if (is_type_dynamic_array(type)) {
- Type *elem_type = base_type(type)->DynamicArray.elem;
- irValue *len = v_zero;
- if (ce->args.count > 1) {
- len = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int);
- }
- irValue *cap = len;
- if (ce->args.count > 2) {
- cap = ir_emit_conv(proc, ir_build_expr(proc, ce->args[2]), t_int);
- }
- ir_emit_slice_bounds_check(proc, ast_node_token(ce->args[0]), v_zero, len, cap, false);
- irValue *array = ir_add_local_generated(proc, type);
- irValue **args = gb_alloc_array(a, irValue *, 5);
- args[0] = ir_emit_conv(proc, array, t_rawptr);
- args[1] = ir_const_int(a, type_size_of(a, elem_type));
- args[2] = ir_const_int(a, type_align_of(a, elem_type));
- args[3] = len;
- args[4] = cap;
- ir_emit_global_call(proc, "__dynamic_array_make", args, 5);
- if (ir_type_has_default_values(elem_type)) {
- ir_init_data_with_defaults(proc, ir_dynamic_array_elem(proc, ir_emit_load(proc, array)), len);
- }
- return ir_emit_load(proc, array);
- }
- break;
- }
- #if 0
- case BuiltinProc_free: {
- ir_emit_comment(proc, str_lit("free"));
- gbAllocator a = proc->module->allocator;
- AstNode *node = ce->args[0];
- TypeAndValue tav = type_and_value_of_expr(proc->module->info, node);
- Type *type = base_type(tav.type);
- if (is_type_dynamic_array(type)) {
- irValue *val = ir_build_expr(proc, node);
- irValue *da_allocator = ir_emit_struct_ev(proc, val, 3);
- irValue *ptr = ir_emit_struct_ev(proc, val, 0);
- ptr = ir_emit_conv(proc, ptr, t_rawptr);
- irValue **args = gb_alloc_array(a, irValue *, 1);
- args[0] = da_allocator;
- args[1] = ptr;
- return ir_emit_global_call(proc, "free_ptr_with_allocator", args, 2);
- } else if (is_type_map(type)) {
- irValue *map = ir_build_expr(proc, node);
- irValue *map_ptr = ir_address_from_load_or_generate_local(proc, map);
- {
- irValue *array = ir_emit_struct_ep(proc, map_ptr, 0);
- irValue *da_allocator = ir_emit_load(proc, ir_emit_struct_ep(proc, array, 3));
- irValue *da_ptr = ir_emit_load(proc, ir_emit_struct_ep(proc, array, 0));
- da_ptr = ir_emit_conv(proc, da_ptr, t_rawptr);
- irValue **args = gb_alloc_array(a, irValue *, 1);
- args[0] = da_allocator;
- args[1] = da_ptr;
- ir_emit_global_call(proc, "free_ptr_with_allocator", args, 2);
- }
- {
- irValue *array = ir_emit_struct_ep(proc, map_ptr, 1);
- irValue *da_allocator = ir_emit_load(proc, ir_emit_struct_ep(proc, array, 3));
- irValue *da_ptr = ir_emit_load(proc, ir_emit_struct_ep(proc, array, 0));
- da_ptr = ir_emit_conv(proc, da_ptr, t_rawptr);
- irValue **args = gb_alloc_array(a, irValue *, 1);
- args[0] = da_allocator;
- args[1] = da_ptr;
- ir_emit_global_call(proc, "free_ptr_with_allocator", args, 2);
- }
- return nullptr;
- }
- irValue *val = ir_build_expr(proc, node);
- irValue *ptr = nullptr;
- if (is_type_pointer(type)) {
- ptr = val;
- } else if (is_type_slice(type)) {
- ptr = ir_slice_elem(proc, val);
- } else if (is_type_string(type)) {
- ptr = ir_string_elem(proc, val);
- } else {
- GB_PANIC("Invalid type to `free`");
- }
- if (ptr == nullptr) {
- return nullptr;
- }
- ptr = ir_emit_conv(proc, ptr, t_rawptr);
- irValue **args = gb_alloc_array(a, irValue *, 1);
- args[0] = ptr;
- return ir_emit_global_call(proc, "free_ptr", args, 1);
- break;
- }
- #endif
- #if 0
- case BuiltinProc_reserve: {
- ir_emit_comment(proc, str_lit("reserve"));
- gbAllocator a = proc->module->allocator;
- irValue *ptr = ir_build_addr_ptr(proc, ce->args[0]);
- Type *type = ir_type(ptr);
- GB_ASSERT(is_type_pointer(type));
- type = base_type(type_deref(type));
- irValue *capacity = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int);
- if (is_type_dynamic_array(type)) {
- Type *elem = type->DynamicArray.elem;
- irValue *elem_size = ir_const_int(a, type_size_of(a, elem));
- irValue *elem_align = ir_const_int(a, type_align_of(a, elem));
- ptr = ir_emit_conv(proc, ptr, t_rawptr);
- irValue **args = gb_alloc_array(a, irValue *, 4);
- args[0] = ptr;
- args[1] = elem_size;
- args[2] = elem_align;
- args[3] = capacity;
- return ir_emit_global_call(proc, "__dynamic_array_reserve", args, 4);
- } else if (is_type_map(type)) {
- irValue **args = gb_alloc_array(a, irValue *, 2);
- args[0] = ir_gen_map_header(proc, ptr, type);
- args[1] = capacity;
- return ir_emit_global_call(proc, "__dynamic_map_reserve", args, 2);
- } else {
- GB_PANIC("Unknown type for `reserve`");
- }
- break;
- }
- #endif
- #if 0
- case BuiltinProc_clear: {
- ir_emit_comment(proc, str_lit("clear"));
- Type *original_type = type_of_expr(proc->module->info, ce->args[0]);
- irAddr addr = ir_build_addr(proc, ce->args[0]);
- irValue *ptr = addr.addr;
- if (is_double_pointer(ir_type(ptr))) {
- ptr = ir_addr_load(proc, addr);
- }
- Type *t = base_type(type_deref(original_type));
- if (is_type_dynamic_array(t)) {
- irValue *count_ptr = ir_emit_struct_ep(proc, ptr, 1);
- ir_emit_store(proc, count_ptr, v_zero);
- } else if (is_type_map(t)) {
- irValue *ha = ir_emit_struct_ep(proc, ptr, 0);
- irValue *ea = ir_emit_struct_ep(proc, ptr, 1);
- ir_emit_store(proc, ir_emit_struct_ep(proc, ha, 1), v_zero);
- ir_emit_store(proc, ir_emit_struct_ep(proc, ea, 1), v_zero);
- } else if (is_type_slice(t)) {
- irValue *count_ptr = ir_emit_struct_ep(proc, ptr, 1);
- ir_emit_store(proc, count_ptr, v_zero);
- } else {
- GB_PANIC("TODO(bill): ir clear for `%s`", type_to_string(t));
- }
- return nullptr;
- break;
- }
- #endif
- #if 0
- case BuiltinProc_append: {
- ir_emit_comment(proc, str_lit("append"));
- gbAllocator a = proc->module->allocator;
- Type *value_type = type_of_expr(proc->module->info, ce->args[0]);
- irAddr array_addr = ir_build_addr(proc, ce->args[0]);
- irValue *array_ptr = array_addr.addr;
- if (is_double_pointer(ir_type(array_ptr))) {
- array_ptr = ir_addr_load(proc, array_addr);
- }
- Type *type = ir_type(array_ptr);
- {
- TokenPos pos = ast_node_token(ce->args[0]).pos;
- GB_ASSERT_MSG(is_type_pointer(type), "%.*s(%td) %s",
- LIT(pos.file), pos.line,
- type_to_string(type));
- }
- type = base_type(type_deref(type));
- Type *elem_type = nullptr;
- bool is_slice = false;
- if (is_type_dynamic_array(type)) {
- elem_type = type->DynamicArray.elem;
- } else if (is_type_slice(type)) {
- is_slice = true;
- elem_type = type->Slice.elem;
- } else {
- GB_PANIC("Invalid type to append");
- }
- irValue *elem_size = ir_const_int(a, type_size_of(a, elem_type));
- irValue *elem_align = ir_const_int(a, type_align_of(a, elem_type));
- array_ptr = ir_emit_conv(proc, array_ptr, t_rawptr);
- isize arg_index = 0;
- isize arg_count = 0;
- for_array(i, ce->args) {
- AstNode *a = ce->args[i];
- Type *at = base_type(type_of_expr(proc->module->info, a));
- if (at->kind == Type_Tuple) {
- arg_count += at->Tuple.variable_count;
- } else {
- arg_count++;
- }
- }
- irValue **args = gb_alloc_array(proc->module->allocator, irValue *, arg_count);
- bool vari_expand = ce->ellipsis.pos.line != 0;
- for_array(i, ce->args) {
- irValue *a = ir_build_expr(proc, ce->args[i]);
- Type *at = ir_type(a);
- if (at->kind == Type_Tuple) {
- for (isize i = 0; i < at->Tuple.variable_count; i++) {
- Entity *e = at->Tuple.variables[i];
- irValue *v = ir_emit_struct_ev(proc, a, i);
- args[arg_index++] = v;
- }
- } else {
- args[arg_index++] = a;
- }
- }
- if (!vari_expand) {
- for (isize i = 1; i < arg_count; i++) {
- args[i] = ir_emit_conv(proc, args[i], elem_type);
- }
- }
- if (!vari_expand) {
- ir_emit_comment(proc, str_lit("variadic call argument generation"));
- Type *slice_type = make_type_slice(a, elem_type);
- irValue *slice = ir_add_local_generated(proc, slice_type);
- isize slice_len = arg_count-1;
- if (slice_len > 0) {
- irValue *base_array = ir_add_local_generated(proc, make_type_array(a, elem_type, slice_len));
- for (isize i = 1; i < arg_count; i++) {
- irValue *addr = ir_emit_array_epi(proc, base_array, i-1);
- ir_emit_store(proc, addr, args[i]);
- }
- irValue *base_elem = ir_emit_array_epi(proc, base_array, 0);
- irValue *len = ir_const_int(a, slice_len);
- ir_fill_slice(proc, slice, base_elem, len, len);
- }
- arg_count = 2;
- args[arg_count-1] = ir_emit_load(proc, slice);
- }
- irValue *item_slice = args[1];
- irValue *items = ir_slice_elem(proc, item_slice);
- irValue *item_count = ir_slice_count(proc, item_slice);
- irValue **daa_args = gb_alloc_array(a, irValue *, 5);
- daa_args[0] = array_ptr;
- daa_args[1] = elem_size;
- daa_args[2] = elem_align;
- daa_args[3] = ir_emit_conv(proc, items, t_rawptr);
- daa_args[4] = ir_emit_conv(proc, item_count, t_int);
- if (is_slice) {
- return ir_emit_global_call(proc, "__slice_append", daa_args, 5);
- }
- return ir_emit_global_call(proc, "__dynamic_array_append", daa_args, 5);
- break;
- }
- #endif
- #if 0
- case BuiltinProc_delete: {
- ir_emit_comment(proc, str_lit("delete"));
- irValue *map = ir_build_expr(proc, ce->args[0]);
- irValue *key = ir_build_expr(proc, ce->args[1]);
- Type *map_type = ir_type(map);
- GB_ASSERT(is_type_map(map_type));
- Type *key_type = base_type(map_type)->Map.key;
- irValue *addr = ir_address_from_load_or_generate_local(proc, map);
- gbAllocator a = proc->module->allocator;
- irValue **args = gb_alloc_array(a, irValue *, 2);
- args[0] = ir_gen_map_header(proc, addr, map_type);
- args[1] = ir_gen_map_key(proc, key, key_type);
- return ir_emit_global_call(proc, "__dynamic_map_delete", args, 2);
- break;
- }
- #endif
- case BuiltinProc_swizzle: {
- ir_emit_comment(proc, str_lit("swizzle.begin"));
- irAddr vector_addr = ir_build_addr(proc, ce->args[0]);
- isize index_count = ce->args.count-1;
- if (index_count == 0) {
- return ir_addr_load(proc, vector_addr);
- }
- irValue *src = ir_addr_get_ptr(proc, vector_addr);
- irValue *dst = ir_add_local_generated(proc, tv.type);
- for (i32 i = 1; i < ce->args.count; i++) {
- TypeAndValue tv = type_and_value_of_expr(proc->module->info, ce->args[i]);
- GB_ASSERT(is_type_integer(tv.type));
- GB_ASSERT(tv.value.kind == ExactValue_Integer);
- i32 src_index = cast(i32)i128_to_i64(tv.value.value_integer);
- i32 dst_index = i-1;
- irValue *src_elem = ir_emit_array_epi(proc, src, src_index);
- irValue *dst_elem = ir_emit_array_epi(proc, dst, dst_index);
- ir_emit_store(proc, dst_elem, ir_emit_load(proc, src_elem));
- }
- ir_emit_comment(proc, str_lit("swizzle.end"));
- return ir_emit_load(proc, dst);
- // return ir_emit(proc, ir_instr_vector_shuffle(proc, vector, indices, index_count));
- break;
- }
- case BuiltinProc_complex: {
- ir_emit_comment(proc, str_lit("complex"));
- irValue *real = ir_build_expr(proc, ce->args[0]);
- irValue *imag = ir_build_expr(proc, ce->args[1]);
- irValue *dst = ir_add_local_generated(proc, tv.type);
- Type *ft = base_complex_elem_type(tv.type);
- real = ir_emit_conv(proc, real, ft);
- imag = ir_emit_conv(proc, imag, ft);
- ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 0), real);
- ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 1), imag);
- return ir_emit_load(proc, dst);
- break;
- }
- case BuiltinProc_real: {
- ir_emit_comment(proc, str_lit("real"));
- irValue *val = ir_build_expr(proc, ce->args[0]);
- irValue *real = ir_emit_struct_ev(proc, val, 0);
- return ir_emit_conv(proc, real, tv.type);
- break;
- }
- case BuiltinProc_imag: {
- ir_emit_comment(proc, str_lit("imag"));
- irValue *val = ir_build_expr(proc, ce->args[0]);
- irValue *imag = ir_emit_struct_ev(proc, val, 1);
- return ir_emit_conv(proc, imag, tv.type);
- break;
- }
- case BuiltinProc_conj: {
- ir_emit_comment(proc, str_lit("conj"));
- irValue *val = ir_build_expr(proc, ce->args[0]);
- irValue *res = nullptr;
- Type *t = ir_type(val);
- if (is_type_complex(t)) {
- res = ir_add_local_generated(proc, tv.type);
- irValue *real = ir_emit_struct_ev(proc, val, 0);
- irValue *imag = ir_emit_struct_ev(proc, val, 1);
- imag = ir_emit_unary_arith(proc, Token_Sub, imag, ir_type(imag));
- ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
- ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
- }
- return ir_emit_load(proc, res);
- break;
- }
- #if 0
- case BuiltinProc_slice_ptr: {
- ir_emit_comment(proc, str_lit("slice_ptr"));
- irValue *ptr = ir_build_expr(proc, ce->args[0]);
- irValue *count = ir_build_expr(proc, ce->args[1]);
- count = ir_emit_conv(proc, count, t_int);
- irValue *capacity = count;
- if (ce->args.count > 2) {
- capacity = ir_build_expr(proc, ce->args[2]);
- capacity = ir_emit_conv(proc, capacity, t_int);
- }
- Type *slice_type = make_type_slice(proc->module->allocator, type_deref(ir_type(ptr)));
- irValue *slice = ir_add_local_generated(proc, slice_type);
- ir_fill_slice(proc, slice, ptr, count, capacity);
- return ir_emit_load(proc, slice);
- break;
- }
- case BuiltinProc_slice_to_bytes: {
- ir_emit_comment(proc, str_lit("slice_to_bytes"));
- irValue *s = ir_build_expr(proc, ce->args[0]);
- Type *t = base_type(ir_type(s));
- if (is_type_u8_slice(t)) {
- return ir_emit_conv(proc, s, tv.type);
- }
- irValue *slice = ir_add_local_generated(proc, tv.type);
- i64 elem_size = type_size_of(proc->module->allocator, t->Slice.elem);
- irValue *ptr = ir_emit_conv(proc, ir_slice_elem(proc, s), t_u8_ptr);
- irValue *count = ir_slice_count(proc, s);
- irValue *capacity = ir_slice_capacity(proc, s);
- count = ir_emit_arith(proc, Token_Mul, count, ir_const_int(proc->module->allocator, elem_size), t_int);
- capacity = ir_emit_arith(proc, Token_Mul, capacity, ir_const_int(proc->module->allocator, elem_size), t_int);
- ir_fill_slice(proc, slice, ptr, count, capacity);
- return ir_emit_load(proc, slice);
- break;
- }
- #endif
- case BuiltinProc_expand_to_tuple: {
- ir_emit_comment(proc, str_lit("expand_to_tuple"));
- irValue *s = ir_build_expr(proc, ce->args[0]);
- Type *t = base_type(ir_type(s));
- GB_ASSERT(t->kind == Type_Struct);
- GB_ASSERT(is_type_tuple(tv.type));
- irValue *tuple = ir_add_local_generated(proc, tv.type);
- for_array(src_index, t->Struct.fields) {
- Entity *field = t->Struct.fields_in_src_order[src_index];
- i32 field_index = field->Variable.field_index;
- irValue *f = ir_emit_struct_ev(proc, s, field_index);
- irValue *ep = ir_emit_struct_ep(proc, tuple, cast(i32)src_index);
- ir_emit_store(proc, ep, f);
- }
- return ir_emit_load(proc, tuple);
- break;
- }
- case BuiltinProc_min: {
- ir_emit_comment(proc, str_lit("min"));
- Type *t = type_of_expr(proc->module->info, expr);
- irValue *x = ir_emit_conv(proc, ir_build_expr(proc, ce->args[0]), t);
- irValue *y = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t);
- irValue *cond = ir_emit_comp(proc, Token_Lt, x, y);
- return ir_emit_select(proc, cond, x, y);
- break;
- }
- case BuiltinProc_max: {
- ir_emit_comment(proc, str_lit("max"));
- Type *t = type_of_expr(proc->module->info, expr);
- irValue *x = ir_emit_conv(proc, ir_build_expr(proc, ce->args[0]), t);
- irValue *y = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t);
- irValue *cond = ir_emit_comp(proc, Token_Gt, x, y);
- return ir_emit_select(proc, cond, x, y);
- break;
- }
- case BuiltinProc_abs: {
- ir_emit_comment(proc, str_lit("abs"));
- irValue *x = ir_build_expr(proc, ce->args[0]);
- Type *t = ir_type(x);
- if (is_type_complex(t)) {
- gbAllocator a = proc->module->allocator;
- i64 sz = 8*type_size_of(a, t);
- irValue **args = gb_alloc_array(a, irValue *, 1);
- args[0] = x;
- switch (sz) {
- case 64: return ir_emit_global_call(proc, "__abs_complex64", args, 1);
- case 128: return ir_emit_global_call(proc, "__abs_complex128", args, 1);
- }
- GB_PANIC("Unknown complex type");
- }
- irValue *zero = ir_emit_conv(proc, v_zero, t);
- irValue *cond = ir_emit_comp(proc, Token_Lt, x, zero);
- irValue *neg = ir_emit(proc, ir_instr_unary_op(proc, Token_Sub, x, t));
- return ir_emit_select(proc, cond, neg, x);
- break;
- }
- case BuiltinProc_clamp: {
- ir_emit_comment(proc, str_lit("clamp"));
- Type *t = type_of_expr(proc->module->info, expr);
- return ir_emit_clamp(proc, t,
- ir_build_expr(proc, ce->args[0]),
- ir_build_expr(proc, ce->args[1]),
- ir_build_expr(proc, ce->args[2]));
- break;
- }
- }
- GB_PANIC("Unhandled built-in procedure");
- return nullptr;
- }
- irValue *ir_build_expr(irProcedure *proc, AstNode *expr) {
- expr = unparen_expr(expr);
- TypeAndValue tv = type_and_value_of_expr(proc->module->info, expr);
- GB_ASSERT(tv.mode != Addressing_Invalid);
- GB_ASSERT(tv.mode != Addressing_Type);
- #if 0
- if (tv.mode == Addressing_Type) {
- // // TODO(bill): Handle this correctly
- #if 0
- i32 entry_index = type_info_index(proc->module->info, tv.type, false);
- if (entry_index >= 0) {
- return ir_get_type_info_ptr(proc, tv.type);
- // i32 id = entry_index+1;
- // return ir_value_constant(proc->module->allocator, t_int, exact_value_i64(id));
- }
- #endif
- // return v_raw_nil;
- return ir_value_nil(proc->module->allocator, tv.type);
- }
- #endif
- if (tv.value.kind != ExactValue_Invalid) {
- // NOTE(bill): Edge case
- if (tv.value.kind != ExactValue_Compound &&
- is_type_vector(tv.type)) {
- Type *elem = base_vector_type(tv.type);
- ExactValue value = convert_exact_value_for_type(tv.value, elem);
- irValue *x = ir_add_module_constant(proc->module, elem, value);
- return ir_emit_conv(proc, x, tv.type);
- }
- return ir_add_module_constant(proc->module, tv.type, tv.value);
- }
- if (tv.mode == Addressing_Variable) {
- return ir_addr_load(proc, ir_build_addr(proc, expr));
- }
- switch (expr->kind) {
- case_ast_node(bl, BasicLit, expr);
- TokenPos pos = bl->pos;
- GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->kind]));
- case_end;
- case_ast_node(bd, BasicDirective, expr);
- TokenPos pos = bd->token.pos;
- GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
- case_end;
- case_ast_node(i, Implicit, expr);
- return ir_addr_load(proc, ir_build_addr(proc, expr));
- case_end;
- case_ast_node(u, Undef, expr);
- return ir_value_undef(proc->module->allocator, tv.type);
- case_end;
- case_ast_node(i, Ident, expr);
- Entity *e = entity_of_ident(proc->module->info, expr);
- GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
- if (e->kind == Entity_Builtin) {
- Token token = ast_node_token(expr);
- GB_PANIC("TODO(bill): ir_build_single_expr Entity_Builtin `%.*s`\n"
- "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
- LIT(token.pos.file), token.pos.line, token.pos.column);
- return nullptr;
- } else if (e->kind == Entity_Nil) {
- return ir_value_nil(proc->module->allocator, tv.type);
- }
- irValue **found = map_get(&proc->module->values, hash_entity(e));
- if (found) {
- irValue *v = *found;
- if (v->kind == irValue_Proc) {
- return v;
- }
- // if (e->kind == Entity_Variable && e->Variable.param) {
- // return v;
- // }
- return ir_emit_load(proc, v);
- } else if (e != nullptr && e->kind == Entity_Variable) {
- return ir_addr_load(proc, ir_build_addr(proc, expr));
- }
- GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr);
- return nullptr;
- case_end;
- case_ast_node(re, RunExpr, expr);
- // TODO(bill): Run Expression
- return ir_build_expr(proc, re->expr);
- case_end;
- case_ast_node(de, DerefExpr, expr);
- return ir_addr_load(proc, ir_build_addr(proc, expr));
- case_end;
- case_ast_node(se, SelectorExpr, expr);
- TypeAndValue tav = type_and_value_of_expr(proc->module->info, expr);
- GB_ASSERT(tav.mode != Addressing_Invalid);
- return ir_addr_load(proc, ir_build_addr(proc, expr));
- case_end;
- case_ast_node(te, TernaryExpr, expr);
- ir_emit_comment(proc, str_lit("TernaryExpr"));
- Array<irValue *> edges = {};
- array_init(&edges, proc->module->allocator, 2);
- GB_ASSERT(te->y != nullptr);
- irBlock *then = ir_new_block(proc, nullptr, "if.then");
- irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
- irBlock *else_ = ir_new_block(proc, nullptr, "if.else");
- irValue *cond = ir_build_cond(proc, te->cond, then, else_);
- ir_start_block(proc, then);
- Type *type = type_of_expr(proc->module->info, expr);
- ir_open_scope(proc);
- array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->x), type));
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- ir_emit_jump(proc, done);
- ir_start_block(proc, else_);
- ir_open_scope(proc);
- array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->y), type));
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- ir_emit_jump(proc, done);
- ir_start_block(proc, done);
- return ir_emit(proc, ir_instr_phi(proc, edges, type));
- case_end;
- #if 0
- case_ast_node(ie, IfExpr, expr);
- ir_emit_comment(proc, str_lit("IfExpr"));
- if (ie->init != nullptr) {
- irBlock *init = ir_new_block(proc, expr, "if.init");
- ir_emit_jump(proc, init);
- ir_start_block(proc, init);
- ir_build_stmt(proc, ie->init);
- }
- Array<irValue *> edges = {};
- array_init(&edges, proc->module->allocator, 2);
- GB_ASSERT(ie->else_expr != nullptr);
- irBlock *then = ir_new_block(proc, expr, "if.then");
- irBlock *done = ir_new_block(proc, expr, "if.done"); // NOTE(bill): Append later
- irBlock *else_ = ir_new_block(proc, ie->else_expr, "if.else");
- irValue *cond = ir_build_cond(proc, ie->cond, then, else_);
- ir_start_block(proc, then);
- ir_open_scope(proc);
- array_add(&edges, ir_build_expr(proc, ie->body));
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- ir_emit_jump(proc, done);
- ir_start_block(proc, else_);
- ir_open_scope(proc);
- array_add(&edges, ir_build_expr(proc, ie->else_expr));
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- ir_emit_jump(proc, done);
- ir_start_block(proc, done);
- Type *type = type_of_expr(proc->module->info, expr);
- return ir_emit(proc, ir_instr_phi(proc, edges, type));
- case_end;
- #endif
- case_ast_node(ta, TypeAssertion, expr);
- TokenPos pos = ast_node_token(expr).pos;
- Type *type = tv.type;
- irValue *e = ir_build_expr(proc, ta->expr);
- Type *t = type_deref(ir_type(e));
- if (is_type_union(t)) {
- ir_emit_comment(proc, str_lit("cast - union_cast"));
- return ir_emit_union_cast(proc, e, type, pos);
- } else if (is_type_any(t)) {
- ir_emit_comment(proc, str_lit("cast - any_cast"));
- return ir_emit_any_cast(proc, e, type, pos);
- } else {
- GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
- }
- case_end;
- case_ast_node(tc, TypeCast, expr);
- irValue *e = ir_build_expr(proc, tc->expr);
- switch (tc->token.kind) {
- case Token_cast:
- return ir_emit_conv(proc, e, tv.type);
- case Token_transmute:
- return ir_emit_transmute(proc, e, tv.type);
- }
- GB_PANIC("Invalid AST TypeCast");
- case_end;
- case_ast_node(ue, UnaryExpr, expr);
- switch (ue->op.kind) {
- case Token_And:
- return ir_emit_ptr_offset(proc, ir_build_addr_ptr(proc, ue->expr), v_zero); // Make a copy of the pointer
- default:
- return ir_emit_unary_arith(proc, ue->op.kind, ir_build_expr(proc, ue->expr), tv.type);
- }
- case_end;
- case_ast_node(be, BinaryExpr, expr);
- irValue *left = ir_build_expr(proc, be->left);
- Type *type = default_type(tv.type);
- switch (be->op.kind) {
- case Token_Add:
- case Token_Sub:
- case Token_Mul:
- case Token_Quo:
- case Token_Mod:
- case Token_ModMod:
- case Token_And:
- case Token_Or:
- case Token_Xor:
- case Token_AndNot:
- case Token_Shl:
- case Token_Shr: {
- irValue *right = ir_build_expr(proc, be->right);
- return ir_emit_arith(proc, be->op.kind, left, right, type);
- }
- case Token_CmpEq:
- case Token_NotEq:
- case Token_Lt:
- case Token_LtEq:
- case Token_Gt:
- case Token_GtEq: {
- irValue *right = ir_build_expr(proc, be->right);
- irValue *cmp = ir_emit_comp(proc, be->op.kind, left, right);
- return ir_emit_conv(proc, cmp, type);
- break;
- }
- case Token_CmpAnd:
- case Token_CmpOr:
- if (is_type_vector(type)) {
- TokenKind op = {};
- switch (be->op.kind) {
- case Token_CmpAnd: op = Token_And; break;
- case Token_CmpOr: op = Token_Or; break;
- }
- irValue *right = ir_build_expr(proc, be->right);
- return ir_emit_arith(proc, op, left, right, type);
- }
- return ir_emit_logical_binary_expr(proc, expr);
- default:
- GB_PANIC("Invalid binary expression");
- break;
- }
- case_end;
- case_ast_node(pl, ProcLit, expr);
- return ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
- case_end;
- case_ast_node(cl, CompoundLit, expr);
- return ir_addr_load(proc, ir_build_addr(proc, expr));
- case_end;
- case_ast_node(ce, CallExpr, expr);
- TypeAndValue proc_tv = type_and_value_of_expr(proc->module->info, ce->proc);
- AddressingMode proc_mode = proc_tv.mode;
- if (proc_mode == Addressing_Type) {
- GB_ASSERT(ce->args.count == 1);
- irValue *x = ir_build_expr(proc, ce->args[0]);
- irValue *y = ir_emit_conv(proc, x, tv.type);
- return y;
- }
- AstNode *p = unparen_expr(ce->proc);
- if (proc_mode == Addressing_Builtin) {
- Entity *e = entity_of_ident(proc->module->info, p);
- BuiltinProcId id = BuiltinProc_Invalid;
- if (e != nullptr) {
- id = cast(BuiltinProcId)e->Builtin.id;
- } else {
- id = BuiltinProc_DIRECTIVE;
- if (ce->proc->kind == AstNode_Implicit) {
- ast_node(i, Implicit, ce->proc);
- GB_ASSERT(i->kind == Token_type_info_of);
- id = BuiltinProc_type_info_of;
- }
- }
- return ir_build_builtin_proc(proc, expr, tv, id);
- }
- // NOTE(bill): Regular call
- irValue *value = ir_build_expr(proc, ce->proc);
- GB_ASSERT(value != nullptr);
- Type *proc_type_ = base_type(ir_type(value));
- GB_ASSERT(proc_type_->kind == Type_Proc);
- TypeProc *type = &proc_type_->Proc;
- if (is_call_expr_field_value(ce)) {
- isize param_count = type->param_count;
- irValue **args = gb_alloc_array(proc->module->allocator, irValue *, param_count);
- for_array(arg_index, ce->args) {
- AstNode *arg = ce->args[arg_index];
- ast_node(fv, FieldValue, arg);
- GB_ASSERT(fv->field->kind == AstNode_Ident);
- String name = fv->field->Ident.token.string;
- isize index = lookup_procedure_parameter(type, name);
- GB_ASSERT(index >= 0);
- TypeAndValue tav = type_and_value_of_expr(proc->module->info, fv->value);
- if (tav.mode == Addressing_Type) {
- args[index] = ir_value_nil(proc->module->allocator, tav.type);
- } else {
- args[index] = ir_build_expr(proc, fv->value);
- }
- }
- TypeTuple *pt = &type->params->Tuple;
- for (isize i = 0; i < param_count; i++) {
- Entity *e = pt->variables[i];
- if (e->kind == Entity_TypeName) {
- args[i] = ir_value_nil(proc->module->allocator, e->type);
- } else {
- GB_ASSERT(e->kind == Entity_Variable);
- if (args[i] == nullptr) {
- if (e->Variable.default_value.kind != ExactValue_Invalid) {
- args[i] = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value);
- } else {
- args[i] = ir_value_nil(proc->module->allocator, e->type);
- }
- } else {
- args[i] = ir_emit_conv(proc, args[i], e->type);
- }
- }
- }
- return ir_emit_call(proc, value, args, param_count);
- }
- isize arg_index = 0;
- isize arg_count = 0;
- for_array(i, ce->args) {
- AstNode *a = ce->args[i];
- Type *at = base_type(type_of_expr(proc->module->info, a));
- if (at->kind == Type_Tuple) {
- arg_count += at->Tuple.variables.count;
- } else {
- arg_count++;
- }
- }
- irValue **args = gb_alloc_array(proc->module->allocator, irValue *, gb_max(type->param_count, arg_count));
- bool variadic = type->variadic;
- bool vari_expand = ce->ellipsis.pos.line != 0;
- bool is_c_vararg = type->c_vararg;
- for_array(i, ce->args) {
- AstNode *arg = ce->args[i];
- TypeAndValue arg_tv = type_and_value_of_expr(proc->module->info, arg);
- if (arg_tv.mode == Addressing_Type) {
- args[arg_index++] = ir_value_nil(proc->module->allocator, arg_tv.type);
- } else {
- irValue *a = ir_build_expr(proc, arg);
- Type *at = ir_type(a);
- if (at->kind == Type_Tuple) {
- for_array(i, at->Tuple.variables) {
- Entity *e = at->Tuple.variables[i];
- irValue *v = ir_emit_struct_ev(proc, a, cast(i32)i);
- args[arg_index++] = v;
- }
- } else {
- args[arg_index++] = a;
- }
- }
- }
- TypeTuple *pt = &type->params->Tuple;
- if (arg_count < type->param_count) {
- String procedure = {};
- if (proc->entity != nullptr) {
- procedure = proc->entity->token.string;
- }
- TokenPos pos = ast_node_token(ce->proc).pos;
- isize end = type->param_count;
- if (variadic) {
- end--;
- }
- while (arg_index < end) {
- Entity *e = pt->variables[arg_index];
- GB_ASSERT(e->kind == Entity_Variable);
- if (e->Variable.default_value.kind != ExactValue_Invalid) {
- args[arg_index++] = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value);
- } else if (e->Variable.default_is_location) {
- args[arg_index++] = ir_emit_source_code_location(proc, procedure, pos);
- } else {
- args[arg_index++] = ir_value_nil(proc->module->allocator, e->type);
- }
- }
- }
- if (is_c_vararg) {
- GB_ASSERT(variadic);
- GB_ASSERT(!vari_expand);
- isize i = 0;
- for (; i < type->param_count-1; i++) {
- Entity *e = pt->variables[i];
- if (e->kind == Entity_Variable) {
- args[i] = ir_emit_conv(proc, args[i], e->type);
- }
- }
- Type *variadic_type = pt->variables[i]->type;
- GB_ASSERT(is_type_slice(variadic_type));
- variadic_type = base_type(variadic_type)->Slice.elem;
- if (!is_type_any(variadic_type)) {
- for (; i < arg_count; i++) {
- args[i] = ir_emit_conv(proc, args[i], variadic_type);
- }
- } else {
- for (; i < arg_count; i++) {
- args[i] = ir_emit_conv(proc, args[i], default_type(ir_type(args[i])));
- }
- }
- } else if (variadic) {
- isize i = 0;
- for (; i < type->param_count-1; i++) {
- Entity *e = pt->variables[i];
- if (e->kind == Entity_Variable) {
- args[i] = ir_emit_conv(proc, args[i], e->type);
- }
- }
- if (!vari_expand) {
- Type *variadic_type = pt->variables[i]->type;
- GB_ASSERT(is_type_slice(variadic_type));
- variadic_type = base_type(variadic_type)->Slice.elem;
- for (; i < arg_count; i++) {
- args[i] = ir_emit_conv(proc, args[i], variadic_type);
- }
- }
- } else {
- for (isize i = 0; i < type->param_count; i++) {
- Entity *e = pt->variables[i];
- if (e->kind == Entity_Variable) {
- args[i] = ir_emit_conv(proc, args[i], e->type);
- }
- }
- }
- i64 final_count = type->param_count;
- if (is_c_vararg) {
- final_count = arg_count;
- }
- if (variadic && !vari_expand && !is_c_vararg) {
- ir_emit_comment(proc, str_lit("variadic call argument generation"));
- gbAllocator allocator = proc->module->allocator;
- Type *slice_type = pt->variables[type->param_count-1]->type;
- Type *elem_type = base_type(slice_type)->Slice.elem;
- irValue *slice = ir_add_local_generated(proc, slice_type);
- isize slice_len = arg_count+1 - type->param_count;
- if (slice_len > 0) {
- irValue *base_array = ir_add_local_generated(proc, make_type_array(allocator, elem_type, slice_len));
- for (isize i = type->param_count-1, j = 0; i < arg_count; i++, j++) {
- irValue *addr = ir_emit_array_epi(proc, base_array, cast(i32)j);
- ir_emit_store(proc, addr, args[i]);
- }
- irValue *base_elem = ir_emit_array_epi(proc, base_array, 0);
- irValue *len = ir_const_int(allocator, slice_len);
- ir_fill_slice(proc, slice, base_elem, len, len);
- }
- arg_count = type->param_count;
- args[arg_count-1] = ir_emit_load(proc, slice);
- }
- return ir_emit_call(proc, value, args, final_count);
- case_end;
- case_ast_node(se, SliceExpr, expr);
- return ir_addr_load(proc, ir_build_addr(proc, expr));
- case_end;
- case_ast_node(ie, IndexExpr, expr);
- return ir_addr_load(proc, ir_build_addr(proc, expr));
- case_end;
- }
- GB_PANIC("Unexpected expression: %.*s", LIT(ast_node_strings[expr->kind]));
- return nullptr;
- }
- irValue *ir_get_using_variable(irProcedure *proc, Entity *e) {
- GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
- String name = e->token.string;
- Entity *parent = e->using_parent;
- Selection sel = lookup_field(proc->module->allocator, parent->type, name, false);
- GB_ASSERT(sel.entity != nullptr);
- irValue **pv = map_get(&proc->module->values, hash_entity(parent));
- irValue *v = nullptr;
- if (pv != nullptr) {
- v = *pv;
- } else {
- GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
- v = ir_build_addr_ptr(proc, e->using_expr);
- }
- GB_ASSERT(v != nullptr);
- GB_ASSERT(parent->type == type_deref(ir_type(v)));
- return ir_emit_deep_field_gep(proc, v, sel);
- }
- bool ir_is_elem_const(irModule *m, AstNode *elem, Type *elem_type) {
- if (!elem_type_can_be_constant(elem_type)) {
- return false;
- }
- if (elem->kind == AstNode_FieldValue) {
- elem = elem->FieldValue.value;
- }
- TypeAndValue tav = type_and_value_of_expr(m->info, elem);
- GB_ASSERT(tav.mode != Addressing_Invalid);
- return tav.value.kind != ExactValue_Invalid;
- }
- irAddr ir_build_addr_from_entity(irProcedure *proc, Entity *e, AstNode *expr) {
- GB_ASSERT(e != nullptr);
- GB_ASSERT(e->kind != Entity_Constant);
- irValue *v = nullptr;
- irValue **found = map_get(&proc->module->values, hash_entity(e));
- if (found) {
- v = *found;
- } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
- // NOTE(bill): Calculate the using variable every time
- v = ir_get_using_variable(proc, e);
- }
- if (v == nullptr) {
- error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
- LIT(proc->name),
- LIT(e->token.string), e, LIT(entity_strings[e->kind]));
- GB_PANIC("Unknown value");
- }
- return ir_addr(v);
- }
- irAddr ir_build_addr(irProcedure *proc, AstNode *expr) {
- switch (expr->kind) {
- case_ast_node(i, Implicit, expr);
- irValue *v = nullptr;
- switch (i->kind) {
- case Token_context:
- v = ir_find_or_generate_context_ptr(proc);
- break;
- }
- GB_ASSERT(v != nullptr);
- return ir_addr(v);
- case_end;
- case_ast_node(i, Ident, expr);
- if (is_blank_ident(expr)) {
- irAddr val = {};
- return val;
- }
- String name = i->token.string;
- Entity *e = entity_of_ident(proc->module->info, expr);
- // GB_ASSERT(name == e->token.string);
- return ir_build_addr_from_entity(proc, e, expr);
- case_end;
- case_ast_node(pe, ParenExpr, expr);
- return ir_build_addr(proc, unparen_expr(expr));
- case_end;
- case_ast_node(se, SelectorExpr, expr);
- ir_emit_comment(proc, str_lit("SelectorExpr"));
- AstNode *sel = unparen_expr(se->selector);
- if (sel->kind == AstNode_Ident) {
- String selector = sel->Ident.token.string;
- TypeAndValue tav = type_and_value_of_expr(proc->module->info, se->expr);
- if (tav.mode == Addressing_Invalid) {
- // NOTE(bill): Imports
- Entity *imp = entity_of_ident(proc->module->info, se->expr);
- if (imp != nullptr) {
- GB_ASSERT(imp->kind == Entity_ImportName);
- }
- return ir_build_addr(proc, unparen_expr(se->selector));
- }
- Type *type = base_type(tav.type);
- if (tav.mode == Addressing_Type) { // Addressing_Type
- Selection sel = lookup_field(proc->module->allocator, type, selector, true);
- Entity *e = sel.entity;
- GB_ASSERT(e->kind == Entity_Variable);
- GB_ASSERT(e->flags & EntityFlag_TypeField);
- String name = e->token.string;
- if (name == "names") {
- irValue *ti_ptr = ir_type_info(proc, type);
- irValue *variant = ir_emit_struct_ep(proc, ti_ptr, 2);
- irValue *names_ptr = nullptr;
- if (is_type_enum(type)) {
- irValue *enum_info = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
- names_ptr = ir_emit_struct_ep(proc, enum_info, 1);
- } else if (type->kind == Type_Struct) {
- irValue *struct_info = ir_emit_conv(proc, variant, t_type_info_struct_ptr);
- names_ptr = ir_emit_struct_ep(proc, struct_info, 1);
- }
- return ir_addr(names_ptr);
- } else {
- GB_PANIC("Unhandled TypeField %.*s", LIT(name));
- }
- GB_PANIC("Unreachable");
- }
- Selection sel = lookup_field(proc->module->allocator, type, selector, false);
- GB_ASSERT(sel.entity != nullptr);
- if (sel.entity->type->kind == Type_BitFieldValue) {
- irAddr addr = ir_build_addr(proc, se->expr);
- Type *bft = type_deref(ir_addr_type(addr));
- if (sel.index.count == 1) {
- GB_ASSERT(is_type_bit_field(bft));
- i32 index = sel.index[0];
- return ir_addr_bit_field(ir_addr_get_ptr(proc, addr), index);
- } else {
- Selection s = sel;
- s.index.count--;
- i32 index = s.index[s.index.count-1];
- irValue *a = ir_addr_get_ptr(proc, addr);
- a = ir_emit_deep_field_gep(proc, a, s);
- return ir_addr_bit_field(a, index);
- }
- } else {
- irValue *a = ir_build_addr_ptr(proc, se->expr);
- a = ir_emit_deep_field_gep(proc, a, sel);
- return ir_addr(a);
- }
- } else {
- // NOTE(bill): x.0
- Type *type = type_deref(type_of_expr(proc->module->info, se->expr));
- Type *selector_type = base_type(type_of_expr(proc->module->info, se->selector));
- GB_ASSERT_MSG(is_type_integer(selector_type), "%s", type_to_string(selector_type));
- ExactValue val = type_and_value_of_expr(proc->module->info, sel).value;
- i64 index = i128_to_i64(val.value_integer);
- Selection sel = lookup_field_from_index(proc->module->allocator, type, index);
- GB_ASSERT(sel.entity != nullptr);
- irValue *a = ir_build_addr_ptr(proc, se->expr);
- a = ir_emit_deep_field_gep(proc, a, sel);
- return ir_addr(a);
- }
- case_end;
- case_ast_node(ta, TypeAssertion, expr);
- gbAllocator a = proc->module->allocator;
- TokenPos pos = ast_node_token(expr).pos;
- irValue *e = ir_build_expr(proc, ta->expr);
- Type *t = type_deref(ir_type(e));
- if (is_type_union(t)) {
- Type *type = type_of_expr(proc->module->info, expr);
- irValue *v = ir_add_local_generated(proc, type);
- ir_emit_comment(proc, str_lit("cast - union_cast"));
- ir_emit_store(proc, v, ir_emit_union_cast(proc, ir_build_expr(proc, ta->expr), type, pos));
- return ir_addr(v);
- } else if (is_type_any(t)) {
- ir_emit_comment(proc, str_lit("cast - any_cast"));
- Type *type = type_of_expr(proc->module->info, expr);
- return ir_emit_any_cast_addr(proc, ir_build_expr(proc, ta->expr), type, pos);
- } else {
- GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
- }
- case_end;
- case_ast_node(ue, UnaryExpr, expr);
- switch (ue->op.kind) {
- case Token_And: {
- return ir_build_addr(proc, ue->expr);
- }
- default:
- GB_PANIC("Invalid unary expression for ir_build_addr");
- }
- case_end;
- case_ast_node(be, BinaryExpr, expr);
- GB_PANIC("Invalid binary expression for ir_build_addr: %.*s\n", LIT(be->op.string));
- case_end;
- case_ast_node(ie, IndexExpr, expr);
- ir_emit_comment(proc, str_lit("IndexExpr"));
- Type *t = base_type(type_of_expr(proc->module->info, ie->expr));
- gbAllocator a = proc->module->allocator;
- bool deref = is_type_pointer(t);
- t = base_type(type_deref(t));
- if (is_type_map(t)) {
- irValue *map_val = ir_build_addr_ptr(proc, ie->expr);
- irValue *key = ir_build_expr(proc, ie->index);
- key = ir_emit_conv(proc, key, t->Map.key);
- Type *result_type = type_of_expr(proc->module->info, expr);
- return ir_addr_map(map_val, key, t, result_type);
- }
- irValue *using_addr = nullptr;
- if (!is_type_indexable(t)) {
- // Using index expression
- Entity *using_field = find_using_index_expr(t);
- if (using_field != nullptr) {
- Selection sel = lookup_field(a, t, using_field->token.string, false);
- irValue *e = ir_build_addr_ptr(proc, ie->expr);
- using_addr = ir_emit_deep_field_gep(proc, e, sel);
- t = using_field->type;
- }
- }
- switch (t->kind) {
- case Type_Vector: {
- irValue *vector = nullptr;
- if (using_addr != nullptr) {
- vector = using_addr;
- } else {
- vector = ir_build_addr_ptr(proc, ie->expr);
- if (deref) {
- vector = ir_emit_load(proc, vector);
- }
- }
- irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
- irValue *elem = ir_emit_array_ep(proc, vector, index);
- irValue *len = ir_const_int(a, t->Vector.count);
- ir_emit_bounds_check(proc, ast_node_token(ie->index), index, len);
- return ir_addr(elem);
- break;
- }
- case Type_Array: {
- irValue *array = nullptr;
- if (using_addr != nullptr) {
- array = using_addr;
- } else {
- array = ir_build_addr_ptr(proc, ie->expr);
- if (deref) {
- array = ir_emit_load(proc, array);
- }
- }
- irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
- irValue *elem = ir_emit_array_ep(proc, array, index);
- irValue *len = ir_const_int(a, t->Vector.count);
- ir_emit_bounds_check(proc, ast_node_token(ie->index), index, len);
- return ir_addr(elem);
- break;
- }
- case Type_Slice: {
- irValue *slice = nullptr;
- if (using_addr != nullptr) {
- slice = ir_emit_load(proc, using_addr);
- } else {
- slice = ir_build_expr(proc, ie->expr);
- if (deref) {
- slice = ir_emit_load(proc, slice);
- }
- }
- irValue *elem = ir_slice_elem(proc, slice);
- irValue *len = ir_slice_count(proc, slice);
- irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
- ir_emit_bounds_check(proc, ast_node_token(ie->index), index, len);
- irValue *v = ir_emit_ptr_offset(proc, elem, index);
- return ir_addr(v);
- break;
- }
- case Type_DynamicArray: {
- irValue *dynamic_array = nullptr;
- if (using_addr != nullptr) {
- dynamic_array = ir_emit_load(proc, using_addr);
- } else {
- dynamic_array = ir_build_expr(proc, ie->expr);
- if (deref) {
- dynamic_array = ir_emit_load(proc, dynamic_array);
- }
- }
- irValue *elem = ir_dynamic_array_elem(proc, dynamic_array);
- irValue *len = ir_dynamic_array_count(proc, dynamic_array);
- irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
- ir_emit_bounds_check(proc, ast_node_token(ie->index), index, len);
- irValue *v = ir_emit_ptr_offset(proc, elem, index);
- return ir_addr(v);
- break;
- }
- case Type_Basic: { // Basic_string
- irValue *str;
- irValue *elem;
- irValue *len;
- irValue *index;
- if (using_addr != nullptr) {
- str = ir_emit_load(proc, using_addr);
- } else {
- str = ir_build_expr(proc, ie->expr);
- if (deref) {
- str = ir_emit_load(proc, str);
- }
- }
- elem = ir_string_elem(proc, str);
- len = ir_string_len(proc, str);
- index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
- ir_emit_bounds_check(proc, ast_node_token(ie->index), index, len);
- return ir_addr(ir_emit_ptr_offset(proc, elem, index));
- break;
- }
- }
- case_end;
- case_ast_node(se, SliceExpr, expr);
- ir_emit_comment(proc, str_lit("SliceExpr"));
- gbAllocator a = proc->module->allocator;
- irValue *low = v_zero;
- irValue *high = nullptr;
- irValue *max = nullptr;
- if (se->low != nullptr) low = ir_build_expr(proc, se->low);
- if (se->high != nullptr) high = ir_build_expr(proc, se->high);
- if (se->max != nullptr) max = ir_build_expr(proc, se->max);
- if (high != nullptr && se->interval0.kind == Token_Ellipsis) {
- high = ir_emit_arith(proc, Token_Add, high, v_one, t_int);
- }
- if (max != nullptr && se->interval1.kind == Token_Ellipsis) {
- max = ir_emit_arith(proc, Token_Add, max, v_one, t_int);
- }
- irValue *addr = ir_build_addr_ptr(proc, se->expr);
- irValue *base = ir_emit_load(proc, addr);
- Type *type = base_type(ir_type(base));
- if (is_type_pointer(type)) {
- type = base_type(type_deref(type));
- addr = base;
- base = ir_emit_load(proc, base);
- }
- // TODO(bill): Cleanup like mad!
- switch (type->kind) {
- case Type_Slice: {
- Type *slice_type = type;
- if (high == nullptr) high = ir_slice_count(proc, base);
- if (max == nullptr) max = ir_slice_capacity(proc, base);
- ir_emit_slice_bounds_check(proc, se->open, low, high, max, false);
- irValue *elem = ir_emit_ptr_offset(proc, ir_slice_elem(proc, base), low);
- irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
- irValue *cap = ir_emit_arith(proc, Token_Sub, max, low, t_int);
- irValue *slice = ir_add_local_generated(proc, slice_type);
- ir_fill_slice(proc, slice, elem, len, cap);
- return ir_addr(slice);
- }
- case Type_DynamicArray: {
- Type *elem_type = type->DynamicArray.elem;
- Type *slice_type = make_type_slice(a, elem_type);
- if (high == nullptr) high = ir_dynamic_array_count(proc, base);
- if (max == nullptr) max = ir_dynamic_array_capacity(proc, base);
- ir_emit_slice_bounds_check(proc, se->open, low, high, max, false);
- irValue *elem = ir_emit_ptr_offset(proc, ir_dynamic_array_elem(proc, base), low);
- irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
- irValue *cap = ir_emit_arith(proc, Token_Sub, max, low, t_int);
- irValue *slice = ir_add_local_generated(proc, slice_type);
- ir_fill_slice(proc, slice, elem, len, cap);
- return ir_addr(slice);
- }
- case Type_Array: {
- Type *slice_type = make_type_slice(a, type->Array.elem);
- if (high == nullptr) high = ir_array_len(proc, base);
- if (max == nullptr) max = ir_array_len(proc, base);
- ir_emit_slice_bounds_check(proc, se->open, low, high, max, false);
- irValue *elem = ir_emit_ptr_offset(proc, ir_array_elem(proc, addr), low);
- irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
- irValue *cap = ir_emit_arith(proc, Token_Sub, max, low, t_int);
- irValue *slice = ir_add_local_generated(proc, slice_type);
- ir_fill_slice(proc, slice, elem, len, cap);
- return ir_addr(slice);
- }
- case Type_Basic: {
- GB_ASSERT(type == t_string);
- if (high == nullptr) high = ir_string_len(proc, base);
- // if (max == nullptr) max = ir_string_len(proc, base);
- ir_emit_slice_bounds_check(proc, se->open, low, high, nullptr, true);
- irValue *elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, base), low);
- irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
- irValue *str = ir_add_local_generated(proc, t_string);
- ir_fill_string(proc, str, elem, len);
- return ir_addr(str);
- break;
- }
- }
- GB_PANIC("Unknown slicable type");
- case_end;
- case_ast_node(de, DerefExpr, expr);
- // TODO(bill): Is a ptr copy needed?
- irValue *addr = ir_build_expr(proc, de->expr);
- addr = ir_emit_ptr_offset(proc, addr, v_zero);
- return ir_addr(addr);
- case_end;
- case_ast_node(ce, CallExpr, expr);
- // NOTE(bill): This is make sure you never need to have an `array_ev`
- irValue *e = ir_build_expr(proc, expr);
- irValue *v = ir_add_local_generated(proc, ir_type(e));
- ir_emit_store(proc, v, e);
- return ir_addr(v);
- case_end;
- case_ast_node(cl, CompoundLit, expr);
- ir_emit_comment(proc, str_lit("CompoundLit"));
- Type *type = type_of_expr(proc->module->info, expr);
- Type *bt = base_type(type);
- irValue *v = ir_add_local_generated(proc, type, true);
- Type *et = nullptr;
- switch (bt->kind) {
- case Type_Vector: et = bt->Vector.elem; break;
- case Type_Array: et = bt->Array.elem; break;
- case Type_Slice: et = bt->Slice.elem; break;
- }
- switch (bt->kind) {
- default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
- case Type_Vector: {
- if (cl->elems.count == 1 && bt->Vector.count > 1) {
- isize index_count = bt->Vector.count;
- irValue *elem_val = ir_build_expr(proc, cl->elems[0]);
- for (isize i = 0; i < index_count; i++) {
- ir_emit_store(proc, ir_emit_array_epi(proc, v, cast(i32)i), elem_val);
- }
- } else if (cl->elems.count > 0) {
- ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
- for_array(i, cl->elems) {
- AstNode *elem = cl->elems[i];
- if (ir_is_elem_const(proc->module, elem, et)) {
- continue;
- }
- irValue *field_expr = ir_build_expr(proc, elem);
- Type *t = ir_type(field_expr);
- GB_ASSERT(t->kind != Type_Tuple);
- irValue *ev = ir_emit_conv(proc, field_expr, et);
- irValue *gep = ir_emit_array_epi(proc, v, cast(i32)i);
- ir_emit_store(proc, gep, ev);
- }
- }
- break;
- }
- case Type_Struct: {
- // TODO(bill): "constant" `#raw_union`s are not initialized constantly at the moment.
- // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
- bool is_raw_union = is_type_raw_union(bt);
- GB_ASSERT(is_type_struct(bt) || is_raw_union);
- TypeStruct *st = &bt->Struct;
- if (cl->elems.count > 0) {
- ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
- for_array(field_index, cl->elems) {
- AstNode *elem = cl->elems[field_index];
- irValue *field_expr = nullptr;
- Entity *field = nullptr;
- isize index = field_index;
- if (elem->kind == AstNode_FieldValue) {
- ast_node(fv, FieldValue, elem);
- String name = fv->field->Ident.token.string;
- Selection sel = lookup_field(proc->module->allocator, bt, name, false);
- index = sel.index[0];
- elem = fv->value;
- } else {
- TypeAndValue tav = type_and_value_of_expr(proc->module->info, elem);
- Selection sel = lookup_field_from_index(proc->module->allocator, bt,
- st->fields_in_src_order[field_index]->Variable.field_src_index);
- index = sel.index[0];
- }
- field = st->fields[index];
- Type *ft = field->type;
- if (!is_raw_union && ir_is_elem_const(proc->module, elem, ft)) {
- continue;
- }
- field_expr = ir_build_expr(proc, elem);
- GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
- irValue *fv = ir_emit_conv(proc, field_expr, ft);
- irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
- ir_emit_store(proc, gep, fv);
- }
- }
- break;
- }
- case Type_Map: {
- if (cl->elems.count == 0) {
- break;
- }
- gbAllocator a = proc->module->allocator;
- {
- irValue **args = gb_alloc_array(a, irValue *, 2);
- args[0] = ir_gen_map_header(proc, v, type);
- args[1] = ir_const_int(a, 2*cl->elems.count);
- ir_emit_global_call(proc, "__dynamic_map_reserve", args, 2);
- }
- for_array(field_index, cl->elems) {
- AstNode *elem = cl->elems[field_index];
- ast_node(fv, FieldValue, elem);
- irValue *key = ir_build_expr(proc, fv->field);
- irValue *value = ir_build_expr(proc, fv->value);
- ir_insert_dynamic_map_key_and_value(proc, v, type, key, value);
- }
- break;
- }
- case Type_DynamicArray: {
- if (cl->elems.count == 0) {
- break;
- }
- Type *elem = bt->DynamicArray.elem;
- gbAllocator a = proc->module->allocator;
- irValue *size = ir_const_int(a, type_size_of(a, elem));
- irValue *align = ir_const_int(a, type_align_of(a, elem));
- {
- irValue **args = gb_alloc_array(a, irValue *, 4);
- args[0] = ir_emit_conv(proc, v, t_rawptr);
- args[1] = size;
- args[2] = align;
- args[3] = ir_const_int(a, 2*cl->elems.count);
- ir_emit_global_call(proc, "__dynamic_array_reserve", args, 4);
- }
- i64 item_count = cl->elems.count;
- irValue *items = ir_generate_array(proc->module, elem, item_count, str_lit("__dacl$"), cast(i64)cast(intptr)expr);
- for_array(field_index, cl->elems) {
- AstNode *f = cl->elems[field_index];
- irValue *value = ir_emit_conv(proc, ir_build_expr(proc, f), elem);
- irValue *ep = ir_emit_array_epi(proc, items, cast(i32)field_index);
- ir_emit_store(proc, ep, value);
- }
- {
- irValue **args = gb_alloc_array(a, irValue *, 5);
- args[0] = ir_emit_conv(proc, v, t_rawptr);
- args[1] = size;
- args[2] = align;
- args[3] = ir_emit_conv(proc, items, t_rawptr);
- args[4] = ir_const_int(a, item_count);
- ir_emit_global_call(proc, "__dynamic_array_append", args, 5);
- }
- break;
- }
- case Type_Array: {
- if (cl->elems.count > 0) {
- ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
- for_array(i, cl->elems) {
- AstNode *elem = cl->elems[i];
- if (ir_is_elem_const(proc->module, elem, et)) {
- continue;
- }
- irValue *field_expr = ir_build_expr(proc, elem);
- Type *t = ir_type(field_expr);
- GB_ASSERT(t->kind != Type_Tuple);
- irValue *ev = ir_emit_conv(proc, field_expr, et);
- irValue *gep = ir_emit_array_epi(proc, v, cast(i32)i);
- ir_emit_store(proc, gep, ev);
- }
- }
- break;
- }
- case Type_Slice: {
- if (cl->elems.count > 0) {
- Type *elem_type = bt->Slice.elem;
- Type *elem_ptr_type = make_type_pointer(proc->module->allocator, elem_type);
- Type *elem_ptr_ptr_type = make_type_pointer(proc->module->allocator, elem_ptr_type);
- irValue *slice = ir_add_module_constant(proc->module, type, exact_value_compound(expr));
- GB_ASSERT(slice->kind == irValue_ConstantSlice);
- irValue *data = ir_emit_array_ep(proc, slice->ConstantSlice.backing_array, v_zero32);
- for_array(i, cl->elems) {
- AstNode *elem = cl->elems[i];
- if (ir_is_elem_const(proc->module, elem, et)) {
- continue;
- }
- irValue *field_expr = ir_build_expr(proc, elem);
- Type *t = ir_type(field_expr);
- GB_ASSERT(t->kind != Type_Tuple);
- irValue *ev = ir_emit_conv(proc, field_expr, elem_type);
- irValue *offset = ir_emit_ptr_offset(proc, data, ir_const_int(proc->module->allocator, i));
- ir_emit_store(proc, offset, ev);
- }
- irValue *count = ir_const_int(proc->module->allocator, slice->ConstantSlice.count);
- ir_fill_slice(proc, v, data, count, count);
- }
- break;
- }
- case Type_Basic: {
- GB_ASSERT(is_type_any(bt));
- if (cl->elems.count > 0) {
- ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
- String field_names[2] = {
- str_lit("data"),
- str_lit("type_info"),
- };
- Type *field_types[2] = {
- t_rawptr,
- t_type_info_ptr,
- };
- for_array(field_index, cl->elems) {
- AstNode *elem = cl->elems[field_index];
- irValue *field_expr = nullptr;
- isize index = field_index;
- if (elem->kind == AstNode_FieldValue) {
- ast_node(fv, FieldValue, elem);
- Selection sel = lookup_field(proc->module->allocator, bt, fv->field->Ident.token.string, false);
- index = sel.index[0];
- elem = fv->value;
- } else {
- TypeAndValue tav = type_and_value_of_expr(proc->module->info, elem);
- Selection sel = lookup_field(proc->module->allocator, bt, field_names[field_index], false);
- index = sel.index[0];
- }
- field_expr = ir_build_expr(proc, elem);
- GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
- Type *ft = field_types[index];
- irValue *fv = ir_emit_conv(proc, field_expr, ft);
- irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
- ir_emit_store(proc, gep, fv);
- }
- }
- }
- }
- return ir_addr(v);
- case_end;
- case_ast_node(tc, TypeCast, expr);
- Type *type = type_of_expr(proc->module->info, expr);
- irValue *x = ir_build_expr(proc, tc->expr);
- irValue *e = ir_emit_conv(proc, x, type);
- irValue *v = ir_add_local_generated(proc, type);
- ir_emit_store(proc, v, e);
- return ir_addr(v);
- case_end;
- }
- TokenPos token_pos = ast_node_token(expr).pos;
- GB_PANIC("Unexpected address expression\n"
- "\tAstNode: %.*s @ "
- "%.*s(%td:%td)\n",
- LIT(ast_node_strings[expr->kind]),
- LIT(token_pos.file), token_pos.line, token_pos.column);
- return ir_addr(nullptr);
- }
- void ir_build_assign_op(irProcedure *proc, irAddr lhs, irValue *value, TokenKind op) {
- irValue *old_value = ir_addr_load(proc, lhs);
- Type *type = ir_type(old_value);
- irValue *change = value;
- if (is_type_pointer(type) && is_type_integer(ir_type(value))) {
- change = ir_emit_conv(proc, value, default_type(ir_type(value)));
- } else {
- change = ir_emit_conv(proc, value, type);
- }
- irValue *new_value = ir_emit_arith(proc, op, old_value, change, type);
- ir_addr_store(proc, lhs, new_value);
- }
- irValue *ir_build_cond(irProcedure *proc, AstNode *cond, irBlock *true_block, irBlock *false_block) {
- switch (cond->kind) {
- case_ast_node(pe, ParenExpr, cond);
- return ir_build_cond(proc, pe->expr, true_block, false_block);
- case_end;
- case_ast_node(ue, UnaryExpr, cond);
- if (ue->op.kind == Token_Not) {
- return ir_build_cond(proc, ue->expr, false_block, true_block);
- }
- case_end;
- case_ast_node(be, BinaryExpr, cond);
- if (be->op.kind == Token_CmpAnd) {
- irBlock *block = ir_new_block(proc, nullptr, "cmp.and");
- ir_build_cond(proc, be->left, block, false_block);
- ir_start_block(proc, block);
- return ir_build_cond(proc, be->right, true_block, false_block);
- } else if (be->op.kind == Token_CmpOr) {
- irBlock *block = ir_new_block(proc, nullptr, "cmp.or");
- ir_build_cond(proc, be->left, true_block, block);
- ir_start_block(proc, block);
- return ir_build_cond(proc, be->right, true_block, false_block);
- }
- case_end;
- }
- irValue *v = ir_build_expr(proc, cond);
- v = ir_emit_conv(proc, v, t_bool);
- ir_emit_if(proc, v, true_block, false_block);
- return v;
- }
- void ir_build_poly_proc(irProcedure *proc, AstNodeProcLit *pd, Entity *e) {
- GB_ASSERT(pd->body != nullptr);
- if (ptr_set_exists(&proc->module->min_dep_set, e) == false) {
- // NOTE(bill): Nothing depends upon it so doesn't need to be built
- return;
- }
- // NOTE(bill): Generate a new name
- // parent.name-guid
- String original_name = e->token.string;
- String pd_name = original_name;
- if (e->Procedure.link_name.len > 0) {
- pd_name = e->Procedure.link_name;
- }
- isize name_len = proc->name.len + 1 + pd_name.len + 1 + 10 + 1;
- u8 *name_text = gb_alloc_array(proc->module->allocator, u8, name_len);
- i32 guid = cast(i32)proc->children.count;
- name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(pd_name), guid);
- String name = make_string(name_text, name_len-1);
- irValue *value = ir_value_procedure(proc->module->allocator,
- proc->module, e, e->type, pd->type, pd->body, name);
- value->Proc.tags = pd->tags;
- value->Proc.inlining = pd->inlining;
- value->Proc.parent = proc;
- ir_module_add_value(proc->module, e, value);
- array_add(&proc->children, &value->Proc);
- array_add(&proc->module->procs_to_generate, value);
- }
- void ir_build_constant_value_decl(irProcedure *proc, AstNodeValueDecl *vd) {
- if (vd == nullptr || vd->is_mutable) {
- return;
- }
- for_array(i, vd->names) {
- AstNode *ident = vd->names[i];
- GB_ASSERT(ident->kind == AstNode_Ident);
- Entity *e = entity_of_ident(proc->module->info, ident);
- GB_ASSERT(e != nullptr);
- switch (e->kind) {
- case Entity_TypeName:
- case Entity_Procedure:
- break;
- default:
- continue;
- }
- if (e->kind == Entity_TypeName) {
- bool polymorphic_struct = false;
- if (e->type != nullptr && e->kind == Entity_TypeName) {
- Type *bt = base_type(e->type);
- if (bt->kind == Type_Struct) {
- polymorphic_struct = bt->Struct.is_polymorphic;
- }
- }
- if (!polymorphic_struct && !ptr_set_exists(&proc->module->min_dep_set, e)) {
- continue;
- }
- // NOTE(bill): Generate a new name
- // parent_proc.name-guid
- String ts_name = e->token.string;
- irModule *m = proc->module;
- isize name_len = proc->name.len + 1 + ts_name.len + 1 + 10 + 1;
- u8 *name_text = gb_alloc_array(m->allocator, u8, name_len);
- i32 guid = cast(i32)m->members.entries.count;
- name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(ts_name), guid);
- String name = make_string(name_text, name_len-1);
- irValue *value = ir_value_type_name(m->allocator, name, e->type);
- map_set(&m->entity_names, hash_entity(e), name);
- ir_gen_global_type_name(m, e, name);
- } else if (e->kind == Entity_Procedure) {
- CheckerInfo *info = proc->module->info;
- DeclInfo *decl = decl_info_of_entity(info, e);
- ast_node(pl, ProcLit, decl->proc_lit);
- if (pl->body != nullptr) {
- auto *found = map_get(&info->gen_procs, hash_pointer(ident));
- if (found) {
- auto procs = *found;
- for_array(i, procs) {
- Entity *e = procs[i];
- if (!ptr_set_exists(&proc->module->min_dep_set, e)) {
- continue;
- }
- DeclInfo *d = decl_info_of_entity(info, e);
- ir_build_poly_proc(proc, &d->proc_lit->ProcLit, e);
- }
- } else {
- ir_build_poly_proc(proc, pl, e);
- }
- } else {
- // FFI - Foreign function interace
- String original_name = e->token.string;
- String name = original_name;
- if (e->Procedure.link_name.len > 0) {
- name = e->Procedure.link_name;
- }
- irValue *value = ir_value_procedure(proc->module->allocator,
- proc->module, e, e->type, pl->type, pl->body, name);
- value->Proc.tags = pl->tags;
- value->Proc.inlining = pl->inlining;
- ir_module_add_value(proc->module, e, value);
- ir_build_proc(value, proc);
- if (value->Proc.is_foreign || value->Proc.is_export) {
- HashKey key = hash_string(name);
- irValue **prev_value = map_get(&proc->module->members, key);
- if (prev_value == nullptr) {
- // NOTE(bill): Don't do mutliple declarations in the IR
- map_set(&proc->module->members, key, value);
- }
- } else {
- array_add(&proc->children, &value->Proc);
- }
- }
- }
- }
- }
- void ir_build_stmt_list(irProcedure *proc, Array<AstNode *> stmts) {
- // NOTE(bill): Precollect constant entities
- for_array(i, stmts) {
- AstNode *stmt = stmts[i];
- switch (stmt->kind) {
- case_ast_node(vd, ValueDecl, stmt);
- ir_build_constant_value_decl(proc, vd);
- case_end;
- case_ast_node(fb, ForeignBlockDecl, stmt);
- ir_build_stmt_list(proc, fb->decls);
- case_end;
- }
- }
- for_array(i, stmts) {
- ir_build_stmt(proc, stmts[i]);
- }
- }
- void ir_build_stmt_internal(irProcedure *proc, AstNode *node);
- void ir_build_stmt(irProcedure *proc, AstNode *node) {
- u64 prev_stmt_state_flags = proc->module->stmt_state_flags;
- if (node->stmt_state_flags != 0) {
- u64 in = node->stmt_state_flags;
- u64 out = proc->module->stmt_state_flags;
- if (in & StmtStateFlag_bounds_check) {
- out |= StmtStateFlag_bounds_check;
- out &= ~StmtStateFlag_no_bounds_check;
- } else if (in & StmtStateFlag_no_bounds_check) {
- out |= StmtStateFlag_no_bounds_check;
- out &= ~StmtStateFlag_bounds_check;
- }
- proc->module->stmt_state_flags = out;
- }
- ir_build_stmt_internal(proc, node);
- proc->module->stmt_state_flags = prev_stmt_state_flags;
- }
- void ir_build_when_stmt(irProcedure *proc, AstNodeWhenStmt *ws) {
- irValue *cond = ir_build_expr(proc, ws->cond);
- GB_ASSERT(cond->kind == irValue_Constant &&
- is_type_boolean(ir_type(cond)));
- GB_ASSERT(cond->Constant.value.kind == ExactValue_Bool);
- if (cond->Constant.value.value_bool) {
- ir_build_stmt_list(proc, ws->body->BlockStmt.stmts);
- } else if (ws->else_stmt) {
- switch (ws->else_stmt->kind) {
- case AstNode_BlockStmt:
- ir_build_stmt_list(proc, ws->else_stmt->BlockStmt.stmts);
- break;
- case AstNode_WhenStmt:
- ir_build_when_stmt(proc, &ws->else_stmt->WhenStmt);
- break;
- default:
- GB_PANIC("Invalid `else` statement in `when` statement");
- break;
- }
- }
- }
- void ir_build_range_indexed(irProcedure *proc, irValue *expr, Type *val_type, irValue *count_ptr,
- irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
- irValue *count = nullptr;
- Type *expr_type = base_type(type_deref(ir_type(expr)));
- switch (expr_type->kind) {
- case Type_Array:
- count = ir_const_int(proc->module->allocator, expr_type->Array.count);
- break;
- case Type_Vector:
- count = ir_const_int(proc->module->allocator, expr_type->Vector.count);
- break;
- }
- irValue *val = nullptr;
- irValue *idx = nullptr;
- irBlock *loop = nullptr;
- irBlock *done = nullptr;
- irBlock *body = nullptr;
- irValue *key = nullptr;
- if (expr_type->kind == Type_Map) {
- key = ir_add_local_generated(proc, expr_type->Map.key);
- }
- irValue *index = ir_add_local_generated(proc, t_int);
- ir_emit_store(proc, index, ir_const_int(proc->module->allocator, -1));
- loop = ir_new_block(proc, nullptr, "for.index.loop");
- ir_emit_jump(proc, loop);
- ir_start_block(proc, loop);
- irValue *incr = ir_emit_arith(proc, Token_Add, ir_emit_load(proc, index), v_one, t_int);
- ir_emit_store(proc, index, incr);
- body = ir_new_block(proc, nullptr, "for.index.body");
- done = ir_new_block(proc, nullptr, "for.index.done");
- if (count == nullptr) {
- count = ir_emit_load(proc, count_ptr);
- }
- irValue *cond = ir_emit_comp(proc, Token_Lt, incr, count);
- ir_emit_if(proc, cond, body, done);
- ir_start_block(proc, body);
- idx = ir_emit_load(proc, index);
- if (val_type != nullptr) {
- switch (expr_type->kind) {
- case Type_Array: {
- val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
- break;
- }
- case Type_Vector: {
- val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
- break;
- }
- case Type_Slice: {
- irValue *elem = ir_slice_elem(proc, expr);
- val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
- break;
- }
- case Type_DynamicArray: {
- irValue *elem = ir_emit_struct_ep(proc, expr, 0);
- elem = ir_emit_load(proc, elem);
- val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
- break;
- }
- case Type_Map: {
- irValue *entries = ir_emit_struct_ep(proc, expr, 1);
- irValue *elem = ir_emit_struct_ep(proc, entries, 0);
- elem = ir_emit_load(proc, elem);
- irValue *entry = ir_emit_ptr_offset(proc, elem, idx);
- val = ir_emit_load(proc, ir_emit_struct_ep(proc, entry, 2));
- irValue *hash = ir_emit_struct_ep(proc, entry, 0);
- if (is_type_string(expr_type->Map.key)) {
- irValue *str = ir_emit_struct_ep(proc, hash, 1);
- ir_emit_store(proc, key, ir_emit_load(proc, str));
- } else {
- irValue *hash_ptr = ir_emit_struct_ep(proc, hash, 0);
- hash_ptr = ir_emit_conv(proc, hash_ptr, ir_type(key));
- ir_emit_store(proc, key, ir_emit_load(proc, hash_ptr));
- }
- break;
- }
- default:
- GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
- break;
- }
- }
- if (key != nullptr) {
- idx = ir_emit_load(proc, key);
- }
- if (val_) *val_ = val;
- if (idx_) *idx_ = idx;
- if (loop_) *loop_ = loop;
- if (done_) *done_ = done;
- }
- void ir_build_range_string(irProcedure *proc, irValue *expr, Type *val_type,
- irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
- irValue *count = v_zero;
- Type *expr_type = base_type(ir_type(expr));
- switch (expr_type->kind) {
- case Type_Basic:
- count = ir_string_len(proc, expr);
- break;
- default:
- GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
- break;
- }
- irValue *val = nullptr;
- irValue *idx = nullptr;
- irBlock *loop = nullptr;
- irBlock *done = nullptr;
- irBlock *body = nullptr;
- irValue *offset_ = ir_add_local_generated(proc, t_int);
- ir_emit_store(proc, offset_, v_zero);
- loop = ir_new_block(proc, nullptr, "for.string.loop");
- ir_emit_jump(proc, loop);
- ir_start_block(proc, loop);
- body = ir_new_block(proc, nullptr, "for.string.body");
- done = ir_new_block(proc, nullptr, "for.string.done");
- irValue *offset = ir_emit_load(proc, offset_);
- irValue *cond = ir_emit_comp(proc, Token_Lt, offset, count);
- ir_emit_if(proc, cond, body, done);
- ir_start_block(proc, body);
- irValue *str_elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, expr), offset);
- irValue *str_len = ir_emit_arith(proc, Token_Sub, count, offset, t_int);
- irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 1);
- args[0] = ir_emit_string(proc, str_elem, str_len);
- irValue *rune_and_len = ir_emit_global_call(proc, "__string_decode_rune", args, 1);
- irValue *len = ir_emit_struct_ev(proc, rune_and_len, 1);
- ir_emit_store(proc, offset_, ir_emit_arith(proc, Token_Add, offset, len, t_int));
- idx = offset;
- if (val_type != nullptr) {
- val = ir_emit_struct_ev(proc, rune_and_len, 0);
- }
- if (val_) *val_ = val;
- if (idx_) *idx_ = idx;
- if (loop_) *loop_ = loop;
- if (done_) *done_ = done;
- }
- void ir_build_range_interval(irProcedure *proc, AstNodeBinaryExpr *node, Type *val_type,
- irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
- // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
- // If `lower` is changed, should `val` do so or is that not typical behaviour?
- irValue *lower = ir_build_expr(proc, node->left);
- irValue *upper = nullptr;
- irValue *val = nullptr;
- irValue *idx = nullptr;
- irBlock *loop = nullptr;
- irBlock *done = nullptr;
- irBlock *body = nullptr;
- if (val_type == nullptr) {
- val_type = ir_type(lower);
- }
- irValue *value = ir_add_local_generated(proc, val_type);
- ir_emit_store(proc, value, lower);
- irValue *index = ir_add_local_generated(proc, t_int);
- ir_emit_store(proc, index, ir_const_int(proc->module->allocator, 0));
- loop = ir_new_block(proc, nullptr, "for.interval.loop");
- ir_emit_jump(proc, loop);
- ir_start_block(proc, loop);
- body = ir_new_block(proc, nullptr, "for.interval.body");
- done = ir_new_block(proc, nullptr, "for.interval.done");
- TokenKind op = Token_Lt;
- switch (node->op.kind) {
- case Token_Ellipsis: op = Token_LtEq; break;
- case Token_HalfClosed: op = Token_Lt; break;
- default: GB_PANIC("Invalid interval operator"); break;
- }
- upper = ir_build_expr(proc, node->right);
- irValue *cond = ir_emit_comp(proc, op, ir_emit_load(proc, value), upper);
- ir_emit_if(proc, cond, body, done);
- ir_start_block(proc, body);
- if (value != nullptr) {
- val = ir_emit_load(proc, value);
- }
- idx = ir_emit_load(proc, index);
- ir_emit_increment(proc, value);
- ir_emit_increment(proc, index);
- if (val_) *val_ = val;
- if (idx_) *idx_ = idx;
- if (loop_) *loop_ = loop;
- if (done_) *done_ = done;
- }
- void ir_store_type_case_implicit(irProcedure *proc, AstNode *clause, irValue *value) {
- Entity *e = implicit_entity_of_node(proc->module->info, clause);
- GB_ASSERT(e != nullptr);
- irValue *x = ir_add_local(proc, e, nullptr, false);
- ir_emit_store(proc, x, value);
- }
- void ir_type_case_body(irProcedure *proc, AstNode *label, AstNode *clause, irBlock *body, irBlock *done) {
- ast_node(cc, CaseClause, clause);
- ir_push_target_list(proc, label, done, nullptr, nullptr);
- ir_open_scope(proc);
- ir_build_stmt_list(proc, cc->stmts);
- ir_close_scope(proc, irDeferExit_Default, body);
- ir_pop_target_list(proc);
- ir_emit_jump(proc, done);
- }
- void ir_build_stmt_internal(irProcedure *proc, AstNode *node) {
- switch (node->kind) {
- case_ast_node(bs, EmptyStmt, node);
- case_end;
- // case_ast_node(fb, ForeignBlockDecl, node);
- // ir_build_stmt_list(proc, fb->decls);
- // case_end;
- case_ast_node(us, UsingStmt, node);
- for_array(i, us->list) {
- AstNode *decl = unparen_expr(us->list[i]);
- // if (decl->kind == AstNode_GenDecl) {
- // ir_build_stmt(proc, decl);
- // }
- }
- case_end;
- case_ast_node(ws, WhenStmt, node);
- ir_build_when_stmt(proc, ws);
- case_end;
- #if 0
- case_ast_node(s, IncDecStmt, node);
- TokenKind op = Token_Add;
- if (s->op.kind == Token_Dec) {
- op = Token_Sub;
- }
- irAddr addr = ir_build_addr(proc, s->expr);
- ir_build_assign_op(proc, addr, v_one, op);
- case_end;
- #endif
- case_ast_node(vd, ValueDecl, node);
- if (vd->is_mutable) {
- irModule *m = proc->module;
- gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
- defer (gb_temp_arena_memory_end(tmp));
- if (vd->values.count == 0) { // declared and zero-initialized
- for_array(i, vd->names) {
- AstNode *name = vd->names[i];
- if (!is_blank_ident(name)) {
- ir_add_local_for_identifier(proc, name, true);
- }
- }
- } else { // Tuple(s)
- Array<irAddr> lvals = {};
- Array<irValue *> inits = {};
- array_init(&lvals, m->tmp_allocator, vd->names.count);
- array_init(&inits, m->tmp_allocator, vd->names.count);
- for_array(i, vd->names) {
- AstNode *name = vd->names[i];
- irAddr lval = ir_addr(nullptr);
- if (!is_blank_ident(name)) {
- ir_add_local_for_identifier(proc, name, false);
- lval = ir_build_addr(proc, name);
- }
- array_add(&lvals, lval);
- ir_check_type_and_gen_for_proc_lit(proc, ir_addr_type(lval));
- }
- for_array(i, vd->values) {
- irValue *init = ir_build_expr(proc, vd->values[i]);
- Type *t = ir_type(init);
- if (t->kind == Type_Tuple) {
- for_array(i, t->Tuple.variables) {
- Entity *e = t->Tuple.variables[i];
- irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
- array_add(&inits, v);
- }
- } else {
- array_add(&inits, init);
- }
- }
- for_array(i, inits) {
- ir_addr_store(proc, lvals[i], inits[i]);
- }
- }
- }
- case_end;
- case_ast_node(as, AssignStmt, node);
- ir_emit_comment(proc, str_lit("AssignStmt"));
- irModule *m = proc->module;
- gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
- switch (as->op.kind) {
- case Token_Eq: {
- Array<irAddr> lvals;
- array_init(&lvals, m->tmp_allocator);
- for_array(i, as->lhs) {
- AstNode *lhs = as->lhs[i];
- irAddr lval = {};
- if (!is_blank_ident(lhs)) {
- lval = ir_build_addr(proc, lhs);
- }
- array_add(&lvals, lval);
- }
- if (as->lhs.count == as->rhs.count) {
- if (as->lhs.count == 1) {
- AstNode *rhs = as->rhs[0];
- irValue *init = ir_build_expr(proc, rhs);
- ir_addr_store(proc, lvals[0], init);
- } else {
- Array<irValue *> inits;
- array_init(&inits, m->tmp_allocator, lvals.count);
- for_array(i, as->rhs) {
- irValue *init = ir_build_expr(proc, as->rhs[i]);
- array_add(&inits, init);
- }
- for_array(i, inits) {
- ir_addr_store(proc, lvals[i], inits[i]);
- }
- }
- } else {
- Array<irValue *> inits;
- array_init(&inits, m->tmp_allocator, lvals.count);
- for_array(i, as->rhs) {
- irValue *init = ir_build_expr(proc, as->rhs[i]);
- Type *t = ir_type(init);
- // TODO(bill): refactor for code reuse as this is repeated a bit
- if (t->kind == Type_Tuple) {
- for_array(i, t->Tuple.variables) {
- Entity *e = t->Tuple.variables[i];
- irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
- array_add(&inits, v);
- }
- } else {
- array_add(&inits, init);
- }
- }
- for_array(i, inits) {
- ir_addr_store(proc, lvals[i], inits[i]);
- }
- }
- break;
- }
- default: {
- // NOTE(bill): Only 1 += 1 is allowed, no tuples
- // +=, -=, etc
- i32 op = cast(i32)as->op.kind;
- op += Token_Add - Token_AddEq; // Convert += to +
- irAddr lhs = ir_build_addr(proc, as->lhs[0]);
- irValue *value = ir_build_expr(proc, as->rhs[0]);
- ir_build_assign_op(proc, lhs, value, cast(TokenKind)op);
- break;
- }
- }
- gb_temp_arena_memory_end(tmp);
- case_end;
- case_ast_node(es, ExprStmt, node);
- // NOTE(bill): No need to use return value
- ir_build_expr(proc, es->expr);
- case_end;
- case_ast_node(bs, BlockStmt, node);
- ir_open_scope(proc);
- ir_build_stmt_list(proc, bs->stmts);
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- case_end;
- case_ast_node(ds, DeferStmt, node);
- ir_emit_comment(proc, str_lit("DeferStmt"));
- isize scope_index = proc->scope_index;
- // TODO(bill): What was the original rationale behind this line?
- // if (ds->stmt->kind == AstNode_BlockStmt) scope_index--;
- ir_add_defer_node(proc, scope_index, ds->stmt);
- case_end;
- case_ast_node(rs, ReturnStmt, node);
- ir_emit_comment(proc, str_lit("ReturnStmt"));
- irValue *v = nullptr;
- TypeTuple *tuple = &proc->type->Proc.results->Tuple;
- isize return_count = proc->type->Proc.result_count;
- isize res_count = rs->results.count;
- if (res_count > 0 &&
- rs->results[0]->kind == AstNode_FieldValue) {
- gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena);
- defer (gb_temp_arena_memory_end(tmp));
- Array<irValue *> results;
- array_init_count(&results, proc->module->tmp_allocator, return_count);
- for_array(arg_index, rs->results) {
- AstNode *arg = rs->results[arg_index];
- ast_node(fv, FieldValue, arg);
- GB_ASSERT(fv->field->kind == AstNode_Ident);
- String name = fv->field->Ident.token.string;
- isize index = lookup_procedure_result(&proc->type->Proc, name);
- GB_ASSERT(index >= 0);
- irValue *expr = ir_build_expr(proc, fv->value);
- results[index] = expr;
- }
- for (isize i = 0; i < return_count; i++) {
- Entity *e = tuple->variables[i];
- GB_ASSERT(e->kind == Entity_Variable);
- if (results[i] == nullptr) {
- if (e->Variable.default_value.kind != ExactValue_Invalid) {
- results[i] = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value);
- } else {
- results[i] = ir_value_nil(proc->module->allocator, e->type);
- }
- } else {
- results[i] = ir_emit_conv(proc, results[i], e->type);
- }
- }
- if (results.count == 1) {
- v = results[0];
- } else {
- GB_ASSERT(results.count == return_count);
- Type *ret_type = proc->type->Proc.results;
- v = ir_add_local_generated(proc, ret_type);
- for_array(i, results) {
- irValue *field = ir_emit_struct_ep(proc, v, cast(i32)i);
- irValue *res = results[i];
- ir_emit_store(proc, field, res);
- }
- v = ir_emit_load(proc, v);
- }
- } else if (return_count == 0) {
- // No return values
- } else if (return_count == 1) {
- Entity *e = tuple->variables[0];
- if (res_count == 0) {
- if (e->Variable.default_value.kind != ExactValue_Invalid) {
- v = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value);
- } else {
- v = ir_value_nil(proc->module->allocator, e->type);
- }
- } else {
- v = ir_build_expr(proc, rs->results[0]);
- v = ir_emit_conv(proc, v, e->type);
- }
- } else {
- gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena);
- defer (gb_temp_arena_memory_end(tmp));
- Array<irValue *> results;
- array_init(&results, proc->module->tmp_allocator, return_count);
- isize total_index = 0;
- isize res_index = 0;
- for (; res_index < res_count; res_index++) {
- irValue *res = ir_build_expr(proc, rs->results[res_index]);
- Type *t = ir_type(res);
- if (t->kind == Type_Tuple) {
- for_array(i, t->Tuple.variables) {
- Entity *e = t->Tuple.variables[i];
- irValue *v = ir_emit_struct_ev(proc, res, cast(i32)i);
- array_add(&results, v);
- total_index++;
- }
- } else {
- array_add(&results, res);
- total_index++;
- }
- }
- while (total_index < return_count) {
- Entity *e = tuple->variables[total_index];
- irValue *res = nullptr;
- if (e->Variable.default_value.kind != ExactValue_Invalid) {
- res = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value);
- } else {
- res = ir_value_nil(proc->module->allocator, e->type);
- }
- array_add(&results, res);
- total_index++;
- }
- GB_ASSERT(results.count == return_count);
- Type *ret_type = proc->type->Proc.results;
- v = ir_add_local_generated(proc, ret_type);
- for_array(i, results) {
- Entity *e = tuple->variables[i];
- irValue *res = ir_emit_conv(proc, results[i], e->type);
- irValue *field = ir_emit_struct_ep(proc, v, cast(i32)i);
- ir_emit_store(proc, field, res);
- }
- v = ir_emit_load(proc, v);
- }
- ir_emit_return(proc, v);
- case_end;
- case_ast_node(is, IfStmt, node);
- ir_emit_comment(proc, str_lit("IfStmt"));
- if (is->init != nullptr) {
- irBlock *init = ir_new_block(proc, node, "if.init");
- ir_emit_jump(proc, init);
- ir_start_block(proc, init);
- ir_build_stmt(proc, is->init);
- }
- irBlock *then = ir_new_block(proc, node, "if.then");
- irBlock *done = ir_new_block(proc, node, "if.done");
- irBlock *else_ = done;
- if (is->else_stmt != nullptr) {
- else_ = ir_new_block(proc, is->else_stmt, "if.else");
- }
- ir_build_cond(proc, is->cond, then, else_);
- ir_start_block(proc, then);
- ir_open_scope(proc);
- ir_build_stmt(proc, is->body);
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- ir_emit_jump(proc, done);
- if (is->else_stmt != nullptr) {
- ir_start_block(proc, else_);
- ir_open_scope(proc);
- ir_build_stmt(proc, is->else_stmt);
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- ir_emit_jump(proc, done);
- }
- ir_start_block(proc, done);
- case_end;
- case_ast_node(fs, ForStmt, node);
- ir_emit_comment(proc, str_lit("ForStmt"));
- if (fs->init != nullptr) {
- irBlock *init = ir_new_block(proc, node, "for.init");
- ir_emit_jump(proc, init);
- ir_start_block(proc, init);
- ir_build_stmt(proc, fs->init);
- }
- irBlock *body = ir_new_block(proc, node, "for.body");
- irBlock *done = ir_new_block(proc, node, "for.done"); // NOTE(bill): Append later
- irBlock *loop = body;
- if (fs->cond != nullptr) {
- loop = ir_new_block(proc, node, "for.loop");
- }
- irBlock *post = loop;
- if (fs->post != nullptr) {
- post = ir_new_block(proc, node, "for.post");
- }
- ir_emit_jump(proc, loop);
- ir_start_block(proc, loop);
- if (loop != body) {
- ir_build_cond(proc, fs->cond, body, done);
- ir_start_block(proc, body);
- }
- ir_push_target_list(proc, fs->label, done, post, nullptr);
- ir_open_scope(proc);
- ir_build_stmt(proc, fs->body);
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- ir_pop_target_list(proc);
- ir_emit_jump(proc, post);
- if (fs->post != nullptr) {
- ir_start_block(proc, post);
- ir_build_stmt(proc, fs->post);
- ir_emit_jump(proc, loop);
- }
- ir_start_block(proc, done);
- case_end;
- case_ast_node(rs, RangeStmt, node);
- ir_emit_comment(proc, str_lit("RangeStmt"));
- Type *val_type = nullptr;
- Type *idx_type = nullptr;
- if (rs->value != nullptr && !is_blank_ident(rs->value)) {
- val_type = type_of_expr(proc->module->info, rs->value);
- }
- if (rs->index != nullptr && !is_blank_ident(rs->index)) {
- idx_type = type_of_expr(proc->module->info, rs->index);
- }
- if (val_type != nullptr) {
- ir_add_local_for_identifier(proc, rs->value, true);
- }
- if (idx_type != nullptr) {
- ir_add_local_for_identifier(proc, rs->index, true);
- }
- irValue *val = nullptr;
- irValue *index = nullptr;
- irBlock *loop = nullptr;
- irBlock *done = nullptr;
- AstNode *expr = unparen_expr(rs->expr);
- TypeAndValue tav = type_and_value_of_expr(proc->module->info, expr);
- if (is_ast_node_a_range(expr)) {
- ir_build_range_interval(proc, &expr->BinaryExpr, val_type, &val, &index, &loop, &done);
- } else if (tav.mode == Addressing_Type) {
- TokenPos pos = ast_node_token(expr).pos;
- gbAllocator a = proc->module->allocator;
- Type *t = tav.type;
- GB_ASSERT(is_type_enum(t));
- Type *enum_ptr = make_type_pointer(a, t);
- t = base_type(t);
- Type *core_elem = core_type(t);
- i64 enum_count = t->Enum.field_count;
- irValue *max_count = ir_const_int(a, enum_count);
- irValue *ti = ir_type_info(proc, t);
- irValue *variant = ir_emit_struct_ep(proc, ti, 2);
- irValue *eti_ptr = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
- irValue *values = ir_emit_load(proc, ir_emit_struct_ep(proc, eti_ptr, 2));
- irValue *values_data = ir_slice_elem(proc, values);
- irValue *offset_ = ir_add_local_generated(proc, t_int);
- ir_emit_store(proc, offset_, v_zero);
- loop = ir_new_block(proc, nullptr, "for.enum.loop");
- ir_emit_jump(proc, loop);
- ir_start_block(proc, loop);
- irBlock *body = ir_new_block(proc, nullptr, "for.enum.body");
- done = ir_new_block(proc, nullptr, "for.enum.done");
- irValue *offset = ir_emit_load(proc, offset_);
- irValue *cond = ir_emit_comp(proc, Token_Lt, offset, max_count);
- ir_emit_if(proc, cond, body, done);
- ir_start_block(proc, body);
- irValue *val_ptr = ir_emit_ptr_offset(proc, values_data, offset);
- ir_emit_increment(proc, offset_);
- index = offset;
- if (val_type != nullptr) {
- if (is_type_float(core_elem)) {
- irValue *f = ir_emit_load(proc, ir_emit_conv(proc, val_ptr, t_f64_ptr));
- val = ir_emit_conv(proc, f, t);
- } else if (is_type_integer(core_elem)) {
- irValue *i = ir_emit_load(proc, ir_emit_conv(proc, val_ptr, t_i64_ptr));
- val = ir_emit_conv(proc, i, t);
- } else {
- GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
- }
- }
- } else {
- Type *expr_type = type_of_expr(proc->module->info, rs->expr);
- Type *et = base_type(type_deref(expr_type));
- switch (et->kind) {
- case Type_Map: {
- irAddr addr = ir_build_addr(proc, rs->expr);
- irValue *map = ir_addr_get_ptr(proc, addr);
- if (is_type_pointer(type_deref(ir_addr_type(addr)))) {
- map = ir_addr_load(proc, addr);
- }
- irValue *entries_ptr = ir_emit_struct_ep(proc, map, 1);
- irValue *count_ptr = ir_emit_struct_ep(proc, entries_ptr, 1);
- ir_build_range_indexed(proc, map, val_type, count_ptr, &val, &index, &loop, &done);
- break;
- }
- case Type_Array: {
- irValue *count_ptr = nullptr;
- irValue *array = ir_build_addr_ptr(proc, rs->expr);
- if (is_type_pointer(type_deref(ir_type(array)))) {
- array = ir_emit_load(proc, array);
- }
- count_ptr = ir_add_local_generated(proc, t_int);
- ir_emit_store(proc, count_ptr, ir_const_int(proc->module->allocator, et->Array.count));
- ir_build_range_indexed(proc, array, val_type, count_ptr, &val, &index, &loop, &done);
- break;
- }
- case Type_Vector: {
- irValue *count_ptr = nullptr;
- irValue *vector = ir_build_addr_ptr(proc, rs->expr);
- if (is_type_pointer(type_deref(ir_type(vector)))) {
- vector = ir_emit_load(proc, vector);
- }
- count_ptr = ir_add_local_generated(proc, t_int);
- ir_emit_store(proc, count_ptr, ir_const_int(proc->module->allocator, et->Vector.count));
- ir_build_range_indexed(proc, vector, val_type, count_ptr, &val, &index, &loop, &done);
- break;
- }
- case Type_DynamicArray: {
- irValue *count_ptr = nullptr;
- irValue *array = ir_build_addr_ptr(proc, rs->expr);
- if (is_type_pointer(type_deref(ir_type(array)))) {
- array = ir_emit_load(proc, array);
- }
- count_ptr = ir_emit_struct_ep(proc, array, 1);
- ir_build_range_indexed(proc, array, val_type, count_ptr, &val, &index, &loop, &done);
- break;
- }
- case Type_Slice: {
- irValue *count_ptr = nullptr;
- irValue *slice = ir_build_expr(proc, rs->expr);
- if (is_type_pointer(ir_type(slice))) {
- count_ptr = ir_emit_struct_ep(proc, slice, 1);
- slice = ir_emit_load(proc, slice);
- } else {
- count_ptr = ir_add_local_generated(proc, t_int);
- ir_emit_store(proc, count_ptr, ir_slice_count(proc, slice));
- }
- ir_build_range_indexed(proc, slice, val_type, count_ptr, &val, &index, &loop, &done);
- break;
- }
- case Type_Basic: {
- irValue *string = ir_build_expr(proc, rs->expr);
- if (is_type_pointer(ir_type(string))) {
- string = ir_emit_load(proc, string);
- }
- if (is_type_untyped(expr_type)) {
- irValue *s = ir_add_local_generated(proc, t_string);
- ir_emit_store(proc, s, string);
- string = ir_emit_load(proc, s);
- }
- ir_build_range_string(proc, string, val_type, &val, &index, &loop, &done);
- break;
- }
- default:
- GB_PANIC("Cannot range over %s", type_to_string(expr_type));
- break;
- }
- }
- irAddr val_addr = {};
- irAddr idx_addr = {};
- if (val_type != nullptr) {
- val_addr = ir_build_addr(proc, rs->value);
- }
- if (idx_type != nullptr) {
- idx_addr = ir_build_addr(proc, rs->index);
- }
- if (val_type != nullptr) {
- ir_addr_store(proc, val_addr, val);
- }
- if (idx_type != nullptr) {
- ir_addr_store(proc, idx_addr, index);
- }
- ir_push_target_list(proc, rs->label, done, loop, nullptr);
- ir_open_scope(proc);
- ir_build_stmt(proc, rs->body);
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- ir_pop_target_list(proc);
- ir_emit_jump(proc, loop);
- ir_start_block(proc, done);
- case_end;
- case_ast_node(ss, SwitchStmt, node);
- ir_emit_comment(proc, str_lit("SwitchStmt"));
- if (ss->init != nullptr) {
- ir_build_stmt(proc, ss->init);
- }
- irValue *tag = v_true;
- if (ss->tag != nullptr) {
- tag = ir_build_expr(proc, ss->tag);
- }
- irBlock *done = ir_new_block(proc, node, "switch.done"); // NOTE(bill): Append later
- ast_node(body, BlockStmt, ss->body);
- Array<AstNode *> default_stmts = {};
- irBlock *default_fall = nullptr;
- irBlock *default_block = nullptr;
- irBlock *fall = nullptr;
- bool append_fall = false;
- isize case_count = body->stmts.count;
- for_array(i, body->stmts) {
- AstNode *clause = body->stmts[i];
- irBlock *body = fall;
- ast_node(cc, CaseClause, clause);
- if (body == nullptr) {
- if (cc->list.count == 0) {
- body = ir_new_block(proc, clause, "switch.dflt.body");
- } else {
- body = ir_new_block(proc, clause, "switch.case.body");
- }
- }
- if (append_fall && body == fall) {
- append_fall = false;
- }
- fall = done;
- if (i+1 < case_count) {
- append_fall = true;
- fall = ir_new_block(proc, clause, "switch.fall.body");
- }
- if (cc->list.count == 0) {
- // default case
- default_stmts = cc->stmts;
- default_fall = fall;
- default_block = body;
- continue;
- }
- irBlock *next_cond = nullptr;
- for_array(j, cc->list) {
- AstNode *expr = unparen_expr(cc->list[j]);
- next_cond = ir_new_block(proc, clause, "switch.case.next");
- irValue *cond = v_false;
- if (is_ast_node_a_range(expr)) {
- ast_node(ie, BinaryExpr, expr);
- TokenKind op = Token_Invalid;
- switch (ie->op.kind) {
- case Token_Ellipsis: op = Token_LtEq; break;
- case Token_HalfClosed: op = Token_Lt; break;
- default: GB_PANIC("Invalid interval operator"); break;
- }
- irValue *lhs = ir_build_expr(proc, ie->left);
- irValue *rhs = ir_build_expr(proc, ie->right);
- // TODO(bill): do short circuit here
- irValue *cond_lhs = ir_emit_comp(proc, Token_LtEq, lhs, tag);
- irValue *cond_rhs = ir_emit_comp(proc, op, tag, rhs);
- cond = ir_emit_arith(proc, Token_And, cond_lhs, cond_rhs, t_bool);
- } else {
- cond = ir_emit_comp(proc, Token_CmpEq, tag, ir_build_expr(proc, expr));
- }
- ir_emit_if(proc, cond, body, next_cond);
- ir_start_block(proc, next_cond);
- }
- ir_start_block(proc, body);
- ir_push_target_list(proc, ss->label, done, nullptr, fall);
- ir_open_scope(proc);
- ir_build_stmt_list(proc, cc->stmts);
- ir_close_scope(proc, irDeferExit_Default, body);
- ir_pop_target_list(proc);
- ir_emit_jump(proc, done);
- proc->curr_block = next_cond;
- // ir_start_block(proc, next_cond);
- }
- if (default_block != nullptr) {
- ir_emit_jump(proc, default_block);
- ir_start_block(proc, default_block);
- ir_push_target_list(proc, ss->label, done, nullptr, default_fall);
- ir_open_scope(proc);
- ir_build_stmt_list(proc, default_stmts);
- ir_close_scope(proc, irDeferExit_Default, default_block);
- ir_pop_target_list(proc);
- }
- ir_emit_jump(proc, done);
- ir_start_block(proc, done);
- case_end;
- case_ast_node(ss, TypeSwitchStmt, node);
- ir_emit_comment(proc, str_lit("TypeSwitchStmt"));
- gbAllocator allocator = proc->module->allocator;
- ast_node(as, AssignStmt, ss->tag);
- GB_ASSERT(as->lhs.count == 1);
- GB_ASSERT(as->rhs.count == 1);
- irValue *parent = ir_build_expr(proc, as->rhs[0]);
- Type *parent_type = ir_type(parent);
- bool is_parent_ptr = is_type_pointer(ir_type(parent));
- MatchTypeKind match_type_kind = check_valid_type_match_type(ir_type(parent));
- GB_ASSERT(match_type_kind != MatchType_Invalid);
- irValue *parent_value = parent;
- irValue *parent_ptr = parent;
- if (!is_parent_ptr) {
- parent_ptr = ir_address_from_load_or_generate_local(proc, parent_ptr);
- }
- irValue *tag_index = nullptr;
- irValue *union_data = nullptr;
- if (match_type_kind == MatchType_Union) {
- ir_emit_comment(proc, str_lit("get union's tag"));
- tag_index = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, parent_ptr));
- union_data = ir_emit_conv(proc, parent_ptr, t_rawptr);
- }
- irBlock *start_block = ir_new_block(proc, node, "typeswitch.case.first");
- ir_emit_jump(proc, start_block);
- ir_start_block(proc, start_block);
- // NOTE(bill): Append this later
- irBlock *done = ir_new_block(proc, node, "typeswitch.done");
- AstNode *default_ = nullptr;
- ast_node(body, BlockStmt, ss->body);
- gb_local_persist i32 weird_count = 0;
- for_array(i, body->stmts) {
- AstNode *clause = body->stmts[i];
- ast_node(cc, CaseClause, clause);
- if (cc->list.count == 0) {
- default_ = clause;
- continue;
- }
- irBlock *body = ir_new_block(proc, clause, "typeswitch.body");
- irBlock *next = nullptr;
- Type *case_type = nullptr;
- for_array(type_index, cc->list) {
- next = ir_new_block(proc, nullptr, "typeswitch.next");
- case_type = type_of_expr(proc->module->info, cc->list[type_index]);
- irValue *cond = nullptr;
- if (match_type_kind == MatchType_Union) {
- Type *ut = base_type(type_deref(parent_type));
- irValue *variant_tag = ir_const_union_tag(proc->module->allocator, ut, case_type);
- cond = ir_emit_comp(proc, Token_CmpEq, tag_index, variant_tag);
- } else if (match_type_kind == MatchType_Any) {
- irValue *any_ti = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 1));
- irValue *case_ti = ir_type_info(proc, case_type);
- cond = ir_emit_comp(proc, Token_CmpEq, any_ti, case_ti);
- }
- GB_ASSERT(cond != nullptr);
- ir_emit_if(proc, cond, body, next);
- ir_start_block(proc, next);
- }
- Entity *case_entity = implicit_entity_of_node(proc->module->info, clause);
- irValue *value = parent_value;
- ir_start_block(proc, body);
- if (cc->list.count == 1) {
- bool any_or_not_ptr = is_type_any(type_deref(parent_type)) || !is_parent_ptr;
- Type *ct = case_entity->type;
- if (any_or_not_ptr) {
- ct = make_type_pointer(proc->module->allocator, ct);
- }
- GB_ASSERT_MSG(is_type_pointer(ct), "%s", type_to_string(ct));
- irValue *data = nullptr;
- if (match_type_kind == MatchType_Union) {
- data = union_data;
- } else if (match_type_kind == MatchType_Any) {
- irValue *any_data = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 0));
- data = any_data;
- }
- value = ir_emit_conv(proc, data, ct);
- if (any_or_not_ptr) {
- value = ir_emit_load(proc, value);
- }
- }
- ir_store_type_case_implicit(proc, clause, value);
- ir_type_case_body(proc, ss->label, clause, body, done);
- ir_start_block(proc, next);
- }
- if (default_ != nullptr) {
- ir_store_type_case_implicit(proc, default_, parent_value);
- ir_type_case_body(proc, ss->label, default_, proc->curr_block, done);
- } else {
- ir_emit_jump(proc, done);
- }
- ir_start_block(proc, done);
- case_end;
- case_ast_node(bs, BranchStmt, node);
- irBlock *block = nullptr;
- if (bs->label != nullptr) {
- irBranchBlocks bb = ir_lookup_branch_blocks(proc, bs->label);
- switch (bs->token.kind) {
- case Token_break: block = bb.break_; break;
- case Token_continue: block = bb.continue_; break;
- case Token_fallthrough:
- GB_PANIC("fallthrough cannot have a label");
- break;
- }
- } else {
- switch (bs->token.kind) {
- case Token_break:
- for (irTargetList *t = proc->target_list; t != nullptr && block == nullptr; t = t->prev) {
- block = t->break_;
- }
- break;
- case Token_continue:
- for (irTargetList *t = proc->target_list; t != nullptr && block == nullptr; t = t->prev) {
- block = t->continue_;
- }
- break;
- case Token_fallthrough:
- for (irTargetList *t = proc->target_list; t != nullptr && block == nullptr; t = t->prev) {
- block = t->fallthrough_;
- }
- break;
- }
- }
- if (block != nullptr) {
- ir_emit_defer_stmts(proc, irDeferExit_Branch, block);
- }
- switch (bs->token.kind) {
- case Token_break: ir_emit_comment(proc, str_lit("break")); break;
- case Token_continue: ir_emit_comment(proc, str_lit("continue")); break;
- case Token_fallthrough: ir_emit_comment(proc, str_lit("fallthrough")); break;
- }
- ir_emit_jump(proc, block);
- ir_emit_unreachable(proc);
- case_end;
- case_ast_node(pa, PushAllocator, node);
- ir_emit_comment(proc, str_lit("push_allocator"));
- irValue *new_allocator = ir_build_expr(proc, pa->expr);
- ir_open_scope(proc);
- irValue *prev = ir_find_or_generate_context_ptr(proc);
- irValue *next = ir_add_local_generated(proc, t_context);
- ir_emit_store(proc, next, ir_emit_load(proc, prev));
- Selection sel = lookup_field(proc->module->allocator, t_context, str_lit("allocator"), false);
- irValue *gep = ir_emit_deep_field_gep(proc, next, sel);
- ir_emit_store(proc, gep, new_allocator);
- array_add(&proc->context_stack, next);
- defer (array_pop(&proc->context_stack));
- // TODO(bill): is this too leaky?
- ir_build_stmt(proc, pa->body);
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- case_end;
- case_ast_node(pc, PushContext, node);
- ir_emit_comment(proc, str_lit("push_context"));
- irValue *new_context = ir_build_expr(proc, pc->expr);
- ir_open_scope(proc);
- irValue *prev = ir_find_or_generate_context_ptr(proc);
- irValue *next = ir_add_local_generated(proc, t_context);
- ir_emit_store(proc, next, new_context);
- array_add(&proc->context_stack, next);
- defer (array_pop(&proc->context_stack));
- ir_build_stmt(proc, pc->body);
- ir_close_scope(proc, irDeferExit_Default, nullptr);
- case_end;
- }
- }
- ////////////////////////////////////////////////////////////////
- //
- // @Procedure
- //
- ////////////////////////////////////////////////////////////////
- void ir_number_proc_registers(irProcedure *proc) {
- i32 reg_index = 0;
- for_array(i, proc->blocks) {
- irBlock *b = proc->blocks[i];
- b->index = cast(i32)i;
- for_array(j, b->instrs) {
- irValue *value = b->instrs[j];
- GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name));
- irInstr *instr = &value->Instr;
- if (ir_instr_type(instr) == nullptr) { // NOTE(bill): Ignore non-returning instructions
- value->index = -1;
- continue;
- }
- value->index = reg_index;
- value->index_set = true;
- reg_index++;
- }
- }
- }
- void ir_begin_procedure_body(irProcedure *proc) {
- gbAllocator a = proc->module->allocator;
- array_add(&proc->module->procs, proc);
- array_init(&proc->blocks, heap_allocator());
- array_init(&proc->defer_stmts, heap_allocator());
- array_init(&proc->children, heap_allocator());
- array_init(&proc->branch_blocks, heap_allocator());
- array_init(&proc->context_stack, heap_allocator());
- DeclInfo *decl = decl_info_of_entity(proc->module->info, proc->entity);
- if (decl != nullptr) {
- for_array(i, decl->labels) {
- BlockLabel bl = decl->labels[i];
- irBranchBlocks bb = {bl.label, nullptr, nullptr};
- array_add(&proc->branch_blocks, bb);
- }
- }
- proc->decl_block = ir_new_block(proc, proc->type_expr, "decls");
- ir_start_block(proc, proc->decl_block);
- proc->entry_block = ir_new_block(proc, proc->type_expr, "entry");
- ir_start_block(proc, proc->entry_block);
- if (proc->type->Proc.return_by_pointer) {
- // NOTE(bill): this must be the first parameter stored
- Type *ptr_type = make_type_pointer(a, reduce_tuple_to_single_type(proc->type->Proc.results));
- Entity *e = make_entity_param(a, nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
- e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
- irValue *param = ir_value_param(a, proc, e, ptr_type);
- param->Param.kind = irParamPass_Pointer;
- ir_module_add_value(proc->module, e, param);
- proc->return_ptr = param;
- }
- GB_ASSERT(proc->type != nullptr);
- if (proc->type->Proc.params != nullptr) {
- TypeTuple *params = &proc->type->Proc.params->Tuple;
- if (proc->type_expr != nullptr) {
- ast_node(pt, ProcType, proc->type_expr);
- isize param_index = 0;
- isize q_index = 0;
- for_array(i, params->variables) {
- ast_node(fl, FieldList, pt->params);
- GB_ASSERT(fl->list.count > 0);
- GB_ASSERT(fl->list[0]->kind == AstNode_Field);
- if (q_index == fl->list[param_index]->Field.names.count) {
- q_index = 0;
- param_index++;
- }
- ast_node(field, Field, fl->list[param_index]);
- AstNode *name = field->names[q_index++];
- Entity *e = params->variables[i];
- if (e->kind != Entity_Variable) {
- continue;
- }
- Type *abi_type = proc->type->Proc.abi_compat_params[i];
- if (e->token.string != "" && !is_blank_ident(e->token)) {
- irValue *param = ir_add_param(proc, e, name, abi_type);
- array_add(&proc->params, param);
- }
- }
- } else {
- Type **abi_types = proc->type->Proc.abi_compat_params;
- for_array(i, params->variables) {
- Entity *e = params->variables[i];
- if (e->kind != Entity_Variable) {
- continue;
- }
- Type *abi_type = e->type;
- if (abi_types != nullptr) {
- abi_type = proc->type->Proc.abi_compat_params[i];
- }
- if (e->token.string != "" && !is_blank_ident(e->token)) {
- irValue *param = ir_add_param(proc, e, nullptr, abi_type);
- array_add(&proc->params, param);
- }
- }
- }
- }
- if (proc->type->Proc.calling_convention == ProcCC_Odin) {
- Entity *e = make_entity_param(a, nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
- e->flags |= EntityFlag_NoAlias;
- irValue *param = ir_value_param(a, proc, e, e->type);
- ir_module_add_value(proc->module, e, param);
- array_add(&proc->context_stack, param);
- }
- }
- void ir_end_procedure_body(irProcedure *proc) {
- if (proc->type->Proc.result_count == 0) {
- ir_emit_return(proc, nullptr);
- }
- if (proc->curr_block->instrs.count == 0) {
- ir_emit_unreachable(proc);
- }
- proc->curr_block = proc->decl_block;
- ir_emit_jump(proc, proc->entry_block);
- proc->curr_block = nullptr;
- ir_number_proc_registers(proc);
- }
- void ir_insert_code_before_proc(irProcedure* proc, irProcedure *parent) {
- // if (parent == nullptr) {
- // if (proc->name == "main") {
- // ir_emit_startup_runtime(proc);
- // }
- // }
- }
- void ir_build_proc(irValue *value, irProcedure *parent) {
- irProcedure *proc = &value->Proc;
- proc->parent = parent;
- if (proc->entity != nullptr) {
- irModule *m = proc->module;
- CheckerInfo *info = m->info;
- Entity *e = proc->entity;
- String filename = e->token.pos.file;
- AstFile *f = ast_file_of_filename(info, filename);
- proc->is_export = e->Procedure.is_export;
- proc->is_foreign = e->Procedure.is_foreign;
- irDebugInfo *di_file = nullptr;
- irDebugInfo **di_file_found = map_get(&m->debug_info, hash_ast_file(f));
- if (di_file_found) {
- di_file = *di_file_found;
- GB_ASSERT(di_file->kind == irDebugInfo_File);
- } else {
- di_file = ir_add_debug_info_file(proc, f);
- }
- ir_add_debug_info_proc(proc, e, proc->name, di_file);
- }
- if (proc->body != nullptr) {
- u64 prev_stmt_state_flags = proc->module->stmt_state_flags;
- if (proc->tags != 0) {
- u64 in = proc->tags;
- u64 out = proc->module->stmt_state_flags;
- if (in & ProcTag_bounds_check) {
- out |= StmtStateFlag_bounds_check;
- out &= ~StmtStateFlag_no_bounds_check;
- } else if (in & ProcTag_no_bounds_check) {
- out |= StmtStateFlag_no_bounds_check;
- out &= ~StmtStateFlag_bounds_check;
- }
- proc->module->stmt_state_flags = out;
- }
- ir_begin_procedure_body(proc);
- ir_insert_code_before_proc(proc, parent);
- ir_build_stmt(proc, proc->body);
- ir_end_procedure_body(proc);
- proc->module->stmt_state_flags = prev_stmt_state_flags;
- }
- if (proc->type->Proc.has_proc_default_values) {
- auto *p = &proc->type->Proc;
- for_array(i, p->params->Tuple.variables) {
- Entity *f = p->params->Tuple.variables[i];
- if (f->kind == Entity_Variable) {
- if (f->Variable.default_value.kind == ExactValue_Procedure) {
- AstNode *expr = f->Variable.default_value.value_procedure;
- GB_ASSERT(expr != nullptr);
- if (expr->kind == AstNode_ProcLit) {
- ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
- }
- } else {
- ir_check_type_and_gen_for_proc_lit(proc, f->type);
- }
- }
- }
- }
- }
- ////////////////////////////////////////////////////////////////
- //
- // @Module
- //
- ////////////////////////////////////////////////////////////////
- void ir_module_add_value(irModule *m, Entity *e, irValue *v) {
- map_set(&m->values, hash_entity(e), v);
- }
- void ir_init_module(irModule *m, Checker *c) {
- // TODO(bill): Determine a decent size for the arena
- isize token_count = c->parser->total_token_count;
- isize arena_size = 4 * token_count * gb_size_of(irValue);
- gb_arena_init_from_allocator(&m->arena, heap_allocator(), arena_size);
- gb_arena_init_from_allocator(&m->tmp_arena, heap_allocator(), arena_size);
- // m->allocator = gb_arena_allocator(&m->arena);
- m->allocator = heap_allocator();
- m->tmp_allocator = gb_arena_allocator(&m->tmp_arena);
- m->info = &c->info;
- map_init(&m->values, heap_allocator());
- map_init(&m->members, heap_allocator());
- map_init(&m->debug_info, heap_allocator());
- map_init(&m->entity_names, heap_allocator());
- map_init(&m->anonymous_proc_lits, heap_allocator());
- array_init(&m->procs, heap_allocator());
- array_init(&m->procs_to_generate, heap_allocator());
- array_init(&m->foreign_library_paths, heap_allocator());
- map_init(&m->const_strings, heap_allocator());
- // Default states
- m->stmt_state_flags = 0;
- m->stmt_state_flags |= StmtStateFlag_bounds_check;
- {
- // Add type info data
- {
- isize max_index = -1;
- for_array(type_info_map_index, m->info->type_info_map.entries) {
- auto *entry = &m->info->type_info_map.entries[type_info_map_index];
- Type *t = cast(Type *)entry->key.ptr;
- t = default_type(t);
- isize entry_index = type_info_index(m->info, t);
- if (max_index < entry_index) {
- max_index = entry_index;
- }
- }
- isize max_type_info_count = max_index+1;
- String name = str_lit(IR_TYPE_INFO_DATA_NAME);
- Entity *e = make_entity_variable(m->allocator, nullptr, make_token_ident(name), make_type_array(m->allocator, t_type_info, max_type_info_count), false);
- irValue *g = ir_value_global(m->allocator, e, nullptr);
- g->Global.is_private = true;
- ir_module_add_value(m, e, g);
- map_set(&m->members, hash_string(name), g);
- ir_global_type_info_data = g;
- }
- // Type info member buffer
- {
- // NOTE(bill): Removes need for heap allocation by making it global memory
- isize count = 0;
- for_array(entry_index, m->info->type_info_map.entries) {
- auto *entry = &m->info->type_info_map.entries[entry_index];
- Type *t = cast(Type *)entry->key.ptr;
- switch (t->kind) {
- case Type_Union:
- count += t->Union.variants.count;
- break;
- case Type_Struct:
- count += t->Struct.fields.count;
- break;
- case Type_Tuple:
- count += t->Tuple.variables.count;
- break;
- }
- }
- {
- String name = str_lit(IR_TYPE_INFO_TYPES_NAME);
- Entity *e = make_entity_variable(m->allocator, nullptr, make_token_ident(name),
- make_type_array(m->allocator, t_type_info_ptr, count), false);
- irValue *g = ir_value_global(m->allocator, e, nullptr);
- ir_module_add_value(m, e, g);
- map_set(&m->members, hash_string(name), g);
- ir_global_type_info_member_types = g;
- }
- {
- String name = str_lit(IR_TYPE_INFO_NAMES_NAME);
- Entity *e = make_entity_variable(m->allocator, nullptr, make_token_ident(name),
- make_type_array(m->allocator, t_string, count), false);
- irValue *g = ir_value_global(m->allocator, e, nullptr);
- ir_module_add_value(m, e, g);
- map_set(&m->members, hash_string(name), g);
- ir_global_type_info_member_names = g;
- }
- {
- String name = str_lit(IR_TYPE_INFO_OFFSETS_NAME);
- Entity *e = make_entity_variable(m->allocator, nullptr, make_token_ident(name),
- make_type_array(m->allocator, t_int, count), false);
- irValue *g = ir_value_global(m->allocator, e, nullptr);
- ir_module_add_value(m, e, g);
- map_set(&m->members, hash_string(name), g);
- ir_global_type_info_member_offsets = g;
- }
- {
- String name = str_lit(IR_TYPE_INFO_USINGS_NAME);
- Entity *e = make_entity_variable(m->allocator, nullptr, make_token_ident(name),
- make_type_array(m->allocator, t_bool, count), false);
- irValue *g = ir_value_global(m->allocator, e, nullptr);
- ir_module_add_value(m, e, g);
- map_set(&m->members, hash_string(name), g);
- ir_global_type_info_member_usings = g;
- }
- }
- }
- {
- irDebugInfo *di = ir_alloc_debug_info(m->allocator, irDebugInfo_CompileUnit);
- di->CompileUnit.file = m->info->files.entries[0].value; // Zeroth is the init file
- di->CompileUnit.producer = str_lit("odin");
- map_set(&m->debug_info, hash_pointer(m), di);
- }
- }
- void ir_destroy_module(irModule *m) {
- map_destroy(&m->values);
- map_destroy(&m->members);
- map_destroy(&m->entity_names);
- map_destroy(&m->anonymous_proc_lits);
- map_destroy(&m->debug_info);
- map_destroy(&m->const_strings);
- array_free(&m->procs);
- array_free(&m->procs_to_generate);
- array_free(&m->foreign_library_paths);
- gb_arena_free(&m->arena);
- }
- ////////////////////////////////////////////////////////////////
- //
- // @Code Generation
- //
- ////////////////////////////////////////////////////////////////
- bool ir_gen_init(irGen *s, Checker *c) {
- if (global_error_collector.count != 0) {
- return false;
- }
- isize tc = c->parser->total_token_count;
- if (tc < 2) {
- return false;
- }
- ir_init_module(&s->module, c);
- // s->module.generate_debug_info = false;
- String init_fullpath = c->parser->init_fullpath;
- // TODO(bill): generate appropriate output name
- int pos = cast(int)string_extension_position(init_fullpath);
- int dir_pos = cast(int)string_extension_position(init_fullpath);
- s->output_name = filename_from_path(init_fullpath);
- s->output_base = make_string(init_fullpath.text, pos);
- gbFileError err = gb_file_create(&s->output_file, gb_bprintf("%.*s.ll", pos, init_fullpath.text));
- if (err != gbFileError_None) {
- return false;
- }
- return true;
- }
- void ir_gen_destroy(irGen *s) {
- ir_destroy_module(&s->module);
- gb_file_close(&s->output_file);
- }
- //
- // Type Info stuff
- //
- irValue *ir_get_type_info_ptr(irProcedure *proc, Type *type) {
- i32 index = cast(i32)type_info_index(proc->module->info, type);
- // gb_printf_err("%d %s\n", index, type_to_string(type));
- irValue *ptr = ir_emit_array_epi(proc, ir_global_type_info_data, index);
- return ir_emit_bitcast(proc, ptr, t_type_info_ptr);
- }
- irValue *ir_type_info_member_types_offset(irProcedure *proc, isize count) {
- irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_types, ir_global_type_info_member_types_index);
- ir_global_type_info_member_types_index += cast(i32)count;
- return offset;
- }
- irValue *ir_type_info_member_names_offset(irProcedure *proc, isize count) {
- irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_names, ir_global_type_info_member_names_index);
- ir_global_type_info_member_names_index += cast(i32)count;
- return offset;
- }
- irValue *ir_type_info_member_offsets_offset(irProcedure *proc, isize count) {
- irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_offsets, ir_global_type_info_member_offsets_index);
- ir_global_type_info_member_offsets_index += cast(i32)count;
- return offset;
- }
- irValue *ir_type_info_member_usings_offset(irProcedure *proc, isize count) {
- irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_usings, ir_global_type_info_member_usings_index);
- ir_global_type_info_member_usings_index += cast(i32)count;
- return offset;
- }
- void ir_add_foreign_library_path(irModule *m, Entity *e) {
- GB_ASSERT(e != nullptr);
- String library_path = e->LibraryName.path;
- if (library_path.len == 0) {
- return;
- }
- for_array(path_index, m->foreign_library_paths) {
- String path = m->foreign_library_paths[path_index];
- #if defined(GB_SYSTEM_WINDOWS)
- if (str_eq_ignore_case(path, library_path)) {
- #else
- if (str_eq(path, library_path)) {
- #endif
- return;
- }
- }
- array_add(&m->foreign_library_paths, library_path);
- }
- void ir_setup_type_info_data(irProcedure *proc) { // NOTE(bill): Setup type_info data
- irModule *m = proc->module;
- gbAllocator a = m->allocator;
- CheckerInfo *info = m->info;
- if (true) {
- irValue *global_type_table = ir_find_global_variable(proc, str_lit("__type_table"));
- Type *type = base_type(type_deref(ir_type(ir_global_type_info_data)));
- GB_ASSERT(is_type_array(type));
- irValue *len = ir_const_int(proc->module->allocator, type->Array.count);
- ir_fill_slice(proc, global_type_table,
- ir_emit_array_epi(proc, ir_global_type_info_data, 0),
- len, len);
- }
- // Useful types
- Type *t_i64_slice_ptr = make_type_pointer(a, make_type_slice(a, t_i64));
- Type *t_string_slice_ptr = make_type_pointer(a, make_type_slice(a, t_string));
- i32 type_info_member_types_index = 0;
- i32 type_info_member_names_index = 0;
- i32 type_info_member_offsets_index = 0;
- for_array(type_info_map_index, info->type_info_map.entries) {
- auto *entry = &info->type_info_map.entries[type_info_map_index];
- Type *t = cast(Type *)entry->key.ptr;
- t = default_type(t);
- if (t == t_invalid) {
- continue;
- }
- isize entry_index = type_info_index(info, t);
- irValue *tag = nullptr;
- irValue *ti_ptr = ir_emit_array_epi(proc, ir_global_type_info_data, cast(i32)entry_index);
- irValue *variant_ptr = ir_emit_struct_ep(proc, ti_ptr, 2);
- ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 0), ir_const_int(a, type_size_of(a, t)));
- ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 1), ir_const_int(a, type_align_of(a, t)));
- switch (t->kind) {
- case Type_Named: {
- ir_emit_comment(proc, str_lit("TypeInfoNamed"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_named_ptr);
- // TODO(bill): Which is better? The mangled name or actual name?
- irValue *name = ir_const_string(a, t->Named.type_name->token.string);
- irValue *gtip = ir_get_type_info_ptr(proc, t->Named.base);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), name);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), gtip);
- break;
- }
- case Type_Basic:
- ir_emit_comment(proc, str_lit("TypeInfoBasic"));
- switch (t->Basic.kind) {
- case Basic_bool:
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_boolean_ptr);
- break;
- case Basic_i8:
- case Basic_u8:
- case Basic_i16:
- case Basic_u16:
- case Basic_i32:
- case Basic_u32:
- case Basic_i64:
- case Basic_u64:
- case Basic_i128:
- case Basic_u128:
- case Basic_int:
- case Basic_uint:
- case Basic_uintptr: {
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_integer_ptr);
- irValue *is_signed = ir_const_bool(a, (t->Basic.flags & BasicFlag_Unsigned) == 0);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), is_signed);
- break;
- }
- case Basic_rune:
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_rune_ptr);
- break;
- // case Basic_f16:
- case Basic_f32:
- case Basic_f64:
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_float_ptr);
- break;
- // case Basic_complex32:
- case Basic_complex64:
- case Basic_complex128:
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_complex_ptr);
- break;
- case Basic_rawptr:
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
- break;
- case Basic_string:
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_string_ptr);
- break;
- case Basic_any:
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_any_ptr);
- break;
- }
- break;
- case Type_Pointer: {
- ir_emit_comment(proc, str_lit("TypeInfoPointer"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
- irValue *gep = ir_get_type_info_ptr(proc, t->Pointer.elem);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
- break;
- }
- case Type_Array: {
- ir_emit_comment(proc, str_lit("TypeInfoArray"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_array_ptr);
- irValue *gep = ir_get_type_info_ptr(proc, t->Array.elem);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
- isize ez = type_size_of(a, t->Array.elem);
- irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
- ir_emit_store(proc, elem_size, ir_const_int(a, ez));
- irValue *count = ir_emit_struct_ep(proc, tag, 2);
- ir_emit_store(proc, count, ir_const_int(a, t->Array.count));
- break;
- }
- case Type_DynamicArray: {
- ir_emit_comment(proc, str_lit("TypeInfoDynamicArray"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_dynamic_array_ptr);
- irValue *gep = ir_get_type_info_ptr(proc, t->DynamicArray.elem);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
- isize ez = type_size_of(a, t->DynamicArray.elem);
- irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
- ir_emit_store(proc, elem_size, ir_const_int(a, ez));
- break;
- }
- case Type_Slice: {
- ir_emit_comment(proc, str_lit("TypeInfoSlice"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_slice_ptr);
- irValue *gep = ir_get_type_info_ptr(proc, t->Slice.elem);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
- isize ez = type_size_of(a, t->Slice.elem);
- irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
- ir_emit_store(proc, elem_size, ir_const_int(a, ez));
- break;
- }
- case Type_Vector: {
- ir_emit_comment(proc, str_lit("TypeInfoVector"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_vector_ptr);
- irValue *gep = ir_get_type_info_ptr(proc, t->Vector.elem);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
- isize ez = type_size_of(a, t->Vector.elem);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), ir_const_int(a, ez));
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), ir_const_int(a, t->Vector.count));
- break;
- }
- case Type_Proc: {
- ir_emit_comment(proc, str_lit("TypeInfoProc"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_procedure_ptr);
- irValue *params = ir_emit_struct_ep(proc, tag, 0);
- irValue *results = ir_emit_struct_ep(proc, tag, 1);
- irValue *variadic = ir_emit_struct_ep(proc, tag, 2);
- irValue *convention = ir_emit_struct_ep(proc, tag, 3);
- if (t->Proc.params != nullptr) {
- ir_emit_store(proc, params, ir_get_type_info_ptr(proc, t->Proc.params));
- }
- if (t->Proc.results != nullptr) {
- ir_emit_store(proc, results, ir_get_type_info_ptr(proc, t->Proc.results));
- }
- ir_emit_store(proc, variadic, ir_const_bool(a, t->Proc.variadic));
- ir_emit_store(proc, convention, ir_const_int(a, t->Proc.calling_convention));
- // TODO(bill): TypeInfo for procedures
- break;
- }
- case Type_Tuple: {
- ir_emit_comment(proc, str_lit("TypeInfoTuple"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_tuple_ptr);
- irValue *memory_types = ir_type_info_member_types_offset(proc, t->Tuple.variables.count);
- irValue *memory_names = ir_type_info_member_names_offset(proc, t->Tuple.variables.count);
- for_array(i, t->Tuple.variables) {
- // NOTE(bill): offset is not used for tuples
- Entity *f = t->Tuple.variables[i];
- irValue *index = ir_const_int(a, i);
- irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
- ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
- if (f->token.string.len > 0) {
- irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
- ir_emit_store(proc, name, ir_const_string(a, f->token.string));
- }
- }
- irValue *count = ir_const_int(a, t->Tuple.variables.count);
- ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, count, count);
- ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, count, count);
- break;
- }
- case Type_Enum:
- ir_emit_comment(proc, str_lit("TypeInfoEnum"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_enum_ptr);
- {
- GB_ASSERT(t->Enum.base_type != nullptr);
- irValue *base = ir_type_info(proc, t->Enum.base_type);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), base);
- if (t->Enum.field_count > 0) {
- Entity **fields = t->Enum.fields;
- isize count = t->Enum.field_count;
- irValue *name_array = ir_generate_array(m, t_string, count,
- str_lit("__$enum_names"), cast(i64)entry_index);
- irValue *value_array = ir_generate_array(m, t_type_info_enum_value, count,
- str_lit("__$enum_values"), cast(i64)entry_index);
- bool is_value_int = is_type_integer(t->Enum.base_type);
- if (!is_value_int) {
- GB_ASSERT(is_type_float(t->Enum.base_type));
- }
- for (isize i = 0; i < count; i++) {
- irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
- irValue *value_ep = ir_emit_array_epi(proc, value_array, cast(i32)i);
- ExactValue value = fields[i]->Constant.value;
- irValue *v = ir_value_constant(a, t->Enum.base_type, value);
- ir_emit_store(proc, value_ep, ir_emit_conv(proc, v, t_type_info_enum_value));
- ir_emit_store(proc, name_ep, ir_const_string(a, fields[i]->token.string));
- }
- irValue *v_count = ir_const_int(a, count);
- irValue *names = ir_emit_struct_ep(proc, tag, 1);
- irValue *name_array_elem = ir_array_elem(proc, name_array);
- ir_fill_slice(proc, names, name_array_elem, v_count, v_count);
- irValue *values = ir_emit_struct_ep(proc, tag, 2);
- irValue *value_array_elem = ir_array_elem(proc, value_array);
- ir_fill_slice(proc, values, value_array_elem, v_count, v_count);
- }
- }
- break;
- case Type_Union: {
- ir_emit_comment(proc, str_lit("TypeInfoUnion"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_union_ptr);
- {
- irValue *variant_types = ir_emit_struct_ep(proc, tag, 0);
- irValue *tag_offset_ptr = ir_emit_struct_ep(proc, tag, 1);
- irValue *tag_type_ptr = ir_emit_struct_ep(proc, tag, 2);
- isize variant_count = gb_max(0, t->Union.variants.count);
- irValue *memory_types = ir_type_info_member_types_offset(proc, variant_count);
- // NOTE(bill): Zeroth is nil so ignore it
- for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
- Type *vt = t->Union.variants[variant_index];
- irValue *tip = ir_get_type_info_ptr(proc, vt);
- irValue *index = ir_const_int(a, variant_index);
- irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
- ir_emit_store(proc, type_info, ir_type_info(proc, vt));
- }
- irValue *count = ir_const_int(a, variant_count);
- ir_fill_slice(proc, variant_types, memory_types, count, count);
- i64 tag_size = union_tag_size(t);
- i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
- ir_emit_store(proc, tag_offset_ptr, ir_const_int(a, tag_offset));
- ir_emit_store(proc, tag_type_ptr, ir_type_info(proc, union_tag_type(t)));
- }
- break;
- }
- case Type_Struct: {
- ir_emit_comment(proc, str_lit("TypeInfoStruct"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_struct_ptr);
- {
- irValue *is_packed = ir_const_bool(a, t->Struct.is_packed);
- irValue *is_ordered = ir_const_bool(a, t->Struct.is_ordered);
- irValue *is_raw_union = ir_const_bool(a, t->Struct.is_raw_union);
- irValue *is_custom_align = ir_const_bool(a, t->Struct.custom_align != 0);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 4), is_packed);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 5), is_ordered);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 6), is_raw_union);
- ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 7), is_custom_align);
- }
- isize count = t->Struct.fields.count;
- irValue *memory_types = ir_type_info_member_types_offset (proc, count);
- irValue *memory_names = ir_type_info_member_names_offset (proc, count);
- irValue *memory_offsets = ir_type_info_member_offsets_offset(proc, count);
- irValue *memory_usings = ir_type_info_member_usings_offset (proc, count);
- type_set_offsets(a, t); // NOTE(bill): Just incase the offsets have not been set yet
- for (isize source_index = 0; source_index < count; source_index++) {
- // TODO(bill): Order fields in source order not layout order
- Entity *f = t->Struct.fields_in_src_order[source_index];
- irValue *tip = ir_get_type_info_ptr(proc, f->type);
- i64 foffset = 0;
- if (!t->Struct.is_raw_union) {
- foffset = t->Struct.offsets[f->Variable.field_index];
- }
- GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
- irValue *index = ir_const_int(a, source_index);
- irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
- irValue *offset = ir_emit_ptr_offset(proc, memory_offsets, index);
- irValue *is_using = ir_emit_ptr_offset(proc, memory_usings, index);
- ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
- if (f->token.string.len > 0) {
- irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
- ir_emit_store(proc, name, ir_const_string(a, f->token.string));
- }
- ir_emit_store(proc, offset, ir_const_int(a, foffset));
- ir_emit_store(proc, is_using, ir_const_bool(a, (f->flags&EntityFlag_Using) != 0));
- }
- irValue *cv = ir_const_int(a, count);
- ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, cv, cv);
- ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, cv, cv);
- ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 2), memory_offsets, cv, cv);
- ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 3), memory_usings, cv, cv);
- break;
- }
- case Type_Map: {
- ir_emit_comment(proc, str_lit("TypeInfoMap"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_map_ptr);
- generate_map_internal_types(a, t);
- irValue *key = ir_emit_struct_ep(proc, tag, 0);
- irValue *value = ir_emit_struct_ep(proc, tag, 1);
- irValue *generated_struct = ir_emit_struct_ep(proc, tag, 2);
- ir_emit_store(proc, key, ir_get_type_info_ptr(proc, t->Map.key));
- ir_emit_store(proc, value, ir_get_type_info_ptr(proc, t->Map.value));
- ir_emit_store(proc, generated_struct, ir_get_type_info_ptr(proc, t->Map.generated_struct_type));
- break;
- }
- case Type_BitField: {
- ir_emit_comment(proc, str_lit("TypeInfoBitField"));
- tag = ir_emit_conv(proc, variant_ptr, t_type_info_bit_field_ptr);
- // names: []string;
- // bits: []u32;
- // offsets: []u32;
- isize count = t->BitField.field_count;
- if (count > 0) {
- Entity **fields = t->BitField.fields;
- irValue *name_array = ir_generate_array(m, t_string, count, str_lit("__$bit_field_names"), cast(i64)entry_index);
- irValue *bit_array = ir_generate_array(m, t_i32, count, str_lit("__$bit_field_bits"), cast(i64)entry_index);
- irValue *offset_array = ir_generate_array(m, t_i32, count, str_lit("__$bit_field_offsets"), cast(i64)entry_index);
- for (isize i = 0; i < count; i++) {
- Entity *f = fields[i];
- GB_ASSERT(f->type != nullptr);
- GB_ASSERT(f->type->kind == Type_BitFieldValue);
- irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
- irValue *bit_ep = ir_emit_array_epi(proc, bit_array, cast(i32)i);
- irValue *offset_ep = ir_emit_array_epi(proc, offset_array, cast(i32)i);
- ir_emit_store(proc, name_ep, ir_const_string(a, f->token.string));
- ir_emit_store(proc, bit_ep, ir_const_i32(a, f->type->BitFieldValue.bits));
- ir_emit_store(proc, offset_ep, ir_const_i32(a, t->BitField.offsets[i]));
- }
- irValue *v_count = ir_const_int(a, count);
- irValue *names = ir_emit_struct_ep(proc, tag, 0);
- irValue *name_array_elem = ir_array_elem(proc, name_array);
- ir_fill_slice(proc, names, name_array_elem, v_count, v_count);
- irValue *bits = ir_emit_struct_ep(proc, tag, 1);
- irValue *bit_array_elem = ir_array_elem(proc, bit_array);
- ir_fill_slice(proc, bits, bit_array_elem, v_count, v_count);
- irValue *offsets = ir_emit_struct_ep(proc, tag, 2);
- irValue *offset_array_elem = ir_array_elem(proc, offset_array);
- ir_fill_slice(proc, offsets, offset_array_elem, v_count, v_count);
- }
- break;
- }
- }
- if (tag != nullptr) {
- Type *tag_type = type_deref(ir_type(tag));
- GB_ASSERT(is_type_named(tag_type));
- Type *variant_type = type_deref(ir_type(variant_ptr));
- irValue *tag = ir_const_union_tag(a, variant_type, tag_type);
- irValue *ptr = ir_emit_union_tag_ptr(proc, variant_ptr);
- ir_emit_store(proc, ptr, tag);
- } else {
- GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
- }
- }
- }
- void ir_gen_tree(irGen *s) {
- irModule *m = &s->module;
- CheckerInfo *info = m->info;
- gbAllocator a = m->allocator;
- if (v_zero == nullptr) {
- v_zero = ir_const_int (m->allocator, 0);
- v_one = ir_const_int (m->allocator, 1);
- v_zero32 = ir_const_i32 (m->allocator, 0);
- v_one32 = ir_const_i32 (m->allocator, 1);
- v_two32 = ir_const_i32 (m->allocator, 2);
- v_false = ir_const_bool(m->allocator, false);
- v_true = ir_const_bool(m->allocator, true);
- v_raw_nil = ir_value_constant(m->allocator, t_rawptr, exact_value_pointer(0));
- }
- isize global_variable_max_count = 0;
- Entity *entry_point = info->entry_point;
- bool has_dll_main = false;
- bool has_win_main = false;
- for_array(i, info->entities.entries) {
- auto *entry = &info->entities.entries[i];
- Entity *e = cast(Entity *)entry->key.ptr;
- String name = e->token.string;
- if (e->kind == Entity_Variable) {
- global_variable_max_count++;
- } else if (e->kind == Entity_Procedure && !e->scope->is_global) {
- if (e->scope->is_init && name == "main") {
- GB_ASSERT(e == entry_point);
- // entry_point = e;
- }
- if (e->Procedure.is_export ||
- (e->Procedure.link_name.len > 0) ||
- (e->scope->is_file && e->Procedure.link_name.len > 0)) {
- if (!has_dll_main && name == "DllMain") {
- has_dll_main = true;
- } else if (!has_win_main && name == "WinMain") {
- has_win_main = true;
- }
- }
- }
- }
- { // Add global default context
- m->global_default_context = ir_add_global_generated(m, t_context, nullptr);
- }
- struct irGlobalVariable {
- irValue *var, *init;
- DeclInfo *decl;
- };
- Array<irGlobalVariable> global_variables;
- array_init(&global_variables, m->tmp_allocator, global_variable_max_count);
- m->entry_point_entity = entry_point;
- m->min_dep_set = info->minimum_dependency_set;
- for_array(i, info->variable_init_order) {
- DeclInfo *d = info->variable_init_order[i];
- for (isize j = 0; j < d->entity_count; j++) {
- Entity *e = d->entities[j];
- if (!e->scope->is_file) {
- continue;
- }
- if (!ptr_set_exists(&m->min_dep_set, e)) {
- continue;
- }
- DeclInfo *decl = decl_info_of_entity(info, e);
- if (decl == nullptr) {
- continue;
- }
- GB_ASSERT(e->kind == Entity_Variable);
- bool is_foreign = e->Variable.is_foreign;
- bool is_export = e->Variable.is_export;
- bool no_name_mangle = e->scope->is_global || e->Variable.link_name.len > 0 || is_foreign || is_export;
- String name = e->token.string;
- if (!no_name_mangle) {
- name = ir_mangle_name(s, e->token.pos.file, e);
- }
- ir_add_entity_name(m, e, name);
- irValue *g = ir_value_global(a, e, nullptr);
- g->Global.name = name;
- g->Global.thread_local_model = e->Variable.thread_local_model;
- g->Global.is_foreign = is_foreign;
- g->Global.is_export = is_export;
- irGlobalVariable var = {};
- var.var = g;
- var.decl = decl;
- if (e->type->kind == Type_Struct && e->type->Struct.has_proc_default_values) {
- for_array(i, e->type->Struct.fields) {
- Entity *f = e->type->Struct.fields[i];
- if (f->kind == Entity_Variable && f->Variable.default_value.kind == ExactValue_Procedure) {
- AstNode *expr = f->Variable.default_value.value_procedure;
- GB_ASSERT(expr != nullptr);
- if (expr->kind == AstNode_ProcLit) {
- ir_gen_anonymous_proc_lit(m, e->token.string, expr);
- }
- }
- }
- }
- if (decl->init_expr != nullptr) {
- if (is_type_any(e->type)) {
- } else {
- TypeAndValue tav = type_and_value_of_expr(info, decl->init_expr);
- if (tav.mode != Addressing_Invalid) {
- if (tav.value.kind != ExactValue_Invalid) {
- ExactValue v = tav.value;
- g->Global.value = ir_add_module_constant(m, tav.type, v);
- }
- }
- }
- }
- // if (g->Global.value == nullptr) {
- array_add(&global_variables, var);
- // }
- ir_module_add_value(m, e, g);
- map_set(&m->members, hash_string(name), g);
- }
- }
- for_array(i, info->entities.entries) {
- auto *entry = &info->entities.entries[i];
- Entity *e = cast(Entity *)entry->key.ptr;
- String name = e->token.string;
- DeclInfo *decl = entry->value;
- Scope *scope = e->scope;
- if (!scope->is_file) {
- continue;
- }
- if (e->kind == Entity_Variable) {
- // NOTE(bill): Handled above as it requires a specific load order
- continue;
- }
- bool polymorphic_struct = false;
- if (e->type != nullptr && e->kind == Entity_TypeName) {
- Type *bt = base_type(e->type);
- if (bt->kind == Type_Struct) {
- polymorphic_struct = is_type_polymorphic(bt);
- }
- }
- if (!polymorphic_struct && !ptr_set_exists(&m->min_dep_set, e)) {
- // NOTE(bill): Nothing depends upon it so doesn't need to be built
- continue;
- }
- String original_name = name;
- if (!scope->is_global || polymorphic_struct || is_type_polymorphic(e->type)) {
- if (e->kind == Entity_Procedure && e->Procedure.is_export) {
- } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
- // Handle later
- } else {
- name = ir_mangle_name(s, e->token.pos.file, e);
- }
- } else if (check_is_entity_overloaded(e)) {
- name = ir_mangle_name(s, e->token.pos.file, e);
- }
- ir_add_entity_name(m, e, name);
- switch (e->kind) {
- case Entity_TypeName:
- ir_gen_global_type_name(m, e, name);
- break;
- case Entity_Procedure: {
- ast_node(pl, ProcLit, decl->proc_lit);
- String original_name = name;
- AstNode *body = pl->body;
- if (e->Procedure.is_foreign) {
- name = e->token.string; // NOTE(bill): Don't use the mangled name
- ir_add_foreign_library_path(m, e->Procedure.foreign_library);
- }
- if (e->Procedure.link_name.len > 0) {
- name = e->Procedure.link_name;
- }
- AstNode *type_expr = pl->type;
- irValue *p = ir_value_procedure(a, m, e, e->type, type_expr, body, name);
- p->Proc.tags = pl->tags;
- p->Proc.inlining = pl->inlining;
- ir_module_add_value(m, e, p);
- HashKey hash_name = hash_string(name);
- if (map_get(&m->members, hash_name) == nullptr) {
- multi_map_insert(&m->members, hash_name, p);
- }
- break;
- }
- }
- }
- for_array(i, m->members.entries) {
- auto *entry = &m->members.entries[i];
- irValue *v = entry->value;
- if (v->kind == irValue_Proc) {
- ir_build_proc(v, nullptr);
- }
- }
- irDebugInfo *compile_unit = m->debug_info.entries[0].value;
- GB_ASSERT(compile_unit->kind == irDebugInfo_CompileUnit);
- irDebugInfo *all_procs = ir_alloc_debug_info(m->allocator, irDebugInfo_AllProcs);
- isize all_proc_max_count = 0;
- for_array(i, m->debug_info.entries) {
- auto *entry = &m->debug_info.entries[i];
- irDebugInfo *di = entry->value;
- di->id = cast(i32)i;
- if (di->kind == irDebugInfo_Proc) {
- all_proc_max_count++;
- }
- }
- array_init(&all_procs->AllProcs.procs, m->allocator, all_proc_max_count);
- map_set(&m->debug_info, hash_pointer(all_procs), all_procs); // NOTE(bill): This doesn't need to be mapped
- compile_unit->CompileUnit.all_procs = all_procs;
- for_array(i, m->debug_info.entries) {
- auto *entry = &m->debug_info.entries[i];
- irDebugInfo *di = entry->value;
- if (di->kind == irDebugInfo_Proc) {
- array_add(&all_procs->AllProcs.procs, di);
- }
- }
- #if defined(GB_SYSTEM_WINDOWS)
- if (build_context.is_dll && !has_dll_main) {
- // DllMain :: proc(inst: rawptr, reason: u32, reserved: rawptr) -> i32
- String name = str_lit("DllMain");
- Type *proc_params = make_type_tuple(a);
- Type *proc_results = make_type_tuple(a);
- Scope *proc_scope = gb_alloc_item(a, Scope);
- array_init_count(&proc_params->Tuple.variables, a, 3);
- array_init_count(&proc_results->Tuple.variables, a, 1);
- proc_params->Tuple.variables[0] = make_entity_param(a, proc_scope, blank_token, t_rawptr, false, false);
- proc_params->Tuple.variables[1] = make_entity_param(a, proc_scope, make_token_ident(str_lit("reason")), t_i32, false, false);
- proc_params->Tuple.variables[2] = make_entity_param(a, proc_scope, blank_token, t_rawptr, false, false);
- proc_results->Tuple.variables[0] = make_entity_param(a, proc_scope, empty_token, t_i32, false, false);
- Type *proc_type = make_type_proc(a, proc_scope,
- proc_params, 3,
- proc_results, 1, false, ProcCC_StdCall);
- // TODO(bill): make this more robust
- proc_type->Proc.abi_compat_params = gb_alloc_array(a, Type *, proc_params->Tuple.variables.count);
- for_array(i, proc_params->Tuple.variables) {
- proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
- }
- proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
- AstNode *body = gb_alloc_item(a, AstNode);
- Entity *e = make_entity_procedure(a, nullptr, make_token_ident(name), proc_type, 0);
- irValue *p = ir_value_procedure(a, m, e, proc_type, nullptr, body, name);
- map_set(&m->values, hash_entity(e), p);
- map_set(&m->members, hash_string(name), p);
- irProcedure *proc = &p->Proc;
- proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
- proc->is_entry_point = true;
- e->Procedure.link_name = name;
- ir_begin_procedure_body(proc);
- // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
- // DLL_PROCESS_ATTACH == 1
- irAddr reason_addr = ir_build_addr_from_entity(proc, proc_params->Tuple.variables[1], nullptr);
- irValue *cond = ir_emit_comp(proc, Token_CmpEq, ir_addr_load(proc, reason_addr), v_one32);
- irBlock *then = ir_new_block(proc, nullptr, "if.then");
- irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
- ir_emit_if(proc, cond, then, done);
- ir_start_block(proc, then);
- {
- irValue **found = map_get(&m->values, hash_entity(entry_point));
- ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
- if (found != nullptr) {
- ir_emit_call(proc, *found, nullptr, 0);
- }
- }
- ir_emit_jump(proc, done);
- ir_start_block(proc, done);
- ir_emit_return(proc, v_one32);
- ir_end_procedure_body(proc);
- }
- #endif
- if (!(build_context.is_dll && !has_dll_main)) {
- // main :: proc(argc: i32, argv: ^^u8) -> i32
- String name = str_lit("main");
- Type *proc_params = make_type_tuple(a);
- Type *proc_results = make_type_tuple(a);
- Scope *proc_scope = gb_alloc_item(a, Scope);
- array_init_count(&proc_params->Tuple.variables, a, 2);
- array_init_count(&proc_results->Tuple.variables, a, 1);
- Type *char_ptr_ptr = make_type_pointer(a, make_type_pointer(a, t_u8));
- proc_params->Tuple.variables[0] = make_entity_param(a, proc_scope, make_token_ident(str_lit("argc")), t_i32, false, false);
- proc_params->Tuple.variables[1] = make_entity_param(a, proc_scope, make_token_ident(str_lit("argv")), char_ptr_ptr, false, false);
- proc_results->Tuple.variables[0] = make_entity_param(a, proc_scope, empty_token, t_i32, false, false);
- Type *proc_type = make_type_proc(a, proc_scope,
- proc_params, 2,
- proc_results, 1, false, ProcCC_CDecl);
- // TODO(bill): make this more robust
- proc_type->Proc.abi_compat_params = gb_alloc_array(a, Type *, proc_params->Tuple.variables.count);
- for_array(i, proc_params->Tuple.variables) {
- proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
- }
- proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
- AstNode *body = gb_alloc_item(a, AstNode);
- Entity *e = make_entity_procedure(a, nullptr, make_token_ident(name), proc_type, 0);
- irValue *p = ir_value_procedure(a, m, e, proc_type, nullptr, body, name);
- map_set(&m->values, hash_entity(e), p);
- map_set(&m->members, hash_string(name), p);
- irProcedure *proc = &p->Proc;
- proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
- proc->is_entry_point = true;
- e->Procedure.link_name = name;
- ir_begin_procedure_body(proc);
- // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
- // DLL_PROCESS_ATTACH == 1
- irValue *argc = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[0])));
- irValue *argv = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[1])));
- irValue *global_argc = ir_find_global_variable(proc, str_lit("__argc__"));
- irValue *global_argv = ir_find_global_variable(proc, str_lit("__argv__"));
- ir_emit_store(proc, global_argc, argc);
- ir_emit_store(proc, global_argv, argv);
- ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
- {
- irValue **found = map_get(&proc->module->values, hash_entity(entry_point));
- if (found != nullptr) {
- ir_emit_call(proc, *found, nullptr, 0);
- }
- }
- ir_emit_return(proc, v_zero32);
- ir_end_procedure_body(proc);
- }
- #if 0 && defined(GB_SYSTEM_WINDOWS)
- if (!m->build_context->is_dll && !has_win_main) {
- // proc WinMain(inst, prev: rawptr, cmd_line: ^byte, cmd_show: i32) -> i32
- String name = str_lit("WinMain");
- Type *proc_params = make_type_tuple(a);
- Type *proc_results = make_type_tuple(a);
- Scope *proc_scope = gb_alloc_item(a, Scope);
- proc_params->Tuple.variables = gb_alloc_array(a, Entity *, 4);
- proc_params->Tuple.variable_count = 4;
- proc_results->Tuple.variables = gb_alloc_array(a, Entity *, 1);
- proc_results->Tuple.variable_count = 1;
- proc_params->Tuple.variables[0] = make_entity_param(a, proc_scope, blank_token, t_rawptr, false);
- proc_params->Tuple.variables[1] = make_entity_param(a, proc_scope, blank_token, t_rawptr, false);
- proc_params->Tuple.variables[2] = make_entity_param(a, proc_scope, blank_token, t_u8_ptr, false);
- proc_params->Tuple.variables[3] = make_entity_param(a, proc_scope, blank_token, t_i32, false);
- proc_results->Tuple.variables[0] = make_entity_param(a, proc_scope, empty_token, t_i32, false);
- Type *proc_type = make_type_proc(a, proc_scope,
- proc_params, 4,
- proc_results, 1, false, ProcCC_Std);
- AstNode *body = gb_alloc_item(a, AstNode);
- Entity *e = make_entity_procedure(a, nullptr, make_token_ident(name), proc_type, 0);
- irValue *p = ir_value_procedure(a, m, e, proc_type, nullptr, body, name);
- m->entry_point_entity = e;
- map_set(&m->values, hash_entity(e), p);
- map_set(&m->members, hash_string(name), p);
- irProcedure *proc = &p->Proc;
- proc->tags = ProcTag_no_inline; // TODO(bill): is no_inline a good idea?
- e->Procedure.link_name = name;
- ir_begin_procedure_body(proc);
- ir_emit_global_call(proc, "main", nullptr, 0);
- ir_emit_return(proc, v_one32);
- ir_end_procedure_body(proc);
- }
- #endif
- { // Startup Runtime
- // Cleanup(bill): probably better way of doing code insertion
- String name = str_lit(IR_STARTUP_RUNTIME_PROC_NAME);
- Type *proc_type = make_type_proc(a, gb_alloc_item(a, Scope),
- nullptr, 0,
- nullptr, 0, false,
- ProcCC_Contextless);
- AstNode *body = gb_alloc_item(a, AstNode);
- Entity *e = make_entity_procedure(a, nullptr, make_token_ident(name), proc_type, 0);
- irValue *p = ir_value_procedure(a, m, e, proc_type, nullptr, body, name);
- map_set(&m->values, hash_entity(e), p);
- map_set(&m->members, hash_string(name), p);
- irProcedure *proc = &p->Proc;
- proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
- ir_begin_procedure_body(proc);
- {
- irValue **args = gb_alloc_array(a, irValue *, 1);
- args[0] = m->global_default_context;
- ir_emit_global_call(proc, "__init_context", args, 1);
- }
- ir_setup_type_info_data(proc);
- for_array(i, global_variables) {
- irGlobalVariable *var = &global_variables[i];
- if (var->decl->init_expr != nullptr) {
- var->init = ir_build_expr(proc, var->decl->init_expr);
- }
- if (var->init != nullptr) {
- Type *t = type_deref(ir_type(var->var));
- if (is_type_any(t)) {
- // NOTE(bill): Edge case for `any` type
- Type *var_type = default_type(ir_type(var->init));
- irValue *g = ir_add_global_generated(proc->module, var_type, var->init);
- ir_emit_store(proc, g, var->init);
- irValue *data = ir_emit_struct_ep(proc, var->var, 0);
- irValue *ti = ir_emit_struct_ep(proc, var->var, 1);
- ir_emit_store(proc, data, ir_emit_conv(proc, g, t_rawptr));
- ir_emit_store(proc, ti, ir_type_info(proc, var_type));
- } else {
- ir_emit_store(proc, var->var, ir_emit_conv(proc, var->init, t));
- }
- }
- }
- ir_end_procedure_body(proc);
- }
- for_array(type_info_map_index, info->type_info_map.entries) {
- auto *entry = &info->type_info_map.entries[type_info_map_index];
- Type *t = cast(Type *)entry->key.ptr;
- t = default_type(t);
- isize entry_index = entry->value;
- gbString s = type_to_string(t);
- GB_ASSERT(s[0] != 0);
- // gb_printf_err("%s\n", s);
- }
- for_array(i, m->procs_to_generate) {
- irValue *p = m->procs_to_generate[i];
- ir_build_proc(p, p->Proc.parent);
- }
- // Number debug info
- for_array(i, m->debug_info.entries) {
- auto *entry = &m->debug_info.entries[i];
- irDebugInfo *di = entry->value;
- di->id = cast(i32)i;
- }
- // m->layout = str_lit("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64");
- }
|