ir.cpp 264 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624
  1. struct irProcedure;
  2. struct irBlock;
  3. struct irValue;
  4. struct irDebugInfo;
  5. struct irModule {
  6. CheckerInfo * info;
  7. gbArena arena;
  8. gbArena tmp_arena;
  9. gbAllocator allocator;
  10. gbAllocator tmp_allocator;
  11. // bool generate_debug_info;
  12. u64 stmt_state_flags;
  13. // String source_filename;
  14. String layout;
  15. // String triple;
  16. PtrSet<Entity *> min_dep_set;
  17. Map<irValue *> values; // Key: Entity *
  18. Map<irValue *> members; // Key: String
  19. Map<String> entity_names; // Key: Entity * of the typename
  20. Map<irDebugInfo *> debug_info; // Key: Unique pointer
  21. Map<irValue *> anonymous_proc_lits; // Key: AstNode *
  22. i32 global_string_index;
  23. i32 global_array_index; // For ConstantSlice
  24. i32 global_generated_index;
  25. irValue * global_default_context;
  26. // NOTE(bill): To prevent strings from being copied a lot
  27. // Mainly used for file names
  28. Map<irValue *> const_strings; // Key: String
  29. Entity * entry_point_entity;
  30. Array<irProcedure *> procs; // NOTE(bill): All procedures with bodies
  31. Array<irValue *> procs_to_generate; // NOTE(bill): Procedures to generate
  32. Array<String> foreign_library_paths; // Only the ones that were used
  33. };
  34. // NOTE(bill): For more info, see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
  35. struct irDomNode {
  36. irBlock * idom; // Parent (Immediate Dominator)
  37. Array<irBlock *> children;
  38. i32 pre, post; // Ordering in tree
  39. };
  40. struct irBlock {
  41. i32 index;
  42. String label;
  43. irProcedure *parent;
  44. AstNode * node; // Can be nullptr
  45. Scope * scope;
  46. isize scope_index;
  47. irDomNode dom;
  48. i32 gaps;
  49. Array<irValue *> instrs;
  50. Array<irValue *> locals;
  51. Array<irBlock *> preds;
  52. Array<irBlock *> succs;
  53. };
  54. struct irTargetList {
  55. irTargetList *prev;
  56. irBlock * break_;
  57. irBlock * continue_;
  58. irBlock * fallthrough_;
  59. };
  60. enum irDeferExitKind {
  61. irDeferExit_Default,
  62. irDeferExit_Return,
  63. irDeferExit_Branch,
  64. };
  65. enum irDeferKind {
  66. irDefer_Node,
  67. irDefer_Instr,
  68. };
  69. struct irDefer {
  70. irDeferKind kind;
  71. isize scope_index;
  72. irBlock * block;
  73. union {
  74. AstNode *stmt;
  75. // NOTE(bill): `instr` will be copied every time to create a new one
  76. irValue *instr;
  77. };
  78. };
  79. struct irBranchBlocks {
  80. AstNode *label;
  81. irBlock *break_;
  82. irBlock *continue_;
  83. };
  84. struct irProcedure {
  85. irProcedure * parent;
  86. Array<irProcedure *> children;
  87. Entity * entity;
  88. irModule * module;
  89. String name;
  90. Type * type;
  91. AstNode * type_expr;
  92. AstNode * body;
  93. u64 tags;
  94. ProcInlining inlining;
  95. bool is_foreign;
  96. bool is_export;
  97. bool is_entry_point;
  98. irValue * return_ptr;
  99. Array<irValue *> params;
  100. Array<irDefer> defer_stmts;
  101. Array<irBlock *> blocks;
  102. i32 scope_index;
  103. irBlock * decl_block;
  104. irBlock * entry_block;
  105. irBlock * curr_block;
  106. irTargetList * target_list;
  107. Array<irValue *> referrers;
  108. Array<irValue *> context_stack;
  109. Array<irBranchBlocks> branch_blocks;
  110. i32 local_count;
  111. i32 instr_count;
  112. i32 block_count;
  113. };
  114. #define IR_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime"
  115. #define IR_TYPE_INFO_DATA_NAME "__$type_info_data"
  116. #define IR_TYPE_INFO_TYPES_NAME "__$type_info_types_data"
  117. #define IR_TYPE_INFO_NAMES_NAME "__$type_info_names_data"
  118. #define IR_TYPE_INFO_OFFSETS_NAME "__$type_info_offsets_data"
  119. #define IR_TYPE_INFO_USINGS_NAME "__$type_info_usings_data"
  120. #define IR_INSTR_KINDS \
  121. IR_INSTR_KIND(Comment, struct { String text; }) \
  122. IR_INSTR_KIND(Local, struct { \
  123. Entity * entity; \
  124. Type * type; \
  125. bool zero_initialized; \
  126. Array<irValue *> referrers; \
  127. i64 alignment; \
  128. }) \
  129. IR_INSTR_KIND(ZeroInit, struct { irValue *address; }) \
  130. IR_INSTR_KIND(Store, struct { \
  131. irValue *address, *value; bool atomic; \
  132. }) \
  133. IR_INSTR_KIND(Load, struct { Type *type; irValue *address; }) \
  134. IR_INSTR_KIND(PtrOffset, struct { \
  135. irValue *address; \
  136. irValue *offset; \
  137. }) \
  138. IR_INSTR_KIND(ArrayElementPtr, struct { \
  139. irValue *address; \
  140. Type * result_type; \
  141. irValue *elem_index; \
  142. }) \
  143. IR_INSTR_KIND(StructElementPtr, struct { \
  144. irValue *address; \
  145. Type * result_type; \
  146. i32 elem_index; \
  147. }) \
  148. IR_INSTR_KIND(StructExtractValue, struct { \
  149. irValue *address; \
  150. Type * result_type; \
  151. i32 index; \
  152. }) \
  153. IR_INSTR_KIND(UnionTagPtr, struct { \
  154. irValue *address; \
  155. Type *type; /* ^int */ \
  156. }) \
  157. IR_INSTR_KIND(UnionTagValue, struct { \
  158. irValue *address; \
  159. Type *type; /* int */ \
  160. }) \
  161. IR_INSTR_KIND(Conv, struct { \
  162. irConvKind kind; \
  163. irValue *value; \
  164. Type *from, *to; \
  165. }) \
  166. IR_INSTR_KIND(Jump, struct { irBlock *block; }) \
  167. IR_INSTR_KIND(If, struct { \
  168. irValue *cond; \
  169. irBlock *true_block; \
  170. irBlock *false_block; \
  171. }) \
  172. IR_INSTR_KIND(Return, struct { irValue *value; }) \
  173. IR_INSTR_KIND(Select, struct { \
  174. irValue *cond; \
  175. irValue *true_value; \
  176. irValue *false_value; \
  177. }) \
  178. IR_INSTR_KIND(Phi, struct { Array<irValue *> edges; Type *type; })\
  179. IR_INSTR_KIND(Unreachable, i32) \
  180. IR_INSTR_KIND(UnaryOp, struct { \
  181. Type * type; \
  182. TokenKind op; \
  183. irValue * expr; \
  184. }) \
  185. IR_INSTR_KIND(BinaryOp, struct { \
  186. Type * type; \
  187. TokenKind op; \
  188. irValue * left, *right; \
  189. }) \
  190. IR_INSTR_KIND(Call, struct { \
  191. Type * type; /* return type */ \
  192. irValue * value; \
  193. irValue * return_ptr; \
  194. irValue **args; \
  195. isize arg_count; \
  196. irValue * context_ptr; \
  197. }) \
  198. IR_INSTR_KIND(StartupRuntime, i32) \
  199. IR_INSTR_KIND(DebugDeclare, struct { \
  200. irDebugInfo *debug_info; \
  201. AstNode * expr; \
  202. Entity * entity; \
  203. bool is_addr; \
  204. irValue * value; \
  205. }) \
  206. // IR_INSTR_KIND(BoundsCheck, struct { \
  207. // TokenPos pos; \
  208. // irValue *index; \
  209. // irValue *len; \
  210. // }) \
  211. // IR_INSTR_KIND(SliceBoundsCheck, struct { \
  212. // TokenPos pos; \
  213. // irValue *low; \
  214. // irValue *high; \
  215. // irValue *max; \
  216. // bool is_substring; \
  217. // }) \
  218. #define IR_CONV_KINDS \
  219. IR_CONV_KIND(trunc) \
  220. IR_CONV_KIND(zext) \
  221. IR_CONV_KIND(sext) \
  222. IR_CONV_KIND(fptrunc) \
  223. IR_CONV_KIND(fpext) \
  224. IR_CONV_KIND(fptoui) \
  225. IR_CONV_KIND(fptosi) \
  226. IR_CONV_KIND(uitofp) \
  227. IR_CONV_KIND(sitofp) \
  228. IR_CONV_KIND(ptrtoint) \
  229. IR_CONV_KIND(inttoptr) \
  230. IR_CONV_KIND(bitcast)
  231. enum irInstrKind {
  232. irInstr_Invalid,
  233. #define IR_INSTR_KIND(x, ...) GB_JOIN2(irInstr_, x),
  234. IR_INSTR_KINDS
  235. #undef IR_INSTR_KIND
  236. };
  237. String const ir_instr_strings[] = {
  238. {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
  239. #define IR_INSTR_KIND(x, ...) {cast(u8 *)#x, gb_size_of(#x)-1},
  240. IR_INSTR_KINDS
  241. #undef IR_INSTR_KIND
  242. };
  243. enum irConvKind {
  244. irConv_Invalid,
  245. #define IR_CONV_KIND(x) GB_JOIN2(irConv_, x),
  246. IR_CONV_KINDS
  247. #undef IR_CONV_KIND
  248. };
  249. String const ir_conv_strings[] = {
  250. {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
  251. #define IR_CONV_KIND(x) {cast(u8 *)#x, gb_size_of(#x)-1},
  252. IR_CONV_KINDS
  253. #undef IR_CONV_KIND
  254. };
  255. #define IR_INSTR_KIND(k, ...) typedef __VA_ARGS__ GB_JOIN2(irInstr, k);
  256. IR_INSTR_KINDS
  257. #undef IR_INSTR_KIND
  258. struct irInstr {
  259. irInstrKind kind;
  260. irBlock *parent;
  261. Type *type;
  262. union {
  263. #define IR_INSTR_KIND(k, ...) GB_JOIN2(irInstr, k) k;
  264. IR_INSTR_KINDS
  265. #undef IR_INSTR_KIND
  266. };
  267. };
  268. enum irValueKind {
  269. irValue_Invalid,
  270. irValue_Constant,
  271. irValue_ConstantSlice,
  272. irValue_Nil,
  273. irValue_Undef,
  274. irValue_TypeName,
  275. irValue_Global,
  276. irValue_Param,
  277. irValue_Proc,
  278. irValue_Block,
  279. irValue_Instr,
  280. irValue_Count,
  281. };
  282. struct irValueConstant {
  283. Type * type;
  284. ExactValue value;
  285. };
  286. struct irValueConstantSlice {
  287. Type * type;
  288. irValue *backing_array;
  289. i64 count;
  290. };
  291. struct irValueNil {
  292. Type *type;
  293. };
  294. struct irValueUndef {
  295. Type *type;
  296. };
  297. struct irValueTypeName {
  298. Type * type;
  299. String name;
  300. };
  301. struct irValueGlobal {
  302. String name;
  303. Entity * entity;
  304. Type * type;
  305. irValue * value;
  306. Array<irValue *> referrers;
  307. bool is_constant;
  308. bool is_export;
  309. bool is_private;
  310. String thread_local_model;
  311. bool is_foreign;
  312. bool is_unnamed_addr;
  313. };
  314. enum irParamPasskind {
  315. irParamPass_Value, // Pass by value
  316. irParamPass_Pointer, // Pass as a pointer rather than by value
  317. irParamPass_Integer, // Pass as an integer of the same size
  318. };
  319. struct irValueParam {
  320. irParamPasskind kind;
  321. irProcedure * parent;
  322. Entity * entity;
  323. Type * type;
  324. Type * original_type;
  325. Array<irValue *> referrers;
  326. };
  327. struct irValue {
  328. irValueKind kind;
  329. i32 index;
  330. bool index_set;
  331. union {
  332. irValueConstant Constant;
  333. irValueConstantSlice ConstantSlice;
  334. irValueNil Nil;
  335. irValueUndef Undef;
  336. irValueTypeName TypeName;
  337. irValueGlobal Global;
  338. irValueParam Param;
  339. irProcedure Proc;
  340. irBlock Block;
  341. irInstr Instr;
  342. };
  343. };
  344. gb_global irValue *v_zero = nullptr;
  345. gb_global irValue *v_one = nullptr;
  346. gb_global irValue *v_zero32 = nullptr;
  347. gb_global irValue *v_one32 = nullptr;
  348. gb_global irValue *v_two32 = nullptr;
  349. gb_global irValue *v_false = nullptr;
  350. gb_global irValue *v_true = nullptr;
  351. gb_global irValue *v_raw_nil = nullptr;
  352. enum irAddrKind {
  353. irAddr_Default,
  354. // irAddr_Vector,
  355. irAddr_Map,
  356. irAddr_BitField,
  357. };
  358. struct irAddr {
  359. irAddrKind kind;
  360. irValue * addr;
  361. union {
  362. struct {
  363. irValue *map_key;
  364. Type * map_type;
  365. Type * map_result;
  366. };
  367. struct {
  368. i32 bit_field_value_index;
  369. };
  370. };
  371. // union {
  372. // struct { irValue *index; } Vector;
  373. // };
  374. };
  375. irAddr ir_addr(irValue *addr) {
  376. irAddr v = {irAddr_Default, addr};
  377. return v;
  378. }
  379. irAddr ir_addr_map(irValue *addr, irValue *map_key, Type *map_type, Type *map_result) {
  380. irAddr v = {irAddr_Map, addr};
  381. v.map_key = map_key;
  382. v.map_type = map_type;
  383. v.map_result = map_result;
  384. return v;
  385. }
  386. irAddr ir_addr_bit_field(irValue *addr, i32 bit_field_value_index) {
  387. irAddr v = {irAddr_BitField, addr};
  388. v.bit_field_value_index = bit_field_value_index;
  389. return v;
  390. }
  391. enum irDebugEncoding {
  392. irDebugBasicEncoding_Invalid = 0,
  393. irDebugBasicEncoding_address = 1,
  394. irDebugBasicEncoding_boolean = 2,
  395. irDebugBasicEncoding_float = 3,
  396. irDebugBasicEncoding_signed = 4,
  397. irDebugBasicEncoding_signed_char = 5,
  398. irDebugBasicEncoding_unsigned = 6,
  399. irDebugBasicEncoding_unsigned_char = 7,
  400. irDebugBasicEncoding_member = 13,
  401. irDebugBasicEncoding_pointer_type = 15,
  402. irDebugBasicEncoding_typedef = 22,
  403. irDebugBasicEncoding_array_type = 1,
  404. irDebugBasicEncoding_enumeration_type = 4,
  405. irDebugBasicEncoding_structure_type = 19,
  406. irDebugBasicEncoding_union_type = 23,
  407. };
  408. enum irDebugInfoKind {
  409. irDebugInfo_Invalid,
  410. irDebugInfo_CompileUnit,
  411. irDebugInfo_File,
  412. irDebugInfo_Scope,
  413. irDebugInfo_Proc,
  414. irDebugInfo_AllProcs,
  415. irDebugInfo_BasicType, // basic types
  416. irDebugInfo_ProcType,
  417. irDebugInfo_DerivedType, // pointer, typedef
  418. irDebugInfo_CompositeType, // array, struct, enum, (raw_)union
  419. irDebugInfo_Enumerator, // For irDebugInfo_CompositeType if enum
  420. irDebugInfo_GlobalVariable,
  421. irDebugInfo_LocalVariable,
  422. irDebugInfo_Count,
  423. };
  424. struct irDebugInfo {
  425. irDebugInfoKind kind;
  426. i32 id;
  427. union {
  428. struct {
  429. AstFile * file;
  430. String producer;
  431. irDebugInfo *all_procs;
  432. } CompileUnit;
  433. struct {
  434. AstFile *file;
  435. String filename;
  436. String directory;
  437. } File;
  438. struct {
  439. irDebugInfo *parent;
  440. irDebugInfo *file;
  441. TokenPos pos;
  442. Scope * scope; // Actual scope
  443. } Scope;
  444. struct {
  445. Entity * entity;
  446. String name;
  447. irDebugInfo *file;
  448. TokenPos pos;
  449. } Proc;
  450. struct {
  451. Array<irDebugInfo *> procs;
  452. } AllProcs;
  453. struct {
  454. String name;
  455. i32 size;
  456. i32 align;
  457. irDebugEncoding encoding;
  458. } BasicType;
  459. struct {
  460. irDebugInfo * return_type;
  461. Array<irDebugInfo *> param_types;
  462. } ProcType;
  463. struct {
  464. irDebugInfo * base_type;
  465. irDebugEncoding encoding;
  466. } DerivedType;
  467. struct {
  468. irDebugEncoding encoding;
  469. String name;
  470. String identifier;
  471. irDebugInfo * file;
  472. TokenPos pos;
  473. i32 size;
  474. i32 align;
  475. Array<irDebugInfo *> elements;
  476. } CompositeType;
  477. struct {
  478. String name;
  479. i64 value;
  480. } Enumerator;
  481. struct {
  482. String name;
  483. String linkage_name;
  484. irDebugInfo *scope;
  485. irDebugInfo *file;
  486. TokenPos pos;
  487. irValue *variable;
  488. irDebugInfo *declaration;
  489. } GlobalVariable;
  490. struct {
  491. String name;
  492. irDebugInfo *scope;
  493. irDebugInfo *file;
  494. TokenPos pos;
  495. i32 arg; // Non-zero if proc parameter
  496. irDebugInfo *type;
  497. } LocalVariable;
  498. };
  499. };
  500. struct irGen {
  501. irModule module;
  502. gbFile output_file;
  503. bool opt_called;
  504. String output_base;
  505. String output_name;
  506. };
  507. Type *ir_type(irValue *value);
  508. Type *ir_instr_type(irInstr *instr) {
  509. switch (instr->kind) {
  510. case irInstr_Local:
  511. return instr->Local.type;
  512. case irInstr_Load:
  513. return instr->Load.type;
  514. case irInstr_StructElementPtr:
  515. return instr->StructElementPtr.result_type;
  516. case irInstr_ArrayElementPtr:
  517. return instr->ArrayElementPtr.result_type;
  518. case irInstr_PtrOffset:
  519. return ir_type(instr->PtrOffset.address);
  520. case irInstr_Phi:
  521. return instr->Phi.type;
  522. case irInstr_StructExtractValue:
  523. return instr->StructExtractValue.result_type;
  524. case irInstr_UnionTagPtr:
  525. return instr->UnionTagPtr.type;
  526. case irInstr_UnionTagValue:
  527. return instr->UnionTagValue.type;
  528. case irInstr_UnaryOp:
  529. return instr->UnaryOp.type;
  530. case irInstr_BinaryOp:
  531. return instr->BinaryOp.type;
  532. case irInstr_Conv:
  533. return instr->Conv.to;
  534. case irInstr_Select:
  535. return ir_type(instr->Select.true_value);
  536. case irInstr_Call: {
  537. Type *pt = base_type(instr->Call.type);
  538. if (pt != nullptr) {
  539. if (pt->kind == Type_Tuple && pt->Tuple.variables.count == 1) {
  540. return pt->Tuple.variables[0]->type;
  541. }
  542. return pt;
  543. }
  544. return nullptr;
  545. }
  546. }
  547. return nullptr;
  548. }
  549. Type *ir_type(irValue *value) {
  550. switch (value->kind) {
  551. case irValue_Constant:
  552. return value->Constant.type;
  553. case irValue_ConstantSlice:
  554. return value->ConstantSlice.type;
  555. case irValue_Nil:
  556. return value->Nil.type;
  557. case irValue_Undef:
  558. return value->Undef.type;
  559. case irValue_TypeName:
  560. return value->TypeName.type;
  561. case irValue_Global:
  562. return value->Global.type;
  563. case irValue_Param:
  564. return value->Param.type;
  565. case irValue_Proc:
  566. return value->Proc.type;
  567. case irValue_Instr:
  568. return ir_instr_type(&value->Instr);
  569. }
  570. return nullptr;
  571. }
  572. bool ir_type_has_default_values(Type *t) {
  573. switch (t->kind) {
  574. case Type_Named:
  575. return ir_type_has_default_values(t->Named.base);
  576. case Type_Array:
  577. return ir_type_has_default_values(t->Array.elem);
  578. case Type_Struct:
  579. if (t->Struct.is_raw_union) return false;
  580. for_array(i, t->Struct.fields) {
  581. Entity *f = t->Struct.fields_in_src_order[i];
  582. if (f->kind != Entity_Variable) continue;
  583. if (f->Variable.default_is_nil) {
  584. // NOTE(bill): This is technically zero
  585. continue;
  586. } else if (f->Variable.default_value.kind != ExactValue_Invalid) {
  587. return true;
  588. } else if (f->Variable.default_is_undef) {
  589. return true;
  590. }
  591. bool sub = ir_type_has_default_values(f->type);
  592. if (sub) return true;
  593. }
  594. break;
  595. }
  596. return false;
  597. }
  598. irInstr *ir_get_last_instr(irBlock *block) {
  599. if (block != nullptr) {
  600. isize len = block->instrs.count;
  601. if (len > 0) {
  602. irValue *v = block->instrs[len-1];
  603. GB_ASSERT(v->kind == irValue_Instr);
  604. return &v->Instr;
  605. }
  606. }
  607. return nullptr;
  608. }
  609. bool ir_is_instr_terminating(irInstr *i) {
  610. if (i != nullptr) {
  611. switch (i->kind) {
  612. case irInstr_Return:
  613. case irInstr_Unreachable:
  614. return true;
  615. }
  616. }
  617. return false;
  618. }
  619. void ir_add_edge(irBlock *from, irBlock *to) {
  620. GB_ASSERT(from->instrs.count > 0);
  621. if (!ir_is_instr_terminating(ir_get_last_instr(from))) {
  622. array_add(&from->succs, to);
  623. array_add(&to->preds, from);
  624. }
  625. }
  626. void ir_set_instr_parent(irValue *instr, irBlock *parent) {
  627. if (instr->kind == irValue_Instr) {
  628. instr->Instr.parent = parent;
  629. }
  630. }
  631. Array<irValue *> *ir_value_referrers(irValue *v) {
  632. switch (v->kind) {
  633. case irValue_Global:
  634. return &v->Global.referrers;
  635. case irValue_Param:
  636. return &v->Param.referrers;
  637. case irValue_Proc: {
  638. if (v->Proc.parent != nullptr) {
  639. return &v->Proc.referrers;
  640. }
  641. return nullptr;
  642. }
  643. case irValue_Instr: {
  644. irInstr *i = &v->Instr;
  645. switch (i->kind) {
  646. case irInstr_Local:
  647. return &i->Local.referrers;
  648. }
  649. break;
  650. }
  651. }
  652. return nullptr;
  653. }
  654. ////////////////////////////////////////////////////////////////
  655. //
  656. // @Make
  657. //
  658. ////////////////////////////////////////////////////////////////
  659. void ir_module_add_value (irModule *m, Entity *e, irValue *v);
  660. irValue *ir_emit_zero_init (irProcedure *p, irValue *address);
  661. irValue *ir_emit_comment (irProcedure *p, String text);
  662. irValue *ir_emit_store (irProcedure *p, irValue *address, irValue *value);
  663. irValue *ir_emit_load (irProcedure *p, irValue *address);
  664. void ir_emit_jump (irProcedure *proc, irBlock *block);
  665. irValue *ir_emit_conv (irProcedure *proc, irValue *value, Type *t);
  666. irValue *ir_type_info (irProcedure *proc, Type *type);
  667. irValue *ir_build_expr (irProcedure *proc, AstNode *expr);
  668. void ir_build_stmt (irProcedure *proc, AstNode *node);
  669. irValue *ir_build_cond (irProcedure *proc, AstNode *cond, irBlock *true_block, irBlock *false_block);
  670. void ir_build_defer_stmt (irProcedure *proc, irDefer d);
  671. irAddr ir_build_addr (irProcedure *proc, AstNode *expr);
  672. void ir_build_proc (irValue *value, irProcedure *parent);
  673. void ir_gen_global_type_name(irModule *m, Entity *e, String name);
  674. irValue *ir_get_type_info_ptr (irProcedure *proc, Type *type);
  675. irValue *ir_alloc_value(gbAllocator a, irValueKind kind) {
  676. irValue *v = gb_alloc_item(a, irValue);
  677. v->kind = kind;
  678. return v;
  679. }
  680. irValue *ir_alloc_instr(irProcedure *proc, irInstrKind kind) {
  681. irValue *v = ir_alloc_value(proc->module->allocator, irValue_Instr);
  682. v->Instr.kind = kind;
  683. proc->instr_count++;
  684. return v;
  685. }
  686. irDebugInfo *ir_alloc_debug_info(gbAllocator a, irDebugInfoKind kind) {
  687. irDebugInfo *di = gb_alloc_item(a, irDebugInfo);
  688. di->kind = kind;
  689. return di;
  690. }
  691. irValue *ir_value_type_name(gbAllocator a, String name, Type *type) {
  692. irValue *v = ir_alloc_value(a, irValue_TypeName);
  693. v->TypeName.name = name;
  694. v->TypeName.type = type;
  695. return v;
  696. }
  697. irValue *ir_value_global(gbAllocator a, Entity *e, irValue *value) {
  698. irValue *v = ir_alloc_value(a, irValue_Global);
  699. v->Global.entity = e;
  700. v->Global.type = make_type_pointer(a, e->type);
  701. v->Global.value = value;
  702. array_init(&v->Global.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  703. return v;
  704. }
  705. irValue *ir_value_param(gbAllocator a, irProcedure *parent, Entity *e, Type *abi_type) {
  706. irValue *v = ir_alloc_value(a, irValue_Param);
  707. v->Param.kind = irParamPass_Value;
  708. v->Param.parent = parent;
  709. v->Param.entity = e;
  710. v->Param.original_type = e->type;
  711. v->Param.type = abi_type;
  712. if (abi_type != e->type) {
  713. if (is_type_pointer(abi_type)) {
  714. v->Param.kind = irParamPass_Pointer;
  715. } else if (is_type_integer(abi_type)) {
  716. v->Param.kind = irParamPass_Integer;
  717. } else {
  718. GB_PANIC("Invalid abi type pass kind");
  719. }
  720. }
  721. array_init(&v->Param.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  722. return v;
  723. }
  724. irValue *ir_value_nil(gbAllocator a, Type *type) {
  725. irValue *v = ir_alloc_value(a, irValue_Nil);
  726. v->Nil.type = type;
  727. return v;
  728. }
  729. irValue *ir_value_undef(gbAllocator a, Type *type) {
  730. irValue *v = ir_alloc_value(a, irValue_Undef);
  731. v->Undef.type = type;
  732. return v;
  733. }
  734. String ir_get_global_name(irModule *m, irValue *v) {
  735. if (v->kind != irValue_Global) {
  736. return str_lit("");
  737. }
  738. irValueGlobal *g = &v->Global;
  739. Entity *e = g->entity;
  740. String name = e->token.string;
  741. String *found = map_get(&m->entity_names, hash_entity(e));
  742. if (found != nullptr) {
  743. name = *found;
  744. } else {
  745. GB_ASSERT(name.len > 0);
  746. }
  747. return name;
  748. }
  749. void ir_add_entity_name(irModule *m, Entity *e, String name) {
  750. GB_ASSERT(name.len > 0);
  751. map_set(&m->entity_names, hash_entity(e), name);
  752. }
  753. irValue *ir_instr_local(irProcedure *p, Entity *e, bool zero_initialized) {
  754. irValue *v = ir_alloc_instr(p, irInstr_Local);
  755. irInstr *i = &v->Instr;
  756. i->Local.entity = e;
  757. i->Local.type = make_type_pointer(p->module->allocator, e->type);
  758. i->Local.zero_initialized = zero_initialized;
  759. i->Local.alignment = type_align_of(p->module->allocator, e->type);
  760. array_init(&i->Local.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  761. ir_module_add_value(p->module, e, v);
  762. return v;
  763. }
  764. irValue *ir_instr_store(irProcedure *p, irValue *address, irValue *value, bool atomic) {
  765. irValue *v = ir_alloc_instr(p, irInstr_Store);
  766. irInstr *i = &v->Instr;
  767. i->Store.address = address;
  768. i->Store.value = value;
  769. i->Store.atomic = atomic;
  770. return v;
  771. }
  772. irValue *ir_instr_zero_init(irProcedure *p, irValue *address) {
  773. irValue *v = ir_alloc_instr(p, irInstr_ZeroInit);
  774. irInstr *i = &v->Instr;
  775. i->ZeroInit.address = address;
  776. return v;
  777. }
  778. irValue *ir_instr_load(irProcedure *p, irValue *address) {
  779. irValue *v = ir_alloc_instr(p, irInstr_Load);
  780. irInstr *i = &v->Instr;
  781. i->Load.address = address;
  782. i->Load.type = type_deref(ir_type(address));
  783. return v;
  784. }
  785. irValue *ir_instr_array_element_ptr(irProcedure *p, irValue *address, irValue *elem_index) {
  786. irValue *v = ir_alloc_instr(p, irInstr_ArrayElementPtr);
  787. irInstr *i = &v->Instr;
  788. Type *t = ir_type(address);
  789. GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
  790. t = base_type(type_deref(t));
  791. GB_ASSERT(is_type_array(t) || is_type_vector(t));
  792. Type *result_type = make_type_pointer(p->module->allocator, t->Array.elem);
  793. i->ArrayElementPtr.address = address;
  794. i->ArrayElementPtr.elem_index = elem_index;
  795. i->ArrayElementPtr.result_type = result_type;
  796. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  797. "%s", type_to_string(ir_type(address)));
  798. return v;
  799. }
  800. irValue *ir_instr_struct_element_ptr(irProcedure *p, irValue *address, i32 elem_index, Type *result_type) {
  801. irValue *v = ir_alloc_instr(p, irInstr_StructElementPtr);
  802. irInstr *i = &v->Instr;
  803. i->StructElementPtr.address = address;
  804. i->StructElementPtr.elem_index = elem_index;
  805. i->StructElementPtr.result_type = result_type;
  806. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  807. "%s", type_to_string(ir_type(address)));
  808. return v;
  809. }
  810. irValue *ir_instr_ptr_offset(irProcedure *p, irValue *address, irValue *offset) {
  811. irValue *v = ir_alloc_instr(p, irInstr_PtrOffset);
  812. irInstr *i = &v->Instr;
  813. i->PtrOffset.address = address;
  814. i->PtrOffset.offset = offset;
  815. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  816. "%s", type_to_string(ir_type(address)));
  817. GB_ASSERT_MSG(is_type_integer(ir_type(offset)),
  818. "%s", type_to_string(ir_type(address)));
  819. return v;
  820. }
  821. irValue *ir_instr_struct_extract_value(irProcedure *p, irValue *address, i32 index, Type *result_type) {
  822. irValue *v = ir_alloc_instr(p, irInstr_StructExtractValue);
  823. irInstr *i = &v->Instr;
  824. i->StructExtractValue.address = address;
  825. i->StructExtractValue.index = index;
  826. i->StructExtractValue.result_type = result_type;
  827. return v;
  828. }
  829. irValue *ir_instr_union_tag_ptr(irProcedure *p, irValue *address) {
  830. irValue *v = ir_alloc_instr(p, irInstr_UnionTagPtr);
  831. irInstr *i = &v->Instr;
  832. i->UnionTagPtr.address = address;
  833. // i->UnionTagPtr.type = make_type_pointer(p->module->allocator, t_type_info_ptr);
  834. Type *u = type_deref(ir_type(address));
  835. i->UnionTagPtr.type = make_type_pointer(p->module->allocator, union_tag_type(u));
  836. return v;
  837. }
  838. irValue *ir_instr_union_tag_value(irProcedure *p, irValue *address) {
  839. irValue *v = ir_alloc_instr(p, irInstr_UnionTagValue);
  840. irInstr *i = &v->Instr;
  841. i->UnionTagValue.address = address;
  842. // i->UnionTagValue.type = t_type_info_ptr;
  843. // i->UnionTagValue.type = t_int;
  844. Type *u = type_deref(ir_type(address));
  845. i->UnionTagPtr.type = union_tag_type(u);
  846. return v;
  847. }
  848. irValue *ir_instr_unary_op(irProcedure *p, TokenKind op, irValue *expr, Type *type) {
  849. irValue *v = ir_alloc_instr(p, irInstr_UnaryOp);
  850. irInstr *i = &v->Instr;
  851. i->UnaryOp.op = op;
  852. i->UnaryOp.expr = expr;
  853. i->UnaryOp.type = type;
  854. return v;
  855. }
  856. irValue *ir_instr_binary_op(irProcedure *p, TokenKind op, irValue *left, irValue *right, Type *type) {
  857. irValue *v = ir_alloc_instr(p, irInstr_BinaryOp);
  858. irInstr *i = &v->Instr;
  859. i->BinaryOp.op = op;
  860. i->BinaryOp.left = left;
  861. i->BinaryOp.right = right;
  862. i->BinaryOp.type = type;
  863. return v;
  864. }
  865. irValue *ir_instr_jump(irProcedure *p, irBlock *block) {
  866. irValue *v = ir_alloc_instr(p, irInstr_Jump);
  867. irInstr *i = &v->Instr;
  868. i->Jump.block = block;
  869. return v;
  870. }
  871. irValue *ir_instr_if(irProcedure *p, irValue *cond, irBlock *true_block, irBlock *false_block) {
  872. irValue *v = ir_alloc_instr(p, irInstr_If);
  873. irInstr *i = &v->Instr;
  874. i->If.cond = cond;
  875. i->If.true_block = true_block;
  876. i->If.false_block = false_block;
  877. return v;
  878. }
  879. irValue *ir_instr_phi(irProcedure *p, Array<irValue *> edges, Type *type) {
  880. irValue *v = ir_alloc_instr(p, irInstr_Phi);
  881. irInstr *i = &v->Instr;
  882. i->Phi.edges = edges;
  883. i->Phi.type = type;
  884. return v;
  885. }
  886. irValue *ir_instr_unreachable(irProcedure *p) {
  887. irValue *v = ir_alloc_instr(p, irInstr_Unreachable);
  888. return v;
  889. }
  890. irValue *ir_instr_return(irProcedure *p, irValue *value) {
  891. irValue *v = ir_alloc_instr(p, irInstr_Return);
  892. v->Instr.Return.value = value;
  893. return v;
  894. }
  895. irValue *ir_instr_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
  896. irValue *v = ir_alloc_instr(p, irInstr_Select);
  897. v->Instr.Select.cond = cond;
  898. v->Instr.Select.true_value = t;
  899. v->Instr.Select.false_value = f;
  900. return v;
  901. }
  902. irValue *ir_instr_call(irProcedure *p, irValue *value, irValue *return_ptr, irValue **args, isize arg_count, Type *result_type, irValue *context_ptr) {
  903. irValue *v = ir_alloc_instr(p, irInstr_Call);
  904. v->Instr.Call.value = value;
  905. v->Instr.Call.return_ptr = return_ptr;
  906. v->Instr.Call.args = args;
  907. v->Instr.Call.arg_count = arg_count;
  908. v->Instr.Call.type = result_type;
  909. v->Instr.Call.context_ptr = context_ptr;
  910. return v;
  911. }
  912. irValue *ir_instr_conv(irProcedure *p, irConvKind kind, irValue *value, Type *from, Type *to) {
  913. irValue *v = ir_alloc_instr(p, irInstr_Conv);
  914. v->Instr.Conv.kind = kind;
  915. v->Instr.Conv.value = value;
  916. v->Instr.Conv.from = from;
  917. v->Instr.Conv.to = to;
  918. return v;
  919. }
  920. irValue *ir_instr_comment(irProcedure *p, String text) {
  921. irValue *v = ir_alloc_instr(p, irInstr_Comment);
  922. v->Instr.Comment.text = text;
  923. return v;
  924. }
  925. irValue *ir_instr_debug_declare(irProcedure *p, irDebugInfo *debug_info, AstNode *expr, Entity *entity, bool is_addr, irValue *value) {
  926. irValue *v = ir_alloc_instr(p, irInstr_DebugDeclare);
  927. v->Instr.DebugDeclare.debug_info = debug_info;
  928. v->Instr.DebugDeclare.expr = expr;
  929. v->Instr.DebugDeclare.entity = entity;
  930. v->Instr.DebugDeclare.is_addr = is_addr;
  931. v->Instr.DebugDeclare.value = value;
  932. return v;
  933. }
  934. irValue *ir_value_constant(gbAllocator a, Type *type, ExactValue value) {
  935. irValue *v = ir_alloc_value(a, irValue_Constant);
  936. v->Constant.type = type;
  937. v->Constant.value = value;
  938. return v;
  939. }
  940. irValue *ir_value_constant_slice(gbAllocator a, Type *type, irValue *backing_array, i64 count) {
  941. irValue *v = ir_alloc_value(a, irValue_ConstantSlice);
  942. v->ConstantSlice.type = type;
  943. v->ConstantSlice.backing_array = backing_array;
  944. v->ConstantSlice.count = count;
  945. return v;
  946. }
  947. irValue *ir_emit(irProcedure *proc, irValue *instr) {
  948. GB_ASSERT(instr->kind == irValue_Instr);
  949. irBlock *b = proc->curr_block;
  950. instr->Instr.parent = b;
  951. if (b != nullptr) {
  952. irInstr *i = ir_get_last_instr(b);
  953. if (!ir_is_instr_terminating(i)) {
  954. array_add(&b->instrs, instr);
  955. }
  956. } else if (instr->Instr.kind != irInstr_Unreachable) {
  957. GB_PANIC("ir_emit: Instruction missing parent block");
  958. }
  959. return instr;
  960. }
  961. irValue *ir_const_int(gbAllocator a, i64 i) {
  962. return ir_value_constant(a, t_int, exact_value_i64(i));
  963. }
  964. irValue *ir_const_i32(gbAllocator a, i32 i) {
  965. return ir_value_constant(a, t_i32, exact_value_i64(i));
  966. }
  967. irValue *ir_const_u32(gbAllocator a, u32 i) {
  968. return ir_value_constant(a, t_u32, exact_value_i64(i));
  969. }
  970. irValue *ir_const_i64(gbAllocator a, i64 i) {
  971. return ir_value_constant(a, t_i64, exact_value_i64(i));
  972. }
  973. irValue *ir_const_u64(gbAllocator a, u64 i) {
  974. return ir_value_constant(a, t_u64, exact_value_i64(i));
  975. }
  976. irValue *ir_const_f32(gbAllocator a, f32 f) {
  977. return ir_value_constant(a, t_f32, exact_value_float(f));
  978. }
  979. irValue *ir_const_f64(gbAllocator a, f64 f) {
  980. return ir_value_constant(a, t_f64, exact_value_float(f));
  981. }
  982. irValue *ir_const_bool(gbAllocator a, bool b) {
  983. return ir_value_constant(a, t_bool, exact_value_bool(b != 0));
  984. }
  985. irValue *ir_const_string(gbAllocator a, String s) {
  986. return ir_value_constant(a, t_string, exact_value_string(s));
  987. }
  988. irValue *ir_value_procedure(gbAllocator a, irModule *m, Entity *entity, Type *type, AstNode *type_expr, AstNode *body, String name) {
  989. irValue *v = ir_alloc_value(a, irValue_Proc);
  990. v->Proc.module = m;
  991. v->Proc.entity = entity;
  992. v->Proc.type = type;
  993. v->Proc.type_expr = type_expr;
  994. v->Proc.body = body;
  995. v->Proc.name = name;
  996. array_init(&v->Proc.referrers, heap_allocator()); // TODO(bill): replace heap allocator
  997. Type *t = base_type(type);
  998. GB_ASSERT(is_type_proc(t));
  999. array_init(&v->Proc.params, heap_allocator(), t->Proc.param_count);
  1000. return v;
  1001. }
  1002. irValue *ir_generate_array(irModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  1003. gbAllocator a = m->allocator;
  1004. Token token = {Token_Ident};
  1005. isize name_len = prefix.len + 10;
  1006. char *text = gb_alloc_array(a, char, name_len);
  1007. gb_snprintf(text, name_len,
  1008. "%.*s-%llx", LIT(prefix), cast(unsigned long long)id);
  1009. String s = make_string_c(text);
  1010. Entity *e = make_entity_variable(a, nullptr,
  1011. make_token_ident(s),
  1012. make_type_array(a, elem_type, count),
  1013. false);
  1014. irValue *value = ir_value_global(a, e, nullptr);
  1015. value->Global.is_private = true;
  1016. ir_module_add_value(m, e, value);
  1017. map_set(&m->members, hash_string(s), value);
  1018. return value;
  1019. }
  1020. irBlock *ir_new_block(irProcedure *proc, AstNode *node, char *label) {
  1021. Scope *scope = nullptr;
  1022. if (node != nullptr) {
  1023. scope = scope_of_node(proc->module->info, node);
  1024. GB_ASSERT_MSG(scope != nullptr, "Block scope not found for %.*s", LIT(ast_node_strings[node->kind]));
  1025. }
  1026. irValue *v = ir_alloc_value(proc->module->allocator, irValue_Block);
  1027. v->Block.label = make_string_c(label);
  1028. v->Block.node = node;
  1029. v->Block.scope = scope;
  1030. v->Block.parent = proc;
  1031. // TODO(bill): Is this correct or even needed?
  1032. v->Block.scope_index = proc->scope_index;
  1033. array_init(&v->Block.instrs, heap_allocator());
  1034. array_init(&v->Block.locals, heap_allocator());
  1035. array_init(&v->Block.preds, heap_allocator());
  1036. array_init(&v->Block.succs, heap_allocator());
  1037. irBlock *block = &v->Block;
  1038. return block;
  1039. }
  1040. void ir_add_block_to_proc(irProcedure *proc, irBlock *b) {
  1041. for_array(i, proc->blocks) {
  1042. if (proc->blocks[i] == b) {
  1043. return;
  1044. }
  1045. }
  1046. array_add(&proc->blocks, b);
  1047. b->index = proc->block_count++;
  1048. }
  1049. void ir_start_block(irProcedure *proc, irBlock *block) {
  1050. proc->curr_block = block;
  1051. if (block != nullptr) {
  1052. ir_add_block_to_proc(proc, block);
  1053. }
  1054. }
  1055. irDefer ir_add_defer_node(irProcedure *proc, isize scope_index, AstNode *stmt) {
  1056. irDefer d = {irDefer_Node};
  1057. d.scope_index = scope_index;
  1058. d.block = proc->curr_block;
  1059. d.stmt = stmt;
  1060. array_add(&proc->defer_stmts, d);
  1061. return d;
  1062. }
  1063. irDefer ir_add_defer_instr(irProcedure *proc, isize scope_index, irValue *instr) {
  1064. irDefer d = {irDefer_Instr};
  1065. d.scope_index = proc->scope_index;
  1066. d.block = proc->curr_block;
  1067. d.instr = instr; // NOTE(bill): It will make a copy everytime it is called
  1068. array_add(&proc->defer_stmts, d);
  1069. return d;
  1070. }
  1071. irValue *ir_add_module_constant(irModule *m, Type *type, ExactValue value) {
  1072. gbAllocator a = m->allocator;
  1073. // gbAllocator a = gb_heap_allocator();
  1074. if (is_type_slice(type)) {
  1075. ast_node(cl, CompoundLit, value.value_compound);
  1076. isize count = cl->elems.count;
  1077. if (count == 0) {
  1078. return ir_value_nil(a, type);
  1079. }
  1080. Type *elem = base_type(type)->Slice.elem;
  1081. Type *t = make_type_array(a, elem, count);
  1082. irValue *backing_array = ir_add_module_constant(m, t, value);
  1083. isize max_len = 7+8+1;
  1084. u8 *str = cast(u8 *)gb_alloc_array(a, u8, max_len);
  1085. isize len = gb_snprintf(cast(char *)str, max_len, "__csba$%x", m->global_array_index);
  1086. m->global_array_index++;
  1087. String name = make_string(str, len-1);
  1088. Entity *e = make_entity_constant(a, nullptr, make_token_ident(name), t, value);
  1089. irValue *g = ir_value_global(a, e, backing_array);
  1090. ir_module_add_value(m, e, g);
  1091. map_set(&m->members, hash_string(name), g);
  1092. return ir_value_constant_slice(a, type, g, count);
  1093. }
  1094. return ir_value_constant(a, type, value);
  1095. }
  1096. irValue *ir_add_global_string_array(irModule *m, String string) {
  1097. // TODO(bill): Should this use the arena allocator or the heap allocator?
  1098. // Strings could be huge!
  1099. // gbAllocator a = m->allocator;
  1100. gbAllocator a = gb_heap_allocator();
  1101. isize max_len = 6+8+1;
  1102. u8 *str = cast(u8 *)gb_alloc_array(a, u8, max_len);
  1103. isize len = gb_snprintf(cast(char *)str, max_len, "__str$%x", m->global_string_index);
  1104. m->global_string_index++;
  1105. String name = make_string(str, len-1);
  1106. Token token = {Token_String};
  1107. token.string = name;
  1108. Type *type = make_type_array(a, t_u8, string.len+1);
  1109. ExactValue ev = exact_value_string(string);
  1110. Entity *entity = make_entity_constant(a, nullptr, token, type, ev);
  1111. irValue *g = ir_value_global(a, entity, ir_add_module_constant(m, type, ev));
  1112. g->Global.is_private = true;
  1113. g->Global.is_unnamed_addr = true;
  1114. // g->Global.is_constant = true;
  1115. ir_module_add_value(m, entity, g);
  1116. map_set(&m->members, hash_string(name), g);
  1117. return g;
  1118. }
  1119. irValue *ir_add_local(irProcedure *proc, Entity *e, AstNode *expr, bool zero_initialized) {
  1120. irBlock *b = proc->decl_block; // all variables must be in the first block
  1121. irValue *instr = ir_instr_local(proc, e, true);
  1122. instr->Instr.parent = b;
  1123. array_add(&b->instrs, instr);
  1124. array_add(&b->locals, instr);
  1125. proc->local_count++;
  1126. if (zero_initialized) {
  1127. ir_emit_zero_init(proc, instr);
  1128. }
  1129. if (expr != nullptr && proc->entity != nullptr) {
  1130. irDebugInfo *di = *map_get(&proc->module->debug_info, hash_entity(proc->entity));
  1131. ir_emit(proc, ir_instr_debug_declare(proc, di, expr, e, true, instr));
  1132. }
  1133. return instr;
  1134. }
  1135. irValue *ir_add_local_for_identifier(irProcedure *proc, AstNode *ident, bool zero_initialized) {
  1136. Entity *e = entity_of_ident(proc->module->info, ident);
  1137. if (e != nullptr) {
  1138. String name = e->token.string;
  1139. ir_emit_comment(proc, name);
  1140. if (e->kind == Entity_Variable &&
  1141. e->Variable.is_foreign) {
  1142. HashKey key = hash_string(name);
  1143. irValue **prev_value = map_get(&proc->module->members, key);
  1144. if (prev_value == nullptr) {
  1145. // NOTE(bill): Don't do mutliple declarations in the IR
  1146. irValue *g = ir_value_global(proc->module->allocator, e, nullptr);
  1147. g->Global.name = name;
  1148. g->Global.is_foreign = true;
  1149. ir_module_add_value(proc->module, e, g);
  1150. map_set(&proc->module->members, key, g);
  1151. return g;
  1152. } else {
  1153. return *prev_value;
  1154. }
  1155. }
  1156. return ir_add_local(proc, e, ident, zero_initialized);
  1157. }
  1158. return nullptr;
  1159. }
  1160. irValue *ir_add_local_generated(irProcedure *proc, Type *type, bool zero_initialized = true) {
  1161. GB_ASSERT(type != nullptr);
  1162. Scope *scope = nullptr;
  1163. if (proc->curr_block) {
  1164. scope = proc->curr_block->scope;
  1165. }
  1166. Entity *e = make_entity_variable(proc->module->allocator,
  1167. scope,
  1168. empty_token,
  1169. type, false);
  1170. return ir_add_local(proc, e, nullptr, zero_initialized);
  1171. }
  1172. irValue *ir_add_global_generated(irModule *m, Type *type, irValue *value) {
  1173. GB_ASSERT(type != nullptr);
  1174. gbAllocator a = m->allocator;
  1175. isize max_len = 7+8+1;
  1176. u8 *str = cast(u8 *)gb_alloc_array(a, u8, max_len);
  1177. isize len = gb_snprintf(cast(char *)str, max_len, "__ggv$%x", m->global_generated_index);
  1178. m->global_generated_index++;
  1179. String name = make_string(str, len-1);
  1180. Scope *scope = nullptr;
  1181. Entity *e = make_entity_variable(a,
  1182. scope,
  1183. make_token_ident(name),
  1184. type, false);
  1185. irValue *g = ir_value_global(a, e, value);
  1186. ir_module_add_value(m, e, g);
  1187. map_set(&m->members, hash_string(name), g);
  1188. return g;
  1189. }
  1190. irValue *ir_add_param(irProcedure *proc, Entity *e, AstNode *expr, Type *abi_type) {
  1191. irValue *v = ir_value_param(proc->module->allocator, proc, e, abi_type);
  1192. irValueParam *p = &v->Param;
  1193. switch (p->kind) {
  1194. case irParamPass_Value: {
  1195. irValue *l = ir_add_local(proc, e, expr, false);
  1196. ir_emit_store(proc, l, v);
  1197. return v;
  1198. }
  1199. case irParamPass_Pointer: {
  1200. ir_module_add_value(proc->module, e, v);
  1201. return ir_emit_load(proc, v);
  1202. }
  1203. case irParamPass_Integer: {
  1204. irValue *l = ir_add_local(proc, e, expr, false);
  1205. irValue *iptr = ir_emit_conv(proc, l, make_type_pointer(proc->module->allocator, p->type));
  1206. ir_emit_store(proc, iptr, v);
  1207. return ir_emit_load(proc, l);
  1208. }
  1209. }
  1210. GB_PANIC("Unreachable");
  1211. return nullptr;
  1212. }
  1213. ////////////////////////////////////////////////////////////////
  1214. //
  1215. // @Debug
  1216. //
  1217. ////////////////////////////////////////////////////////////////
  1218. irDebugInfo *ir_add_debug_info_file(irProcedure *proc, AstFile *file) {
  1219. // if (!proc->module->generate_debug_info) {
  1220. // return nullptr;
  1221. // }
  1222. GB_ASSERT(file != nullptr);
  1223. irDebugInfo *di = ir_alloc_debug_info(proc->module->allocator, irDebugInfo_File);
  1224. di->File.file = file;
  1225. String filename = file->tokenizer.fullpath;
  1226. String directory = filename;
  1227. isize slash_index = 0;
  1228. for (isize i = filename.len-1; i >= 0; i--) {
  1229. if (filename[i] == '\\' ||
  1230. filename[i] == '/') {
  1231. break;
  1232. }
  1233. slash_index = i;
  1234. }
  1235. directory.len = slash_index-1;
  1236. filename.text = filename.text + slash_index;
  1237. filename.len -= slash_index;
  1238. di->File.filename = filename;
  1239. di->File.directory = directory;
  1240. map_set(&proc->module->debug_info, hash_ast_file(file), di);
  1241. return di;
  1242. }
  1243. irDebugInfo *ir_add_debug_info_proc(irProcedure *proc, Entity *entity, String name, irDebugInfo *file) {
  1244. // if (!proc->module->generate_debug_info) {
  1245. // return nullptr;
  1246. // }
  1247. GB_ASSERT(entity != nullptr);
  1248. irDebugInfo *di = ir_alloc_debug_info(proc->module->allocator, irDebugInfo_Proc);
  1249. di->Proc.entity = entity;
  1250. di->Proc.name = name;
  1251. di->Proc.file = file;
  1252. di->Proc.pos = entity->token.pos;
  1253. map_set(&proc->module->debug_info, hash_entity(entity), di);
  1254. return di;
  1255. }
  1256. ////////////////////////////////////////////////////////////////
  1257. //
  1258. // @Emit
  1259. //
  1260. ////////////////////////////////////////////////////////////////
  1261. irValue *ir_emit_store(irProcedure *p, irValue *address, irValue *value) {
  1262. #if 1
  1263. // NOTE(bill): Sanity check
  1264. Type *a = type_deref(ir_type(address));
  1265. Type *b = ir_type(value);
  1266. if (!is_type_untyped(b)) {
  1267. GB_ASSERT_MSG(are_types_identical(core_type(a), core_type(b)), "%s %s", type_to_string(a), type_to_string(b));
  1268. }
  1269. #endif
  1270. return ir_emit(p, ir_instr_store(p, address, value, false));
  1271. }
  1272. irValue *ir_emit_load(irProcedure *p, irValue *address) {
  1273. GB_ASSERT(address != nullptr);
  1274. return ir_emit(p, ir_instr_load(p, address));
  1275. }
  1276. irValue *ir_emit_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
  1277. return ir_emit(p, ir_instr_select(p, cond, t, f));
  1278. }
  1279. irValue *ir_emit_zero_init(irProcedure *p, irValue *address) {
  1280. return ir_emit(p, ir_instr_zero_init(p, address));
  1281. }
  1282. irValue *ir_emit_comment(irProcedure *p, String text) {
  1283. return ir_emit(p, ir_instr_comment(p, text));
  1284. }
  1285. irValue *ir_copy_value_to_ptr(irProcedure *proc, irValue *val, Type *new_type, i64 alignment) {
  1286. i64 type_alignment = type_align_of(proc->module->allocator, new_type);
  1287. if (alignment < type_alignment) {
  1288. alignment = type_alignment;
  1289. }
  1290. irValue *ptr = ir_add_local_generated(proc, new_type);
  1291. ptr->Instr.Local.alignment = alignment;
  1292. ir_emit_store(proc, ptr, val);
  1293. return ptr;
  1294. }
  1295. irValue *ir_emit_bitcast(irProcedure *proc, irValue *data, Type *type) {
  1296. return ir_emit(proc, ir_instr_conv(proc, irConv_bitcast, data, ir_type(data), type));
  1297. }
  1298. irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t);
  1299. irValue *ir_emit_global_call(irProcedure *proc, char *name_, irValue **args, isize arg_count);
  1300. irValue *ir_find_or_generate_context_ptr(irProcedure *proc) {
  1301. if (proc->context_stack.count > 0) {
  1302. return proc->context_stack[proc->context_stack.count-1];
  1303. }
  1304. irValue *c = ir_add_local_generated(proc, t_context);
  1305. ir_emit_store(proc, c, ir_emit_load(proc, proc->module->global_default_context));
  1306. array_add(&proc->context_stack, c);
  1307. return c;
  1308. }
  1309. irValue *ir_emit_call(irProcedure *p, irValue *value, irValue **args, isize arg_count) {
  1310. Type *pt = base_type(ir_type(value));
  1311. GB_ASSERT(pt->kind == Type_Proc);
  1312. Type *results = pt->Proc.results;
  1313. irValue *context_ptr = nullptr;
  1314. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1315. context_ptr = ir_find_or_generate_context_ptr(p);
  1316. }
  1317. isize param_count = pt->Proc.param_count;
  1318. if (pt->Proc.c_vararg) {
  1319. GB_ASSERT(param_count-1 <= arg_count);
  1320. } else {
  1321. GB_ASSERT(param_count == arg_count);
  1322. }
  1323. for (isize i = 0; i < param_count; i++) {
  1324. Entity *e = pt->Proc.params->Tuple.variables[i];
  1325. if (e->kind != Entity_Variable) {
  1326. continue;
  1327. }
  1328. Type *original_type = e->type;
  1329. Type *new_type = pt->Proc.abi_compat_params[i];
  1330. if (original_type != new_type) {
  1331. if (is_type_pointer(new_type)) {
  1332. args[i] = ir_copy_value_to_ptr(p, args[i], original_type, 16);
  1333. } else if (is_type_integer(new_type)) {
  1334. args[i] = ir_emit_transmute(p, args[i], new_type);
  1335. }
  1336. }
  1337. }
  1338. Type *abi_rt = pt->Proc.abi_compat_result_type;
  1339. Type *rt = reduce_tuple_to_single_type(results);
  1340. if (pt->Proc.return_by_pointer) {
  1341. irValue *return_ptr = ir_add_local_generated(p, rt);
  1342. GB_ASSERT(is_type_pointer(ir_type(return_ptr)));
  1343. ir_emit(p, ir_instr_call(p, value, return_ptr, args, arg_count, nullptr, context_ptr));
  1344. return ir_emit_load(p, return_ptr);
  1345. }
  1346. irValue *result = ir_emit(p, ir_instr_call(p, value, nullptr, args, arg_count, abi_rt, context_ptr));
  1347. if (abi_rt != results) {
  1348. result = ir_emit_transmute(p, result, rt);
  1349. }
  1350. return result;
  1351. }
  1352. irValue *ir_emit_global_call(irProcedure *proc, char *name_, irValue **args, isize arg_count) {
  1353. String name = make_string_c(name_);
  1354. irValue **found = map_get(&proc->module->members, hash_string(name));
  1355. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(name));
  1356. irValue *gp = *found;
  1357. return ir_emit_call(proc, gp, args, arg_count);
  1358. }
  1359. void ir_emit_defer_stmts(irProcedure *proc, irDeferExitKind kind, irBlock *block) {
  1360. isize count = proc->defer_stmts.count;
  1361. isize i = count;
  1362. while (i --> 0) {
  1363. irDefer d = proc->defer_stmts[i];
  1364. if (kind == irDeferExit_Default) {
  1365. if (proc->scope_index == d.scope_index &&
  1366. d.scope_index > 1) {
  1367. ir_build_defer_stmt(proc, d);
  1368. array_pop(&proc->defer_stmts);
  1369. continue;
  1370. } else {
  1371. break;
  1372. }
  1373. } else if (kind == irDeferExit_Return) {
  1374. ir_build_defer_stmt(proc, d);
  1375. } else if (kind == irDeferExit_Branch) {
  1376. GB_ASSERT(block != nullptr);
  1377. isize lower_limit = block->scope_index+1;
  1378. if (lower_limit < d.scope_index) {
  1379. ir_build_defer_stmt(proc, d);
  1380. }
  1381. }
  1382. }
  1383. }
  1384. void ir_open_scope(irProcedure *proc) {
  1385. proc->scope_index++;
  1386. }
  1387. void ir_close_scope(irProcedure *proc, irDeferExitKind kind, irBlock *block) {
  1388. ir_emit_defer_stmts(proc, kind, block);
  1389. GB_ASSERT(proc->scope_index > 0);
  1390. proc->scope_index--;
  1391. }
  1392. void ir_emit_unreachable(irProcedure *proc) {
  1393. ir_emit(proc, ir_instr_unreachable(proc));
  1394. }
  1395. void ir_emit_return(irProcedure *proc, irValue *v) {
  1396. ir_emit_defer_stmts(proc, irDeferExit_Return, nullptr);
  1397. if (proc->type->Proc.return_by_pointer) {
  1398. ir_emit_store(proc, proc->return_ptr, v);
  1399. ir_emit(proc, ir_instr_return(proc, nullptr));
  1400. } else {
  1401. Type *abi_rt = proc->type->Proc.abi_compat_result_type;
  1402. if (abi_rt != proc->type->Proc.results) {
  1403. v = ir_emit_transmute(proc, v, abi_rt);
  1404. }
  1405. ir_emit(proc, ir_instr_return(proc, v));
  1406. }
  1407. }
  1408. void ir_emit_jump(irProcedure *proc, irBlock *target_block) {
  1409. irBlock *b = proc->curr_block;
  1410. if (b == nullptr) {
  1411. return;
  1412. }
  1413. ir_emit(proc, ir_instr_jump(proc, target_block));
  1414. ir_add_edge(b, target_block);
  1415. ir_start_block(proc, nullptr);
  1416. }
  1417. void ir_emit_if(irProcedure *proc, irValue *cond, irBlock *true_block, irBlock *false_block) {
  1418. irBlock *b = proc->curr_block;
  1419. if (b == nullptr) {
  1420. return;
  1421. }
  1422. ir_emit(proc, ir_instr_if(proc, cond, true_block, false_block));
  1423. ir_add_edge(b, true_block);
  1424. ir_add_edge(b, false_block);
  1425. ir_start_block(proc, nullptr);
  1426. }
  1427. void ir_emit_startup_runtime(irProcedure *proc) {
  1428. GB_ASSERT(proc->parent == nullptr && proc->name == "main");
  1429. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  1430. }
  1431. irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index);
  1432. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right);
  1433. irValue *ir_gen_map_header(irProcedure *proc, irValue *map_val, Type *map_type) {
  1434. GB_ASSERT_MSG(is_type_pointer(ir_type(map_val)), "%s", type_to_string(ir_type(map_val)));
  1435. gbAllocator a = proc->module->allocator;
  1436. irValue *h = ir_add_local_generated(proc, t_map_header);
  1437. map_type = base_type(map_type);
  1438. Type *key_type = map_type->Map.key;
  1439. Type *val_type = map_type->Map.value;
  1440. // NOTE(bill): Removes unnecessary allocation if split gep
  1441. irValue *gep0 = ir_emit_struct_ep(proc, h, 0);
  1442. irValue *m = ir_emit_conv(proc, map_val, type_deref(ir_type(gep0)));
  1443. ir_emit_store(proc, gep0, m);
  1444. if (is_type_string(key_type)) {
  1445. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 1), v_true);
  1446. }
  1447. i64 entry_size = type_size_of(a, map_type->Map.entry_type);
  1448. i64 entry_align = type_align_of(a, map_type->Map.entry_type);
  1449. i64 value_offset = type_offset_of(a, map_type->Map.entry_type, 2);
  1450. i64 value_size = type_size_of(a, map_type->Map.value);
  1451. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 2), ir_const_int(a, entry_size));
  1452. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 3), ir_const_int(a, entry_align));
  1453. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 4), ir_const_int(a, value_offset));
  1454. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 5), ir_const_int(a, value_size));
  1455. return ir_emit_load(proc, h);
  1456. }
  1457. irValue *ir_gen_map_key(irProcedure *proc, irValue *key, Type *key_type) {
  1458. Type *hash_type = t_u128;
  1459. irValue *v = ir_add_local_generated(proc, t_map_key);
  1460. Type *t = base_type(ir_type(key));
  1461. key = ir_emit_conv(proc, key, key_type);
  1462. if (is_type_integer(t)) {
  1463. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, key, hash_type));
  1464. } else if (is_type_pointer(t)) {
  1465. irValue *p = ir_emit_conv(proc, key, t_uint);
  1466. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, p, hash_type));
  1467. } else if (is_type_float(t)) {
  1468. irValue *bits = nullptr;
  1469. i64 size = type_size_of(proc->module->allocator, t);
  1470. switch (8*size) {
  1471. case 32: bits = ir_emit_transmute(proc, key, t_u32); break;
  1472. case 64: bits = ir_emit_transmute(proc, key, t_u64); break;
  1473. default: GB_PANIC("Unhandled float size: %lld bits", size); break;
  1474. }
  1475. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, bits, hash_type));
  1476. } else if (is_type_string(t)) {
  1477. irValue *str = ir_emit_conv(proc, key, t_string);
  1478. irValue *hashed_str = nullptr;
  1479. if (str->kind == irValue_Constant) {
  1480. ExactValue ev = str->Constant.value;
  1481. GB_ASSERT(ev.kind == ExactValue_String);
  1482. u128 hs = fnv128a(ev.value_string.text, ev.value_string.len);
  1483. hashed_str = ir_value_constant(proc->module->allocator, t_u128, exact_value_u128(hs));
  1484. } else {
  1485. irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 1);
  1486. args[0] = str;
  1487. hashed_str = ir_emit_global_call(proc, "__default_hash_string", args, 1);
  1488. }
  1489. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), hashed_str);
  1490. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), str);
  1491. } else {
  1492. GB_PANIC("Unhandled map key type");
  1493. }
  1494. return ir_emit_load(proc, v);
  1495. }
  1496. // NOTE(bill): Returns nullptr if not possible
  1497. irValue *ir_address_from_load_or_generate_local(irProcedure *proc, irValue *val) {
  1498. if (val->kind == irValue_Instr) {
  1499. if (val->Instr.kind == irInstr_Load) {
  1500. return val->Instr.Load.address;
  1501. }
  1502. }
  1503. Type *type = ir_type(val);
  1504. irValue *local = ir_add_local_generated(proc, type);
  1505. ir_emit_store(proc, local, val);
  1506. return local;
  1507. }
  1508. Type *ir_addr_type(irAddr addr) {
  1509. if (addr.addr == nullptr) {
  1510. return nullptr;
  1511. }
  1512. if (addr.kind == irAddr_Map) {
  1513. Type *t = base_type(addr.map_type);
  1514. GB_ASSERT(is_type_map(t));
  1515. return t->Map.value;
  1516. }
  1517. Type *t = ir_type(addr.addr);
  1518. GB_ASSERT(is_type_pointer(t));
  1519. return type_deref(t);
  1520. }
  1521. irValue *ir_insert_dynamic_map_key_and_value(irProcedure *proc, irValue *addr, Type *map_type,
  1522. irValue *map_key, irValue *map_value) {
  1523. map_type = base_type(map_type);
  1524. irValue *h = ir_gen_map_header(proc, addr, map_type);
  1525. irValue *key = ir_gen_map_key(proc, map_key, map_type->Map.key);
  1526. irValue *v = ir_emit_conv(proc, map_value, map_type->Map.value);
  1527. irValue *ptr = ir_add_local_generated(proc, ir_type(v));
  1528. ir_emit_store(proc, ptr, v);
  1529. irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 3);
  1530. args[0] = h;
  1531. args[1] = key;
  1532. args[2] = ir_emit_conv(proc, ptr, t_rawptr);
  1533. return ir_emit_global_call(proc, "__dynamic_map_set", args, 3);
  1534. }
  1535. irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset);
  1536. irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type);
  1537. irValue *ir_addr_store(irProcedure *proc, irAddr addr, irValue *value) {
  1538. if (addr.addr == nullptr) {
  1539. return nullptr;
  1540. }
  1541. if (addr.kind == irAddr_Map) {
  1542. return ir_insert_dynamic_map_key_and_value(proc, addr.addr, addr.map_type, addr.map_key, value);
  1543. } else if (addr.kind == irAddr_BitField) {
  1544. gbAllocator a = proc->module->allocator;
  1545. Type *bft = base_type(type_deref(ir_type(addr.addr)));
  1546. GB_ASSERT(is_type_bit_field(bft));
  1547. i32 value_index = addr.bit_field_value_index;
  1548. i32 offset = bft->BitField.offsets[value_index];
  1549. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  1550. i32 byte_index = offset / 8;
  1551. i32 bit_inset = offset % 8;
  1552. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  1553. if (size_in_bytes == 0) {
  1554. GB_ASSERT(size_in_bits == 0);
  1555. return nullptr;
  1556. }
  1557. Type *int_type = nullptr;
  1558. switch (size_in_bytes) {
  1559. case 1: int_type = t_u8; break;
  1560. case 2: int_type = t_u16; break;
  1561. case 4: int_type = t_u32; break;
  1562. case 8: int_type = t_u64; break;
  1563. case 16: int_type = t_u128; break;
  1564. }
  1565. GB_ASSERT(int_type != nullptr);
  1566. value = ir_emit_conv(proc, value, int_type);
  1567. irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
  1568. bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(a, byte_index));
  1569. if (bit_inset == 0) {
  1570. irValue *v = value;
  1571. i32 sa = 8*size_in_bytes - size_in_bits;
  1572. if (sa > 0) {
  1573. irValue *shift_amount = ir_const_int(a, sa);
  1574. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  1575. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  1576. }
  1577. irValue *ptr = ir_emit_conv(proc, bytes, make_type_pointer(a, int_type));
  1578. v = ir_emit_arith(proc, Token_Or, ir_emit_load(proc, ptr), v, int_type);
  1579. return ir_emit_store(proc, ptr, v);
  1580. }
  1581. // First byte
  1582. {
  1583. i32 sa = 8 - bit_inset;
  1584. irValue *shift_amount = ir_const_int(a, sa);
  1585. irValue *v = ir_emit_conv(proc, value, t_u8);
  1586. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  1587. v = ir_emit_arith(proc, Token_Or, ir_emit_load(proc, bytes), v, int_type);
  1588. ir_emit_store(proc, bytes, v);
  1589. }
  1590. // Remaining bytes
  1591. {
  1592. irValue *shift_amount = ir_const_int(a, bit_inset);
  1593. irValue *ptr = ir_emit_conv(proc, ir_emit_ptr_offset(proc, bytes, v_one), make_type_pointer(a, int_type));
  1594. irValue *v = ir_emit_arith(proc, Token_Shr, value, shift_amount, int_type);
  1595. v = ir_emit_arith(proc, Token_Or, ir_emit_load(proc, ptr), v, int_type);
  1596. return ir_emit_store(proc, ptr, v);
  1597. }
  1598. }
  1599. irValue *v = ir_emit_conv(proc, value, ir_addr_type(addr));
  1600. return ir_emit_store(proc, addr.addr, v);
  1601. }
  1602. irValue *ir_addr_load(irProcedure *proc, irAddr addr) {
  1603. if (addr.addr == nullptr) {
  1604. GB_PANIC("Illegal addr load");
  1605. return nullptr;
  1606. }
  1607. if (addr.kind == irAddr_Map) {
  1608. // TODO(bill): map lookup
  1609. Type *map_type = base_type(addr.map_type);
  1610. irValue *v = ir_add_local_generated(proc, map_type->Map.lookup_result_type);
  1611. irValue *h = ir_gen_map_header(proc, addr.addr, map_type);
  1612. irValue *key = ir_gen_map_key(proc, addr.map_key, map_type->Map.key);
  1613. irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 2);
  1614. args[0] = h;
  1615. args[1] = key;
  1616. irValue *ptr = ir_emit_global_call(proc, "__dynamic_map_get", args, 2);
  1617. irValue *ok = ir_emit_comp(proc, Token_NotEq, ptr, v_raw_nil);
  1618. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), ok);
  1619. irBlock *then = ir_new_block(proc, nullptr, "map.get.then");
  1620. irBlock *done = ir_new_block(proc, nullptr, "map.get.done");
  1621. ir_emit_if(proc, ok, then, done);
  1622. ir_start_block(proc, then);
  1623. {
  1624. // TODO(bill): mem copy it instead?
  1625. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  1626. irValue *value = ir_emit_conv(proc, ptr, ir_type(gep0));
  1627. ir_emit_store(proc, gep0, ir_emit_load(proc, value));
  1628. }
  1629. ir_emit_jump(proc, done);
  1630. ir_start_block(proc, done);
  1631. if (is_type_tuple(addr.map_result)) {
  1632. return ir_emit_load(proc, v);
  1633. } else {
  1634. irValue *single = ir_emit_struct_ep(proc, v, 0);
  1635. return ir_emit_load(proc, single);
  1636. }
  1637. } else if (addr.kind == irAddr_BitField) {
  1638. gbAllocator a = proc->module->allocator;
  1639. Type *bft = base_type(type_deref(ir_type(addr.addr)));
  1640. GB_ASSERT(is_type_bit_field(bft));
  1641. i32 value_index = addr.bit_field_value_index;
  1642. i32 offset = bft->BitField.offsets[value_index];
  1643. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  1644. i32 byte_index = offset / 8;
  1645. i32 bit_inset = offset % 8;
  1646. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  1647. if (size_in_bytes == 0) {
  1648. GB_ASSERT(size_in_bits == 0);
  1649. return ir_const_i32(a, 0);
  1650. }
  1651. Type *int_type = nullptr;
  1652. switch (size_in_bytes) {
  1653. case 1: int_type = t_u8; break;
  1654. case 2: int_type = t_u16; break;
  1655. case 4: int_type = t_u32; break;
  1656. case 8: int_type = t_u64; break;
  1657. case 16: int_type = t_u128; break;
  1658. }
  1659. GB_ASSERT(int_type != nullptr);
  1660. irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
  1661. bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(a, byte_index));
  1662. Type *int_ptr = make_type_pointer(a, int_type);
  1663. if (bit_inset == 0) {
  1664. irValue *v = ir_emit_load(proc, ir_emit_conv(proc, bytes, int_ptr));
  1665. i32 sa = 8*size_in_bytes - size_in_bits;
  1666. if (sa > 0) {
  1667. irValue *shift_amount = ir_const_int(a, sa);
  1668. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  1669. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  1670. }
  1671. return v;
  1672. }
  1673. GB_ASSERT(8 > bit_inset);
  1674. irValue *shift_amount = ir_value_constant(a, int_type, exact_value_i64(bit_inset));
  1675. irValue *first_byte = ir_emit_load(proc, bytes);
  1676. irValue *res = ir_emit_arith(proc, Token_Shr, first_byte, shift_amount, int_type);
  1677. irValue *remaining_bytes = ir_emit_load(proc, ir_emit_conv(proc, ir_emit_ptr_offset(proc, bytes, v_one), int_ptr));
  1678. remaining_bytes = ir_emit_arith(proc, Token_Shl, remaining_bytes, shift_amount, int_type);
  1679. return ir_emit_arith(proc, Token_Or, res, remaining_bytes, int_type);
  1680. }
  1681. Type *t = base_type(ir_type(addr.addr));
  1682. if (t->kind == Type_Proc) {
  1683. // NOTE(bill): Imported procedures don't require a load as they are pointers
  1684. return addr.addr;
  1685. }
  1686. return ir_emit_load(proc, addr.addr);
  1687. }
  1688. irValue *ir_addr_get_ptr(irProcedure *proc, irAddr addr) {
  1689. if (addr.addr == nullptr) {
  1690. GB_PANIC("Illegal addr -> nullptr");
  1691. return nullptr;
  1692. }
  1693. switch (addr.kind) {
  1694. case irAddr_Map:
  1695. case irAddr_BitField: {
  1696. irValue *v = ir_addr_load(proc, addr);
  1697. return ir_address_from_load_or_generate_local(proc, v);
  1698. }
  1699. }
  1700. return addr.addr;
  1701. }
  1702. irValue *ir_build_addr_ptr(irProcedure *proc, AstNode *expr) {
  1703. irAddr addr = ir_build_addr(proc, expr);
  1704. return ir_addr_get_ptr(proc, addr);
  1705. }
  1706. irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index);
  1707. irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index);
  1708. irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset) {
  1709. offset = ir_emit_conv(proc, offset, t_int);
  1710. return ir_emit(proc, ir_instr_ptr_offset(proc, ptr, offset));
  1711. }
  1712. irValue *ir_emit_unary_arith(irProcedure *proc, TokenKind op, irValue *x, Type *type) {
  1713. switch (op) {
  1714. case Token_Add:
  1715. return x;
  1716. case Token_Not: // Boolean not
  1717. case Token_Xor: // Bitwise not
  1718. case Token_Sub: // Bitwise Not
  1719. break;
  1720. case Token_Pointer:
  1721. GB_PANIC("This should be handled elsewhere");
  1722. break;
  1723. }
  1724. if (is_type_vector(ir_type(x))) {
  1725. ir_emit_comment(proc, str_lit("vector.arith.begin"));
  1726. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  1727. Type *tl = base_type(ir_type(x));
  1728. irValue *val = ir_address_from_load_or_generate_local(proc, x);
  1729. GB_ASSERT(is_type_vector(type));
  1730. Type *elem_type = base_type(type)->Vector.elem;
  1731. irValue *res = ir_add_local_generated(proc, type);
  1732. for (i32 i = 0; i < tl->Vector.count; i++) {
  1733. irValue *e = ir_emit_load(proc, ir_emit_array_epi(proc, val, i));
  1734. irValue *z = ir_emit_unary_arith(proc, op, e, elem_type);
  1735. ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
  1736. }
  1737. ir_emit_comment(proc, str_lit("vector.arith.end"));
  1738. return ir_emit_load(proc, res);
  1739. }
  1740. return ir_emit(proc, ir_instr_unary_op(proc, op, x, type));
  1741. }
  1742. irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type) {
  1743. Type *t_left = ir_type(left);
  1744. Type *t_right = ir_type(right);
  1745. if (is_type_vector(t_left) || is_type_vector(t_right)) {
  1746. ir_emit_comment(proc, str_lit("vector.arith.begin"));
  1747. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  1748. left = ir_emit_conv(proc, left, type);
  1749. right = ir_emit_conv(proc, right, type);
  1750. irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
  1751. irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
  1752. GB_ASSERT(is_type_vector(type));
  1753. Type *elem_type = base_type(type)->Vector.elem;
  1754. irValue *res = ir_add_local_generated(proc, type);
  1755. i64 count = base_type(type)->Vector.count;
  1756. for (i32 i = 0; i < count; i++) {
  1757. irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
  1758. irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
  1759. irValue *z = ir_emit_arith(proc, op, x, y, elem_type);
  1760. ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
  1761. }
  1762. ir_emit_comment(proc, str_lit("vector.arith.end"));
  1763. return ir_emit_load(proc, res);
  1764. }
  1765. if (is_type_complex(t_left)) {
  1766. ir_emit_comment(proc, str_lit("complex.arith.begin"));
  1767. Type *ft = base_complex_elem_type(t_left);
  1768. irValue *res = ir_add_local_generated(proc, type);
  1769. irValue *a = ir_emit_struct_ev(proc, left, 0);
  1770. irValue *b = ir_emit_struct_ev(proc, left, 1);
  1771. irValue *c = ir_emit_struct_ev(proc, right, 0);
  1772. irValue *d = ir_emit_struct_ev(proc, right, 1);
  1773. irValue *real = nullptr;
  1774. irValue *imag = nullptr;
  1775. switch (op) {
  1776. case Token_Add:
  1777. real = ir_emit_arith(proc, Token_Add, a, c, ft);
  1778. imag = ir_emit_arith(proc, Token_Add, b, d, ft);
  1779. break;
  1780. case Token_Sub:
  1781. real = ir_emit_arith(proc, Token_Sub, a, c, ft);
  1782. imag = ir_emit_arith(proc, Token_Sub, b, d, ft);
  1783. break;
  1784. case Token_Mul: {
  1785. irValue *x = ir_emit_arith(proc, Token_Mul, a, c, ft);
  1786. irValue *y = ir_emit_arith(proc, Token_Mul, b, d, ft);
  1787. real = ir_emit_arith(proc, Token_Sub, x, y, ft);
  1788. irValue *z = ir_emit_arith(proc, Token_Mul, b, c, ft);
  1789. irValue *w = ir_emit_arith(proc, Token_Mul, a, d, ft);
  1790. imag = ir_emit_arith(proc, Token_Add, z, w, ft);
  1791. break;
  1792. }
  1793. case Token_Quo: {
  1794. irValue *s1 = ir_emit_arith(proc, Token_Mul, c, c, ft);
  1795. irValue *s2 = ir_emit_arith(proc, Token_Mul, d, d, ft);
  1796. irValue *s = ir_emit_arith(proc, Token_Add, s1, s2, ft);
  1797. irValue *x = ir_emit_arith(proc, Token_Mul, a, c, ft);
  1798. irValue *y = ir_emit_arith(proc, Token_Mul, b, d, ft);
  1799. real = ir_emit_arith(proc, Token_Add, x, y, ft);
  1800. real = ir_emit_arith(proc, Token_Quo, real, s, ft);
  1801. irValue *z = ir_emit_arith(proc, Token_Mul, b, c, ft);
  1802. irValue *w = ir_emit_arith(proc, Token_Mul, a, d, ft);
  1803. imag = ir_emit_arith(proc, Token_Sub, z, w, ft);
  1804. imag = ir_emit_arith(proc, Token_Quo, imag, s, ft);
  1805. break;
  1806. }
  1807. }
  1808. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
  1809. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
  1810. ir_emit_comment(proc, str_lit("complex.end.begin"));
  1811. return ir_emit_load(proc, res);
  1812. }
  1813. if (op == Token_Add) {
  1814. if (is_type_pointer(t_left)) {
  1815. irValue *ptr = ir_emit_conv(proc, left, type);
  1816. irValue *offset = right;
  1817. return ir_emit_ptr_offset(proc, ptr, offset);
  1818. } else if (is_type_pointer(ir_type(right))) {
  1819. irValue *ptr = ir_emit_conv(proc, right, type);
  1820. irValue *offset = left;
  1821. return ir_emit_ptr_offset(proc, ptr, offset);
  1822. }
  1823. } else if (op == Token_Sub) {
  1824. if (is_type_pointer(t_left) && is_type_integer(t_right)) {
  1825. // ptr - int
  1826. irValue *ptr = ir_emit_conv(proc, left, type);
  1827. irValue *offset = ir_emit_unary_arith(proc, Token_Sub, right, t_int);
  1828. return ir_emit_ptr_offset(proc, ptr, offset);
  1829. } else if (is_type_pointer(t_left) && is_type_pointer(t_right)) {
  1830. GB_ASSERT(is_type_integer(type));
  1831. irModule *m = proc->module;
  1832. Type *ptr_type = base_type(t_left);
  1833. GB_ASSERT(!is_type_rawptr(ptr_type));
  1834. irValue *elem_size = ir_const_int(m->allocator, type_size_of(m->allocator, ptr_type->Pointer.elem));
  1835. irValue *x = ir_emit_conv(proc, ir_emit_conv(proc, left, t_uintptr), type);
  1836. irValue *y = ir_emit_conv(proc, ir_emit_conv(proc, right, t_uintptr), type);
  1837. irValue *diff = ir_emit_arith(proc, op, x, y, type);
  1838. return ir_emit_arith(proc, Token_Quo, diff, elem_size, type);
  1839. }
  1840. }
  1841. switch (op) {
  1842. case Token_Shl:
  1843. case Token_Shr:
  1844. left = ir_emit_conv(proc, left, type);
  1845. right = ir_emit_conv(proc, right, type);
  1846. break;
  1847. case Token_AndNot: {
  1848. // NOTE(bill): x &~ y == x & (~y) == x & (y ~ -1)
  1849. // NOTE(bill): "not" `x` == `x` "xor" `-1`
  1850. irValue *neg = ir_add_module_constant(proc->module, type, exact_value_i64(-1));
  1851. op = Token_Xor;
  1852. right = ir_emit_arith(proc, op, right, neg, type);
  1853. GB_ASSERT(right->Instr.kind == irInstr_BinaryOp);
  1854. right->Instr.BinaryOp.type = type;
  1855. op = Token_And;
  1856. } /* fallthrough */
  1857. case Token_Add:
  1858. case Token_Sub:
  1859. case Token_Mul:
  1860. case Token_Quo:
  1861. case Token_Mod:
  1862. case Token_ModMod:
  1863. case Token_And:
  1864. case Token_Or:
  1865. case Token_Xor:
  1866. left = ir_emit_conv(proc, left, type);
  1867. right = ir_emit_conv(proc, right, type);
  1868. break;
  1869. }
  1870. if (op == Token_ModMod) {
  1871. irValue *n = left;
  1872. irValue *m = right;
  1873. if (is_type_unsigned(type)) {
  1874. return ir_emit_arith(proc, Token_Mod, n, m, type);
  1875. }
  1876. irValue *a = ir_emit_arith(proc, Token_Mod, n, m, type);
  1877. irValue *b = ir_emit_arith(proc, Token_Add, a, m, type);
  1878. return ir_emit_arith(proc, Token_Mod, b, m, type);
  1879. }
  1880. if (is_type_i128_or_u128(type)) {
  1881. // IMPORTANT NOTE(bill): LLVM is goddamn buggy!
  1882. bool is_unsigned = is_type_unsigned(type);
  1883. char *name = nullptr;
  1884. if (op == Token_Quo) {
  1885. name = cast(char *)(is_unsigned ? "__udivti3" : "__divti3");
  1886. } else if (op == Token_Mod) {
  1887. name = cast(char *)(is_unsigned ? "__umodti3" : "__modti3");
  1888. }
  1889. if (name != nullptr) {
  1890. irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 2);
  1891. args[0] = left;
  1892. args[1] = right;
  1893. return ir_emit_global_call(proc, name, args, 2);
  1894. }
  1895. }
  1896. return ir_emit(proc, ir_instr_binary_op(proc, op, left, right, type));
  1897. }
  1898. irValue *ir_emit_union_tag_ptr(irProcedure *proc, irValue *u) {
  1899. Type *t = ir_type(u);
  1900. GB_ASSERT_MSG(is_type_pointer(t) &&
  1901. is_type_union(type_deref(t)), "%s", type_to_string(t));
  1902. irValue *tag_ptr = ir_emit(proc, ir_instr_union_tag_ptr(proc, u));
  1903. return tag_ptr;
  1904. }
  1905. irValue *ir_emit_union_tag_value(irProcedure *proc, irValue *u) {
  1906. Type *t = ir_type(u);
  1907. GB_ASSERT(is_type_union(t));
  1908. GB_ASSERT(are_types_identical(t, ir_type(u)));
  1909. return ir_emit(proc, ir_instr_union_tag_value(proc, u));
  1910. }
  1911. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right);
  1912. irValue *ir_emit_comp_against_nil(irProcedure *proc, TokenKind op_kind, irValue *x) {
  1913. Type *t = ir_type(x);
  1914. if (is_type_any(t)) {
  1915. irValue *data = ir_emit_struct_ev(proc, x, 0);
  1916. irValue *ti = ir_emit_struct_ev(proc, x, 1);
  1917. if (op_kind == Token_CmpEq) {
  1918. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  1919. irValue *b = ir_emit_comp(proc, Token_CmpEq, ti, v_raw_nil);
  1920. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  1921. } else if (op_kind == Token_NotEq) {
  1922. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  1923. irValue *b = ir_emit_comp(proc, Token_NotEq, ti, v_raw_nil);
  1924. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  1925. }
  1926. } else if (is_type_slice(t)) {
  1927. irValue *data = ir_emit_struct_ev(proc, x, 0);
  1928. irValue *cap = ir_emit_struct_ev(proc, x, 2);
  1929. if (op_kind == Token_CmpEq) {
  1930. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  1931. irValue *b = ir_emit_comp(proc, Token_CmpEq, cap, v_zero);
  1932. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  1933. } else if (op_kind == Token_NotEq) {
  1934. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  1935. irValue *b = ir_emit_comp(proc, Token_NotEq, cap, v_zero);
  1936. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  1937. }
  1938. } else if (is_type_dynamic_array(t)) {
  1939. irValue *data = ir_emit_struct_ev(proc, x, 0);
  1940. irValue *cap = ir_emit_struct_ev(proc, x, 2);
  1941. if (op_kind == Token_CmpEq) {
  1942. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  1943. irValue *b = ir_emit_comp(proc, Token_CmpEq, cap, v_zero);
  1944. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  1945. } else if (op_kind == Token_NotEq) {
  1946. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  1947. irValue *b = ir_emit_comp(proc, Token_NotEq, cap, v_zero);
  1948. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  1949. }
  1950. } else if (is_type_map(t)) {
  1951. irValue *hashes = ir_emit_struct_ev(proc, x, 0);
  1952. irValue *entries = ir_emit_struct_ev(proc, x, 1);
  1953. irValue *a = ir_emit_comp_against_nil(proc, op_kind, hashes);
  1954. irValue *b = ir_emit_comp_against_nil(proc, op_kind, entries);
  1955. if (op_kind == Token_CmpEq) {
  1956. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  1957. } else if (op_kind == Token_NotEq) {
  1958. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  1959. }
  1960. } else if (is_type_union(t)) {
  1961. irValue *tag = ir_emit_union_tag_value(proc, x);
  1962. return ir_emit_comp(proc, op_kind, tag, v_zero);
  1963. }
  1964. return nullptr;
  1965. }
  1966. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right) {
  1967. Type *a = base_type(ir_type(left));
  1968. Type *b = base_type(ir_type(right));
  1969. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  1970. irValue *nil_check = nullptr;
  1971. if (left->kind == irValue_Nil) {
  1972. nil_check = ir_emit_comp_against_nil(proc, op_kind, right);
  1973. } else if (right->kind == irValue_Nil) {
  1974. nil_check = ir_emit_comp_against_nil(proc, op_kind, left);
  1975. }
  1976. if (nil_check != nullptr) {
  1977. return nil_check;
  1978. }
  1979. if (are_types_identical(a, b)) {
  1980. // NOTE(bill): No need for a conversion
  1981. } else if (left->kind == irValue_Constant || left->kind == irValue_Nil) {
  1982. left = ir_emit_conv(proc, left, ir_type(right));
  1983. } else if (right->kind == irValue_Constant || right->kind == irValue_Nil) {
  1984. right = ir_emit_conv(proc, right, ir_type(left));
  1985. } else {
  1986. gbAllocator a = proc->module->allocator;
  1987. i64 ls = type_size_of(a, ir_type(left));
  1988. i64 rs = type_size_of(a, ir_type(right));
  1989. if (ls < rs) {
  1990. left = ir_emit_conv(proc, left, ir_type(right));
  1991. } else if (ls > rs) {
  1992. right = ir_emit_conv(proc, right, ir_type(left));
  1993. } else {
  1994. right = ir_emit_conv(proc, right, ir_type(left));
  1995. }
  1996. }
  1997. Type *result = t_bool;
  1998. if (is_type_vector(a)) {
  1999. result = make_type_vector(proc->module->allocator, t_bool, a->Vector.count);
  2000. }
  2001. if (is_type_vector(a)) {
  2002. ir_emit_comment(proc, str_lit("vector.comp.begin"));
  2003. Type *tl = base_type(a);
  2004. irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
  2005. irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
  2006. GB_ASSERT(is_type_vector(result));
  2007. Type *elem_type = base_type(result)->Vector.elem;
  2008. irValue *res = ir_add_local_generated(proc, result);
  2009. for (i32 i = 0; i < tl->Vector.count; i++) {
  2010. irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
  2011. irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
  2012. irValue *z = ir_emit_comp(proc, op_kind, x, y);
  2013. ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
  2014. }
  2015. ir_emit_comment(proc, str_lit("vector.comp.end"));
  2016. return ir_emit_load(proc, res);
  2017. }
  2018. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, left, right, result));
  2019. }
  2020. irValue *ir_emit_array_ep(irProcedure *proc, irValue *s, irValue *index) {
  2021. GB_ASSERT(index != nullptr);
  2022. Type *t = ir_type(s);
  2023. GB_ASSERT(is_type_pointer(t));
  2024. Type *st = base_type(type_deref(t));
  2025. GB_ASSERT_MSG(is_type_array(st) || is_type_vector(st), "%s", type_to_string(st));
  2026. // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
  2027. index = ir_emit_conv(proc, index, t_i32);
  2028. return ir_emit(proc, ir_instr_array_element_ptr(proc, s, index));
  2029. }
  2030. irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index) {
  2031. return ir_emit_array_ep(proc, s, ir_const_i32(proc->module->allocator, index));
  2032. }
  2033. irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index) {
  2034. gbAllocator a = proc->module->allocator;
  2035. Type *t = base_type(type_deref(ir_type(s)));
  2036. Type *result_type = nullptr;
  2037. if (is_type_struct(t)) {
  2038. result_type = make_type_pointer(a, t->Struct.fields[index]->type);
  2039. } else if (is_type_union(t)) {
  2040. GB_ASSERT(index == -1);
  2041. return ir_emit_union_tag_ptr(proc, s);
  2042. } else if (is_type_tuple(t)) {
  2043. GB_ASSERT(t->Tuple.variables.count > 0);
  2044. result_type = make_type_pointer(a, t->Tuple.variables[index]->type);
  2045. } else if (is_type_complex(t)) {
  2046. Type *ft = base_complex_elem_type(t);
  2047. switch (index) {
  2048. case 0: result_type = make_type_pointer(a, ft); break;
  2049. case 1: result_type = make_type_pointer(a, ft); break;
  2050. }
  2051. } else if (is_type_slice(t)) {
  2052. switch (index) {
  2053. case 0: result_type = make_type_pointer(a, make_type_pointer(a, t->Slice.elem)); break;
  2054. case 1: result_type = make_type_pointer(a, t_int); break;
  2055. case 2: result_type = make_type_pointer(a, t_int); break;
  2056. }
  2057. } else if (is_type_string(t)) {
  2058. switch (index) {
  2059. case 0: result_type = make_type_pointer(a, t_u8_ptr); break;
  2060. case 1: result_type = make_type_pointer(a, t_int); break;
  2061. }
  2062. } else if (is_type_any(t)) {
  2063. switch (index) {
  2064. case 0: result_type = make_type_pointer(a, t_rawptr); break;
  2065. case 1: result_type = make_type_pointer(a, t_type_info_ptr); break;
  2066. }
  2067. } else if (is_type_dynamic_array(t)) {
  2068. switch (index) {
  2069. case 0: result_type = make_type_pointer(a, make_type_pointer(a, t->DynamicArray.elem)); break;
  2070. case 1: result_type = t_int_ptr; break;
  2071. case 2: result_type = t_int_ptr; break;
  2072. case 3: result_type = t_allocator_ptr; break;
  2073. }
  2074. } else if (is_type_map(t)) {
  2075. generate_map_internal_types(a, t);
  2076. Type *gst = t->Map.generated_struct_type;
  2077. switch (index) {
  2078. case 0: result_type = make_type_pointer(a, gst->Struct.fields[0]->type); break;
  2079. case 1: result_type = make_type_pointer(a, gst->Struct.fields[1]->type); break;
  2080. }
  2081. }else {
  2082. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(ir_type(s)), index);
  2083. }
  2084. GB_ASSERT(result_type != nullptr);
  2085. return ir_emit(proc, ir_instr_struct_element_ptr(proc, s, index, result_type));
  2086. }
  2087. irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index) {
  2088. // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
  2089. gbAllocator a = proc->module->allocator;
  2090. Type *t = base_type(ir_type(s));
  2091. Type *result_type = nullptr;
  2092. switch (t->kind) {
  2093. case Type_Basic:
  2094. switch (t->Basic.kind) {
  2095. case Basic_string:
  2096. switch (index) {
  2097. case 0: result_type = t_u8_ptr; break;
  2098. case 1: result_type = t_int; break;
  2099. }
  2100. break;
  2101. case Basic_any:
  2102. switch (index) {
  2103. case 0: result_type = t_rawptr; break;
  2104. case 1: result_type = t_type_info_ptr; break;
  2105. }
  2106. break;
  2107. case Basic_complex64: case Basic_complex128:
  2108. {
  2109. Type *ft = base_complex_elem_type(t);
  2110. switch (index) {
  2111. case 0: result_type = ft; break;
  2112. case 1: result_type = ft; break;
  2113. }
  2114. break;
  2115. }
  2116. }
  2117. break;
  2118. case Type_Struct:
  2119. result_type = t->Struct.fields[index]->type;
  2120. break;
  2121. case Type_Union:
  2122. GB_ASSERT(index == -1);
  2123. return ir_emit_union_tag_value(proc, s);
  2124. case Type_Tuple:
  2125. GB_ASSERT(t->Tuple.variables.count > 0);
  2126. result_type = t->Tuple.variables[index]->type;
  2127. break;
  2128. case Type_Slice:
  2129. switch (index) {
  2130. case 0: result_type = make_type_pointer(a, t->Slice.elem); break;
  2131. case 1: result_type = t_int; break;
  2132. case 2: result_type = t_int; break;
  2133. }
  2134. break;
  2135. case Type_DynamicArray:
  2136. switch (index) {
  2137. case 0: result_type = make_type_pointer(a, t->DynamicArray.elem); break;
  2138. case 1: result_type = t_int; break;
  2139. case 2: result_type = t_int; break;
  2140. case 3: result_type = t_allocator; break;
  2141. }
  2142. break;
  2143. case Type_Map: {
  2144. generate_map_internal_types(a, t);
  2145. Type *gst = t->Map.generated_struct_type;
  2146. switch (index) {
  2147. case 0: result_type = gst->Struct.fields[0]->type; break;
  2148. case 1: result_type = gst->Struct.fields[1]->type; break;
  2149. }
  2150. break;
  2151. }
  2152. default:
  2153. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(ir_type(s)), index);
  2154. break;
  2155. }
  2156. GB_ASSERT(result_type != nullptr);
  2157. return ir_emit(proc, ir_instr_struct_extract_value(proc, s, index, result_type));
  2158. }
  2159. irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel) {
  2160. GB_ASSERT(sel.index.count > 0);
  2161. Type *type = type_deref(ir_type(e));
  2162. gbAllocator a = proc->module->allocator;
  2163. for_array(i, sel.index) {
  2164. i32 index = cast(i32)sel.index[i];
  2165. if (is_type_pointer(type)) {
  2166. type = type_deref(type);
  2167. e = ir_emit_load(proc, e);
  2168. e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
  2169. }
  2170. type = core_type(type);
  2171. if (is_type_raw_union(type)) {
  2172. type = type->Struct.fields[index]->type;
  2173. e = ir_emit_conv(proc, e, make_type_pointer(a, type));
  2174. } else if (is_type_struct(type)) {
  2175. type = type->Struct.fields[index]->type;
  2176. e = ir_emit_struct_ep(proc, e, index);
  2177. } else if (type->kind == Type_Union) {
  2178. GB_ASSERT(index == -1);
  2179. type = t_type_info_ptr;
  2180. e = ir_emit_struct_ep(proc, e, index);
  2181. } else if (type->kind == Type_Tuple) {
  2182. type = type->Tuple.variables[index]->type;
  2183. e = ir_emit_struct_ep(proc, e, index);
  2184. } else if (type->kind == Type_Basic) {
  2185. switch (type->Basic.kind) {
  2186. case Basic_any: {
  2187. if (index == 0) {
  2188. type = t_rawptr;
  2189. } else if (index == 1) {
  2190. type = t_type_info_ptr;
  2191. }
  2192. e = ir_emit_struct_ep(proc, e, index);
  2193. break;
  2194. }
  2195. case Basic_string:
  2196. e = ir_emit_struct_ep(proc, e, index);
  2197. break;
  2198. default:
  2199. GB_PANIC("un-gep-able type");
  2200. break;
  2201. }
  2202. } else if (type->kind == Type_Slice) {
  2203. e = ir_emit_struct_ep(proc, e, index);
  2204. } else if (type->kind == Type_DynamicArray) {
  2205. e = ir_emit_struct_ep(proc, e, index);
  2206. } else if (type->kind == Type_Vector) {
  2207. e = ir_emit_array_epi(proc, e, index);
  2208. } else if (type->kind == Type_Array) {
  2209. e = ir_emit_array_epi(proc, e, index);
  2210. } else if (type->kind == Type_Map) {
  2211. e = ir_emit_struct_ep(proc, e, 1);
  2212. switch (index) {
  2213. case 0: e = ir_emit_struct_ep(proc, e, 1); break; // count
  2214. case 1: e = ir_emit_struct_ep(proc, e, 2); break; // capacity
  2215. case 2: e = ir_emit_struct_ep(proc, e, 3); break; // allocator
  2216. }
  2217. } else {
  2218. GB_PANIC("un-gep-able type %s", type_to_string(type));
  2219. }
  2220. }
  2221. return e;
  2222. }
  2223. irValue *ir_emit_deep_field_ev(irProcedure *proc, irValue *e, Selection sel) {
  2224. GB_ASSERT(sel.index.count > 0);
  2225. Type *type = ir_type(e);
  2226. for_array(i, sel.index) {
  2227. i32 index = cast(i32)sel.index[i];
  2228. if (is_type_pointer(type)) {
  2229. type = type_deref(type);
  2230. e = ir_emit_load(proc, e);
  2231. e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
  2232. }
  2233. type = base_type(type);
  2234. if (is_type_raw_union(type)) {
  2235. GB_PANIC("TODO(bill): IS THIS EVEN CORRECT?");
  2236. type = type->Struct.fields[index]->type;
  2237. e = ir_emit_conv(proc, e, type);
  2238. } else if (type->kind == Type_Map) {
  2239. e = ir_emit_struct_ev(proc, e, 1);
  2240. switch (index) {
  2241. case 0: e = ir_emit_struct_ev(proc, e, 1); break; // count
  2242. case 1: e = ir_emit_struct_ev(proc, e, 2); break; // capacity
  2243. case 2: e = ir_emit_struct_ev(proc, e, 3); break; // allocator
  2244. }
  2245. } else {
  2246. e = ir_emit_struct_ev(proc, e, index);
  2247. }
  2248. }
  2249. return e;
  2250. }
  2251. irValue *ir_array_elem(irProcedure *proc, irValue *array) {
  2252. return ir_emit_array_ep(proc, array, v_zero32);
  2253. }
  2254. irValue *ir_array_len(irProcedure *proc, irValue *array) {
  2255. Type *t = base_type(ir_type(array));
  2256. GB_ASSERT(t->kind == Type_Array);
  2257. return ir_const_int(proc->module->allocator, t->Array.count);
  2258. }
  2259. irValue *ir_vector_elem(irProcedure *proc, irValue *vector) {
  2260. return ir_emit_array_ep(proc, vector, v_one32);
  2261. }
  2262. irValue *ir_slice_elem(irProcedure *proc, irValue *slice) {
  2263. Type *t = base_type(ir_type(slice));
  2264. GB_ASSERT(t->kind == Type_Slice);
  2265. return ir_emit_struct_ev(proc, slice, 0);
  2266. }
  2267. irValue *ir_slice_count(irProcedure *proc, irValue *slice) {
  2268. Type *t = base_type(ir_type(slice));
  2269. GB_ASSERT(t->kind == Type_Slice);
  2270. return ir_emit_struct_ev(proc, slice, 1);
  2271. }
  2272. irValue *ir_slice_capacity(irProcedure *proc, irValue *slice) {
  2273. Type *t = base_type(ir_type(slice));
  2274. GB_ASSERT(t->kind == Type_Slice);
  2275. return ir_emit_struct_ev(proc, slice, 2);
  2276. }
  2277. irValue *ir_dynamic_array_elem(irProcedure *proc, irValue *da) {
  2278. Type *t = ir_type(da);
  2279. GB_ASSERT(t->kind == Type_DynamicArray);
  2280. return ir_emit_struct_ev(proc, da, 0);
  2281. }
  2282. irValue *ir_dynamic_array_count(irProcedure *proc, irValue *da) {
  2283. Type *t = base_type(ir_type(da));
  2284. GB_ASSERT_MSG(t->kind == Type_DynamicArray, "%s", type_to_string(t));
  2285. return ir_emit_struct_ev(proc, da, 1);
  2286. }
  2287. irValue *ir_dynamic_array_capacity(irProcedure *proc, irValue *da) {
  2288. Type *t = base_type(ir_type(da));
  2289. GB_ASSERT(t->kind == Type_DynamicArray);
  2290. return ir_emit_struct_ev(proc, da, 2);
  2291. }
  2292. irValue *ir_dynamic_array_allocator(irProcedure *proc, irValue *da) {
  2293. Type *t = base_type(ir_type(da));
  2294. GB_ASSERT(t->kind == Type_DynamicArray);
  2295. return ir_emit_struct_ev(proc, da, 3);
  2296. }
  2297. irValue *ir_string_elem(irProcedure *proc, irValue *string) {
  2298. Type *t = base_type(ir_type(string));
  2299. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  2300. return ir_emit_struct_ev(proc, string, 0);
  2301. }
  2302. irValue *ir_string_len(irProcedure *proc, irValue *string) {
  2303. Type *t = base_type(ir_type(string));
  2304. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  2305. return ir_emit_struct_ev(proc, string, 1);
  2306. }
  2307. void ir_fill_slice(irProcedure *proc, irValue *slice_ptr, irValue *data, irValue *len, irValue *cap) {
  2308. Type *t = ir_type(slice_ptr);
  2309. GB_ASSERT(is_type_pointer(t));
  2310. t = type_deref(t);
  2311. GB_ASSERT(is_type_slice(t));
  2312. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 0), data);
  2313. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 1), len);
  2314. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 2), cap);
  2315. }
  2316. void ir_fill_string(irProcedure *proc, irValue *string_ptr, irValue *data, irValue *len) {
  2317. Type *t = ir_type(string_ptr);
  2318. GB_ASSERT(is_type_pointer(t));
  2319. t = type_deref(t);
  2320. GB_ASSERT(is_type_string(t));
  2321. ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 0), data);
  2322. ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 1), len);
  2323. }
  2324. irValue *ir_emit_string(irProcedure *proc, irValue *elem, irValue *len) {
  2325. irValue *str = ir_add_local_generated(proc, t_string);
  2326. ir_fill_string(proc, str, elem, len);
  2327. return ir_emit_load(proc, str);
  2328. }
  2329. irValue *ir_add_local_slice(irProcedure *proc, Type *slice_type, irValue *base, irValue *low, irValue *high, irValue *max) {
  2330. // TODO(bill): array bounds checking for slice creation
  2331. // TODO(bill): check that low < high <= max
  2332. gbAllocator a = proc->module->allocator;
  2333. Type *bt = base_type(ir_type(base));
  2334. if (low == nullptr) {
  2335. low = v_zero;
  2336. }
  2337. if (high == nullptr) {
  2338. switch (bt->kind) {
  2339. case Type_Array: high = ir_array_len(proc, base); break;
  2340. case Type_Slice: high = ir_slice_count(proc, base); break;
  2341. case Type_Pointer: high = v_one; break;
  2342. }
  2343. }
  2344. if (max == nullptr) {
  2345. switch (bt->kind) {
  2346. case Type_Array: high = ir_array_len(proc, base); break;
  2347. case Type_Slice: high = ir_slice_capacity(proc, base); break;
  2348. case Type_Pointer: high = v_one; break;
  2349. }
  2350. }
  2351. irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  2352. irValue *cap = ir_emit_arith(proc, Token_Sub, max, low, t_int);
  2353. irValue *elem = nullptr;
  2354. switch (bt->kind) {
  2355. case Type_Array: elem = ir_array_elem(proc, base); break;
  2356. case Type_Slice: elem = ir_slice_elem(proc, base); break;
  2357. case Type_Pointer: elem = ir_emit_load(proc, base); break;
  2358. }
  2359. elem = ir_emit_ptr_offset(proc, elem, low);
  2360. irValue *slice = ir_add_local_generated(proc, slice_type);
  2361. ir_fill_slice(proc, slice, elem, len, cap);
  2362. return slice;
  2363. }
  2364. irValue *ir_find_or_add_entity_string(irModule *m, String str) {
  2365. irValue **found = map_get(&m->const_strings, hash_string(str));
  2366. if (found != nullptr) {
  2367. return *found;
  2368. }
  2369. irValue *v = ir_const_string(m->allocator, str);
  2370. map_set(&m->const_strings, hash_string(str), v);
  2371. return v;
  2372. }
  2373. irValue *ir_const_union_tag(gbAllocator a, Type *u, Type *v) {
  2374. return ir_value_constant(a, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  2375. }
  2376. String ir_lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  2377. Type *prev_src = src;
  2378. // Type *prev_dst = dst;
  2379. src = base_type(type_deref(src));
  2380. // dst = base_type(type_deref(dst));
  2381. bool src_is_ptr = src != prev_src;
  2382. // bool dst_is_ptr = dst != prev_dst;
  2383. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  2384. for_array(i, src->Struct.fields) {
  2385. Entity *f = src->Struct.fields[i];
  2386. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  2387. if (are_types_identical(dst, f->type)) {
  2388. return f->token.string;
  2389. }
  2390. if (src_is_ptr && is_type_pointer(dst)) {
  2391. if (are_types_identical(type_deref(dst), f->type)) {
  2392. return f->token.string;
  2393. }
  2394. }
  2395. if (is_type_struct(f->type)) {
  2396. String name = ir_lookup_subtype_polymorphic_field(info, dst, f->type);
  2397. if (name.len > 0) {
  2398. return name;
  2399. }
  2400. }
  2401. }
  2402. }
  2403. return str_lit("");
  2404. }
  2405. irValue *ir_emit_ptr_to_uintptr(irProcedure *proc, irValue *value, Type *t, bool allow_type_type = false) {
  2406. Type *vt = core_type(ir_type(value));
  2407. GB_ASSERT(is_type_pointer(vt));
  2408. if (allow_type_type) {
  2409. GB_ASSERT(is_type_uintptr(core_type(t)));
  2410. } else {
  2411. GB_ASSERT(is_type_uintptr(core_type(t)));
  2412. }
  2413. return ir_emit(proc, ir_instr_conv(proc, irConv_ptrtoint, value, vt, t));
  2414. }
  2415. irValue *ir_emit_uintptr_to_ptr(irProcedure *proc, irValue *value, Type *t) {
  2416. Type *vt = core_type(ir_type(value));
  2417. GB_ASSERT(is_type_uintptr(vt));
  2418. GB_ASSERT(is_type_pointer(core_type(t)));
  2419. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, value, vt, t));
  2420. }
  2421. irValue *ir_emit_conv(irProcedure *proc, irValue *value, Type *t) {
  2422. Type *src_type = ir_type(value);
  2423. if (are_types_identical(t, src_type)) {
  2424. return value;
  2425. }
  2426. Type *src = core_type(src_type);
  2427. Type *dst = core_type(t);
  2428. // if (is_type_untyped_nil(src) && type_has_nil(dst)) {
  2429. if (is_type_untyped_nil(src)) {
  2430. return ir_value_nil(proc->module->allocator, t);
  2431. }
  2432. if (is_type_untyped_undef(src)) {
  2433. return ir_value_undef(proc->module->allocator, t);
  2434. }
  2435. if (value->kind == irValue_Constant) {
  2436. if (is_type_any(dst)) {
  2437. irValue *default_value = ir_add_local_generated(proc, default_type(src_type));
  2438. ir_emit_store(proc, default_value, value);
  2439. return ir_emit_conv(proc, ir_emit_load(proc, default_value), t_any);
  2440. } else if (dst->kind == Type_Basic) {
  2441. ExactValue ev = value->Constant.value;
  2442. if (is_type_float(dst)) {
  2443. ev = exact_value_to_float(ev);
  2444. } else if (is_type_complex(dst)) {
  2445. ev = exact_value_to_complex(ev);
  2446. } else if (is_type_string(dst)) {
  2447. // Handled elsewhere
  2448. GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  2449. } else if (is_type_integer(dst)) {
  2450. ev = exact_value_to_integer(ev);
  2451. } else if (is_type_pointer(dst)) {
  2452. // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect `null`
  2453. irValue *i = ir_add_module_constant(proc->module, t_uint, ev);
  2454. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, i, t_uint, dst));
  2455. }
  2456. return ir_add_module_constant(proc->module, t, ev);
  2457. }
  2458. }
  2459. if (are_types_identical(src, dst)) {
  2460. if (!are_types_identical(src_type, t)) {
  2461. return ir_emit_transmute(proc, value, t);
  2462. }
  2463. return value;
  2464. }
  2465. // integer -> integer
  2466. if (is_type_integer(src) && is_type_integer(dst)) {
  2467. GB_ASSERT(src->kind == Type_Basic &&
  2468. dst->kind == Type_Basic);
  2469. i64 sz = type_size_of(proc->module->allocator, default_type(src));
  2470. i64 dz = type_size_of(proc->module->allocator, default_type(dst));
  2471. irConvKind kind = irConv_trunc;
  2472. if (dz < sz) {
  2473. kind = irConv_trunc;
  2474. } else if (dz == sz) {
  2475. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  2476. // NOTE(bill): Copy the value just for type correctness
  2477. kind = irConv_bitcast;
  2478. } else if (dz > sz) {
  2479. if (is_type_unsigned(src)) {
  2480. kind = irConv_zext; // zero extent
  2481. } else {
  2482. kind = irConv_sext; // sign extent
  2483. }
  2484. }
  2485. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  2486. }
  2487. // boolean -> integer
  2488. if (is_type_boolean(src) && is_type_integer(dst)) {
  2489. return ir_emit(proc, ir_instr_conv(proc, irConv_zext, value, src_type, t));
  2490. }
  2491. // integer -> boolean
  2492. if (is_type_integer(src) && is_type_boolean(dst)) {
  2493. return ir_emit_comp(proc, Token_NotEq, value, v_zero);
  2494. }
  2495. // float -> float
  2496. if (is_type_float(src) && is_type_float(dst)) {
  2497. gbAllocator a = proc->module->allocator;
  2498. i64 sz = type_size_of(proc->module->allocator, src);
  2499. i64 dz = type_size_of(proc->module->allocator, dst);
  2500. if (sz == 2) {
  2501. switch (dz) {
  2502. case 2: return value;
  2503. case 4: {
  2504. irValue **args = gb_alloc_array(a, irValue *, 1);
  2505. args[0] = value;
  2506. return ir_emit_global_call(proc, "__gnu_h2f_ieee", args, 1);
  2507. break;
  2508. }
  2509. case 8: {
  2510. irValue **args = gb_alloc_array(a, irValue *, 1);
  2511. args[0] = value;
  2512. return ir_emit_global_call(proc, "__f16_to_f64", args, 1);
  2513. break;
  2514. }
  2515. }
  2516. } else if (dz == 2) {
  2517. switch (sz) {
  2518. case 2: return value;
  2519. case 4: {
  2520. irValue **args = gb_alloc_array(a, irValue *, 1);
  2521. args[0] = value;
  2522. return ir_emit_global_call(proc, "__gnu_f2h_ieee", args, 1);
  2523. break;
  2524. }
  2525. case 8: {
  2526. irValue **args = gb_alloc_array(a, irValue *, 1);
  2527. args[0] = value;
  2528. return ir_emit_global_call(proc, "__truncdfhf2", args, 1);
  2529. break;
  2530. }
  2531. }
  2532. }
  2533. irConvKind kind = irConv_fptrunc;
  2534. if (dz >= sz) {
  2535. kind = irConv_fpext;
  2536. }
  2537. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  2538. }
  2539. if (is_type_complex(src) && is_type_complex(dst)) {
  2540. Type *ft = base_complex_elem_type(dst);
  2541. irValue *gen = ir_add_local_generated(proc, dst);
  2542. irValue *real = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  2543. irValue *imag = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  2544. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), real);
  2545. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 1), imag);
  2546. return ir_emit_load(proc, gen);
  2547. }
  2548. // float <-> integer
  2549. if (is_type_float(src) && is_type_integer(dst)) {
  2550. irConvKind kind = irConv_fptosi;
  2551. if (is_type_unsigned(dst)) {
  2552. kind = irConv_fptoui;
  2553. }
  2554. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  2555. }
  2556. if (is_type_integer(src) && is_type_float(dst)) {
  2557. irConvKind kind = irConv_sitofp;
  2558. if (is_type_unsigned(src)) {
  2559. kind = irConv_uitofp;
  2560. }
  2561. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  2562. }
  2563. // Pointer <-> uintptr
  2564. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2565. return ir_emit_ptr_to_uintptr(proc, value, t);
  2566. }
  2567. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2568. return ir_emit_uintptr_to_ptr(proc, value, t);
  2569. }
  2570. if (is_type_union(dst)) {
  2571. for_array(i, dst->Union.variants) {
  2572. Type *vt = dst->Union.variants[i];
  2573. if (are_types_identical(vt, src_type)) {
  2574. ir_emit_comment(proc, str_lit("union - child to parent"));
  2575. gbAllocator a = proc->module->allocator;
  2576. irValue *parent = ir_add_local_generated(proc, t);
  2577. irValue *underlying = ir_emit_conv(proc, parent, make_type_pointer(a, vt));
  2578. ir_emit_store(proc, underlying, value);
  2579. irValue *tag_ptr = ir_emit_union_tag_ptr(proc, parent);
  2580. ir_emit_store(proc, tag_ptr, ir_const_union_tag(a, t, src_type));
  2581. return ir_emit_load(proc, parent);
  2582. }
  2583. }
  2584. }
  2585. // NOTE(bill): This has to be done before `Pointer <-> Pointer` as it's
  2586. // subtype polymorphism casting
  2587. if (check_is_assignable_to_using_subtype(src_type, t)) {
  2588. Type *st = type_deref(src_type);
  2589. Type *pst = st;
  2590. st = type_deref(st);
  2591. bool st_is_ptr = st != pst;
  2592. st = base_type(st);
  2593. Type *dt = t;
  2594. bool dt_is_ptr = is_type_pointer(dt);
  2595. GB_ASSERT(is_type_struct(st) || is_type_union(st));
  2596. String field_name = ir_lookup_subtype_polymorphic_field(proc->module->info, t, st);
  2597. // gb_printf("field_name: %.*s\n", LIT(field_name));
  2598. if (field_name.len > 0) {
  2599. // NOTE(bill): It can be casted
  2600. Selection sel = lookup_field(proc->module->allocator, st, field_name, false);
  2601. if (sel.entity != nullptr) {
  2602. ir_emit_comment(proc, str_lit("cast - polymorphism"));
  2603. if (st_is_ptr) {
  2604. irValue *res = ir_emit_deep_field_gep(proc, value, sel);
  2605. if (!dt_is_ptr) {
  2606. res = ir_emit_load(proc, res);
  2607. }
  2608. return res;
  2609. } else {
  2610. if (is_type_pointer(ir_type(value))) {
  2611. if (!dt_is_ptr) {
  2612. value = ir_emit_load(proc, value);
  2613. } else {
  2614. value = ir_emit_deep_field_gep(proc, value, sel);
  2615. return ir_emit_load(proc, value);
  2616. }
  2617. }
  2618. return ir_emit_deep_field_ev(proc, value, sel);
  2619. }
  2620. }
  2621. }
  2622. }
  2623. // Pointer <-> Pointer
  2624. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2625. return ir_emit_bitcast(proc, value, t);
  2626. }
  2627. // proc <-> proc
  2628. if (is_type_proc(src) && is_type_proc(dst)) {
  2629. return ir_emit_bitcast(proc, value, t);
  2630. }
  2631. // pointer -> proc
  2632. if (is_type_pointer(src) && is_type_proc(dst)) {
  2633. return ir_emit_bitcast(proc, value, t);
  2634. }
  2635. // proc -> pointer
  2636. if (is_type_proc(src) && is_type_pointer(dst)) {
  2637. return ir_emit_bitcast(proc, value, t);
  2638. }
  2639. // []byte/[]u8 <-> string
  2640. if (is_type_u8_slice(src) && is_type_string(dst)) {
  2641. irValue *elem = ir_slice_elem(proc, value);
  2642. irValue *len = ir_slice_count(proc, value);
  2643. return ir_emit_string(proc, elem, len);
  2644. }
  2645. if (is_type_string(src) && is_type_u8_slice(dst)) {
  2646. irValue *elem = ir_string_elem(proc, value);
  2647. irValue *elem_ptr = ir_add_local_generated(proc, ir_type(elem));
  2648. ir_emit_store(proc, elem_ptr, elem);
  2649. irValue *len = ir_string_len(proc, value);
  2650. irValue *cap = len;
  2651. irValue *slice = ir_add_local_slice(proc, t, elem_ptr, v_zero, len, cap);
  2652. return ir_emit_load(proc, slice);
  2653. }
  2654. if (is_type_vector(dst)) {
  2655. Type *dst_elem = dst->Vector.elem;
  2656. value = ir_emit_conv(proc, value, dst_elem);
  2657. irValue *v = ir_add_local_generated(proc, t);
  2658. isize index_count = dst->Vector.count;
  2659. for (i32 i = 0; i < index_count; i++) {
  2660. irValue *elem = ir_emit_array_epi(proc, v, i);
  2661. ir_emit_store(proc, elem, value);
  2662. }
  2663. return ir_emit_load(proc, v);
  2664. }
  2665. if (is_type_any(dst)) {
  2666. irValue *result = ir_add_local_generated(proc, t_any);
  2667. if (is_type_untyped_nil(src)) {
  2668. return ir_emit_load(proc, result);
  2669. }
  2670. Type *st = default_type(src_type);
  2671. irValue *data = nullptr;
  2672. if (value->kind == irValue_Instr &&
  2673. value->Instr.kind == irInstr_Load) {
  2674. // NOTE(bill): Addreirble value
  2675. data = value->Instr.Load.address;
  2676. } else {
  2677. // NOTE(bill): Non-addreirble value
  2678. data = ir_add_local_generated(proc, st);
  2679. ir_emit_store(proc, data, value);
  2680. }
  2681. GB_ASSERT(is_type_pointer(ir_type(data)));
  2682. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  2683. data = ir_emit_conv(proc, data, t_rawptr);
  2684. irValue *ti = ir_type_info(proc, st);
  2685. ir_emit_store(proc, ir_emit_struct_ep(proc, result, 0), data);
  2686. ir_emit_store(proc, ir_emit_struct_ep(proc, result, 1), ti);
  2687. return ir_emit_load(proc, result);
  2688. }
  2689. gb_printf_err("ir_emit_conv: src -> dst\n");
  2690. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  2691. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  2692. GB_PANIC("Invalid type conversion: `%s` to `%s` for procedure `%.*s`",
  2693. type_to_string(src_type), type_to_string(t),
  2694. LIT(proc->name));
  2695. return nullptr;
  2696. }
  2697. bool ir_is_type_aggregate(Type *t) {
  2698. t = base_type(t);
  2699. switch (t->kind) {
  2700. case Type_Basic:
  2701. switch (t->Basic.kind) {
  2702. case Basic_string:
  2703. case Basic_any:
  2704. return true;
  2705. // case Basic_complex32:
  2706. case Basic_complex64:
  2707. case Basic_complex128:
  2708. return true;
  2709. }
  2710. break;
  2711. case Type_Pointer:
  2712. return false;
  2713. case Type_Vector:
  2714. case Type_Array:
  2715. case Type_Slice:
  2716. case Type_Struct:
  2717. case Type_Tuple:
  2718. case Type_DynamicArray:
  2719. case Type_Map:
  2720. case Type_BitField:
  2721. return true;
  2722. case Type_Named:
  2723. return ir_is_type_aggregate(t->Named.base);
  2724. }
  2725. return false;
  2726. }
  2727. irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t) {
  2728. Type *src_type = ir_type(value);
  2729. if (are_types_identical(t, src_type)) {
  2730. return value;
  2731. }
  2732. Type *src = base_type(src_type);
  2733. Type *dst = base_type(t);
  2734. irModule *m = proc->module;
  2735. i64 sz = type_size_of(m->allocator, src);
  2736. i64 dz = type_size_of(m->allocator, dst);
  2737. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: `%s` to `%s`", type_to_string(src_type), type_to_string(t));
  2738. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  2739. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2740. return ir_emit_uintptr_to_ptr(proc, value, t);
  2741. }
  2742. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2743. return ir_emit_ptr_to_uintptr(proc, value, t);
  2744. }
  2745. if (ir_is_type_aggregate(src) || ir_is_type_aggregate(dst)) {
  2746. irValue *s = ir_address_from_load_or_generate_local(proc, value);
  2747. irValue *d = ir_emit_bitcast(proc, s, make_type_pointer(m->allocator, t));
  2748. return ir_emit_load(proc, d);
  2749. }
  2750. // TODO(bill): Actually figure out what the conversion needs to be correctly 'cause LLVM
  2751. return ir_emit_bitcast(proc, value, dst);
  2752. }
  2753. irValue *ir_emit_union_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  2754. gbAllocator a = proc->module->allocator;
  2755. Type *src_type = ir_type(value);
  2756. bool is_ptr = is_type_pointer(src_type);
  2757. bool is_tuple = true;
  2758. Type *tuple = type;
  2759. if (type->kind != Type_Tuple) {
  2760. is_tuple = false;
  2761. tuple = make_optional_ok_type(a, type);
  2762. }
  2763. irValue *v = ir_add_local_generated(proc, tuple);
  2764. if (is_ptr) {
  2765. value = ir_emit_load(proc, value);
  2766. }
  2767. Type *src = base_type(type_deref(src_type));
  2768. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  2769. Type *dst = tuple->Tuple.variables[0]->type;
  2770. irValue *value_ = ir_address_from_load_or_generate_local(proc, value);
  2771. irValue *tag = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, value_));
  2772. irValue *dst_tag = ir_const_union_tag(a, src, dst);
  2773. irBlock *ok_block = ir_new_block(proc, nullptr, "union_cast.ok");
  2774. irBlock *end_block = ir_new_block(proc, nullptr, "union_cast.end");
  2775. irValue *cond = ir_emit_comp(proc, Token_CmpEq, tag, dst_tag);
  2776. ir_emit_if(proc, cond, ok_block, end_block);
  2777. ir_start_block(proc, ok_block);
  2778. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  2779. irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
  2780. irValue *data = ir_emit_load(proc, ir_emit_conv(proc, value_, ir_type(gep0)));
  2781. ir_emit_store(proc, gep0, data);
  2782. ir_emit_store(proc, gep1, v_true);
  2783. ir_emit_jump(proc, end_block);
  2784. ir_start_block(proc, end_block);
  2785. if (!is_tuple) {
  2786. if (do_conversion_check) {
  2787. // NOTE(bill): Panic on invalid conversion
  2788. Type *dst_type = tuple->Tuple.variables[0]->type;
  2789. irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
  2790. irValue **args = gb_alloc_array(a, irValue *, 6);
  2791. args[0] = ok;
  2792. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  2793. args[2] = ir_const_int(a, pos.line);
  2794. args[3] = ir_const_int(a, pos.column);
  2795. args[4] = ir_type_info(proc, src_type);
  2796. args[5] = ir_type_info(proc, dst_type);
  2797. ir_emit_global_call(proc, "__type_assertion_check", args, 6);
  2798. }
  2799. return ir_emit_load(proc, ir_emit_struct_ep(proc, v, 0));
  2800. }
  2801. return ir_emit_load(proc, v);
  2802. }
  2803. irAddr ir_emit_any_cast_addr(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
  2804. gbAllocator a = proc->module->allocator;
  2805. Type *src_type = ir_type(value);
  2806. if (is_type_pointer(src_type)) {
  2807. value = ir_emit_load(proc, value);
  2808. }
  2809. bool is_tuple = true;
  2810. Type *tuple = type;
  2811. if (type->kind != Type_Tuple) {
  2812. is_tuple = false;
  2813. tuple = make_optional_ok_type(a, type);
  2814. }
  2815. Type *dst_type = tuple->Tuple.variables[0]->type;
  2816. irValue *v = ir_add_local_generated(proc, tuple);
  2817. irValue *ti_ptr = ir_type_info(proc, dst_type);
  2818. irValue *any_ti = ir_emit_struct_ev(proc, value, 1);
  2819. irBlock *ok_block = ir_new_block(proc, nullptr, "any_cast.ok");
  2820. irBlock *end_block = ir_new_block(proc, nullptr, "any_cast.end");
  2821. irValue *cond = ir_emit_comp(proc, Token_CmpEq, any_ti, ti_ptr);
  2822. ir_emit_if(proc, cond, ok_block, end_block);
  2823. ir_start_block(proc, ok_block);
  2824. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  2825. irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
  2826. irValue *any_data = ir_emit_struct_ev(proc, value, 0);
  2827. irValue *ptr = ir_emit_conv(proc, any_data, make_type_pointer(a, dst_type));
  2828. ir_emit_store(proc, gep0, ir_emit_load(proc, ptr));
  2829. ir_emit_store(proc, gep1, v_true);
  2830. ir_emit_jump(proc, end_block);
  2831. ir_start_block(proc, end_block);
  2832. if (!is_tuple) {
  2833. // NOTE(bill): Panic on invalid conversion
  2834. irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
  2835. irValue **args = gb_alloc_array(a, irValue *, 6);
  2836. args[0] = ok;
  2837. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  2838. args[2] = ir_const_int(a, pos.line);
  2839. args[3] = ir_const_int(a, pos.column);
  2840. args[4] = any_ti;
  2841. args[5] = ti_ptr;
  2842. ir_emit_global_call(proc, "__type_assertion_check", args, 6);
  2843. return ir_addr(ir_emit_struct_ep(proc, v, 0));
  2844. }
  2845. return ir_addr(v);
  2846. }
  2847. irValue *ir_emit_any_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
  2848. return ir_addr_load(proc, ir_emit_any_cast_addr(proc, value, type, pos));
  2849. }
  2850. // TODO(bill): Try and make a lot of this constant aggregate literals in LLVM IR
  2851. gb_global irValue *ir_global_type_info_data = nullptr;
  2852. gb_global irValue *ir_global_type_info_member_types = nullptr;
  2853. gb_global irValue *ir_global_type_info_member_names = nullptr;
  2854. gb_global irValue *ir_global_type_info_member_offsets = nullptr;
  2855. gb_global irValue *ir_global_type_info_member_usings = nullptr;
  2856. gb_global i32 ir_global_type_info_data_index = 0;
  2857. gb_global i32 ir_global_type_info_member_types_index = 0;
  2858. gb_global i32 ir_global_type_info_member_names_index = 0;
  2859. gb_global i32 ir_global_type_info_member_offsets_index = 0;
  2860. gb_global i32 ir_global_type_info_member_usings_index = 0;
  2861. irValue *ir_type_info(irProcedure *proc, Type *type) {
  2862. CheckerInfo *info = proc->module->info;
  2863. type = default_type(type);
  2864. i32 entry_index = cast(i32)type_info_index(info, type);
  2865. GB_ASSERT(entry_index >= 0);
  2866. // gb_printf_err("%d %s\n", entry_index, type_to_string(type));
  2867. return ir_emit_array_ep(proc, ir_global_type_info_data, ir_const_i32(proc->module->allocator, entry_index));
  2868. }
  2869. irValue *ir_emit_logical_binary_expr(irProcedure *proc, AstNode *expr) {
  2870. ast_node(be, BinaryExpr, expr);
  2871. #if 0
  2872. irBlock *true_ = ir_new_block(proc, nullptr, "logical.cmp.true");
  2873. irBlock *false_ = ir_new_block(proc, nullptr, "logical.cmp.false");
  2874. irBlock *done = ir_new_block(proc, nullptr, "logical.cmp.done");
  2875. irValue *result = ir_add_local_generated(proc, t_bool);
  2876. ir_build_cond(proc, expr, true_, false_);
  2877. ir_start_block(proc, true_);
  2878. ir_emit_store(proc, result, v_true);
  2879. ir_emit_jump(proc, done);
  2880. ir_start_block(proc, false_);
  2881. ir_emit_store(proc, result, v_false);
  2882. ir_emit_jump(proc, done);
  2883. ir_start_block(proc, done);
  2884. return ir_emit_load(proc, result);
  2885. #else
  2886. irBlock *rhs = ir_new_block(proc, nullptr, "logical.cmp.rhs");
  2887. irBlock *done = ir_new_block(proc, nullptr, "logical.cmp.done");
  2888. Type *type = type_of_expr(proc->module->info, expr);
  2889. type = default_type(type);
  2890. irValue *short_circuit = nullptr;
  2891. if (be->op.kind == Token_CmpAnd) {
  2892. ir_build_cond(proc, be->left, rhs, done);
  2893. short_circuit = v_false;
  2894. } else if (be->op.kind == Token_CmpOr) {
  2895. ir_build_cond(proc, be->left, done, rhs);
  2896. short_circuit = v_true;
  2897. }
  2898. if (rhs->preds.count == 0) {
  2899. ir_start_block(proc, done);
  2900. return short_circuit;
  2901. }
  2902. if (done->preds.count == 0) {
  2903. ir_start_block(proc, rhs);
  2904. return ir_build_expr(proc, be->right);
  2905. }
  2906. Array<irValue *> edges = {};
  2907. array_init(&edges, proc->module->allocator, done->preds.count+1);
  2908. for_array(i, done->preds) {
  2909. array_add(&edges, short_circuit);
  2910. }
  2911. ir_start_block(proc, rhs);
  2912. array_add(&edges, ir_build_expr(proc, be->right));
  2913. ir_emit_jump(proc, done);
  2914. ir_start_block(proc, done);
  2915. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  2916. #endif
  2917. }
  2918. void ir_emit_bounds_check(irProcedure *proc, Token token, irValue *index, irValue *len) {
  2919. if ((proc->module->stmt_state_flags & StmtStateFlag_no_bounds_check) != 0) {
  2920. return;
  2921. }
  2922. index = ir_emit_conv(proc, index, t_int);
  2923. len = ir_emit_conv(proc, len, t_int);
  2924. gbAllocator a = proc->module->allocator;
  2925. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  2926. irValue *line = ir_const_int(a, token.pos.line);
  2927. irValue *column = ir_const_int(a, token.pos.column);
  2928. irValue **args = gb_alloc_array(a, irValue *, 5);
  2929. args[0] = file;
  2930. args[1] = line;
  2931. args[2] = column;
  2932. args[3] = index;
  2933. args[4] = len;
  2934. ir_emit_global_call(proc, "__bounds_check_error", args, 5);
  2935. // ir_emit(proc, ir_instr_bounds_check(proc, token.pos, index, len));
  2936. }
  2937. void ir_emit_slice_bounds_check(irProcedure *proc, Token token, irValue *low, irValue *high, irValue *max, bool is_substring) {
  2938. if ((proc->module->stmt_state_flags & StmtStateFlag_no_bounds_check) != 0) {
  2939. return;
  2940. }
  2941. gbAllocator a = proc->module->allocator;
  2942. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  2943. irValue *line = ir_const_int(a, token.pos.line);
  2944. irValue *column = ir_const_int(a, token.pos.column);
  2945. low = ir_emit_conv(proc, low, t_int);
  2946. high = ir_emit_conv(proc, high, t_int);
  2947. irValue **args = gb_alloc_array(a, irValue *, 6);
  2948. args[0] = file;
  2949. args[1] = line;
  2950. args[2] = column;
  2951. args[3] = low;
  2952. args[4] = high;
  2953. args[5] = max;
  2954. if (is_substring) {
  2955. ir_emit_global_call(proc, "__substring_expr_error", args, 5);
  2956. } else {
  2957. ir_emit_global_call(proc, "__slice_expr_error", args, 6);
  2958. }
  2959. // ir_emit(proc, ir_instr_slice_bounds_check(proc, token.pos, low, high, max, is_substring));
  2960. }
  2961. ////////////////////////////////////////////////////////////////
  2962. //
  2963. // @Build
  2964. //
  2965. ////////////////////////////////////////////////////////////////
  2966. String ir_mangle_name(irGen *s, String path, Entity *e) {
  2967. // NOTE(bill): prefix names not in the init scope
  2968. // TODO(bill): make robust and not just rely on the file's name
  2969. String name = e->token.string;
  2970. irModule *m = &s->module;
  2971. CheckerInfo *info = m->info;
  2972. gbAllocator a = m->allocator;
  2973. AstFile *file = ast_file_of_filename(info, path);
  2974. char *str = gb_alloc_array(a, char, path.len+1);
  2975. gb_memmove(str, path.text, path.len);
  2976. str[path.len] = 0;
  2977. for (isize i = 0; i < path.len; i++) {
  2978. if (str[i] == '\\') {
  2979. str[i] = '/';
  2980. }
  2981. }
  2982. char const *base = gb_path_base_name(str);
  2983. char const *ext = gb_path_extension(base);
  2984. isize base_len = ext-1-base;
  2985. isize max_len = base_len + 1 + 1 + 10 + 1 + name.len;
  2986. bool require_suffix_id = check_is_entity_overloaded(e) || is_type_polymorphic(e->type);
  2987. if (require_suffix_id) {
  2988. max_len += 21;
  2989. }
  2990. u8 *new_name = gb_alloc_array(a, u8, max_len);
  2991. isize new_name_len = 0;
  2992. if ((base_len > 0 && gb_char_is_digit(base[0])) ||
  2993. base_len == 0) {
  2994. new_name_len = gb_snprintf(
  2995. cast(char *)new_name, max_len,
  2996. "_%.*s-%u.%.*s",
  2997. cast(int)base_len, base,
  2998. cast(u32)file->id,
  2999. LIT(name));
  3000. } else {
  3001. new_name_len = gb_snprintf(
  3002. cast(char *)new_name, max_len,
  3003. "%.*s-%u.%.*s",
  3004. cast(int)base_len, base,
  3005. cast(u32)file->id,
  3006. LIT(name));
  3007. }
  3008. if (require_suffix_id) {
  3009. char *str = cast(char *)new_name + new_name_len-1;
  3010. isize len = max_len-new_name_len;
  3011. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  3012. new_name_len += extra-1;
  3013. }
  3014. return make_string(new_name, new_name_len-1);
  3015. }
  3016. void ir_mangle_add_sub_type_name(irModule *m, Entity *field, String parent) {
  3017. if (field->kind != Entity_TypeName) {
  3018. return;
  3019. }
  3020. String cn = field->token.string;
  3021. isize len = parent.len + 1 + 16 + 1 + cn.len;
  3022. u8 *text = gb_alloc_array(m->allocator, u8, len);
  3023. isize new_name_len = gb_snprintf(cast(char *)text, len,
  3024. "%.*s.%.*s", LIT(parent), LIT(cn));
  3025. String child = {text, new_name_len-1};
  3026. GB_ASSERT(child.len > 0);
  3027. ir_add_entity_name(m, field, child);
  3028. ir_gen_global_type_name(m, field, child);
  3029. }
  3030. irBranchBlocks ir_lookup_branch_blocks(irProcedure *proc, AstNode *ident) {
  3031. GB_ASSERT(ident->kind == AstNode_Ident);
  3032. Entity *e = entity_of_ident(proc->module->info, ident);
  3033. GB_ASSERT(e->kind == Entity_Label);
  3034. for_array(i, proc->branch_blocks) {
  3035. irBranchBlocks *b = &proc->branch_blocks[i];
  3036. if (b->label == e->Label.node) {
  3037. return *b;
  3038. }
  3039. }
  3040. GB_PANIC("Unreachable");
  3041. irBranchBlocks empty = {};
  3042. return empty;
  3043. }
  3044. void ir_push_target_list(irProcedure *proc, AstNode *label, irBlock *break_, irBlock *continue_, irBlock *fallthrough_) {
  3045. irTargetList *tl = gb_alloc_item(proc->module->allocator, irTargetList);
  3046. tl->prev = proc->target_list;
  3047. tl->break_ = break_;
  3048. tl->continue_ = continue_;
  3049. tl->fallthrough_ = fallthrough_;
  3050. proc->target_list = tl;
  3051. if (label != nullptr) { // Set label blocks
  3052. GB_ASSERT(label->kind == AstNode_Label);
  3053. for_array(i, proc->branch_blocks) {
  3054. irBranchBlocks *b = &proc->branch_blocks[i];
  3055. GB_ASSERT(b->label != nullptr && label != nullptr);
  3056. GB_ASSERT(b->label->kind == AstNode_Label);
  3057. if (b->label == label) {
  3058. b->break_ = break_;
  3059. b->continue_ = continue_;
  3060. return;
  3061. }
  3062. }
  3063. GB_PANIC("ir_set_label_blocks: Unreachable");
  3064. }
  3065. }
  3066. void ir_pop_target_list(irProcedure *proc) {
  3067. proc->target_list = proc->target_list->prev;
  3068. }
  3069. irValue *ir_gen_anonymous_proc_lit(irModule *m, String prefix_name, AstNode *expr, irProcedure *proc = nullptr) {
  3070. ast_node(pl, ProcLit, expr);
  3071. // NOTE(bill): Generate a new name
  3072. // parent$count
  3073. isize name_len = prefix_name.len + 1 + 8 + 1;
  3074. u8 *name_text = gb_alloc_array(m->allocator, u8, name_len);
  3075. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  3076. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  3077. String name = make_string(name_text, name_len-1);
  3078. Type *type = type_of_expr(m->info, expr);
  3079. irValue *value = ir_value_procedure(m->allocator,
  3080. m, nullptr, type, pl->type, pl->body, name);
  3081. value->Proc.tags = pl->tags;
  3082. value->Proc.inlining = pl->inlining;
  3083. value->Proc.parent = proc;
  3084. array_add(&m->procs_to_generate, value);
  3085. if (proc != nullptr) {
  3086. array_add(&proc->children, &value->Proc);
  3087. } else {
  3088. map_set(&m->members, hash_string(name), value);
  3089. }
  3090. map_set(&m->anonymous_proc_lits, hash_pointer(expr), value);
  3091. return value;
  3092. }
  3093. void ir_check_type_and_gen_for_proc_lit(irProcedure *proc, Type *t) {
  3094. if (t == nullptr) return;
  3095. if (t->kind == Type_Struct && t->Struct.has_proc_default_values) {
  3096. for_array(i, t->Struct.fields) {
  3097. Entity *f = t->Struct.fields[i];
  3098. if (f->kind == Entity_Variable && f->Variable.default_value.kind == ExactValue_Procedure) {
  3099. AstNode *expr = f->Variable.default_value.value_procedure;
  3100. GB_ASSERT(expr != nullptr);
  3101. if (expr->kind == AstNode_ProcLit) {
  3102. ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  3103. }
  3104. }
  3105. }
  3106. }
  3107. }
  3108. void ir_check_type_and_gen_for_proc_lit(irModule *m, String prefix_name, Type *t) {
  3109. if (t == nullptr) return;
  3110. if (t->kind == Type_Struct && t->Struct.has_proc_default_values) {
  3111. for_array(i, t->Struct.fields) {
  3112. Entity *f = t->Struct.fields[i];
  3113. if (f->kind == Entity_Variable && f->Variable.default_value.kind == ExactValue_Procedure) {
  3114. AstNode *expr = f->Variable.default_value.value_procedure;
  3115. GB_ASSERT(expr != nullptr);
  3116. if (expr->kind == AstNode_ProcLit) {
  3117. ir_gen_anonymous_proc_lit(m, prefix_name, expr);
  3118. }
  3119. }
  3120. }
  3121. }
  3122. }
  3123. void ir_gen_global_type_name(irModule *m, Entity *e, String name) {
  3124. if (e->type == nullptr) return;
  3125. if (e->kind == Entity_TypeName && e->type->kind == Type_Named) {
  3126. if (e != e->type->Named.type_name) {
  3127. // NOTE(bill): Is alias
  3128. return;
  3129. }
  3130. }
  3131. Type *bt = base_type(e->type);
  3132. bool is_poly = is_type_polymorphic(bt);
  3133. if (!is_poly) {
  3134. if (bt->kind == Type_Struct &&
  3135. bt->Struct.is_polymorphic &&
  3136. !bt->Struct.is_poly_specialized) {
  3137. is_poly = true;
  3138. }
  3139. }
  3140. if (is_poly) {
  3141. auto found = map_get(&m->info->gen_types, hash_pointer(e->type));
  3142. if (found != nullptr) {
  3143. for_array(i, *found) {
  3144. Entity *sub = (*found)[i];
  3145. // gb_printf_err("--> %.*s\n", LIT(sub->token.string));
  3146. if (ptr_set_exists(&m->min_dep_set, sub)) {
  3147. ir_mangle_add_sub_type_name(m, sub, name);
  3148. }
  3149. }
  3150. }
  3151. return;
  3152. }
  3153. if (!ptr_set_exists(&m->min_dep_set, e)) return;
  3154. irValue *t = ir_value_type_name(m->allocator, name, e->type);
  3155. ir_module_add_value(m, e, t);
  3156. map_set(&m->members, hash_string(name), t);
  3157. #if 0
  3158. if (is_type_union(e->type)) {
  3159. Type *bt = base_type(e->type);
  3160. // NOTE(bill): Zeroth entry is null (for `match type` stmts)
  3161. for (isize j = 1; j < bt->Struct.variant_count; j++) {
  3162. ir_mangle_add_sub_type_name(m, bt->Struct.variants[j], name);
  3163. }
  3164. }
  3165. #endif
  3166. // if (bt->kind == Type_Struct) {
  3167. // Scope *s = bt->Struct.scope;
  3168. // if (s != nullptr) {
  3169. // for_array(i, s->elements.entries) {
  3170. // Entity *e = s->elements.entries[i].value;
  3171. // if (e->kind == Entity_TypeName) {
  3172. // ir_mangle_add_sub_type_name(m, e, name);
  3173. // }
  3174. // }
  3175. // }
  3176. // }
  3177. ir_check_type_and_gen_for_proc_lit(m, e->token.string, bt);
  3178. }
  3179. void ir_build_defer_stmt(irProcedure *proc, irDefer d) {
  3180. irBlock *b = ir_new_block(proc, nullptr, "defer");
  3181. // NOTE(bill): The prev block may defer injection before it's terminator
  3182. irInstr *last_instr = ir_get_last_instr(proc->curr_block);
  3183. if (last_instr == nullptr || !ir_is_instr_terminating(last_instr)) {
  3184. ir_emit_jump(proc, b);
  3185. }
  3186. ir_start_block(proc, b);
  3187. ir_emit_comment(proc, str_lit("defer"));
  3188. if (d.kind == irDefer_Node) {
  3189. ir_build_stmt(proc, d.stmt);
  3190. } else if (d.kind == irDefer_Instr) {
  3191. // NOTE(bill): Need to make a new copy
  3192. irValue *instr = cast(irValue *)gb_alloc_copy(proc->module->allocator, d.instr, gb_size_of(irValue));
  3193. ir_emit(proc, instr);
  3194. }
  3195. }
  3196. irValue *ir_emit_clamp(irProcedure *proc, Type *t, irValue *x, irValue *min, irValue *max) {
  3197. irValue *cond = nullptr;
  3198. ir_emit_comment(proc, str_lit("clamp"));
  3199. x = ir_emit_conv(proc, x, t);
  3200. min = ir_emit_conv(proc, min, t);
  3201. max = ir_emit_conv(proc, max, t);
  3202. cond = ir_emit_comp(proc, Token_Gt, min, x);
  3203. x = ir_emit_select(proc, cond, min, x);
  3204. cond = ir_emit_comp(proc, Token_Lt, max, x);
  3205. x = ir_emit_select(proc, cond, max, x);
  3206. return x;
  3207. }
  3208. irValue *ir_find_global_variable(irProcedure *proc, String name) {
  3209. irValue **value = map_get(&proc->module->members, hash_string(name));
  3210. GB_ASSERT_MSG(value != nullptr, "Unable to find global variable `%.*s`", LIT(name));
  3211. return *value;
  3212. }
  3213. void ir_build_stmt_list(irProcedure *proc, Array<AstNode *> stmts);
  3214. bool is_double_pointer(Type *t) {
  3215. if (!is_type_pointer(t)) {
  3216. return false;
  3217. }
  3218. Type *td = type_deref(t);
  3219. if (td == nullptr || td == t) {
  3220. return false;
  3221. }
  3222. return is_type_pointer(td);
  3223. }
  3224. irValue *ir_emit_source_code_location(irProcedure *proc, String procedure, TokenPos pos) {
  3225. gbAllocator a = proc->module->allocator;
  3226. irValue **args = gb_alloc_array(a, irValue *, 4);
  3227. args[0] = ir_find_or_add_entity_string(proc->module, pos.file);
  3228. args[1] = ir_const_i64(a, pos.line);
  3229. args[2] = ir_const_i64(a, pos.column);
  3230. args[3] = ir_find_or_add_entity_string(proc->module, procedure);
  3231. return ir_emit_global_call(proc, "make_source_code_location", args, 4);
  3232. }
  3233. void ir_emit_increment(irProcedure *proc, irValue *addr) {
  3234. GB_ASSERT(is_type_pointer(ir_type(addr)));
  3235. Type *type = type_deref(ir_type(addr));
  3236. ir_emit_store(proc, addr, ir_emit_arith(proc, Token_Add, ir_emit_load(proc, addr), v_one, type));
  3237. }
  3238. void ir_init_data_with_defaults(irProcedure *proc, irValue *ptr, irValue *count) {
  3239. Type *elem_type = type_deref(ir_type(ptr));
  3240. GB_ASSERT(is_type_struct(elem_type) || is_type_array(elem_type));
  3241. irValue *index = ir_add_local_generated(proc, t_int);
  3242. ir_emit_store(proc, index, ir_const_int(proc->module->allocator, 0));
  3243. irBlock *loop = nullptr;
  3244. irBlock *done = nullptr;
  3245. irBlock *body = nullptr;
  3246. loop = ir_new_block(proc, nullptr, "make.init.loop");
  3247. ir_emit_jump(proc, loop);
  3248. ir_start_block(proc, loop);
  3249. body = ir_new_block(proc, nullptr, "make.init.body");
  3250. done = ir_new_block(proc, nullptr, "make.init.done");
  3251. irValue *cond = ir_emit_comp(proc, Token_Lt, ir_emit_load(proc, index), count);
  3252. ir_emit_if(proc, cond, body, done);
  3253. ir_start_block(proc, body);
  3254. irValue *offset_ptr = ir_emit_ptr_offset(proc, ptr, ir_emit_load(proc, index));
  3255. ir_emit_zero_init(proc, offset_ptr);
  3256. ir_emit_increment(proc, index);
  3257. ir_emit_jump(proc, loop);
  3258. ir_start_block(proc, done);
  3259. }
  3260. irValue *ir_build_builtin_proc(irProcedure *proc, AstNode *expr, TypeAndValue tv, BuiltinProcId id) {
  3261. ast_node(ce, CallExpr, expr);
  3262. switch (id) {
  3263. case BuiltinProc_DIRECTIVE: {
  3264. ast_node(bd, BasicDirective, ce->proc);
  3265. String name = bd->name;
  3266. GB_ASSERT(name == "location");
  3267. String procedure = proc->entity->token.string;
  3268. TokenPos pos = ast_node_token(ce->proc).pos;
  3269. if (ce->args.count > 0) {
  3270. AstNode *ident = ce->args[0];;
  3271. while (ident->kind == AstNode_SelectorExpr) {
  3272. ident = ident->SelectorExpr.selector;
  3273. }
  3274. Entity *e = entity_of_ident(proc->module->info, ident);
  3275. GB_ASSERT(e != nullptr);
  3276. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity_count > 0) {
  3277. procedure = e->parent_proc_decl->entities[0]->token.string;
  3278. } else {
  3279. procedure = str_lit("");
  3280. }
  3281. pos = e->token.pos;
  3282. }
  3283. return ir_emit_source_code_location(proc, procedure, pos);
  3284. break;
  3285. }
  3286. case BuiltinProc_type_info_of: {
  3287. Type *t = default_type(type_of_expr(proc->module->info, ce->args[0]));
  3288. return ir_type_info(proc, t);
  3289. break;
  3290. }
  3291. case BuiltinProc_len: {
  3292. irValue *v = ir_build_expr(proc, ce->args[0]);
  3293. Type *t = base_type(ir_type(v));
  3294. if (is_type_pointer(t)) {
  3295. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  3296. v = ir_emit_load(proc, v);
  3297. t = type_deref(t);
  3298. }
  3299. if (is_type_string(t)) {
  3300. return ir_string_len(proc, v);
  3301. } else if (is_type_array(t)) {
  3302. GB_PANIC("Array lengths are constant");
  3303. } else if (is_type_vector(t)) {
  3304. GB_PANIC("Vector lengths are constant");
  3305. } else if (is_type_slice(t)) {
  3306. return ir_slice_count(proc, v);
  3307. } else if (is_type_dynamic_array(t)) {
  3308. return ir_dynamic_array_count(proc, v);
  3309. } else if (is_type_map(t)) {
  3310. ir_emit_comment(proc, str_lit("len: map"));
  3311. irValue *entries = ir_emit_struct_ev(proc, v, 1);
  3312. return ir_dynamic_array_count(proc, entries);
  3313. }
  3314. GB_PANIC("Unreachable");
  3315. break;
  3316. }
  3317. case BuiltinProc_cap: {
  3318. irValue *v = ir_build_expr(proc, ce->args[0]);
  3319. Type *t = base_type(ir_type(v));
  3320. if (is_type_pointer(t)) {
  3321. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  3322. v = ir_emit_load(proc, v);
  3323. t = type_deref(t);
  3324. }
  3325. if (is_type_string(t)) {
  3326. GB_PANIC("Unreachable");
  3327. } else if (is_type_array(t)) {
  3328. GB_PANIC("Array lengths are constant");
  3329. } else if (is_type_vector(t)) {
  3330. GB_PANIC("Unreachable");
  3331. } else if (is_type_slice(t)) {
  3332. return ir_slice_capacity(proc, v);
  3333. } else if (is_type_dynamic_array(t)) {
  3334. return ir_dynamic_array_capacity(proc, v);
  3335. } else if (is_type_map(t)) {
  3336. irValue *entries = ir_emit_struct_ev(proc, v, 1);
  3337. return ir_dynamic_array_capacity(proc, entries);
  3338. }
  3339. GB_PANIC("Unreachable");
  3340. break;
  3341. }
  3342. #if 0
  3343. case BuiltinProc_new: {
  3344. ir_emit_comment(proc, str_lit("new"));
  3345. // proc new(Type) -> ^Type
  3346. gbAllocator a = proc->module->allocator;
  3347. Type *type = type_of_expr(proc->module->info, ce->args[0]);
  3348. Type *allocation_type = type;
  3349. i32 variant_index = 0;
  3350. if (is_type_struct(type)) {
  3351. Type *st = base_type(type);
  3352. if (st->Struct.variant_parent != nullptr) {
  3353. allocation_type = st->Struct.variant_parent;
  3354. variant_index = st->Struct.variant_index;
  3355. GB_ASSERT(allocation_type != nullptr);
  3356. }
  3357. }
  3358. Type *ptr_type = make_type_pointer(a, type);
  3359. i64 size = type_size_of(a, allocation_type);
  3360. i64 align = type_align_of(a, allocation_type);
  3361. irValue **args = gb_alloc_array(a, irValue *, 2);
  3362. args[0] = ir_const_int(a, size);
  3363. args[1] = ir_const_int(a, align);
  3364. irValue *call = ir_emit_global_call(proc, "alloc", args, 2);
  3365. irValue *v = ir_emit_conv(proc, call, ptr_type);
  3366. if (type != allocation_type) {
  3367. Type *u = base_type(allocation_type);
  3368. Type *uptr_type = make_type_pointer(a, u);
  3369. irValue *parent = ir_emit_conv(proc, call, uptr_type);
  3370. irValue *tag_ptr = ir_emit_union_tag_ptr(proc, parent);
  3371. ir_emit_store(proc, tag_ptr, ir_const_int(a, variant_index));
  3372. }
  3373. return v;
  3374. break;
  3375. }
  3376. #endif
  3377. case BuiltinProc_make: {
  3378. ir_emit_comment(proc, str_lit("make"));
  3379. gbAllocator a = proc->module->allocator;
  3380. Type *type = type_of_expr(proc->module->info, ce->args[0]);
  3381. if (is_type_slice(type)) {
  3382. Type *elem_type = core_type(type)->Slice.elem;
  3383. Type *elem_ptr_type = make_type_pointer(a, elem_type);
  3384. irValue *elem_size = ir_const_int(a, type_size_of(a, elem_type));
  3385. irValue *elem_align = ir_const_int(a, type_align_of(a, elem_type));
  3386. irValue *count = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int);
  3387. irValue *capacity = count;
  3388. if (ce->args.count == 3) {
  3389. capacity = ir_emit_conv(proc, ir_build_expr(proc, ce->args[2]), t_int);
  3390. }
  3391. ir_emit_slice_bounds_check(proc, ast_node_token(ce->args[1]), v_zero, count, capacity, false);
  3392. irValue *slice_size = ir_emit_arith(proc, Token_Mul, elem_size, capacity, t_int);
  3393. irValue **args = gb_alloc_array(a, irValue *, 2);
  3394. args[0] = slice_size;
  3395. args[1] = elem_align;
  3396. irValue *call = ir_emit_global_call(proc, "alloc", args, 2);
  3397. irValue *ptr = ir_emit_conv(proc, call, elem_ptr_type);
  3398. if (ir_type_has_default_values(elem_type)) {
  3399. ir_init_data_with_defaults(proc, ptr, count);
  3400. }
  3401. irValue *slice = ir_add_local_generated(proc, type);
  3402. ir_fill_slice(proc, slice, ptr, count, capacity);
  3403. return ir_emit_load(proc, slice);
  3404. } else if (is_type_map(type)) {
  3405. irValue *int_16 = ir_const_int(a, 16);
  3406. irValue *cap = int_16;
  3407. if (ce->args.count == 2) {
  3408. cap = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int);
  3409. }
  3410. irValue *cond = ir_emit_comp(proc, Token_Gt, cap, v_zero);
  3411. cap = ir_emit_select(proc, cond, cap, int_16);
  3412. irValue *map = ir_add_local_generated(proc, type);
  3413. irValue *header = ir_gen_map_header(proc, map, base_type(type));
  3414. irValue **args = gb_alloc_array(a, irValue *, 2);
  3415. args[0] = header;
  3416. args[1] = cap;
  3417. ir_emit_global_call(proc, "__dynamic_map_reserve", args, 2);
  3418. return ir_emit_load(proc, map);
  3419. } else if (is_type_dynamic_array(type)) {
  3420. Type *elem_type = base_type(type)->DynamicArray.elem;
  3421. irValue *len = v_zero;
  3422. if (ce->args.count > 1) {
  3423. len = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int);
  3424. }
  3425. irValue *cap = len;
  3426. if (ce->args.count > 2) {
  3427. cap = ir_emit_conv(proc, ir_build_expr(proc, ce->args[2]), t_int);
  3428. }
  3429. ir_emit_slice_bounds_check(proc, ast_node_token(ce->args[0]), v_zero, len, cap, false);
  3430. irValue *array = ir_add_local_generated(proc, type);
  3431. irValue **args = gb_alloc_array(a, irValue *, 5);
  3432. args[0] = ir_emit_conv(proc, array, t_rawptr);
  3433. args[1] = ir_const_int(a, type_size_of(a, elem_type));
  3434. args[2] = ir_const_int(a, type_align_of(a, elem_type));
  3435. args[3] = len;
  3436. args[4] = cap;
  3437. ir_emit_global_call(proc, "__dynamic_array_make", args, 5);
  3438. if (ir_type_has_default_values(elem_type)) {
  3439. ir_init_data_with_defaults(proc, ir_dynamic_array_elem(proc, ir_emit_load(proc, array)), len);
  3440. }
  3441. return ir_emit_load(proc, array);
  3442. }
  3443. break;
  3444. }
  3445. #if 0
  3446. case BuiltinProc_free: {
  3447. ir_emit_comment(proc, str_lit("free"));
  3448. gbAllocator a = proc->module->allocator;
  3449. AstNode *node = ce->args[0];
  3450. TypeAndValue tav = type_and_value_of_expr(proc->module->info, node);
  3451. Type *type = base_type(tav.type);
  3452. if (is_type_dynamic_array(type)) {
  3453. irValue *val = ir_build_expr(proc, node);
  3454. irValue *da_allocator = ir_emit_struct_ev(proc, val, 3);
  3455. irValue *ptr = ir_emit_struct_ev(proc, val, 0);
  3456. ptr = ir_emit_conv(proc, ptr, t_rawptr);
  3457. irValue **args = gb_alloc_array(a, irValue *, 1);
  3458. args[0] = da_allocator;
  3459. args[1] = ptr;
  3460. return ir_emit_global_call(proc, "free_ptr_with_allocator", args, 2);
  3461. } else if (is_type_map(type)) {
  3462. irValue *map = ir_build_expr(proc, node);
  3463. irValue *map_ptr = ir_address_from_load_or_generate_local(proc, map);
  3464. {
  3465. irValue *array = ir_emit_struct_ep(proc, map_ptr, 0);
  3466. irValue *da_allocator = ir_emit_load(proc, ir_emit_struct_ep(proc, array, 3));
  3467. irValue *da_ptr = ir_emit_load(proc, ir_emit_struct_ep(proc, array, 0));
  3468. da_ptr = ir_emit_conv(proc, da_ptr, t_rawptr);
  3469. irValue **args = gb_alloc_array(a, irValue *, 1);
  3470. args[0] = da_allocator;
  3471. args[1] = da_ptr;
  3472. ir_emit_global_call(proc, "free_ptr_with_allocator", args, 2);
  3473. }
  3474. {
  3475. irValue *array = ir_emit_struct_ep(proc, map_ptr, 1);
  3476. irValue *da_allocator = ir_emit_load(proc, ir_emit_struct_ep(proc, array, 3));
  3477. irValue *da_ptr = ir_emit_load(proc, ir_emit_struct_ep(proc, array, 0));
  3478. da_ptr = ir_emit_conv(proc, da_ptr, t_rawptr);
  3479. irValue **args = gb_alloc_array(a, irValue *, 1);
  3480. args[0] = da_allocator;
  3481. args[1] = da_ptr;
  3482. ir_emit_global_call(proc, "free_ptr_with_allocator", args, 2);
  3483. }
  3484. return nullptr;
  3485. }
  3486. irValue *val = ir_build_expr(proc, node);
  3487. irValue *ptr = nullptr;
  3488. if (is_type_pointer(type)) {
  3489. ptr = val;
  3490. } else if (is_type_slice(type)) {
  3491. ptr = ir_slice_elem(proc, val);
  3492. } else if (is_type_string(type)) {
  3493. ptr = ir_string_elem(proc, val);
  3494. } else {
  3495. GB_PANIC("Invalid type to `free`");
  3496. }
  3497. if (ptr == nullptr) {
  3498. return nullptr;
  3499. }
  3500. ptr = ir_emit_conv(proc, ptr, t_rawptr);
  3501. irValue **args = gb_alloc_array(a, irValue *, 1);
  3502. args[0] = ptr;
  3503. return ir_emit_global_call(proc, "free_ptr", args, 1);
  3504. break;
  3505. }
  3506. #endif
  3507. #if 0
  3508. case BuiltinProc_reserve: {
  3509. ir_emit_comment(proc, str_lit("reserve"));
  3510. gbAllocator a = proc->module->allocator;
  3511. irValue *ptr = ir_build_addr_ptr(proc, ce->args[0]);
  3512. Type *type = ir_type(ptr);
  3513. GB_ASSERT(is_type_pointer(type));
  3514. type = base_type(type_deref(type));
  3515. irValue *capacity = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int);
  3516. if (is_type_dynamic_array(type)) {
  3517. Type *elem = type->DynamicArray.elem;
  3518. irValue *elem_size = ir_const_int(a, type_size_of(a, elem));
  3519. irValue *elem_align = ir_const_int(a, type_align_of(a, elem));
  3520. ptr = ir_emit_conv(proc, ptr, t_rawptr);
  3521. irValue **args = gb_alloc_array(a, irValue *, 4);
  3522. args[0] = ptr;
  3523. args[1] = elem_size;
  3524. args[2] = elem_align;
  3525. args[3] = capacity;
  3526. return ir_emit_global_call(proc, "__dynamic_array_reserve", args, 4);
  3527. } else if (is_type_map(type)) {
  3528. irValue **args = gb_alloc_array(a, irValue *, 2);
  3529. args[0] = ir_gen_map_header(proc, ptr, type);
  3530. args[1] = capacity;
  3531. return ir_emit_global_call(proc, "__dynamic_map_reserve", args, 2);
  3532. } else {
  3533. GB_PANIC("Unknown type for `reserve`");
  3534. }
  3535. break;
  3536. }
  3537. #endif
  3538. #if 0
  3539. case BuiltinProc_clear: {
  3540. ir_emit_comment(proc, str_lit("clear"));
  3541. Type *original_type = type_of_expr(proc->module->info, ce->args[0]);
  3542. irAddr addr = ir_build_addr(proc, ce->args[0]);
  3543. irValue *ptr = addr.addr;
  3544. if (is_double_pointer(ir_type(ptr))) {
  3545. ptr = ir_addr_load(proc, addr);
  3546. }
  3547. Type *t = base_type(type_deref(original_type));
  3548. if (is_type_dynamic_array(t)) {
  3549. irValue *count_ptr = ir_emit_struct_ep(proc, ptr, 1);
  3550. ir_emit_store(proc, count_ptr, v_zero);
  3551. } else if (is_type_map(t)) {
  3552. irValue *ha = ir_emit_struct_ep(proc, ptr, 0);
  3553. irValue *ea = ir_emit_struct_ep(proc, ptr, 1);
  3554. ir_emit_store(proc, ir_emit_struct_ep(proc, ha, 1), v_zero);
  3555. ir_emit_store(proc, ir_emit_struct_ep(proc, ea, 1), v_zero);
  3556. } else if (is_type_slice(t)) {
  3557. irValue *count_ptr = ir_emit_struct_ep(proc, ptr, 1);
  3558. ir_emit_store(proc, count_ptr, v_zero);
  3559. } else {
  3560. GB_PANIC("TODO(bill): ir clear for `%s`", type_to_string(t));
  3561. }
  3562. return nullptr;
  3563. break;
  3564. }
  3565. #endif
  3566. #if 0
  3567. case BuiltinProc_append: {
  3568. ir_emit_comment(proc, str_lit("append"));
  3569. gbAllocator a = proc->module->allocator;
  3570. Type *value_type = type_of_expr(proc->module->info, ce->args[0]);
  3571. irAddr array_addr = ir_build_addr(proc, ce->args[0]);
  3572. irValue *array_ptr = array_addr.addr;
  3573. if (is_double_pointer(ir_type(array_ptr))) {
  3574. array_ptr = ir_addr_load(proc, array_addr);
  3575. }
  3576. Type *type = ir_type(array_ptr);
  3577. {
  3578. TokenPos pos = ast_node_token(ce->args[0]).pos;
  3579. GB_ASSERT_MSG(is_type_pointer(type), "%.*s(%td) %s",
  3580. LIT(pos.file), pos.line,
  3581. type_to_string(type));
  3582. }
  3583. type = base_type(type_deref(type));
  3584. Type *elem_type = nullptr;
  3585. bool is_slice = false;
  3586. if (is_type_dynamic_array(type)) {
  3587. elem_type = type->DynamicArray.elem;
  3588. } else if (is_type_slice(type)) {
  3589. is_slice = true;
  3590. elem_type = type->Slice.elem;
  3591. } else {
  3592. GB_PANIC("Invalid type to append");
  3593. }
  3594. irValue *elem_size = ir_const_int(a, type_size_of(a, elem_type));
  3595. irValue *elem_align = ir_const_int(a, type_align_of(a, elem_type));
  3596. array_ptr = ir_emit_conv(proc, array_ptr, t_rawptr);
  3597. isize arg_index = 0;
  3598. isize arg_count = 0;
  3599. for_array(i, ce->args) {
  3600. AstNode *a = ce->args[i];
  3601. Type *at = base_type(type_of_expr(proc->module->info, a));
  3602. if (at->kind == Type_Tuple) {
  3603. arg_count += at->Tuple.variable_count;
  3604. } else {
  3605. arg_count++;
  3606. }
  3607. }
  3608. irValue **args = gb_alloc_array(proc->module->allocator, irValue *, arg_count);
  3609. bool vari_expand = ce->ellipsis.pos.line != 0;
  3610. for_array(i, ce->args) {
  3611. irValue *a = ir_build_expr(proc, ce->args[i]);
  3612. Type *at = ir_type(a);
  3613. if (at->kind == Type_Tuple) {
  3614. for (isize i = 0; i < at->Tuple.variable_count; i++) {
  3615. Entity *e = at->Tuple.variables[i];
  3616. irValue *v = ir_emit_struct_ev(proc, a, i);
  3617. args[arg_index++] = v;
  3618. }
  3619. } else {
  3620. args[arg_index++] = a;
  3621. }
  3622. }
  3623. if (!vari_expand) {
  3624. for (isize i = 1; i < arg_count; i++) {
  3625. args[i] = ir_emit_conv(proc, args[i], elem_type);
  3626. }
  3627. }
  3628. if (!vari_expand) {
  3629. ir_emit_comment(proc, str_lit("variadic call argument generation"));
  3630. Type *slice_type = make_type_slice(a, elem_type);
  3631. irValue *slice = ir_add_local_generated(proc, slice_type);
  3632. isize slice_len = arg_count-1;
  3633. if (slice_len > 0) {
  3634. irValue *base_array = ir_add_local_generated(proc, make_type_array(a, elem_type, slice_len));
  3635. for (isize i = 1; i < arg_count; i++) {
  3636. irValue *addr = ir_emit_array_epi(proc, base_array, i-1);
  3637. ir_emit_store(proc, addr, args[i]);
  3638. }
  3639. irValue *base_elem = ir_emit_array_epi(proc, base_array, 0);
  3640. irValue *len = ir_const_int(a, slice_len);
  3641. ir_fill_slice(proc, slice, base_elem, len, len);
  3642. }
  3643. arg_count = 2;
  3644. args[arg_count-1] = ir_emit_load(proc, slice);
  3645. }
  3646. irValue *item_slice = args[1];
  3647. irValue *items = ir_slice_elem(proc, item_slice);
  3648. irValue *item_count = ir_slice_count(proc, item_slice);
  3649. irValue **daa_args = gb_alloc_array(a, irValue *, 5);
  3650. daa_args[0] = array_ptr;
  3651. daa_args[1] = elem_size;
  3652. daa_args[2] = elem_align;
  3653. daa_args[3] = ir_emit_conv(proc, items, t_rawptr);
  3654. daa_args[4] = ir_emit_conv(proc, item_count, t_int);
  3655. if (is_slice) {
  3656. return ir_emit_global_call(proc, "__slice_append", daa_args, 5);
  3657. }
  3658. return ir_emit_global_call(proc, "__dynamic_array_append", daa_args, 5);
  3659. break;
  3660. }
  3661. #endif
  3662. #if 0
  3663. case BuiltinProc_delete: {
  3664. ir_emit_comment(proc, str_lit("delete"));
  3665. irValue *map = ir_build_expr(proc, ce->args[0]);
  3666. irValue *key = ir_build_expr(proc, ce->args[1]);
  3667. Type *map_type = ir_type(map);
  3668. GB_ASSERT(is_type_map(map_type));
  3669. Type *key_type = base_type(map_type)->Map.key;
  3670. irValue *addr = ir_address_from_load_or_generate_local(proc, map);
  3671. gbAllocator a = proc->module->allocator;
  3672. irValue **args = gb_alloc_array(a, irValue *, 2);
  3673. args[0] = ir_gen_map_header(proc, addr, map_type);
  3674. args[1] = ir_gen_map_key(proc, key, key_type);
  3675. return ir_emit_global_call(proc, "__dynamic_map_delete", args, 2);
  3676. break;
  3677. }
  3678. #endif
  3679. case BuiltinProc_swizzle: {
  3680. ir_emit_comment(proc, str_lit("swizzle.begin"));
  3681. irAddr vector_addr = ir_build_addr(proc, ce->args[0]);
  3682. isize index_count = ce->args.count-1;
  3683. if (index_count == 0) {
  3684. return ir_addr_load(proc, vector_addr);
  3685. }
  3686. irValue *src = ir_addr_get_ptr(proc, vector_addr);
  3687. irValue *dst = ir_add_local_generated(proc, tv.type);
  3688. for (i32 i = 1; i < ce->args.count; i++) {
  3689. TypeAndValue tv = type_and_value_of_expr(proc->module->info, ce->args[i]);
  3690. GB_ASSERT(is_type_integer(tv.type));
  3691. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  3692. i32 src_index = cast(i32)i128_to_i64(tv.value.value_integer);
  3693. i32 dst_index = i-1;
  3694. irValue *src_elem = ir_emit_array_epi(proc, src, src_index);
  3695. irValue *dst_elem = ir_emit_array_epi(proc, dst, dst_index);
  3696. ir_emit_store(proc, dst_elem, ir_emit_load(proc, src_elem));
  3697. }
  3698. ir_emit_comment(proc, str_lit("swizzle.end"));
  3699. return ir_emit_load(proc, dst);
  3700. // return ir_emit(proc, ir_instr_vector_shuffle(proc, vector, indices, index_count));
  3701. break;
  3702. }
  3703. case BuiltinProc_complex: {
  3704. ir_emit_comment(proc, str_lit("complex"));
  3705. irValue *real = ir_build_expr(proc, ce->args[0]);
  3706. irValue *imag = ir_build_expr(proc, ce->args[1]);
  3707. irValue *dst = ir_add_local_generated(proc, tv.type);
  3708. Type *ft = base_complex_elem_type(tv.type);
  3709. real = ir_emit_conv(proc, real, ft);
  3710. imag = ir_emit_conv(proc, imag, ft);
  3711. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 0), real);
  3712. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 1), imag);
  3713. return ir_emit_load(proc, dst);
  3714. break;
  3715. }
  3716. case BuiltinProc_real: {
  3717. ir_emit_comment(proc, str_lit("real"));
  3718. irValue *val = ir_build_expr(proc, ce->args[0]);
  3719. irValue *real = ir_emit_struct_ev(proc, val, 0);
  3720. return ir_emit_conv(proc, real, tv.type);
  3721. break;
  3722. }
  3723. case BuiltinProc_imag: {
  3724. ir_emit_comment(proc, str_lit("imag"));
  3725. irValue *val = ir_build_expr(proc, ce->args[0]);
  3726. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  3727. return ir_emit_conv(proc, imag, tv.type);
  3728. break;
  3729. }
  3730. case BuiltinProc_conj: {
  3731. ir_emit_comment(proc, str_lit("conj"));
  3732. irValue *val = ir_build_expr(proc, ce->args[0]);
  3733. irValue *res = nullptr;
  3734. Type *t = ir_type(val);
  3735. if (is_type_complex(t)) {
  3736. res = ir_add_local_generated(proc, tv.type);
  3737. irValue *real = ir_emit_struct_ev(proc, val, 0);
  3738. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  3739. imag = ir_emit_unary_arith(proc, Token_Sub, imag, ir_type(imag));
  3740. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
  3741. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
  3742. }
  3743. return ir_emit_load(proc, res);
  3744. break;
  3745. }
  3746. #if 0
  3747. case BuiltinProc_slice_ptr: {
  3748. ir_emit_comment(proc, str_lit("slice_ptr"));
  3749. irValue *ptr = ir_build_expr(proc, ce->args[0]);
  3750. irValue *count = ir_build_expr(proc, ce->args[1]);
  3751. count = ir_emit_conv(proc, count, t_int);
  3752. irValue *capacity = count;
  3753. if (ce->args.count > 2) {
  3754. capacity = ir_build_expr(proc, ce->args[2]);
  3755. capacity = ir_emit_conv(proc, capacity, t_int);
  3756. }
  3757. Type *slice_type = make_type_slice(proc->module->allocator, type_deref(ir_type(ptr)));
  3758. irValue *slice = ir_add_local_generated(proc, slice_type);
  3759. ir_fill_slice(proc, slice, ptr, count, capacity);
  3760. return ir_emit_load(proc, slice);
  3761. break;
  3762. }
  3763. case BuiltinProc_slice_to_bytes: {
  3764. ir_emit_comment(proc, str_lit("slice_to_bytes"));
  3765. irValue *s = ir_build_expr(proc, ce->args[0]);
  3766. Type *t = base_type(ir_type(s));
  3767. if (is_type_u8_slice(t)) {
  3768. return ir_emit_conv(proc, s, tv.type);
  3769. }
  3770. irValue *slice = ir_add_local_generated(proc, tv.type);
  3771. i64 elem_size = type_size_of(proc->module->allocator, t->Slice.elem);
  3772. irValue *ptr = ir_emit_conv(proc, ir_slice_elem(proc, s), t_u8_ptr);
  3773. irValue *count = ir_slice_count(proc, s);
  3774. irValue *capacity = ir_slice_capacity(proc, s);
  3775. count = ir_emit_arith(proc, Token_Mul, count, ir_const_int(proc->module->allocator, elem_size), t_int);
  3776. capacity = ir_emit_arith(proc, Token_Mul, capacity, ir_const_int(proc->module->allocator, elem_size), t_int);
  3777. ir_fill_slice(proc, slice, ptr, count, capacity);
  3778. return ir_emit_load(proc, slice);
  3779. break;
  3780. }
  3781. #endif
  3782. case BuiltinProc_expand_to_tuple: {
  3783. ir_emit_comment(proc, str_lit("expand_to_tuple"));
  3784. irValue *s = ir_build_expr(proc, ce->args[0]);
  3785. Type *t = base_type(ir_type(s));
  3786. GB_ASSERT(t->kind == Type_Struct);
  3787. GB_ASSERT(is_type_tuple(tv.type));
  3788. irValue *tuple = ir_add_local_generated(proc, tv.type);
  3789. for_array(src_index, t->Struct.fields) {
  3790. Entity *field = t->Struct.fields_in_src_order[src_index];
  3791. i32 field_index = field->Variable.field_index;
  3792. irValue *f = ir_emit_struct_ev(proc, s, field_index);
  3793. irValue *ep = ir_emit_struct_ep(proc, tuple, cast(i32)src_index);
  3794. ir_emit_store(proc, ep, f);
  3795. }
  3796. return ir_emit_load(proc, tuple);
  3797. break;
  3798. }
  3799. case BuiltinProc_min: {
  3800. ir_emit_comment(proc, str_lit("min"));
  3801. Type *t = type_of_expr(proc->module->info, expr);
  3802. irValue *x = ir_emit_conv(proc, ir_build_expr(proc, ce->args[0]), t);
  3803. irValue *y = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t);
  3804. irValue *cond = ir_emit_comp(proc, Token_Lt, x, y);
  3805. return ir_emit_select(proc, cond, x, y);
  3806. break;
  3807. }
  3808. case BuiltinProc_max: {
  3809. ir_emit_comment(proc, str_lit("max"));
  3810. Type *t = type_of_expr(proc->module->info, expr);
  3811. irValue *x = ir_emit_conv(proc, ir_build_expr(proc, ce->args[0]), t);
  3812. irValue *y = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t);
  3813. irValue *cond = ir_emit_comp(proc, Token_Gt, x, y);
  3814. return ir_emit_select(proc, cond, x, y);
  3815. break;
  3816. }
  3817. case BuiltinProc_abs: {
  3818. ir_emit_comment(proc, str_lit("abs"));
  3819. irValue *x = ir_build_expr(proc, ce->args[0]);
  3820. Type *t = ir_type(x);
  3821. if (is_type_complex(t)) {
  3822. gbAllocator a = proc->module->allocator;
  3823. i64 sz = 8*type_size_of(a, t);
  3824. irValue **args = gb_alloc_array(a, irValue *, 1);
  3825. args[0] = x;
  3826. switch (sz) {
  3827. case 64: return ir_emit_global_call(proc, "__abs_complex64", args, 1);
  3828. case 128: return ir_emit_global_call(proc, "__abs_complex128", args, 1);
  3829. }
  3830. GB_PANIC("Unknown complex type");
  3831. }
  3832. irValue *zero = ir_emit_conv(proc, v_zero, t);
  3833. irValue *cond = ir_emit_comp(proc, Token_Lt, x, zero);
  3834. irValue *neg = ir_emit(proc, ir_instr_unary_op(proc, Token_Sub, x, t));
  3835. return ir_emit_select(proc, cond, neg, x);
  3836. break;
  3837. }
  3838. case BuiltinProc_clamp: {
  3839. ir_emit_comment(proc, str_lit("clamp"));
  3840. Type *t = type_of_expr(proc->module->info, expr);
  3841. return ir_emit_clamp(proc, t,
  3842. ir_build_expr(proc, ce->args[0]),
  3843. ir_build_expr(proc, ce->args[1]),
  3844. ir_build_expr(proc, ce->args[2]));
  3845. break;
  3846. }
  3847. }
  3848. GB_PANIC("Unhandled built-in procedure");
  3849. return nullptr;
  3850. }
  3851. irValue *ir_build_expr(irProcedure *proc, AstNode *expr) {
  3852. expr = unparen_expr(expr);
  3853. TypeAndValue tv = type_and_value_of_expr(proc->module->info, expr);
  3854. GB_ASSERT(tv.mode != Addressing_Invalid);
  3855. GB_ASSERT(tv.mode != Addressing_Type);
  3856. #if 0
  3857. if (tv.mode == Addressing_Type) {
  3858. // // TODO(bill): Handle this correctly
  3859. #if 0
  3860. i32 entry_index = type_info_index(proc->module->info, tv.type, false);
  3861. if (entry_index >= 0) {
  3862. return ir_get_type_info_ptr(proc, tv.type);
  3863. // i32 id = entry_index+1;
  3864. // return ir_value_constant(proc->module->allocator, t_int, exact_value_i64(id));
  3865. }
  3866. #endif
  3867. // return v_raw_nil;
  3868. return ir_value_nil(proc->module->allocator, tv.type);
  3869. }
  3870. #endif
  3871. if (tv.value.kind != ExactValue_Invalid) {
  3872. // NOTE(bill): Edge case
  3873. if (tv.value.kind != ExactValue_Compound &&
  3874. is_type_vector(tv.type)) {
  3875. Type *elem = base_vector_type(tv.type);
  3876. ExactValue value = convert_exact_value_for_type(tv.value, elem);
  3877. irValue *x = ir_add_module_constant(proc->module, elem, value);
  3878. return ir_emit_conv(proc, x, tv.type);
  3879. }
  3880. return ir_add_module_constant(proc->module, tv.type, tv.value);
  3881. }
  3882. if (tv.mode == Addressing_Variable) {
  3883. return ir_addr_load(proc, ir_build_addr(proc, expr));
  3884. }
  3885. switch (expr->kind) {
  3886. case_ast_node(bl, BasicLit, expr);
  3887. TokenPos pos = bl->pos;
  3888. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->kind]));
  3889. case_end;
  3890. case_ast_node(bd, BasicDirective, expr);
  3891. TokenPos pos = bd->token.pos;
  3892. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  3893. case_end;
  3894. case_ast_node(i, Implicit, expr);
  3895. return ir_addr_load(proc, ir_build_addr(proc, expr));
  3896. case_end;
  3897. case_ast_node(u, Undef, expr);
  3898. return ir_value_undef(proc->module->allocator, tv.type);
  3899. case_end;
  3900. case_ast_node(i, Ident, expr);
  3901. Entity *e = entity_of_ident(proc->module->info, expr);
  3902. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  3903. if (e->kind == Entity_Builtin) {
  3904. Token token = ast_node_token(expr);
  3905. GB_PANIC("TODO(bill): ir_build_single_expr Entity_Builtin `%.*s`\n"
  3906. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  3907. LIT(token.pos.file), token.pos.line, token.pos.column);
  3908. return nullptr;
  3909. } else if (e->kind == Entity_Nil) {
  3910. return ir_value_nil(proc->module->allocator, tv.type);
  3911. }
  3912. irValue **found = map_get(&proc->module->values, hash_entity(e));
  3913. if (found) {
  3914. irValue *v = *found;
  3915. if (v->kind == irValue_Proc) {
  3916. return v;
  3917. }
  3918. // if (e->kind == Entity_Variable && e->Variable.param) {
  3919. // return v;
  3920. // }
  3921. return ir_emit_load(proc, v);
  3922. } else if (e != nullptr && e->kind == Entity_Variable) {
  3923. return ir_addr_load(proc, ir_build_addr(proc, expr));
  3924. }
  3925. GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr);
  3926. return nullptr;
  3927. case_end;
  3928. case_ast_node(re, RunExpr, expr);
  3929. // TODO(bill): Run Expression
  3930. return ir_build_expr(proc, re->expr);
  3931. case_end;
  3932. case_ast_node(de, DerefExpr, expr);
  3933. return ir_addr_load(proc, ir_build_addr(proc, expr));
  3934. case_end;
  3935. case_ast_node(se, SelectorExpr, expr);
  3936. TypeAndValue tav = type_and_value_of_expr(proc->module->info, expr);
  3937. GB_ASSERT(tav.mode != Addressing_Invalid);
  3938. return ir_addr_load(proc, ir_build_addr(proc, expr));
  3939. case_end;
  3940. case_ast_node(te, TernaryExpr, expr);
  3941. ir_emit_comment(proc, str_lit("TernaryExpr"));
  3942. Array<irValue *> edges = {};
  3943. array_init(&edges, proc->module->allocator, 2);
  3944. GB_ASSERT(te->y != nullptr);
  3945. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  3946. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  3947. irBlock *else_ = ir_new_block(proc, nullptr, "if.else");
  3948. irValue *cond = ir_build_cond(proc, te->cond, then, else_);
  3949. ir_start_block(proc, then);
  3950. Type *type = type_of_expr(proc->module->info, expr);
  3951. ir_open_scope(proc);
  3952. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->x), type));
  3953. ir_close_scope(proc, irDeferExit_Default, nullptr);
  3954. ir_emit_jump(proc, done);
  3955. ir_start_block(proc, else_);
  3956. ir_open_scope(proc);
  3957. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->y), type));
  3958. ir_close_scope(proc, irDeferExit_Default, nullptr);
  3959. ir_emit_jump(proc, done);
  3960. ir_start_block(proc, done);
  3961. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  3962. case_end;
  3963. #if 0
  3964. case_ast_node(ie, IfExpr, expr);
  3965. ir_emit_comment(proc, str_lit("IfExpr"));
  3966. if (ie->init != nullptr) {
  3967. irBlock *init = ir_new_block(proc, expr, "if.init");
  3968. ir_emit_jump(proc, init);
  3969. ir_start_block(proc, init);
  3970. ir_build_stmt(proc, ie->init);
  3971. }
  3972. Array<irValue *> edges = {};
  3973. array_init(&edges, proc->module->allocator, 2);
  3974. GB_ASSERT(ie->else_expr != nullptr);
  3975. irBlock *then = ir_new_block(proc, expr, "if.then");
  3976. irBlock *done = ir_new_block(proc, expr, "if.done"); // NOTE(bill): Append later
  3977. irBlock *else_ = ir_new_block(proc, ie->else_expr, "if.else");
  3978. irValue *cond = ir_build_cond(proc, ie->cond, then, else_);
  3979. ir_start_block(proc, then);
  3980. ir_open_scope(proc);
  3981. array_add(&edges, ir_build_expr(proc, ie->body));
  3982. ir_close_scope(proc, irDeferExit_Default, nullptr);
  3983. ir_emit_jump(proc, done);
  3984. ir_start_block(proc, else_);
  3985. ir_open_scope(proc);
  3986. array_add(&edges, ir_build_expr(proc, ie->else_expr));
  3987. ir_close_scope(proc, irDeferExit_Default, nullptr);
  3988. ir_emit_jump(proc, done);
  3989. ir_start_block(proc, done);
  3990. Type *type = type_of_expr(proc->module->info, expr);
  3991. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  3992. case_end;
  3993. #endif
  3994. case_ast_node(ta, TypeAssertion, expr);
  3995. TokenPos pos = ast_node_token(expr).pos;
  3996. Type *type = tv.type;
  3997. irValue *e = ir_build_expr(proc, ta->expr);
  3998. Type *t = type_deref(ir_type(e));
  3999. if (is_type_union(t)) {
  4000. ir_emit_comment(proc, str_lit("cast - union_cast"));
  4001. return ir_emit_union_cast(proc, e, type, pos);
  4002. } else if (is_type_any(t)) {
  4003. ir_emit_comment(proc, str_lit("cast - any_cast"));
  4004. return ir_emit_any_cast(proc, e, type, pos);
  4005. } else {
  4006. GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
  4007. }
  4008. case_end;
  4009. case_ast_node(tc, TypeCast, expr);
  4010. irValue *e = ir_build_expr(proc, tc->expr);
  4011. switch (tc->token.kind) {
  4012. case Token_cast:
  4013. return ir_emit_conv(proc, e, tv.type);
  4014. case Token_transmute:
  4015. return ir_emit_transmute(proc, e, tv.type);
  4016. }
  4017. GB_PANIC("Invalid AST TypeCast");
  4018. case_end;
  4019. case_ast_node(ue, UnaryExpr, expr);
  4020. switch (ue->op.kind) {
  4021. case Token_And:
  4022. return ir_emit_ptr_offset(proc, ir_build_addr_ptr(proc, ue->expr), v_zero); // Make a copy of the pointer
  4023. default:
  4024. return ir_emit_unary_arith(proc, ue->op.kind, ir_build_expr(proc, ue->expr), tv.type);
  4025. }
  4026. case_end;
  4027. case_ast_node(be, BinaryExpr, expr);
  4028. irValue *left = ir_build_expr(proc, be->left);
  4029. Type *type = default_type(tv.type);
  4030. switch (be->op.kind) {
  4031. case Token_Add:
  4032. case Token_Sub:
  4033. case Token_Mul:
  4034. case Token_Quo:
  4035. case Token_Mod:
  4036. case Token_ModMod:
  4037. case Token_And:
  4038. case Token_Or:
  4039. case Token_Xor:
  4040. case Token_AndNot:
  4041. case Token_Shl:
  4042. case Token_Shr: {
  4043. irValue *right = ir_build_expr(proc, be->right);
  4044. return ir_emit_arith(proc, be->op.kind, left, right, type);
  4045. }
  4046. case Token_CmpEq:
  4047. case Token_NotEq:
  4048. case Token_Lt:
  4049. case Token_LtEq:
  4050. case Token_Gt:
  4051. case Token_GtEq: {
  4052. irValue *right = ir_build_expr(proc, be->right);
  4053. irValue *cmp = ir_emit_comp(proc, be->op.kind, left, right);
  4054. return ir_emit_conv(proc, cmp, type);
  4055. break;
  4056. }
  4057. case Token_CmpAnd:
  4058. case Token_CmpOr:
  4059. if (is_type_vector(type)) {
  4060. TokenKind op = {};
  4061. switch (be->op.kind) {
  4062. case Token_CmpAnd: op = Token_And; break;
  4063. case Token_CmpOr: op = Token_Or; break;
  4064. }
  4065. irValue *right = ir_build_expr(proc, be->right);
  4066. return ir_emit_arith(proc, op, left, right, type);
  4067. }
  4068. return ir_emit_logical_binary_expr(proc, expr);
  4069. default:
  4070. GB_PANIC("Invalid binary expression");
  4071. break;
  4072. }
  4073. case_end;
  4074. case_ast_node(pl, ProcLit, expr);
  4075. return ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  4076. case_end;
  4077. case_ast_node(cl, CompoundLit, expr);
  4078. return ir_addr_load(proc, ir_build_addr(proc, expr));
  4079. case_end;
  4080. case_ast_node(ce, CallExpr, expr);
  4081. TypeAndValue proc_tv = type_and_value_of_expr(proc->module->info, ce->proc);
  4082. AddressingMode proc_mode = proc_tv.mode;
  4083. if (proc_mode == Addressing_Type) {
  4084. GB_ASSERT(ce->args.count == 1);
  4085. irValue *x = ir_build_expr(proc, ce->args[0]);
  4086. irValue *y = ir_emit_conv(proc, x, tv.type);
  4087. return y;
  4088. }
  4089. AstNode *p = unparen_expr(ce->proc);
  4090. if (proc_mode == Addressing_Builtin) {
  4091. Entity *e = entity_of_ident(proc->module->info, p);
  4092. BuiltinProcId id = BuiltinProc_Invalid;
  4093. if (e != nullptr) {
  4094. id = cast(BuiltinProcId)e->Builtin.id;
  4095. } else {
  4096. id = BuiltinProc_DIRECTIVE;
  4097. if (ce->proc->kind == AstNode_Implicit) {
  4098. ast_node(i, Implicit, ce->proc);
  4099. GB_ASSERT(i->kind == Token_type_info_of);
  4100. id = BuiltinProc_type_info_of;
  4101. }
  4102. }
  4103. return ir_build_builtin_proc(proc, expr, tv, id);
  4104. }
  4105. // NOTE(bill): Regular call
  4106. irValue *value = ir_build_expr(proc, ce->proc);
  4107. GB_ASSERT(value != nullptr);
  4108. Type *proc_type_ = base_type(ir_type(value));
  4109. GB_ASSERT(proc_type_->kind == Type_Proc);
  4110. TypeProc *type = &proc_type_->Proc;
  4111. if (is_call_expr_field_value(ce)) {
  4112. isize param_count = type->param_count;
  4113. irValue **args = gb_alloc_array(proc->module->allocator, irValue *, param_count);
  4114. for_array(arg_index, ce->args) {
  4115. AstNode *arg = ce->args[arg_index];
  4116. ast_node(fv, FieldValue, arg);
  4117. GB_ASSERT(fv->field->kind == AstNode_Ident);
  4118. String name = fv->field->Ident.token.string;
  4119. isize index = lookup_procedure_parameter(type, name);
  4120. GB_ASSERT(index >= 0);
  4121. TypeAndValue tav = type_and_value_of_expr(proc->module->info, fv->value);
  4122. if (tav.mode == Addressing_Type) {
  4123. args[index] = ir_value_nil(proc->module->allocator, tav.type);
  4124. } else {
  4125. args[index] = ir_build_expr(proc, fv->value);
  4126. }
  4127. }
  4128. TypeTuple *pt = &type->params->Tuple;
  4129. for (isize i = 0; i < param_count; i++) {
  4130. Entity *e = pt->variables[i];
  4131. if (e->kind == Entity_TypeName) {
  4132. args[i] = ir_value_nil(proc->module->allocator, e->type);
  4133. } else {
  4134. GB_ASSERT(e->kind == Entity_Variable);
  4135. if (args[i] == nullptr) {
  4136. if (e->Variable.default_value.kind != ExactValue_Invalid) {
  4137. args[i] = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value);
  4138. } else {
  4139. args[i] = ir_value_nil(proc->module->allocator, e->type);
  4140. }
  4141. } else {
  4142. args[i] = ir_emit_conv(proc, args[i], e->type);
  4143. }
  4144. }
  4145. }
  4146. return ir_emit_call(proc, value, args, param_count);
  4147. }
  4148. isize arg_index = 0;
  4149. isize arg_count = 0;
  4150. for_array(i, ce->args) {
  4151. AstNode *a = ce->args[i];
  4152. Type *at = base_type(type_of_expr(proc->module->info, a));
  4153. if (at->kind == Type_Tuple) {
  4154. arg_count += at->Tuple.variables.count;
  4155. } else {
  4156. arg_count++;
  4157. }
  4158. }
  4159. irValue **args = gb_alloc_array(proc->module->allocator, irValue *, gb_max(type->param_count, arg_count));
  4160. bool variadic = type->variadic;
  4161. bool vari_expand = ce->ellipsis.pos.line != 0;
  4162. bool is_c_vararg = type->c_vararg;
  4163. for_array(i, ce->args) {
  4164. AstNode *arg = ce->args[i];
  4165. TypeAndValue arg_tv = type_and_value_of_expr(proc->module->info, arg);
  4166. if (arg_tv.mode == Addressing_Type) {
  4167. args[arg_index++] = ir_value_nil(proc->module->allocator, arg_tv.type);
  4168. } else {
  4169. irValue *a = ir_build_expr(proc, arg);
  4170. Type *at = ir_type(a);
  4171. if (at->kind == Type_Tuple) {
  4172. for_array(i, at->Tuple.variables) {
  4173. Entity *e = at->Tuple.variables[i];
  4174. irValue *v = ir_emit_struct_ev(proc, a, cast(i32)i);
  4175. args[arg_index++] = v;
  4176. }
  4177. } else {
  4178. args[arg_index++] = a;
  4179. }
  4180. }
  4181. }
  4182. TypeTuple *pt = &type->params->Tuple;
  4183. if (arg_count < type->param_count) {
  4184. String procedure = {};
  4185. if (proc->entity != nullptr) {
  4186. procedure = proc->entity->token.string;
  4187. }
  4188. TokenPos pos = ast_node_token(ce->proc).pos;
  4189. isize end = type->param_count;
  4190. if (variadic) {
  4191. end--;
  4192. }
  4193. while (arg_index < end) {
  4194. Entity *e = pt->variables[arg_index];
  4195. GB_ASSERT(e->kind == Entity_Variable);
  4196. if (e->Variable.default_value.kind != ExactValue_Invalid) {
  4197. args[arg_index++] = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value);
  4198. } else if (e->Variable.default_is_location) {
  4199. args[arg_index++] = ir_emit_source_code_location(proc, procedure, pos);
  4200. } else {
  4201. args[arg_index++] = ir_value_nil(proc->module->allocator, e->type);
  4202. }
  4203. }
  4204. }
  4205. if (is_c_vararg) {
  4206. GB_ASSERT(variadic);
  4207. GB_ASSERT(!vari_expand);
  4208. isize i = 0;
  4209. for (; i < type->param_count-1; i++) {
  4210. Entity *e = pt->variables[i];
  4211. if (e->kind == Entity_Variable) {
  4212. args[i] = ir_emit_conv(proc, args[i], e->type);
  4213. }
  4214. }
  4215. Type *variadic_type = pt->variables[i]->type;
  4216. GB_ASSERT(is_type_slice(variadic_type));
  4217. variadic_type = base_type(variadic_type)->Slice.elem;
  4218. if (!is_type_any(variadic_type)) {
  4219. for (; i < arg_count; i++) {
  4220. args[i] = ir_emit_conv(proc, args[i], variadic_type);
  4221. }
  4222. } else {
  4223. for (; i < arg_count; i++) {
  4224. args[i] = ir_emit_conv(proc, args[i], default_type(ir_type(args[i])));
  4225. }
  4226. }
  4227. } else if (variadic) {
  4228. isize i = 0;
  4229. for (; i < type->param_count-1; i++) {
  4230. Entity *e = pt->variables[i];
  4231. if (e->kind == Entity_Variable) {
  4232. args[i] = ir_emit_conv(proc, args[i], e->type);
  4233. }
  4234. }
  4235. if (!vari_expand) {
  4236. Type *variadic_type = pt->variables[i]->type;
  4237. GB_ASSERT(is_type_slice(variadic_type));
  4238. variadic_type = base_type(variadic_type)->Slice.elem;
  4239. for (; i < arg_count; i++) {
  4240. args[i] = ir_emit_conv(proc, args[i], variadic_type);
  4241. }
  4242. }
  4243. } else {
  4244. for (isize i = 0; i < type->param_count; i++) {
  4245. Entity *e = pt->variables[i];
  4246. if (e->kind == Entity_Variable) {
  4247. args[i] = ir_emit_conv(proc, args[i], e->type);
  4248. }
  4249. }
  4250. }
  4251. i64 final_count = type->param_count;
  4252. if (is_c_vararg) {
  4253. final_count = arg_count;
  4254. }
  4255. if (variadic && !vari_expand && !is_c_vararg) {
  4256. ir_emit_comment(proc, str_lit("variadic call argument generation"));
  4257. gbAllocator allocator = proc->module->allocator;
  4258. Type *slice_type = pt->variables[type->param_count-1]->type;
  4259. Type *elem_type = base_type(slice_type)->Slice.elem;
  4260. irValue *slice = ir_add_local_generated(proc, slice_type);
  4261. isize slice_len = arg_count+1 - type->param_count;
  4262. if (slice_len > 0) {
  4263. irValue *base_array = ir_add_local_generated(proc, make_type_array(allocator, elem_type, slice_len));
  4264. for (isize i = type->param_count-1, j = 0; i < arg_count; i++, j++) {
  4265. irValue *addr = ir_emit_array_epi(proc, base_array, cast(i32)j);
  4266. ir_emit_store(proc, addr, args[i]);
  4267. }
  4268. irValue *base_elem = ir_emit_array_epi(proc, base_array, 0);
  4269. irValue *len = ir_const_int(allocator, slice_len);
  4270. ir_fill_slice(proc, slice, base_elem, len, len);
  4271. }
  4272. arg_count = type->param_count;
  4273. args[arg_count-1] = ir_emit_load(proc, slice);
  4274. }
  4275. return ir_emit_call(proc, value, args, final_count);
  4276. case_end;
  4277. case_ast_node(se, SliceExpr, expr);
  4278. return ir_addr_load(proc, ir_build_addr(proc, expr));
  4279. case_end;
  4280. case_ast_node(ie, IndexExpr, expr);
  4281. return ir_addr_load(proc, ir_build_addr(proc, expr));
  4282. case_end;
  4283. }
  4284. GB_PANIC("Unexpected expression: %.*s", LIT(ast_node_strings[expr->kind]));
  4285. return nullptr;
  4286. }
  4287. irValue *ir_get_using_variable(irProcedure *proc, Entity *e) {
  4288. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  4289. String name = e->token.string;
  4290. Entity *parent = e->using_parent;
  4291. Selection sel = lookup_field(proc->module->allocator, parent->type, name, false);
  4292. GB_ASSERT(sel.entity != nullptr);
  4293. irValue **pv = map_get(&proc->module->values, hash_entity(parent));
  4294. irValue *v = nullptr;
  4295. if (pv != nullptr) {
  4296. v = *pv;
  4297. } else {
  4298. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  4299. v = ir_build_addr_ptr(proc, e->using_expr);
  4300. }
  4301. GB_ASSERT(v != nullptr);
  4302. GB_ASSERT(parent->type == type_deref(ir_type(v)));
  4303. return ir_emit_deep_field_gep(proc, v, sel);
  4304. }
  4305. bool ir_is_elem_const(irModule *m, AstNode *elem, Type *elem_type) {
  4306. if (!elem_type_can_be_constant(elem_type)) {
  4307. return false;
  4308. }
  4309. if (elem->kind == AstNode_FieldValue) {
  4310. elem = elem->FieldValue.value;
  4311. }
  4312. TypeAndValue tav = type_and_value_of_expr(m->info, elem);
  4313. GB_ASSERT(tav.mode != Addressing_Invalid);
  4314. return tav.value.kind != ExactValue_Invalid;
  4315. }
  4316. irAddr ir_build_addr_from_entity(irProcedure *proc, Entity *e, AstNode *expr) {
  4317. GB_ASSERT(e != nullptr);
  4318. GB_ASSERT(e->kind != Entity_Constant);
  4319. irValue *v = nullptr;
  4320. irValue **found = map_get(&proc->module->values, hash_entity(e));
  4321. if (found) {
  4322. v = *found;
  4323. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  4324. // NOTE(bill): Calculate the using variable every time
  4325. v = ir_get_using_variable(proc, e);
  4326. }
  4327. if (v == nullptr) {
  4328. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  4329. LIT(proc->name),
  4330. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  4331. GB_PANIC("Unknown value");
  4332. }
  4333. return ir_addr(v);
  4334. }
  4335. irAddr ir_build_addr(irProcedure *proc, AstNode *expr) {
  4336. switch (expr->kind) {
  4337. case_ast_node(i, Implicit, expr);
  4338. irValue *v = nullptr;
  4339. switch (i->kind) {
  4340. case Token_context:
  4341. v = ir_find_or_generate_context_ptr(proc);
  4342. break;
  4343. }
  4344. GB_ASSERT(v != nullptr);
  4345. return ir_addr(v);
  4346. case_end;
  4347. case_ast_node(i, Ident, expr);
  4348. if (is_blank_ident(expr)) {
  4349. irAddr val = {};
  4350. return val;
  4351. }
  4352. String name = i->token.string;
  4353. Entity *e = entity_of_ident(proc->module->info, expr);
  4354. // GB_ASSERT(name == e->token.string);
  4355. return ir_build_addr_from_entity(proc, e, expr);
  4356. case_end;
  4357. case_ast_node(pe, ParenExpr, expr);
  4358. return ir_build_addr(proc, unparen_expr(expr));
  4359. case_end;
  4360. case_ast_node(se, SelectorExpr, expr);
  4361. ir_emit_comment(proc, str_lit("SelectorExpr"));
  4362. AstNode *sel = unparen_expr(se->selector);
  4363. if (sel->kind == AstNode_Ident) {
  4364. String selector = sel->Ident.token.string;
  4365. TypeAndValue tav = type_and_value_of_expr(proc->module->info, se->expr);
  4366. if (tav.mode == Addressing_Invalid) {
  4367. // NOTE(bill): Imports
  4368. Entity *imp = entity_of_ident(proc->module->info, se->expr);
  4369. if (imp != nullptr) {
  4370. GB_ASSERT(imp->kind == Entity_ImportName);
  4371. }
  4372. return ir_build_addr(proc, unparen_expr(se->selector));
  4373. }
  4374. Type *type = base_type(tav.type);
  4375. if (tav.mode == Addressing_Type) { // Addressing_Type
  4376. Selection sel = lookup_field(proc->module->allocator, type, selector, true);
  4377. Entity *e = sel.entity;
  4378. GB_ASSERT(e->kind == Entity_Variable);
  4379. GB_ASSERT(e->flags & EntityFlag_TypeField);
  4380. String name = e->token.string;
  4381. if (name == "names") {
  4382. irValue *ti_ptr = ir_type_info(proc, type);
  4383. irValue *variant = ir_emit_struct_ep(proc, ti_ptr, 2);
  4384. irValue *names_ptr = nullptr;
  4385. if (is_type_enum(type)) {
  4386. irValue *enum_info = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
  4387. names_ptr = ir_emit_struct_ep(proc, enum_info, 1);
  4388. } else if (type->kind == Type_Struct) {
  4389. irValue *struct_info = ir_emit_conv(proc, variant, t_type_info_struct_ptr);
  4390. names_ptr = ir_emit_struct_ep(proc, struct_info, 1);
  4391. }
  4392. return ir_addr(names_ptr);
  4393. } else {
  4394. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  4395. }
  4396. GB_PANIC("Unreachable");
  4397. }
  4398. Selection sel = lookup_field(proc->module->allocator, type, selector, false);
  4399. GB_ASSERT(sel.entity != nullptr);
  4400. if (sel.entity->type->kind == Type_BitFieldValue) {
  4401. irAddr addr = ir_build_addr(proc, se->expr);
  4402. Type *bft = type_deref(ir_addr_type(addr));
  4403. if (sel.index.count == 1) {
  4404. GB_ASSERT(is_type_bit_field(bft));
  4405. i32 index = sel.index[0];
  4406. return ir_addr_bit_field(ir_addr_get_ptr(proc, addr), index);
  4407. } else {
  4408. Selection s = sel;
  4409. s.index.count--;
  4410. i32 index = s.index[s.index.count-1];
  4411. irValue *a = ir_addr_get_ptr(proc, addr);
  4412. a = ir_emit_deep_field_gep(proc, a, s);
  4413. return ir_addr_bit_field(a, index);
  4414. }
  4415. } else {
  4416. irValue *a = ir_build_addr_ptr(proc, se->expr);
  4417. a = ir_emit_deep_field_gep(proc, a, sel);
  4418. return ir_addr(a);
  4419. }
  4420. } else {
  4421. // NOTE(bill): x.0
  4422. Type *type = type_deref(type_of_expr(proc->module->info, se->expr));
  4423. Type *selector_type = base_type(type_of_expr(proc->module->info, se->selector));
  4424. GB_ASSERT_MSG(is_type_integer(selector_type), "%s", type_to_string(selector_type));
  4425. ExactValue val = type_and_value_of_expr(proc->module->info, sel).value;
  4426. i64 index = i128_to_i64(val.value_integer);
  4427. Selection sel = lookup_field_from_index(proc->module->allocator, type, index);
  4428. GB_ASSERT(sel.entity != nullptr);
  4429. irValue *a = ir_build_addr_ptr(proc, se->expr);
  4430. a = ir_emit_deep_field_gep(proc, a, sel);
  4431. return ir_addr(a);
  4432. }
  4433. case_end;
  4434. case_ast_node(ta, TypeAssertion, expr);
  4435. gbAllocator a = proc->module->allocator;
  4436. TokenPos pos = ast_node_token(expr).pos;
  4437. irValue *e = ir_build_expr(proc, ta->expr);
  4438. Type *t = type_deref(ir_type(e));
  4439. if (is_type_union(t)) {
  4440. Type *type = type_of_expr(proc->module->info, expr);
  4441. irValue *v = ir_add_local_generated(proc, type);
  4442. ir_emit_comment(proc, str_lit("cast - union_cast"));
  4443. ir_emit_store(proc, v, ir_emit_union_cast(proc, ir_build_expr(proc, ta->expr), type, pos));
  4444. return ir_addr(v);
  4445. } else if (is_type_any(t)) {
  4446. ir_emit_comment(proc, str_lit("cast - any_cast"));
  4447. Type *type = type_of_expr(proc->module->info, expr);
  4448. return ir_emit_any_cast_addr(proc, ir_build_expr(proc, ta->expr), type, pos);
  4449. } else {
  4450. GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
  4451. }
  4452. case_end;
  4453. case_ast_node(ue, UnaryExpr, expr);
  4454. switch (ue->op.kind) {
  4455. case Token_And: {
  4456. return ir_build_addr(proc, ue->expr);
  4457. }
  4458. default:
  4459. GB_PANIC("Invalid unary expression for ir_build_addr");
  4460. }
  4461. case_end;
  4462. case_ast_node(be, BinaryExpr, expr);
  4463. GB_PANIC("Invalid binary expression for ir_build_addr: %.*s\n", LIT(be->op.string));
  4464. case_end;
  4465. case_ast_node(ie, IndexExpr, expr);
  4466. ir_emit_comment(proc, str_lit("IndexExpr"));
  4467. Type *t = base_type(type_of_expr(proc->module->info, ie->expr));
  4468. gbAllocator a = proc->module->allocator;
  4469. bool deref = is_type_pointer(t);
  4470. t = base_type(type_deref(t));
  4471. if (is_type_map(t)) {
  4472. irValue *map_val = ir_build_addr_ptr(proc, ie->expr);
  4473. irValue *key = ir_build_expr(proc, ie->index);
  4474. key = ir_emit_conv(proc, key, t->Map.key);
  4475. Type *result_type = type_of_expr(proc->module->info, expr);
  4476. return ir_addr_map(map_val, key, t, result_type);
  4477. }
  4478. irValue *using_addr = nullptr;
  4479. if (!is_type_indexable(t)) {
  4480. // Using index expression
  4481. Entity *using_field = find_using_index_expr(t);
  4482. if (using_field != nullptr) {
  4483. Selection sel = lookup_field(a, t, using_field->token.string, false);
  4484. irValue *e = ir_build_addr_ptr(proc, ie->expr);
  4485. using_addr = ir_emit_deep_field_gep(proc, e, sel);
  4486. t = using_field->type;
  4487. }
  4488. }
  4489. switch (t->kind) {
  4490. case Type_Vector: {
  4491. irValue *vector = nullptr;
  4492. if (using_addr != nullptr) {
  4493. vector = using_addr;
  4494. } else {
  4495. vector = ir_build_addr_ptr(proc, ie->expr);
  4496. if (deref) {
  4497. vector = ir_emit_load(proc, vector);
  4498. }
  4499. }
  4500. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  4501. irValue *elem = ir_emit_array_ep(proc, vector, index);
  4502. irValue *len = ir_const_int(a, t->Vector.count);
  4503. ir_emit_bounds_check(proc, ast_node_token(ie->index), index, len);
  4504. return ir_addr(elem);
  4505. break;
  4506. }
  4507. case Type_Array: {
  4508. irValue *array = nullptr;
  4509. if (using_addr != nullptr) {
  4510. array = using_addr;
  4511. } else {
  4512. array = ir_build_addr_ptr(proc, ie->expr);
  4513. if (deref) {
  4514. array = ir_emit_load(proc, array);
  4515. }
  4516. }
  4517. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  4518. irValue *elem = ir_emit_array_ep(proc, array, index);
  4519. irValue *len = ir_const_int(a, t->Vector.count);
  4520. ir_emit_bounds_check(proc, ast_node_token(ie->index), index, len);
  4521. return ir_addr(elem);
  4522. break;
  4523. }
  4524. case Type_Slice: {
  4525. irValue *slice = nullptr;
  4526. if (using_addr != nullptr) {
  4527. slice = ir_emit_load(proc, using_addr);
  4528. } else {
  4529. slice = ir_build_expr(proc, ie->expr);
  4530. if (deref) {
  4531. slice = ir_emit_load(proc, slice);
  4532. }
  4533. }
  4534. irValue *elem = ir_slice_elem(proc, slice);
  4535. irValue *len = ir_slice_count(proc, slice);
  4536. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  4537. ir_emit_bounds_check(proc, ast_node_token(ie->index), index, len);
  4538. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  4539. return ir_addr(v);
  4540. break;
  4541. }
  4542. case Type_DynamicArray: {
  4543. irValue *dynamic_array = nullptr;
  4544. if (using_addr != nullptr) {
  4545. dynamic_array = ir_emit_load(proc, using_addr);
  4546. } else {
  4547. dynamic_array = ir_build_expr(proc, ie->expr);
  4548. if (deref) {
  4549. dynamic_array = ir_emit_load(proc, dynamic_array);
  4550. }
  4551. }
  4552. irValue *elem = ir_dynamic_array_elem(proc, dynamic_array);
  4553. irValue *len = ir_dynamic_array_count(proc, dynamic_array);
  4554. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  4555. ir_emit_bounds_check(proc, ast_node_token(ie->index), index, len);
  4556. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  4557. return ir_addr(v);
  4558. break;
  4559. }
  4560. case Type_Basic: { // Basic_string
  4561. irValue *str;
  4562. irValue *elem;
  4563. irValue *len;
  4564. irValue *index;
  4565. if (using_addr != nullptr) {
  4566. str = ir_emit_load(proc, using_addr);
  4567. } else {
  4568. str = ir_build_expr(proc, ie->expr);
  4569. if (deref) {
  4570. str = ir_emit_load(proc, str);
  4571. }
  4572. }
  4573. elem = ir_string_elem(proc, str);
  4574. len = ir_string_len(proc, str);
  4575. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  4576. ir_emit_bounds_check(proc, ast_node_token(ie->index), index, len);
  4577. return ir_addr(ir_emit_ptr_offset(proc, elem, index));
  4578. break;
  4579. }
  4580. }
  4581. case_end;
  4582. case_ast_node(se, SliceExpr, expr);
  4583. ir_emit_comment(proc, str_lit("SliceExpr"));
  4584. gbAllocator a = proc->module->allocator;
  4585. irValue *low = v_zero;
  4586. irValue *high = nullptr;
  4587. irValue *max = nullptr;
  4588. if (se->low != nullptr) low = ir_build_expr(proc, se->low);
  4589. if (se->high != nullptr) high = ir_build_expr(proc, se->high);
  4590. if (se->max != nullptr) max = ir_build_expr(proc, se->max);
  4591. if (high != nullptr && se->interval0.kind == Token_Ellipsis) {
  4592. high = ir_emit_arith(proc, Token_Add, high, v_one, t_int);
  4593. }
  4594. if (max != nullptr && se->interval1.kind == Token_Ellipsis) {
  4595. max = ir_emit_arith(proc, Token_Add, max, v_one, t_int);
  4596. }
  4597. irValue *addr = ir_build_addr_ptr(proc, se->expr);
  4598. irValue *base = ir_emit_load(proc, addr);
  4599. Type *type = base_type(ir_type(base));
  4600. if (is_type_pointer(type)) {
  4601. type = base_type(type_deref(type));
  4602. addr = base;
  4603. base = ir_emit_load(proc, base);
  4604. }
  4605. // TODO(bill): Cleanup like mad!
  4606. switch (type->kind) {
  4607. case Type_Slice: {
  4608. Type *slice_type = type;
  4609. if (high == nullptr) high = ir_slice_count(proc, base);
  4610. if (max == nullptr) max = ir_slice_capacity(proc, base);
  4611. ir_emit_slice_bounds_check(proc, se->open, low, high, max, false);
  4612. irValue *elem = ir_emit_ptr_offset(proc, ir_slice_elem(proc, base), low);
  4613. irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  4614. irValue *cap = ir_emit_arith(proc, Token_Sub, max, low, t_int);
  4615. irValue *slice = ir_add_local_generated(proc, slice_type);
  4616. ir_fill_slice(proc, slice, elem, len, cap);
  4617. return ir_addr(slice);
  4618. }
  4619. case Type_DynamicArray: {
  4620. Type *elem_type = type->DynamicArray.elem;
  4621. Type *slice_type = make_type_slice(a, elem_type);
  4622. if (high == nullptr) high = ir_dynamic_array_count(proc, base);
  4623. if (max == nullptr) max = ir_dynamic_array_capacity(proc, base);
  4624. ir_emit_slice_bounds_check(proc, se->open, low, high, max, false);
  4625. irValue *elem = ir_emit_ptr_offset(proc, ir_dynamic_array_elem(proc, base), low);
  4626. irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  4627. irValue *cap = ir_emit_arith(proc, Token_Sub, max, low, t_int);
  4628. irValue *slice = ir_add_local_generated(proc, slice_type);
  4629. ir_fill_slice(proc, slice, elem, len, cap);
  4630. return ir_addr(slice);
  4631. }
  4632. case Type_Array: {
  4633. Type *slice_type = make_type_slice(a, type->Array.elem);
  4634. if (high == nullptr) high = ir_array_len(proc, base);
  4635. if (max == nullptr) max = ir_array_len(proc, base);
  4636. ir_emit_slice_bounds_check(proc, se->open, low, high, max, false);
  4637. irValue *elem = ir_emit_ptr_offset(proc, ir_array_elem(proc, addr), low);
  4638. irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  4639. irValue *cap = ir_emit_arith(proc, Token_Sub, max, low, t_int);
  4640. irValue *slice = ir_add_local_generated(proc, slice_type);
  4641. ir_fill_slice(proc, slice, elem, len, cap);
  4642. return ir_addr(slice);
  4643. }
  4644. case Type_Basic: {
  4645. GB_ASSERT(type == t_string);
  4646. if (high == nullptr) high = ir_string_len(proc, base);
  4647. // if (max == nullptr) max = ir_string_len(proc, base);
  4648. ir_emit_slice_bounds_check(proc, se->open, low, high, nullptr, true);
  4649. irValue *elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, base), low);
  4650. irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  4651. irValue *str = ir_add_local_generated(proc, t_string);
  4652. ir_fill_string(proc, str, elem, len);
  4653. return ir_addr(str);
  4654. break;
  4655. }
  4656. }
  4657. GB_PANIC("Unknown slicable type");
  4658. case_end;
  4659. case_ast_node(de, DerefExpr, expr);
  4660. // TODO(bill): Is a ptr copy needed?
  4661. irValue *addr = ir_build_expr(proc, de->expr);
  4662. addr = ir_emit_ptr_offset(proc, addr, v_zero);
  4663. return ir_addr(addr);
  4664. case_end;
  4665. case_ast_node(ce, CallExpr, expr);
  4666. // NOTE(bill): This is make sure you never need to have an `array_ev`
  4667. irValue *e = ir_build_expr(proc, expr);
  4668. irValue *v = ir_add_local_generated(proc, ir_type(e));
  4669. ir_emit_store(proc, v, e);
  4670. return ir_addr(v);
  4671. case_end;
  4672. case_ast_node(cl, CompoundLit, expr);
  4673. ir_emit_comment(proc, str_lit("CompoundLit"));
  4674. Type *type = type_of_expr(proc->module->info, expr);
  4675. Type *bt = base_type(type);
  4676. irValue *v = ir_add_local_generated(proc, type, true);
  4677. Type *et = nullptr;
  4678. switch (bt->kind) {
  4679. case Type_Vector: et = bt->Vector.elem; break;
  4680. case Type_Array: et = bt->Array.elem; break;
  4681. case Type_Slice: et = bt->Slice.elem; break;
  4682. }
  4683. switch (bt->kind) {
  4684. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  4685. case Type_Vector: {
  4686. if (cl->elems.count == 1 && bt->Vector.count > 1) {
  4687. isize index_count = bt->Vector.count;
  4688. irValue *elem_val = ir_build_expr(proc, cl->elems[0]);
  4689. for (isize i = 0; i < index_count; i++) {
  4690. ir_emit_store(proc, ir_emit_array_epi(proc, v, cast(i32)i), elem_val);
  4691. }
  4692. } else if (cl->elems.count > 0) {
  4693. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  4694. for_array(i, cl->elems) {
  4695. AstNode *elem = cl->elems[i];
  4696. if (ir_is_elem_const(proc->module, elem, et)) {
  4697. continue;
  4698. }
  4699. irValue *field_expr = ir_build_expr(proc, elem);
  4700. Type *t = ir_type(field_expr);
  4701. GB_ASSERT(t->kind != Type_Tuple);
  4702. irValue *ev = ir_emit_conv(proc, field_expr, et);
  4703. irValue *gep = ir_emit_array_epi(proc, v, cast(i32)i);
  4704. ir_emit_store(proc, gep, ev);
  4705. }
  4706. }
  4707. break;
  4708. }
  4709. case Type_Struct: {
  4710. // TODO(bill): "constant" `#raw_union`s are not initialized constantly at the moment.
  4711. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  4712. bool is_raw_union = is_type_raw_union(bt);
  4713. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  4714. TypeStruct *st = &bt->Struct;
  4715. if (cl->elems.count > 0) {
  4716. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  4717. for_array(field_index, cl->elems) {
  4718. AstNode *elem = cl->elems[field_index];
  4719. irValue *field_expr = nullptr;
  4720. Entity *field = nullptr;
  4721. isize index = field_index;
  4722. if (elem->kind == AstNode_FieldValue) {
  4723. ast_node(fv, FieldValue, elem);
  4724. String name = fv->field->Ident.token.string;
  4725. Selection sel = lookup_field(proc->module->allocator, bt, name, false);
  4726. index = sel.index[0];
  4727. elem = fv->value;
  4728. } else {
  4729. TypeAndValue tav = type_and_value_of_expr(proc->module->info, elem);
  4730. Selection sel = lookup_field_from_index(proc->module->allocator, bt,
  4731. st->fields_in_src_order[field_index]->Variable.field_src_index);
  4732. index = sel.index[0];
  4733. }
  4734. field = st->fields[index];
  4735. Type *ft = field->type;
  4736. if (!is_raw_union && ir_is_elem_const(proc->module, elem, ft)) {
  4737. continue;
  4738. }
  4739. field_expr = ir_build_expr(proc, elem);
  4740. GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
  4741. irValue *fv = ir_emit_conv(proc, field_expr, ft);
  4742. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  4743. ir_emit_store(proc, gep, fv);
  4744. }
  4745. }
  4746. break;
  4747. }
  4748. case Type_Map: {
  4749. if (cl->elems.count == 0) {
  4750. break;
  4751. }
  4752. gbAllocator a = proc->module->allocator;
  4753. {
  4754. irValue **args = gb_alloc_array(a, irValue *, 2);
  4755. args[0] = ir_gen_map_header(proc, v, type);
  4756. args[1] = ir_const_int(a, 2*cl->elems.count);
  4757. ir_emit_global_call(proc, "__dynamic_map_reserve", args, 2);
  4758. }
  4759. for_array(field_index, cl->elems) {
  4760. AstNode *elem = cl->elems[field_index];
  4761. ast_node(fv, FieldValue, elem);
  4762. irValue *key = ir_build_expr(proc, fv->field);
  4763. irValue *value = ir_build_expr(proc, fv->value);
  4764. ir_insert_dynamic_map_key_and_value(proc, v, type, key, value);
  4765. }
  4766. break;
  4767. }
  4768. case Type_DynamicArray: {
  4769. if (cl->elems.count == 0) {
  4770. break;
  4771. }
  4772. Type *elem = bt->DynamicArray.elem;
  4773. gbAllocator a = proc->module->allocator;
  4774. irValue *size = ir_const_int(a, type_size_of(a, elem));
  4775. irValue *align = ir_const_int(a, type_align_of(a, elem));
  4776. {
  4777. irValue **args = gb_alloc_array(a, irValue *, 4);
  4778. args[0] = ir_emit_conv(proc, v, t_rawptr);
  4779. args[1] = size;
  4780. args[2] = align;
  4781. args[3] = ir_const_int(a, 2*cl->elems.count);
  4782. ir_emit_global_call(proc, "__dynamic_array_reserve", args, 4);
  4783. }
  4784. i64 item_count = cl->elems.count;
  4785. irValue *items = ir_generate_array(proc->module, elem, item_count, str_lit("__dacl$"), cast(i64)cast(intptr)expr);
  4786. for_array(field_index, cl->elems) {
  4787. AstNode *f = cl->elems[field_index];
  4788. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, f), elem);
  4789. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)field_index);
  4790. ir_emit_store(proc, ep, value);
  4791. }
  4792. {
  4793. irValue **args = gb_alloc_array(a, irValue *, 5);
  4794. args[0] = ir_emit_conv(proc, v, t_rawptr);
  4795. args[1] = size;
  4796. args[2] = align;
  4797. args[3] = ir_emit_conv(proc, items, t_rawptr);
  4798. args[4] = ir_const_int(a, item_count);
  4799. ir_emit_global_call(proc, "__dynamic_array_append", args, 5);
  4800. }
  4801. break;
  4802. }
  4803. case Type_Array: {
  4804. if (cl->elems.count > 0) {
  4805. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  4806. for_array(i, cl->elems) {
  4807. AstNode *elem = cl->elems[i];
  4808. if (ir_is_elem_const(proc->module, elem, et)) {
  4809. continue;
  4810. }
  4811. irValue *field_expr = ir_build_expr(proc, elem);
  4812. Type *t = ir_type(field_expr);
  4813. GB_ASSERT(t->kind != Type_Tuple);
  4814. irValue *ev = ir_emit_conv(proc, field_expr, et);
  4815. irValue *gep = ir_emit_array_epi(proc, v, cast(i32)i);
  4816. ir_emit_store(proc, gep, ev);
  4817. }
  4818. }
  4819. break;
  4820. }
  4821. case Type_Slice: {
  4822. if (cl->elems.count > 0) {
  4823. Type *elem_type = bt->Slice.elem;
  4824. Type *elem_ptr_type = make_type_pointer(proc->module->allocator, elem_type);
  4825. Type *elem_ptr_ptr_type = make_type_pointer(proc->module->allocator, elem_ptr_type);
  4826. irValue *slice = ir_add_module_constant(proc->module, type, exact_value_compound(expr));
  4827. GB_ASSERT(slice->kind == irValue_ConstantSlice);
  4828. irValue *data = ir_emit_array_ep(proc, slice->ConstantSlice.backing_array, v_zero32);
  4829. for_array(i, cl->elems) {
  4830. AstNode *elem = cl->elems[i];
  4831. if (ir_is_elem_const(proc->module, elem, et)) {
  4832. continue;
  4833. }
  4834. irValue *field_expr = ir_build_expr(proc, elem);
  4835. Type *t = ir_type(field_expr);
  4836. GB_ASSERT(t->kind != Type_Tuple);
  4837. irValue *ev = ir_emit_conv(proc, field_expr, elem_type);
  4838. irValue *offset = ir_emit_ptr_offset(proc, data, ir_const_int(proc->module->allocator, i));
  4839. ir_emit_store(proc, offset, ev);
  4840. }
  4841. irValue *count = ir_const_int(proc->module->allocator, slice->ConstantSlice.count);
  4842. ir_fill_slice(proc, v, data, count, count);
  4843. }
  4844. break;
  4845. }
  4846. case Type_Basic: {
  4847. GB_ASSERT(is_type_any(bt));
  4848. if (cl->elems.count > 0) {
  4849. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  4850. String field_names[2] = {
  4851. str_lit("data"),
  4852. str_lit("type_info"),
  4853. };
  4854. Type *field_types[2] = {
  4855. t_rawptr,
  4856. t_type_info_ptr,
  4857. };
  4858. for_array(field_index, cl->elems) {
  4859. AstNode *elem = cl->elems[field_index];
  4860. irValue *field_expr = nullptr;
  4861. isize index = field_index;
  4862. if (elem->kind == AstNode_FieldValue) {
  4863. ast_node(fv, FieldValue, elem);
  4864. Selection sel = lookup_field(proc->module->allocator, bt, fv->field->Ident.token.string, false);
  4865. index = sel.index[0];
  4866. elem = fv->value;
  4867. } else {
  4868. TypeAndValue tav = type_and_value_of_expr(proc->module->info, elem);
  4869. Selection sel = lookup_field(proc->module->allocator, bt, field_names[field_index], false);
  4870. index = sel.index[0];
  4871. }
  4872. field_expr = ir_build_expr(proc, elem);
  4873. GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
  4874. Type *ft = field_types[index];
  4875. irValue *fv = ir_emit_conv(proc, field_expr, ft);
  4876. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  4877. ir_emit_store(proc, gep, fv);
  4878. }
  4879. }
  4880. }
  4881. }
  4882. return ir_addr(v);
  4883. case_end;
  4884. case_ast_node(tc, TypeCast, expr);
  4885. Type *type = type_of_expr(proc->module->info, expr);
  4886. irValue *x = ir_build_expr(proc, tc->expr);
  4887. irValue *e = ir_emit_conv(proc, x, type);
  4888. irValue *v = ir_add_local_generated(proc, type);
  4889. ir_emit_store(proc, v, e);
  4890. return ir_addr(v);
  4891. case_end;
  4892. }
  4893. TokenPos token_pos = ast_node_token(expr).pos;
  4894. GB_PANIC("Unexpected address expression\n"
  4895. "\tAstNode: %.*s @ "
  4896. "%.*s(%td:%td)\n",
  4897. LIT(ast_node_strings[expr->kind]),
  4898. LIT(token_pos.file), token_pos.line, token_pos.column);
  4899. return ir_addr(nullptr);
  4900. }
  4901. void ir_build_assign_op(irProcedure *proc, irAddr lhs, irValue *value, TokenKind op) {
  4902. irValue *old_value = ir_addr_load(proc, lhs);
  4903. Type *type = ir_type(old_value);
  4904. irValue *change = value;
  4905. if (is_type_pointer(type) && is_type_integer(ir_type(value))) {
  4906. change = ir_emit_conv(proc, value, default_type(ir_type(value)));
  4907. } else {
  4908. change = ir_emit_conv(proc, value, type);
  4909. }
  4910. irValue *new_value = ir_emit_arith(proc, op, old_value, change, type);
  4911. ir_addr_store(proc, lhs, new_value);
  4912. }
  4913. irValue *ir_build_cond(irProcedure *proc, AstNode *cond, irBlock *true_block, irBlock *false_block) {
  4914. switch (cond->kind) {
  4915. case_ast_node(pe, ParenExpr, cond);
  4916. return ir_build_cond(proc, pe->expr, true_block, false_block);
  4917. case_end;
  4918. case_ast_node(ue, UnaryExpr, cond);
  4919. if (ue->op.kind == Token_Not) {
  4920. return ir_build_cond(proc, ue->expr, false_block, true_block);
  4921. }
  4922. case_end;
  4923. case_ast_node(be, BinaryExpr, cond);
  4924. if (be->op.kind == Token_CmpAnd) {
  4925. irBlock *block = ir_new_block(proc, nullptr, "cmp.and");
  4926. ir_build_cond(proc, be->left, block, false_block);
  4927. ir_start_block(proc, block);
  4928. return ir_build_cond(proc, be->right, true_block, false_block);
  4929. } else if (be->op.kind == Token_CmpOr) {
  4930. irBlock *block = ir_new_block(proc, nullptr, "cmp.or");
  4931. ir_build_cond(proc, be->left, true_block, block);
  4932. ir_start_block(proc, block);
  4933. return ir_build_cond(proc, be->right, true_block, false_block);
  4934. }
  4935. case_end;
  4936. }
  4937. irValue *v = ir_build_expr(proc, cond);
  4938. v = ir_emit_conv(proc, v, t_bool);
  4939. ir_emit_if(proc, v, true_block, false_block);
  4940. return v;
  4941. }
  4942. void ir_build_poly_proc(irProcedure *proc, AstNodeProcLit *pd, Entity *e) {
  4943. GB_ASSERT(pd->body != nullptr);
  4944. if (ptr_set_exists(&proc->module->min_dep_set, e) == false) {
  4945. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  4946. return;
  4947. }
  4948. // NOTE(bill): Generate a new name
  4949. // parent.name-guid
  4950. String original_name = e->token.string;
  4951. String pd_name = original_name;
  4952. if (e->Procedure.link_name.len > 0) {
  4953. pd_name = e->Procedure.link_name;
  4954. }
  4955. isize name_len = proc->name.len + 1 + pd_name.len + 1 + 10 + 1;
  4956. u8 *name_text = gb_alloc_array(proc->module->allocator, u8, name_len);
  4957. i32 guid = cast(i32)proc->children.count;
  4958. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(pd_name), guid);
  4959. String name = make_string(name_text, name_len-1);
  4960. irValue *value = ir_value_procedure(proc->module->allocator,
  4961. proc->module, e, e->type, pd->type, pd->body, name);
  4962. value->Proc.tags = pd->tags;
  4963. value->Proc.inlining = pd->inlining;
  4964. value->Proc.parent = proc;
  4965. ir_module_add_value(proc->module, e, value);
  4966. array_add(&proc->children, &value->Proc);
  4967. array_add(&proc->module->procs_to_generate, value);
  4968. }
  4969. void ir_build_constant_value_decl(irProcedure *proc, AstNodeValueDecl *vd) {
  4970. if (vd == nullptr || vd->is_mutable) {
  4971. return;
  4972. }
  4973. for_array(i, vd->names) {
  4974. AstNode *ident = vd->names[i];
  4975. GB_ASSERT(ident->kind == AstNode_Ident);
  4976. Entity *e = entity_of_ident(proc->module->info, ident);
  4977. GB_ASSERT(e != nullptr);
  4978. switch (e->kind) {
  4979. case Entity_TypeName:
  4980. case Entity_Procedure:
  4981. break;
  4982. default:
  4983. continue;
  4984. }
  4985. if (e->kind == Entity_TypeName) {
  4986. bool polymorphic_struct = false;
  4987. if (e->type != nullptr && e->kind == Entity_TypeName) {
  4988. Type *bt = base_type(e->type);
  4989. if (bt->kind == Type_Struct) {
  4990. polymorphic_struct = bt->Struct.is_polymorphic;
  4991. }
  4992. }
  4993. if (!polymorphic_struct && !ptr_set_exists(&proc->module->min_dep_set, e)) {
  4994. continue;
  4995. }
  4996. // NOTE(bill): Generate a new name
  4997. // parent_proc.name-guid
  4998. String ts_name = e->token.string;
  4999. irModule *m = proc->module;
  5000. isize name_len = proc->name.len + 1 + ts_name.len + 1 + 10 + 1;
  5001. u8 *name_text = gb_alloc_array(m->allocator, u8, name_len);
  5002. i32 guid = cast(i32)m->members.entries.count;
  5003. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(ts_name), guid);
  5004. String name = make_string(name_text, name_len-1);
  5005. irValue *value = ir_value_type_name(m->allocator, name, e->type);
  5006. map_set(&m->entity_names, hash_entity(e), name);
  5007. ir_gen_global_type_name(m, e, name);
  5008. } else if (e->kind == Entity_Procedure) {
  5009. CheckerInfo *info = proc->module->info;
  5010. DeclInfo *decl = decl_info_of_entity(info, e);
  5011. ast_node(pl, ProcLit, decl->proc_lit);
  5012. if (pl->body != nullptr) {
  5013. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  5014. if (found) {
  5015. auto procs = *found;
  5016. for_array(i, procs) {
  5017. Entity *e = procs[i];
  5018. if (!ptr_set_exists(&proc->module->min_dep_set, e)) {
  5019. continue;
  5020. }
  5021. DeclInfo *d = decl_info_of_entity(info, e);
  5022. ir_build_poly_proc(proc, &d->proc_lit->ProcLit, e);
  5023. }
  5024. } else {
  5025. ir_build_poly_proc(proc, pl, e);
  5026. }
  5027. } else {
  5028. // FFI - Foreign function interace
  5029. String original_name = e->token.string;
  5030. String name = original_name;
  5031. if (e->Procedure.link_name.len > 0) {
  5032. name = e->Procedure.link_name;
  5033. }
  5034. irValue *value = ir_value_procedure(proc->module->allocator,
  5035. proc->module, e, e->type, pl->type, pl->body, name);
  5036. value->Proc.tags = pl->tags;
  5037. value->Proc.inlining = pl->inlining;
  5038. ir_module_add_value(proc->module, e, value);
  5039. ir_build_proc(value, proc);
  5040. if (value->Proc.is_foreign || value->Proc.is_export) {
  5041. HashKey key = hash_string(name);
  5042. irValue **prev_value = map_get(&proc->module->members, key);
  5043. if (prev_value == nullptr) {
  5044. // NOTE(bill): Don't do mutliple declarations in the IR
  5045. map_set(&proc->module->members, key, value);
  5046. }
  5047. } else {
  5048. array_add(&proc->children, &value->Proc);
  5049. }
  5050. }
  5051. }
  5052. }
  5053. }
  5054. void ir_build_stmt_list(irProcedure *proc, Array<AstNode *> stmts) {
  5055. // NOTE(bill): Precollect constant entities
  5056. for_array(i, stmts) {
  5057. AstNode *stmt = stmts[i];
  5058. switch (stmt->kind) {
  5059. case_ast_node(vd, ValueDecl, stmt);
  5060. ir_build_constant_value_decl(proc, vd);
  5061. case_end;
  5062. case_ast_node(fb, ForeignBlockDecl, stmt);
  5063. ir_build_stmt_list(proc, fb->decls);
  5064. case_end;
  5065. }
  5066. }
  5067. for_array(i, stmts) {
  5068. ir_build_stmt(proc, stmts[i]);
  5069. }
  5070. }
  5071. void ir_build_stmt_internal(irProcedure *proc, AstNode *node);
  5072. void ir_build_stmt(irProcedure *proc, AstNode *node) {
  5073. u64 prev_stmt_state_flags = proc->module->stmt_state_flags;
  5074. if (node->stmt_state_flags != 0) {
  5075. u64 in = node->stmt_state_flags;
  5076. u64 out = proc->module->stmt_state_flags;
  5077. if (in & StmtStateFlag_bounds_check) {
  5078. out |= StmtStateFlag_bounds_check;
  5079. out &= ~StmtStateFlag_no_bounds_check;
  5080. } else if (in & StmtStateFlag_no_bounds_check) {
  5081. out |= StmtStateFlag_no_bounds_check;
  5082. out &= ~StmtStateFlag_bounds_check;
  5083. }
  5084. proc->module->stmt_state_flags = out;
  5085. }
  5086. ir_build_stmt_internal(proc, node);
  5087. proc->module->stmt_state_flags = prev_stmt_state_flags;
  5088. }
  5089. void ir_build_when_stmt(irProcedure *proc, AstNodeWhenStmt *ws) {
  5090. irValue *cond = ir_build_expr(proc, ws->cond);
  5091. GB_ASSERT(cond->kind == irValue_Constant &&
  5092. is_type_boolean(ir_type(cond)));
  5093. GB_ASSERT(cond->Constant.value.kind == ExactValue_Bool);
  5094. if (cond->Constant.value.value_bool) {
  5095. ir_build_stmt_list(proc, ws->body->BlockStmt.stmts);
  5096. } else if (ws->else_stmt) {
  5097. switch (ws->else_stmt->kind) {
  5098. case AstNode_BlockStmt:
  5099. ir_build_stmt_list(proc, ws->else_stmt->BlockStmt.stmts);
  5100. break;
  5101. case AstNode_WhenStmt:
  5102. ir_build_when_stmt(proc, &ws->else_stmt->WhenStmt);
  5103. break;
  5104. default:
  5105. GB_PANIC("Invalid `else` statement in `when` statement");
  5106. break;
  5107. }
  5108. }
  5109. }
  5110. void ir_build_range_indexed(irProcedure *proc, irValue *expr, Type *val_type, irValue *count_ptr,
  5111. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  5112. irValue *count = nullptr;
  5113. Type *expr_type = base_type(type_deref(ir_type(expr)));
  5114. switch (expr_type->kind) {
  5115. case Type_Array:
  5116. count = ir_const_int(proc->module->allocator, expr_type->Array.count);
  5117. break;
  5118. case Type_Vector:
  5119. count = ir_const_int(proc->module->allocator, expr_type->Vector.count);
  5120. break;
  5121. }
  5122. irValue *val = nullptr;
  5123. irValue *idx = nullptr;
  5124. irBlock *loop = nullptr;
  5125. irBlock *done = nullptr;
  5126. irBlock *body = nullptr;
  5127. irValue *key = nullptr;
  5128. if (expr_type->kind == Type_Map) {
  5129. key = ir_add_local_generated(proc, expr_type->Map.key);
  5130. }
  5131. irValue *index = ir_add_local_generated(proc, t_int);
  5132. ir_emit_store(proc, index, ir_const_int(proc->module->allocator, -1));
  5133. loop = ir_new_block(proc, nullptr, "for.index.loop");
  5134. ir_emit_jump(proc, loop);
  5135. ir_start_block(proc, loop);
  5136. irValue *incr = ir_emit_arith(proc, Token_Add, ir_emit_load(proc, index), v_one, t_int);
  5137. ir_emit_store(proc, index, incr);
  5138. body = ir_new_block(proc, nullptr, "for.index.body");
  5139. done = ir_new_block(proc, nullptr, "for.index.done");
  5140. if (count == nullptr) {
  5141. count = ir_emit_load(proc, count_ptr);
  5142. }
  5143. irValue *cond = ir_emit_comp(proc, Token_Lt, incr, count);
  5144. ir_emit_if(proc, cond, body, done);
  5145. ir_start_block(proc, body);
  5146. idx = ir_emit_load(proc, index);
  5147. if (val_type != nullptr) {
  5148. switch (expr_type->kind) {
  5149. case Type_Array: {
  5150. val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
  5151. break;
  5152. }
  5153. case Type_Vector: {
  5154. val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
  5155. break;
  5156. }
  5157. case Type_Slice: {
  5158. irValue *elem = ir_slice_elem(proc, expr);
  5159. val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
  5160. break;
  5161. }
  5162. case Type_DynamicArray: {
  5163. irValue *elem = ir_emit_struct_ep(proc, expr, 0);
  5164. elem = ir_emit_load(proc, elem);
  5165. val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
  5166. break;
  5167. }
  5168. case Type_Map: {
  5169. irValue *entries = ir_emit_struct_ep(proc, expr, 1);
  5170. irValue *elem = ir_emit_struct_ep(proc, entries, 0);
  5171. elem = ir_emit_load(proc, elem);
  5172. irValue *entry = ir_emit_ptr_offset(proc, elem, idx);
  5173. val = ir_emit_load(proc, ir_emit_struct_ep(proc, entry, 2));
  5174. irValue *hash = ir_emit_struct_ep(proc, entry, 0);
  5175. if (is_type_string(expr_type->Map.key)) {
  5176. irValue *str = ir_emit_struct_ep(proc, hash, 1);
  5177. ir_emit_store(proc, key, ir_emit_load(proc, str));
  5178. } else {
  5179. irValue *hash_ptr = ir_emit_struct_ep(proc, hash, 0);
  5180. hash_ptr = ir_emit_conv(proc, hash_ptr, ir_type(key));
  5181. ir_emit_store(proc, key, ir_emit_load(proc, hash_ptr));
  5182. }
  5183. break;
  5184. }
  5185. default:
  5186. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  5187. break;
  5188. }
  5189. }
  5190. if (key != nullptr) {
  5191. idx = ir_emit_load(proc, key);
  5192. }
  5193. if (val_) *val_ = val;
  5194. if (idx_) *idx_ = idx;
  5195. if (loop_) *loop_ = loop;
  5196. if (done_) *done_ = done;
  5197. }
  5198. void ir_build_range_string(irProcedure *proc, irValue *expr, Type *val_type,
  5199. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  5200. irValue *count = v_zero;
  5201. Type *expr_type = base_type(ir_type(expr));
  5202. switch (expr_type->kind) {
  5203. case Type_Basic:
  5204. count = ir_string_len(proc, expr);
  5205. break;
  5206. default:
  5207. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  5208. break;
  5209. }
  5210. irValue *val = nullptr;
  5211. irValue *idx = nullptr;
  5212. irBlock *loop = nullptr;
  5213. irBlock *done = nullptr;
  5214. irBlock *body = nullptr;
  5215. irValue *offset_ = ir_add_local_generated(proc, t_int);
  5216. ir_emit_store(proc, offset_, v_zero);
  5217. loop = ir_new_block(proc, nullptr, "for.string.loop");
  5218. ir_emit_jump(proc, loop);
  5219. ir_start_block(proc, loop);
  5220. body = ir_new_block(proc, nullptr, "for.string.body");
  5221. done = ir_new_block(proc, nullptr, "for.string.done");
  5222. irValue *offset = ir_emit_load(proc, offset_);
  5223. irValue *cond = ir_emit_comp(proc, Token_Lt, offset, count);
  5224. ir_emit_if(proc, cond, body, done);
  5225. ir_start_block(proc, body);
  5226. irValue *str_elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, expr), offset);
  5227. irValue *str_len = ir_emit_arith(proc, Token_Sub, count, offset, t_int);
  5228. irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 1);
  5229. args[0] = ir_emit_string(proc, str_elem, str_len);
  5230. irValue *rune_and_len = ir_emit_global_call(proc, "__string_decode_rune", args, 1);
  5231. irValue *len = ir_emit_struct_ev(proc, rune_and_len, 1);
  5232. ir_emit_store(proc, offset_, ir_emit_arith(proc, Token_Add, offset, len, t_int));
  5233. idx = offset;
  5234. if (val_type != nullptr) {
  5235. val = ir_emit_struct_ev(proc, rune_and_len, 0);
  5236. }
  5237. if (val_) *val_ = val;
  5238. if (idx_) *idx_ = idx;
  5239. if (loop_) *loop_ = loop;
  5240. if (done_) *done_ = done;
  5241. }
  5242. void ir_build_range_interval(irProcedure *proc, AstNodeBinaryExpr *node, Type *val_type,
  5243. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  5244. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  5245. // If `lower` is changed, should `val` do so or is that not typical behaviour?
  5246. irValue *lower = ir_build_expr(proc, node->left);
  5247. irValue *upper = nullptr;
  5248. irValue *val = nullptr;
  5249. irValue *idx = nullptr;
  5250. irBlock *loop = nullptr;
  5251. irBlock *done = nullptr;
  5252. irBlock *body = nullptr;
  5253. if (val_type == nullptr) {
  5254. val_type = ir_type(lower);
  5255. }
  5256. irValue *value = ir_add_local_generated(proc, val_type);
  5257. ir_emit_store(proc, value, lower);
  5258. irValue *index = ir_add_local_generated(proc, t_int);
  5259. ir_emit_store(proc, index, ir_const_int(proc->module->allocator, 0));
  5260. loop = ir_new_block(proc, nullptr, "for.interval.loop");
  5261. ir_emit_jump(proc, loop);
  5262. ir_start_block(proc, loop);
  5263. body = ir_new_block(proc, nullptr, "for.interval.body");
  5264. done = ir_new_block(proc, nullptr, "for.interval.done");
  5265. TokenKind op = Token_Lt;
  5266. switch (node->op.kind) {
  5267. case Token_Ellipsis: op = Token_LtEq; break;
  5268. case Token_HalfClosed: op = Token_Lt; break;
  5269. default: GB_PANIC("Invalid interval operator"); break;
  5270. }
  5271. upper = ir_build_expr(proc, node->right);
  5272. irValue *cond = ir_emit_comp(proc, op, ir_emit_load(proc, value), upper);
  5273. ir_emit_if(proc, cond, body, done);
  5274. ir_start_block(proc, body);
  5275. if (value != nullptr) {
  5276. val = ir_emit_load(proc, value);
  5277. }
  5278. idx = ir_emit_load(proc, index);
  5279. ir_emit_increment(proc, value);
  5280. ir_emit_increment(proc, index);
  5281. if (val_) *val_ = val;
  5282. if (idx_) *idx_ = idx;
  5283. if (loop_) *loop_ = loop;
  5284. if (done_) *done_ = done;
  5285. }
  5286. void ir_store_type_case_implicit(irProcedure *proc, AstNode *clause, irValue *value) {
  5287. Entity *e = implicit_entity_of_node(proc->module->info, clause);
  5288. GB_ASSERT(e != nullptr);
  5289. irValue *x = ir_add_local(proc, e, nullptr, false);
  5290. ir_emit_store(proc, x, value);
  5291. }
  5292. void ir_type_case_body(irProcedure *proc, AstNode *label, AstNode *clause, irBlock *body, irBlock *done) {
  5293. ast_node(cc, CaseClause, clause);
  5294. ir_push_target_list(proc, label, done, nullptr, nullptr);
  5295. ir_open_scope(proc);
  5296. ir_build_stmt_list(proc, cc->stmts);
  5297. ir_close_scope(proc, irDeferExit_Default, body);
  5298. ir_pop_target_list(proc);
  5299. ir_emit_jump(proc, done);
  5300. }
  5301. void ir_build_stmt_internal(irProcedure *proc, AstNode *node) {
  5302. switch (node->kind) {
  5303. case_ast_node(bs, EmptyStmt, node);
  5304. case_end;
  5305. // case_ast_node(fb, ForeignBlockDecl, node);
  5306. // ir_build_stmt_list(proc, fb->decls);
  5307. // case_end;
  5308. case_ast_node(us, UsingStmt, node);
  5309. for_array(i, us->list) {
  5310. AstNode *decl = unparen_expr(us->list[i]);
  5311. // if (decl->kind == AstNode_GenDecl) {
  5312. // ir_build_stmt(proc, decl);
  5313. // }
  5314. }
  5315. case_end;
  5316. case_ast_node(ws, WhenStmt, node);
  5317. ir_build_when_stmt(proc, ws);
  5318. case_end;
  5319. #if 0
  5320. case_ast_node(s, IncDecStmt, node);
  5321. TokenKind op = Token_Add;
  5322. if (s->op.kind == Token_Dec) {
  5323. op = Token_Sub;
  5324. }
  5325. irAddr addr = ir_build_addr(proc, s->expr);
  5326. ir_build_assign_op(proc, addr, v_one, op);
  5327. case_end;
  5328. #endif
  5329. case_ast_node(vd, ValueDecl, node);
  5330. if (vd->is_mutable) {
  5331. irModule *m = proc->module;
  5332. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
  5333. defer (gb_temp_arena_memory_end(tmp));
  5334. if (vd->values.count == 0) { // declared and zero-initialized
  5335. for_array(i, vd->names) {
  5336. AstNode *name = vd->names[i];
  5337. if (!is_blank_ident(name)) {
  5338. ir_add_local_for_identifier(proc, name, true);
  5339. }
  5340. }
  5341. } else { // Tuple(s)
  5342. Array<irAddr> lvals = {};
  5343. Array<irValue *> inits = {};
  5344. array_init(&lvals, m->tmp_allocator, vd->names.count);
  5345. array_init(&inits, m->tmp_allocator, vd->names.count);
  5346. for_array(i, vd->names) {
  5347. AstNode *name = vd->names[i];
  5348. irAddr lval = ir_addr(nullptr);
  5349. if (!is_blank_ident(name)) {
  5350. ir_add_local_for_identifier(proc, name, false);
  5351. lval = ir_build_addr(proc, name);
  5352. }
  5353. array_add(&lvals, lval);
  5354. ir_check_type_and_gen_for_proc_lit(proc, ir_addr_type(lval));
  5355. }
  5356. for_array(i, vd->values) {
  5357. irValue *init = ir_build_expr(proc, vd->values[i]);
  5358. Type *t = ir_type(init);
  5359. if (t->kind == Type_Tuple) {
  5360. for_array(i, t->Tuple.variables) {
  5361. Entity *e = t->Tuple.variables[i];
  5362. irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
  5363. array_add(&inits, v);
  5364. }
  5365. } else {
  5366. array_add(&inits, init);
  5367. }
  5368. }
  5369. for_array(i, inits) {
  5370. ir_addr_store(proc, lvals[i], inits[i]);
  5371. }
  5372. }
  5373. }
  5374. case_end;
  5375. case_ast_node(as, AssignStmt, node);
  5376. ir_emit_comment(proc, str_lit("AssignStmt"));
  5377. irModule *m = proc->module;
  5378. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
  5379. switch (as->op.kind) {
  5380. case Token_Eq: {
  5381. Array<irAddr> lvals;
  5382. array_init(&lvals, m->tmp_allocator);
  5383. for_array(i, as->lhs) {
  5384. AstNode *lhs = as->lhs[i];
  5385. irAddr lval = {};
  5386. if (!is_blank_ident(lhs)) {
  5387. lval = ir_build_addr(proc, lhs);
  5388. }
  5389. array_add(&lvals, lval);
  5390. }
  5391. if (as->lhs.count == as->rhs.count) {
  5392. if (as->lhs.count == 1) {
  5393. AstNode *rhs = as->rhs[0];
  5394. irValue *init = ir_build_expr(proc, rhs);
  5395. ir_addr_store(proc, lvals[0], init);
  5396. } else {
  5397. Array<irValue *> inits;
  5398. array_init(&inits, m->tmp_allocator, lvals.count);
  5399. for_array(i, as->rhs) {
  5400. irValue *init = ir_build_expr(proc, as->rhs[i]);
  5401. array_add(&inits, init);
  5402. }
  5403. for_array(i, inits) {
  5404. ir_addr_store(proc, lvals[i], inits[i]);
  5405. }
  5406. }
  5407. } else {
  5408. Array<irValue *> inits;
  5409. array_init(&inits, m->tmp_allocator, lvals.count);
  5410. for_array(i, as->rhs) {
  5411. irValue *init = ir_build_expr(proc, as->rhs[i]);
  5412. Type *t = ir_type(init);
  5413. // TODO(bill): refactor for code reuse as this is repeated a bit
  5414. if (t->kind == Type_Tuple) {
  5415. for_array(i, t->Tuple.variables) {
  5416. Entity *e = t->Tuple.variables[i];
  5417. irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
  5418. array_add(&inits, v);
  5419. }
  5420. } else {
  5421. array_add(&inits, init);
  5422. }
  5423. }
  5424. for_array(i, inits) {
  5425. ir_addr_store(proc, lvals[i], inits[i]);
  5426. }
  5427. }
  5428. break;
  5429. }
  5430. default: {
  5431. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  5432. // +=, -=, etc
  5433. i32 op = cast(i32)as->op.kind;
  5434. op += Token_Add - Token_AddEq; // Convert += to +
  5435. irAddr lhs = ir_build_addr(proc, as->lhs[0]);
  5436. irValue *value = ir_build_expr(proc, as->rhs[0]);
  5437. ir_build_assign_op(proc, lhs, value, cast(TokenKind)op);
  5438. break;
  5439. }
  5440. }
  5441. gb_temp_arena_memory_end(tmp);
  5442. case_end;
  5443. case_ast_node(es, ExprStmt, node);
  5444. // NOTE(bill): No need to use return value
  5445. ir_build_expr(proc, es->expr);
  5446. case_end;
  5447. case_ast_node(bs, BlockStmt, node);
  5448. ir_open_scope(proc);
  5449. ir_build_stmt_list(proc, bs->stmts);
  5450. ir_close_scope(proc, irDeferExit_Default, nullptr);
  5451. case_end;
  5452. case_ast_node(ds, DeferStmt, node);
  5453. ir_emit_comment(proc, str_lit("DeferStmt"));
  5454. isize scope_index = proc->scope_index;
  5455. // TODO(bill): What was the original rationale behind this line?
  5456. // if (ds->stmt->kind == AstNode_BlockStmt) scope_index--;
  5457. ir_add_defer_node(proc, scope_index, ds->stmt);
  5458. case_end;
  5459. case_ast_node(rs, ReturnStmt, node);
  5460. ir_emit_comment(proc, str_lit("ReturnStmt"));
  5461. irValue *v = nullptr;
  5462. TypeTuple *tuple = &proc->type->Proc.results->Tuple;
  5463. isize return_count = proc->type->Proc.result_count;
  5464. isize res_count = rs->results.count;
  5465. if (res_count > 0 &&
  5466. rs->results[0]->kind == AstNode_FieldValue) {
  5467. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena);
  5468. defer (gb_temp_arena_memory_end(tmp));
  5469. Array<irValue *> results;
  5470. array_init_count(&results, proc->module->tmp_allocator, return_count);
  5471. for_array(arg_index, rs->results) {
  5472. AstNode *arg = rs->results[arg_index];
  5473. ast_node(fv, FieldValue, arg);
  5474. GB_ASSERT(fv->field->kind == AstNode_Ident);
  5475. String name = fv->field->Ident.token.string;
  5476. isize index = lookup_procedure_result(&proc->type->Proc, name);
  5477. GB_ASSERT(index >= 0);
  5478. irValue *expr = ir_build_expr(proc, fv->value);
  5479. results[index] = expr;
  5480. }
  5481. for (isize i = 0; i < return_count; i++) {
  5482. Entity *e = tuple->variables[i];
  5483. GB_ASSERT(e->kind == Entity_Variable);
  5484. if (results[i] == nullptr) {
  5485. if (e->Variable.default_value.kind != ExactValue_Invalid) {
  5486. results[i] = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value);
  5487. } else {
  5488. results[i] = ir_value_nil(proc->module->allocator, e->type);
  5489. }
  5490. } else {
  5491. results[i] = ir_emit_conv(proc, results[i], e->type);
  5492. }
  5493. }
  5494. if (results.count == 1) {
  5495. v = results[0];
  5496. } else {
  5497. GB_ASSERT(results.count == return_count);
  5498. Type *ret_type = proc->type->Proc.results;
  5499. v = ir_add_local_generated(proc, ret_type);
  5500. for_array(i, results) {
  5501. irValue *field = ir_emit_struct_ep(proc, v, cast(i32)i);
  5502. irValue *res = results[i];
  5503. ir_emit_store(proc, field, res);
  5504. }
  5505. v = ir_emit_load(proc, v);
  5506. }
  5507. } else if (return_count == 0) {
  5508. // No return values
  5509. } else if (return_count == 1) {
  5510. Entity *e = tuple->variables[0];
  5511. if (res_count == 0) {
  5512. if (e->Variable.default_value.kind != ExactValue_Invalid) {
  5513. v = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value);
  5514. } else {
  5515. v = ir_value_nil(proc->module->allocator, e->type);
  5516. }
  5517. } else {
  5518. v = ir_build_expr(proc, rs->results[0]);
  5519. v = ir_emit_conv(proc, v, e->type);
  5520. }
  5521. } else {
  5522. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena);
  5523. defer (gb_temp_arena_memory_end(tmp));
  5524. Array<irValue *> results;
  5525. array_init(&results, proc->module->tmp_allocator, return_count);
  5526. isize total_index = 0;
  5527. isize res_index = 0;
  5528. for (; res_index < res_count; res_index++) {
  5529. irValue *res = ir_build_expr(proc, rs->results[res_index]);
  5530. Type *t = ir_type(res);
  5531. if (t->kind == Type_Tuple) {
  5532. for_array(i, t->Tuple.variables) {
  5533. Entity *e = t->Tuple.variables[i];
  5534. irValue *v = ir_emit_struct_ev(proc, res, cast(i32)i);
  5535. array_add(&results, v);
  5536. total_index++;
  5537. }
  5538. } else {
  5539. array_add(&results, res);
  5540. total_index++;
  5541. }
  5542. }
  5543. while (total_index < return_count) {
  5544. Entity *e = tuple->variables[total_index];
  5545. irValue *res = nullptr;
  5546. if (e->Variable.default_value.kind != ExactValue_Invalid) {
  5547. res = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value);
  5548. } else {
  5549. res = ir_value_nil(proc->module->allocator, e->type);
  5550. }
  5551. array_add(&results, res);
  5552. total_index++;
  5553. }
  5554. GB_ASSERT(results.count == return_count);
  5555. Type *ret_type = proc->type->Proc.results;
  5556. v = ir_add_local_generated(proc, ret_type);
  5557. for_array(i, results) {
  5558. Entity *e = tuple->variables[i];
  5559. irValue *res = ir_emit_conv(proc, results[i], e->type);
  5560. irValue *field = ir_emit_struct_ep(proc, v, cast(i32)i);
  5561. ir_emit_store(proc, field, res);
  5562. }
  5563. v = ir_emit_load(proc, v);
  5564. }
  5565. ir_emit_return(proc, v);
  5566. case_end;
  5567. case_ast_node(is, IfStmt, node);
  5568. ir_emit_comment(proc, str_lit("IfStmt"));
  5569. if (is->init != nullptr) {
  5570. irBlock *init = ir_new_block(proc, node, "if.init");
  5571. ir_emit_jump(proc, init);
  5572. ir_start_block(proc, init);
  5573. ir_build_stmt(proc, is->init);
  5574. }
  5575. irBlock *then = ir_new_block(proc, node, "if.then");
  5576. irBlock *done = ir_new_block(proc, node, "if.done");
  5577. irBlock *else_ = done;
  5578. if (is->else_stmt != nullptr) {
  5579. else_ = ir_new_block(proc, is->else_stmt, "if.else");
  5580. }
  5581. ir_build_cond(proc, is->cond, then, else_);
  5582. ir_start_block(proc, then);
  5583. ir_open_scope(proc);
  5584. ir_build_stmt(proc, is->body);
  5585. ir_close_scope(proc, irDeferExit_Default, nullptr);
  5586. ir_emit_jump(proc, done);
  5587. if (is->else_stmt != nullptr) {
  5588. ir_start_block(proc, else_);
  5589. ir_open_scope(proc);
  5590. ir_build_stmt(proc, is->else_stmt);
  5591. ir_close_scope(proc, irDeferExit_Default, nullptr);
  5592. ir_emit_jump(proc, done);
  5593. }
  5594. ir_start_block(proc, done);
  5595. case_end;
  5596. case_ast_node(fs, ForStmt, node);
  5597. ir_emit_comment(proc, str_lit("ForStmt"));
  5598. if (fs->init != nullptr) {
  5599. irBlock *init = ir_new_block(proc, node, "for.init");
  5600. ir_emit_jump(proc, init);
  5601. ir_start_block(proc, init);
  5602. ir_build_stmt(proc, fs->init);
  5603. }
  5604. irBlock *body = ir_new_block(proc, node, "for.body");
  5605. irBlock *done = ir_new_block(proc, node, "for.done"); // NOTE(bill): Append later
  5606. irBlock *loop = body;
  5607. if (fs->cond != nullptr) {
  5608. loop = ir_new_block(proc, node, "for.loop");
  5609. }
  5610. irBlock *post = loop;
  5611. if (fs->post != nullptr) {
  5612. post = ir_new_block(proc, node, "for.post");
  5613. }
  5614. ir_emit_jump(proc, loop);
  5615. ir_start_block(proc, loop);
  5616. if (loop != body) {
  5617. ir_build_cond(proc, fs->cond, body, done);
  5618. ir_start_block(proc, body);
  5619. }
  5620. ir_push_target_list(proc, fs->label, done, post, nullptr);
  5621. ir_open_scope(proc);
  5622. ir_build_stmt(proc, fs->body);
  5623. ir_close_scope(proc, irDeferExit_Default, nullptr);
  5624. ir_pop_target_list(proc);
  5625. ir_emit_jump(proc, post);
  5626. if (fs->post != nullptr) {
  5627. ir_start_block(proc, post);
  5628. ir_build_stmt(proc, fs->post);
  5629. ir_emit_jump(proc, loop);
  5630. }
  5631. ir_start_block(proc, done);
  5632. case_end;
  5633. case_ast_node(rs, RangeStmt, node);
  5634. ir_emit_comment(proc, str_lit("RangeStmt"));
  5635. Type *val_type = nullptr;
  5636. Type *idx_type = nullptr;
  5637. if (rs->value != nullptr && !is_blank_ident(rs->value)) {
  5638. val_type = type_of_expr(proc->module->info, rs->value);
  5639. }
  5640. if (rs->index != nullptr && !is_blank_ident(rs->index)) {
  5641. idx_type = type_of_expr(proc->module->info, rs->index);
  5642. }
  5643. if (val_type != nullptr) {
  5644. ir_add_local_for_identifier(proc, rs->value, true);
  5645. }
  5646. if (idx_type != nullptr) {
  5647. ir_add_local_for_identifier(proc, rs->index, true);
  5648. }
  5649. irValue *val = nullptr;
  5650. irValue *index = nullptr;
  5651. irBlock *loop = nullptr;
  5652. irBlock *done = nullptr;
  5653. AstNode *expr = unparen_expr(rs->expr);
  5654. TypeAndValue tav = type_and_value_of_expr(proc->module->info, expr);
  5655. if (is_ast_node_a_range(expr)) {
  5656. ir_build_range_interval(proc, &expr->BinaryExpr, val_type, &val, &index, &loop, &done);
  5657. } else if (tav.mode == Addressing_Type) {
  5658. TokenPos pos = ast_node_token(expr).pos;
  5659. gbAllocator a = proc->module->allocator;
  5660. Type *t = tav.type;
  5661. GB_ASSERT(is_type_enum(t));
  5662. Type *enum_ptr = make_type_pointer(a, t);
  5663. t = base_type(t);
  5664. Type *core_elem = core_type(t);
  5665. i64 enum_count = t->Enum.field_count;
  5666. irValue *max_count = ir_const_int(a, enum_count);
  5667. irValue *ti = ir_type_info(proc, t);
  5668. irValue *variant = ir_emit_struct_ep(proc, ti, 2);
  5669. irValue *eti_ptr = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
  5670. irValue *values = ir_emit_load(proc, ir_emit_struct_ep(proc, eti_ptr, 2));
  5671. irValue *values_data = ir_slice_elem(proc, values);
  5672. irValue *offset_ = ir_add_local_generated(proc, t_int);
  5673. ir_emit_store(proc, offset_, v_zero);
  5674. loop = ir_new_block(proc, nullptr, "for.enum.loop");
  5675. ir_emit_jump(proc, loop);
  5676. ir_start_block(proc, loop);
  5677. irBlock *body = ir_new_block(proc, nullptr, "for.enum.body");
  5678. done = ir_new_block(proc, nullptr, "for.enum.done");
  5679. irValue *offset = ir_emit_load(proc, offset_);
  5680. irValue *cond = ir_emit_comp(proc, Token_Lt, offset, max_count);
  5681. ir_emit_if(proc, cond, body, done);
  5682. ir_start_block(proc, body);
  5683. irValue *val_ptr = ir_emit_ptr_offset(proc, values_data, offset);
  5684. ir_emit_increment(proc, offset_);
  5685. index = offset;
  5686. if (val_type != nullptr) {
  5687. if (is_type_float(core_elem)) {
  5688. irValue *f = ir_emit_load(proc, ir_emit_conv(proc, val_ptr, t_f64_ptr));
  5689. val = ir_emit_conv(proc, f, t);
  5690. } else if (is_type_integer(core_elem)) {
  5691. irValue *i = ir_emit_load(proc, ir_emit_conv(proc, val_ptr, t_i64_ptr));
  5692. val = ir_emit_conv(proc, i, t);
  5693. } else {
  5694. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  5695. }
  5696. }
  5697. } else {
  5698. Type *expr_type = type_of_expr(proc->module->info, rs->expr);
  5699. Type *et = base_type(type_deref(expr_type));
  5700. switch (et->kind) {
  5701. case Type_Map: {
  5702. irAddr addr = ir_build_addr(proc, rs->expr);
  5703. irValue *map = ir_addr_get_ptr(proc, addr);
  5704. if (is_type_pointer(type_deref(ir_addr_type(addr)))) {
  5705. map = ir_addr_load(proc, addr);
  5706. }
  5707. irValue *entries_ptr = ir_emit_struct_ep(proc, map, 1);
  5708. irValue *count_ptr = ir_emit_struct_ep(proc, entries_ptr, 1);
  5709. ir_build_range_indexed(proc, map, val_type, count_ptr, &val, &index, &loop, &done);
  5710. break;
  5711. }
  5712. case Type_Array: {
  5713. irValue *count_ptr = nullptr;
  5714. irValue *array = ir_build_addr_ptr(proc, rs->expr);
  5715. if (is_type_pointer(type_deref(ir_type(array)))) {
  5716. array = ir_emit_load(proc, array);
  5717. }
  5718. count_ptr = ir_add_local_generated(proc, t_int);
  5719. ir_emit_store(proc, count_ptr, ir_const_int(proc->module->allocator, et->Array.count));
  5720. ir_build_range_indexed(proc, array, val_type, count_ptr, &val, &index, &loop, &done);
  5721. break;
  5722. }
  5723. case Type_Vector: {
  5724. irValue *count_ptr = nullptr;
  5725. irValue *vector = ir_build_addr_ptr(proc, rs->expr);
  5726. if (is_type_pointer(type_deref(ir_type(vector)))) {
  5727. vector = ir_emit_load(proc, vector);
  5728. }
  5729. count_ptr = ir_add_local_generated(proc, t_int);
  5730. ir_emit_store(proc, count_ptr, ir_const_int(proc->module->allocator, et->Vector.count));
  5731. ir_build_range_indexed(proc, vector, val_type, count_ptr, &val, &index, &loop, &done);
  5732. break;
  5733. }
  5734. case Type_DynamicArray: {
  5735. irValue *count_ptr = nullptr;
  5736. irValue *array = ir_build_addr_ptr(proc, rs->expr);
  5737. if (is_type_pointer(type_deref(ir_type(array)))) {
  5738. array = ir_emit_load(proc, array);
  5739. }
  5740. count_ptr = ir_emit_struct_ep(proc, array, 1);
  5741. ir_build_range_indexed(proc, array, val_type, count_ptr, &val, &index, &loop, &done);
  5742. break;
  5743. }
  5744. case Type_Slice: {
  5745. irValue *count_ptr = nullptr;
  5746. irValue *slice = ir_build_expr(proc, rs->expr);
  5747. if (is_type_pointer(ir_type(slice))) {
  5748. count_ptr = ir_emit_struct_ep(proc, slice, 1);
  5749. slice = ir_emit_load(proc, slice);
  5750. } else {
  5751. count_ptr = ir_add_local_generated(proc, t_int);
  5752. ir_emit_store(proc, count_ptr, ir_slice_count(proc, slice));
  5753. }
  5754. ir_build_range_indexed(proc, slice, val_type, count_ptr, &val, &index, &loop, &done);
  5755. break;
  5756. }
  5757. case Type_Basic: {
  5758. irValue *string = ir_build_expr(proc, rs->expr);
  5759. if (is_type_pointer(ir_type(string))) {
  5760. string = ir_emit_load(proc, string);
  5761. }
  5762. if (is_type_untyped(expr_type)) {
  5763. irValue *s = ir_add_local_generated(proc, t_string);
  5764. ir_emit_store(proc, s, string);
  5765. string = ir_emit_load(proc, s);
  5766. }
  5767. ir_build_range_string(proc, string, val_type, &val, &index, &loop, &done);
  5768. break;
  5769. }
  5770. default:
  5771. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  5772. break;
  5773. }
  5774. }
  5775. irAddr val_addr = {};
  5776. irAddr idx_addr = {};
  5777. if (val_type != nullptr) {
  5778. val_addr = ir_build_addr(proc, rs->value);
  5779. }
  5780. if (idx_type != nullptr) {
  5781. idx_addr = ir_build_addr(proc, rs->index);
  5782. }
  5783. if (val_type != nullptr) {
  5784. ir_addr_store(proc, val_addr, val);
  5785. }
  5786. if (idx_type != nullptr) {
  5787. ir_addr_store(proc, idx_addr, index);
  5788. }
  5789. ir_push_target_list(proc, rs->label, done, loop, nullptr);
  5790. ir_open_scope(proc);
  5791. ir_build_stmt(proc, rs->body);
  5792. ir_close_scope(proc, irDeferExit_Default, nullptr);
  5793. ir_pop_target_list(proc);
  5794. ir_emit_jump(proc, loop);
  5795. ir_start_block(proc, done);
  5796. case_end;
  5797. case_ast_node(ss, SwitchStmt, node);
  5798. ir_emit_comment(proc, str_lit("SwitchStmt"));
  5799. if (ss->init != nullptr) {
  5800. ir_build_stmt(proc, ss->init);
  5801. }
  5802. irValue *tag = v_true;
  5803. if (ss->tag != nullptr) {
  5804. tag = ir_build_expr(proc, ss->tag);
  5805. }
  5806. irBlock *done = ir_new_block(proc, node, "switch.done"); // NOTE(bill): Append later
  5807. ast_node(body, BlockStmt, ss->body);
  5808. Array<AstNode *> default_stmts = {};
  5809. irBlock *default_fall = nullptr;
  5810. irBlock *default_block = nullptr;
  5811. irBlock *fall = nullptr;
  5812. bool append_fall = false;
  5813. isize case_count = body->stmts.count;
  5814. for_array(i, body->stmts) {
  5815. AstNode *clause = body->stmts[i];
  5816. irBlock *body = fall;
  5817. ast_node(cc, CaseClause, clause);
  5818. if (body == nullptr) {
  5819. if (cc->list.count == 0) {
  5820. body = ir_new_block(proc, clause, "switch.dflt.body");
  5821. } else {
  5822. body = ir_new_block(proc, clause, "switch.case.body");
  5823. }
  5824. }
  5825. if (append_fall && body == fall) {
  5826. append_fall = false;
  5827. }
  5828. fall = done;
  5829. if (i+1 < case_count) {
  5830. append_fall = true;
  5831. fall = ir_new_block(proc, clause, "switch.fall.body");
  5832. }
  5833. if (cc->list.count == 0) {
  5834. // default case
  5835. default_stmts = cc->stmts;
  5836. default_fall = fall;
  5837. default_block = body;
  5838. continue;
  5839. }
  5840. irBlock *next_cond = nullptr;
  5841. for_array(j, cc->list) {
  5842. AstNode *expr = unparen_expr(cc->list[j]);
  5843. next_cond = ir_new_block(proc, clause, "switch.case.next");
  5844. irValue *cond = v_false;
  5845. if (is_ast_node_a_range(expr)) {
  5846. ast_node(ie, BinaryExpr, expr);
  5847. TokenKind op = Token_Invalid;
  5848. switch (ie->op.kind) {
  5849. case Token_Ellipsis: op = Token_LtEq; break;
  5850. case Token_HalfClosed: op = Token_Lt; break;
  5851. default: GB_PANIC("Invalid interval operator"); break;
  5852. }
  5853. irValue *lhs = ir_build_expr(proc, ie->left);
  5854. irValue *rhs = ir_build_expr(proc, ie->right);
  5855. // TODO(bill): do short circuit here
  5856. irValue *cond_lhs = ir_emit_comp(proc, Token_LtEq, lhs, tag);
  5857. irValue *cond_rhs = ir_emit_comp(proc, op, tag, rhs);
  5858. cond = ir_emit_arith(proc, Token_And, cond_lhs, cond_rhs, t_bool);
  5859. } else {
  5860. cond = ir_emit_comp(proc, Token_CmpEq, tag, ir_build_expr(proc, expr));
  5861. }
  5862. ir_emit_if(proc, cond, body, next_cond);
  5863. ir_start_block(proc, next_cond);
  5864. }
  5865. ir_start_block(proc, body);
  5866. ir_push_target_list(proc, ss->label, done, nullptr, fall);
  5867. ir_open_scope(proc);
  5868. ir_build_stmt_list(proc, cc->stmts);
  5869. ir_close_scope(proc, irDeferExit_Default, body);
  5870. ir_pop_target_list(proc);
  5871. ir_emit_jump(proc, done);
  5872. proc->curr_block = next_cond;
  5873. // ir_start_block(proc, next_cond);
  5874. }
  5875. if (default_block != nullptr) {
  5876. ir_emit_jump(proc, default_block);
  5877. ir_start_block(proc, default_block);
  5878. ir_push_target_list(proc, ss->label, done, nullptr, default_fall);
  5879. ir_open_scope(proc);
  5880. ir_build_stmt_list(proc, default_stmts);
  5881. ir_close_scope(proc, irDeferExit_Default, default_block);
  5882. ir_pop_target_list(proc);
  5883. }
  5884. ir_emit_jump(proc, done);
  5885. ir_start_block(proc, done);
  5886. case_end;
  5887. case_ast_node(ss, TypeSwitchStmt, node);
  5888. ir_emit_comment(proc, str_lit("TypeSwitchStmt"));
  5889. gbAllocator allocator = proc->module->allocator;
  5890. ast_node(as, AssignStmt, ss->tag);
  5891. GB_ASSERT(as->lhs.count == 1);
  5892. GB_ASSERT(as->rhs.count == 1);
  5893. irValue *parent = ir_build_expr(proc, as->rhs[0]);
  5894. Type *parent_type = ir_type(parent);
  5895. bool is_parent_ptr = is_type_pointer(ir_type(parent));
  5896. MatchTypeKind match_type_kind = check_valid_type_match_type(ir_type(parent));
  5897. GB_ASSERT(match_type_kind != MatchType_Invalid);
  5898. irValue *parent_value = parent;
  5899. irValue *parent_ptr = parent;
  5900. if (!is_parent_ptr) {
  5901. parent_ptr = ir_address_from_load_or_generate_local(proc, parent_ptr);
  5902. }
  5903. irValue *tag_index = nullptr;
  5904. irValue *union_data = nullptr;
  5905. if (match_type_kind == MatchType_Union) {
  5906. ir_emit_comment(proc, str_lit("get union's tag"));
  5907. tag_index = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, parent_ptr));
  5908. union_data = ir_emit_conv(proc, parent_ptr, t_rawptr);
  5909. }
  5910. irBlock *start_block = ir_new_block(proc, node, "typeswitch.case.first");
  5911. ir_emit_jump(proc, start_block);
  5912. ir_start_block(proc, start_block);
  5913. // NOTE(bill): Append this later
  5914. irBlock *done = ir_new_block(proc, node, "typeswitch.done");
  5915. AstNode *default_ = nullptr;
  5916. ast_node(body, BlockStmt, ss->body);
  5917. gb_local_persist i32 weird_count = 0;
  5918. for_array(i, body->stmts) {
  5919. AstNode *clause = body->stmts[i];
  5920. ast_node(cc, CaseClause, clause);
  5921. if (cc->list.count == 0) {
  5922. default_ = clause;
  5923. continue;
  5924. }
  5925. irBlock *body = ir_new_block(proc, clause, "typeswitch.body");
  5926. irBlock *next = nullptr;
  5927. Type *case_type = nullptr;
  5928. for_array(type_index, cc->list) {
  5929. next = ir_new_block(proc, nullptr, "typeswitch.next");
  5930. case_type = type_of_expr(proc->module->info, cc->list[type_index]);
  5931. irValue *cond = nullptr;
  5932. if (match_type_kind == MatchType_Union) {
  5933. Type *ut = base_type(type_deref(parent_type));
  5934. irValue *variant_tag = ir_const_union_tag(proc->module->allocator, ut, case_type);
  5935. cond = ir_emit_comp(proc, Token_CmpEq, tag_index, variant_tag);
  5936. } else if (match_type_kind == MatchType_Any) {
  5937. irValue *any_ti = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 1));
  5938. irValue *case_ti = ir_type_info(proc, case_type);
  5939. cond = ir_emit_comp(proc, Token_CmpEq, any_ti, case_ti);
  5940. }
  5941. GB_ASSERT(cond != nullptr);
  5942. ir_emit_if(proc, cond, body, next);
  5943. ir_start_block(proc, next);
  5944. }
  5945. Entity *case_entity = implicit_entity_of_node(proc->module->info, clause);
  5946. irValue *value = parent_value;
  5947. ir_start_block(proc, body);
  5948. if (cc->list.count == 1) {
  5949. bool any_or_not_ptr = is_type_any(type_deref(parent_type)) || !is_parent_ptr;
  5950. Type *ct = case_entity->type;
  5951. if (any_or_not_ptr) {
  5952. ct = make_type_pointer(proc->module->allocator, ct);
  5953. }
  5954. GB_ASSERT_MSG(is_type_pointer(ct), "%s", type_to_string(ct));
  5955. irValue *data = nullptr;
  5956. if (match_type_kind == MatchType_Union) {
  5957. data = union_data;
  5958. } else if (match_type_kind == MatchType_Any) {
  5959. irValue *any_data = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 0));
  5960. data = any_data;
  5961. }
  5962. value = ir_emit_conv(proc, data, ct);
  5963. if (any_or_not_ptr) {
  5964. value = ir_emit_load(proc, value);
  5965. }
  5966. }
  5967. ir_store_type_case_implicit(proc, clause, value);
  5968. ir_type_case_body(proc, ss->label, clause, body, done);
  5969. ir_start_block(proc, next);
  5970. }
  5971. if (default_ != nullptr) {
  5972. ir_store_type_case_implicit(proc, default_, parent_value);
  5973. ir_type_case_body(proc, ss->label, default_, proc->curr_block, done);
  5974. } else {
  5975. ir_emit_jump(proc, done);
  5976. }
  5977. ir_start_block(proc, done);
  5978. case_end;
  5979. case_ast_node(bs, BranchStmt, node);
  5980. irBlock *block = nullptr;
  5981. if (bs->label != nullptr) {
  5982. irBranchBlocks bb = ir_lookup_branch_blocks(proc, bs->label);
  5983. switch (bs->token.kind) {
  5984. case Token_break: block = bb.break_; break;
  5985. case Token_continue: block = bb.continue_; break;
  5986. case Token_fallthrough:
  5987. GB_PANIC("fallthrough cannot have a label");
  5988. break;
  5989. }
  5990. } else {
  5991. switch (bs->token.kind) {
  5992. case Token_break:
  5993. for (irTargetList *t = proc->target_list; t != nullptr && block == nullptr; t = t->prev) {
  5994. block = t->break_;
  5995. }
  5996. break;
  5997. case Token_continue:
  5998. for (irTargetList *t = proc->target_list; t != nullptr && block == nullptr; t = t->prev) {
  5999. block = t->continue_;
  6000. }
  6001. break;
  6002. case Token_fallthrough:
  6003. for (irTargetList *t = proc->target_list; t != nullptr && block == nullptr; t = t->prev) {
  6004. block = t->fallthrough_;
  6005. }
  6006. break;
  6007. }
  6008. }
  6009. if (block != nullptr) {
  6010. ir_emit_defer_stmts(proc, irDeferExit_Branch, block);
  6011. }
  6012. switch (bs->token.kind) {
  6013. case Token_break: ir_emit_comment(proc, str_lit("break")); break;
  6014. case Token_continue: ir_emit_comment(proc, str_lit("continue")); break;
  6015. case Token_fallthrough: ir_emit_comment(proc, str_lit("fallthrough")); break;
  6016. }
  6017. ir_emit_jump(proc, block);
  6018. ir_emit_unreachable(proc);
  6019. case_end;
  6020. case_ast_node(pa, PushAllocator, node);
  6021. ir_emit_comment(proc, str_lit("push_allocator"));
  6022. irValue *new_allocator = ir_build_expr(proc, pa->expr);
  6023. ir_open_scope(proc);
  6024. irValue *prev = ir_find_or_generate_context_ptr(proc);
  6025. irValue *next = ir_add_local_generated(proc, t_context);
  6026. ir_emit_store(proc, next, ir_emit_load(proc, prev));
  6027. Selection sel = lookup_field(proc->module->allocator, t_context, str_lit("allocator"), false);
  6028. irValue *gep = ir_emit_deep_field_gep(proc, next, sel);
  6029. ir_emit_store(proc, gep, new_allocator);
  6030. array_add(&proc->context_stack, next);
  6031. defer (array_pop(&proc->context_stack));
  6032. // TODO(bill): is this too leaky?
  6033. ir_build_stmt(proc, pa->body);
  6034. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6035. case_end;
  6036. case_ast_node(pc, PushContext, node);
  6037. ir_emit_comment(proc, str_lit("push_context"));
  6038. irValue *new_context = ir_build_expr(proc, pc->expr);
  6039. ir_open_scope(proc);
  6040. irValue *prev = ir_find_or_generate_context_ptr(proc);
  6041. irValue *next = ir_add_local_generated(proc, t_context);
  6042. ir_emit_store(proc, next, new_context);
  6043. array_add(&proc->context_stack, next);
  6044. defer (array_pop(&proc->context_stack));
  6045. ir_build_stmt(proc, pc->body);
  6046. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6047. case_end;
  6048. }
  6049. }
  6050. ////////////////////////////////////////////////////////////////
  6051. //
  6052. // @Procedure
  6053. //
  6054. ////////////////////////////////////////////////////////////////
  6055. void ir_number_proc_registers(irProcedure *proc) {
  6056. i32 reg_index = 0;
  6057. for_array(i, proc->blocks) {
  6058. irBlock *b = proc->blocks[i];
  6059. b->index = cast(i32)i;
  6060. for_array(j, b->instrs) {
  6061. irValue *value = b->instrs[j];
  6062. GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name));
  6063. irInstr *instr = &value->Instr;
  6064. if (ir_instr_type(instr) == nullptr) { // NOTE(bill): Ignore non-returning instructions
  6065. value->index = -1;
  6066. continue;
  6067. }
  6068. value->index = reg_index;
  6069. value->index_set = true;
  6070. reg_index++;
  6071. }
  6072. }
  6073. }
  6074. void ir_begin_procedure_body(irProcedure *proc) {
  6075. gbAllocator a = proc->module->allocator;
  6076. array_add(&proc->module->procs, proc);
  6077. array_init(&proc->blocks, heap_allocator());
  6078. array_init(&proc->defer_stmts, heap_allocator());
  6079. array_init(&proc->children, heap_allocator());
  6080. array_init(&proc->branch_blocks, heap_allocator());
  6081. array_init(&proc->context_stack, heap_allocator());
  6082. DeclInfo *decl = decl_info_of_entity(proc->module->info, proc->entity);
  6083. if (decl != nullptr) {
  6084. for_array(i, decl->labels) {
  6085. BlockLabel bl = decl->labels[i];
  6086. irBranchBlocks bb = {bl.label, nullptr, nullptr};
  6087. array_add(&proc->branch_blocks, bb);
  6088. }
  6089. }
  6090. proc->decl_block = ir_new_block(proc, proc->type_expr, "decls");
  6091. ir_start_block(proc, proc->decl_block);
  6092. proc->entry_block = ir_new_block(proc, proc->type_expr, "entry");
  6093. ir_start_block(proc, proc->entry_block);
  6094. if (proc->type->Proc.return_by_pointer) {
  6095. // NOTE(bill): this must be the first parameter stored
  6096. Type *ptr_type = make_type_pointer(a, reduce_tuple_to_single_type(proc->type->Proc.results));
  6097. Entity *e = make_entity_param(a, nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  6098. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  6099. irValue *param = ir_value_param(a, proc, e, ptr_type);
  6100. param->Param.kind = irParamPass_Pointer;
  6101. ir_module_add_value(proc->module, e, param);
  6102. proc->return_ptr = param;
  6103. }
  6104. GB_ASSERT(proc->type != nullptr);
  6105. if (proc->type->Proc.params != nullptr) {
  6106. TypeTuple *params = &proc->type->Proc.params->Tuple;
  6107. if (proc->type_expr != nullptr) {
  6108. ast_node(pt, ProcType, proc->type_expr);
  6109. isize param_index = 0;
  6110. isize q_index = 0;
  6111. for_array(i, params->variables) {
  6112. ast_node(fl, FieldList, pt->params);
  6113. GB_ASSERT(fl->list.count > 0);
  6114. GB_ASSERT(fl->list[0]->kind == AstNode_Field);
  6115. if (q_index == fl->list[param_index]->Field.names.count) {
  6116. q_index = 0;
  6117. param_index++;
  6118. }
  6119. ast_node(field, Field, fl->list[param_index]);
  6120. AstNode *name = field->names[q_index++];
  6121. Entity *e = params->variables[i];
  6122. if (e->kind != Entity_Variable) {
  6123. continue;
  6124. }
  6125. Type *abi_type = proc->type->Proc.abi_compat_params[i];
  6126. if (e->token.string != "" && !is_blank_ident(e->token)) {
  6127. irValue *param = ir_add_param(proc, e, name, abi_type);
  6128. array_add(&proc->params, param);
  6129. }
  6130. }
  6131. } else {
  6132. Type **abi_types = proc->type->Proc.abi_compat_params;
  6133. for_array(i, params->variables) {
  6134. Entity *e = params->variables[i];
  6135. if (e->kind != Entity_Variable) {
  6136. continue;
  6137. }
  6138. Type *abi_type = e->type;
  6139. if (abi_types != nullptr) {
  6140. abi_type = proc->type->Proc.abi_compat_params[i];
  6141. }
  6142. if (e->token.string != "" && !is_blank_ident(e->token)) {
  6143. irValue *param = ir_add_param(proc, e, nullptr, abi_type);
  6144. array_add(&proc->params, param);
  6145. }
  6146. }
  6147. }
  6148. }
  6149. if (proc->type->Proc.calling_convention == ProcCC_Odin) {
  6150. Entity *e = make_entity_param(a, nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  6151. e->flags |= EntityFlag_NoAlias;
  6152. irValue *param = ir_value_param(a, proc, e, e->type);
  6153. ir_module_add_value(proc->module, e, param);
  6154. array_add(&proc->context_stack, param);
  6155. }
  6156. }
  6157. void ir_end_procedure_body(irProcedure *proc) {
  6158. if (proc->type->Proc.result_count == 0) {
  6159. ir_emit_return(proc, nullptr);
  6160. }
  6161. if (proc->curr_block->instrs.count == 0) {
  6162. ir_emit_unreachable(proc);
  6163. }
  6164. proc->curr_block = proc->decl_block;
  6165. ir_emit_jump(proc, proc->entry_block);
  6166. proc->curr_block = nullptr;
  6167. ir_number_proc_registers(proc);
  6168. }
  6169. void ir_insert_code_before_proc(irProcedure* proc, irProcedure *parent) {
  6170. // if (parent == nullptr) {
  6171. // if (proc->name == "main") {
  6172. // ir_emit_startup_runtime(proc);
  6173. // }
  6174. // }
  6175. }
  6176. void ir_build_proc(irValue *value, irProcedure *parent) {
  6177. irProcedure *proc = &value->Proc;
  6178. proc->parent = parent;
  6179. if (proc->entity != nullptr) {
  6180. irModule *m = proc->module;
  6181. CheckerInfo *info = m->info;
  6182. Entity *e = proc->entity;
  6183. String filename = e->token.pos.file;
  6184. AstFile *f = ast_file_of_filename(info, filename);
  6185. proc->is_export = e->Procedure.is_export;
  6186. proc->is_foreign = e->Procedure.is_foreign;
  6187. irDebugInfo *di_file = nullptr;
  6188. irDebugInfo **di_file_found = map_get(&m->debug_info, hash_ast_file(f));
  6189. if (di_file_found) {
  6190. di_file = *di_file_found;
  6191. GB_ASSERT(di_file->kind == irDebugInfo_File);
  6192. } else {
  6193. di_file = ir_add_debug_info_file(proc, f);
  6194. }
  6195. ir_add_debug_info_proc(proc, e, proc->name, di_file);
  6196. }
  6197. if (proc->body != nullptr) {
  6198. u64 prev_stmt_state_flags = proc->module->stmt_state_flags;
  6199. if (proc->tags != 0) {
  6200. u64 in = proc->tags;
  6201. u64 out = proc->module->stmt_state_flags;
  6202. if (in & ProcTag_bounds_check) {
  6203. out |= StmtStateFlag_bounds_check;
  6204. out &= ~StmtStateFlag_no_bounds_check;
  6205. } else if (in & ProcTag_no_bounds_check) {
  6206. out |= StmtStateFlag_no_bounds_check;
  6207. out &= ~StmtStateFlag_bounds_check;
  6208. }
  6209. proc->module->stmt_state_flags = out;
  6210. }
  6211. ir_begin_procedure_body(proc);
  6212. ir_insert_code_before_proc(proc, parent);
  6213. ir_build_stmt(proc, proc->body);
  6214. ir_end_procedure_body(proc);
  6215. proc->module->stmt_state_flags = prev_stmt_state_flags;
  6216. }
  6217. if (proc->type->Proc.has_proc_default_values) {
  6218. auto *p = &proc->type->Proc;
  6219. for_array(i, p->params->Tuple.variables) {
  6220. Entity *f = p->params->Tuple.variables[i];
  6221. if (f->kind == Entity_Variable) {
  6222. if (f->Variable.default_value.kind == ExactValue_Procedure) {
  6223. AstNode *expr = f->Variable.default_value.value_procedure;
  6224. GB_ASSERT(expr != nullptr);
  6225. if (expr->kind == AstNode_ProcLit) {
  6226. ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  6227. }
  6228. } else {
  6229. ir_check_type_and_gen_for_proc_lit(proc, f->type);
  6230. }
  6231. }
  6232. }
  6233. }
  6234. }
  6235. ////////////////////////////////////////////////////////////////
  6236. //
  6237. // @Module
  6238. //
  6239. ////////////////////////////////////////////////////////////////
  6240. void ir_module_add_value(irModule *m, Entity *e, irValue *v) {
  6241. map_set(&m->values, hash_entity(e), v);
  6242. }
  6243. void ir_init_module(irModule *m, Checker *c) {
  6244. // TODO(bill): Determine a decent size for the arena
  6245. isize token_count = c->parser->total_token_count;
  6246. isize arena_size = 4 * token_count * gb_size_of(irValue);
  6247. gb_arena_init_from_allocator(&m->arena, heap_allocator(), arena_size);
  6248. gb_arena_init_from_allocator(&m->tmp_arena, heap_allocator(), arena_size);
  6249. // m->allocator = gb_arena_allocator(&m->arena);
  6250. m->allocator = heap_allocator();
  6251. m->tmp_allocator = gb_arena_allocator(&m->tmp_arena);
  6252. m->info = &c->info;
  6253. map_init(&m->values, heap_allocator());
  6254. map_init(&m->members, heap_allocator());
  6255. map_init(&m->debug_info, heap_allocator());
  6256. map_init(&m->entity_names, heap_allocator());
  6257. map_init(&m->anonymous_proc_lits, heap_allocator());
  6258. array_init(&m->procs, heap_allocator());
  6259. array_init(&m->procs_to_generate, heap_allocator());
  6260. array_init(&m->foreign_library_paths, heap_allocator());
  6261. map_init(&m->const_strings, heap_allocator());
  6262. // Default states
  6263. m->stmt_state_flags = 0;
  6264. m->stmt_state_flags |= StmtStateFlag_bounds_check;
  6265. {
  6266. // Add type info data
  6267. {
  6268. isize max_index = -1;
  6269. for_array(type_info_map_index, m->info->type_info_map.entries) {
  6270. auto *entry = &m->info->type_info_map.entries[type_info_map_index];
  6271. Type *t = cast(Type *)entry->key.ptr;
  6272. t = default_type(t);
  6273. isize entry_index = type_info_index(m->info, t);
  6274. if (max_index < entry_index) {
  6275. max_index = entry_index;
  6276. }
  6277. }
  6278. isize max_type_info_count = max_index+1;
  6279. String name = str_lit(IR_TYPE_INFO_DATA_NAME);
  6280. 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);
  6281. irValue *g = ir_value_global(m->allocator, e, nullptr);
  6282. g->Global.is_private = true;
  6283. ir_module_add_value(m, e, g);
  6284. map_set(&m->members, hash_string(name), g);
  6285. ir_global_type_info_data = g;
  6286. }
  6287. // Type info member buffer
  6288. {
  6289. // NOTE(bill): Removes need for heap allocation by making it global memory
  6290. isize count = 0;
  6291. for_array(entry_index, m->info->type_info_map.entries) {
  6292. auto *entry = &m->info->type_info_map.entries[entry_index];
  6293. Type *t = cast(Type *)entry->key.ptr;
  6294. switch (t->kind) {
  6295. case Type_Union:
  6296. count += t->Union.variants.count;
  6297. break;
  6298. case Type_Struct:
  6299. count += t->Struct.fields.count;
  6300. break;
  6301. case Type_Tuple:
  6302. count += t->Tuple.variables.count;
  6303. break;
  6304. }
  6305. }
  6306. {
  6307. String name = str_lit(IR_TYPE_INFO_TYPES_NAME);
  6308. Entity *e = make_entity_variable(m->allocator, nullptr, make_token_ident(name),
  6309. make_type_array(m->allocator, t_type_info_ptr, count), false);
  6310. irValue *g = ir_value_global(m->allocator, e, nullptr);
  6311. ir_module_add_value(m, e, g);
  6312. map_set(&m->members, hash_string(name), g);
  6313. ir_global_type_info_member_types = g;
  6314. }
  6315. {
  6316. String name = str_lit(IR_TYPE_INFO_NAMES_NAME);
  6317. Entity *e = make_entity_variable(m->allocator, nullptr, make_token_ident(name),
  6318. make_type_array(m->allocator, t_string, count), false);
  6319. irValue *g = ir_value_global(m->allocator, e, nullptr);
  6320. ir_module_add_value(m, e, g);
  6321. map_set(&m->members, hash_string(name), g);
  6322. ir_global_type_info_member_names = g;
  6323. }
  6324. {
  6325. String name = str_lit(IR_TYPE_INFO_OFFSETS_NAME);
  6326. Entity *e = make_entity_variable(m->allocator, nullptr, make_token_ident(name),
  6327. make_type_array(m->allocator, t_int, count), false);
  6328. irValue *g = ir_value_global(m->allocator, e, nullptr);
  6329. ir_module_add_value(m, e, g);
  6330. map_set(&m->members, hash_string(name), g);
  6331. ir_global_type_info_member_offsets = g;
  6332. }
  6333. {
  6334. String name = str_lit(IR_TYPE_INFO_USINGS_NAME);
  6335. Entity *e = make_entity_variable(m->allocator, nullptr, make_token_ident(name),
  6336. make_type_array(m->allocator, t_bool, count), false);
  6337. irValue *g = ir_value_global(m->allocator, e, nullptr);
  6338. ir_module_add_value(m, e, g);
  6339. map_set(&m->members, hash_string(name), g);
  6340. ir_global_type_info_member_usings = g;
  6341. }
  6342. }
  6343. }
  6344. {
  6345. irDebugInfo *di = ir_alloc_debug_info(m->allocator, irDebugInfo_CompileUnit);
  6346. di->CompileUnit.file = m->info->files.entries[0].value; // Zeroth is the init file
  6347. di->CompileUnit.producer = str_lit("odin");
  6348. map_set(&m->debug_info, hash_pointer(m), di);
  6349. }
  6350. }
  6351. void ir_destroy_module(irModule *m) {
  6352. map_destroy(&m->values);
  6353. map_destroy(&m->members);
  6354. map_destroy(&m->entity_names);
  6355. map_destroy(&m->anonymous_proc_lits);
  6356. map_destroy(&m->debug_info);
  6357. map_destroy(&m->const_strings);
  6358. array_free(&m->procs);
  6359. array_free(&m->procs_to_generate);
  6360. array_free(&m->foreign_library_paths);
  6361. gb_arena_free(&m->arena);
  6362. }
  6363. ////////////////////////////////////////////////////////////////
  6364. //
  6365. // @Code Generation
  6366. //
  6367. ////////////////////////////////////////////////////////////////
  6368. bool ir_gen_init(irGen *s, Checker *c) {
  6369. if (global_error_collector.count != 0) {
  6370. return false;
  6371. }
  6372. isize tc = c->parser->total_token_count;
  6373. if (tc < 2) {
  6374. return false;
  6375. }
  6376. ir_init_module(&s->module, c);
  6377. // s->module.generate_debug_info = false;
  6378. String init_fullpath = c->parser->init_fullpath;
  6379. // TODO(bill): generate appropriate output name
  6380. int pos = cast(int)string_extension_position(init_fullpath);
  6381. int dir_pos = cast(int)string_extension_position(init_fullpath);
  6382. s->output_name = filename_from_path(init_fullpath);
  6383. s->output_base = make_string(init_fullpath.text, pos);
  6384. gbFileError err = gb_file_create(&s->output_file, gb_bprintf("%.*s.ll", pos, init_fullpath.text));
  6385. if (err != gbFileError_None) {
  6386. return false;
  6387. }
  6388. return true;
  6389. }
  6390. void ir_gen_destroy(irGen *s) {
  6391. ir_destroy_module(&s->module);
  6392. gb_file_close(&s->output_file);
  6393. }
  6394. //
  6395. // Type Info stuff
  6396. //
  6397. irValue *ir_get_type_info_ptr(irProcedure *proc, Type *type) {
  6398. i32 index = cast(i32)type_info_index(proc->module->info, type);
  6399. // gb_printf_err("%d %s\n", index, type_to_string(type));
  6400. irValue *ptr = ir_emit_array_epi(proc, ir_global_type_info_data, index);
  6401. return ir_emit_bitcast(proc, ptr, t_type_info_ptr);
  6402. }
  6403. irValue *ir_type_info_member_types_offset(irProcedure *proc, isize count) {
  6404. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_types, ir_global_type_info_member_types_index);
  6405. ir_global_type_info_member_types_index += cast(i32)count;
  6406. return offset;
  6407. }
  6408. irValue *ir_type_info_member_names_offset(irProcedure *proc, isize count) {
  6409. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_names, ir_global_type_info_member_names_index);
  6410. ir_global_type_info_member_names_index += cast(i32)count;
  6411. return offset;
  6412. }
  6413. irValue *ir_type_info_member_offsets_offset(irProcedure *proc, isize count) {
  6414. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_offsets, ir_global_type_info_member_offsets_index);
  6415. ir_global_type_info_member_offsets_index += cast(i32)count;
  6416. return offset;
  6417. }
  6418. irValue *ir_type_info_member_usings_offset(irProcedure *proc, isize count) {
  6419. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_usings, ir_global_type_info_member_usings_index);
  6420. ir_global_type_info_member_usings_index += cast(i32)count;
  6421. return offset;
  6422. }
  6423. void ir_add_foreign_library_path(irModule *m, Entity *e) {
  6424. GB_ASSERT(e != nullptr);
  6425. String library_path = e->LibraryName.path;
  6426. if (library_path.len == 0) {
  6427. return;
  6428. }
  6429. for_array(path_index, m->foreign_library_paths) {
  6430. String path = m->foreign_library_paths[path_index];
  6431. #if defined(GB_SYSTEM_WINDOWS)
  6432. if (str_eq_ignore_case(path, library_path)) {
  6433. #else
  6434. if (str_eq(path, library_path)) {
  6435. #endif
  6436. return;
  6437. }
  6438. }
  6439. array_add(&m->foreign_library_paths, library_path);
  6440. }
  6441. void ir_setup_type_info_data(irProcedure *proc) { // NOTE(bill): Setup type_info data
  6442. irModule *m = proc->module;
  6443. gbAllocator a = m->allocator;
  6444. CheckerInfo *info = m->info;
  6445. if (true) {
  6446. irValue *global_type_table = ir_find_global_variable(proc, str_lit("__type_table"));
  6447. Type *type = base_type(type_deref(ir_type(ir_global_type_info_data)));
  6448. GB_ASSERT(is_type_array(type));
  6449. irValue *len = ir_const_int(proc->module->allocator, type->Array.count);
  6450. ir_fill_slice(proc, global_type_table,
  6451. ir_emit_array_epi(proc, ir_global_type_info_data, 0),
  6452. len, len);
  6453. }
  6454. // Useful types
  6455. Type *t_i64_slice_ptr = make_type_pointer(a, make_type_slice(a, t_i64));
  6456. Type *t_string_slice_ptr = make_type_pointer(a, make_type_slice(a, t_string));
  6457. i32 type_info_member_types_index = 0;
  6458. i32 type_info_member_names_index = 0;
  6459. i32 type_info_member_offsets_index = 0;
  6460. for_array(type_info_map_index, info->type_info_map.entries) {
  6461. auto *entry = &info->type_info_map.entries[type_info_map_index];
  6462. Type *t = cast(Type *)entry->key.ptr;
  6463. t = default_type(t);
  6464. if (t == t_invalid) {
  6465. continue;
  6466. }
  6467. isize entry_index = type_info_index(info, t);
  6468. irValue *tag = nullptr;
  6469. irValue *ti_ptr = ir_emit_array_epi(proc, ir_global_type_info_data, cast(i32)entry_index);
  6470. irValue *variant_ptr = ir_emit_struct_ep(proc, ti_ptr, 2);
  6471. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 0), ir_const_int(a, type_size_of(a, t)));
  6472. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 1), ir_const_int(a, type_align_of(a, t)));
  6473. switch (t->kind) {
  6474. case Type_Named: {
  6475. ir_emit_comment(proc, str_lit("TypeInfoNamed"));
  6476. tag = ir_emit_conv(proc, variant_ptr, t_type_info_named_ptr);
  6477. // TODO(bill): Which is better? The mangled name or actual name?
  6478. irValue *name = ir_const_string(a, t->Named.type_name->token.string);
  6479. irValue *gtip = ir_get_type_info_ptr(proc, t->Named.base);
  6480. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), name);
  6481. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), gtip);
  6482. break;
  6483. }
  6484. case Type_Basic:
  6485. ir_emit_comment(proc, str_lit("TypeInfoBasic"));
  6486. switch (t->Basic.kind) {
  6487. case Basic_bool:
  6488. tag = ir_emit_conv(proc, variant_ptr, t_type_info_boolean_ptr);
  6489. break;
  6490. case Basic_i8:
  6491. case Basic_u8:
  6492. case Basic_i16:
  6493. case Basic_u16:
  6494. case Basic_i32:
  6495. case Basic_u32:
  6496. case Basic_i64:
  6497. case Basic_u64:
  6498. case Basic_i128:
  6499. case Basic_u128:
  6500. case Basic_int:
  6501. case Basic_uint:
  6502. case Basic_uintptr: {
  6503. tag = ir_emit_conv(proc, variant_ptr, t_type_info_integer_ptr);
  6504. irValue *is_signed = ir_const_bool(a, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  6505. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), is_signed);
  6506. break;
  6507. }
  6508. case Basic_rune:
  6509. tag = ir_emit_conv(proc, variant_ptr, t_type_info_rune_ptr);
  6510. break;
  6511. // case Basic_f16:
  6512. case Basic_f32:
  6513. case Basic_f64:
  6514. tag = ir_emit_conv(proc, variant_ptr, t_type_info_float_ptr);
  6515. break;
  6516. // case Basic_complex32:
  6517. case Basic_complex64:
  6518. case Basic_complex128:
  6519. tag = ir_emit_conv(proc, variant_ptr, t_type_info_complex_ptr);
  6520. break;
  6521. case Basic_rawptr:
  6522. tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
  6523. break;
  6524. case Basic_string:
  6525. tag = ir_emit_conv(proc, variant_ptr, t_type_info_string_ptr);
  6526. break;
  6527. case Basic_any:
  6528. tag = ir_emit_conv(proc, variant_ptr, t_type_info_any_ptr);
  6529. break;
  6530. }
  6531. break;
  6532. case Type_Pointer: {
  6533. ir_emit_comment(proc, str_lit("TypeInfoPointer"));
  6534. tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
  6535. irValue *gep = ir_get_type_info_ptr(proc, t->Pointer.elem);
  6536. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  6537. break;
  6538. }
  6539. case Type_Array: {
  6540. ir_emit_comment(proc, str_lit("TypeInfoArray"));
  6541. tag = ir_emit_conv(proc, variant_ptr, t_type_info_array_ptr);
  6542. irValue *gep = ir_get_type_info_ptr(proc, t->Array.elem);
  6543. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  6544. isize ez = type_size_of(a, t->Array.elem);
  6545. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  6546. ir_emit_store(proc, elem_size, ir_const_int(a, ez));
  6547. irValue *count = ir_emit_struct_ep(proc, tag, 2);
  6548. ir_emit_store(proc, count, ir_const_int(a, t->Array.count));
  6549. break;
  6550. }
  6551. case Type_DynamicArray: {
  6552. ir_emit_comment(proc, str_lit("TypeInfoDynamicArray"));
  6553. tag = ir_emit_conv(proc, variant_ptr, t_type_info_dynamic_array_ptr);
  6554. irValue *gep = ir_get_type_info_ptr(proc, t->DynamicArray.elem);
  6555. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  6556. isize ez = type_size_of(a, t->DynamicArray.elem);
  6557. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  6558. ir_emit_store(proc, elem_size, ir_const_int(a, ez));
  6559. break;
  6560. }
  6561. case Type_Slice: {
  6562. ir_emit_comment(proc, str_lit("TypeInfoSlice"));
  6563. tag = ir_emit_conv(proc, variant_ptr, t_type_info_slice_ptr);
  6564. irValue *gep = ir_get_type_info_ptr(proc, t->Slice.elem);
  6565. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  6566. isize ez = type_size_of(a, t->Slice.elem);
  6567. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  6568. ir_emit_store(proc, elem_size, ir_const_int(a, ez));
  6569. break;
  6570. }
  6571. case Type_Vector: {
  6572. ir_emit_comment(proc, str_lit("TypeInfoVector"));
  6573. tag = ir_emit_conv(proc, variant_ptr, t_type_info_vector_ptr);
  6574. irValue *gep = ir_get_type_info_ptr(proc, t->Vector.elem);
  6575. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  6576. isize ez = type_size_of(a, t->Vector.elem);
  6577. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), ir_const_int(a, ez));
  6578. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), ir_const_int(a, t->Vector.count));
  6579. break;
  6580. }
  6581. case Type_Proc: {
  6582. ir_emit_comment(proc, str_lit("TypeInfoProc"));
  6583. tag = ir_emit_conv(proc, variant_ptr, t_type_info_procedure_ptr);
  6584. irValue *params = ir_emit_struct_ep(proc, tag, 0);
  6585. irValue *results = ir_emit_struct_ep(proc, tag, 1);
  6586. irValue *variadic = ir_emit_struct_ep(proc, tag, 2);
  6587. irValue *convention = ir_emit_struct_ep(proc, tag, 3);
  6588. if (t->Proc.params != nullptr) {
  6589. ir_emit_store(proc, params, ir_get_type_info_ptr(proc, t->Proc.params));
  6590. }
  6591. if (t->Proc.results != nullptr) {
  6592. ir_emit_store(proc, results, ir_get_type_info_ptr(proc, t->Proc.results));
  6593. }
  6594. ir_emit_store(proc, variadic, ir_const_bool(a, t->Proc.variadic));
  6595. ir_emit_store(proc, convention, ir_const_int(a, t->Proc.calling_convention));
  6596. // TODO(bill): TypeInfo for procedures
  6597. break;
  6598. }
  6599. case Type_Tuple: {
  6600. ir_emit_comment(proc, str_lit("TypeInfoTuple"));
  6601. tag = ir_emit_conv(proc, variant_ptr, t_type_info_tuple_ptr);
  6602. irValue *memory_types = ir_type_info_member_types_offset(proc, t->Tuple.variables.count);
  6603. irValue *memory_names = ir_type_info_member_names_offset(proc, t->Tuple.variables.count);
  6604. for_array(i, t->Tuple.variables) {
  6605. // NOTE(bill): offset is not used for tuples
  6606. Entity *f = t->Tuple.variables[i];
  6607. irValue *index = ir_const_int(a, i);
  6608. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  6609. ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
  6610. if (f->token.string.len > 0) {
  6611. irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
  6612. ir_emit_store(proc, name, ir_const_string(a, f->token.string));
  6613. }
  6614. }
  6615. irValue *count = ir_const_int(a, t->Tuple.variables.count);
  6616. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, count, count);
  6617. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, count, count);
  6618. break;
  6619. }
  6620. case Type_Enum:
  6621. ir_emit_comment(proc, str_lit("TypeInfoEnum"));
  6622. tag = ir_emit_conv(proc, variant_ptr, t_type_info_enum_ptr);
  6623. {
  6624. GB_ASSERT(t->Enum.base_type != nullptr);
  6625. irValue *base = ir_type_info(proc, t->Enum.base_type);
  6626. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), base);
  6627. if (t->Enum.field_count > 0) {
  6628. Entity **fields = t->Enum.fields;
  6629. isize count = t->Enum.field_count;
  6630. irValue *name_array = ir_generate_array(m, t_string, count,
  6631. str_lit("__$enum_names"), cast(i64)entry_index);
  6632. irValue *value_array = ir_generate_array(m, t_type_info_enum_value, count,
  6633. str_lit("__$enum_values"), cast(i64)entry_index);
  6634. bool is_value_int = is_type_integer(t->Enum.base_type);
  6635. if (!is_value_int) {
  6636. GB_ASSERT(is_type_float(t->Enum.base_type));
  6637. }
  6638. for (isize i = 0; i < count; i++) {
  6639. irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
  6640. irValue *value_ep = ir_emit_array_epi(proc, value_array, cast(i32)i);
  6641. ExactValue value = fields[i]->Constant.value;
  6642. irValue *v = ir_value_constant(a, t->Enum.base_type, value);
  6643. ir_emit_store(proc, value_ep, ir_emit_conv(proc, v, t_type_info_enum_value));
  6644. ir_emit_store(proc, name_ep, ir_const_string(a, fields[i]->token.string));
  6645. }
  6646. irValue *v_count = ir_const_int(a, count);
  6647. irValue *names = ir_emit_struct_ep(proc, tag, 1);
  6648. irValue *name_array_elem = ir_array_elem(proc, name_array);
  6649. ir_fill_slice(proc, names, name_array_elem, v_count, v_count);
  6650. irValue *values = ir_emit_struct_ep(proc, tag, 2);
  6651. irValue *value_array_elem = ir_array_elem(proc, value_array);
  6652. ir_fill_slice(proc, values, value_array_elem, v_count, v_count);
  6653. }
  6654. }
  6655. break;
  6656. case Type_Union: {
  6657. ir_emit_comment(proc, str_lit("TypeInfoUnion"));
  6658. tag = ir_emit_conv(proc, variant_ptr, t_type_info_union_ptr);
  6659. {
  6660. irValue *variant_types = ir_emit_struct_ep(proc, tag, 0);
  6661. irValue *tag_offset_ptr = ir_emit_struct_ep(proc, tag, 1);
  6662. irValue *tag_type_ptr = ir_emit_struct_ep(proc, tag, 2);
  6663. isize variant_count = gb_max(0, t->Union.variants.count);
  6664. irValue *memory_types = ir_type_info_member_types_offset(proc, variant_count);
  6665. // NOTE(bill): Zeroth is nil so ignore it
  6666. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  6667. Type *vt = t->Union.variants[variant_index];
  6668. irValue *tip = ir_get_type_info_ptr(proc, vt);
  6669. irValue *index = ir_const_int(a, variant_index);
  6670. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  6671. ir_emit_store(proc, type_info, ir_type_info(proc, vt));
  6672. }
  6673. irValue *count = ir_const_int(a, variant_count);
  6674. ir_fill_slice(proc, variant_types, memory_types, count, count);
  6675. i64 tag_size = union_tag_size(t);
  6676. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  6677. ir_emit_store(proc, tag_offset_ptr, ir_const_int(a, tag_offset));
  6678. ir_emit_store(proc, tag_type_ptr, ir_type_info(proc, union_tag_type(t)));
  6679. }
  6680. break;
  6681. }
  6682. case Type_Struct: {
  6683. ir_emit_comment(proc, str_lit("TypeInfoStruct"));
  6684. tag = ir_emit_conv(proc, variant_ptr, t_type_info_struct_ptr);
  6685. {
  6686. irValue *is_packed = ir_const_bool(a, t->Struct.is_packed);
  6687. irValue *is_ordered = ir_const_bool(a, t->Struct.is_ordered);
  6688. irValue *is_raw_union = ir_const_bool(a, t->Struct.is_raw_union);
  6689. irValue *is_custom_align = ir_const_bool(a, t->Struct.custom_align != 0);
  6690. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 4), is_packed);
  6691. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 5), is_ordered);
  6692. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 6), is_raw_union);
  6693. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 7), is_custom_align);
  6694. }
  6695. isize count = t->Struct.fields.count;
  6696. irValue *memory_types = ir_type_info_member_types_offset (proc, count);
  6697. irValue *memory_names = ir_type_info_member_names_offset (proc, count);
  6698. irValue *memory_offsets = ir_type_info_member_offsets_offset(proc, count);
  6699. irValue *memory_usings = ir_type_info_member_usings_offset (proc, count);
  6700. type_set_offsets(a, t); // NOTE(bill): Just incase the offsets have not been set yet
  6701. for (isize source_index = 0; source_index < count; source_index++) {
  6702. // TODO(bill): Order fields in source order not layout order
  6703. Entity *f = t->Struct.fields_in_src_order[source_index];
  6704. irValue *tip = ir_get_type_info_ptr(proc, f->type);
  6705. i64 foffset = 0;
  6706. if (!t->Struct.is_raw_union) {
  6707. foffset = t->Struct.offsets[f->Variable.field_index];
  6708. }
  6709. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  6710. irValue *index = ir_const_int(a, source_index);
  6711. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  6712. irValue *offset = ir_emit_ptr_offset(proc, memory_offsets, index);
  6713. irValue *is_using = ir_emit_ptr_offset(proc, memory_usings, index);
  6714. ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
  6715. if (f->token.string.len > 0) {
  6716. irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
  6717. ir_emit_store(proc, name, ir_const_string(a, f->token.string));
  6718. }
  6719. ir_emit_store(proc, offset, ir_const_int(a, foffset));
  6720. ir_emit_store(proc, is_using, ir_const_bool(a, (f->flags&EntityFlag_Using) != 0));
  6721. }
  6722. irValue *cv = ir_const_int(a, count);
  6723. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, cv, cv);
  6724. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, cv, cv);
  6725. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 2), memory_offsets, cv, cv);
  6726. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 3), memory_usings, cv, cv);
  6727. break;
  6728. }
  6729. case Type_Map: {
  6730. ir_emit_comment(proc, str_lit("TypeInfoMap"));
  6731. tag = ir_emit_conv(proc, variant_ptr, t_type_info_map_ptr);
  6732. generate_map_internal_types(a, t);
  6733. irValue *key = ir_emit_struct_ep(proc, tag, 0);
  6734. irValue *value = ir_emit_struct_ep(proc, tag, 1);
  6735. irValue *generated_struct = ir_emit_struct_ep(proc, tag, 2);
  6736. ir_emit_store(proc, key, ir_get_type_info_ptr(proc, t->Map.key));
  6737. ir_emit_store(proc, value, ir_get_type_info_ptr(proc, t->Map.value));
  6738. ir_emit_store(proc, generated_struct, ir_get_type_info_ptr(proc, t->Map.generated_struct_type));
  6739. break;
  6740. }
  6741. case Type_BitField: {
  6742. ir_emit_comment(proc, str_lit("TypeInfoBitField"));
  6743. tag = ir_emit_conv(proc, variant_ptr, t_type_info_bit_field_ptr);
  6744. // names: []string;
  6745. // bits: []u32;
  6746. // offsets: []u32;
  6747. isize count = t->BitField.field_count;
  6748. if (count > 0) {
  6749. Entity **fields = t->BitField.fields;
  6750. irValue *name_array = ir_generate_array(m, t_string, count, str_lit("__$bit_field_names"), cast(i64)entry_index);
  6751. irValue *bit_array = ir_generate_array(m, t_i32, count, str_lit("__$bit_field_bits"), cast(i64)entry_index);
  6752. irValue *offset_array = ir_generate_array(m, t_i32, count, str_lit("__$bit_field_offsets"), cast(i64)entry_index);
  6753. for (isize i = 0; i < count; i++) {
  6754. Entity *f = fields[i];
  6755. GB_ASSERT(f->type != nullptr);
  6756. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  6757. irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
  6758. irValue *bit_ep = ir_emit_array_epi(proc, bit_array, cast(i32)i);
  6759. irValue *offset_ep = ir_emit_array_epi(proc, offset_array, cast(i32)i);
  6760. ir_emit_store(proc, name_ep, ir_const_string(a, f->token.string));
  6761. ir_emit_store(proc, bit_ep, ir_const_i32(a, f->type->BitFieldValue.bits));
  6762. ir_emit_store(proc, offset_ep, ir_const_i32(a, t->BitField.offsets[i]));
  6763. }
  6764. irValue *v_count = ir_const_int(a, count);
  6765. irValue *names = ir_emit_struct_ep(proc, tag, 0);
  6766. irValue *name_array_elem = ir_array_elem(proc, name_array);
  6767. ir_fill_slice(proc, names, name_array_elem, v_count, v_count);
  6768. irValue *bits = ir_emit_struct_ep(proc, tag, 1);
  6769. irValue *bit_array_elem = ir_array_elem(proc, bit_array);
  6770. ir_fill_slice(proc, bits, bit_array_elem, v_count, v_count);
  6771. irValue *offsets = ir_emit_struct_ep(proc, tag, 2);
  6772. irValue *offset_array_elem = ir_array_elem(proc, offset_array);
  6773. ir_fill_slice(proc, offsets, offset_array_elem, v_count, v_count);
  6774. }
  6775. break;
  6776. }
  6777. }
  6778. if (tag != nullptr) {
  6779. Type *tag_type = type_deref(ir_type(tag));
  6780. GB_ASSERT(is_type_named(tag_type));
  6781. Type *variant_type = type_deref(ir_type(variant_ptr));
  6782. irValue *tag = ir_const_union_tag(a, variant_type, tag_type);
  6783. irValue *ptr = ir_emit_union_tag_ptr(proc, variant_ptr);
  6784. ir_emit_store(proc, ptr, tag);
  6785. } else {
  6786. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  6787. }
  6788. }
  6789. }
  6790. void ir_gen_tree(irGen *s) {
  6791. irModule *m = &s->module;
  6792. CheckerInfo *info = m->info;
  6793. gbAllocator a = m->allocator;
  6794. if (v_zero == nullptr) {
  6795. v_zero = ir_const_int (m->allocator, 0);
  6796. v_one = ir_const_int (m->allocator, 1);
  6797. v_zero32 = ir_const_i32 (m->allocator, 0);
  6798. v_one32 = ir_const_i32 (m->allocator, 1);
  6799. v_two32 = ir_const_i32 (m->allocator, 2);
  6800. v_false = ir_const_bool(m->allocator, false);
  6801. v_true = ir_const_bool(m->allocator, true);
  6802. v_raw_nil = ir_value_constant(m->allocator, t_rawptr, exact_value_pointer(0));
  6803. }
  6804. isize global_variable_max_count = 0;
  6805. Entity *entry_point = info->entry_point;
  6806. bool has_dll_main = false;
  6807. bool has_win_main = false;
  6808. for_array(i, info->entities.entries) {
  6809. auto *entry = &info->entities.entries[i];
  6810. Entity *e = cast(Entity *)entry->key.ptr;
  6811. String name = e->token.string;
  6812. if (e->kind == Entity_Variable) {
  6813. global_variable_max_count++;
  6814. } else if (e->kind == Entity_Procedure && !e->scope->is_global) {
  6815. if (e->scope->is_init && name == "main") {
  6816. GB_ASSERT(e == entry_point);
  6817. // entry_point = e;
  6818. }
  6819. if (e->Procedure.is_export ||
  6820. (e->Procedure.link_name.len > 0) ||
  6821. (e->scope->is_file && e->Procedure.link_name.len > 0)) {
  6822. if (!has_dll_main && name == "DllMain") {
  6823. has_dll_main = true;
  6824. } else if (!has_win_main && name == "WinMain") {
  6825. has_win_main = true;
  6826. }
  6827. }
  6828. }
  6829. }
  6830. { // Add global default context
  6831. m->global_default_context = ir_add_global_generated(m, t_context, nullptr);
  6832. }
  6833. struct irGlobalVariable {
  6834. irValue *var, *init;
  6835. DeclInfo *decl;
  6836. };
  6837. Array<irGlobalVariable> global_variables;
  6838. array_init(&global_variables, m->tmp_allocator, global_variable_max_count);
  6839. m->entry_point_entity = entry_point;
  6840. m->min_dep_set = info->minimum_dependency_set;
  6841. for_array(i, info->variable_init_order) {
  6842. DeclInfo *d = info->variable_init_order[i];
  6843. for (isize j = 0; j < d->entity_count; j++) {
  6844. Entity *e = d->entities[j];
  6845. if (!e->scope->is_file) {
  6846. continue;
  6847. }
  6848. if (!ptr_set_exists(&m->min_dep_set, e)) {
  6849. continue;
  6850. }
  6851. DeclInfo *decl = decl_info_of_entity(info, e);
  6852. if (decl == nullptr) {
  6853. continue;
  6854. }
  6855. GB_ASSERT(e->kind == Entity_Variable);
  6856. bool is_foreign = e->Variable.is_foreign;
  6857. bool is_export = e->Variable.is_export;
  6858. bool no_name_mangle = e->scope->is_global || e->Variable.link_name.len > 0 || is_foreign || is_export;
  6859. String name = e->token.string;
  6860. if (!no_name_mangle) {
  6861. name = ir_mangle_name(s, e->token.pos.file, e);
  6862. }
  6863. ir_add_entity_name(m, e, name);
  6864. irValue *g = ir_value_global(a, e, nullptr);
  6865. g->Global.name = name;
  6866. g->Global.thread_local_model = e->Variable.thread_local_model;
  6867. g->Global.is_foreign = is_foreign;
  6868. g->Global.is_export = is_export;
  6869. irGlobalVariable var = {};
  6870. var.var = g;
  6871. var.decl = decl;
  6872. if (e->type->kind == Type_Struct && e->type->Struct.has_proc_default_values) {
  6873. for_array(i, e->type->Struct.fields) {
  6874. Entity *f = e->type->Struct.fields[i];
  6875. if (f->kind == Entity_Variable && f->Variable.default_value.kind == ExactValue_Procedure) {
  6876. AstNode *expr = f->Variable.default_value.value_procedure;
  6877. GB_ASSERT(expr != nullptr);
  6878. if (expr->kind == AstNode_ProcLit) {
  6879. ir_gen_anonymous_proc_lit(m, e->token.string, expr);
  6880. }
  6881. }
  6882. }
  6883. }
  6884. if (decl->init_expr != nullptr) {
  6885. if (is_type_any(e->type)) {
  6886. } else {
  6887. TypeAndValue tav = type_and_value_of_expr(info, decl->init_expr);
  6888. if (tav.mode != Addressing_Invalid) {
  6889. if (tav.value.kind != ExactValue_Invalid) {
  6890. ExactValue v = tav.value;
  6891. g->Global.value = ir_add_module_constant(m, tav.type, v);
  6892. }
  6893. }
  6894. }
  6895. }
  6896. // if (g->Global.value == nullptr) {
  6897. array_add(&global_variables, var);
  6898. // }
  6899. ir_module_add_value(m, e, g);
  6900. map_set(&m->members, hash_string(name), g);
  6901. }
  6902. }
  6903. for_array(i, info->entities.entries) {
  6904. auto *entry = &info->entities.entries[i];
  6905. Entity *e = cast(Entity *)entry->key.ptr;
  6906. String name = e->token.string;
  6907. DeclInfo *decl = entry->value;
  6908. Scope *scope = e->scope;
  6909. if (!scope->is_file) {
  6910. continue;
  6911. }
  6912. if (e->kind == Entity_Variable) {
  6913. // NOTE(bill): Handled above as it requires a specific load order
  6914. continue;
  6915. }
  6916. bool polymorphic_struct = false;
  6917. if (e->type != nullptr && e->kind == Entity_TypeName) {
  6918. Type *bt = base_type(e->type);
  6919. if (bt->kind == Type_Struct) {
  6920. polymorphic_struct = is_type_polymorphic(bt);
  6921. }
  6922. }
  6923. if (!polymorphic_struct && !ptr_set_exists(&m->min_dep_set, e)) {
  6924. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  6925. continue;
  6926. }
  6927. String original_name = name;
  6928. if (!scope->is_global || polymorphic_struct || is_type_polymorphic(e->type)) {
  6929. if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  6930. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  6931. // Handle later
  6932. } else {
  6933. name = ir_mangle_name(s, e->token.pos.file, e);
  6934. }
  6935. } else if (check_is_entity_overloaded(e)) {
  6936. name = ir_mangle_name(s, e->token.pos.file, e);
  6937. }
  6938. ir_add_entity_name(m, e, name);
  6939. switch (e->kind) {
  6940. case Entity_TypeName:
  6941. ir_gen_global_type_name(m, e, name);
  6942. break;
  6943. case Entity_Procedure: {
  6944. ast_node(pl, ProcLit, decl->proc_lit);
  6945. String original_name = name;
  6946. AstNode *body = pl->body;
  6947. if (e->Procedure.is_foreign) {
  6948. name = e->token.string; // NOTE(bill): Don't use the mangled name
  6949. ir_add_foreign_library_path(m, e->Procedure.foreign_library);
  6950. }
  6951. if (e->Procedure.link_name.len > 0) {
  6952. name = e->Procedure.link_name;
  6953. }
  6954. AstNode *type_expr = pl->type;
  6955. irValue *p = ir_value_procedure(a, m, e, e->type, type_expr, body, name);
  6956. p->Proc.tags = pl->tags;
  6957. p->Proc.inlining = pl->inlining;
  6958. ir_module_add_value(m, e, p);
  6959. HashKey hash_name = hash_string(name);
  6960. if (map_get(&m->members, hash_name) == nullptr) {
  6961. multi_map_insert(&m->members, hash_name, p);
  6962. }
  6963. break;
  6964. }
  6965. }
  6966. }
  6967. for_array(i, m->members.entries) {
  6968. auto *entry = &m->members.entries[i];
  6969. irValue *v = entry->value;
  6970. if (v->kind == irValue_Proc) {
  6971. ir_build_proc(v, nullptr);
  6972. }
  6973. }
  6974. irDebugInfo *compile_unit = m->debug_info.entries[0].value;
  6975. GB_ASSERT(compile_unit->kind == irDebugInfo_CompileUnit);
  6976. irDebugInfo *all_procs = ir_alloc_debug_info(m->allocator, irDebugInfo_AllProcs);
  6977. isize all_proc_max_count = 0;
  6978. for_array(i, m->debug_info.entries) {
  6979. auto *entry = &m->debug_info.entries[i];
  6980. irDebugInfo *di = entry->value;
  6981. di->id = cast(i32)i;
  6982. if (di->kind == irDebugInfo_Proc) {
  6983. all_proc_max_count++;
  6984. }
  6985. }
  6986. array_init(&all_procs->AllProcs.procs, m->allocator, all_proc_max_count);
  6987. map_set(&m->debug_info, hash_pointer(all_procs), all_procs); // NOTE(bill): This doesn't need to be mapped
  6988. compile_unit->CompileUnit.all_procs = all_procs;
  6989. for_array(i, m->debug_info.entries) {
  6990. auto *entry = &m->debug_info.entries[i];
  6991. irDebugInfo *di = entry->value;
  6992. if (di->kind == irDebugInfo_Proc) {
  6993. array_add(&all_procs->AllProcs.procs, di);
  6994. }
  6995. }
  6996. #if defined(GB_SYSTEM_WINDOWS)
  6997. if (build_context.is_dll && !has_dll_main) {
  6998. // DllMain :: proc(inst: rawptr, reason: u32, reserved: rawptr) -> i32
  6999. String name = str_lit("DllMain");
  7000. Type *proc_params = make_type_tuple(a);
  7001. Type *proc_results = make_type_tuple(a);
  7002. Scope *proc_scope = gb_alloc_item(a, Scope);
  7003. array_init_count(&proc_params->Tuple.variables, a, 3);
  7004. array_init_count(&proc_results->Tuple.variables, a, 1);
  7005. proc_params->Tuple.variables[0] = make_entity_param(a, proc_scope, blank_token, t_rawptr, false, false);
  7006. proc_params->Tuple.variables[1] = make_entity_param(a, proc_scope, make_token_ident(str_lit("reason")), t_i32, false, false);
  7007. proc_params->Tuple.variables[2] = make_entity_param(a, proc_scope, blank_token, t_rawptr, false, false);
  7008. proc_results->Tuple.variables[0] = make_entity_param(a, proc_scope, empty_token, t_i32, false, false);
  7009. Type *proc_type = make_type_proc(a, proc_scope,
  7010. proc_params, 3,
  7011. proc_results, 1, false, ProcCC_StdCall);
  7012. // TODO(bill): make this more robust
  7013. proc_type->Proc.abi_compat_params = gb_alloc_array(a, Type *, proc_params->Tuple.variables.count);
  7014. for_array(i, proc_params->Tuple.variables) {
  7015. proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
  7016. }
  7017. proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
  7018. AstNode *body = gb_alloc_item(a, AstNode);
  7019. Entity *e = make_entity_procedure(a, nullptr, make_token_ident(name), proc_type, 0);
  7020. irValue *p = ir_value_procedure(a, m, e, proc_type, nullptr, body, name);
  7021. map_set(&m->values, hash_entity(e), p);
  7022. map_set(&m->members, hash_string(name), p);
  7023. irProcedure *proc = &p->Proc;
  7024. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  7025. proc->is_entry_point = true;
  7026. e->Procedure.link_name = name;
  7027. ir_begin_procedure_body(proc);
  7028. // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
  7029. // DLL_PROCESS_ATTACH == 1
  7030. irAddr reason_addr = ir_build_addr_from_entity(proc, proc_params->Tuple.variables[1], nullptr);
  7031. irValue *cond = ir_emit_comp(proc, Token_CmpEq, ir_addr_load(proc, reason_addr), v_one32);
  7032. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  7033. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  7034. ir_emit_if(proc, cond, then, done);
  7035. ir_start_block(proc, then);
  7036. {
  7037. irValue **found = map_get(&m->values, hash_entity(entry_point));
  7038. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  7039. if (found != nullptr) {
  7040. ir_emit_call(proc, *found, nullptr, 0);
  7041. }
  7042. }
  7043. ir_emit_jump(proc, done);
  7044. ir_start_block(proc, done);
  7045. ir_emit_return(proc, v_one32);
  7046. ir_end_procedure_body(proc);
  7047. }
  7048. #endif
  7049. if (!(build_context.is_dll && !has_dll_main)) {
  7050. // main :: proc(argc: i32, argv: ^^u8) -> i32
  7051. String name = str_lit("main");
  7052. Type *proc_params = make_type_tuple(a);
  7053. Type *proc_results = make_type_tuple(a);
  7054. Scope *proc_scope = gb_alloc_item(a, Scope);
  7055. array_init_count(&proc_params->Tuple.variables, a, 2);
  7056. array_init_count(&proc_results->Tuple.variables, a, 1);
  7057. Type *char_ptr_ptr = make_type_pointer(a, make_type_pointer(a, t_u8));
  7058. proc_params->Tuple.variables[0] = make_entity_param(a, proc_scope, make_token_ident(str_lit("argc")), t_i32, false, false);
  7059. proc_params->Tuple.variables[1] = make_entity_param(a, proc_scope, make_token_ident(str_lit("argv")), char_ptr_ptr, false, false);
  7060. proc_results->Tuple.variables[0] = make_entity_param(a, proc_scope, empty_token, t_i32, false, false);
  7061. Type *proc_type = make_type_proc(a, proc_scope,
  7062. proc_params, 2,
  7063. proc_results, 1, false, ProcCC_CDecl);
  7064. // TODO(bill): make this more robust
  7065. proc_type->Proc.abi_compat_params = gb_alloc_array(a, Type *, proc_params->Tuple.variables.count);
  7066. for_array(i, proc_params->Tuple.variables) {
  7067. proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
  7068. }
  7069. proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
  7070. AstNode *body = gb_alloc_item(a, AstNode);
  7071. Entity *e = make_entity_procedure(a, nullptr, make_token_ident(name), proc_type, 0);
  7072. irValue *p = ir_value_procedure(a, m, e, proc_type, nullptr, body, name);
  7073. map_set(&m->values, hash_entity(e), p);
  7074. map_set(&m->members, hash_string(name), p);
  7075. irProcedure *proc = &p->Proc;
  7076. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  7077. proc->is_entry_point = true;
  7078. e->Procedure.link_name = name;
  7079. ir_begin_procedure_body(proc);
  7080. // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
  7081. // DLL_PROCESS_ATTACH == 1
  7082. irValue *argc = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[0])));
  7083. irValue *argv = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[1])));
  7084. irValue *global_argc = ir_find_global_variable(proc, str_lit("__argc__"));
  7085. irValue *global_argv = ir_find_global_variable(proc, str_lit("__argv__"));
  7086. ir_emit_store(proc, global_argc, argc);
  7087. ir_emit_store(proc, global_argv, argv);
  7088. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  7089. {
  7090. irValue **found = map_get(&proc->module->values, hash_entity(entry_point));
  7091. if (found != nullptr) {
  7092. ir_emit_call(proc, *found, nullptr, 0);
  7093. }
  7094. }
  7095. ir_emit_return(proc, v_zero32);
  7096. ir_end_procedure_body(proc);
  7097. }
  7098. #if 0 && defined(GB_SYSTEM_WINDOWS)
  7099. if (!m->build_context->is_dll && !has_win_main) {
  7100. // proc WinMain(inst, prev: rawptr, cmd_line: ^byte, cmd_show: i32) -> i32
  7101. String name = str_lit("WinMain");
  7102. Type *proc_params = make_type_tuple(a);
  7103. Type *proc_results = make_type_tuple(a);
  7104. Scope *proc_scope = gb_alloc_item(a, Scope);
  7105. proc_params->Tuple.variables = gb_alloc_array(a, Entity *, 4);
  7106. proc_params->Tuple.variable_count = 4;
  7107. proc_results->Tuple.variables = gb_alloc_array(a, Entity *, 1);
  7108. proc_results->Tuple.variable_count = 1;
  7109. proc_params->Tuple.variables[0] = make_entity_param(a, proc_scope, blank_token, t_rawptr, false);
  7110. proc_params->Tuple.variables[1] = make_entity_param(a, proc_scope, blank_token, t_rawptr, false);
  7111. proc_params->Tuple.variables[2] = make_entity_param(a, proc_scope, blank_token, t_u8_ptr, false);
  7112. proc_params->Tuple.variables[3] = make_entity_param(a, proc_scope, blank_token, t_i32, false);
  7113. proc_results->Tuple.variables[0] = make_entity_param(a, proc_scope, empty_token, t_i32, false);
  7114. Type *proc_type = make_type_proc(a, proc_scope,
  7115. proc_params, 4,
  7116. proc_results, 1, false, ProcCC_Std);
  7117. AstNode *body = gb_alloc_item(a, AstNode);
  7118. Entity *e = make_entity_procedure(a, nullptr, make_token_ident(name), proc_type, 0);
  7119. irValue *p = ir_value_procedure(a, m, e, proc_type, nullptr, body, name);
  7120. m->entry_point_entity = e;
  7121. map_set(&m->values, hash_entity(e), p);
  7122. map_set(&m->members, hash_string(name), p);
  7123. irProcedure *proc = &p->Proc;
  7124. proc->tags = ProcTag_no_inline; // TODO(bill): is no_inline a good idea?
  7125. e->Procedure.link_name = name;
  7126. ir_begin_procedure_body(proc);
  7127. ir_emit_global_call(proc, "main", nullptr, 0);
  7128. ir_emit_return(proc, v_one32);
  7129. ir_end_procedure_body(proc);
  7130. }
  7131. #endif
  7132. { // Startup Runtime
  7133. // Cleanup(bill): probably better way of doing code insertion
  7134. String name = str_lit(IR_STARTUP_RUNTIME_PROC_NAME);
  7135. Type *proc_type = make_type_proc(a, gb_alloc_item(a, Scope),
  7136. nullptr, 0,
  7137. nullptr, 0, false,
  7138. ProcCC_Contextless);
  7139. AstNode *body = gb_alloc_item(a, AstNode);
  7140. Entity *e = make_entity_procedure(a, nullptr, make_token_ident(name), proc_type, 0);
  7141. irValue *p = ir_value_procedure(a, m, e, proc_type, nullptr, body, name);
  7142. map_set(&m->values, hash_entity(e), p);
  7143. map_set(&m->members, hash_string(name), p);
  7144. irProcedure *proc = &p->Proc;
  7145. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  7146. ir_begin_procedure_body(proc);
  7147. {
  7148. irValue **args = gb_alloc_array(a, irValue *, 1);
  7149. args[0] = m->global_default_context;
  7150. ir_emit_global_call(proc, "__init_context", args, 1);
  7151. }
  7152. ir_setup_type_info_data(proc);
  7153. for_array(i, global_variables) {
  7154. irGlobalVariable *var = &global_variables[i];
  7155. if (var->decl->init_expr != nullptr) {
  7156. var->init = ir_build_expr(proc, var->decl->init_expr);
  7157. }
  7158. if (var->init != nullptr) {
  7159. Type *t = type_deref(ir_type(var->var));
  7160. if (is_type_any(t)) {
  7161. // NOTE(bill): Edge case for `any` type
  7162. Type *var_type = default_type(ir_type(var->init));
  7163. irValue *g = ir_add_global_generated(proc->module, var_type, var->init);
  7164. ir_emit_store(proc, g, var->init);
  7165. irValue *data = ir_emit_struct_ep(proc, var->var, 0);
  7166. irValue *ti = ir_emit_struct_ep(proc, var->var, 1);
  7167. ir_emit_store(proc, data, ir_emit_conv(proc, g, t_rawptr));
  7168. ir_emit_store(proc, ti, ir_type_info(proc, var_type));
  7169. } else {
  7170. ir_emit_store(proc, var->var, ir_emit_conv(proc, var->init, t));
  7171. }
  7172. }
  7173. }
  7174. ir_end_procedure_body(proc);
  7175. }
  7176. for_array(type_info_map_index, info->type_info_map.entries) {
  7177. auto *entry = &info->type_info_map.entries[type_info_map_index];
  7178. Type *t = cast(Type *)entry->key.ptr;
  7179. t = default_type(t);
  7180. isize entry_index = entry->value;
  7181. gbString s = type_to_string(t);
  7182. GB_ASSERT(s[0] != 0);
  7183. // gb_printf_err("%s\n", s);
  7184. }
  7185. for_array(i, m->procs_to_generate) {
  7186. irValue *p = m->procs_to_generate[i];
  7187. ir_build_proc(p, p->Proc.parent);
  7188. }
  7189. // Number debug info
  7190. for_array(i, m->debug_info.entries) {
  7191. auto *entry = &m->debug_info.entries[i];
  7192. irDebugInfo *di = entry->value;
  7193. di->id = cast(i32)i;
  7194. }
  7195. // 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");
  7196. }