ir.cpp 406 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814
  1. struct irProcedure;
  2. struct irBlock;
  3. struct irValue;
  4. struct irDebugInfo;
  5. struct irModule {
  6. CheckerInfo * info;
  7. gbArena tmp_arena;
  8. // gbAllocator allocator;
  9. gbAllocator tmp_allocator;
  10. bool generate_debug_info;
  11. u64 state_flags;
  12. // String source_filename;
  13. // String layout;
  14. // String triple;
  15. PtrSet<Entity *> min_dep_set;
  16. Map<irValue *> values; // Key: Entity *
  17. StringMap<irValue *> members;
  18. Map<String> entity_names; // Key: Entity * of the typename
  19. Map<irDebugInfo *> debug_info; // Key: Unique pointer
  20. Map<irValue *> anonymous_proc_lits; // Key: Ast *
  21. irDebugInfo * debug_compile_unit;
  22. Array<irDebugInfo *> debug_location_stack;
  23. i32 global_string_index;
  24. i32 global_array_index; // For ConstantSlice
  25. i32 global_generated_index;
  26. irValue * global_default_context;
  27. // NOTE(bill): To prevent strings from being copied a lot
  28. // Mainly used for file names
  29. StringMap<irValue *> const_strings;
  30. StringMap<irValue *> const_string_byte_slices;
  31. Map<irValue *> constant_value_to_global; // Key: irValue *
  32. Entity * entry_point_entity;
  33. Array<irProcedure *> procs; // NOTE(bill): All procedures with bodies
  34. Array<irValue *> procs_to_generate; // NOTE(bill): Procedures to generate
  35. Array<String> foreign_library_paths; // Only the ones that were used
  36. };
  37. // NOTE(bill): For more info, see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
  38. struct irDomNode {
  39. irBlock * idom; // Parent (Immediate Dominator)
  40. Array<irBlock *> children;
  41. i32 pre, post; // Ordering in tree
  42. };
  43. struct irBlock {
  44. i32 index;
  45. String label;
  46. irProcedure *proc;
  47. Ast * node; // Can be nullptr
  48. Scope * scope;
  49. isize scope_index;
  50. irDomNode dom;
  51. i32 gaps;
  52. Array<irValue *> instrs;
  53. Array<irValue *> locals;
  54. Array<irBlock *> preds;
  55. Array<irBlock *> succs;
  56. };
  57. struct irTargetList {
  58. irTargetList *prev;
  59. bool is_block;
  60. irBlock * break_;
  61. irBlock * continue_;
  62. irBlock * fallthrough_;
  63. };
  64. enum irDeferExitKind {
  65. irDeferExit_Default,
  66. irDeferExit_Return,
  67. irDeferExit_Branch,
  68. };
  69. enum irDeferKind {
  70. irDefer_Node,
  71. irDefer_Instr,
  72. irDefer_Proc,
  73. };
  74. struct irDefer {
  75. irDeferKind kind;
  76. isize scope_index;
  77. isize context_stack_count;
  78. irBlock * block;
  79. union {
  80. Ast *stmt;
  81. // NOTE(bill): 'instr' will be copied every time to create a new one
  82. irValue *instr;
  83. struct {
  84. irValue *deferred;
  85. Array<irValue *> result_as_args;
  86. } proc;
  87. };
  88. };
  89. struct irBranchBlocks {
  90. Ast *label;
  91. irBlock *break_;
  92. irBlock *continue_;
  93. };
  94. struct irContextData {
  95. irValue *value;
  96. isize scope_index;
  97. };
  98. struct irProcedure {
  99. irProcedure * parent;
  100. Array<irProcedure *> children;
  101. Entity * entity;
  102. irModule * module;
  103. String name;
  104. Type * type;
  105. Ast * type_expr;
  106. Ast * body;
  107. u64 tags;
  108. ProcInlining inlining;
  109. bool is_foreign;
  110. bool is_export;
  111. bool is_entry_point;
  112. bool is_startup;
  113. irDebugInfo * debug_scope;
  114. irValue * return_ptr;
  115. Array<irValue *> params;
  116. Array<irDefer> defer_stmts;
  117. Array<irBlock *> blocks;
  118. i32 scope_index;
  119. irBlock * decl_block;
  120. irBlock * entry_block;
  121. irBlock * curr_block;
  122. irTargetList * target_list;
  123. Array<irValue *> referrers;
  124. Ast *curr_stmt;
  125. Array<irContextData> context_stack;
  126. i32 parameter_count;
  127. irValue *return_ptr_hint_value;
  128. Ast * return_ptr_hint_ast;
  129. bool return_ptr_hint_used;
  130. Array<irBranchBlocks> branch_blocks;
  131. i32 local_count;
  132. i32 instr_count;
  133. i32 block_count;
  134. };
  135. gb_global Arena global_ir_arena = {};
  136. gbAllocator ir_allocator(void) {
  137. Arena *arena = &global_ir_arena;
  138. return arena_allocator(arena);
  139. }
  140. #define IR_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime"
  141. #define IR_TYPE_INFO_DATA_NAME "__$type_info_data"
  142. #define IR_TYPE_INFO_TYPES_NAME "__$type_info_types_data"
  143. #define IR_TYPE_INFO_NAMES_NAME "__$type_info_names_data"
  144. #define IR_TYPE_INFO_OFFSETS_NAME "__$type_info_offsets_data"
  145. #define IR_TYPE_INFO_USINGS_NAME "__$type_info_usings_data"
  146. #define IR_TYPE_INFO_TAGS_NAME "__$type_info_tags_data"
  147. #define IR_INSTR_KINDS \
  148. IR_INSTR_KIND(Comment, struct { String text; }) \
  149. IR_INSTR_KIND(Local, struct { \
  150. Entity * entity; \
  151. Type * type; \
  152. bool zero_initialized; \
  153. Array<irValue *> referrers; \
  154. i64 alignment; \
  155. }) \
  156. IR_INSTR_KIND(ZeroInit, struct { irValue *address; }) \
  157. IR_INSTR_KIND(Store, struct { irValue *address, *value; bool is_volatile; }) \
  158. IR_INSTR_KIND(Load, struct { Type *type; irValue *address; i64 custom_align; }) \
  159. IR_INSTR_KIND(InlineCode, struct { BuiltinProcId id; Array<irValue *> operands; }) \
  160. IR_INSTR_KIND(AtomicFence, struct { BuiltinProcId id; }) \
  161. IR_INSTR_KIND(AtomicStore, struct { \
  162. irValue *address, *value; \
  163. BuiltinProcId id; \
  164. }) \
  165. IR_INSTR_KIND(AtomicLoad, struct { \
  166. Type *type; irValue *address; \
  167. BuiltinProcId id; \
  168. }) \
  169. IR_INSTR_KIND(AtomicRmw, struct { \
  170. Type *type; irValue *address; \
  171. irValue *value; \
  172. BuiltinProcId id; \
  173. }) \
  174. IR_INSTR_KIND(AtomicCxchg, struct { \
  175. Type *type; irValue *address; \
  176. irValue *old_value; irValue *new_value; \
  177. BuiltinProcId id; \
  178. }) \
  179. IR_INSTR_KIND(PtrOffset, struct { \
  180. irValue *address; \
  181. irValue *offset; \
  182. }) \
  183. IR_INSTR_KIND(ArrayElementPtr, struct { \
  184. irValue *address; \
  185. Type * result_type; \
  186. irValue *elem_index; \
  187. }) \
  188. IR_INSTR_KIND(StructElementPtr, struct { \
  189. irValue *address; \
  190. Type * result_type; \
  191. i32 elem_index; \
  192. }) \
  193. IR_INSTR_KIND(StructExtractValue, struct { \
  194. irValue *address; \
  195. Type * result_type; \
  196. i32 index; \
  197. }) \
  198. IR_INSTR_KIND(UnionTagPtr, struct { \
  199. irValue *address; \
  200. Type *type; /* ^int */ \
  201. }) \
  202. IR_INSTR_KIND(UnionTagValue, struct { \
  203. irValue *address; \
  204. Type *type; /* int */ \
  205. }) \
  206. IR_INSTR_KIND(Conv, struct { \
  207. irConvKind kind; \
  208. irValue *value; \
  209. Type *from, *to; \
  210. }) \
  211. IR_INSTR_KIND(Jump, struct { irBlock *block; }) \
  212. IR_INSTR_KIND(If, struct { \
  213. irValue *cond; \
  214. irBlock *true_block; \
  215. irBlock *false_block; \
  216. }) \
  217. IR_INSTR_KIND(Return, struct { irValue *value; }) \
  218. IR_INSTR_KIND(Select, struct { \
  219. irValue *cond; \
  220. irValue *true_value; \
  221. irValue *false_value; \
  222. }) \
  223. IR_INSTR_KIND(Phi, struct { Array<irValue *> edges; Type *type; })\
  224. IR_INSTR_KIND(Unreachable, i32) \
  225. IR_INSTR_KIND(UnaryOp, struct { \
  226. Type * type; \
  227. TokenKind op; \
  228. irValue * expr; \
  229. }) \
  230. IR_INSTR_KIND(BinaryOp, struct { \
  231. Type * type; \
  232. TokenKind op; \
  233. irValue * left, *right; \
  234. }) \
  235. IR_INSTR_KIND(Call, struct { \
  236. Type * type; /* return type */ \
  237. irValue * value; \
  238. irValue * return_ptr; \
  239. Array<irValue *> args; \
  240. irValue * context_ptr; \
  241. ProcInlining inlining; \
  242. }) \
  243. IR_INSTR_KIND(StartupRuntime, i32) \
  244. IR_INSTR_KIND(DebugDeclare, struct { \
  245. Ast * expr; \
  246. Entity * entity; \
  247. bool is_addr; \
  248. irValue * value; \
  249. }) \
  250. // IR_INSTR_KIND(BoundsCheck, struct { \
  251. // TokenPos pos; \
  252. // irValue *index; \
  253. // irValue *len; \
  254. // }) \
  255. // IR_INSTR_KIND(SliceBoundsCheck, struct { \
  256. // TokenPos pos; \
  257. // irValue *low; \
  258. // irValue *high; \
  259. // irValue *max; \
  260. // bool is_substring; \
  261. // }) \
  262. #define IR_CONV_KINDS \
  263. IR_CONV_KIND(trunc) \
  264. IR_CONV_KIND(zext) \
  265. IR_CONV_KIND(sext) \
  266. IR_CONV_KIND(fptrunc) \
  267. IR_CONV_KIND(fpext) \
  268. IR_CONV_KIND(fptoui) \
  269. IR_CONV_KIND(fptosi) \
  270. IR_CONV_KIND(uitofp) \
  271. IR_CONV_KIND(sitofp) \
  272. IR_CONV_KIND(ptrtoint) \
  273. IR_CONV_KIND(inttoptr) \
  274. IR_CONV_KIND(bitcast) \
  275. IR_CONV_KIND(byteswap)
  276. /*
  277. Odin specifc conversion
  278. byteswap - swap bytes for endian change
  279. */
  280. enum irInstrKind {
  281. irInstr_Invalid,
  282. #define IR_INSTR_KIND(x, ...) GB_JOIN2(irInstr_, x),
  283. IR_INSTR_KINDS
  284. #undef IR_INSTR_KIND
  285. };
  286. String const ir_instr_strings[] = {
  287. {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
  288. #define IR_INSTR_KIND(x, ...) {cast(u8 *)#x, gb_size_of(#x)-1},
  289. IR_INSTR_KINDS
  290. #undef IR_INSTR_KIND
  291. };
  292. enum irConvKind {
  293. irConv_Invalid,
  294. #define IR_CONV_KIND(x) GB_JOIN2(irConv_, x),
  295. IR_CONV_KINDS
  296. #undef IR_CONV_KIND
  297. };
  298. String const ir_conv_strings[] = {
  299. {cast(u8 *)"Invalid", gb_size_of("Invalid")-1},
  300. #define IR_CONV_KIND(x) {cast(u8 *)#x, gb_size_of(#x)-1},
  301. IR_CONV_KINDS
  302. #undef IR_CONV_KIND
  303. };
  304. #define IR_INSTR_KIND(k, ...) typedef __VA_ARGS__ GB_JOIN2(irInstr, k);
  305. IR_INSTR_KINDS
  306. #undef IR_INSTR_KIND
  307. struct irInstr {
  308. irInstrKind kind;
  309. irBlock *block;
  310. Type *type;
  311. union {
  312. #define IR_INSTR_KIND(k, ...) GB_JOIN2(irInstr, k) k;
  313. IR_INSTR_KINDS
  314. #undef IR_INSTR_KIND
  315. };
  316. };
  317. enum irValueKind {
  318. irValue_Invalid,
  319. irValue_Constant,
  320. irValue_ConstantSlice,
  321. irValue_Nil,
  322. irValue_Undef,
  323. irValue_TypeName,
  324. irValue_Global,
  325. irValue_Param,
  326. irValue_SourceCodeLocation,
  327. irValue_Proc,
  328. irValue_Block,
  329. irValue_Instr,
  330. irValue_Count,
  331. };
  332. struct irValueConstant {
  333. Type * type;
  334. ExactValue value;
  335. };
  336. struct irValueConstantSlice {
  337. Type * type;
  338. irValue *backing_array;
  339. i64 count;
  340. };
  341. struct irValueNil {
  342. Type *type;
  343. };
  344. struct irValueUndef {
  345. Type *type;
  346. };
  347. struct irValueTypeName {
  348. Type * type;
  349. String name;
  350. };
  351. struct irValueGlobal {
  352. String name;
  353. Entity * entity;
  354. Type * type;
  355. irValue * value;
  356. Array<irValue *> referrers;
  357. bool is_constant;
  358. bool is_export;
  359. bool is_private;
  360. bool is_internal;
  361. String thread_local_model;
  362. bool is_foreign;
  363. bool is_unnamed_addr;
  364. };
  365. enum irParamPasskind {
  366. irParamPass_Value, // Pass by value
  367. irParamPass_Pointer, // Pass as a pointer rather than by value
  368. irParamPass_Integer, // Pass as an integer of the same size
  369. irParamPass_ConstRef, // Pass as a pointer but the value is immutable
  370. irParamPass_BitCast, // Pass by value and bit cast to the correct type
  371. irParamPass_Tuple, // Pass across multiple parameters (System V AMD64, up to 2)
  372. };
  373. struct irValueParam {
  374. irParamPasskind kind;
  375. irProcedure * parent;
  376. Entity * entity;
  377. Type * type;
  378. Type * original_type;
  379. i32 index;
  380. Array<irValue *> referrers;
  381. };
  382. struct irValueSourceCodeLocation {
  383. irValue *file;
  384. irValue *line;
  385. irValue *column;
  386. irValue *procedure;
  387. u64 hash;
  388. };
  389. struct irValue {
  390. irValueKind kind;
  391. i32 index;
  392. bool index_set;
  393. irDebugInfo * loc;
  394. isize uses;
  395. union {
  396. irValueConstant Constant;
  397. irValueConstantSlice ConstantSlice;
  398. irValueNil Nil;
  399. irValueUndef Undef;
  400. irValueTypeName TypeName;
  401. irValueGlobal Global;
  402. irValueParam Param;
  403. irProcedure Proc;
  404. irBlock Block;
  405. irInstr Instr;
  406. irValueSourceCodeLocation SourceCodeLocation;
  407. };
  408. };
  409. gb_global irValue *v_zero = nullptr;
  410. gb_global irValue *v_one = nullptr;
  411. gb_global irValue *v_zero32 = nullptr;
  412. gb_global irValue *v_one32 = nullptr;
  413. gb_global irValue *v_two32 = nullptr;
  414. gb_global irValue *v_false = nullptr;
  415. gb_global irValue *v_true = nullptr;
  416. gb_global irValue *v_raw_nil = nullptr;
  417. enum irAddrKind {
  418. irAddr_Default,
  419. irAddr_Map,
  420. irAddr_BitField,
  421. irAddr_Context,
  422. irAddr_SoaVariable,
  423. irAddr_RelativePointer,
  424. irAddr_RelativeSlice,
  425. };
  426. struct irAddr {
  427. irAddrKind kind;
  428. irValue * addr;
  429. union {
  430. struct {
  431. irValue *map_key;
  432. Type * map_type;
  433. Type * map_result;
  434. };
  435. struct {
  436. i32 bit_field_value_index;
  437. };
  438. struct {
  439. Selection sel;
  440. } ctx;
  441. struct {
  442. irValue *index;
  443. Ast *index_expr;
  444. } soa;
  445. struct {
  446. bool deref;
  447. } relative;
  448. };
  449. };
  450. Type *ir_type(irValue *value);
  451. irValue *ir_gen_anonymous_proc_lit(irModule *m, String prefix_name, Ast *expr, irProcedure *proc = nullptr);
  452. irAddr ir_addr(irValue *addr) {
  453. irAddr v = {irAddr_Default, addr};
  454. if (addr != nullptr && is_type_relative_pointer(type_deref(ir_type(addr)))) {
  455. GB_ASSERT(is_type_pointer(ir_type(addr)));
  456. v.kind = irAddr_RelativePointer;
  457. } else if (addr != nullptr && is_type_relative_slice(type_deref(ir_type(addr)))) {
  458. GB_ASSERT(is_type_pointer(ir_type(addr)));
  459. v.kind = irAddr_RelativeSlice;
  460. }
  461. return v;
  462. }
  463. irAddr ir_addr_map(irValue *addr, irValue *map_key, Type *map_type, Type *map_result) {
  464. irAddr v = {irAddr_Map, addr};
  465. v.map_key = map_key;
  466. v.map_type = map_type;
  467. v.map_result = map_result;
  468. return v;
  469. }
  470. irAddr ir_addr_context(irValue *addr, Selection sel = empty_selection) {
  471. irAddr v = {irAddr_Context, addr};
  472. v.ctx.sel = sel;
  473. return v;
  474. }
  475. irAddr ir_addr_bit_field(irValue *addr, i32 bit_field_value_index) {
  476. irAddr v = {irAddr_BitField, addr};
  477. v.bit_field_value_index = bit_field_value_index;
  478. return v;
  479. }
  480. irAddr ir_addr_soa_variable(irValue *addr, irValue *index, Ast *index_expr) {
  481. irAddr v = {irAddr_SoaVariable, addr};
  482. v.soa.index = index;
  483. v.soa.index_expr = index_expr;
  484. return v;
  485. }
  486. enum irDebugEncoding {
  487. irDebugBasicEncoding_Invalid = 0,
  488. irDebugBasicEncoding_address = 1,
  489. irDebugBasicEncoding_boolean = 2,
  490. irDebugBasicEncoding_float = 3,
  491. irDebugBasicEncoding_signed = 4,
  492. irDebugBasicEncoding_signed_char = 5,
  493. irDebugBasicEncoding_unsigned = 6,
  494. irDebugBasicEncoding_unsigned_char = 7,
  495. // TODO(lachsinc): Should the following be renamed from basic -> tag to mirror their DW_TAG_*
  496. // counterparts? Perhaps separate out if they truly have different meaning.
  497. irDebugBasicEncoding_member = 13,
  498. irDebugBasicEncoding_pointer_type = 15,
  499. irDebugBasicEncoding_typedef = 22,
  500. irDebugBasicEncoding_array_type = 1,
  501. irDebugBasicEncoding_enumeration_type = 4,
  502. irDebugBasicEncoding_structure_type = 19,
  503. irDebugBasicEncoding_union_type = 23,
  504. };
  505. enum irDebugInfoFlags {
  506. irDebugInfoFlag_Bitfield = (1 << 19),
  507. };
  508. enum irDebugInfoKind {
  509. irDebugInfo_Invalid,
  510. irDebugInfo_CompileUnit,
  511. irDebugInfo_File,
  512. irDebugInfo_Proc,
  513. irDebugInfo_ProcType,
  514. irDebugInfo_Location,
  515. irDebugInfo_LexicalBlock,
  516. irDebugInfo_AllProcs,
  517. irDebugInfo_BasicType, // primitive types
  518. irDebugInfo_DerivedType, // pointer, distinct etc.
  519. irDebugInfo_CompositeType, // array, struct, enum, union etc.
  520. irDebugInfo_Enumerator, // For irDebugInfo_CompositeType if enum
  521. irDebugInfo_GlobalVariableExpression, // used to describe if global is const or not
  522. irDebugInfo_GlobalVariable,
  523. irDebugInfo_LocalVariable,
  524. irDebugInfo_DebugInfoArray, // array of irDebugInfo *'s
  525. irDebugInfo_Count,
  526. };
  527. struct irDebugInfo {
  528. irDebugInfoKind kind;
  529. i32 id;
  530. union {
  531. struct {
  532. AstFile * file;
  533. String producer;
  534. irDebugInfo *enums; // DebugInfoArray
  535. irDebugInfo *globals; // DebugInfoArray
  536. } CompileUnit;
  537. struct {
  538. AstFile *file;
  539. String filename;
  540. String directory;
  541. } File;
  542. struct {
  543. Entity * entity;
  544. String name;
  545. irDebugInfo * file;
  546. TokenPos pos;
  547. irDebugInfo * type;
  548. // TODO(lachsinc): variables / retainedNodes ?
  549. } Proc;
  550. struct {
  551. irDebugInfo * types; // !{return, return, param, param, param.. etc.}
  552. } ProcType;
  553. struct {
  554. TokenPos pos;
  555. irDebugInfo *scope;
  556. } Location;
  557. struct {
  558. TokenPos pos;
  559. irDebugInfo *file;
  560. irDebugInfo *scope;
  561. } LexicalBlock;
  562. struct {
  563. Type * type;
  564. String name;
  565. i32 size;
  566. i32 align;
  567. irDebugEncoding encoding;
  568. } BasicType;
  569. struct {
  570. Type * type;
  571. irDebugEncoding tag;
  572. irDebugInfo * base_type;
  573. String name;
  574. irDebugInfo * scope;
  575. irDebugInfo * file;
  576. TokenPos pos;
  577. i32 size;
  578. i32 align;
  579. i32 offset;
  580. irDebugInfoFlags flags; // Used only for DIFlagBitField.
  581. } DerivedType;
  582. struct {
  583. irDebugEncoding tag;
  584. String name;
  585. irDebugInfo * scope;
  586. irDebugInfo * file;
  587. TokenPos pos;
  588. irDebugInfo * base_type; // optional, used for enumeration_type.
  589. i32 size;
  590. i32 align;
  591. irDebugInfo * elements;
  592. i32 array_count; // for DISubrange
  593. } CompositeType;
  594. struct {
  595. String name;
  596. i64 value;
  597. } Enumerator;
  598. struct {
  599. irDebugInfo *var;
  600. } GlobalVariableExpression;
  601. struct {
  602. String name;
  603. String linkage_name;
  604. irDebugInfo *scope;
  605. irDebugInfo *file;
  606. TokenPos pos;
  607. irDebugInfo *type;
  608. irValue *variable;
  609. } GlobalVariable;
  610. struct {
  611. String name;
  612. irDebugInfo *scope;
  613. irDebugInfo *file;
  614. TokenPos pos;
  615. i32 arg; // Non-zero if proc parameter
  616. irDebugInfo *type;
  617. } LocalVariable;
  618. struct {
  619. Array<irDebugInfo *> elements; // TODO(lachsinc): Leak?
  620. } DebugInfoArray;
  621. };
  622. };
  623. static irDebugInfo IR_DEBUG_INFO_EMPTY = {};
  624. struct irGen {
  625. irModule module;
  626. gbFile output_file;
  627. bool opt_called;
  628. String output_base;
  629. String output_name;
  630. bool print_chkstk;
  631. };
  632. gb_inline bool ir_min_dep_entity(irModule *m, Entity *e) {
  633. return ptr_set_exists(&m->min_dep_set, e);
  634. }
  635. Type *ir_instr_type(irInstr *instr) {
  636. switch (instr->kind) {
  637. case irInstr_Local:
  638. return instr->Local.type;
  639. case irInstr_Load:
  640. return instr->Load.type;
  641. case irInstr_AtomicLoad:
  642. return instr->AtomicLoad.type;
  643. case irInstr_AtomicRmw:
  644. return instr->AtomicRmw.type;
  645. case irInstr_AtomicCxchg:
  646. return instr->AtomicCxchg.type;
  647. case irInstr_StructElementPtr:
  648. return instr->StructElementPtr.result_type;
  649. case irInstr_ArrayElementPtr:
  650. return instr->ArrayElementPtr.result_type;
  651. case irInstr_PtrOffset:
  652. return ir_type(instr->PtrOffset.address);
  653. case irInstr_Phi:
  654. return instr->Phi.type;
  655. case irInstr_StructExtractValue:
  656. return instr->StructExtractValue.result_type;
  657. case irInstr_UnionTagPtr:
  658. return instr->UnionTagPtr.type;
  659. case irInstr_UnionTagValue:
  660. return instr->UnionTagValue.type;
  661. case irInstr_UnaryOp:
  662. return instr->UnaryOp.type;
  663. case irInstr_BinaryOp:
  664. return instr->BinaryOp.type;
  665. case irInstr_Conv:
  666. return instr->Conv.to;
  667. case irInstr_Select:
  668. return ir_type(instr->Select.true_value);
  669. case irInstr_Call: {
  670. Type *pt = base_type(instr->Call.type);
  671. if (pt != nullptr) {
  672. if (pt->kind == Type_Tuple && pt->Tuple.variables.count == 1) {
  673. return pt->Tuple.variables[0]->type;
  674. }
  675. return pt;
  676. }
  677. return nullptr;
  678. }
  679. }
  680. return nullptr;
  681. }
  682. Type *ir_type(irValue *value) {
  683. if (value == nullptr) {
  684. return nullptr;
  685. }
  686. switch (value->kind) {
  687. case irValue_Constant:
  688. return value->Constant.type;
  689. case irValue_ConstantSlice:
  690. return value->ConstantSlice.type;
  691. case irValue_Nil:
  692. return value->Nil.type;
  693. case irValue_Undef:
  694. return value->Undef.type;
  695. case irValue_TypeName:
  696. return value->TypeName.type;
  697. case irValue_Global:
  698. return value->Global.type;
  699. case irValue_Param:
  700. return value->Param.type;
  701. case irValue_SourceCodeLocation:
  702. return t_source_code_location;
  703. case irValue_Proc:
  704. return value->Proc.type;
  705. case irValue_Instr:
  706. return ir_instr_type(&value->Instr);
  707. }
  708. return nullptr;
  709. }
  710. irInstr *ir_get_last_instr(irBlock *block) {
  711. if (block != nullptr) {
  712. isize len = block->instrs.count;
  713. if (len > 0) {
  714. irValue *v = block->instrs[len-1];
  715. GB_ASSERT(v->kind == irValue_Instr);
  716. return &v->Instr;
  717. }
  718. }
  719. return nullptr;
  720. }
  721. bool ir_is_instr_terminating(irInstr *i) {
  722. if (i != nullptr) {
  723. switch (i->kind) {
  724. case irInstr_Return:
  725. case irInstr_Unreachable:
  726. return true;
  727. }
  728. }
  729. return false;
  730. }
  731. void ir_add_edge(irBlock *from, irBlock *to) {
  732. GB_ASSERT(from->instrs.count > 0);
  733. if (!ir_is_instr_terminating(ir_get_last_instr(from))) {
  734. array_add(&from->succs, to);
  735. array_add(&to->preds, from);
  736. }
  737. }
  738. void ir_set_instr_block(irValue *instr, irBlock *block) {
  739. if (instr->kind == irValue_Instr) {
  740. instr->Instr.block = block;
  741. }
  742. }
  743. Array<irValue *> *ir_value_referrers(irValue *v) {
  744. switch (v->kind) {
  745. case irValue_Global:
  746. return &v->Global.referrers;
  747. case irValue_Param:
  748. return &v->Param.referrers;
  749. case irValue_Proc: {
  750. if (v->Proc.parent != nullptr) {
  751. return &v->Proc.referrers;
  752. }
  753. return nullptr;
  754. }
  755. case irValue_Instr: {
  756. irInstr *i = &v->Instr;
  757. switch (i->kind) {
  758. case irInstr_Local:
  759. return &i->Local.referrers;
  760. }
  761. break;
  762. }
  763. }
  764. return nullptr;
  765. }
  766. ////////////////////////////////////////////////////////////////
  767. //
  768. // @Make
  769. //
  770. ////////////////////////////////////////////////////////////////
  771. void ir_module_add_value (irModule *m, Entity *e, irValue *v);
  772. void ir_emit_zero_init (irProcedure *p, irValue *address, Ast *expr);
  773. irValue *ir_emit_comment (irProcedure *p, String text);
  774. irValue *ir_emit_store (irProcedure *p, irValue *address, irValue *value, bool is_volatile=false);
  775. irValue *ir_emit_load (irProcedure *p, irValue *address, i64 custom_align=0);
  776. void ir_emit_jump (irProcedure *proc, irBlock *block);
  777. irValue *ir_emit_conv (irProcedure *proc, irValue *value, Type *t);
  778. irValue *ir_type_info (irProcedure *proc, Type *type);
  779. irValue *ir_typeid (irModule *m, Type *type);
  780. irValue *ir_build_expr (irProcedure *proc, Ast *expr);
  781. void ir_build_stmt (irProcedure *proc, Ast *node);
  782. irValue *ir_build_cond (irProcedure *proc, Ast *cond, irBlock *true_block, irBlock *false_block);
  783. void ir_build_defer_stmt (irProcedure *proc, irDefer d);
  784. irAddr ir_build_addr (irProcedure *proc, Ast *expr);
  785. void ir_build_proc (irValue *value, irProcedure *parent);
  786. void ir_gen_global_type_name(irModule *m, Entity *e, String name);
  787. irValue *ir_get_type_info_ptr (irProcedure *proc, Type *type);
  788. void ir_value_set_debug_location(irProcedure *proc, irValue *v);
  789. void ir_push_debug_location (irModule *m, Ast *node, irDebugInfo *scope, Entity *e=nullptr);
  790. void ir_pop_debug_location (irModule *m);
  791. irDebugInfo *ir_add_debug_info_local(irProcedure *proc, Entity *e, i32 arg_id);
  792. irDebugInfo *ir_add_debug_info_file(irModule *module, AstFile *file);
  793. irDebugInfo *ir_add_debug_info_proc(irProcedure *proc);
  794. void ir_emit_increment(irProcedure *proc, irValue *addr);
  795. irValue *ir_emit_array_ep(irProcedure *proc, irValue *s, irValue *index);
  796. irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index);
  797. irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index);
  798. irValue *ir_emit_bitcast(irProcedure *proc, irValue *data, Type *type);
  799. irValue *ir_emit_byte_swap(irProcedure *proc, irValue *value, Type *t);
  800. irValue *ir_find_or_add_entity_string(irModule *m, String str);
  801. irValue *ir_find_or_add_entity_string_byte_slice(irModule *m, String str);
  802. irValue *ir_slice_elem(irProcedure *proc, irValue *slice);
  803. irValue *ir_slice_len(irProcedure *proc, irValue *slice);
  804. void ir_fill_slice(irProcedure *proc, irValue *slice_ptr, irValue *data, irValue *len);
  805. irValue *ir_alloc_value(irValueKind kind) {
  806. irValue *v = gb_alloc_item(ir_allocator(), irValue);
  807. v->kind = kind;
  808. return v;
  809. }
  810. irValue *ir_alloc_instr(irProcedure *proc, irInstrKind kind) {
  811. irValue *v = ir_alloc_value(irValue_Instr);
  812. v->Instr.kind = kind;
  813. proc->instr_count++;
  814. return v;
  815. }
  816. irDebugInfo *ir_alloc_debug_info(irDebugInfoKind kind) {
  817. irDebugInfo *di = gb_alloc_item(ir_allocator(), irDebugInfo);
  818. di->kind = kind;
  819. return di;
  820. }
  821. irValue *ir_value_type_name(String name, Type *type) {
  822. irValue *v = ir_alloc_value(irValue_TypeName);
  823. v->TypeName.name = name;
  824. v->TypeName.type = type;
  825. return v;
  826. }
  827. irValue *ir_value_global(Entity *e, irValue *value) {
  828. irValue *v = ir_alloc_value(irValue_Global);
  829. v->Global.entity = e;
  830. v->Global.type = alloc_type_pointer(e->type);
  831. v->Global.value = value;
  832. array_init(&v->Global.referrers, ir_allocator()); // TODO(bill): Replace heap allocator here
  833. if (value) value->uses += 1;
  834. return v;
  835. }
  836. irValue *ir_value_param(irProcedure *parent, Entity *e, Type *abi_type, i32 index) {
  837. irValue *v = ir_alloc_value(irValue_Param);
  838. v->Param.kind = irParamPass_Value;
  839. v->Param.parent = parent;
  840. if (e != nullptr) {
  841. v->Param.entity = e;
  842. v->Param.original_type = e->type;
  843. }
  844. v->Param.type = abi_type;
  845. v->Param.index = index;
  846. if (e != nullptr && abi_type != e->type) {
  847. if (is_type_pointer(abi_type)) {
  848. GB_ASSERT(e->kind == Entity_Variable);
  849. Type *av = core_type(type_deref(abi_type));
  850. if (are_types_identical(av, core_type(e->type))) {
  851. v->Param.kind = irParamPass_Pointer;
  852. if (e->flags&EntityFlag_Value) {
  853. v->Param.kind = irParamPass_ConstRef;
  854. }
  855. } else {
  856. v->Param.kind = irParamPass_BitCast;
  857. }
  858. } else if (is_type_integer(abi_type)) {
  859. v->Param.kind = irParamPass_Integer;
  860. } else if (abi_type == t_llvm_bool) {
  861. v->Param.kind = irParamPass_Value;
  862. } else if (is_type_boolean(abi_type)) {
  863. v->Param.kind = irParamPass_Integer;
  864. } else if (is_type_simd_vector(abi_type)) {
  865. v->Param.kind = irParamPass_BitCast;
  866. } else if (is_type_float(abi_type)) {
  867. v->Param.kind = irParamPass_BitCast;
  868. } else if (is_type_tuple(abi_type)) {
  869. v->Param.kind = irParamPass_Tuple;
  870. } else {
  871. GB_PANIC("Invalid abi type pass kind: %s", type_to_string(abi_type));
  872. }
  873. }
  874. array_init(&v->Param.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  875. return v;
  876. }
  877. irValue *ir_value_nil(Type *type) {
  878. irValue *v = ir_alloc_value(irValue_Nil);
  879. v->Nil.type = type;
  880. return v;
  881. }
  882. irValue *ir_value_undef(Type *type) {
  883. irValue *v = ir_alloc_value(irValue_Undef);
  884. v->Undef.type = type;
  885. return v;
  886. }
  887. String ir_get_global_name(irModule *m, irValue *v) {
  888. if (v->kind != irValue_Global) {
  889. return str_lit("");
  890. }
  891. irValueGlobal *g = &v->Global;
  892. Entity *e = g->entity;
  893. String name = e->token.string;
  894. String *found = map_get(&m->entity_names, hash_entity(e));
  895. if (found != nullptr) {
  896. name = *found;
  897. } else {
  898. GB_ASSERT(name.len > 0);
  899. }
  900. return name;
  901. }
  902. void ir_add_entity_name(irModule *m, Entity *e, String name) {
  903. GB_ASSERT(name.len > 0);
  904. if (e != nullptr && e->kind == Entity_TypeName) {
  905. e->TypeName.ir_mangled_name = name;
  906. }
  907. map_set(&m->entity_names, hash_entity(e), name);
  908. }
  909. irValue *ir_instr_local(irProcedure *p, Entity *e, bool zero_initialized) {
  910. irValue *v = ir_alloc_instr(p, irInstr_Local);
  911. irInstr *i = &v->Instr;
  912. i->Local.entity = e;
  913. i->Local.type = alloc_type_pointer(e->type);
  914. i->Local.zero_initialized = zero_initialized;
  915. // i->Local.alignment = type_align_of(p->module->allocator, e->type);
  916. // TODO(bill): determine the correct alignment
  917. i->Local.alignment = gb_max(16, type_align_of(e->type));
  918. array_init(&i->Local.referrers, heap_allocator()); // TODO(bill): Replace heap allocator here
  919. ir_module_add_value(p->module, e, v);
  920. return v;
  921. }
  922. irValue *ir_instr_zero_init(irProcedure *p, irValue *address) {
  923. irValue *v = ir_alloc_instr(p, irInstr_ZeroInit);
  924. irInstr *i = &v->Instr;
  925. i->ZeroInit.address = address;
  926. if (address) address->uses += 1;
  927. return v;
  928. }
  929. irValue *ir_instr_store(irProcedure *p, irValue *address, irValue *value, bool is_volatile) {
  930. irValue *v = ir_alloc_instr(p, irInstr_Store);
  931. irInstr *i = &v->Instr;
  932. i->Store.address = address;
  933. i->Store.value = value;
  934. i->Store.is_volatile = is_volatile;
  935. if (address) address->uses += 1;
  936. if (value) value->uses += 1;
  937. return v;
  938. }
  939. irValue *ir_instr_load(irProcedure *p, irValue *address) {
  940. irValue *v = ir_alloc_instr(p, irInstr_Load);
  941. irInstr *i = &v->Instr;
  942. i->Load.address = address;
  943. i->Load.type = type_deref(ir_type(address));
  944. if (address) address->uses += 1;
  945. return v;
  946. }
  947. irValue *ir_instr_inline_code(irProcedure *p, BuiltinProcId id, Array<irValue *> operands) {
  948. irValue *v = ir_alloc_instr(p, irInstr_InlineCode);
  949. irInstr *i = &v->Instr;
  950. i->InlineCode.id = id;
  951. i->InlineCode.operands = operands;
  952. return v;
  953. }
  954. irValue *ir_instr_atomic_fence(irProcedure *p, BuiltinProcId id) {
  955. irValue *v = ir_alloc_instr(p, irInstr_AtomicFence);
  956. irInstr *i = &v->Instr;
  957. i->AtomicFence.id = id;
  958. return v;
  959. }
  960. irValue *ir_instr_atomic_store(irProcedure *p, irValue *address, irValue *value, BuiltinProcId id) {
  961. irValue *v = ir_alloc_instr(p, irInstr_AtomicStore);
  962. irInstr *i = &v->Instr;
  963. i->AtomicStore.address = address;
  964. i->AtomicStore.value = value;
  965. i->AtomicStore.id = id;
  966. if (address) address->uses += 1;
  967. if (value) value->uses += 1;
  968. return v;
  969. }
  970. irValue *ir_instr_atomic_load(irProcedure *p, irValue *address, BuiltinProcId id) {
  971. irValue *v = ir_alloc_instr(p, irInstr_AtomicLoad);
  972. irInstr *i = &v->Instr;
  973. i->AtomicLoad.address = address;
  974. i->AtomicLoad.type = type_deref(ir_type(address));
  975. i->AtomicLoad.id = id;
  976. if (address) address->uses += 1;
  977. return v;
  978. }
  979. irValue *ir_instr_atomic_rmw(irProcedure *p, irValue *address, irValue *value, BuiltinProcId id) {
  980. irValue *v = ir_alloc_instr(p, irInstr_AtomicRmw);
  981. irInstr *i = &v->Instr;
  982. i->AtomicRmw.type = type_deref(ir_type(address));
  983. i->AtomicRmw.address = address;
  984. i->AtomicRmw.value = value;
  985. i->AtomicRmw.id = id;
  986. if (address) address->uses += 1;
  987. if (value) value->uses += 1;
  988. return v;
  989. }
  990. irValue *ir_instr_atomic_cxchg(irProcedure *p, Type *type, irValue *address, irValue *old_value, irValue *new_value, BuiltinProcId id) {
  991. irValue *v = ir_alloc_instr(p, irInstr_AtomicCxchg);
  992. irInstr *i = &v->Instr;
  993. if (type->kind == Type_Tuple) {
  994. GB_ASSERT(type->Tuple.variables.count == 2);
  995. Type *elem = type->Tuple.variables[0]->type;
  996. // LEAK TODO(bill): LLVM returns {T, i1} whilst Odin does {T, bool}, fix this mapping hack
  997. gbAllocator a = heap_allocator();
  998. Type *llvm_type = alloc_type_tuple();
  999. array_init(&llvm_type->Tuple.variables, a, 0, 2);
  1000. array_add (&llvm_type->Tuple.variables, alloc_entity_field(nullptr, blank_token, elem, false, 0));
  1001. array_add (&llvm_type->Tuple.variables, alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1));
  1002. type = llvm_type;
  1003. }
  1004. i->AtomicCxchg.type = type;
  1005. i->AtomicCxchg.address = address;
  1006. i->AtomicCxchg.old_value = old_value;
  1007. i->AtomicCxchg.new_value = new_value;
  1008. i->AtomicCxchg.id = id;
  1009. if (address) address->uses += 1;
  1010. if (old_value) old_value->uses += 1;
  1011. if (new_value) new_value->uses += 1;
  1012. return v;
  1013. }
  1014. irValue *ir_instr_array_element_ptr(irProcedure *p, irValue *address, irValue *elem_index) {
  1015. irValue *v = ir_alloc_instr(p, irInstr_ArrayElementPtr);
  1016. irInstr *i = &v->Instr;
  1017. Type *t = ir_type(address);
  1018. GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
  1019. t = base_type(type_deref(t));
  1020. GB_ASSERT(is_type_array(t) || is_type_enumerated_array(t));
  1021. Type *result_type = nullptr;
  1022. if (t->kind == Type_Array) {
  1023. result_type = alloc_type_pointer(t->Array.elem);
  1024. } else if (t->kind == Type_EnumeratedArray) {
  1025. result_type = alloc_type_pointer(t->EnumeratedArray.elem);
  1026. }
  1027. i->ArrayElementPtr.address = address;
  1028. i->ArrayElementPtr.elem_index = elem_index;
  1029. i->ArrayElementPtr.result_type = result_type;
  1030. if (address) address->uses += 1;
  1031. if (elem_index) elem_index->uses += 1;
  1032. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  1033. "%s", type_to_string(ir_type(address)));
  1034. return v;
  1035. }
  1036. irValue *ir_instr_struct_element_ptr(irProcedure *p, irValue *address, i32 elem_index, Type *result_type) {
  1037. irValue *v = ir_alloc_instr(p, irInstr_StructElementPtr);
  1038. irInstr *i = &v->Instr;
  1039. i->StructElementPtr.address = address;
  1040. i->StructElementPtr.elem_index = elem_index;
  1041. i->StructElementPtr.result_type = result_type;
  1042. if (address) address->uses += 1;
  1043. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  1044. "%s", type_to_string(ir_type(address)));
  1045. return v;
  1046. }
  1047. irValue *ir_instr_ptr_offset(irProcedure *p, irValue *address, irValue *offset) {
  1048. irValue *v = ir_alloc_instr(p, irInstr_PtrOffset);
  1049. irInstr *i = &v->Instr;
  1050. i->PtrOffset.address = address;
  1051. i->PtrOffset.offset = offset;
  1052. if (address) address->uses += 1;
  1053. if (offset) offset->uses += 1;
  1054. GB_ASSERT_MSG(is_type_pointer(ir_type(address)),
  1055. "%s", type_to_string(ir_type(address)));
  1056. GB_ASSERT_MSG(is_type_integer(ir_type(offset)),
  1057. "%s", type_to_string(ir_type(address)));
  1058. return v;
  1059. }
  1060. irValue *ir_instr_struct_extract_value(irProcedure *p, irValue *address, i32 index, Type *result_type) {
  1061. irValue *v = ir_alloc_instr(p, irInstr_StructExtractValue);
  1062. irInstr *i = &v->Instr;
  1063. i->StructExtractValue.address = address;
  1064. i->StructExtractValue.index = index;
  1065. i->StructExtractValue.result_type = result_type;
  1066. if (address) address->uses += 1;
  1067. return v;
  1068. }
  1069. irValue *ir_instr_union_tag_ptr(irProcedure *p, irValue *address) {
  1070. irValue *v = ir_alloc_instr(p, irInstr_UnionTagPtr);
  1071. irInstr *i = &v->Instr;
  1072. i->UnionTagPtr.address = address;
  1073. if (address) address->uses += 1;
  1074. // i->UnionTagPtr.type = alloc_type_pointer(t_type_info_ptr);
  1075. Type *u = type_deref(ir_type(address));
  1076. if (is_type_union_maybe_pointer(u)) {
  1077. GB_PANIC("union #maybe UnionTagPtr");
  1078. }
  1079. i->UnionTagPtr.type = alloc_type_pointer(union_tag_type(u));
  1080. return v;
  1081. }
  1082. irValue *ir_instr_union_tag_value(irProcedure *p, irValue *address) {
  1083. irValue *v = ir_alloc_instr(p, irInstr_UnionTagValue);
  1084. irInstr *i = &v->Instr;
  1085. i->UnionTagValue.address = address;
  1086. if (address) address->uses += 1;
  1087. Type *u = type_deref(ir_type(address));
  1088. if (is_type_union_maybe_pointer(u)) {
  1089. GB_PANIC("union #maybe UnionTagValue");
  1090. }
  1091. i->UnionTagPtr.type = union_tag_type(u);
  1092. return v;
  1093. }
  1094. irValue *ir_instr_unary_op(irProcedure *p, TokenKind op, irValue *expr, Type *type) {
  1095. irValue *v = ir_alloc_instr(p, irInstr_UnaryOp);
  1096. irInstr *i = &v->Instr;
  1097. i->UnaryOp.op = op;
  1098. i->UnaryOp.expr = expr;
  1099. i->UnaryOp.type = type;
  1100. if (expr) expr->uses += 1;
  1101. return v;
  1102. }
  1103. irValue *ir_instr_binary_op(irProcedure *p, TokenKind op, irValue *left, irValue *right, Type *type) {
  1104. irValue *v = ir_alloc_instr(p, irInstr_BinaryOp);
  1105. irInstr *i = &v->Instr;
  1106. i->BinaryOp.op = op;
  1107. i->BinaryOp.left = left;
  1108. i->BinaryOp.right = right;
  1109. i->BinaryOp.type = type;
  1110. if (left) left->uses += 1;
  1111. if (right) right->uses += 1;
  1112. return v;
  1113. }
  1114. irValue *ir_instr_jump(irProcedure *p, irBlock *block) {
  1115. irValue *v = ir_alloc_instr(p, irInstr_Jump);
  1116. irInstr *i = &v->Instr;
  1117. i->Jump.block = block;
  1118. return v;
  1119. }
  1120. irValue *ir_instr_if(irProcedure *p, irValue *cond, irBlock *true_block, irBlock *false_block) {
  1121. irValue *v = ir_alloc_instr(p, irInstr_If);
  1122. irInstr *i = &v->Instr;
  1123. i->If.cond = ir_emit_conv(p, cond, t_llvm_bool);
  1124. i->If.true_block = true_block;
  1125. i->If.false_block = false_block;
  1126. return v;
  1127. }
  1128. irValue *ir_instr_phi(irProcedure *p, Array<irValue *> edges, Type *type) {
  1129. GB_ASSERT(is_type_typed(type));
  1130. irValue *v = ir_alloc_instr(p, irInstr_Phi);
  1131. irInstr *i = &v->Instr;
  1132. i->Phi.edges = edges;
  1133. i->Phi.type = type;
  1134. for_array(j, edges) {
  1135. if (edges[j]) edges[j]->uses += 1;
  1136. }
  1137. return v;
  1138. }
  1139. irValue *ir_instr_unreachable(irProcedure *p) {
  1140. irValue *v = ir_alloc_instr(p, irInstr_Unreachable);
  1141. return v;
  1142. }
  1143. irValue *ir_instr_return(irProcedure *p, irValue *value) {
  1144. irValue *v = ir_alloc_instr(p, irInstr_Return);
  1145. v->Instr.Return.value = value;
  1146. if (value) value->uses += 1;
  1147. return v;
  1148. }
  1149. irValue *ir_instr_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
  1150. irValue *v = ir_alloc_instr(p, irInstr_Select);
  1151. v->Instr.Select.cond = cond;
  1152. v->Instr.Select.true_value = t;
  1153. v->Instr.Select.false_value = f;
  1154. if (cond) cond->uses += 1;
  1155. if (t) t->uses += 1;
  1156. if (f) f->uses += 1;
  1157. return v;
  1158. }
  1159. irValue *ir_instr_call(irProcedure *p, irValue *value, irValue *return_ptr, Array<irValue *> args, Type *result_type, irValue *context_ptr, ProcInlining inlining) {
  1160. irValue *v = ir_alloc_instr(p, irInstr_Call);
  1161. v->Instr.Call.value = value;
  1162. v->Instr.Call.return_ptr = return_ptr;
  1163. v->Instr.Call.args = args;
  1164. v->Instr.Call.type = result_type;
  1165. v->Instr.Call.context_ptr = context_ptr;
  1166. v->Instr.Call.inlining = inlining;
  1167. if (value) value->uses += 1;
  1168. if (return_ptr) return_ptr->uses += 1;
  1169. for_array(i, args) {
  1170. if (args[i]) args[i]->uses += 1;
  1171. }
  1172. if (context_ptr) context_ptr->uses += 1;
  1173. return v;
  1174. }
  1175. irValue *ir_instr_conv(irProcedure *p, irConvKind kind, irValue *value, Type *from, Type *to) {
  1176. irValue *v = ir_alloc_instr(p, irInstr_Conv);
  1177. v->Instr.Conv.kind = kind;
  1178. v->Instr.Conv.value = value;
  1179. v->Instr.Conv.from = from;
  1180. v->Instr.Conv.to = to;
  1181. if (value) value->uses += 1;
  1182. return v;
  1183. }
  1184. irValue *ir_instr_comment(irProcedure *p, String text) {
  1185. irValue *v = ir_alloc_instr(p, irInstr_Comment);
  1186. v->Instr.Comment.text = text;
  1187. return v;
  1188. }
  1189. irValue *ir_instr_debug_declare(irProcedure *p, Ast *expr, Entity *entity, bool is_addr, irValue *value) {
  1190. irValue *v = ir_alloc_instr(p, irInstr_DebugDeclare);
  1191. v->Instr.DebugDeclare.expr = expr;
  1192. v->Instr.DebugDeclare.entity = entity;
  1193. v->Instr.DebugDeclare.is_addr = is_addr;
  1194. v->Instr.DebugDeclare.value = value;
  1195. if (value) value->uses += 1;
  1196. return v;
  1197. }
  1198. irValue *ir_value_constant(Type *type, ExactValue value) {
  1199. irValue *v = ir_alloc_value(irValue_Constant);
  1200. v->Constant.type = type;
  1201. v->Constant.value = value;
  1202. return v;
  1203. }
  1204. irValue *ir_value_constant_slice(Type *type, irValue *backing_array, i64 count) {
  1205. irValue *v = ir_alloc_value(irValue_ConstantSlice);
  1206. v->ConstantSlice.type = type;
  1207. v->ConstantSlice.backing_array = backing_array;
  1208. v->ConstantSlice.count = count;
  1209. if (backing_array) backing_array->uses += 1;
  1210. return v;
  1211. }
  1212. irValue *ir_emit(irProcedure *proc, irValue *instr) {
  1213. GB_ASSERT(instr->kind == irValue_Instr);
  1214. irModule *m = proc->module;
  1215. irBlock *b = proc->curr_block;
  1216. instr->Instr.block = b;
  1217. if (b != nullptr) {
  1218. irInstr *i = ir_get_last_instr(b);
  1219. if (!ir_is_instr_terminating(i)) {
  1220. array_add(&b->instrs, instr);
  1221. }
  1222. } else if (instr->Instr.kind != irInstr_Unreachable) {
  1223. GB_PANIC("ir_emit: Instruction missing parent block");
  1224. }
  1225. if (m->generate_debug_info) {
  1226. ir_value_set_debug_location(proc, instr);
  1227. }
  1228. return instr;
  1229. }
  1230. irValue *ir_de_emit(irProcedure *proc, irValue *instr) {
  1231. GB_ASSERT(instr->kind == irValue_Instr);
  1232. irModule *m = proc->module;
  1233. irBlock *b = proc->curr_block;
  1234. GB_ASSERT(b != nullptr);
  1235. irInstr *i = ir_get_last_instr(b);
  1236. GB_ASSERT(i == &instr->Instr);
  1237. array_pop(&b->instrs);
  1238. return instr;
  1239. }
  1240. irValue *ir_const_int(i64 i) {
  1241. return ir_value_constant(t_int, exact_value_i64(i));
  1242. }
  1243. irValue *ir_const_uintptr(u64 i) {
  1244. return ir_value_constant(t_uintptr, exact_value_i64(i));
  1245. }
  1246. irValue *ir_const_u8(u32 i) {
  1247. return ir_value_constant(t_u8, exact_value_i64(i));
  1248. }
  1249. irValue *ir_const_i32(i32 i) {
  1250. return ir_value_constant(t_i32, exact_value_i64(i));
  1251. }
  1252. irValue *ir_const_u32(u32 i) {
  1253. return ir_value_constant(t_u32, exact_value_i64(i));
  1254. }
  1255. irValue *ir_const_i64(i64 i) {
  1256. return ir_value_constant(t_i64, exact_value_i64(i));
  1257. }
  1258. irValue *ir_const_u64(u64 i) {
  1259. return ir_value_constant(t_u64, exact_value_i64(i));
  1260. }
  1261. irValue *ir_const_f32(f32 f) {
  1262. return ir_value_constant(t_f32, exact_value_float(f));
  1263. }
  1264. irValue *ir_const_f64(f64 f) {
  1265. return ir_value_constant(t_f64, exact_value_float(f));
  1266. }
  1267. irValue *ir_const_bool(bool b) {
  1268. return ir_value_constant(t_bool, exact_value_bool(b != 0));
  1269. }
  1270. irValue *ir_const_string(irModule *m, String s) {
  1271. return ir_find_or_add_entity_string(m, s);
  1272. // return ir_value_constant(t_string, exact_value_string(s));
  1273. }
  1274. irValue *ir_value_procedure(irModule *m, Entity *entity, Type *type, Ast *type_expr, Ast *body, String name) {
  1275. irValue *v = ir_alloc_value(irValue_Proc);
  1276. v->Proc.module = m;
  1277. v->Proc.entity = entity;
  1278. v->Proc.type = type;
  1279. v->Proc.type_expr = type_expr;
  1280. v->Proc.body = body;
  1281. v->Proc.name = name;
  1282. array_init(&v->Proc.referrers, heap_allocator());
  1283. Type *t = base_type(type);
  1284. GB_ASSERT(is_type_proc(t));
  1285. array_init(&v->Proc.params, heap_allocator(), 0, t->Proc.param_count);
  1286. return v;
  1287. }
  1288. irValue *ir_generate_array(irModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  1289. gbAllocator a = ir_allocator();
  1290. Token token = {Token_Ident};
  1291. isize name_len = prefix.len + 1 + 20;
  1292. auto suffix_id = cast(unsigned long long)id;
  1293. char *text = gb_alloc_array(a, char, name_len+1);
  1294. gb_snprintf(text, name_len,
  1295. "%.*s-%llu", LIT(prefix), suffix_id);
  1296. text[name_len] = 0;
  1297. String s = make_string_c(text);
  1298. Entity *e = alloc_entity_variable(nullptr, make_token_ident(s), alloc_type_array(elem_type, count));
  1299. irValue *value = ir_value_global(e, nullptr);
  1300. value->Global.is_private = true;
  1301. ir_module_add_value(m, e, value);
  1302. string_map_set(&m->members, s, value);
  1303. return value;
  1304. }
  1305. irBlock *ir_new_block(irProcedure *proc, Ast *node, char const *label) {
  1306. Scope *scope = nullptr;
  1307. if (node != nullptr) {
  1308. scope = scope_of_node(node);
  1309. GB_ASSERT_MSG(scope != nullptr, "Block scope not found for %.*s", LIT(ast_strings[node->kind]));
  1310. }
  1311. irValue *v = ir_alloc_value(irValue_Block);
  1312. v->Block.label = make_string_c(label);
  1313. v->Block.node = node;
  1314. v->Block.scope = scope;
  1315. v->Block.proc = proc;
  1316. // TODO(bill): Is this correct or even needed?
  1317. v->Block.scope_index = proc->scope_index;
  1318. array_init(&v->Block.instrs, heap_allocator());
  1319. array_init(&v->Block.locals, heap_allocator());
  1320. array_init(&v->Block.preds, heap_allocator());
  1321. array_init(&v->Block.succs, heap_allocator());
  1322. irBlock *block = &v->Block;
  1323. return block;
  1324. }
  1325. void ir_add_block_to_proc(irProcedure *proc, irBlock *b) {
  1326. for_array(i, proc->blocks) {
  1327. if (proc->blocks[i] == b) {
  1328. return;
  1329. }
  1330. }
  1331. array_add(&proc->blocks, b);
  1332. b->index = proc->block_count++;
  1333. }
  1334. void ir_start_block(irProcedure *proc, irBlock *block) {
  1335. proc->curr_block = block;
  1336. if (block != nullptr) {
  1337. ir_add_block_to_proc(proc, block);
  1338. }
  1339. }
  1340. irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t);
  1341. irValue *ir_address_from_load_or_generate_local(irProcedure *proc, irValue *val);
  1342. irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index);
  1343. irDefer ir_add_defer_node(irProcedure *proc, isize scope_index, Ast *stmt) {
  1344. irDefer d = {irDefer_Node};
  1345. d.scope_index = scope_index;
  1346. d.context_stack_count = proc->context_stack.count;
  1347. d.block = proc->curr_block;
  1348. d.stmt = stmt;
  1349. array_add(&proc->defer_stmts, d);
  1350. return d;
  1351. }
  1352. irDefer ir_add_defer_instr(irProcedure *proc, isize scope_index, irValue *instr) {
  1353. irDefer d = {irDefer_Instr};
  1354. d.scope_index = proc->scope_index;
  1355. d.block = proc->curr_block;
  1356. d.instr = instr; // NOTE(bill): It will make a copy everytime it is called
  1357. array_add(&proc->defer_stmts, d);
  1358. return d;
  1359. }
  1360. irDefer ir_add_defer_proc(irProcedure *proc, isize scope_index, irValue *deferred, Array<irValue *> const &result_as_args) {
  1361. irDefer d = {irDefer_Proc};
  1362. d.scope_index = proc->scope_index;
  1363. d.block = proc->curr_block;
  1364. d.proc.deferred = deferred;
  1365. d.proc.result_as_args = result_as_args;
  1366. array_add(&proc->defer_stmts, d);
  1367. return d;
  1368. }
  1369. irValue *ir_check_compound_lit_constant(irModule *m, Ast *expr) {
  1370. expr = unparen_expr(expr);
  1371. if (expr == nullptr) {
  1372. return nullptr;
  1373. }
  1374. if (expr->kind == Ast_CompoundLit) {
  1375. ast_node(cl, CompoundLit, expr);
  1376. for_array(i, cl->elems) {
  1377. Ast *elem = cl->elems[i];
  1378. if (elem->kind == Ast_FieldValue) {
  1379. ast_node(fv, FieldValue, elem);
  1380. ir_check_compound_lit_constant(m, fv->value);
  1381. } else {
  1382. ir_check_compound_lit_constant(m, elem);
  1383. }
  1384. }
  1385. }
  1386. if (expr->kind == Ast_ProcLit) {
  1387. return ir_gen_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  1388. }
  1389. return nullptr;
  1390. }
  1391. irValue *ir_add_module_constant(irModule *m, Type *type, ExactValue value) {
  1392. gbAllocator a = ir_allocator();
  1393. if (is_type_slice(type)) {
  1394. if (value.kind == ExactValue_String) {
  1395. GB_ASSERT(is_type_u8_slice(type));
  1396. return ir_find_or_add_entity_string_byte_slice(m, value.value_string);
  1397. } else {
  1398. ast_node(cl, CompoundLit, value.value_compound);
  1399. isize count = cl->elems.count;
  1400. if (count == 0) {
  1401. return ir_value_nil(type);
  1402. }
  1403. count = gb_max(cl->max_count, count);
  1404. Type *elem = base_type(type)->Slice.elem;
  1405. Type *t = alloc_type_array(elem, count);
  1406. irValue *backing_array = ir_add_module_constant(m, t, value);
  1407. isize max_len = 7+8+1;
  1408. u8 *str = cast(u8 *)gb_alloc_array(a, u8, max_len);
  1409. isize len = gb_snprintf(cast(char *)str, max_len, "csba$%x", m->global_array_index);
  1410. m->global_array_index++;
  1411. String name = make_string(str, len-1);
  1412. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  1413. irValue *g = ir_value_global(e, backing_array);
  1414. ir_module_add_value(m, e, g);
  1415. string_map_set(&m->members, name, g);
  1416. return ir_value_constant_slice(type, g, count);
  1417. }
  1418. }
  1419. if (value.kind == ExactValue_Compound) {
  1420. // NOTE(bill): Removed for numerous reasons
  1421. irValue *lit = ir_check_compound_lit_constant(m, value.value_compound);
  1422. if (lit != nullptr) {
  1423. return lit;
  1424. }
  1425. }
  1426. return ir_value_constant(type, value);
  1427. }
  1428. irValue *ir_add_global_string_array(irModule *m, String string) {
  1429. irValue *global_constant_value = nullptr;
  1430. {
  1431. irValue **found = string_map_get(&m->const_string_byte_slices, string);
  1432. if (found != nullptr) {
  1433. global_constant_value = *found;
  1434. irValue **global_found = map_get(&m->constant_value_to_global, hash_pointer(global_constant_value));
  1435. if (global_found != nullptr) {
  1436. return *global_found;
  1437. }
  1438. }
  1439. }
  1440. if (global_constant_value == nullptr) {
  1441. global_constant_value = ir_find_or_add_entity_string_byte_slice(m, string);
  1442. }
  1443. Type *type = alloc_type_array(t_u8, string.len+1);
  1444. isize max_len = 6+8+1;
  1445. u8 *str = cast(u8 *)gb_alloc_array(ir_allocator(), u8, max_len);
  1446. isize len = gb_snprintf(cast(char *)str, max_len, "str$%x", m->global_string_index);
  1447. m->global_string_index++;
  1448. String name = make_string(str, len-1);
  1449. Token token = {Token_String};
  1450. token.string = name;
  1451. Entity *entity = alloc_entity_constant(nullptr, token, type, exact_value_string(string));
  1452. irValue *g = ir_value_global(entity, global_constant_value);
  1453. g->Global.is_private = true;
  1454. g->Global.is_unnamed_addr = true;
  1455. g->Global.is_constant = true;
  1456. map_set(&m->constant_value_to_global, hash_pointer(global_constant_value), g);
  1457. ir_module_add_value(m, entity, g);
  1458. string_map_set(&m->members, name, g);
  1459. return g;
  1460. }
  1461. void ir_add_foreign_library_path(irModule *m, Entity *e) {
  1462. if (e == nullptr) {
  1463. return;
  1464. }
  1465. GB_ASSERT(e->kind == Entity_LibraryName);
  1466. GB_ASSERT(e->flags & EntityFlag_Used);
  1467. for_array(i, e->LibraryName.paths) {
  1468. String library_path = e->LibraryName.paths[i];
  1469. if (library_path.len == 0) {
  1470. continue;
  1471. }
  1472. bool ok = true;
  1473. for_array(path_index, m->foreign_library_paths) {
  1474. String path = m->foreign_library_paths[path_index];
  1475. #if defined(GB_SYSTEM_WINDOWS)
  1476. if (str_eq_ignore_case(path, library_path)) {
  1477. #else
  1478. if (str_eq(path, library_path)) {
  1479. #endif
  1480. ok = false;
  1481. break;
  1482. }
  1483. }
  1484. if (ok) {
  1485. array_add(&m->foreign_library_paths, library_path);
  1486. }
  1487. }
  1488. }
  1489. void ir_push_context_onto_stack(irProcedure *proc, irValue *ctx) {
  1490. irContextData cd = {ctx, proc->scope_index};
  1491. array_add(&proc->context_stack, cd);
  1492. }
  1493. irValue *ir_add_local(irProcedure *proc, Entity *e, Ast *expr, bool zero_initialized, i32 param_index = 0) {
  1494. irBlock *b = proc->decl_block; // all variables must be in the first block
  1495. irValue *instr = ir_instr_local(proc, e, true);
  1496. instr->Instr.block = b;
  1497. array_add(&b->instrs, instr);
  1498. array_add(&b->locals, instr);
  1499. proc->local_count++;
  1500. if (zero_initialized) {
  1501. ir_emit_zero_init(proc, instr, expr);
  1502. }
  1503. set_procedure_abi_types(heap_allocator(), e->type);
  1504. // if (proc->module->generate_debug_info && expr != nullptr && proc->entity != nullptr) {
  1505. // if (proc->module->generate_debug_info && proc->entity != nullptr) {
  1506. if (proc->module->generate_debug_info) {
  1507. // GB_ASSERT_NOT_NULL(proc->debug_scope);
  1508. if (expr != nullptr) {
  1509. ir_emit(proc, ir_instr_debug_declare(proc, expr, e, true, instr));
  1510. }
  1511. if (e->scope != nullptr && proc->debug_scope != nullptr) {
  1512. irDebugInfo *di_local = ir_add_debug_info_local(proc, e, param_index);
  1513. }
  1514. }
  1515. return instr;
  1516. }
  1517. irValue *ir_add_local_for_identifier(irProcedure *proc, Ast *ident, bool zero_initialized) {
  1518. Entity *e = entity_of_node(ident);
  1519. if (e != nullptr) {
  1520. String name = e->token.string;
  1521. ir_emit_comment(proc, name);
  1522. if (e->kind == Entity_Variable &&
  1523. e->Variable.is_foreign) {
  1524. if (e->Variable.link_name.len != 0) {
  1525. name = e->Variable.link_name;
  1526. }
  1527. StringHashKey key = string_hash_string(name);
  1528. irValue **prev_value = string_map_get(&proc->module->members, key);
  1529. if (prev_value == nullptr) {
  1530. ir_add_foreign_library_path(proc->module, e->Variable.foreign_library);
  1531. // NOTE(bill): Don't do mutliple declarations in the IR
  1532. irValue *g = ir_value_global(e, nullptr);
  1533. g->Global.name = name;
  1534. g->Global.is_foreign = true;
  1535. ir_module_add_value(proc->module, e, g);
  1536. string_map_set(&proc->module->members, key, g);
  1537. return g;
  1538. } else {
  1539. return *prev_value;
  1540. }
  1541. }
  1542. return ir_add_local(proc, e, ident, zero_initialized);
  1543. }
  1544. return nullptr;
  1545. }
  1546. irValue *ir_add_local_generated(irProcedure *proc, Type *type, bool zero_initialized) {
  1547. GB_ASSERT(type != nullptr);
  1548. type = default_type(type);
  1549. Scope *scope = nullptr;
  1550. if (proc->curr_block) {
  1551. scope = proc->curr_block->scope;
  1552. }
  1553. Entity *e = alloc_entity_variable(scope, empty_token, type);
  1554. return ir_add_local(proc, e, nullptr, zero_initialized);
  1555. }
  1556. irValue *ir_add_global_generated(irModule *m, Type *type, irValue *value) {
  1557. GB_ASSERT(type != nullptr);
  1558. type = default_type(type);
  1559. isize max_len = 7+8+1;
  1560. u8 *str = cast(u8 *)gb_alloc_array(ir_allocator(), u8, max_len);
  1561. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  1562. m->global_generated_index++;
  1563. String name = make_string(str, len-1);
  1564. Scope *scope = nullptr;
  1565. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  1566. irValue *g = ir_value_global(e, value);
  1567. ir_module_add_value(m, e, g);
  1568. string_map_set(&m->members, name, g);
  1569. return g;
  1570. }
  1571. irValue *ir_add_param(irProcedure *proc, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1572. irValue *v = ir_value_param(proc, e, abi_type, index);
  1573. array_add(&proc->params, v);
  1574. irValueParam *p = &v->Param;
  1575. irValue *res = nullptr;
  1576. ir_push_debug_location(proc->module, e ? e->identifier : nullptr, proc->debug_scope, e);
  1577. defer (ir_pop_debug_location(proc->module));
  1578. switch (p->kind) {
  1579. case irParamPass_Value: {
  1580. irValue *l = ir_add_local(proc, e, expr, false, index);
  1581. irValue *x = v;
  1582. if (abi_type == t_llvm_bool) {
  1583. x = ir_emit_conv(proc, x, t_bool);
  1584. }
  1585. ir_emit_store(proc, l, x);
  1586. return x;
  1587. }
  1588. case irParamPass_Pointer:
  1589. ir_module_add_value(proc->module, e, v);
  1590. return ir_emit_load(proc, v);
  1591. case irParamPass_Integer: {
  1592. irValue *l = ir_add_local(proc, e, expr, false, index);
  1593. irValue *iptr = ir_emit_conv(proc, l, alloc_type_pointer(p->type));
  1594. ir_emit_store(proc, iptr, v);
  1595. return ir_emit_load(proc, l);
  1596. }
  1597. case irParamPass_ConstRef:
  1598. ir_module_add_value(proc->module, e, v);
  1599. return ir_emit_load(proc, v);
  1600. case irParamPass_BitCast: {
  1601. irValue *l = ir_add_local(proc, e, expr, false, index);
  1602. irValue *x = ir_emit_transmute(proc, v, e->type);
  1603. ir_emit_store(proc, l, x);
  1604. return x;
  1605. }
  1606. case irParamPass_Tuple: {
  1607. irValue *l = ir_add_local(proc, e, expr, true, index);
  1608. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  1609. irValue *ptr = ir_emit_transmute(proc, l, alloc_type_pointer(st));
  1610. if (abi_type->Tuple.variables.count > 0) {
  1611. array_pop(&proc->params);
  1612. }
  1613. for_array(i, abi_type->Tuple.variables) {
  1614. Type *t = abi_type->Tuple.variables[i]->type;
  1615. irValue *elem = ir_value_param(proc, nullptr, t, index+cast(i32)i);
  1616. array_add(&proc->params, elem);
  1617. irValue *dst = ir_emit_struct_ep(proc, ptr, cast(i32)i);
  1618. ir_emit_store(proc, dst, elem);
  1619. }
  1620. return ir_emit_load(proc, l);
  1621. }
  1622. }
  1623. GB_PANIC("Unreachable");
  1624. return nullptr;
  1625. }
  1626. ////////////////////////////////////////////////////////////////
  1627. //
  1628. // @Debug
  1629. //
  1630. ////////////////////////////////////////////////////////////////
  1631. irDebugInfo *ir_add_debug_info_type(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file);
  1632. irDebugInfo *ir_add_debug_info_array(irModule *module, isize count, isize capacity) {
  1633. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  1634. array_init(&di->DebugInfoArray.elements, ir_allocator(), count, capacity);
  1635. map_set(&module->debug_info, hash_pointer(di), di);
  1636. return di;
  1637. }
  1638. irDebugInfo *ir_add_debug_info_file(irModule *module, AstFile *file) {
  1639. // if (!proc->module->generate_debug_info) {
  1640. // return nullptr;
  1641. // }
  1642. irDebugInfo **existing = map_get(&module->debug_info, hash_ast_file(file));
  1643. if (existing != nullptr) {
  1644. GB_ASSERT((*existing)->kind == irDebugInfo_File);
  1645. return *existing;
  1646. }
  1647. GB_ASSERT(file != nullptr);
  1648. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_File);
  1649. di->File.file = file;
  1650. String filename = file->tokenizer.fullpath;
  1651. String directory = filename;
  1652. isize slash_index = 0;
  1653. for (isize i = filename.len-1; i >= 0; i--) {
  1654. if (filename[i] == '\\' ||
  1655. filename[i] == '/') {
  1656. break;
  1657. }
  1658. slash_index = i;
  1659. }
  1660. directory.len = slash_index-1;
  1661. filename.text = filename.text + slash_index;
  1662. filename.len -= slash_index;
  1663. di->File.filename = filename;
  1664. di->File.directory = directory;
  1665. map_set(&module->debug_info, hash_ast_file(file), di);
  1666. return di;
  1667. }
  1668. irDebugEncoding ir_debug_encoding_for_basic(BasicKind kind) {
  1669. switch (kind) {
  1670. case Basic_llvm_bool:
  1671. case Basic_bool:
  1672. case Basic_b8:
  1673. case Basic_b16:
  1674. case Basic_b32:
  1675. case Basic_b64:
  1676. return irDebugBasicEncoding_boolean;
  1677. case Basic_i8:
  1678. return irDebugBasicEncoding_signed_char;
  1679. case Basic_u8:
  1680. return irDebugBasicEncoding_unsigned_char;
  1681. case Basic_i16:
  1682. case Basic_i32:
  1683. case Basic_i64:
  1684. case Basic_i128:
  1685. case Basic_i16le:
  1686. case Basic_i32le:
  1687. case Basic_i64le:
  1688. case Basic_i128le:
  1689. case Basic_i16be:
  1690. case Basic_i32be:
  1691. case Basic_i64be:
  1692. case Basic_i128be:
  1693. case Basic_int:
  1694. case Basic_rune:
  1695. case Basic_typeid:
  1696. return irDebugBasicEncoding_signed;
  1697. case Basic_u16:
  1698. case Basic_u32:
  1699. case Basic_u64:
  1700. case Basic_u128:
  1701. case Basic_u16le:
  1702. case Basic_u32le:
  1703. case Basic_u64le:
  1704. case Basic_u128le:
  1705. case Basic_u16be:
  1706. case Basic_u32be:
  1707. case Basic_u64be:
  1708. case Basic_u128be:
  1709. case Basic_uint:
  1710. case Basic_uintptr:
  1711. return irDebugBasicEncoding_unsigned;
  1712. // case Basic_f16:
  1713. case Basic_f32:
  1714. case Basic_f64:
  1715. case Basic_f32le:
  1716. case Basic_f64le:
  1717. case Basic_f32be:
  1718. case Basic_f64be:
  1719. return irDebugBasicEncoding_float;
  1720. // case Basic_complex32:
  1721. case Basic_complex64:
  1722. case Basic_complex128:
  1723. case Basic_cstring:
  1724. case Basic_string:
  1725. case Basic_any:
  1726. case Basic_rawptr:
  1727. case Basic_quaternion128:
  1728. case Basic_quaternion256:
  1729. break; // not a "DIBasicType"
  1730. }
  1731. GB_PANIC("Unreachable %d", kind);
  1732. return irDebugBasicEncoding_Invalid;
  1733. }
  1734. i32 ir_debug_info_bits(i64 size) {
  1735. return 8*cast(i32)size;
  1736. }
  1737. i32 ir_debug_size_bits(Type *type) {
  1738. return ir_debug_info_bits(type_size_of(type));
  1739. }
  1740. i32 ir_debug_align_bits(Type *type) {
  1741. return ir_debug_info_bits(type_align_of(type));
  1742. }
  1743. irDebugInfo *ir_add_debug_info_field_internal(irModule *module, String name, Type *type, i32 offset_bits, Entity *e, irDebugInfo *scope) {
  1744. // NOTE(lachsinc): Caller is expected to insert the returned value into map themselves.
  1745. // "scope", if set, should be inserted into map prior to calling to ensure no cyclical dependency issues.
  1746. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  1747. // GB_ASSERT_MSG(name.len > 0, "%s", type_to_string(type));
  1748. di->DerivedType.name = name;
  1749. di->DerivedType.tag = irDebugBasicEncoding_member;
  1750. di->DerivedType.size = ir_debug_size_bits(type);
  1751. di->DerivedType.offset = offset_bits;
  1752. di->DerivedType.scope = scope;
  1753. // NOTE(lachsinc): It is "safe" to overwrite this base_type after a call to this function,
  1754. // if you need to set a specific type for this field.
  1755. di->DerivedType.base_type = ir_add_debug_info_type(module, type, e, scope, nullptr);
  1756. GB_ASSERT_NOT_NULL(di->DerivedType.base_type);
  1757. return di;
  1758. }
  1759. irDebugInfo *ir_add_debug_info_field(irModule *module, irDebugInfo *scope, Entity *e, Type *scope_type, i32 index, Type *type, irDebugInfo *file) {
  1760. // NOTE(lachsinc): This lookup will only work for struct fields!!
  1761. if (e) {
  1762. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  1763. if (existing != nullptr) {
  1764. return *existing;
  1765. }
  1766. }
  1767. irDebugInfo *di = ir_add_debug_info_field_internal(module, make_string(nullptr, 0), type, 0, e, scope);
  1768. void *ptr_to_hash = nullptr;
  1769. if (scope_type) {
  1770. Type *scope_base = base_type(scope_type);
  1771. if (is_type_struct(scope_type) || is_type_tuple(scope_type)) {
  1772. if (is_type_struct(scope_type) && scope_base->Struct.are_offsets_set) {
  1773. di->DerivedType.offset = ir_debug_info_bits(scope_base->Struct.offsets[index]);
  1774. } else if (is_type_tuple(scope_type) && scope_base->Tuple.are_offsets_set) {
  1775. di->DerivedType.offset = ir_debug_info_bits(scope_base->Tuple.offsets[index]);
  1776. } else {
  1777. di->DerivedType.offset = ir_debug_info_bits(type_offset_of(scope_base, index));
  1778. }
  1779. if (e) {
  1780. ptr_to_hash = e;
  1781. di->DerivedType.name = e->token.string;
  1782. if (e->token.string.len == 0) {
  1783. // If no name available for field, use its field index as its name.
  1784. isize max_len = 8;
  1785. u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len);
  1786. isize len = gb_snprintf(cast(char *)str, 8, "%d", index);
  1787. di->DerivedType.name = make_string(str, len-1);
  1788. }
  1789. di->DerivedType.pos = e->token.pos;
  1790. } else {
  1791. GB_PANIC("Unreachable"); // struct field Entity's should be provided.
  1792. }
  1793. } else if (is_type_union(scope_base)) {
  1794. // TODO(lachsinc): Handle this in a more generic manner/pass in??...
  1795. // Token token = base_type(scope_base)->Union.node->UnionType.token;
  1796. // di->DerivedType.name = token.string;
  1797. // di->DerivedType.pos = token.pos;
  1798. if (is_type_named(type)) {
  1799. di->DerivedType.name = type->kind == Type_Named ? type->Named.name : type->Basic.name;
  1800. }
  1801. ptr_to_hash = di;
  1802. }
  1803. }
  1804. di->DerivedType.file = file;
  1805. GB_ASSERT_NOT_NULL(ptr_to_hash);
  1806. map_set(&module->debug_info, hash_pointer(ptr_to_hash), di);
  1807. return di;
  1808. }
  1809. irDebugInfo *ir_add_debug_info_enumerator(irModule *module, Entity *e) {
  1810. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  1811. if (existing != nullptr) {
  1812. return *existing;
  1813. }
  1814. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Enumerator);
  1815. di->Enumerator.name = e->token.string;
  1816. GB_ASSERT(e->kind == Entity_Constant);
  1817. GB_ASSERT(e->Constant.value.kind == ExactValue_Integer);
  1818. di->Enumerator.value = big_int_to_i64(&e->Constant.value.value_integer);
  1819. map_set(&module->debug_info, hash_entity(e), di);
  1820. return di;
  1821. }
  1822. irDebugInfo *ir_add_debug_info_type_dynamic_array(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file) {
  1823. GB_ASSERT(type->kind == Type_DynamicArray);
  1824. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1825. di->CompositeType.name = str_lit("dynamic_array"); // TODO(lachsinc): [dynamic] .. type->DynamicArray.elem name
  1826. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1827. di->CompositeType.size = ir_debug_size_bits(t_rawptr) +
  1828. ir_debug_size_bits(t_int) +
  1829. ir_debug_size_bits(t_int) +
  1830. ir_debug_size_bits(t_allocator);
  1831. di->CompositeType.align = ir_debug_align_bits(t_rawptr);
  1832. map_set(&module->debug_info, hash_type(type), di);
  1833. // Data pointer type
  1834. // TODO(lachsinc): Perhaps lookup/alloc-a-fake Type_Pointer type and go via ir_add_debug_info_type() with it.
  1835. irDebugInfo *data_ptr_di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  1836. data_ptr_di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  1837. data_ptr_di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  1838. map_set(&module->debug_info, hash_pointer(data_ptr_di), data_ptr_di);
  1839. data_ptr_di->DerivedType.base_type = ir_add_debug_info_type(module, type->DynamicArray.elem, e, scope, file);
  1840. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  1841. 0,
  1842. nullptr,
  1843. di);
  1844. data_di->DerivedType.base_type = data_ptr_di;
  1845. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  1846. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_int,
  1847. data_di->DerivedType.size,
  1848. nullptr,
  1849. di);
  1850. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  1851. irDebugInfo *cap_di = ir_add_debug_info_field_internal(module, str_lit("cap"), t_int,
  1852. data_di->DerivedType.size +
  1853. len_di->DerivedType.size,
  1854. nullptr,
  1855. di);
  1856. map_set(&module->debug_info, hash_pointer(cap_di), cap_di);
  1857. irDebugInfo *alloc_di = ir_add_debug_info_field_internal(module, str_lit("allocator"), t_allocator,
  1858. data_di->DerivedType.size +
  1859. len_di->DerivedType.size +
  1860. cap_di->DerivedType.size,
  1861. nullptr,
  1862. di);
  1863. map_set(&module->debug_info, hash_pointer(alloc_di), alloc_di);
  1864. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 4);
  1865. array_add(&elements_di->DebugInfoArray.elements, data_di);
  1866. array_add(&elements_di->DebugInfoArray.elements, len_di);
  1867. array_add(&elements_di->DebugInfoArray.elements, cap_di);
  1868. array_add(&elements_di->DebugInfoArray.elements, alloc_di);
  1869. di->CompositeType.elements = elements_di;
  1870. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1871. return di;
  1872. }
  1873. irDebugInfo *ir_add_debug_info_type_bit_field(irModule *module, Type *type, Entity *e, irDebugInfo *scope) {
  1874. GB_ASSERT(type->kind == Type_BitField || (type->kind == Type_Named && type->Named.base->kind == Type_BitField));
  1875. Type *bf_type = base_type(type);
  1876. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1877. di->CompositeType.name = is_type_named(type) ? type->Named.name : str_lit("bit_field");
  1878. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1879. di->CompositeType.size = ir_debug_size_bits(bf_type);
  1880. map_set(&module->debug_info, hash_type(type), di);
  1881. GB_ASSERT(bf_type->BitField.fields.count == bf_type->BitField.offsets.count &&
  1882. bf_type->BitField.fields.count == bf_type->BitField.sizes.count);
  1883. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, bf_type->BitField.fields.count);
  1884. di->CompositeType.elements = elements_di;
  1885. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1886. for_array(field_index, bf_type->BitField.fields) {
  1887. Entity *field = bf_type->BitField.fields[field_index];
  1888. u32 offset = bf_type->BitField.offsets[field_index];
  1889. u32 size = bf_type->BitField.sizes[field_index];
  1890. String name = str_lit("field_todo");
  1891. if (field != nullptr && field->token.string.len > 0) {
  1892. name = field->token.string;
  1893. }
  1894. // TODO(lachsinc): t_i64 may not be safe to use for all bitfields?
  1895. irDebugInfo *field_di = ir_add_debug_info_field_internal(module, name, t_i64,
  1896. 0,
  1897. nullptr,
  1898. di);
  1899. // NOTE(lachsinc): Above calls BitFieldValues type_size_of() which returns size in bits,
  1900. // replace with its true bit value here..
  1901. field_di->DerivedType.size = size;
  1902. field_di->DerivedType.offset = offset; // Offset stored in bits already, no need to convert
  1903. field_di->DerivedType.flags = irDebugInfoFlag_Bitfield;
  1904. map_set(&module->debug_info, hash_pointer(field_di), field_di);
  1905. array_add(&elements_di->DebugInfoArray.elements, field_di);
  1906. }
  1907. return di;
  1908. }
  1909. irDebugInfo *ir_add_debug_info_type_bit_set(irModule *module, Type *type, Entity *e, irDebugInfo *scope) {
  1910. GB_ASSERT(type->kind == Type_BitSet || type->kind == Type_Named);
  1911. Type *base = base_type(type);
  1912. Type *named = nullptr;
  1913. if (type->kind == Type_Named) {
  1914. named = type;
  1915. }
  1916. Type *elem_type = nullptr;
  1917. if (base->BitSet.elem != nullptr) {
  1918. // TODO(lachsinc): Do bitsets have integration with non-primitive types other than enums?
  1919. elem_type = base->BitSet.elem;
  1920. if (elem_type->kind == Type_Enum) {
  1921. GB_ASSERT(elem_type->Enum.fields.count == base->BitSet.upper + 1);
  1922. }
  1923. }
  1924. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1925. di->CompositeType.name = named != nullptr ? named->Named.name : str_lit("bit_set");
  1926. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1927. di->CompositeType.size = ir_debug_size_bits(base);
  1928. map_set(&module->debug_info, hash_type(type), di);
  1929. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, base->BitSet.upper + 1);
  1930. di->CompositeType.elements = elements_di;
  1931. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1932. for (i64 i = 0; i <= base->BitSet.upper; ++i) {
  1933. u32 offset = cast(u32)i;
  1934. // TODO(lachsinc): Maybe name these fields numbered ascending?
  1935. String name = str_lit("field_todo");
  1936. if (elem_type != nullptr && is_type_enum(elem_type)) {
  1937. // name = base_type(elem_type)->Enum.fields[i]->token.string;
  1938. }
  1939. irDebugInfo *field_di = ir_add_debug_info_field_internal(module, name, t_u32, // TODO(lachsinc): u32 fine??
  1940. 0,
  1941. nullptr,
  1942. di);
  1943. field_di->DerivedType.size = 1;
  1944. field_di->DerivedType.offset = offset; // Offset stored in bits already, no need to convert
  1945. field_di->DerivedType.flags = irDebugInfoFlag_Bitfield;
  1946. map_set(&module->debug_info, hash_pointer(field_di), field_di);
  1947. array_add(&elements_di->DebugInfoArray.elements, field_di);
  1948. }
  1949. return di;
  1950. }
  1951. irDebugInfo *ir_add_debug_info_type_string(irModule *module, irDebugInfo *scope, Entity *e, Type *type) {
  1952. // TODO(lachsinc): Does this only occur once ??
  1953. irDebugInfo **existing = map_get(&module->debug_info, hash_type(t_string));
  1954. if (existing != nullptr) {
  1955. GB_ASSERT((*existing)->kind == irDebugInfo_CompositeType);
  1956. return *existing;
  1957. } else {
  1958. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1959. di->CompositeType.name = type->Basic.name;
  1960. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1961. di->CompositeType.size = ir_debug_size_bits(t_string);
  1962. di->CompositeType.align = ir_debug_align_bits(t_string);
  1963. map_set(&module->debug_info, hash_type(type), di);
  1964. // Field "data"
  1965. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_cstring,
  1966. 0,
  1967. nullptr,
  1968. di);
  1969. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  1970. // Field "len"
  1971. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_i64,
  1972. data_di->DerivedType.size,
  1973. nullptr,
  1974. di);
  1975. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  1976. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  1977. array_add(&elements_di->DebugInfoArray.elements, data_di);
  1978. array_add(&elements_di->DebugInfoArray.elements, len_di);
  1979. di->CompositeType.elements = elements_di;
  1980. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  1981. return di;
  1982. }
  1983. }
  1984. irDebugInfo *ir_add_debug_info_type_any(irModule *module) {
  1985. irDebugInfo **existing = map_get(&module->debug_info, hash_type(t_any));
  1986. if (existing != nullptr) {
  1987. GB_ASSERT((*existing)->kind == irDebugInfo_CompositeType);
  1988. return *existing;
  1989. } else {
  1990. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  1991. di->CompositeType.name = t_any->Basic.name;
  1992. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  1993. di->CompositeType.size = ir_debug_size_bits(t_any);
  1994. di->CompositeType.align = ir_debug_align_bits(t_any);
  1995. map_set(&module->debug_info, hash_type(t_any), di);
  1996. // Field "data"
  1997. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  1998. 0,
  1999. nullptr,
  2000. di);
  2001. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  2002. // Field "id"
  2003. irDebugInfo *id_di = ir_add_debug_info_field_internal(module, str_lit("id"), t_typeid,
  2004. data_di->DerivedType.size,
  2005. nullptr,
  2006. di);
  2007. map_set(&module->debug_info, hash_pointer(id_di), id_di);
  2008. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  2009. array_add(&elements_di->DebugInfoArray.elements, data_di);
  2010. array_add(&elements_di->DebugInfoArray.elements, id_di);
  2011. di->CompositeType.elements = elements_di;
  2012. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2013. return di;
  2014. }
  2015. }
  2016. irDebugInfo *ir_add_debug_info_type_complex(irModule *module, Type *type) {
  2017. GB_ASSERT(type->kind == Type_Basic && is_type_complex(type));
  2018. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2019. map_set(&module->debug_info, hash_type(type), di);
  2020. di->CompositeType.name = type->Basic.name;
  2021. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2022. di->CompositeType.size = ir_debug_size_bits(type);
  2023. Type *field_type = base_complex_elem_type(type);
  2024. irDebugInfo *real_di = ir_add_debug_info_field_internal(module, str_lit("real"), field_type, 0*cast(i32)type_size_of(field_type), nullptr, di);
  2025. irDebugInfo *imag_di = ir_add_debug_info_field_internal(module, str_lit("imag"), field_type, 1*cast(i32)type_size_of(field_type), nullptr, di);
  2026. map_set(&module->debug_info, hash_pointer(real_di), real_di);
  2027. map_set(&module->debug_info, hash_pointer(imag_di), imag_di);
  2028. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  2029. array_add(&elements_di->DebugInfoArray.elements, real_di);
  2030. array_add(&elements_di->DebugInfoArray.elements, imag_di);
  2031. di->CompositeType.elements = elements_di;
  2032. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2033. return di;
  2034. }
  2035. irDebugInfo *ir_add_debug_info_type_quaternion(irModule *module, Type *type) {
  2036. GB_ASSERT(type->kind == Type_Basic && is_type_quaternion(type));
  2037. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2038. map_set(&module->debug_info, hash_type(type), di);
  2039. di->CompositeType.name = type->Basic.name;
  2040. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2041. di->CompositeType.size = ir_debug_size_bits(type);
  2042. Type *field_type = base_complex_elem_type(type);
  2043. // @QuaternionLayout
  2044. irDebugInfo *imag_di = ir_add_debug_info_field_internal(module, str_lit("imag"), field_type, 0*cast(i32)type_size_of(field_type), nullptr, di);
  2045. irDebugInfo *jmag_di = ir_add_debug_info_field_internal(module, str_lit("jmag"), field_type, 1*cast(i32)type_size_of(field_type), nullptr, di);
  2046. irDebugInfo *kmag_di = ir_add_debug_info_field_internal(module, str_lit("kmag"), field_type, 2*cast(i32)type_size_of(field_type), nullptr, di);
  2047. irDebugInfo *real_di = ir_add_debug_info_field_internal(module, str_lit("real"), field_type, 3*cast(i32)type_size_of(field_type), nullptr, di);
  2048. map_set(&module->debug_info, hash_pointer(imag_di), imag_di);
  2049. map_set(&module->debug_info, hash_pointer(jmag_di), jmag_di);
  2050. map_set(&module->debug_info, hash_pointer(kmag_di), kmag_di);
  2051. map_set(&module->debug_info, hash_pointer(real_di), real_di);
  2052. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 4);
  2053. array_add(&elements_di->DebugInfoArray.elements, imag_di);
  2054. array_add(&elements_di->DebugInfoArray.elements, jmag_di);
  2055. array_add(&elements_di->DebugInfoArray.elements, kmag_di);
  2056. array_add(&elements_di->DebugInfoArray.elements, real_di);
  2057. di->CompositeType.elements = elements_di;
  2058. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2059. return di;
  2060. }
  2061. irDebugInfo *ir_add_debug_info_proc_type(irModule *module, Type *type) {
  2062. GB_ASSERT(type->kind == Type_Proc);
  2063. irDebugInfo **existing = map_get(&module->debug_info, hash_type(type));
  2064. if (existing != nullptr) {
  2065. GB_ASSERT((*existing)->kind == irDebugInfo_ProcType);
  2066. return *existing;
  2067. }
  2068. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_ProcType);
  2069. map_set(&module->debug_info, hash_type(type), di);
  2070. isize result_count = type->Proc.result_count;
  2071. isize param_count = type->Proc.param_count;
  2072. // gb_max(result_count, 1) because llvm expects explicit "null" return type
  2073. di->ProcType.types = ir_add_debug_info_array(module, 0, gb_max(result_count, 1) + param_count);
  2074. // TODO(bill): Is this even correct?!
  2075. irDebugInfo *scope = di;
  2076. // Result/return types
  2077. if (result_count >= 1) {
  2078. TypeTuple *results_tuple = &type->Proc.results->Tuple;
  2079. for_array(i, results_tuple->variables) {
  2080. Entity *e = results_tuple->variables[i];
  2081. if (e->kind != Entity_Variable) {
  2082. continue;
  2083. }
  2084. irDebugInfo *type_di = ir_add_debug_info_type(module, e->type, e, scope, nullptr);
  2085. GB_ASSERT_NOT_NULL(type_di);
  2086. array_add(&di->ProcType.types->DebugInfoArray.elements, type_di);
  2087. }
  2088. } else {
  2089. // llvm expects "!{null}" for a function without return type, use nullptr to represent it.
  2090. array_add(&di->ProcType.types->DebugInfoArray.elements, (irDebugInfo*)nullptr);
  2091. }
  2092. // Param types
  2093. if (param_count >= 1) {
  2094. TypeTuple *params_tuple = &type->Proc.params->Tuple;
  2095. for_array(i, params_tuple->variables) {
  2096. Entity *e = params_tuple->variables[i];
  2097. if (e->kind != Entity_Variable) {
  2098. continue;
  2099. }
  2100. irDebugInfo *type_di = ir_add_debug_info_type(module, e->type, e, scope, nullptr);
  2101. GB_ASSERT_NOT_NULL(type_di);
  2102. array_add(&di->ProcType.types->DebugInfoArray.elements, type_di);
  2103. }
  2104. }
  2105. return di;
  2106. }
  2107. irDebugInfo *ir_add_debug_info_type(irModule *module, Type *type, Entity *e, irDebugInfo *scope, irDebugInfo *file) {
  2108. // NOTE(lachsinc): Special handling for procedure pointers - we hash their types directly into DISubroutineType's
  2109. // but we need them interpreted as pointers when we use them as variables.
  2110. if (type->kind == Type_Proc) {
  2111. if (e->kind == Entity_Variable || e->kind == Entity_TypeName) {
  2112. // TODO(lachsinc): Wasteful (maybe?). Create a derived type for _every_ different proc ptr type
  2113. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2114. map_set(&module->debug_info, hash_pointer(di), di);
  2115. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2116. di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2117. di->DerivedType.base_type = ir_add_debug_info_proc_type(module, type);
  2118. return di;
  2119. } else {
  2120. GB_PANIC("Proc definitions should have their type created manually (not through this function)");
  2121. }
  2122. }
  2123. irDebugInfo **existing = map_get(&module->debug_info, hash_type(type));
  2124. if (existing != nullptr) {
  2125. return *existing;
  2126. }
  2127. // Reset entity/location info, if applicable, for every type we try add.
  2128. // TODO(lachsinc): Confirm this doesn't mess up field's scopes etc.
  2129. if (type->kind == Type_Named) {
  2130. e = type->Named.type_name;
  2131. if (e) {
  2132. CheckerInfo *info = module->info;
  2133. file = ir_add_debug_info_file(module, ast_file_of_filename(info, e->token.pos.file));
  2134. // TODO(lachsinc): Determine proper scope for type declaration location stuff.
  2135. scope = file;
  2136. }
  2137. }
  2138. // TODO(lachsinc): Reorder if tests, "unique" types, like basic etc. should go last, they are most likely to hit the existing hashed type
  2139. // and no point checking them for the rest of the types. Or just use a massive switch...
  2140. // NOTE(lachsinc): Types should be inserted into debug_info map as their named, not base_type()'d counterparts.
  2141. Type *base = base_type(type);
  2142. if (type->kind == Type_Named) {
  2143. Type *named_base = type->Named.base;
  2144. // TODO(lachsinc): Better way to determine distinct etc. or just handle structs, enums before we reach here.
  2145. // ir_is_type_aggregate() except with no call to base_type().
  2146. if (named_base->kind != Type_Struct &&
  2147. named_base->kind != Type_Union &&
  2148. named_base->kind != Type_Enum &&
  2149. named_base->kind != Type_BitField &&
  2150. named_base->kind != Type_Tuple) {
  2151. // distinct / typedef etc.
  2152. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2153. if (type->kind == Type_Named) {
  2154. di->DerivedType.name = type->Named.name;
  2155. } else if (named_base->kind == Type_Basic) {
  2156. di->DerivedType.name = named_base->Basic.name;
  2157. }
  2158. di->DerivedType.tag = irDebugBasicEncoding_typedef;
  2159. map_set(&module->debug_info, hash_type(type), di);
  2160. // TODO(lachsinc): Do we need to try and resolve a new entity/scope for the base type?
  2161. // Maybe we also want to pull out type->Named.type_name ?? in the case it is a Named
  2162. di->DerivedType.base_type = ir_add_debug_info_type(module, named_base, e, scope, file);
  2163. return di;
  2164. }
  2165. }
  2166. if (type->kind == Type_Basic) {
  2167. switch (type->Basic.kind) {
  2168. // Composite basic types
  2169. case Basic_complex64: case Basic_complex128:
  2170. return ir_add_debug_info_type_complex(module, type);
  2171. case Basic_quaternion128: case Basic_quaternion256:
  2172. return ir_add_debug_info_type_quaternion(module, type);
  2173. case Basic_string:
  2174. return ir_add_debug_info_type_string(module, scope, e, type);
  2175. case Basic_any:
  2176. return ir_add_debug_info_type_any(module);
  2177. // Derived basic types
  2178. case Basic_cstring:
  2179. case Basic_rawptr: {
  2180. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2181. di->DerivedType.name = type->Basic.name;
  2182. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2183. di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2184. di->DerivedType.align = ir_debug_align_bits(t_rawptr); // TODO(lachsinc): Not sure if align is required.
  2185. map_set(&module->debug_info, hash_type(type), di);
  2186. if (type->Basic.kind == Basic_cstring) {
  2187. di->DerivedType.base_type = ir_add_debug_info_type(module, t_i8, e, scope, file);
  2188. } else {
  2189. // NOTE(lachsinc): llvm expects "null" for rawptr/voidptr
  2190. }
  2191. return di;
  2192. }
  2193. // Basic basic types
  2194. default: {
  2195. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_BasicType);
  2196. di->BasicType.encoding = ir_debug_encoding_for_basic(type->Basic.kind);
  2197. di->BasicType.name = type->Basic.name;
  2198. di->BasicType.size = ir_debug_size_bits(type);
  2199. di->BasicType.align = ir_debug_align_bits(type);
  2200. map_set(&module->debug_info, hash_type(type), di);
  2201. return di;
  2202. }
  2203. }
  2204. }
  2205. if (is_type_pointer(type)) {
  2206. // TODO(lachsinc): Ensure this handles pointer-to-pointer of same type etc. correctly.
  2207. Type *deref = type_deref(base);
  2208. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2209. di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2210. di->DerivedType.size = ir_debug_size_bits(type);
  2211. // NOTE(lachsinc): Map set before creating base_type to avoid circular dependency issues.
  2212. map_set(&module->debug_info, hash_type(type), di);
  2213. if (is_type_struct(deref)) {
  2214. int i = 123;
  2215. }
  2216. di->DerivedType.base_type = ir_add_debug_info_type(module, deref, e, scope, file);
  2217. return di;
  2218. }
  2219. if (is_type_opaque(type)) {
  2220. return ir_add_debug_info_type(module, strip_opaque_type(type), e, scope, file);
  2221. }
  2222. if (is_type_struct(type) ||
  2223. is_type_union(type) || is_type_enum(type) || is_type_tuple(type)) {
  2224. if (type->kind == Type_Named) {
  2225. // NOTE(lachsinc): Named named's should always be handled prior as typedefs.
  2226. GB_ASSERT(type->Named.base->kind != Type_Named);
  2227. }
  2228. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2229. // NOTE(lachsinc): Set map value before resolving field types to avoid circular dependencies.
  2230. map_set(&module->debug_info, hash_type(type), di);
  2231. if (is_type_named(type)) {
  2232. di->CompositeType.name = type->kind == Type_Named ? type->Named.name : type->Basic.name;
  2233. }
  2234. if (e) {
  2235. di->CompositeType.file = file;
  2236. di->CompositeType.scope = scope;
  2237. di->CompositeType.pos = e->token.pos;
  2238. }
  2239. di->CompositeType.size = ir_debug_size_bits(type);
  2240. // di->CompositeType.align = ir_debug_align_bits(type); // TODO(lachsinc): Necessary?
  2241. if (is_type_struct(type)) {
  2242. GB_ASSERT(base->kind == Type_Struct);
  2243. if (!is_type_named(type)) {
  2244. di->CompositeType.name = str_lit("struct");
  2245. GB_ASSERT_NOT_NULL(scope);
  2246. di->CompositeType.scope = scope;
  2247. }
  2248. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2249. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Struct.fields.count);
  2250. for_array(field_index, base->Struct.fields) {
  2251. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2252. ir_add_debug_info_field(module, di, base->Struct.fields[field_index], type,
  2253. cast(i32)field_index, base->Struct.fields[field_index]->type, file));
  2254. }
  2255. } else if (is_type_union(type)) {
  2256. GB_ASSERT(base->kind == Type_Union);
  2257. if (!is_type_named(type)) {
  2258. di->CompositeType.name = str_lit("union");
  2259. GB_ASSERT_NOT_NULL(scope);
  2260. di->CompositeType.scope = scope;
  2261. }
  2262. di->CompositeType.tag = irDebugBasicEncoding_union_type;
  2263. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Union.variants.count);
  2264. // TODO(lachsinc): Cleanup; this should be handled in a more generic manner for all types.
  2265. file = ir_add_debug_info_file(module, base->Union.node->file);
  2266. GB_ASSERT_NOT_NULL(file); // Union debug info requires file info
  2267. di->CompositeType.file = file;
  2268. di->CompositeType.pos = base->Union.node->UnionType.token.pos;
  2269. for_array(field_index, base->Union.variants) {
  2270. // TODO(bill): Union pseudo-"fields"
  2271. // irDebugInfo *di = ir_add_debug_info_field(module, di, nullptr, type, cast(i32)field_index, base->Union.variants[field_index], file);
  2272. // array_add(&di->CompositeType.elements->DebugInfoArray.elements, di);
  2273. }
  2274. } else if (is_type_enum(type)) {
  2275. GB_ASSERT(base->kind == Type_Enum);
  2276. if (!is_type_named(type)) {
  2277. di->CompositeType.name = str_lit("enum");
  2278. GB_ASSERT_NOT_NULL(scope);
  2279. di->CompositeType.scope = scope;
  2280. }
  2281. di->CompositeType.tag = irDebugBasicEncoding_enumeration_type;
  2282. di->CompositeType.base_type = ir_add_debug_info_type(module, base->Enum.base_type, e, scope, file);
  2283. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Enum.fields.count);
  2284. for_array(field_index, base->Enum.fields) {
  2285. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2286. ir_add_debug_info_enumerator(module, base->Enum.fields[field_index]));
  2287. }
  2288. // TODO(lachsinc): Do we want to ensure this is an enum in the global scope before
  2289. // adding it into the modules enum array ??
  2290. array_add(&module->debug_compile_unit->CompileUnit.enums->DebugInfoArray.elements, di);
  2291. } else if (is_type_tuple(type)) {
  2292. GB_ASSERT(base->kind == Type_Tuple);
  2293. if (!is_type_named(type)) {
  2294. di->CompositeType.name = str_lit("tuple");
  2295. GB_ASSERT_NOT_NULL(scope);
  2296. di->CompositeType.scope = scope;
  2297. }
  2298. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2299. di->CompositeType.elements = ir_add_debug_info_array(module, 0, base->Tuple.variables.count);
  2300. // TODO(lachsinc): Ensure offsets are set properly?
  2301. for_array(var_index, base->Tuple.variables) {
  2302. array_add(&di->CompositeType.elements->DebugInfoArray.elements,
  2303. ir_add_debug_info_field(module, di, base->Tuple.variables[var_index], type,
  2304. cast(i32)var_index, base->Tuple.variables[var_index]->type, file));
  2305. }
  2306. }
  2307. return di;
  2308. }
  2309. if (is_type_dynamic_array(type)) {
  2310. return ir_add_debug_info_type_dynamic_array(module, type, e, scope, file);
  2311. }
  2312. if (is_type_array(type)) {
  2313. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2314. di->CompositeType.size = ir_debug_size_bits(type);
  2315. di->CompositeType.align = ir_debug_align_bits(type);
  2316. di->CompositeType.tag = irDebugBasicEncoding_array_type;
  2317. di->CompositeType.array_count = (i32)type->Array.count;
  2318. map_set(&module->debug_info, hash_type(type), di);
  2319. di->CompositeType.base_type = ir_add_debug_info_type(module, type->Array.elem, e, scope, file);
  2320. GB_ASSERT(base->kind != Type_Named);
  2321. return di;
  2322. }
  2323. if (is_type_enumerated_array(type)) {
  2324. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2325. di->CompositeType.size = ir_debug_size_bits(type);
  2326. di->CompositeType.align = ir_debug_align_bits(type);
  2327. di->CompositeType.tag = irDebugBasicEncoding_array_type;
  2328. di->CompositeType.array_count = (i32)type->EnumeratedArray.count;
  2329. map_set(&module->debug_info, hash_type(type), di);
  2330. di->CompositeType.base_type = ir_add_debug_info_type(module, type->EnumeratedArray.elem, e, scope, file);
  2331. GB_ASSERT(base->kind != Type_Named);
  2332. return di;
  2333. }
  2334. if (is_type_slice(type)) {
  2335. // NOTE(lachsinc): Every slice type has its own composite type / field debug infos created. This is sorta wasteful.
  2336. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2337. di->CompositeType.name = str_lit("slice");
  2338. di->CompositeType.tag = irDebugBasicEncoding_structure_type;
  2339. di->CompositeType.size = ir_debug_size_bits(type); // TODO(lachsinc): Correct ??
  2340. di->CompositeType.align = ir_debug_align_bits(type);
  2341. map_set(&module->debug_info, hash_type(type), di);
  2342. // Data pointer type
  2343. irDebugInfo *data_ptr_di = ir_alloc_debug_info(irDebugInfo_DerivedType);
  2344. Type *elem_type = type->Slice.elem;
  2345. if (is_type_named(elem_type)) {
  2346. data_ptr_di->DerivedType.name = elem_type->kind == Type_Named ? elem_type->Named.name : elem_type->Basic.name;
  2347. }
  2348. data_ptr_di->DerivedType.tag = irDebugBasicEncoding_pointer_type;
  2349. data_ptr_di->DerivedType.size = ir_debug_size_bits(t_rawptr);
  2350. map_set(&module->debug_info, hash_pointer(data_ptr_di), data_ptr_di);
  2351. data_ptr_di->DerivedType.base_type = ir_add_debug_info_type(module, elem_type, e, scope, file);
  2352. irDebugInfo *data_di = ir_add_debug_info_field_internal(module, str_lit("data"), t_rawptr,
  2353. 0,
  2354. nullptr,
  2355. di);
  2356. data_di->DerivedType.base_type = data_ptr_di;
  2357. map_set(&module->debug_info, hash_pointer(data_di), data_di);
  2358. irDebugInfo *len_di = ir_add_debug_info_field_internal(module, str_lit("len"), t_int,
  2359. data_di->DerivedType.size,
  2360. nullptr,
  2361. di);
  2362. map_set(&module->debug_info, hash_pointer(len_di), len_di);
  2363. irDebugInfo *elements_di = ir_add_debug_info_array(module, 0, 2);
  2364. array_add(&elements_di->DebugInfoArray.elements, data_di);
  2365. array_add(&elements_di->DebugInfoArray.elements, len_di);
  2366. di->CompositeType.elements = elements_di;
  2367. map_set(&module->debug_info, hash_pointer(elements_di), elements_di);
  2368. return di;
  2369. }
  2370. if (is_type_map(type)) {
  2371. // TODO(lachsinc): Looks like "generated_struct_type" map.entries.data is just a u8*, we could
  2372. // always look at the map header and create the debug info manually (if we
  2373. // want struct members to be interpreted as the correct type).
  2374. // Also; are hashes meant to be interpreted as bool*'s ?? or is that simply slot occupied data?
  2375. return ir_add_debug_info_type(module, type->Map.generated_struct_type, e, scope, file);
  2376. }
  2377. // NOTE(lachsinc): For now we just interpret all BitFieldValues as i64 inside ir_add_debug_info_type_bit_field().
  2378. /*
  2379. if (is_type_bit_field_value(type)) {
  2380. // NOTE(Lachsinc): Suboptimal; creates a new type for each unique bit field value type
  2381. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_BasicType);
  2382. di->BasicType.encoding = irDebugBasicEncoding_unsigned;
  2383. // di->BasicType.name = str_lit("todo");
  2384. di->BasicType.size = base->BitFieldValue.bits;
  2385. map_set(&module->debug_info, hash_type(type), di);
  2386. return di;
  2387. }
  2388. */
  2389. if (is_type_bit_field(type)) {
  2390. return ir_add_debug_info_type_bit_field(module, type, e, scope);
  2391. }
  2392. if (is_type_bit_set(type)) {
  2393. return ir_add_debug_info_type_bit_set(module, type, e, scope);
  2394. }
  2395. if (is_type_simd_vector(type)) {
  2396. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompositeType);
  2397. di->CompositeType.size = ir_debug_size_bits(type);
  2398. di->CompositeType.align = ir_debug_align_bits(type);
  2399. di->CompositeType.tag = irDebugBasicEncoding_array_type;
  2400. di->CompositeType.array_count = (i32)type->SimdVector.count;
  2401. map_set(&module->debug_info, hash_type(type), di);
  2402. di->CompositeType.base_type = ir_add_debug_info_type(module, type->SimdVector.elem, e, scope, file);
  2403. GB_ASSERT(base->kind != Type_Named);
  2404. return di;
  2405. }
  2406. GB_PANIC("Unreachable %s", type_to_string(type));
  2407. return nullptr;
  2408. }
  2409. irDebugInfo *ir_add_debug_info_global(irModule *module, irValue *v) {
  2410. if (!module->generate_debug_info) {
  2411. return nullptr;
  2412. }
  2413. Entity *e = v->Global.entity;
  2414. // NOTE(lachsinc): Just to be safe/robust; globals are likely added once only?
  2415. irDebugInfo **existing = map_get(&module->debug_info, hash_entity(e));
  2416. if (existing != nullptr) {
  2417. return *existing;
  2418. }
  2419. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_GlobalVariableExpression);
  2420. map_set(&module->debug_info, hash_entity(e), di);
  2421. // Create or fetch file debug info.
  2422. CheckerInfo *info = module->info;
  2423. String filename = e->token.pos.file;
  2424. AstFile *f = ast_file_of_filename(info, filename);
  2425. GB_ASSERT_NOT_NULL(f);
  2426. irDebugInfo *scope = ir_add_debug_info_file(module, f);
  2427. irDebugInfo *var_di = ir_alloc_debug_info(irDebugInfo_GlobalVariable);
  2428. var_di->GlobalVariable.name = e->token.string;
  2429. var_di->GlobalVariable.scope = scope;
  2430. var_di->GlobalVariable.file = scope;
  2431. var_di->GlobalVariable.pos = e->token.pos;
  2432. var_di->GlobalVariable.variable = v;
  2433. // NOTE(lachsinc): The "DIGlobalVariableExpression" owns us, and is what we refer to from other
  2434. // locations in the ir source, so we will reserve the "e" hash for it, and use something else
  2435. // unique for the DIGlobalVariable's hash.
  2436. map_set(&module->debug_info, hash_pointer(var_di), var_di);
  2437. var_di->GlobalVariable.type = ir_add_debug_info_type(module, e->type, nullptr, scope, nullptr);
  2438. GB_ASSERT_NOT_NULL(var_di->GlobalVariable.type);
  2439. di->GlobalVariableExpression.var = var_di;
  2440. array_add(&module->debug_compile_unit->CompileUnit.globals->DebugInfoArray.elements, di);
  2441. return di;
  2442. }
  2443. irDebugInfo *ir_add_debug_info_block(irProcedure *proc, Scope *scope) {
  2444. irModule *module = proc->module;
  2445. irDebugInfo **existing = map_get(&module->debug_info, hash_pointer(scope));
  2446. if (existing != nullptr) {
  2447. GB_ASSERT((*existing)->kind == irDebugInfo_LexicalBlock);
  2448. return *existing;
  2449. }
  2450. Ast *block = scope->node;
  2451. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_LexicalBlock);
  2452. di->LexicalBlock.file = proc->debug_scope->Proc.file;
  2453. di->LexicalBlock.scope = proc->debug_scope;
  2454. di->LexicalBlock.pos = ast_token(block).pos;
  2455. map_set(&module->debug_info, hash_pointer(scope), di);
  2456. return di;
  2457. }
  2458. irDebugInfo *ir_add_debug_info_local(irProcedure *proc, Entity *e, i32 arg_id) {
  2459. // TODO(lachsinc): Not sure if this handles generated locals properly as they may not have
  2460. // enough information contained inside "e".
  2461. irModule *module = proc->module;
  2462. if (!module->generate_debug_info) {
  2463. return nullptr;
  2464. }
  2465. irDebugInfo *scope = nullptr;
  2466. irDebugInfo *file = nullptr;
  2467. if (e->scope && e->scope->node->kind == Ast_ProcType) {
  2468. scope = proc->debug_scope;
  2469. file = proc->debug_scope->Proc.file;
  2470. } else {
  2471. scope = ir_add_debug_info_block(proc, e->scope);
  2472. file = scope->LexicalBlock.file;
  2473. }
  2474. GB_ASSERT_NOT_NULL(scope);
  2475. GB_ASSERT_NOT_NULL(file);
  2476. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_LocalVariable);
  2477. di->LocalVariable.name = e->token.string;
  2478. di->LocalVariable.scope = scope;
  2479. di->LocalVariable.file = file;
  2480. di->LocalVariable.pos = e->token.pos;
  2481. di->LocalVariable.arg = arg_id;
  2482. di->LocalVariable.type = ir_add_debug_info_type(module, e->type, e, scope, file); // TODO(lachsinc): Is this the correct entity to pass? Or do we want a TypeName ??
  2483. map_set(&module->debug_info, hash_entity(e), di);
  2484. return di;
  2485. }
  2486. irDebugInfo *ir_add_debug_info_proc(irProcedure *proc) {
  2487. irModule *module = proc->module;
  2488. if (!module->generate_debug_info) {
  2489. return nullptr;
  2490. }
  2491. Entity *entity = proc->entity;
  2492. // Add / retrieve debug info for file.
  2493. CheckerInfo *info = proc->module->info;
  2494. String filename = proc->entity->token.pos.file;
  2495. AstFile *f = ast_file_of_filename(info, filename);
  2496. irDebugInfo *file = nullptr;
  2497. if (f) {
  2498. file = ir_add_debug_info_file(proc->module, f);
  2499. }
  2500. // TODO(lachsinc): Should scope be made separate to file?
  2501. irDebugInfo *scope = file;
  2502. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Proc);
  2503. map_set(&proc->module->debug_info, hash_entity(entity), di);
  2504. di->Proc.entity = entity;
  2505. di->Proc.name = proc->name;
  2506. di->Proc.file = file;
  2507. di->Proc.pos = entity->token.pos;
  2508. di->Proc.type = ir_add_debug_info_proc_type(proc->module, proc->type);
  2509. proc->debug_scope = di;
  2510. return di;
  2511. }
  2512. irDebugInfo *ir_add_debug_info_location(irModule *m, Ast *node, irDebugInfo *scope, Entity *e) {
  2513. if (node == nullptr || scope == nullptr) {
  2514. if (e != nullptr && scope != nullptr) {
  2515. // irDebugInfo **existing = map_get(&m->debug_info, hash_entity(e));
  2516. // if (existing != nullptr) {
  2517. // return *existing;
  2518. // }
  2519. // // TODO HACK(bill): This is a little dirty but it is should do for the weird edge cases
  2520. // irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Location);
  2521. // di->Location.pos = e->token.pos;
  2522. // di->Location.scope = scope;
  2523. // map_set(&m->debug_info, hash_entity(e), di);
  2524. // return di;
  2525. }
  2526. return nullptr;
  2527. }
  2528. // TODO(lachsinc): Should we traverse the node/children until we find one with
  2529. // valid token/pos and use that instead??
  2530. irDebugInfo **existing = map_get(&m->debug_info, hash_node(node));
  2531. if (existing != nullptr) {
  2532. return *existing;
  2533. }
  2534. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_Location);
  2535. di->Location.pos = ast_token(node).pos;
  2536. di->Location.scope = scope;
  2537. map_set(&m->debug_info, hash_node(node), di);
  2538. return di;
  2539. }
  2540. void ir_push_debug_location(irModule *m, Ast *node, irDebugInfo *scope, Entity *e) {
  2541. irDebugInfo *debug_location = ir_add_debug_info_location(m, node, scope, e);
  2542. array_add(&m->debug_location_stack, debug_location);
  2543. }
  2544. void ir_pop_debug_location(irModule *m) {
  2545. GB_ASSERT_MSG(m->debug_location_stack.count > 0, "Attempt to pop debug location stack too many times");
  2546. array_pop(&m->debug_location_stack);
  2547. }
  2548. ////////////////////////////////////////////////////////////////
  2549. //
  2550. // @Emit
  2551. //
  2552. ////////////////////////////////////////////////////////////////
  2553. irValue *ir_emit_runtime_call(irProcedure *proc, char const *name_, Array<irValue *> args, Ast *expr = nullptr, ProcInlining inlining = ProcInlining_none);
  2554. irValue *ir_emit_package_call(irProcedure *proc, char const *package_name_, char const *name_, Array<irValue *> args, Ast *expr = nullptr, ProcInlining inlining = ProcInlining_none);
  2555. irValue *ir_emit_store(irProcedure *p, irValue *address, irValue *value, bool is_volatile) {
  2556. Type *a = type_deref(ir_type(address));
  2557. if (is_type_boolean(a)) {
  2558. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  2559. value = ir_emit_conv(p, value, a);
  2560. }
  2561. if (address) address->uses += 1;
  2562. if (value) value->uses += 1;
  2563. Type *b = ir_type(value);
  2564. if (!is_type_untyped(b)) {
  2565. GB_ASSERT_MSG(are_types_identical(core_type(a), core_type(b)), "%s %s", type_to_string(a), type_to_string(b));
  2566. }
  2567. return ir_emit(p, ir_instr_store(p, address, value, is_volatile));
  2568. }
  2569. irValue *ir_emit_load(irProcedure *p, irValue *address, i64 custom_align) {
  2570. GB_ASSERT(address != nullptr);
  2571. Type *t = type_deref(ir_type(address));
  2572. // if (is_type_boolean(t)) {
  2573. // return ir_emit(p, ir_instr_load_bool(p, address));
  2574. // }
  2575. if (address) address->uses += 1;
  2576. auto instr = ir_instr_load(p, address);
  2577. instr->Instr.Load.custom_align = custom_align;
  2578. return ir_emit(p, instr);
  2579. }
  2580. irValue *ir_emit_select(irProcedure *p, irValue *cond, irValue *t, irValue *f) {
  2581. if (cond) cond->uses += 1;
  2582. if (t) t->uses += 1;
  2583. if (f) f->uses += 1;
  2584. return ir_emit(p, ir_instr_select(p, cond, t, f));
  2585. }
  2586. void ir_value_set_debug_location(irProcedure *proc, irValue *v) {
  2587. GB_ASSERT_NOT_NULL(proc);
  2588. GB_ASSERT_NOT_NULL(v);
  2589. if (v->loc != nullptr) {
  2590. return; // Already set
  2591. }
  2592. irModule *m = proc->module;
  2593. GB_ASSERT(m->debug_location_stack.count > 0);
  2594. v->loc = *array_end_ptr(&m->debug_location_stack);
  2595. if (v->loc == nullptr && proc->entity != nullptr) {
  2596. if (proc->is_entry_point || (string_compare(proc->name, str_lit(IR_STARTUP_RUNTIME_PROC_NAME)) == 0)) {
  2597. // NOTE(lachsinc): Entry point (main()) and runtime_startup are the only ones where null location is considered valid.
  2598. } else {
  2599. if (v->kind == irValue_Instr) {
  2600. auto *instr = &v->Instr;
  2601. gb_printf_err("Instruction kind: %.*s\n", LIT(ir_instr_strings[instr->kind]));
  2602. if (instr->kind == irInstr_DebugDeclare) {
  2603. gb_printf_err("\t%.*s\n", LIT(instr->DebugDeclare.entity->token.string));
  2604. }
  2605. }
  2606. GB_PANIC("Value without debug location: %.*s %p; %p :: %s", LIT(proc->name), proc->entity, v, type_to_string(proc->type));
  2607. }
  2608. }
  2609. }
  2610. void ir_emit_zero_init(irProcedure *p, irValue *address, Ast *expr) {
  2611. gbAllocator a = ir_allocator();
  2612. Type *t = type_deref(ir_type(address));
  2613. isize sz = type_size_of(t);
  2614. if (address) address->uses += 1;
  2615. if (!(gb_is_power_of_two(sz) && sz <= build_context.max_align)) {
  2616. // TODO(bill): Is this a good idea?
  2617. auto args = array_make<irValue *>(a, 2);
  2618. args[0] = ir_emit_conv(p, address, t_rawptr);
  2619. args[1] = ir_const_int(type_size_of(t));
  2620. AstPackage *pkg_runtime = get_core_package(p->module->info, str_lit("runtime"));
  2621. if (p->entity != nullptr) {
  2622. String name = p->entity->token.string;
  2623. if (p->entity->pkg != pkg_runtime && !(name == "mem_zero" || name == "memset")) {
  2624. ir_emit_comment(p, str_lit("ZeroInit"));
  2625. irValue *v = ir_emit_package_call(p, "runtime", "mem_zero", args, expr);
  2626. return;
  2627. }
  2628. }
  2629. }
  2630. ir_emit(p, ir_instr_zero_init(p, address));
  2631. }
  2632. irValue *ir_emit_comment(irProcedure *p, String text) {
  2633. return ir_emit(p, ir_instr_comment(p, text));
  2634. }
  2635. void ir_emit_init_context(irProcedure *proc, irValue *c = nullptr) {
  2636. irModule *m = proc->module;
  2637. gbAllocator a = ir_allocator();
  2638. auto args = array_make<irValue *>(a, 1);
  2639. args[0] = c ? c : m->global_default_context;
  2640. ir_emit_runtime_call(proc, "__init_context", args);
  2641. }
  2642. irValue *ir_copy_value_to_ptr(irProcedure *proc, irValue *val, Type *new_type, i64 alignment) {
  2643. i64 type_alignment = type_align_of(new_type);
  2644. if (alignment < type_alignment) {
  2645. alignment = type_alignment;
  2646. }
  2647. GB_ASSERT_MSG(are_types_identical(new_type, ir_type(val)), "%s %s", type_to_string(new_type), type_to_string(ir_type(val)));
  2648. irValue *ptr = ir_add_local_generated(proc, new_type, false);
  2649. ptr->Instr.Local.alignment = alignment;
  2650. ir_emit_store(proc, ptr, val);
  2651. return ptr;
  2652. }
  2653. irValue *ir_emit_bitcast(irProcedure *proc, irValue *data, Type *type) {
  2654. return ir_emit(proc, ir_instr_conv(proc, irConv_bitcast, data, ir_type(data), type));
  2655. }
  2656. void ir_emit_unreachable(irProcedure *proc) {
  2657. ir_emit(proc, ir_instr_unreachable(proc));
  2658. }
  2659. irValue *ir_get_package_value(irModule *m, String package_name, String entity_name) {
  2660. AstPackage *rt_pkg = get_core_package(m->info, package_name);
  2661. Entity *e = scope_lookup_current(rt_pkg->scope, entity_name);
  2662. irValue **found = map_get(&m->values, hash_entity(e));
  2663. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  2664. return *found;
  2665. }
  2666. irValue *ir_find_or_generate_context_ptr(irProcedure *proc) {
  2667. if (proc->context_stack.count > 0) {
  2668. return proc->context_stack[proc->context_stack.count-1].value;
  2669. }
  2670. irValue *c = ir_add_local_generated(proc, t_context, true);
  2671. ir_push_context_onto_stack(proc, c);
  2672. ir_emit_init_context(proc, c);
  2673. return c;
  2674. }
  2675. Array<irValue *> ir_value_to_array(irProcedure *p, irValue *value) {
  2676. Array<irValue *> array = {};
  2677. Type *t = base_type(ir_type(value));
  2678. if (t == nullptr) {
  2679. // Do nothing
  2680. } else if (is_type_tuple(t)) {
  2681. GB_ASSERT(t->kind == Type_Tuple);
  2682. auto *rt = &t->Tuple;
  2683. if (rt->variables.count > 0) {
  2684. array = array_make<irValue *>(ir_allocator(), rt->variables.count);
  2685. for_array(i, rt->variables) {
  2686. irValue *elem = ir_emit_struct_ev(p, value, cast(i32)i);
  2687. array[i] = elem;
  2688. }
  2689. }
  2690. } else {
  2691. array = array_make<irValue *>(ir_allocator(), 1);
  2692. array[0] = value;
  2693. }
  2694. return array;
  2695. }
  2696. irValue *ir_emit_call(irProcedure *p, irValue *value, Array<irValue *> const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false) {
  2697. Type *pt = base_type(ir_type(value));
  2698. GB_ASSERT(pt->kind == Type_Proc);
  2699. Type *results = pt->Proc.results;
  2700. if (p->entity != nullptr) {
  2701. if (p->entity->flags & EntityFlag_Disabled) {
  2702. return nullptr;
  2703. }
  2704. }
  2705. defer (if (pt->Proc.diverging) {
  2706. ir_emit_unreachable(p);
  2707. });
  2708. irValue *context_ptr = nullptr;
  2709. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2710. context_ptr = ir_find_or_generate_context_ptr(p);
  2711. }
  2712. set_procedure_abi_types(heap_allocator(), pt);
  2713. bool is_c_vararg = pt->Proc.c_vararg;
  2714. isize param_count = pt->Proc.param_count;
  2715. if (is_c_vararg) {
  2716. GB_ASSERT(param_count-1 <= args.count);
  2717. param_count -= 1;
  2718. } else {
  2719. GB_ASSERT_MSG(param_count == args.count, "%.*s %td == %td", LIT(p->entity->token.string), param_count, args.count);
  2720. }
  2721. auto processed_args = array_make<irValue *>(heap_allocator(), 0, args.count);
  2722. for (isize i = 0; i < param_count; i++) {
  2723. Entity *e = pt->Proc.params->Tuple.variables[i];
  2724. if (e->kind != Entity_Variable) {
  2725. array_add(&processed_args, args[i]);
  2726. continue;
  2727. }
  2728. GB_ASSERT(e->flags & EntityFlag_Param);
  2729. Type *original_type = e->type;
  2730. Type *new_type = pt->Proc.abi_compat_params[i];
  2731. Type *arg_type = ir_type(args[i]);
  2732. if (are_types_identical(arg_type, new_type)) {
  2733. // NOTE(bill): Done
  2734. array_add(&processed_args, args[i]);
  2735. } else if (!are_types_identical(original_type, new_type)) {
  2736. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  2737. Type *av = core_type(type_deref(new_type));
  2738. if (are_types_identical(av, core_type(original_type))) {
  2739. if (e->flags&EntityFlag_ImplicitReference) {
  2740. array_add(&processed_args, ir_address_from_load_or_generate_local(p, args[i]));
  2741. } else if (!is_type_pointer(arg_type)) {
  2742. array_add(&processed_args, ir_copy_value_to_ptr(p, args[i], original_type, 16));
  2743. }
  2744. } else {
  2745. array_add(&processed_args, ir_emit_transmute(p, args[i], new_type));
  2746. }
  2747. } else if (is_type_integer(new_type) || is_type_float(new_type)) {
  2748. array_add(&processed_args, ir_emit_transmute(p, args[i], new_type));
  2749. } else if (new_type == t_llvm_bool) {
  2750. array_add(&processed_args, ir_emit_conv(p, args[i], new_type));
  2751. } else if (is_type_simd_vector(new_type)) {
  2752. array_add(&processed_args, ir_emit_transmute(p, args[i], new_type));
  2753. } else if (is_type_tuple(new_type)) {
  2754. Type *abi_type = pt->Proc.abi_compat_params[i];
  2755. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2756. irValue *x = ir_emit_transmute(p, args[i], st);
  2757. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  2758. irValue *xx = ir_emit_struct_ev(p, x, cast(i32)j);
  2759. array_add(&processed_args, xx);
  2760. }
  2761. }
  2762. } else {
  2763. irValue *x = ir_emit_conv(p, args[i], new_type);
  2764. array_add(&processed_args, x);
  2765. }
  2766. }
  2767. if (inlining == ProcInlining_none) {
  2768. inlining = p->inlining;
  2769. }
  2770. irValue *result = nullptr;
  2771. Type *abi_rt = pt->Proc.abi_compat_result_type;
  2772. Type *rt = reduce_tuple_to_single_type(results);
  2773. if (pt->Proc.return_by_pointer) {
  2774. irValue *return_ptr = nullptr;
  2775. if (use_return_ptr_hint && p->return_ptr_hint_value != nullptr) {
  2776. if (are_types_identical(type_deref(ir_type(p->return_ptr_hint_value)), rt)) {
  2777. return_ptr = p->return_ptr_hint_value;
  2778. p->return_ptr_hint_used = true;
  2779. return_ptr->uses += 1;
  2780. }
  2781. }
  2782. if (return_ptr == nullptr) {
  2783. return_ptr = ir_add_local_generated(p, rt, true);
  2784. }
  2785. GB_ASSERT(is_type_pointer(ir_type(return_ptr)));
  2786. ir_emit(p, ir_instr_call(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining));
  2787. result = ir_emit_load(p, return_ptr);
  2788. } else {
  2789. result = ir_emit(p, ir_instr_call(p, value, nullptr, processed_args, abi_rt, context_ptr, inlining));
  2790. if (abi_rt != results) {
  2791. result = ir_emit_transmute(p, result, rt);
  2792. }
  2793. }
  2794. if (value->kind == irValue_Proc) {
  2795. irProcedure *the_proc = &value->Proc;
  2796. Entity *e = the_proc->entity;
  2797. if (e != nullptr && entity_has_deferred_procedure(e)) {
  2798. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  2799. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  2800. irValue **deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  2801. GB_ASSERT(deferred_found != nullptr);
  2802. irValue *deferred = *deferred_found;
  2803. auto in_args = args;
  2804. Array<irValue *> result_as_args = {};
  2805. switch (kind) {
  2806. case DeferredProcedure_none:
  2807. break;
  2808. case DeferredProcedure_in:
  2809. result_as_args = in_args;
  2810. break;
  2811. case DeferredProcedure_out:
  2812. result_as_args = ir_value_to_array(p, result);
  2813. break;
  2814. case DeferredProcedure_in_out:
  2815. {
  2816. auto out_args = ir_value_to_array(p, result);
  2817. array_init(&result_as_args, heap_allocator(), in_args.count + out_args.count);
  2818. array_copy(&result_as_args, in_args, 0);
  2819. array_copy(&result_as_args, out_args, in_args.count);
  2820. }
  2821. break;
  2822. }
  2823. ir_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  2824. }
  2825. }
  2826. return result;
  2827. }
  2828. irValue *ir_emit_runtime_call(irProcedure *proc, char const *name_, Array<irValue *> args, Ast *expr, ProcInlining inlining) {
  2829. String name = make_string_c(cast(char *)name_);
  2830. AstPackage *p = proc->module->info->runtime_package;
  2831. Entity *e = scope_lookup_current(p->scope, name);
  2832. irValue **found = map_get(&proc->module->values, hash_entity(e));
  2833. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(name));
  2834. irValue *gp = *found;
  2835. irValue *call = ir_emit_call(proc, gp, args, inlining);
  2836. return call;
  2837. }
  2838. irValue *ir_emit_package_call(irProcedure *proc, char const *package_name_, char const *name_, Array<irValue *> args, Ast *expr, ProcInlining inlining) {
  2839. String name = make_string_c(cast(char *)name_);
  2840. String package_name = make_string_c(cast(char *)package_name_);
  2841. AstPackage *p = get_core_package(proc->module->info, package_name);
  2842. Entity *e = scope_lookup_current(p->scope, name);
  2843. irValue **found = map_get(&proc->module->values, hash_entity(e));
  2844. GB_ASSERT_MSG(found != nullptr, "%s.%.*s", package_name_, LIT(name));
  2845. irValue *gp = *found;
  2846. irValue *call = ir_emit_call(proc, gp, args, inlining);
  2847. return call;
  2848. }
  2849. void ir_emit_defer_stmts(irProcedure *proc, irDeferExitKind kind, irBlock *block) {
  2850. isize count = proc->defer_stmts.count;
  2851. isize i = count;
  2852. while (i --> 0) {
  2853. irDefer d = proc->defer_stmts[i];
  2854. isize prev_context_stack_count = proc->context_stack.count;
  2855. defer (proc->context_stack.count = prev_context_stack_count);
  2856. proc->context_stack.count = d.context_stack_count;
  2857. if (kind == irDeferExit_Default) {
  2858. if (proc->scope_index == d.scope_index &&
  2859. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  2860. ir_build_defer_stmt(proc, d);
  2861. array_pop(&proc->defer_stmts);
  2862. continue;
  2863. } else {
  2864. break;
  2865. }
  2866. } else if (kind == irDeferExit_Return) {
  2867. ir_build_defer_stmt(proc, d);
  2868. } else if (kind == irDeferExit_Branch) {
  2869. GB_ASSERT(block != nullptr);
  2870. isize lower_limit = block->scope_index;
  2871. if (lower_limit < d.scope_index) {
  2872. ir_build_defer_stmt(proc, d);
  2873. }
  2874. }
  2875. }
  2876. }
  2877. void ir_open_scope(irProcedure *proc) {
  2878. proc->scope_index++;
  2879. }
  2880. void ir_close_scope(irProcedure *proc, irDeferExitKind kind, irBlock *block, bool pop_stack=true) {
  2881. ir_emit_defer_stmts(proc, kind, block);
  2882. GB_ASSERT(proc->scope_index > 0);
  2883. // NOTE(bill): Remove `context`s made in that scope
  2884. isize end_idx = proc->context_stack.count-1;
  2885. isize pop_count = 0;
  2886. for (;;) {
  2887. if (end_idx < 0) {
  2888. break;
  2889. }
  2890. irContextData *end = &proc->context_stack[end_idx];
  2891. if (end == nullptr) {
  2892. break;
  2893. }
  2894. if (end->scope_index != proc->scope_index) {
  2895. break;
  2896. }
  2897. end_idx -= 1;
  2898. pop_count += 1;
  2899. }
  2900. if (pop_stack) {
  2901. for (isize i = 0; i < pop_count; i++) {
  2902. array_pop(&proc->context_stack);
  2903. }
  2904. }
  2905. proc->scope_index--;
  2906. }
  2907. void ir_emit_return(irProcedure *proc, irValue *v) {
  2908. ir_emit_defer_stmts(proc, irDeferExit_Return, nullptr);
  2909. if (proc->type->Proc.return_by_pointer) {
  2910. ir_emit_store(proc, proc->return_ptr, v);
  2911. ir_emit(proc, ir_instr_return(proc, nullptr));
  2912. } else {
  2913. Type *abi_rt = proc->type->Proc.abi_compat_result_type;
  2914. if (abi_rt != proc->type->Proc.results) {
  2915. v = ir_emit_transmute(proc, v, abi_rt);
  2916. }
  2917. ir_emit(proc, ir_instr_return(proc, v));
  2918. }
  2919. if (v) v->uses += 1;
  2920. }
  2921. void ir_emit_jump(irProcedure *proc, irBlock *target_block) {
  2922. irBlock *b = proc->curr_block;
  2923. if (b == nullptr) {
  2924. return;
  2925. }
  2926. ir_emit(proc, ir_instr_jump(proc, target_block));
  2927. ir_add_edge(b, target_block);
  2928. ir_start_block(proc, nullptr);
  2929. }
  2930. void ir_emit_if(irProcedure *proc, irValue *cond, irBlock *true_block, irBlock *false_block) {
  2931. irBlock *b = proc->curr_block;
  2932. if (b == nullptr) {
  2933. return;
  2934. }
  2935. ir_emit(proc, ir_instr_if(proc, cond, true_block, false_block));
  2936. ir_add_edge(b, true_block);
  2937. ir_add_edge(b, false_block);
  2938. ir_start_block(proc, nullptr);
  2939. if (cond) cond->uses += 1;
  2940. }
  2941. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right);
  2942. irValue *ir_gen_map_header(irProcedure *proc, irValue *map_val_ptr, Type *map_type) {
  2943. GB_ASSERT_MSG(is_type_pointer(ir_type(map_val_ptr)), "%s", type_to_string(ir_type(map_val_ptr)));
  2944. gbAllocator a = ir_allocator();
  2945. irValue *h = ir_add_local_generated(proc, t_map_header, false); // all the values will be initialzed later
  2946. map_type = base_type(map_type);
  2947. Type *key_type = map_type->Map.key;
  2948. Type *val_type = map_type->Map.value;
  2949. // NOTE(bill): Removes unnecessary allocation if split gep
  2950. irValue *gep0 = ir_emit_struct_ep(proc, h, 0);
  2951. irValue *m = ir_emit_conv(proc, map_val_ptr, type_deref(ir_type(gep0)));
  2952. ir_emit_store(proc, gep0, m);
  2953. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 1), ir_const_bool(is_type_string(key_type)));
  2954. i64 entry_size = type_size_of (map_type->Map.entry_type);
  2955. i64 entry_align = type_align_of (map_type->Map.entry_type);
  2956. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  2957. i64 value_size = type_size_of (map_type->Map.value);
  2958. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 2), ir_const_int(entry_size));
  2959. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 3), ir_const_int(entry_align));
  2960. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 4), ir_const_uintptr(value_offset));
  2961. ir_emit_store(proc, ir_emit_struct_ep(proc, h, 5), ir_const_int(value_size));
  2962. return ir_emit_load(proc, h);
  2963. }
  2964. irValue *ir_gen_map_key(irProcedure *proc, irValue *key, Type *key_type) {
  2965. Type *hash_type = t_u64;
  2966. irValue *v = ir_add_local_generated(proc, t_map_key, true);
  2967. Type *t = base_type(ir_type(key));
  2968. key = ir_emit_conv(proc, key, key_type);
  2969. if (is_type_integer(t)) {
  2970. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, key, hash_type));
  2971. } else if (is_type_enum(t)) {
  2972. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, key, hash_type));
  2973. } else if (is_type_typeid(t)) {
  2974. irValue *i = ir_emit_bitcast(proc, key, t_uint);
  2975. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, i, hash_type));
  2976. } else if (is_type_pointer(t)) {
  2977. irValue *p = ir_emit_conv(proc, key, t_uintptr);
  2978. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, p, hash_type));
  2979. } else if (is_type_float(t)) {
  2980. irValue *bits = nullptr;
  2981. i64 size = type_size_of(t);
  2982. switch (8*size) {
  2983. case 32: bits = ir_emit_transmute(proc, key, t_u32); break;
  2984. case 64: bits = ir_emit_transmute(proc, key, t_u64); break;
  2985. default: GB_PANIC("Unhandled float size: %lld bits", size); break;
  2986. }
  2987. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), ir_emit_conv(proc, bits, hash_type));
  2988. } else if (is_type_string(t)) {
  2989. irValue *str = ir_emit_conv(proc, key, t_string);
  2990. irValue *hashed_str = nullptr;
  2991. if (str->kind == irValue_Constant) {
  2992. ExactValue ev = str->Constant.value;
  2993. GB_ASSERT(ev.kind == ExactValue_String);
  2994. u64 hs = fnv64a(ev.value_string.text, ev.value_string.len);
  2995. hashed_str = ir_value_constant(t_u64, exact_value_u64(hs));
  2996. } else {
  2997. auto args = array_make<irValue *>(ir_allocator(), 1);
  2998. args[0] = str;
  2999. hashed_str = ir_emit_runtime_call(proc, "default_hash_string", args);
  3000. }
  3001. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 0), hashed_str);
  3002. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), str);
  3003. } else {
  3004. GB_PANIC("Unhandled map key type");
  3005. }
  3006. return ir_emit_load(proc, v);
  3007. }
  3008. // NOTE(bill): Returns nullptr if not possible
  3009. irValue *ir_address_from_load_or_generate_local(irProcedure *proc, irValue *val) {
  3010. if (val->kind == irValue_Instr) {
  3011. if (val->Instr.kind == irInstr_Load) {
  3012. return val->Instr.Load.address;
  3013. }
  3014. }
  3015. Type *type = ir_type(val);
  3016. irValue *local = ir_add_local_generated(proc, type, false);
  3017. ir_emit_store(proc, local, val);
  3018. return local;
  3019. }
  3020. irValue *ir_address_from_load(irProcedure *proc, irValue *val) {
  3021. if (val->kind == irValue_Instr) {
  3022. if (val->Instr.kind == irInstr_Load) {
  3023. return val->Instr.Load.address;
  3024. }
  3025. }
  3026. GB_PANIC("ir_address_from_load");
  3027. return nullptr;
  3028. }
  3029. Type *ir_addr_type(irAddr const &addr) {
  3030. if (addr.addr == nullptr) {
  3031. return nullptr;
  3032. }
  3033. if (addr.kind == irAddr_Map) {
  3034. Type *t = base_type(addr.map_type);
  3035. GB_ASSERT(is_type_map(t));
  3036. return t->Map.value;
  3037. }
  3038. Type *t = ir_type(addr.addr);
  3039. GB_ASSERT(is_type_pointer(t));
  3040. return type_deref(t);
  3041. }
  3042. irValue *ir_emit_source_code_location(irProcedure *proc, String procedure, TokenPos pos);
  3043. irValue *ir_emit_source_code_location(irProcedure *proc, Ast *node);
  3044. irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset);
  3045. irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type);
  3046. irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel);
  3047. void ir_emit_bounds_check(irProcedure *proc, Token token, irValue *index, irValue *len);
  3048. irValue *ir_insert_dynamic_map_key_and_value(irProcedure *proc, irValue *addr, Type *map_type,
  3049. irValue *map_key, irValue *map_value, Ast *node) {
  3050. map_type = base_type(map_type);
  3051. irValue *h = ir_gen_map_header(proc, addr, map_type);
  3052. irValue *key = ir_gen_map_key(proc, map_key, map_type->Map.key);
  3053. irValue *v = ir_emit_conv(proc, map_value, map_type->Map.value);
  3054. irValue *ptr = ir_add_local_generated(proc, ir_type(v), false);
  3055. ir_emit_store(proc, ptr, v);
  3056. auto args = array_make<irValue *>(ir_allocator(), 4);
  3057. args[0] = h;
  3058. args[1] = key;
  3059. args[2] = ir_emit_conv(proc, ptr, t_rawptr);
  3060. args[3] = ir_emit_source_code_location(proc, node);
  3061. return ir_emit_runtime_call(proc, "__dynamic_map_set", args);
  3062. }
  3063. irValue *ir_soa_struct_len(irProcedure *proc, irValue *value) {
  3064. Type *t = base_type(ir_type(value));
  3065. bool is_ptr = false;
  3066. if (is_type_pointer(t)) {
  3067. is_ptr = true;
  3068. t = base_type(type_deref(t));
  3069. }
  3070. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3071. return ir_const_int(t->Struct.soa_count);
  3072. }
  3073. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  3074. t->Struct.soa_kind == StructSoa_Dynamic);
  3075. isize n = 0;
  3076. Type *elem = base_type(t->Struct.soa_elem);
  3077. if (elem->kind == Type_Struct) {
  3078. n = elem->Struct.fields.count;
  3079. } else if (elem->kind == Type_Array) {
  3080. n = elem->Array.count;
  3081. } else {
  3082. GB_PANIC("Unreachable");
  3083. }
  3084. if (is_ptr) {
  3085. irValue *v = ir_emit_struct_ep(proc, value, cast(i32)n);
  3086. return ir_emit_load(proc, v);
  3087. }
  3088. return ir_emit_struct_ev(proc, value, cast(i32)n);
  3089. }
  3090. irValue *ir_soa_struct_cap(irProcedure *proc, irValue *value) {
  3091. Type *t = base_type(ir_type(value));
  3092. bool is_ptr = false;
  3093. if (is_type_pointer(t)) {
  3094. is_ptr = true;
  3095. t = base_type(type_deref(t));
  3096. }
  3097. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3098. return ir_const_int(t->Struct.soa_count);
  3099. }
  3100. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  3101. isize n = 0;
  3102. Type *elem = base_type(t->Struct.soa_elem);
  3103. if (elem->kind == Type_Struct) {
  3104. n = elem->Struct.fields.count+1;
  3105. } else if (elem->kind == Type_Array) {
  3106. n = elem->Array.count+1;
  3107. } else {
  3108. GB_PANIC("Unreachable");
  3109. }
  3110. if (is_ptr) {
  3111. irValue *v = ir_emit_struct_ep(proc, value, cast(i32)n);
  3112. return ir_emit_load(proc, v);
  3113. }
  3114. return ir_emit_struct_ev(proc, value, cast(i32)n);
  3115. }
  3116. irValue *ir_addr_load(irProcedure *proc, irAddr const &addr);
  3117. void ir_addr_store(irProcedure *proc, irAddr addr, irValue *value) {
  3118. if (addr.addr == nullptr) {
  3119. return;
  3120. }
  3121. if (addr.kind == irAddr_RelativePointer && addr.relative.deref) {
  3122. addr = ir_addr(ir_address_from_load(proc, ir_addr_load(proc, addr)));
  3123. }
  3124. if (addr.kind == irAddr_RelativePointer) {
  3125. Type *rel_ptr = base_type(ir_addr_type(addr));
  3126. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  3127. value = ir_emit_conv(proc, value, rel_ptr->RelativePointer.pointer_type);
  3128. GB_ASSERT(is_type_pointer(ir_type(addr.addr)));
  3129. irValue *ptr = ir_emit_conv(proc, addr.addr, t_uintptr);
  3130. irValue *val_ptr = ir_emit_conv(proc, value, t_uintptr);
  3131. irValue *offset = offset = ir_emit_arith(proc, Token_Sub, val_ptr, ptr, t_uintptr);
  3132. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  3133. offset = ir_emit_conv(proc, offset, t_i64);
  3134. }
  3135. offset = ir_emit_conv(proc, offset, rel_ptr->RelativePointer.base_integer);
  3136. irValue *offset_ptr = ir_emit_conv(proc, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  3137. offset = ir_emit_select(proc,
  3138. ir_emit_comp(proc, Token_CmpEq, val_ptr, ir_value_nil(t_uintptr)),
  3139. ir_value_nil(rel_ptr->RelativePointer.base_integer),
  3140. offset
  3141. );
  3142. ir_emit_store(proc, offset_ptr, offset);
  3143. return;
  3144. } else if (addr.kind == irAddr_RelativeSlice) {
  3145. Type *rel_ptr = base_type(ir_addr_type(addr));
  3146. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  3147. value = ir_emit_conv(proc, value, rel_ptr->RelativeSlice.slice_type);
  3148. GB_ASSERT(is_type_pointer(ir_type(addr.addr)));
  3149. irValue *ptr = ir_emit_conv(proc, ir_emit_struct_ep(proc, addr.addr, 0), t_uintptr);
  3150. irValue *val_ptr = ir_emit_conv(proc, ir_slice_elem(proc, value), t_uintptr);
  3151. irValue *offset = ir_emit_arith(proc, Token_Sub, val_ptr, ptr, t_uintptr);
  3152. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  3153. offset = ir_emit_conv(proc, offset, t_i64);
  3154. }
  3155. offset = ir_emit_conv(proc, offset, rel_ptr->RelativePointer.base_integer);
  3156. irValue *offset_ptr = ir_emit_conv(proc, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  3157. offset = ir_emit_select(proc,
  3158. ir_emit_comp(proc, Token_CmpEq, val_ptr, ir_value_nil(t_uintptr)),
  3159. ir_value_nil(rel_ptr->RelativePointer.base_integer),
  3160. offset
  3161. );
  3162. ir_emit_store(proc, offset_ptr, offset);
  3163. irValue *len = ir_slice_len(proc, value);
  3164. len = ir_emit_conv(proc, len, rel_ptr->RelativePointer.base_integer);
  3165. irValue *len_ptr = ir_emit_struct_ep(proc, addr.addr, 1);
  3166. ir_emit_store(proc, len_ptr, len);
  3167. return;
  3168. } else if (addr.kind == irAddr_Map) {
  3169. ir_insert_dynamic_map_key_and_value(proc, addr.addr, addr.map_type, addr.map_key, value, proc->curr_stmt);
  3170. return;
  3171. } else if (addr.kind == irAddr_BitField) {
  3172. gbAllocator a = ir_allocator();
  3173. Type *bft = base_type(type_deref(ir_type(addr.addr)));
  3174. GB_ASSERT(is_type_bit_field(bft));
  3175. i32 value_index = addr.bit_field_value_index;
  3176. i32 offset = bft->BitField.offsets[value_index];
  3177. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  3178. i32 byte_index = offset / 8;
  3179. i32 bit_inset = offset % 8;
  3180. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  3181. if (size_in_bytes == 0) {
  3182. GB_ASSERT(size_in_bits == 0);
  3183. return;
  3184. }
  3185. Type *int_type = nullptr;
  3186. switch (size_in_bytes) {
  3187. case 1: int_type = t_u8; break;
  3188. case 2: int_type = t_u16; break;
  3189. case 4: int_type = t_u32; break;
  3190. case 8: int_type = t_u64; break;
  3191. }
  3192. GB_ASSERT(int_type != nullptr);
  3193. value = ir_emit_conv(proc, value, int_type);
  3194. irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
  3195. bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(byte_index));
  3196. if (bit_inset == 0) {
  3197. irValue *v = value;
  3198. i32 sa = 8*size_in_bytes - size_in_bits;
  3199. if (sa > 0) {
  3200. irValue *shift_amount = ir_const_int(sa);
  3201. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  3202. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  3203. }
  3204. irValue *ptr = ir_emit_conv(proc, bytes, alloc_type_pointer(int_type));
  3205. irValue *sv = ir_emit_load(proc, ptr, 1);
  3206. // NOTE(bill): Zero out the lower bits that need to be stored to
  3207. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(size_in_bits), int_type);
  3208. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(size_in_bits), int_type);
  3209. v = ir_emit_arith(proc, Token_Or, sv, v, int_type);
  3210. ir_emit_store(proc, ptr, v, true);
  3211. return;
  3212. }
  3213. GB_ASSERT(0 < bit_inset && bit_inset < 8);
  3214. // First byte
  3215. {
  3216. irValue *shift_amount = ir_const_int(bit_inset);
  3217. irValue *ptr = ir_emit_conv(proc, bytes, alloc_type_pointer(t_u8));
  3218. irValue *v = ir_emit_conv(proc, value, t_u8);
  3219. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, t_u8);
  3220. irValue *sv = ir_emit_load(proc, bytes, 1);
  3221. // NOTE(bill): Zero out the upper bits that need to be stored to
  3222. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(8-bit_inset), t_u8);
  3223. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(8-bit_inset), t_u8);
  3224. v = ir_emit_arith(proc, Token_Or, sv, v, t_u8);
  3225. ir_emit_store(proc, ptr, v, true);
  3226. }
  3227. // Remaining bytes
  3228. if (bit_inset+size_in_bits > 8) {
  3229. irValue *ptr = ir_emit_conv(proc, ir_emit_ptr_offset(proc, bytes, v_one), alloc_type_pointer(int_type));
  3230. irValue *v = ir_emit_conv(proc, value, int_type);
  3231. v = ir_emit_arith(proc, Token_Shr, v, ir_const_int(8-bit_inset), int_type);
  3232. irValue *sv = ir_emit_load(proc, ptr, 1);
  3233. // NOTE(bill): Zero out the lower bits that need to be stored to
  3234. sv = ir_emit_arith(proc, Token_Shr, sv, ir_const_int(size_in_bits-bit_inset), int_type);
  3235. sv = ir_emit_arith(proc, Token_Shl, sv, ir_const_int(size_in_bits-bit_inset), int_type);
  3236. v = ir_emit_arith(proc, Token_Or, sv, v, int_type);
  3237. ir_emit_store(proc, ptr, v, true);
  3238. }
  3239. return;
  3240. } else if (addr.kind == irAddr_Context) {
  3241. irValue *old = ir_emit_load(proc, ir_find_or_generate_context_ptr(proc));
  3242. irValue *next = ir_add_local_generated(proc, t_context, true);
  3243. ir_emit_store(proc, next, old);
  3244. ir_push_context_onto_stack(proc, next);
  3245. if (addr.ctx.sel.index.count > 0) {
  3246. irValue *lhs = ir_emit_deep_field_gep(proc, next, addr.ctx.sel);
  3247. irValue *rhs = ir_emit_conv(proc, value, type_deref(ir_type(lhs)));
  3248. ir_emit_store(proc, lhs, rhs);
  3249. } else {
  3250. irValue *lhs = next;
  3251. irValue *rhs = ir_emit_conv(proc, value, ir_addr_type(addr));
  3252. ir_emit_store(proc, lhs, rhs);
  3253. }
  3254. return;
  3255. } else if (addr.kind == irAddr_SoaVariable) {
  3256. Type *t = type_deref(ir_type(addr.addr));
  3257. t = base_type(t);
  3258. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  3259. value = ir_emit_conv(proc, value, t->Struct.soa_elem);
  3260. irValue *index = addr.soa.index;
  3261. if (index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) {
  3262. Type *t = base_type(type_deref(ir_type(addr.addr)));
  3263. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  3264. i64 count = t->Struct.soa_count;
  3265. irValue *len = ir_const_int(count);
  3266. ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), index, len);
  3267. }
  3268. for_array(i, t->Struct.fields) {
  3269. irValue *dst = ir_emit_struct_ep(proc, addr.addr, cast(i32)i);
  3270. dst = ir_emit_array_ep(proc, dst, index);
  3271. irValue *src = ir_emit_struct_ev(proc, value, cast(i32)i);
  3272. ir_emit_store(proc, dst, src);
  3273. }
  3274. return;
  3275. }
  3276. irValue *v = ir_emit_conv(proc, value, ir_addr_type(addr));
  3277. ir_emit_store(proc, addr.addr, v);
  3278. }
  3279. irValue *ir_addr_load(irProcedure *proc, irAddr const &addr) {
  3280. if (addr.addr == nullptr) {
  3281. GB_PANIC("Illegal addr load");
  3282. return nullptr;
  3283. }
  3284. if (addr.kind == irAddr_RelativePointer) {
  3285. Type *rel_ptr = base_type(ir_addr_type(addr));
  3286. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  3287. irValue *ptr = ir_emit_conv(proc, addr.addr, t_uintptr);
  3288. irValue *offset = ir_emit_conv(proc, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  3289. offset = ir_emit_load(proc, offset);
  3290. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  3291. offset = ir_emit_conv(proc, offset, t_i64);
  3292. }
  3293. offset = ir_emit_conv(proc, offset, t_uintptr);
  3294. irValue *absolute_ptr = ir_emit_arith(proc, Token_Add, ptr, offset, t_uintptr);
  3295. absolute_ptr = ir_emit_conv(proc, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  3296. irValue *cond = ir_emit_comp(proc, Token_CmpEq, offset, ir_value_nil(rel_ptr->RelativePointer.base_integer));
  3297. // NOTE(bill): nil check
  3298. irValue *nil_ptr = ir_value_nil(rel_ptr->RelativePointer.pointer_type);
  3299. irValue *final_ptr = ir_emit_select(proc, cond, nil_ptr, absolute_ptr);
  3300. return ir_emit_load(proc, final_ptr);
  3301. } else if (addr.kind == irAddr_RelativeSlice) {
  3302. Type *rel_ptr = base_type(ir_addr_type(addr));
  3303. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  3304. irValue *offset_ptr = ir_emit_struct_ep(proc, addr.addr, 0);
  3305. irValue *ptr = ir_emit_conv(proc, offset_ptr, t_uintptr);
  3306. irValue *offset = ir_emit_load(proc, offset_ptr);
  3307. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  3308. offset = ir_emit_conv(proc, offset, t_i64);
  3309. }
  3310. offset = ir_emit_conv(proc, offset, t_uintptr);
  3311. irValue *absolute_ptr = ir_emit_arith(proc, Token_Add, ptr, offset, t_uintptr);
  3312. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  3313. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  3314. Type *slice_elem = slice_type->Slice.elem;
  3315. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  3316. absolute_ptr = ir_emit_conv(proc, absolute_ptr, slice_elem_ptr);
  3317. irValue *cond = ir_emit_comp(proc, Token_CmpEq, offset, ir_value_nil(rel_ptr->RelativeSlice.base_integer));
  3318. // NOTE(bill): nil check
  3319. irValue *nil_ptr = ir_value_nil(slice_elem_ptr);
  3320. irValue *data = ir_emit_select(proc, cond, nil_ptr, absolute_ptr);
  3321. irValue *len = ir_emit_load(proc, ir_emit_struct_ep(proc, addr.addr, 1));
  3322. len = ir_emit_conv(proc, len, t_int);
  3323. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  3324. ir_fill_slice(proc, slice, data, len);
  3325. return ir_emit_load(proc, slice);
  3326. } else if (addr.kind == irAddr_Map) {
  3327. Type *map_type = base_type(addr.map_type);
  3328. irValue *v = ir_add_local_generated(proc, map_type->Map.lookup_result_type, true);
  3329. irValue *h = ir_gen_map_header(proc, addr.addr, map_type);
  3330. irValue *key = ir_gen_map_key(proc, addr.map_key, map_type->Map.key);
  3331. auto args = array_make<irValue *>(ir_allocator(), 2);
  3332. args[0] = h;
  3333. args[1] = key;
  3334. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  3335. irValue *ok = ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, ptr, v_raw_nil), t_bool);
  3336. ir_emit_store(proc, ir_emit_struct_ep(proc, v, 1), ok);
  3337. irBlock *then = ir_new_block(proc, nullptr, "map.get.then");
  3338. irBlock *done = ir_new_block(proc, nullptr, "map.get.done");
  3339. ir_emit_if(proc, ok, then, done);
  3340. ir_start_block(proc, then);
  3341. {
  3342. // TODO(bill): mem copy it instead?
  3343. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  3344. irValue *value = ir_emit_conv(proc, ptr, ir_type(gep0));
  3345. ir_emit_store(proc, gep0, ir_emit_load(proc, value));
  3346. }
  3347. ir_emit_jump(proc, done);
  3348. ir_start_block(proc, done);
  3349. if (is_type_tuple(addr.map_result)) {
  3350. return ir_emit_load(proc, v);
  3351. } else {
  3352. irValue *single = ir_emit_struct_ep(proc, v, 0);
  3353. return ir_emit_load(proc, single);
  3354. }
  3355. } else if (addr.kind == irAddr_BitField) {
  3356. gbAllocator a = ir_allocator();
  3357. Type *bft = base_type(type_deref(ir_type(addr.addr)));
  3358. GB_ASSERT(is_type_bit_field(bft));
  3359. i32 value_index = addr.bit_field_value_index;
  3360. i32 offset = bft->BitField.offsets[value_index];
  3361. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  3362. i32 byte_index = offset / 8;
  3363. i32 bit_inset = offset % 8;
  3364. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  3365. if (size_in_bytes == 0) {
  3366. GB_ASSERT(size_in_bits == 0);
  3367. return v_zero32;
  3368. }
  3369. Type *int_type = nullptr;
  3370. switch (size_in_bytes) {
  3371. case 1: int_type = t_u8; break;
  3372. case 2: int_type = t_u16; break;
  3373. case 4: int_type = t_u32; break;
  3374. case 8: int_type = t_u64; break;
  3375. }
  3376. GB_ASSERT(int_type != nullptr);
  3377. irValue *bytes = ir_emit_conv(proc, addr.addr, t_u8_ptr);
  3378. bytes = ir_emit_ptr_offset(proc, bytes, ir_const_int(byte_index));
  3379. Type *int_ptr = alloc_type_pointer(int_type);
  3380. i32 sa = 8*size_in_bytes - size_in_bits;
  3381. if (bit_inset == 0) {
  3382. irValue *v = ir_emit_load(proc, ir_emit_conv(proc, bytes, int_ptr), 1);
  3383. if (sa > 0) {
  3384. irValue *shift_amount = ir_const_int(sa);
  3385. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  3386. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  3387. }
  3388. return v;
  3389. }
  3390. GB_ASSERT(8 > bit_inset);
  3391. irValue *ptr = ir_emit_conv(proc, bytes, int_ptr);
  3392. irValue *v = ir_emit_load(proc, ptr, 1);
  3393. v = ir_emit_arith(proc, Token_Shr, v, ir_const_int(bit_inset), int_type);
  3394. if (sa > 0) {
  3395. irValue *shift_amount = ir_const_int(sa);
  3396. v = ir_emit_arith(proc, Token_Shl, v, shift_amount, int_type);
  3397. v = ir_emit_arith(proc, Token_Shr, v, shift_amount, int_type);
  3398. }
  3399. return v;
  3400. } else if (addr.kind == irAddr_Context) {
  3401. if (addr.ctx.sel.index.count > 0) {
  3402. irValue *a = addr.addr;
  3403. irValue *b = ir_emit_deep_field_gep(proc, a, addr.ctx.sel);
  3404. return ir_emit_load(proc, b);
  3405. }
  3406. } else if (addr.kind == irAddr_SoaVariable) {
  3407. Type *t = type_deref(ir_type(addr.addr));
  3408. t = base_type(t);
  3409. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  3410. Type *elem = t->Struct.soa_elem;
  3411. irValue *len = nullptr;
  3412. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3413. len = ir_const_int(t->Struct.soa_count);
  3414. } else {
  3415. irValue *v = ir_emit_load(proc, addr.addr);
  3416. len = ir_soa_struct_len(proc, v);
  3417. }
  3418. irValue *res = ir_add_local_generated(proc, elem, true);
  3419. if (addr.soa.index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) {
  3420. ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), addr.soa.index, len);
  3421. }
  3422. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3423. for_array(i, t->Struct.fields) {
  3424. Entity *field = t->Struct.fields[i];
  3425. Type *base_type = field->type;
  3426. GB_ASSERT(base_type->kind == Type_Array);
  3427. irValue *dst = ir_emit_struct_ep(proc, res, cast(i32)i);
  3428. irValue *src_ptr = ir_emit_struct_ep(proc, addr.addr, cast(i32)i);
  3429. src_ptr = ir_emit_array_ep(proc, src_ptr, addr.soa.index);
  3430. irValue *src = ir_emit_load(proc, src_ptr);
  3431. ir_emit_store(proc, dst, src);
  3432. }
  3433. } else {
  3434. isize field_count = t->Struct.fields.count;
  3435. if (t->Struct.soa_kind == StructSoa_Slice) {
  3436. field_count -= 1;
  3437. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  3438. field_count -= 3;
  3439. }
  3440. for (isize i = 0; i < field_count; i++) {
  3441. Entity *field = t->Struct.fields[i];
  3442. Type *base_type = field->type;
  3443. GB_ASSERT(base_type->kind == Type_Pointer);
  3444. Type *elem = base_type->Pointer.elem;
  3445. irValue *dst = ir_emit_struct_ep(proc, res, cast(i32)i);
  3446. irValue *src_ptr = ir_emit_struct_ep(proc, addr.addr, cast(i32)i);
  3447. src_ptr = ir_emit_ptr_offset(proc, src_ptr, addr.soa.index);
  3448. irValue *src = ir_emit_load(proc, src_ptr);
  3449. src = ir_emit_load(proc, src);
  3450. ir_emit_store(proc, dst, src);
  3451. }
  3452. }
  3453. return ir_emit_load(proc, res);
  3454. }
  3455. Type *t = base_type(ir_type(addr.addr));
  3456. if (t->kind == Type_Proc) {
  3457. // NOTE(bill): Imported procedures don't require a load as they are pointers
  3458. return addr.addr;
  3459. }
  3460. return ir_emit_load(proc, addr.addr);
  3461. }
  3462. irValue *ir_addr_get_ptr(irProcedure *proc, irAddr const &addr, bool allow_reference=false) {
  3463. if (addr.addr == nullptr) {
  3464. GB_PANIC("Illegal addr -> nullptr");
  3465. return nullptr;
  3466. }
  3467. switch (addr.kind) {
  3468. case irAddr_Map: {
  3469. if (allow_reference) {
  3470. Type *map_type = base_type(addr.map_type);
  3471. irValue *h = ir_gen_map_header(proc, addr.addr, map_type);
  3472. irValue *key = ir_gen_map_key(proc, addr.map_key, map_type->Map.key);
  3473. auto args = array_make<irValue *>(ir_allocator(), 2);
  3474. args[0] = h;
  3475. args[1] = key;
  3476. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  3477. return ir_emit_conv(proc, ptr, alloc_type_pointer(map_type->Map.value));
  3478. } else {
  3479. irValue *v = ir_addr_load(proc, addr);
  3480. return ir_address_from_load_or_generate_local(proc, v);
  3481. }
  3482. }
  3483. case irAddr_BitField: {
  3484. irValue *v = ir_addr_load(proc, addr);
  3485. return ir_address_from_load_or_generate_local(proc, v);
  3486. }
  3487. case irAddr_Context:
  3488. GB_PANIC("irAddr_Context should be handled elsewhere");
  3489. }
  3490. return addr.addr;
  3491. }
  3492. irValue *ir_build_addr_ptr(irProcedure *proc, Ast *expr) {
  3493. irAddr addr = ir_build_addr(proc, expr);
  3494. return ir_addr_get_ptr(proc, addr);
  3495. }
  3496. irValue *ir_dynamic_array_len(irProcedure *proc, irValue *da);
  3497. irValue *ir_dynamic_array_cap(irProcedure *proc, irValue *da);
  3498. irValue *ir_map_entries(irProcedure *proc, irValue *value) {
  3499. gbAllocator a = ir_allocator();
  3500. Type *t = base_type(ir_type(value));
  3501. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  3502. init_map_internal_types(t);
  3503. Type *gst = t->Map.generated_struct_type;
  3504. i32 index = 1;
  3505. irValue *entries = ir_emit(proc, ir_instr_struct_extract_value(proc, value, index, gst->Struct.fields[index]->type));
  3506. return entries;
  3507. }
  3508. irValue *ir_map_entries_ptr(irProcedure *proc, irValue *value) {
  3509. gbAllocator a = ir_allocator();
  3510. Type *t = base_type(type_deref(ir_type(value)));
  3511. if (is_type_pointer(t)) {
  3512. value = ir_emit_load(proc, value);
  3513. t = base_type(type_deref(t));
  3514. }
  3515. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  3516. init_map_internal_types(t);
  3517. Type *gst = t->Map.generated_struct_type;
  3518. i32 index = 1;
  3519. Type *ptr_t = alloc_type_pointer(gst->Struct.fields[index]->type);
  3520. irValue *entries = ir_emit(proc, ir_instr_struct_element_ptr(proc, value, index, ptr_t));
  3521. return entries;
  3522. }
  3523. irValue *ir_map_len(irProcedure *proc, irValue *value) {
  3524. irValue *entries = ir_map_entries(proc, value);
  3525. return ir_dynamic_array_len(proc, entries);
  3526. }
  3527. irValue *ir_map_cap(irProcedure *proc, irValue *value) {
  3528. irValue *entries = ir_map_entries(proc, value);
  3529. return ir_dynamic_array_cap(proc, entries);
  3530. }
  3531. struct irLoopData {
  3532. irValue *idx_addr;
  3533. irValue *idx;
  3534. irBlock *body;
  3535. irBlock *done;
  3536. irBlock *loop;
  3537. };
  3538. irLoopData ir_loop_start(irProcedure *proc, isize count, Type *index_type=t_int) {
  3539. irLoopData data = {};
  3540. irValue *max = ir_const_int(count);
  3541. data.idx_addr = ir_add_local_generated(proc, index_type, true);
  3542. data.body = ir_new_block(proc, nullptr, "loop.body");
  3543. data.done = ir_new_block(proc, nullptr, "loop.done");
  3544. data.loop = ir_new_block(proc, nullptr, "loop.loop");
  3545. ir_emit_jump(proc, data.loop);
  3546. ir_start_block(proc, data.loop);
  3547. data.idx = ir_emit_load(proc, data.idx_addr);
  3548. irValue *cond = ir_emit_comp(proc, Token_Lt, data.idx, max);
  3549. ir_emit_if(proc, cond, data.body, data.done);
  3550. ir_start_block(proc, data.body);
  3551. return data;
  3552. }
  3553. void ir_loop_end(irProcedure *proc, irLoopData const &data) {
  3554. if (data.idx_addr != nullptr) {
  3555. ir_emit_increment(proc, data.idx_addr);
  3556. ir_emit_jump(proc, data.loop);
  3557. ir_start_block(proc, data.done);
  3558. }
  3559. }
  3560. irValue *ir_emit_ptr_offset(irProcedure *proc, irValue *ptr, irValue *offset) {
  3561. offset = ir_emit_conv(proc, offset, t_int);
  3562. return ir_emit(proc, ir_instr_ptr_offset(proc, ptr, offset));
  3563. }
  3564. irValue *ir_emit_unary_arith(irProcedure *proc, TokenKind op, irValue *x, Type *type) {
  3565. switch (op) {
  3566. case Token_Add:
  3567. return x;
  3568. case Token_Not: // Boolean not
  3569. case Token_Xor: // Bitwise not
  3570. case Token_Sub: // Bitwise Not
  3571. break;
  3572. case Token_Pointer:
  3573. GB_PANIC("This should be handled elsewhere");
  3574. break;
  3575. }
  3576. if (is_type_array(ir_type(x))) {
  3577. ir_emit_comment(proc, str_lit("array.arith.begin"));
  3578. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3579. Type *tl = base_type(ir_type(x));
  3580. irValue *val = ir_address_from_load_or_generate_local(proc, x);
  3581. GB_ASSERT(is_type_array(type));
  3582. Type *elem_type = base_array_type(type);
  3583. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3584. irValue *res = ir_add_local_generated(proc, type, false);
  3585. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3586. i32 count = cast(i32)tl->Array.count;
  3587. if (inline_array_arith) {
  3588. // inline
  3589. for (i32 i = 0; i < count; i++) {
  3590. irValue *e = ir_emit_load(proc, ir_emit_array_epi(proc, val, i));
  3591. irValue *z = ir_emit_unary_arith(proc, op, e, elem_type);
  3592. ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
  3593. }
  3594. } else {
  3595. auto loop_data = ir_loop_start(proc, count, t_i32);
  3596. irValue *e = ir_emit_load(proc, ir_emit_array_ep(proc, val, loop_data.idx));
  3597. irValue *z = ir_emit_unary_arith(proc, op, e, elem_type);
  3598. ir_emit_store(proc, ir_emit_array_ep(proc, res, loop_data.idx), z);
  3599. ir_loop_end(proc, loop_data);
  3600. }
  3601. ir_emit_comment(proc, str_lit("array.arith.end"));
  3602. return ir_emit_load(proc, res);
  3603. }
  3604. if (op == Token_Not) {
  3605. irValue *cmp = ir_emit_comp(proc, Token_CmpEq, x, v_false);
  3606. return ir_emit_conv(proc, cmp, type);
  3607. }
  3608. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3609. Type *platform_type = integer_endian_type_to_platform_type(type);
  3610. irValue *v = ir_emit_byte_swap(proc, x, platform_type);
  3611. irValue *res = ir_emit(proc, ir_instr_unary_op(proc, op, v, platform_type));
  3612. return ir_emit_byte_swap(proc, res, type);
  3613. }
  3614. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  3615. Type *platform_type = integer_endian_type_to_platform_type(type);
  3616. irValue *v = ir_emit_byte_swap(proc, x, platform_type);
  3617. irValue *res = ir_emit(proc, ir_instr_unary_op(proc, op, v, platform_type));
  3618. return ir_emit_byte_swap(proc, res, type);
  3619. }
  3620. if (op == Token_Sub) {
  3621. if (is_type_integer(ir_type(x))) {
  3622. return ir_emit(proc, ir_instr_unary_op(proc, op, x, type));
  3623. } else if (is_type_float(ir_type(x))) {
  3624. return ir_emit(proc, ir_instr_unary_op(proc, op, x, type));
  3625. } else if (is_type_complex(ir_type(x))) {
  3626. irValue *addr = ir_add_local_generated(proc, ir_type(x), false);
  3627. irValue *v0 = ir_emit_struct_ev(proc, x, 0);
  3628. irValue *v1 = ir_emit_struct_ev(proc, x, 1);
  3629. v0 = ir_emit(proc, ir_instr_unary_op(proc, op, v0, ir_type(v0)));
  3630. v1 = ir_emit(proc, ir_instr_unary_op(proc, op, v1, ir_type(v1)));
  3631. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 0), v0);
  3632. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 1), v1);
  3633. return ir_emit_load(proc, addr);
  3634. } else if (is_type_quaternion(ir_type(x))) {
  3635. irValue *addr = ir_add_local_generated(proc, ir_type(x), false);
  3636. irValue *v0 = ir_emit_struct_ev(proc, x, 0);
  3637. irValue *v1 = ir_emit_struct_ev(proc, x, 1);
  3638. irValue *v2 = ir_emit_struct_ev(proc, x, 2);
  3639. irValue *v3 = ir_emit_struct_ev(proc, x, 3);
  3640. v0 = ir_emit(proc, ir_instr_unary_op(proc, op, v0, ir_type(v0)));
  3641. v1 = ir_emit(proc, ir_instr_unary_op(proc, op, v1, ir_type(v1)));
  3642. v2 = ir_emit(proc, ir_instr_unary_op(proc, op, v2, ir_type(v2)));
  3643. v3 = ir_emit(proc, ir_instr_unary_op(proc, op, v3, ir_type(v3)));
  3644. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 0), v0);
  3645. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 1), v1);
  3646. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 2), v2);
  3647. ir_emit_store(proc, ir_emit_struct_ep(proc, addr, 3), v3);
  3648. return ir_emit_load(proc, addr);
  3649. }
  3650. }
  3651. return ir_emit(proc, ir_instr_unary_op(proc, op, x, type));
  3652. }
  3653. irValue *ir_emit_arith(irProcedure *proc, TokenKind op, irValue *left, irValue *right, Type *type) {
  3654. Type *t_left = ir_type(left);
  3655. Type *t_right = ir_type(right);
  3656. if (is_type_array(t_left) || is_type_array(t_right)) {
  3657. ir_emit_comment(proc, str_lit("array.arith.begin"));
  3658. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3659. left = ir_emit_conv(proc, left, type);
  3660. right = ir_emit_conv(proc, right, type);
  3661. irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
  3662. irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
  3663. GB_ASSERT(is_type_array(type));
  3664. Type *elem_type = base_array_type(type);
  3665. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3666. irValue *res = ir_add_local_generated(proc, type, false);
  3667. i64 count = base_type(type)->Array.count;
  3668. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3669. if (inline_array_arith) {
  3670. // inline
  3671. for (i32 i = 0; i < count; i++) {
  3672. irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
  3673. irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
  3674. irValue *z = ir_emit_arith(proc, op, x, y, elem_type);
  3675. ir_emit_store(proc, ir_emit_array_epi(proc, res, i), z);
  3676. }
  3677. } else {
  3678. auto loop_data = ir_loop_start(proc, count, t_i32);
  3679. irValue *x = ir_emit_load(proc, ir_emit_array_ep(proc, lhs, loop_data.idx));
  3680. irValue *y = ir_emit_load(proc, ir_emit_array_ep(proc, rhs, loop_data.idx));
  3681. irValue *z = ir_emit_arith(proc, op, x, y, elem_type);
  3682. ir_emit_store(proc, ir_emit_array_ep(proc, res, loop_data.idx), z);
  3683. ir_loop_end(proc, loop_data);
  3684. }
  3685. ir_emit_comment(proc, str_lit("array.arith.end"));
  3686. return ir_emit_load(proc, res);
  3687. }
  3688. if (is_type_complex(t_left)) {
  3689. ir_emit_comment(proc, str_lit("complex.arith.begin"));
  3690. defer (ir_emit_comment(proc, str_lit("complex.arith.end")));
  3691. Type *ft = base_complex_elem_type(t_left);
  3692. if (op == Token_Quo) {
  3693. auto args = array_make<irValue *>(heap_allocator(), 2);
  3694. args[0] = left;
  3695. args[1] = right;
  3696. switch (type_size_of(ft)) {
  3697. case 4: return ir_emit_runtime_call(proc, "quo_complex64", args);
  3698. case 8: return ir_emit_runtime_call(proc, "quo_complex128", args);
  3699. default: GB_PANIC("Unknown float type"); break;
  3700. }
  3701. }
  3702. irValue *res = ir_add_local_generated(proc, type, false); // NOTE: initialized in full later
  3703. irValue *a = ir_emit_struct_ev(proc, left, 0);
  3704. irValue *b = ir_emit_struct_ev(proc, left, 1);
  3705. irValue *c = ir_emit_struct_ev(proc, right, 0);
  3706. irValue *d = ir_emit_struct_ev(proc, right, 1);
  3707. irValue *real = nullptr;
  3708. irValue *imag = nullptr;
  3709. switch (op) {
  3710. case Token_Add:
  3711. real = ir_emit_arith(proc, Token_Add, a, c, ft);
  3712. imag = ir_emit_arith(proc, Token_Add, b, d, ft);
  3713. break;
  3714. case Token_Sub:
  3715. real = ir_emit_arith(proc, Token_Sub, a, c, ft);
  3716. imag = ir_emit_arith(proc, Token_Sub, b, d, ft);
  3717. break;
  3718. case Token_Mul: {
  3719. irValue *x = ir_emit_arith(proc, Token_Mul, a, c, ft);
  3720. irValue *y = ir_emit_arith(proc, Token_Mul, b, d, ft);
  3721. real = ir_emit_arith(proc, Token_Sub, x, y, ft);
  3722. irValue *z = ir_emit_arith(proc, Token_Mul, b, c, ft);
  3723. irValue *w = ir_emit_arith(proc, Token_Mul, a, d, ft);
  3724. imag = ir_emit_arith(proc, Token_Add, z, w, ft);
  3725. break;
  3726. }
  3727. }
  3728. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
  3729. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
  3730. return ir_emit_load(proc, res);
  3731. }
  3732. if (is_type_quaternion(t_left)) {
  3733. ir_emit_comment(proc, str_lit("complex.arith.begin"));
  3734. defer (ir_emit_comment(proc, str_lit("complex.arith.end")));
  3735. right = ir_emit_conv(proc, right, t_left);
  3736. Type *ft = base_complex_elem_type(t_left);
  3737. if (op == Token_Add || op == Token_Sub) {
  3738. irValue *res = ir_add_local_generated(proc, type, false); // NOTE: initialized in full later
  3739. irValue *x0 = ir_emit_struct_ev(proc, left, 0);
  3740. irValue *x1 = ir_emit_struct_ev(proc, left, 1);
  3741. irValue *x2 = ir_emit_struct_ev(proc, left, 2);
  3742. irValue *x3 = ir_emit_struct_ev(proc, left, 3);
  3743. irValue *y0 = ir_emit_struct_ev(proc, right, 0);
  3744. irValue *y1 = ir_emit_struct_ev(proc, right, 1);
  3745. irValue *y2 = ir_emit_struct_ev(proc, right, 2);
  3746. irValue *y3 = ir_emit_struct_ev(proc, right, 3);
  3747. irValue *z0 = ir_emit_arith(proc, op, x0, y0, ft);
  3748. irValue *z1 = ir_emit_arith(proc, op, x1, y1, ft);
  3749. irValue *z2 = ir_emit_arith(proc, op, x2, y2, ft);
  3750. irValue *z3 = ir_emit_arith(proc, op, x3, y3, ft);
  3751. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), z0);
  3752. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), z1);
  3753. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 2), z2);
  3754. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 3), z3);
  3755. return ir_emit_load(proc, res);
  3756. } else if (op == Token_Mul) {
  3757. auto args = array_make<irValue *>(heap_allocator(), 2);
  3758. args[0] = left;
  3759. args[1] = right;
  3760. switch (8*type_size_of(ft)) {
  3761. case 32: return ir_emit_runtime_call(proc, "mul_quaternion128", args);
  3762. case 64: return ir_emit_runtime_call(proc, "mul_quaternion256", args);
  3763. default: GB_PANIC("Unknown float type"); break;
  3764. }
  3765. } else if (op == Token_Quo) {
  3766. auto args = array_make<irValue *>(heap_allocator(), 2);
  3767. args[0] = left;
  3768. args[1] = right;
  3769. switch (8*type_size_of(ft)) {
  3770. case 32: return ir_emit_runtime_call(proc, "quo_quaternion128", args);
  3771. case 64: return ir_emit_runtime_call(proc, "quo_quaternion256", args);
  3772. default: GB_PANIC("Unknown float type"); break;
  3773. }
  3774. }
  3775. }
  3776. #if 0
  3777. if (op == Token_Add) {
  3778. if (is_type_pointer(t_left)) {
  3779. irValue *ptr = ir_emit_conv(proc, left, type);
  3780. irValue *offset = right;
  3781. return ir_emit_ptr_offset(proc, ptr, offset);
  3782. } else if (is_type_pointer(ir_type(right))) {
  3783. irValue *ptr = ir_emit_conv(proc, right, type);
  3784. irValue *offset = left;
  3785. return ir_emit_ptr_offset(proc, ptr, offset);
  3786. }
  3787. } else if (op == Token_Sub) {
  3788. if (is_type_pointer(t_left) && is_type_integer(t_right)) {
  3789. // ptr - int
  3790. irValue *ptr = ir_emit_conv(proc, left, type);
  3791. irValue *offset = ir_emit_unary_arith(proc, Token_Sub, right, t_int);
  3792. return ir_emit_ptr_offset(proc, ptr, offset);
  3793. } else if (is_type_pointer(t_left) && is_type_pointer(t_right)) {
  3794. GB_ASSERT(is_type_integer(type));
  3795. irModule *m = proc->module;
  3796. Type *ptr_type = base_type(t_left);
  3797. GB_ASSERT(!is_type_rawptr(ptr_type));
  3798. irValue *elem_size = ir_const_int(type_size_of(ptr_type->Pointer.elem));
  3799. irValue *x = ir_emit_conv(proc, ir_emit_conv(proc, left, t_uintptr), type);
  3800. irValue *y = ir_emit_conv(proc, ir_emit_conv(proc, right, t_uintptr), type);
  3801. irValue *diff = ir_emit_arith(proc, op, x, y, type);
  3802. return ir_emit_arith(proc, Token_Quo, diff, elem_size, type);
  3803. }
  3804. }
  3805. #endif
  3806. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3807. switch (op) {
  3808. case Token_AndNot:
  3809. case Token_And:
  3810. case Token_Or:
  3811. case Token_Xor:
  3812. goto handle_op;
  3813. }
  3814. Type *platform_type = integer_endian_type_to_platform_type(type);
  3815. irValue *x = ir_emit_conv(proc, left, integer_endian_type_to_platform_type(t_left));
  3816. irValue *y = ir_emit_conv(proc, right, integer_endian_type_to_platform_type(t_right));
  3817. irValue *res = ir_emit_arith(proc, op, x, y, platform_type);
  3818. return ir_emit_byte_swap(proc, res, type);
  3819. }
  3820. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  3821. Type *platform_type = integer_endian_type_to_platform_type(type);
  3822. irValue *x = ir_emit_conv(proc, left, integer_endian_type_to_platform_type(t_left));
  3823. irValue *y = ir_emit_conv(proc, right, integer_endian_type_to_platform_type(t_right));
  3824. irValue *res = ir_emit_arith(proc, op, x, y, platform_type);
  3825. return ir_emit_byte_swap(proc, res, type);
  3826. }
  3827. handle_op:
  3828. switch (op) {
  3829. case Token_Shl:
  3830. {
  3831. left = ir_emit_conv(proc, left, type);
  3832. right = ir_emit_conv(proc, right, type);
  3833. ir_emit(proc, ir_instr_binary_op(proc, op, left, right, type));
  3834. irValue *bits = right;
  3835. irValue *max = ir_value_constant(type, exact_value_i64(8*type_size_of(type) - 1));
  3836. irValue *less_equal_width = ir_emit(proc, ir_instr_binary_op(proc, Token_LtEq, bits, max, t_llvm_bool));
  3837. irValue *zero = ir_value_constant(type, exact_value_i64(0));
  3838. irValue *res = ir_emit(proc, ir_instr_binary_op(proc, op, left, bits, type));
  3839. return ir_emit_select(proc, less_equal_width, res, zero);
  3840. }
  3841. case Token_Shr:
  3842. {
  3843. left = ir_emit_conv(proc, left, type);
  3844. right = ir_emit_conv(proc, right, type);
  3845. bool is_unsigned = is_type_unsigned(ir_type(left));
  3846. irValue *bits = right;
  3847. irValue *max = ir_value_constant(type, exact_value_i64(8*type_size_of(type) - 1));
  3848. irValue *less_equal_width = ir_emit(proc, ir_instr_binary_op(proc, Token_LtEq, bits, max, t_llvm_bool));
  3849. bits = ir_emit_select(proc, less_equal_width, bits, max);
  3850. return ir_emit(proc, ir_instr_binary_op(proc, op, left, bits, type));
  3851. }
  3852. case Token_AndNot: {
  3853. // NOTE(bill): x &~ y == x & (~y) == x & (y ~ -1)
  3854. // NOTE(bill): "not" 'x' == 'x' "xor" '-1'
  3855. irValue *neg = ir_add_module_constant(proc->module, type, exact_value_i64(-1));
  3856. op = Token_Xor;
  3857. right = ir_emit_arith(proc, op, right, neg, type);
  3858. GB_ASSERT(right->Instr.kind == irInstr_BinaryOp);
  3859. right->Instr.BinaryOp.type = type;
  3860. op = Token_And;
  3861. } /* fallthrough */
  3862. case Token_Add:
  3863. case Token_Sub:
  3864. case Token_Mul:
  3865. case Token_Quo:
  3866. case Token_Mod:
  3867. case Token_ModMod:
  3868. case Token_And:
  3869. case Token_Or:
  3870. case Token_Xor:
  3871. left = ir_emit_conv(proc, left, type);
  3872. right = ir_emit_conv(proc, right, type);
  3873. break;
  3874. }
  3875. if (op == Token_ModMod) {
  3876. if (is_type_unsigned(type)) {
  3877. op = Token_Mod;
  3878. } else {
  3879. irValue *a = ir_emit_arith(proc, Token_Mod, left, right, type);
  3880. irValue *b = ir_emit_arith(proc, Token_Add, a, right, type);
  3881. return ir_emit_arith(proc, Token_Mod, b, right, type);
  3882. }
  3883. }
  3884. return ir_emit(proc, ir_instr_binary_op(proc, op, left, right, type));
  3885. }
  3886. irValue *ir_emit_union_tag_ptr(irProcedure *proc, irValue *u) {
  3887. Type *t = ir_type(u);
  3888. GB_ASSERT_MSG(is_type_pointer(t) &&
  3889. is_type_union(type_deref(t)), "%s", type_to_string(t));
  3890. irValue *tag_ptr = ir_emit(proc, ir_instr_union_tag_ptr(proc, u));
  3891. return tag_ptr;
  3892. }
  3893. irValue *ir_emit_union_tag_value(irProcedure *proc, irValue *u) {
  3894. Type *t = ir_type(u);
  3895. GB_ASSERT(is_type_union(t));
  3896. GB_ASSERT(are_types_identical(t, ir_type(u)));
  3897. return ir_emit(proc, ir_instr_union_tag_value(proc, u));
  3898. }
  3899. irValue *ir_emit_comp_against_nil(irProcedure *proc, TokenKind op_kind, irValue *x) {
  3900. Type *t = ir_type(x);
  3901. if (is_type_pointer(t)) {
  3902. return ir_emit_comp(proc, op_kind, x, v_raw_nil);
  3903. } else if (is_type_cstring(t)) {
  3904. irValue *ptr = ir_emit_conv(proc, x, t_u8_ptr);
  3905. return ir_emit_comp(proc, op_kind, ptr, v_raw_nil);
  3906. } else if (is_type_any(t)) {
  3907. // TODO(bill): is this correct behaviour for nil comparison for any?
  3908. irValue *data = ir_emit_struct_ev(proc, x, 0);
  3909. irValue *ti = ir_emit_struct_ev(proc, x, 1);
  3910. if (op_kind == Token_CmpEq) {
  3911. irValue *a = ir_emit_comp(proc, Token_CmpEq, data, v_raw_nil);
  3912. irValue *b = ir_emit_comp(proc, Token_CmpEq, ti, v_raw_nil);
  3913. return ir_emit_arith(proc, Token_Or, a, b, t_bool);
  3914. } else if (op_kind == Token_NotEq) {
  3915. irValue *a = ir_emit_comp(proc, Token_NotEq, data, v_raw_nil);
  3916. irValue *b = ir_emit_comp(proc, Token_NotEq, ti, v_raw_nil);
  3917. return ir_emit_arith(proc, Token_And, a, b, t_bool);
  3918. }
  3919. } else if (is_type_slice(t)) {
  3920. irValue *len = ir_emit_struct_ev(proc, x, 1);
  3921. return ir_emit_comp(proc, op_kind, len, v_zero);
  3922. } else if (is_type_dynamic_array(t)) {
  3923. irValue *cap = ir_emit_struct_ev(proc, x, 2);
  3924. return ir_emit_comp(proc, op_kind, cap, v_zero);
  3925. } else if (is_type_map(t)) {
  3926. irValue *cap = ir_map_cap(proc, x);
  3927. return ir_emit_comp(proc, op_kind, cap, v_zero);
  3928. } else if (is_type_union(t)) {
  3929. if (type_size_of(t) == 0) {
  3930. return ir_emit_comp(proc, op_kind, v_zero, v_zero);
  3931. } else if (is_type_union_maybe_pointer(t)) {
  3932. Type *bt = base_type(t);
  3933. irValue *ptr = ir_address_from_load_or_generate_local(proc, x);
  3934. ptr = ir_emit_bitcast(proc, ptr, alloc_type_pointer(bt->Union.variants[0]));
  3935. irValue *data = ir_emit_load(proc, ptr);
  3936. return ir_emit_comp_against_nil(proc, op_kind, data);
  3937. } else {
  3938. irValue *tag = ir_emit_union_tag_value(proc, x);
  3939. return ir_emit_comp(proc, op_kind, tag, v_zero);
  3940. }
  3941. } else if (is_type_typeid(t)) {
  3942. irValue *invalid_typeid = ir_value_constant(t_typeid, exact_value_i64(0));
  3943. return ir_emit_comp(proc, op_kind, x, invalid_typeid);
  3944. } else if (is_type_bit_field(t)) {
  3945. auto args = array_make<irValue *>(heap_allocator(), 2);
  3946. irValue *lhs = ir_address_from_load_or_generate_local(proc, x);
  3947. args[0] = ir_emit_conv(proc, lhs, t_rawptr);
  3948. args[1] = ir_const_int(type_size_of(t));
  3949. irValue *val = ir_emit_runtime_call(proc, "memory_compare_zero", args);
  3950. irValue *res = ir_emit_comp(proc, op_kind, val, v_zero);
  3951. return ir_emit_conv(proc, res, t_bool);
  3952. } else if (is_type_soa_struct(t)) {
  3953. Type *bt = base_type(t);
  3954. if (bt->Struct.soa_kind == StructSoa_Slice) {
  3955. ir_emit_comment(proc, str_lit("soa-slice-nil-comp"));
  3956. irValue *len = ir_soa_struct_len(proc, x);
  3957. return ir_emit_comp(proc, op_kind, len, v_zero);
  3958. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  3959. ir_emit_comment(proc, str_lit("soa-dynamic-array-nil-comp"));
  3960. irValue *cap = ir_soa_struct_cap(proc, x);
  3961. return ir_emit_comp(proc, op_kind, cap, v_zero);
  3962. }
  3963. } else if (is_type_struct(t) && type_has_nil(t)) {
  3964. auto args = array_make<irValue *>(heap_allocator(), 2);
  3965. irValue *lhs = ir_address_from_load_or_generate_local(proc, x);
  3966. args[0] = ir_emit_conv(proc, lhs, t_rawptr);
  3967. args[1] = ir_const_int(type_size_of(t));
  3968. irValue *val = ir_emit_runtime_call(proc, "memory_compare_zero", args);
  3969. irValue *res = ir_emit_comp(proc, op_kind, val, v_zero);
  3970. return ir_emit_conv(proc, res, t_bool);
  3971. }
  3972. return nullptr;
  3973. }
  3974. irValue *ir_emit_comp(irProcedure *proc, TokenKind op_kind, irValue *left, irValue *right) {
  3975. Type *a = base_type(ir_type(left));
  3976. Type *b = base_type(ir_type(right));
  3977. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  3978. irValue *nil_check = nullptr;
  3979. if (left->kind == irValue_Nil) {
  3980. nil_check = ir_emit_comp_against_nil(proc, op_kind, right);
  3981. } else if (right->kind == irValue_Nil) {
  3982. nil_check = ir_emit_comp_against_nil(proc, op_kind, left);
  3983. }
  3984. if (nil_check != nullptr) {
  3985. return nil_check;
  3986. }
  3987. if (are_types_identical(a, b)) {
  3988. // NOTE(bill): No need for a conversion
  3989. } else if (left->kind == irValue_Constant || left->kind == irValue_Nil) {
  3990. left = ir_emit_conv(proc, left, ir_type(right));
  3991. } else if (right->kind == irValue_Constant || right->kind == irValue_Nil) {
  3992. right = ir_emit_conv(proc, right, ir_type(left));
  3993. } else {
  3994. gbAllocator a = ir_allocator();
  3995. Type *lt = ir_type(left);
  3996. Type *rt = ir_type(right);
  3997. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  3998. Type *blt = base_type(lt);
  3999. Type *brt = base_type(rt);
  4000. GB_ASSERT(is_type_bit_field_value(blt));
  4001. GB_ASSERT(is_type_bit_field_value(brt));
  4002. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  4003. i64 bytes = bits / 8;
  4004. switch (bytes) {
  4005. case 1:
  4006. left = ir_emit_conv(proc, left, t_u8);
  4007. right = ir_emit_conv(proc, right, t_u8);
  4008. break;
  4009. case 2:
  4010. left = ir_emit_conv(proc, left, t_u16);
  4011. right = ir_emit_conv(proc, right, t_u16);
  4012. break;
  4013. case 4:
  4014. left = ir_emit_conv(proc, left, t_u32);
  4015. right = ir_emit_conv(proc, right, t_u32);
  4016. break;
  4017. case 8:
  4018. left = ir_emit_conv(proc, left, t_u64);
  4019. right = ir_emit_conv(proc, right, t_u64);
  4020. break;
  4021. default: GB_PANIC("Unknown integer size"); break;
  4022. }
  4023. }
  4024. lt = ir_type(left);
  4025. rt = ir_type(right);
  4026. i64 ls = type_size_of(lt);
  4027. i64 rs = type_size_of(rt);
  4028. if (ls < rs) {
  4029. left = ir_emit_conv(proc, left, rt);
  4030. } else if (ls > rs) {
  4031. right = ir_emit_conv(proc, right, lt);
  4032. } else {
  4033. right = ir_emit_conv(proc, right, lt);
  4034. }
  4035. }
  4036. if (is_type_array(a)) {
  4037. ir_emit_comment(proc, str_lit("array.comp.begin"));
  4038. defer (ir_emit_comment(proc, str_lit("array.comp.end")));
  4039. Type *tl = base_type(a);
  4040. irValue *lhs = ir_address_from_load_or_generate_local(proc, left);
  4041. irValue *rhs = ir_address_from_load_or_generate_local(proc, right);
  4042. TokenKind cmp_op = Token_And;
  4043. irValue *res = v_true;
  4044. if (op_kind == Token_NotEq) {
  4045. res = v_false;
  4046. cmp_op = Token_Or;
  4047. } else if (op_kind == Token_CmpEq) {
  4048. res = v_true;
  4049. cmp_op = Token_And;
  4050. }
  4051. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  4052. i32 count = cast(i32)tl->Array.count;
  4053. if (inline_array_arith) {
  4054. // inline
  4055. irValue *val = ir_add_local_generated(proc, t_bool, false);
  4056. ir_emit_store(proc, val, res);
  4057. for (i32 i = 0; i < count; i++) {
  4058. irValue *x = ir_emit_load(proc, ir_emit_array_epi(proc, lhs, i));
  4059. irValue *y = ir_emit_load(proc, ir_emit_array_epi(proc, rhs, i));
  4060. irValue *cmp = ir_emit_comp(proc, op_kind, x, y);
  4061. irValue *new_res = ir_emit_arith(proc, cmp_op, ir_emit_load(proc, val), cmp, t_bool);
  4062. ir_emit_store(proc, val, ir_emit_conv(proc, new_res, t_bool));
  4063. }
  4064. return ir_emit_load(proc, val);
  4065. } else {
  4066. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  4067. // TODO(bill): Test to see if this is actually faster!!!!
  4068. auto args = array_make<irValue *>(heap_allocator(), 3);
  4069. args[0] = ir_emit_conv(proc, lhs, t_rawptr);
  4070. args[1] = ir_emit_conv(proc, rhs, t_rawptr);
  4071. args[2] = ir_const_int(type_size_of(tl));
  4072. irValue *val = ir_emit_runtime_call(proc, "memory_compare", args);
  4073. irValue *res = ir_emit_comp(proc, op_kind, val, v_zero);
  4074. return ir_emit_conv(proc, res, t_bool);
  4075. } else {
  4076. irValue *val = ir_add_local_generated(proc, t_bool, false);
  4077. ir_emit_store(proc, val, res);
  4078. auto loop_data = ir_loop_start(proc, count, t_i32);
  4079. {
  4080. irValue *i = loop_data.idx;
  4081. irValue *x = ir_emit_load(proc, ir_emit_array_ep(proc, lhs, i));
  4082. irValue *y = ir_emit_load(proc, ir_emit_array_ep(proc, rhs, i));
  4083. irValue *cmp = ir_emit_comp(proc, op_kind, x, y);
  4084. irValue *new_res = ir_emit_arith(proc, cmp_op, ir_emit_load(proc, val), cmp, t_bool);
  4085. ir_emit_store(proc, val, ir_emit_conv(proc, new_res, t_bool));
  4086. }
  4087. ir_loop_end(proc, loop_data);
  4088. return ir_emit_load(proc, val);
  4089. }
  4090. }
  4091. }
  4092. if (is_type_string(a)) {
  4093. if (is_type_cstring(a)) {
  4094. left = ir_emit_conv(proc, left, t_string);
  4095. right = ir_emit_conv(proc, right, t_string);
  4096. }
  4097. char const *runtime_proc = nullptr;
  4098. switch (op_kind) {
  4099. case Token_CmpEq: runtime_proc = "string_eq"; break;
  4100. case Token_NotEq: runtime_proc = "string_ne"; break;
  4101. case Token_Lt: runtime_proc = "string_lt"; break;
  4102. case Token_Gt: runtime_proc = "string_gt"; break;
  4103. case Token_LtEq: runtime_proc = "string_le"; break;
  4104. case Token_GtEq: runtime_proc = "string_gt"; break;
  4105. }
  4106. GB_ASSERT(runtime_proc != nullptr);
  4107. auto args = array_make<irValue *>(ir_allocator(), 2);
  4108. args[0] = left;
  4109. args[1] = right;
  4110. return ir_emit_runtime_call(proc, runtime_proc, args);
  4111. }
  4112. if (is_type_complex(a)) {
  4113. char const *runtime_proc = "";
  4114. i64 sz = 8*type_size_of(a);
  4115. switch (sz) {
  4116. case 64:
  4117. switch (op_kind) {
  4118. case Token_CmpEq: runtime_proc = "complex64_eq"; break;
  4119. case Token_NotEq: runtime_proc = "complex64_ne"; break;
  4120. }
  4121. break;
  4122. case 128:
  4123. switch (op_kind) {
  4124. case Token_CmpEq: runtime_proc = "complex128_eq"; break;
  4125. case Token_NotEq: runtime_proc = "complex128_ne"; break;
  4126. }
  4127. break;
  4128. }
  4129. GB_ASSERT(runtime_proc != nullptr);
  4130. auto args = array_make<irValue *>(ir_allocator(), 2);
  4131. args[0] = left;
  4132. args[1] = right;
  4133. return ir_emit_runtime_call(proc, runtime_proc, args);
  4134. }
  4135. if (is_type_quaternion(a)) {
  4136. char const *runtime_proc = "";
  4137. i64 sz = 8*type_size_of(a);
  4138. switch (sz) {
  4139. case 128:
  4140. switch (op_kind) {
  4141. case Token_CmpEq: runtime_proc = "quaternion128_eq"; break;
  4142. case Token_NotEq: runtime_proc = "quaternion128_ne"; break;
  4143. }
  4144. break;
  4145. case 256:
  4146. switch (op_kind) {
  4147. case Token_CmpEq: runtime_proc = "quaternion256_eq"; break;
  4148. case Token_NotEq: runtime_proc = "quaternion256_ne"; break;
  4149. }
  4150. break;
  4151. }
  4152. GB_ASSERT(runtime_proc != nullptr);
  4153. auto args = array_make<irValue *>(ir_allocator(), 2);
  4154. args[0] = left;
  4155. args[1] = right;
  4156. return ir_emit_runtime_call(proc, runtime_proc, args);
  4157. }
  4158. if (is_type_bit_set(a)) {
  4159. switch (op_kind) {
  4160. case Token_Lt:
  4161. case Token_LtEq:
  4162. case Token_Gt:
  4163. case Token_GtEq:
  4164. {
  4165. Type *it = bit_set_to_int(a);
  4166. irValue *lhs = ir_emit_bitcast(proc, left, it);
  4167. irValue *rhs = ir_emit_bitcast(proc, right, it);
  4168. irValue *res = ir_emit_arith(proc, Token_And, lhs, rhs, it);
  4169. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  4170. // (lhs & rhs) == lhs
  4171. res = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, res, lhs, t_llvm_bool));
  4172. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  4173. // (lhs & rhs) == rhs
  4174. res = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, res, rhs, t_llvm_bool));
  4175. }
  4176. // NOTE(bill): Strict subsets
  4177. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  4178. // res &~ (lhs == rhs)
  4179. irValue *eq = ir_emit(proc, ir_instr_binary_op(proc, Token_CmpEq, lhs, rhs, t_llvm_bool));
  4180. res = ir_emit_arith(proc, Token_AndNot, res, eq, t_llvm_bool);
  4181. }
  4182. return res;
  4183. }
  4184. }
  4185. }
  4186. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  4187. Type *t = ir_type(left);
  4188. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  4189. Type *platform_type = integer_endian_type_to_platform_type(t);
  4190. irValue *x = ir_emit_byte_swap(proc, left, platform_type);
  4191. irValue *y = ir_emit_byte_swap(proc, right, platform_type);
  4192. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, x, y, t_llvm_bool));
  4193. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  4194. Type *platform_type = integer_endian_type_to_platform_type(t);
  4195. irValue *x = ir_emit_conv(proc, left, platform_type);
  4196. irValue *y = ir_emit_conv(proc, right, platform_type);
  4197. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, x, y, t_llvm_bool));
  4198. }
  4199. }
  4200. return ir_emit(proc, ir_instr_binary_op(proc, op_kind, left, right, t_llvm_bool));
  4201. }
  4202. irValue *ir_emit_array_ep(irProcedure *proc, irValue *s, irValue *index) {
  4203. GB_ASSERT(index != nullptr);
  4204. Type *t = ir_type(s);
  4205. GB_ASSERT(is_type_pointer(t));
  4206. Type *st = base_type(type_deref(t));
  4207. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  4208. // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
  4209. index = ir_emit_conv(proc, index, t_i32);
  4210. return ir_emit(proc, ir_instr_array_element_ptr(proc, s, index));
  4211. }
  4212. irValue *ir_emit_array_epi(irProcedure *proc, irValue *s, i32 index) {
  4213. return ir_emit_array_ep(proc, s, ir_const_i32(index));
  4214. }
  4215. irValue *ir_emit_struct_ep(irProcedure *proc, irValue *s, i32 index) {
  4216. gbAllocator a = ir_allocator();
  4217. GB_ASSERT(is_type_pointer(ir_type(s)));
  4218. Type *t = base_type(type_deref(ir_type(s)));
  4219. Type *result_type = nullptr;
  4220. if (t->kind == Type_Opaque) {
  4221. t = t->Opaque.elem;
  4222. }
  4223. if (is_type_struct(t)) {
  4224. result_type = alloc_type_pointer(t->Struct.fields[index]->type);
  4225. } else if (is_type_union(t)) {
  4226. GB_ASSERT(index == -1);
  4227. return ir_emit_union_tag_ptr(proc, s);
  4228. } else if (is_type_tuple(t)) {
  4229. GB_ASSERT(t->Tuple.variables.count > 0);
  4230. result_type = alloc_type_pointer(t->Tuple.variables[index]->type);
  4231. } else if (is_type_complex(t)) {
  4232. Type *ft = base_complex_elem_type(t);
  4233. switch (index) {
  4234. case 0: result_type = alloc_type_pointer(ft); break;
  4235. case 1: result_type = alloc_type_pointer(ft); break;
  4236. }
  4237. } else if (is_type_quaternion(t)) {
  4238. Type *ft = base_complex_elem_type(t);
  4239. switch (index) {
  4240. case 0: result_type = alloc_type_pointer(ft); break;
  4241. case 1: result_type = alloc_type_pointer(ft); break;
  4242. case 2: result_type = alloc_type_pointer(ft); break;
  4243. case 3: result_type = alloc_type_pointer(ft); break;
  4244. }
  4245. } else if (is_type_slice(t)) {
  4246. switch (index) {
  4247. case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->Slice.elem)); break;
  4248. case 1: result_type = alloc_type_pointer(t_int); break;
  4249. }
  4250. } else if (is_type_string(t)) {
  4251. switch (index) {
  4252. case 0: result_type = alloc_type_pointer(t_u8_ptr); break;
  4253. case 1: result_type = alloc_type_pointer(t_int); break;
  4254. }
  4255. } else if (is_type_any(t)) {
  4256. switch (index) {
  4257. case 0: result_type = alloc_type_pointer(t_rawptr); break;
  4258. case 1: result_type = alloc_type_pointer(t_typeid); break;
  4259. }
  4260. } else if (is_type_dynamic_array(t)) {
  4261. switch (index) {
  4262. case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->DynamicArray.elem)); break;
  4263. case 1: result_type = t_int_ptr; break;
  4264. case 2: result_type = t_int_ptr; break;
  4265. case 3: result_type = t_allocator_ptr; break;
  4266. }
  4267. } else if (is_type_map(t)) {
  4268. init_map_internal_types(t);
  4269. Type *itp = alloc_type_pointer(t->Map.internal_type);
  4270. s = ir_emit_transmute(proc, s, itp);
  4271. Type *gst = t->Map.internal_type;
  4272. GB_ASSERT(gst->kind == Type_Struct);
  4273. switch (index) {
  4274. case 0: result_type = alloc_type_pointer(gst->Struct.fields[0]->type); break;
  4275. case 1: result_type = alloc_type_pointer(gst->Struct.fields[1]->type); break;
  4276. }
  4277. } else if (is_type_array(t)) {
  4278. return ir_emit_array_epi(proc, s, index);
  4279. } else if (is_type_relative_slice(t)) {
  4280. switch (index) {
  4281. case 0: result_type = alloc_type_pointer(t->RelativeSlice.base_integer); break;
  4282. case 1: result_type = alloc_type_pointer(t->RelativeSlice.base_integer); break;
  4283. }
  4284. } else {
  4285. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(ir_type(s)), index);
  4286. }
  4287. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  4288. return ir_emit(proc, ir_instr_struct_element_ptr(proc, s, index, result_type));
  4289. }
  4290. irValue *ir_emit_struct_ev(irProcedure *proc, irValue *s, i32 index) {
  4291. // NOTE(bill): For some weird legacy reason in LLVM, structure elements must be accessed as an i32
  4292. if (s->kind == irValue_Instr) {
  4293. if (s->Instr.kind == irInstr_Load) {
  4294. irValue *addr = s->Instr.Load.address;
  4295. irValue *ptr = ir_emit_struct_ep(proc, addr, index);
  4296. return ir_emit_load(proc, ptr);
  4297. }
  4298. }
  4299. gbAllocator a = ir_allocator();
  4300. Type *t = base_type(ir_type(s));
  4301. Type *result_type = nullptr;
  4302. switch (t->kind) {
  4303. case Type_Basic:
  4304. switch (t->Basic.kind) {
  4305. case Basic_string:
  4306. switch (index) {
  4307. case 0: result_type = t_u8_ptr; break;
  4308. case 1: result_type = t_int; break;
  4309. }
  4310. break;
  4311. case Basic_any:
  4312. switch (index) {
  4313. case 0: result_type = t_rawptr; break;
  4314. case 1: result_type = t_typeid; break;
  4315. }
  4316. break;
  4317. case Basic_complex64: case Basic_complex128:
  4318. {
  4319. Type *ft = base_complex_elem_type(t);
  4320. switch (index) {
  4321. case 0: result_type = ft; break;
  4322. case 1: result_type = ft; break;
  4323. }
  4324. break;
  4325. }
  4326. case Basic_quaternion128: case Basic_quaternion256:
  4327. {
  4328. Type *ft = base_complex_elem_type(t);
  4329. switch (index) {
  4330. case 0: result_type = ft; break;
  4331. case 1: result_type = ft; break;
  4332. case 2: result_type = ft; break;
  4333. case 3: result_type = ft; break;
  4334. }
  4335. break;
  4336. }
  4337. }
  4338. break;
  4339. case Type_Struct:
  4340. result_type = t->Struct.fields[index]->type;
  4341. break;
  4342. case Type_Union:
  4343. GB_ASSERT(index == -1);
  4344. return ir_emit_union_tag_value(proc, s);
  4345. case Type_Tuple:
  4346. GB_ASSERT(t->Tuple.variables.count > 0);
  4347. result_type = t->Tuple.variables[index]->type;
  4348. break;
  4349. case Type_Slice:
  4350. switch (index) {
  4351. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  4352. case 1: result_type = t_int; break;
  4353. }
  4354. break;
  4355. case Type_DynamicArray:
  4356. switch (index) {
  4357. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  4358. case 1: result_type = t_int; break;
  4359. case 2: result_type = t_int; break;
  4360. case 3: result_type = t_allocator; break;
  4361. }
  4362. break;
  4363. case Type_Map:
  4364. {
  4365. init_map_internal_types(t);
  4366. Type *gst = t->Map.generated_struct_type;
  4367. switch (index) {
  4368. case 0: result_type = gst->Struct.fields[0]->type; break;
  4369. case 1: result_type = gst->Struct.fields[1]->type; break;
  4370. }
  4371. }
  4372. break;
  4373. case Type_Array:
  4374. result_type = t->Array.elem;
  4375. break;
  4376. default:
  4377. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(ir_type(s)), index);
  4378. break;
  4379. }
  4380. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(ir_type(s)), index);
  4381. return ir_emit(proc, ir_instr_struct_extract_value(proc, s, index, result_type));
  4382. }
  4383. irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel) {
  4384. GB_ASSERT(sel.index.count > 0);
  4385. Type *type = type_deref(ir_type(e));
  4386. gbAllocator a = ir_allocator();
  4387. for_array(i, sel.index) {
  4388. i32 index = cast(i32)sel.index[i];
  4389. if (is_type_pointer(type)) {
  4390. type = type_deref(type);
  4391. e = ir_emit_load(proc, e);
  4392. // e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
  4393. }
  4394. type = core_type(type);
  4395. if (type->kind == Type_Opaque) {
  4396. type = type->Opaque.elem;
  4397. }
  4398. if (is_type_quaternion(type)) {
  4399. e = ir_emit_struct_ep(proc, e, index);
  4400. } else if (is_type_raw_union(type)) {
  4401. type = type->Struct.fields[index]->type;
  4402. GB_ASSERT(is_type_pointer(ir_type(e)));
  4403. e = ir_emit_bitcast(proc, e, alloc_type_pointer(type));
  4404. } else if (is_type_struct(type)) {
  4405. type = type->Struct.fields[index]->type;
  4406. e = ir_emit_struct_ep(proc, e, index);
  4407. } else if (type->kind == Type_Union) {
  4408. GB_ASSERT(index == -1);
  4409. type = t_type_info_ptr;
  4410. e = ir_emit_struct_ep(proc, e, index);
  4411. } else if (type->kind == Type_Tuple) {
  4412. type = type->Tuple.variables[index]->type;
  4413. e = ir_emit_struct_ep(proc, e, index);
  4414. } else if (type->kind == Type_Basic) {
  4415. switch (type->Basic.kind) {
  4416. case Basic_any: {
  4417. if (index == 0) {
  4418. type = t_rawptr;
  4419. } else if (index == 1) {
  4420. type = t_type_info_ptr;
  4421. }
  4422. e = ir_emit_struct_ep(proc, e, index);
  4423. break;
  4424. }
  4425. case Basic_string:
  4426. e = ir_emit_struct_ep(proc, e, index);
  4427. break;
  4428. default:
  4429. GB_PANIC("un-gep-able type");
  4430. break;
  4431. }
  4432. } else if (type->kind == Type_Slice) {
  4433. e = ir_emit_struct_ep(proc, e, index);
  4434. } else if (type->kind == Type_DynamicArray) {
  4435. e = ir_emit_struct_ep(proc, e, index);
  4436. } else if (type->kind == Type_Array) {
  4437. e = ir_emit_array_epi(proc, e, index);
  4438. } else if (type->kind == Type_Map) {
  4439. e = ir_emit_struct_ep(proc, e, index);
  4440. } else {
  4441. GB_PANIC("un-gep-able type %s", type_to_string(type));
  4442. }
  4443. }
  4444. return e;
  4445. }
  4446. irValue *ir_emit_deep_field_ev(irProcedure *proc, irValue *e, Selection sel) {
  4447. GB_ASSERT(sel.index.count > 0);
  4448. if (e->kind == irValue_Instr) {
  4449. if (e->Instr.kind == irInstr_Load) {
  4450. irValue *addr = e->Instr.Load.address;
  4451. irValue *ptr = ir_emit_deep_field_gep(proc, addr, sel);
  4452. return ir_emit_load(proc, ptr);
  4453. }
  4454. }
  4455. Type *type = ir_type(e);
  4456. for_array(i, sel.index) {
  4457. i32 index = cast(i32)sel.index[i];
  4458. if (is_type_pointer(type)) {
  4459. type = type_deref(type);
  4460. e = ir_emit_load(proc, e);
  4461. e = ir_emit_ptr_offset(proc, e, v_zero); // TODO(bill): Do I need these copies?
  4462. }
  4463. type = base_type(type);
  4464. if (is_type_raw_union(type)) {
  4465. GB_PANIC("TODO(bill): IS THIS EVEN CORRECT?");
  4466. type = type->Struct.fields[index]->type;
  4467. e = ir_emit_conv(proc, e, type);
  4468. } else if (type->kind == Type_Map) {
  4469. e = ir_emit_struct_ev(proc, e, 1);
  4470. switch (index) {
  4471. case 0: e = ir_emit_struct_ev(proc, e, 1); break; // count
  4472. case 1: e = ir_emit_struct_ev(proc, e, 2); break; // capacity
  4473. case 2: e = ir_emit_struct_ev(proc, e, 3); break; // allocator
  4474. }
  4475. } else {
  4476. e = ir_emit_struct_ev(proc, e, index);
  4477. }
  4478. }
  4479. return e;
  4480. }
  4481. irValue *ir_array_elem(irProcedure *proc, irValue *array) {
  4482. return ir_emit_array_ep(proc, array, v_zero32);
  4483. }
  4484. irValue *ir_array_len(irProcedure *proc, irValue *array) {
  4485. Type *t = base_type(ir_type(array));
  4486. GB_ASSERT(t->kind == Type_Array);
  4487. return ir_const_int(t->Array.count);
  4488. }
  4489. irValue *ir_slice_elem(irProcedure *proc, irValue *slice) {
  4490. GB_ASSERT(is_type_slice(ir_type(slice)));
  4491. return ir_emit_struct_ev(proc, slice, 0);
  4492. }
  4493. irValue *ir_slice_len(irProcedure *proc, irValue *slice) {
  4494. GB_ASSERT(is_type_slice(ir_type(slice)));
  4495. return ir_emit_struct_ev(proc, slice, 1);
  4496. }
  4497. irValue *ir_dynamic_array_elem(irProcedure *proc, irValue *da) {
  4498. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4499. return ir_emit_struct_ev(proc, da, 0);
  4500. }
  4501. irValue *ir_dynamic_array_len(irProcedure *proc, irValue *da) {
  4502. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4503. return ir_emit_struct_ev(proc, da, 1);
  4504. }
  4505. irValue *ir_dynamic_array_cap(irProcedure *proc, irValue *da) {
  4506. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4507. return ir_emit_struct_ev(proc, da, 2);
  4508. }
  4509. irValue *ir_dynamic_array_allocator(irProcedure *proc, irValue *da) {
  4510. GB_ASSERT(is_type_dynamic_array(ir_type(da)));
  4511. return ir_emit_struct_ev(proc, da, 3);
  4512. }
  4513. irValue *ir_string_elem(irProcedure *proc, irValue *string) {
  4514. Type *t = base_type(ir_type(string));
  4515. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  4516. return ir_emit_struct_ev(proc, string, 0);
  4517. }
  4518. irValue *ir_string_len(irProcedure *proc, irValue *string) {
  4519. Type *t = base_type(ir_type(string));
  4520. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  4521. return ir_emit_struct_ev(proc, string, 1);
  4522. }
  4523. irValue *ir_cstring_len(irProcedure *proc, irValue *value) {
  4524. GB_ASSERT(is_type_cstring(ir_type(value)));
  4525. auto args = array_make<irValue *>(ir_allocator(), 1);
  4526. args[0] = ir_emit_conv(proc, value, t_cstring);
  4527. return ir_emit_runtime_call(proc, "cstring_len", args);
  4528. }
  4529. void ir_fill_slice(irProcedure *proc, irValue *slice_ptr, irValue *data, irValue *len) {
  4530. Type *t = ir_type(slice_ptr);
  4531. GB_ASSERT(is_type_pointer(t));
  4532. t = type_deref(t);
  4533. GB_ASSERT(is_type_slice(t));
  4534. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 0), data);
  4535. ir_emit_store(proc, ir_emit_struct_ep(proc, slice_ptr, 1), len);
  4536. }
  4537. void ir_fill_string(irProcedure *proc, irValue *string_ptr, irValue *data, irValue *len) {
  4538. Type *t = ir_type(string_ptr);
  4539. GB_ASSERT(is_type_pointer(t));
  4540. t = type_deref(t);
  4541. GB_ASSERT(is_type_string(t));
  4542. ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 0), data);
  4543. ir_emit_store(proc, ir_emit_struct_ep(proc, string_ptr, 1), len);
  4544. }
  4545. irValue *ir_emit_string(irProcedure *proc, irValue *elem, irValue *len) {
  4546. irValue *str = ir_add_local_generated(proc, t_string, false);
  4547. ir_fill_string(proc, str, elem, len);
  4548. return ir_emit_load(proc, str);
  4549. }
  4550. irValue *ir_add_local_slice(irProcedure *proc, Type *slice_type, irValue *base, irValue *low, irValue *high) {
  4551. // TODO(bill): array bounds checking for slice creation
  4552. // TODO(bill): check that low < high <= max
  4553. gbAllocator a = ir_allocator();
  4554. Type *bt = base_type(ir_type(base));
  4555. if (low == nullptr) {
  4556. low = v_zero;
  4557. }
  4558. if (high == nullptr) {
  4559. switch (bt->kind) {
  4560. case Type_Array: high = ir_array_len(proc, base); break;
  4561. case Type_Slice: high = ir_slice_len(proc, base); break;
  4562. case Type_Pointer: high = v_one; break;
  4563. }
  4564. }
  4565. irValue *len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  4566. irValue *elem = nullptr;
  4567. switch (bt->kind) {
  4568. case Type_Array: elem = ir_array_elem(proc, base); break;
  4569. case Type_Slice: elem = ir_slice_elem(proc, base); break;
  4570. case Type_Pointer: elem = ir_emit_load(proc, base); break;
  4571. }
  4572. elem = ir_emit_ptr_offset(proc, elem, low);
  4573. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  4574. ir_fill_slice(proc, slice, elem, len);
  4575. return slice;
  4576. }
  4577. irValue *ir_find_or_add_entity_string(irModule *m, String str) {
  4578. StringHashKey key = string_hash_string(str);
  4579. irValue **found = string_map_get(&m->const_strings, key);
  4580. if (found != nullptr) {
  4581. return *found;
  4582. }
  4583. irValue *v = ir_value_constant(t_string, exact_value_string(str));
  4584. string_map_set(&m->const_strings, key, v);
  4585. return v;
  4586. }
  4587. irValue *ir_find_or_add_entity_string_byte_slice(irModule *m, String str) {
  4588. StringHashKey key = string_hash_string(str);
  4589. irValue **found = string_map_get(&m->const_string_byte_slices, key);
  4590. if (found != nullptr) {
  4591. return *found;
  4592. }
  4593. Type *t = t_u8_slice;
  4594. irValue *v = ir_value_constant(t, exact_value_string(str));
  4595. string_map_set(&m->const_string_byte_slices, key, v);
  4596. return v;
  4597. }
  4598. irValue *ir_const_union_tag(Type *u, Type *v) {
  4599. return ir_value_constant(union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  4600. }
  4601. String ir_lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  4602. Type *prev_src = src;
  4603. // Type *prev_dst = dst;
  4604. src = base_type(type_deref(src));
  4605. // dst = base_type(type_deref(dst));
  4606. bool src_is_ptr = src != prev_src;
  4607. // bool dst_is_ptr = dst != prev_dst;
  4608. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  4609. for_array(i, src->Struct.fields) {
  4610. Entity *f = src->Struct.fields[i];
  4611. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  4612. if (are_types_identical(dst, f->type)) {
  4613. return f->token.string;
  4614. }
  4615. if (src_is_ptr && is_type_pointer(dst)) {
  4616. if (are_types_identical(type_deref(dst), f->type)) {
  4617. return f->token.string;
  4618. }
  4619. }
  4620. if (is_type_struct(f->type)) {
  4621. String name = ir_lookup_subtype_polymorphic_field(info, dst, f->type);
  4622. if (name.len > 0) {
  4623. return name;
  4624. }
  4625. }
  4626. }
  4627. }
  4628. return str_lit("");
  4629. }
  4630. irValue *ir_emit_ptr_to_uintptr(irProcedure *proc, irValue *value, Type *t, bool allow_type_type = false) {
  4631. Type *vt = core_type(ir_type(value));
  4632. GB_ASSERT(is_type_pointer(vt));
  4633. if (allow_type_type) {
  4634. GB_ASSERT(is_type_uintptr(core_type(t)));
  4635. } else {
  4636. GB_ASSERT(is_type_uintptr(core_type(t)));
  4637. }
  4638. return ir_emit(proc, ir_instr_conv(proc, irConv_ptrtoint, value, vt, t));
  4639. }
  4640. irValue *ir_emit_uintptr_to_ptr(irProcedure *proc, irValue *value, Type *t) {
  4641. Type *vt = core_type(ir_type(value));
  4642. GB_ASSERT(is_type_uintptr(vt));
  4643. GB_ASSERT(is_type_pointer(core_type(t)));
  4644. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, value, vt, t));
  4645. }
  4646. irValue *ir_emit_byte_swap(irProcedure *proc, irValue *value, Type *t) {
  4647. Type *vt = core_type(ir_type(value));
  4648. if (is_type_untyped(vt)) {
  4649. return value;
  4650. }
  4651. GB_ASSERT(type_size_of(vt) == type_size_of(t));
  4652. if (is_type_float(t)) {
  4653. i64 sz = type_size_of(t);
  4654. auto args = array_make<irValue *>(ir_allocator(), 1);
  4655. args[0] = value;
  4656. char const *proc_name = nullptr;
  4657. switch (sz*8) {
  4658. case 32: proc_name = "bswap_f32"; break;
  4659. case 64: proc_name = "bswap_f64"; break;
  4660. }
  4661. GB_ASSERT(proc_name != nullptr);
  4662. String name = make_string_c(proc_name);
  4663. AstPackage *p = proc->module->info->runtime_package;
  4664. Entity *e = scope_lookup_current(p->scope, name);
  4665. irValue **found = map_get(&proc->module->values, hash_entity(e));
  4666. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(name));
  4667. irValue *gp = *found;
  4668. return ir_emit(proc, ir_instr_call(proc, gp, nullptr, args, t, nullptr, ProcInlining_none));
  4669. }
  4670. return ir_emit(proc, ir_instr_conv(proc, irConv_byteswap, value, vt, t));
  4671. }
  4672. void ir_emit_store_union_variant(irProcedure *proc, irValue *parent, irValue *variant, Type *variant_type) {
  4673. gbAllocator a = ir_allocator();
  4674. irValue *underlying = ir_emit_conv(proc, parent, alloc_type_pointer(variant_type));
  4675. ir_emit_store(proc, underlying, variant);
  4676. Type *t = type_deref(ir_type(parent));
  4677. if (is_type_union_maybe_pointer(t)) {
  4678. // No tag needed!
  4679. } else {
  4680. irValue *tag_ptr = ir_emit_union_tag_ptr(proc, parent);
  4681. ir_emit_store(proc, tag_ptr, ir_const_union_tag(t, variant_type));
  4682. }
  4683. }
  4684. irValue *ir_emit_conv(irProcedure *proc, irValue *value, Type *t) {
  4685. Type *src_type = ir_type(value);
  4686. if (are_types_identical(t, src_type)) {
  4687. return value;
  4688. }
  4689. Type *src = core_type(src_type);
  4690. Type *dst = core_type(t);
  4691. // if (is_type_untyped_nil(src) && type_has_nil(dst)) {
  4692. if (is_type_untyped_nil(src)) {
  4693. return ir_value_nil(t);
  4694. }
  4695. if (is_type_untyped_undef(src)) {
  4696. return ir_value_undef(t);
  4697. }
  4698. if (value->kind == irValue_Constant) {
  4699. if (is_type_any(dst)) {
  4700. irValue *default_value = ir_add_local_generated(proc, default_type(src_type), false);
  4701. ir_emit_store(proc, default_value, value);
  4702. return ir_emit_conv(proc, ir_emit_load(proc, default_value), t_any);
  4703. } else if (dst->kind == Type_Basic) {
  4704. ExactValue ev = value->Constant.value;
  4705. if (is_type_float(dst)) {
  4706. ev = exact_value_to_float(ev);
  4707. } else if (is_type_complex(dst)) {
  4708. ev = exact_value_to_complex(ev);
  4709. } else if (is_type_quaternion(dst)) {
  4710. ev = exact_value_to_quaternion(ev);
  4711. } else if (is_type_string(dst)) {
  4712. // Handled elsewhere
  4713. GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  4714. } else if (is_type_integer(dst)) {
  4715. ev = exact_value_to_integer(ev);
  4716. } else if (is_type_pointer(dst)) {
  4717. // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  4718. irValue *i = ir_add_module_constant(proc->module, t_uintptr, ev);
  4719. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, i, t_uintptr, dst));
  4720. }
  4721. return ir_add_module_constant(proc->module, t, ev);
  4722. }
  4723. }
  4724. if (are_types_identical(src, dst)) {
  4725. if (!are_types_identical(src_type, t)) {
  4726. return ir_emit_transmute(proc, value, t);
  4727. }
  4728. return value;
  4729. }
  4730. // bool <-> llvm bool
  4731. if (is_type_boolean(src) && dst == t_llvm_bool) {
  4732. return ir_emit(proc, ir_instr_conv(proc, irConv_trunc, value, src_type, t));
  4733. }
  4734. if (src == t_llvm_bool && is_type_boolean(dst)) {
  4735. return ir_emit(proc, ir_instr_conv(proc, irConv_zext, value, src_type, t));
  4736. }
  4737. // integer -> integer
  4738. if (is_type_integer(src) && is_type_integer(dst)) {
  4739. GB_ASSERT(src->kind == Type_Basic &&
  4740. dst->kind == Type_Basic);
  4741. i64 sz = type_size_of(default_type(src));
  4742. i64 dz = type_size_of(default_type(dst));
  4743. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  4744. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  4745. value = ir_emit_byte_swap(proc, value, platform_src_type);
  4746. }
  4747. irConvKind kind = irConv_trunc;
  4748. if (dz < sz) {
  4749. kind = irConv_trunc;
  4750. } else if (dz == sz) {
  4751. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  4752. // NOTE(bill): Copy the value just for type correctness
  4753. kind = irConv_bitcast;
  4754. } else if (dz > sz) {
  4755. if (is_type_unsigned(src)) {
  4756. kind = irConv_zext; // zero extent
  4757. } else {
  4758. kind = irConv_sext; // sign extent
  4759. }
  4760. }
  4761. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  4762. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  4763. irValue *res = ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, platform_dst_type));
  4764. return ir_emit_byte_swap(proc, res, t);
  4765. } else {
  4766. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4767. }
  4768. }
  4769. // boolean -> boolean/integer
  4770. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  4771. irValue *b = ir_emit(proc, ir_instr_binary_op(proc, Token_NotEq, value, v_zero, t_llvm_bool));
  4772. return ir_emit(proc, ir_instr_conv(proc, irConv_zext, b, t_llvm_bool, t));
  4773. }
  4774. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  4775. return ir_emit_bitcast(proc, value, dst);
  4776. }
  4777. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  4778. return ir_emit_bitcast(proc, value, dst);
  4779. }
  4780. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  4781. return ir_emit_bitcast(proc, value, dst);
  4782. }
  4783. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  4784. return ir_emit_bitcast(proc, value, dst);
  4785. }
  4786. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  4787. irValue *c = ir_emit_conv(proc, value, t_cstring);
  4788. auto args = array_make<irValue *>(ir_allocator(), 1);
  4789. args[0] = c;
  4790. irValue *s = ir_emit_runtime_call(proc, "cstring_to_string", args);
  4791. return ir_emit_conv(proc, s, dst);
  4792. }
  4793. // integer -> boolean
  4794. if (is_type_integer(src) && is_type_boolean(dst)) {
  4795. return ir_emit_comp(proc, Token_NotEq, value, v_zero);
  4796. }
  4797. // float -> float
  4798. if (is_type_float(src) && is_type_float(dst)) {
  4799. GB_ASSERT(!are_types_identical(src, dst));
  4800. gbAllocator a = ir_allocator();
  4801. i64 sz = type_size_of(src);
  4802. i64 dz = type_size_of(dst);
  4803. irConvKind kind = irConv_fptrunc;
  4804. if (dz == sz) {
  4805. if (types_have_same_internal_endian(src, dst)) {
  4806. return ir_emit_transmute(proc, value, t);
  4807. } else {
  4808. return ir_emit_byte_swap(proc, value, t);
  4809. }
  4810. }
  4811. if (dz >= sz) {
  4812. kind = irConv_fpext;
  4813. }
  4814. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  4815. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  4816. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  4817. irValue *res = nullptr;
  4818. res = ir_emit_conv(proc, value, platform_src_type);
  4819. res = ir_emit_conv(proc, res, platform_dst_type);
  4820. if (is_type_different_to_arch_endianness(dst)) {
  4821. res = ir_emit_byte_swap(proc, res, t);
  4822. }
  4823. return ir_emit_conv(proc, res, t);
  4824. }
  4825. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4826. }
  4827. if (is_type_complex(src) && is_type_complex(dst)) {
  4828. Type *ft = base_complex_elem_type(dst);
  4829. irValue *gen = ir_add_local_generated(proc, dst, false);
  4830. irValue *real = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  4831. irValue *imag = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  4832. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), real);
  4833. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 1), imag);
  4834. return ir_emit_load(proc, gen);
  4835. }
  4836. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  4837. // @QuaternionLayout
  4838. Type *ft = base_complex_elem_type(dst);
  4839. irValue *gen = ir_add_local_generated(proc, dst, false);
  4840. irValue *q0 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  4841. irValue *q1 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  4842. irValue *q2 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 2), ft);
  4843. irValue *q3 = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 3), ft);
  4844. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), q0);
  4845. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 1), q1);
  4846. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 2), q2);
  4847. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), q3);
  4848. return ir_emit_load(proc, gen);
  4849. }
  4850. if (is_type_float(src) && is_type_complex(dst)) {
  4851. Type *ft = base_complex_elem_type(dst);
  4852. irValue *gen = ir_add_local_generated(proc, dst, true);
  4853. irValue *real = ir_emit_conv(proc, value, ft);
  4854. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), real);
  4855. return ir_emit_load(proc, gen);
  4856. }
  4857. if (is_type_float(src) && is_type_quaternion(dst)) {
  4858. Type *ft = base_complex_elem_type(dst);
  4859. irValue *gen = ir_add_local_generated(proc, dst, true);
  4860. irValue *real = ir_emit_conv(proc, value, ft);
  4861. // @QuaternionLayout
  4862. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), real);
  4863. return ir_emit_load(proc, gen);
  4864. }
  4865. if (is_type_complex(src) && is_type_quaternion(dst)) {
  4866. Type *ft = base_complex_elem_type(dst);
  4867. irValue *gen = ir_add_local_generated(proc, dst, true);
  4868. irValue *real = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 0), ft);
  4869. irValue *imag = ir_emit_conv(proc, ir_emit_struct_ev(proc, value, 1), ft);
  4870. // @QuaternionLayout
  4871. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 3), real);
  4872. ir_emit_store(proc, ir_emit_struct_ep(proc, gen, 0), imag);
  4873. return ir_emit_load(proc, gen);
  4874. }
  4875. // float <-> integer
  4876. if (is_type_float(src) && is_type_integer(dst)) {
  4877. irConvKind kind = irConv_fptosi;
  4878. if (is_type_unsigned(dst)) {
  4879. kind = irConv_fptoui;
  4880. }
  4881. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4882. }
  4883. if (is_type_integer(src) && is_type_float(dst)) {
  4884. irConvKind kind = irConv_sitofp;
  4885. if (is_type_unsigned(src)) {
  4886. kind = irConv_uitofp;
  4887. }
  4888. return ir_emit(proc, ir_instr_conv(proc, kind, value, src_type, t));
  4889. }
  4890. // Pointer <-> uintptr
  4891. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4892. return ir_emit_ptr_to_uintptr(proc, value, t);
  4893. }
  4894. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4895. return ir_emit_uintptr_to_ptr(proc, value, t);
  4896. }
  4897. if (is_type_union(dst)) {
  4898. for_array(i, dst->Union.variants) {
  4899. Type *vt = dst->Union.variants[i];
  4900. if (are_types_identical(vt, src_type)) {
  4901. ir_emit_comment(proc, str_lit("union - child to parent"));
  4902. gbAllocator a = ir_allocator();
  4903. irValue *parent = ir_add_local_generated(proc, t, true);
  4904. ir_emit_store_union_variant(proc, parent, value, vt);
  4905. return ir_emit_load(proc, parent);
  4906. }
  4907. }
  4908. }
  4909. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  4910. // subtype polymorphism casting
  4911. if (check_is_assignable_to_using_subtype(src_type, t)) {
  4912. Type *st = type_deref(src_type);
  4913. Type *pst = st;
  4914. st = type_deref(st);
  4915. bool st_is_ptr = is_type_pointer(src_type);
  4916. st = base_type(st);
  4917. Type *dt = t;
  4918. bool dt_is_ptr = type_deref(dt) != dt;
  4919. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  4920. String field_name = ir_lookup_subtype_polymorphic_field(proc->module->info, t, src_type);
  4921. if (field_name.len > 0) {
  4922. // NOTE(bill): It can be casted
  4923. Selection sel = lookup_field(st, field_name, false, true);
  4924. if (sel.entity != nullptr) {
  4925. ir_emit_comment(proc, str_lit("cast - polymorphism"));
  4926. if (st_is_ptr) {
  4927. irValue *res = ir_emit_deep_field_gep(proc, value, sel);
  4928. Type *rt = ir_type(res);
  4929. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4930. res = ir_emit_load(proc, res);
  4931. }
  4932. return res;
  4933. } else {
  4934. if (is_type_pointer(ir_type(value))) {
  4935. Type *rt = ir_type(value);
  4936. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4937. value = ir_emit_load(proc, value);
  4938. } else {
  4939. value = ir_emit_deep_field_gep(proc, value, sel);
  4940. return ir_emit_load(proc, value);
  4941. }
  4942. }
  4943. return ir_emit_deep_field_ev(proc, value, sel);
  4944. }
  4945. } else {
  4946. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  4947. }
  4948. }
  4949. }
  4950. // Pointer <-> Pointer
  4951. if (is_type_pointer(src) && is_type_pointer(dst)) {
  4952. return ir_emit_bitcast(proc, value, t);
  4953. }
  4954. // proc <-> proc
  4955. if (is_type_proc(src) && is_type_proc(dst)) {
  4956. return ir_emit_bitcast(proc, value, t);
  4957. }
  4958. // pointer -> proc
  4959. if (is_type_pointer(src) && is_type_proc(dst)) {
  4960. return ir_emit_bitcast(proc, value, t);
  4961. }
  4962. // proc -> pointer
  4963. if (is_type_proc(src) && is_type_pointer(dst)) {
  4964. return ir_emit_bitcast(proc, value, t);
  4965. }
  4966. // []byte/[]u8 <-> string
  4967. if (is_type_u8_slice(src) && is_type_string(dst)) {
  4968. irValue *elem = ir_slice_elem(proc, value);
  4969. irValue *len = ir_slice_len(proc, value);
  4970. return ir_emit_string(proc, elem, len);
  4971. }
  4972. if (is_type_string(src) && is_type_u8_slice(dst)) {
  4973. irValue *elem = ir_string_elem(proc, value);
  4974. irValue *elem_ptr = ir_add_local_generated(proc, ir_type(elem), false);
  4975. ir_emit_store(proc, elem_ptr, elem);
  4976. irValue *len = ir_string_len(proc, value);
  4977. irValue *slice = ir_add_local_slice(proc, t, elem_ptr, v_zero, len);
  4978. return ir_emit_load(proc, slice);
  4979. }
  4980. if (is_type_array(dst)) {
  4981. Type *elem = dst->Array.elem;
  4982. irValue *e = ir_emit_conv(proc, value, elem);
  4983. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4984. irValue *v = ir_add_local_generated(proc, t, false);
  4985. isize index_count = cast(isize)dst->Array.count;
  4986. for (i32 i = 0; i < index_count; i++) {
  4987. irValue *elem = ir_emit_array_epi(proc, v, i);
  4988. ir_emit_store(proc, elem, e);
  4989. }
  4990. return ir_emit_load(proc, v);
  4991. }
  4992. if (is_type_any(dst)) {
  4993. irValue *result = ir_add_local_generated(proc, t_any, true);
  4994. if (is_type_untyped_nil(src)) {
  4995. return ir_emit_load(proc, result);
  4996. }
  4997. Type *st = default_type(src_type);
  4998. irValue *data = ir_address_from_load_or_generate_local(proc, value);
  4999. GB_ASSERT_MSG(is_type_pointer(ir_type(data)), type_to_string(ir_type(data)));
  5000. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5001. data = ir_emit_conv(proc, data, t_rawptr);
  5002. irValue *id = ir_typeid(proc->module, st);
  5003. ir_emit_store(proc, ir_emit_struct_ep(proc, result, 0), data);
  5004. ir_emit_store(proc, ir_emit_struct_ep(proc, result, 1), id);
  5005. return ir_emit_load(proc, result);
  5006. }
  5007. if (is_type_untyped(src)) {
  5008. if (is_type_string(src) && is_type_string(dst)) {
  5009. irValue *result = ir_add_local_generated(proc, t, false);
  5010. ir_emit_store(proc, result, value);
  5011. return ir_emit_load(proc, result);
  5012. }
  5013. }
  5014. gb_printf_err("ir_emit_conv: src -> dst\n");
  5015. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5016. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5017. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5018. type_to_string(src_type), type_to_string(t),
  5019. LIT(proc->name));
  5020. return nullptr;
  5021. }
  5022. bool ir_is_type_aggregate(Type *t) {
  5023. t = base_type(t);
  5024. switch (t->kind) {
  5025. case Type_Basic:
  5026. switch (t->Basic.kind) {
  5027. case Basic_string:
  5028. case Basic_any:
  5029. return true;
  5030. // case Basic_complex32:
  5031. case Basic_complex64:
  5032. case Basic_complex128:
  5033. case Basic_quaternion128:
  5034. case Basic_quaternion256:
  5035. return true;
  5036. }
  5037. break;
  5038. case Type_Pointer:
  5039. return false;
  5040. case Type_Array:
  5041. case Type_Slice:
  5042. case Type_Struct:
  5043. case Type_Union:
  5044. case Type_Tuple:
  5045. case Type_DynamicArray:
  5046. case Type_Map:
  5047. case Type_BitField:
  5048. case Type_SimdVector:
  5049. return true;
  5050. case Type_Named:
  5051. return ir_is_type_aggregate(t->Named.base);
  5052. }
  5053. return false;
  5054. }
  5055. irValue *ir_emit_transmute(irProcedure *proc, irValue *value, Type *t) {
  5056. Type *src_type = ir_type(value);
  5057. if (are_types_identical(t, src_type)) {
  5058. return value;
  5059. }
  5060. Type *src = base_type(src_type);
  5061. Type *dst = base_type(t);
  5062. irModule *m = proc->module;
  5063. i64 sz = type_size_of(src);
  5064. i64 dz = type_size_of(dst);
  5065. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5066. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5067. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5068. return ir_emit_uintptr_to_ptr(proc, value, t);
  5069. }
  5070. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5071. return ir_emit_ptr_to_uintptr(proc, value, t);
  5072. }
  5073. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5074. irValue *ptr = ir_emit_uintptr_to_ptr(proc, value, t_rawptr);
  5075. return ir_emit_bitcast(proc, ptr, dst);
  5076. }
  5077. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5078. irValue *ptr = ir_emit_uintptr_to_ptr(proc, value, t_rawptr);
  5079. return ir_emit_bitcast(proc, ptr, dst);
  5080. }
  5081. if (is_type_float(src) && is_type_float(dst)) {
  5082. return ir_emit_bitcast(proc, value, t);
  5083. }
  5084. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5085. Type *vt = core_type(ir_type(value));
  5086. return ir_emit(proc, ir_instr_conv(proc, irConv_inttoptr, value, vt, t));
  5087. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5088. Type *vt = core_type(ir_type(value));
  5089. return ir_emit(proc, ir_instr_conv(proc, irConv_ptrtoint, value, vt, t));
  5090. }
  5091. if (ir_is_type_aggregate(src) || ir_is_type_aggregate(dst)) {
  5092. irValue *s = ir_address_from_load_or_generate_local(proc, value);
  5093. irValue *d = ir_emit_bitcast(proc, s, alloc_type_pointer(t));
  5094. return ir_emit_load(proc, d);
  5095. }
  5096. // TODO(bill): Actually figure out what the conversion needs to be correctly 'cause LLVM
  5097. return ir_emit_bitcast(proc, value, t);
  5098. }
  5099. irValue *ir_emit_union_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  5100. gbAllocator a = ir_allocator();
  5101. Type *src_type = ir_type(value);
  5102. bool is_ptr = is_type_pointer(src_type);
  5103. bool is_tuple = true;
  5104. Type *tuple = type;
  5105. if (type->kind != Type_Tuple) {
  5106. is_tuple = false;
  5107. tuple = make_optional_ok_type(type);
  5108. }
  5109. irValue *v = ir_add_local_generated(proc, tuple, true);
  5110. if (is_ptr) {
  5111. value = ir_emit_load(proc, value);
  5112. }
  5113. Type *src = base_type(type_deref(src_type));
  5114. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  5115. Type *dst = tuple->Tuple.variables[0]->type;
  5116. irValue *value_ = ir_address_from_load_or_generate_local(proc, value);
  5117. irValue *tag = nullptr;
  5118. irValue *dst_tag = nullptr;
  5119. irValue *cond = nullptr;
  5120. irValue *data = nullptr;
  5121. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  5122. irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
  5123. if (is_type_union_maybe_pointer(src)) {
  5124. data = ir_emit_load(proc, ir_emit_conv(proc, value_, ir_type(gep0)));
  5125. } else {
  5126. tag = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, value_));
  5127. dst_tag = ir_const_union_tag(src, dst);
  5128. }
  5129. irBlock *ok_block = ir_new_block(proc, nullptr, "union_cast.ok");
  5130. irBlock *end_block = ir_new_block(proc, nullptr, "union_cast.end");
  5131. if (data != nullptr) {
  5132. GB_ASSERT(is_type_union_maybe_pointer(src));
  5133. cond = ir_emit_comp_against_nil(proc, Token_NotEq, data);
  5134. } else {
  5135. cond = ir_emit_comp(proc, Token_CmpEq, tag, dst_tag);
  5136. }
  5137. ir_emit_if(proc, cond, ok_block, end_block);
  5138. ir_start_block(proc, ok_block);
  5139. if (data == nullptr) {
  5140. data = ir_emit_load(proc, ir_emit_conv(proc, value_, ir_type(gep0)));
  5141. }
  5142. ir_emit_store(proc, gep0, data);
  5143. ir_emit_store(proc, gep1, v_true);
  5144. ir_emit_jump(proc, end_block);
  5145. ir_start_block(proc, end_block);
  5146. if (!is_tuple) {
  5147. if (do_conversion_check) {
  5148. // NOTE(bill): Panic on invalid conversion
  5149. Type *dst_type = tuple->Tuple.variables[0]->type;
  5150. irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
  5151. auto args = array_make<irValue *>(ir_allocator(), 6);
  5152. args[0] = ok;
  5153. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  5154. args[2] = ir_const_int(pos.line);
  5155. args[3] = ir_const_int(pos.column);
  5156. args[4] = ir_typeid(proc->module, src_type);
  5157. args[5] = ir_typeid(proc->module, dst_type);
  5158. ir_emit_runtime_call(proc, "type_assertion_check", args);
  5159. }
  5160. return ir_emit_load(proc, ir_emit_struct_ep(proc, v, 0));
  5161. }
  5162. return ir_emit_load(proc, v);
  5163. }
  5164. irAddr ir_emit_any_cast_addr(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
  5165. gbAllocator a = ir_allocator();
  5166. Type *src_type = ir_type(value);
  5167. if (is_type_pointer(src_type)) {
  5168. value = ir_emit_load(proc, value);
  5169. }
  5170. bool is_tuple = true;
  5171. Type *tuple = type;
  5172. if (type->kind != Type_Tuple) {
  5173. is_tuple = false;
  5174. tuple = make_optional_ok_type(type);
  5175. }
  5176. Type *dst_type = tuple->Tuple.variables[0]->type;
  5177. irValue *v = ir_add_local_generated(proc, tuple, true);
  5178. irValue *dst_typeid = ir_typeid(proc->module, dst_type);
  5179. irValue *any_typeid = ir_emit_struct_ev(proc, value, 1);
  5180. irBlock *ok_block = ir_new_block(proc, nullptr, "any_cast.ok");
  5181. irBlock *end_block = ir_new_block(proc, nullptr, "any_cast.end");
  5182. irValue *cond = ir_emit_comp(proc, Token_CmpEq, any_typeid, dst_typeid);
  5183. ir_emit_if(proc, cond, ok_block, end_block);
  5184. ir_start_block(proc, ok_block);
  5185. irValue *gep0 = ir_emit_struct_ep(proc, v, 0);
  5186. irValue *gep1 = ir_emit_struct_ep(proc, v, 1);
  5187. irValue *any_data = ir_emit_struct_ev(proc, value, 0);
  5188. irValue *ptr = ir_emit_conv(proc, any_data, alloc_type_pointer(dst_type));
  5189. ir_emit_store(proc, gep0, ir_emit_load(proc, ptr));
  5190. ir_emit_store(proc, gep1, v_true);
  5191. ir_emit_jump(proc, end_block);
  5192. ir_start_block(proc, end_block);
  5193. if (!is_tuple) {
  5194. // NOTE(bill): Panic on invalid conversion
  5195. irValue *ok = ir_emit_load(proc, ir_emit_struct_ep(proc, v, 1));
  5196. auto args = array_make<irValue *>(ir_allocator(), 6);
  5197. args[0] = ok;
  5198. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  5199. args[2] = ir_const_int(pos.line);
  5200. args[3] = ir_const_int(pos.column);
  5201. args[4] = any_typeid;
  5202. args[5] = dst_typeid;
  5203. ir_emit_runtime_call(proc, "type_assertion_check", args);
  5204. return ir_addr(ir_emit_struct_ep(proc, v, 0));
  5205. }
  5206. return ir_addr(v);
  5207. }
  5208. irValue *ir_emit_any_cast(irProcedure *proc, irValue *value, Type *type, TokenPos pos) {
  5209. return ir_addr_load(proc, ir_emit_any_cast_addr(proc, value, type, pos));
  5210. }
  5211. // TODO(bill): Try and make a lot of this constant aggregate literals in LLVM IR
  5212. gb_global irValue *ir_global_type_info_data = nullptr;
  5213. gb_global irValue *ir_global_type_info_member_types = nullptr;
  5214. gb_global irValue *ir_global_type_info_member_names = nullptr;
  5215. gb_global irValue *ir_global_type_info_member_offsets = nullptr;
  5216. gb_global irValue *ir_global_type_info_member_usings = nullptr;
  5217. gb_global irValue *ir_global_type_info_member_tags = nullptr;
  5218. gb_global i32 ir_global_type_info_data_index = 0;
  5219. gb_global i32 ir_global_type_info_member_types_index = 0;
  5220. gb_global i32 ir_global_type_info_member_names_index = 0;
  5221. gb_global i32 ir_global_type_info_member_offsets_index = 0;
  5222. gb_global i32 ir_global_type_info_member_usings_index = 0;
  5223. gb_global i32 ir_global_type_info_member_tags_index = 0;
  5224. isize ir_type_info_count(CheckerInfo *info) {
  5225. return info->minimum_dependency_type_info_set.entries.count+1;
  5226. }
  5227. isize ir_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  5228. isize index = type_info_index(info, type, false);
  5229. if (index >= 0) {
  5230. auto *set = &info->minimum_dependency_type_info_set;
  5231. for_array(i, set->entries) {
  5232. if (set->entries[i].ptr == index) {
  5233. return i+1;
  5234. }
  5235. }
  5236. }
  5237. if (err_on_not_found) {
  5238. GB_PANIC("NOT FOUND ir_type_info_index %s @ index %td", type_to_string(type), index);
  5239. }
  5240. return -1;
  5241. }
  5242. irValue *ir_type_info(irProcedure *proc, Type *type) {
  5243. CheckerInfo *info = proc->module->info;
  5244. type = default_type(type);
  5245. i32 id = cast(i32)ir_type_info_index(info, type);
  5246. GB_ASSERT(id >= 0);
  5247. return ir_emit_array_ep(proc, ir_global_type_info_data, ir_const_i32(id));
  5248. }
  5249. irValue *ir_typeid(irModule *m, Type *type) {
  5250. type = default_type(type);
  5251. u64 id = cast(u64)ir_type_info_index(m->info, type);
  5252. GB_ASSERT(id >= 0);
  5253. u64 kind = Typeid_Invalid;
  5254. u64 named = is_type_named(type) && type->kind != Type_Basic;
  5255. u64 special = 0;
  5256. u64 reserved = 0;
  5257. Type *bt = base_type(type);
  5258. TypeKind tk = bt->kind;
  5259. switch (tk) {
  5260. case Type_Basic: {
  5261. u32 flags = bt->Basic.flags;
  5262. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  5263. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  5264. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  5265. if (flags & BasicFlag_Float) kind = Typeid_Float;
  5266. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  5267. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  5268. if (flags & BasicFlag_String) kind = Typeid_String;
  5269. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  5270. } break;
  5271. case Type_Pointer: kind = Typeid_Pointer; break;
  5272. case Type_Array: kind = Typeid_Array; break;
  5273. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  5274. case Type_Slice: kind = Typeid_Slice; break;
  5275. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  5276. case Type_Map: kind = Typeid_Map; break;
  5277. case Type_Struct: kind = Typeid_Struct; break;
  5278. case Type_Enum: kind = Typeid_Enum; break;
  5279. case Type_Union: kind = Typeid_Union; break;
  5280. case Type_Tuple: kind = Typeid_Tuple; break;
  5281. case Type_Proc: kind = Typeid_Procedure; break;
  5282. case Type_BitField: kind = Typeid_Bit_Field; break;
  5283. case Type_BitSet: kind = Typeid_Bit_Set; break;
  5284. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  5285. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  5286. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  5287. }
  5288. if (is_type_cstring(type)) {
  5289. special = 1;
  5290. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  5291. special = 1;
  5292. }
  5293. u64 data = 0;
  5294. if (build_context.word_size == 4) {
  5295. data |= (id &~ (1u<<24)) << 0u; // index
  5296. data |= (kind &~ (1u<<5)) << 24u; // kind
  5297. data |= (named &~ (1u<<1)) << 29u; // kind
  5298. data |= (special &~ (1u<<1)) << 30u; // kind
  5299. data |= (reserved &~ (1u<<1)) << 31u; // kind
  5300. } else {
  5301. GB_ASSERT(build_context.word_size == 8);
  5302. data |= (id &~ (1ull<<56)) << 0ul; // index
  5303. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  5304. data |= (named &~ (1ull<<1)) << 61ull; // kind
  5305. data |= (special &~ (1ull<<1)) << 62ull; // kind
  5306. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  5307. }
  5308. return ir_value_constant(t_typeid, exact_value_u64(data));
  5309. }
  5310. irValue *ir_emit_logical_binary_expr(irProcedure *proc, TokenKind op, Ast *left, Ast *right, Type *type) {
  5311. irBlock *rhs = ir_new_block(proc, nullptr, "logical.cmp.rhs");
  5312. irBlock *done = ir_new_block(proc, nullptr, "logical.cmp.done");
  5313. type = default_type(type);
  5314. irValue *short_circuit = nullptr;
  5315. if (op == Token_CmpAnd) {
  5316. ir_build_cond(proc, left, rhs, done);
  5317. short_circuit = v_false;
  5318. } else if (op == Token_CmpOr) {
  5319. ir_build_cond(proc, left, done, rhs);
  5320. short_circuit = v_true;
  5321. }
  5322. if (rhs->preds.count == 0) {
  5323. ir_start_block(proc, done);
  5324. return short_circuit;
  5325. }
  5326. if (done->preds.count == 0) {
  5327. ir_start_block(proc, rhs);
  5328. return ir_build_expr(proc, right);
  5329. }
  5330. auto edges = array_make<irValue *>(ir_allocator(), 0, done->preds.count+1);
  5331. for_array(i, done->preds) {
  5332. irValue *edge = ir_emit_conv(proc, short_circuit, type);
  5333. array_add(&edges, edge);
  5334. }
  5335. ir_start_block(proc, rhs);
  5336. irValue *edge = ir_emit_conv(proc, ir_build_expr(proc, right), type);
  5337. array_add(&edges, edge);
  5338. ir_emit_jump(proc, done);
  5339. ir_start_block(proc, done);
  5340. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  5341. }
  5342. irValue *ir_emit_logical_binary_expr(irProcedure *proc, Ast *expr) {
  5343. ast_node(be, BinaryExpr, expr);
  5344. Type *type = type_of_expr(expr);
  5345. type = default_type(type);
  5346. return ir_emit_logical_binary_expr(proc, be->op.kind, be->left, be->right, type);
  5347. }
  5348. void ir_emit_bounds_check(irProcedure *proc, Token token, irValue *index, irValue *len) {
  5349. if (build_context.no_bounds_check) {
  5350. return;
  5351. }
  5352. if ((proc->module->state_flags & StateFlag_no_bounds_check) != 0) {
  5353. return;
  5354. }
  5355. index = ir_emit_conv(proc, index, t_int);
  5356. len = ir_emit_conv(proc, len, t_int);
  5357. gbAllocator a = ir_allocator();
  5358. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  5359. irValue *line = ir_const_int(token.pos.line);
  5360. irValue *column = ir_const_int(token.pos.column);
  5361. auto args = array_make<irValue *>(ir_allocator(), 5);
  5362. args[0] = file;
  5363. args[1] = line;
  5364. args[2] = column;
  5365. args[3] = index;
  5366. args[4] = len;
  5367. ir_emit_runtime_call(proc, "bounds_check_error", args);
  5368. }
  5369. void ir_emit_slice_bounds_check(irProcedure *proc, Token token, irValue *low, irValue *high, irValue *len, bool lower_value_used) {
  5370. if (build_context.no_bounds_check) {
  5371. return;
  5372. }
  5373. if ((proc->module->state_flags & StateFlag_no_bounds_check) != 0) {
  5374. return;
  5375. }
  5376. gbAllocator a = ir_allocator();
  5377. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  5378. irValue *line = ir_const_int(token.pos.line);
  5379. irValue *column = ir_const_int(token.pos.column);
  5380. high = ir_emit_conv(proc, high, t_int);
  5381. if (!lower_value_used) {
  5382. auto args = array_make<irValue *>(ir_allocator(), 5);
  5383. args[0] = file;
  5384. args[1] = line;
  5385. args[2] = column;
  5386. args[3] = high;
  5387. args[4] = len;
  5388. ir_emit_runtime_call(proc, "slice_expr_error_hi", args);
  5389. } else {
  5390. // No need to convert unless used
  5391. low = ir_emit_conv(proc, low, t_int);
  5392. auto args = array_make<irValue *>(ir_allocator(), 6);
  5393. args[0] = file;
  5394. args[1] = line;
  5395. args[2] = column;
  5396. args[3] = low;
  5397. args[4] = high;
  5398. args[5] = len;
  5399. ir_emit_runtime_call(proc, "slice_expr_error_lo_hi", args);
  5400. }
  5401. }
  5402. void ir_emit_dynamic_array_bounds_check(irProcedure *proc, Token token, irValue *low, irValue *high, irValue *max) {
  5403. if (build_context.no_bounds_check) {
  5404. return;
  5405. }
  5406. if ((proc->module->state_flags & StateFlag_no_bounds_check) != 0) {
  5407. return;
  5408. }
  5409. gbAllocator a = ir_allocator();
  5410. irValue *file = ir_find_or_add_entity_string(proc->module, token.pos.file);
  5411. irValue *line = ir_const_int(token.pos.line);
  5412. irValue *column = ir_const_int(token.pos.column);
  5413. low = ir_emit_conv(proc, low, t_int);
  5414. high = ir_emit_conv(proc, high, t_int);
  5415. auto args = array_make<irValue *>(ir_allocator(), 6);
  5416. args[0] = file;
  5417. args[1] = line;
  5418. args[2] = column;
  5419. args[3] = low;
  5420. args[4] = high;
  5421. args[5] = max;
  5422. ir_emit_runtime_call(proc, "dynamic_array_expr_error", args);
  5423. }
  5424. ////////////////////////////////////////////////////////////////
  5425. //
  5426. // @Build
  5427. //
  5428. ////////////////////////////////////////////////////////////////
  5429. String ir_mangle_name(irGen *s, Entity *e) {
  5430. irModule *m = &s->module;
  5431. CheckerInfo *info = m->info;
  5432. gbAllocator a = ir_allocator();
  5433. String name = e->token.string;
  5434. AstPackage *pkg = e->pkg;
  5435. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  5436. String pkgn = pkg->name;
  5437. GB_ASSERT(!rune_is_digit(pkgn[0]));
  5438. if (pkgn == "llvm") {
  5439. pkgn = str_lit("llvm$");
  5440. }
  5441. isize max_len = pkgn.len + 1 + name.len + 1;
  5442. bool require_suffix_id = is_type_polymorphic(e->type, true);
  5443. if (e->flags & EntityFlag_NotExported) {
  5444. require_suffix_id = true;
  5445. }
  5446. if (require_suffix_id) {
  5447. max_len += 21;
  5448. }
  5449. u8 *new_name = gb_alloc_array(a, u8, max_len);
  5450. isize new_name_len = gb_snprintf(
  5451. cast(char *)new_name, max_len,
  5452. "%.*s.%.*s", LIT(pkgn), LIT(name)
  5453. );
  5454. if (require_suffix_id) {
  5455. char *str = cast(char *)new_name + new_name_len-1;
  5456. isize len = max_len-new_name_len;
  5457. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  5458. new_name_len += extra-1;
  5459. }
  5460. return make_string(new_name, new_name_len-1);
  5461. }
  5462. void ir_mangle_add_sub_type_name(irModule *m, Entity *field, String parent) {
  5463. if (field->kind != Entity_TypeName) {
  5464. return;
  5465. }
  5466. if (is_type_proc(field->type)) {
  5467. set_procedure_abi_types(heap_allocator(), field->type);
  5468. }
  5469. String cn = field->token.string;
  5470. isize max_len = parent.len + 1 + 16 + 1 + cn.len;
  5471. bool require_suffix_id = is_type_polymorphic(field->type, true);
  5472. if (require_suffix_id) {
  5473. max_len += 21;
  5474. }
  5475. u8 *new_name = gb_alloc_array(ir_allocator(), u8, max_len);
  5476. isize new_name_len = gb_snprintf(cast(char *)new_name, max_len,
  5477. "%.*s.%.*s", LIT(parent), LIT(cn));
  5478. if (require_suffix_id) {
  5479. char *str = cast(char *)new_name + new_name_len-1;
  5480. isize len = max_len-new_name_len;
  5481. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)field->id);
  5482. new_name_len += extra-1;
  5483. }
  5484. String child = {new_name, new_name_len-1};
  5485. GB_ASSERT(child.len > 0);
  5486. ir_add_entity_name(m, field, child);
  5487. ir_gen_global_type_name(m, field, child);
  5488. }
  5489. irBranchBlocks ir_lookup_branch_blocks(irProcedure *proc, Ast *ident) {
  5490. GB_ASSERT(ident->kind == Ast_Ident);
  5491. Entity *e = entity_of_node(ident);
  5492. GB_ASSERT(e->kind == Entity_Label);
  5493. for_array(i, proc->branch_blocks) {
  5494. irBranchBlocks *b = &proc->branch_blocks[i];
  5495. if (b->label == e->Label.node) {
  5496. return *b;
  5497. }
  5498. }
  5499. GB_PANIC("Unreachable");
  5500. irBranchBlocks empty = {};
  5501. return empty;
  5502. }
  5503. irTargetList *ir_push_target_list(irProcedure *proc, Ast *label, irBlock *break_, irBlock *continue_, irBlock *fallthrough_) {
  5504. irTargetList *tl = gb_alloc_item(ir_allocator(), irTargetList);
  5505. tl->prev = proc->target_list;
  5506. tl->break_ = break_;
  5507. tl->continue_ = continue_;
  5508. tl->fallthrough_ = fallthrough_;
  5509. proc->target_list = tl;
  5510. if (label != nullptr) { // Set label blocks
  5511. GB_ASSERT(label->kind == Ast_Label);
  5512. for_array(i, proc->branch_blocks) {
  5513. irBranchBlocks *b = &proc->branch_blocks[i];
  5514. GB_ASSERT(b->label != nullptr && label != nullptr);
  5515. GB_ASSERT(b->label->kind == Ast_Label);
  5516. if (b->label == label) {
  5517. b->break_ = break_;
  5518. b->continue_ = continue_;
  5519. return tl;
  5520. }
  5521. }
  5522. GB_PANIC("ir_set_label_blocks: Unreachable");
  5523. }
  5524. return tl;
  5525. }
  5526. void ir_pop_target_list(irProcedure *proc) {
  5527. proc->target_list = proc->target_list->prev;
  5528. }
  5529. irValue *ir_gen_anonymous_proc_lit(irModule *m, String prefix_name, Ast *expr, irProcedure *proc) {
  5530. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  5531. if (found != nullptr) {
  5532. return *found;
  5533. }
  5534. ast_node(pl, ProcLit, expr);
  5535. // NOTE(bill): Generate a new name
  5536. // parent$count
  5537. isize name_len = prefix_name.len + 1 + 8 + 1;
  5538. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  5539. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  5540. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  5541. String name = make_string(name_text, name_len-1);
  5542. Type *type = type_of_expr(expr);
  5543. set_procedure_abi_types(heap_allocator(), type);
  5544. irValue *value = ir_value_procedure(m, nullptr, type, pl->type, pl->body, name);
  5545. value->Proc.tags = pl->tags;
  5546. value->Proc.inlining = pl->inlining;
  5547. value->Proc.parent = proc;
  5548. array_add(&m->procs_to_generate, value);
  5549. if (proc != nullptr) {
  5550. array_add(&proc->children, &value->Proc);
  5551. } else {
  5552. string_map_set(&m->members, name, value);
  5553. }
  5554. map_set(&m->anonymous_proc_lits, hash_pointer(expr), value);
  5555. return value;
  5556. }
  5557. void ir_gen_global_type_name(irModule *m, Entity *e, String name) {
  5558. if (e->type == nullptr) return;
  5559. if (e->kind == Entity_TypeName && e->type->kind == Type_Named) {
  5560. if (e != e->type->Named.type_name) {
  5561. // NOTE(bill): Is alias
  5562. return;
  5563. }
  5564. }
  5565. Type *bt = base_type(e->type);
  5566. bool is_poly = is_type_polymorphic(bt);
  5567. if (!is_poly) {
  5568. if (bt->kind == Type_Struct &&
  5569. bt->Struct.is_polymorphic &&
  5570. !bt->Struct.is_poly_specialized) {
  5571. is_poly = true;
  5572. }
  5573. }
  5574. if (is_poly) {
  5575. auto found = map_get(&m->info->gen_types, hash_pointer(e->type));
  5576. if (found != nullptr) {
  5577. for_array(i, *found) {
  5578. Entity *sub = (*found)[i];
  5579. // gb_printf_err("--> %.*s %p\n", LIT(sub->token.string), sub);
  5580. if (ir_min_dep_entity(m, sub)) {
  5581. ir_mangle_add_sub_type_name(m, sub, name);
  5582. }
  5583. }
  5584. }
  5585. return;
  5586. }
  5587. if (!ir_min_dep_entity(m, e)) {
  5588. return;
  5589. }
  5590. irValue *t = ir_value_type_name(name, e->type);
  5591. ir_module_add_value(m, e, t);
  5592. string_map_set(&m->members, name, t);
  5593. // if (bt->kind == Type_Struct) {
  5594. // Scope *s = bt->Struct.scope;
  5595. // if (s != nullptr) {
  5596. // for_array(i, s->elements.entries) {
  5597. // Entity *e = s->elements.entries[i].value;
  5598. // if (e->kind == Entity_TypeName) {
  5599. // ir_mangle_add_sub_type_name(m, e, name);
  5600. // }
  5601. // }
  5602. // }
  5603. // }
  5604. }
  5605. void ir_build_defer_stmt(irProcedure *proc, irDefer d) {
  5606. irBlock *b = ir_new_block(proc, nullptr, "defer");
  5607. // NOTE(bill): The prev block may defer injection before it's terminator
  5608. irInstr *last_instr = ir_get_last_instr(proc->curr_block);
  5609. if (last_instr == nullptr || !ir_is_instr_terminating(last_instr)) {
  5610. ir_emit_jump(proc, b);
  5611. }
  5612. ir_start_block(proc, b);
  5613. ir_emit_comment(proc, str_lit("defer"));
  5614. if (d.kind == irDefer_Node) {
  5615. ir_build_stmt(proc, d.stmt);
  5616. } else if (d.kind == irDefer_Instr) {
  5617. // NOTE(bill): Need to make a new copy
  5618. irValue *instr = cast(irValue *)gb_alloc_copy(ir_allocator(), d.instr, gb_size_of(irValue));
  5619. ir_emit(proc, instr);
  5620. } else if (d.kind == irDefer_Proc) {
  5621. ir_emit_call(proc, d.proc.deferred, d.proc.result_as_args);
  5622. }
  5623. }
  5624. irValue *ir_emit_min(irProcedure *proc, Type *t, irValue *x, irValue *y) {
  5625. x = ir_emit_conv(proc, x, t);
  5626. y = ir_emit_conv(proc, y, t);
  5627. if (is_type_float(t)) {
  5628. gbAllocator a = ir_allocator();
  5629. i64 sz = 8*type_size_of(t);
  5630. auto args = array_make<irValue *>(ir_allocator(), 2);
  5631. args[0] = x;
  5632. args[1] = y;
  5633. switch (sz) {
  5634. case 32: return ir_emit_runtime_call(proc, "min_f32", args);
  5635. case 64: return ir_emit_runtime_call(proc, "min_f64", args);
  5636. }
  5637. GB_PANIC("Unknown float type");
  5638. }
  5639. return ir_emit_select(proc, ir_emit_comp(proc, Token_Lt, x, y), x, y);
  5640. }
  5641. irValue *ir_emit_max(irProcedure *proc, Type *t, irValue *x, irValue *y) {
  5642. x = ir_emit_conv(proc, x, t);
  5643. y = ir_emit_conv(proc, y, t);
  5644. if (is_type_float(t)) {
  5645. gbAllocator a = ir_allocator();
  5646. i64 sz = 8*type_size_of(t);
  5647. auto args = array_make<irValue *>(ir_allocator(), 2);
  5648. args[0] = x;
  5649. args[1] = y;
  5650. switch (sz) {
  5651. case 32: return ir_emit_runtime_call(proc, "max_f32", args);
  5652. case 64: return ir_emit_runtime_call(proc, "max_f64", args);
  5653. }
  5654. GB_PANIC("Unknown float type");
  5655. }
  5656. return ir_emit_select(proc, ir_emit_comp(proc, Token_Gt, x, y), x, y);
  5657. }
  5658. irValue *ir_emit_clamp(irProcedure *proc, Type *t, irValue *x, irValue *min, irValue *max) {
  5659. ir_emit_comment(proc, str_lit("clamp"));
  5660. irValue *z = nullptr;
  5661. z = ir_emit_max(proc, t, x, min);
  5662. z = ir_emit_min(proc, t, z, max);
  5663. return z;
  5664. }
  5665. irValue *ir_find_global_variable(irProcedure *proc, String name) {
  5666. AstPackage *pkg = proc->module->info->runtime_package;
  5667. Entity *e = scope_lookup_current(pkg->scope, name);
  5668. irValue **value = map_get(&proc->module->values, hash_entity(e));
  5669. GB_ASSERT_MSG(value != nullptr, "Unable to find global variable '%.*s'", LIT(name));
  5670. return *value;
  5671. }
  5672. void ir_build_stmt_list(irProcedure *proc, Array<Ast *> stmts);
  5673. void ir_build_assign_op(irProcedure *proc, irAddr const &lhs, irValue *value, TokenKind op);
  5674. bool is_double_pointer(Type *t) {
  5675. if (!is_type_pointer(t)) {
  5676. return false;
  5677. }
  5678. Type *td = type_deref(t);
  5679. if (td == nullptr || td == t) {
  5680. return false;
  5681. }
  5682. return is_type_pointer(td);
  5683. }
  5684. u64 ir_generate_source_code_location_hash(TokenPos pos) {
  5685. u64 h = 0xcbf29ce484222325;
  5686. for (isize i = 0; i < pos.file.len; i++) {
  5687. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  5688. }
  5689. h = h ^ (u64(pos.line) * 0x100000001b3);
  5690. h = h ^ (u64(pos.column) * 0x100000001b3);
  5691. return h;
  5692. }
  5693. irValue *ir_emit_source_code_location(irProcedure *proc, String procedure, TokenPos pos) {
  5694. if (pos.file == "") {
  5695. gb_printf_err("here\n");
  5696. }
  5697. gbAllocator a = ir_allocator();
  5698. irValue *v = ir_alloc_value(irValue_SourceCodeLocation);
  5699. v->SourceCodeLocation.file = ir_find_or_add_entity_string(proc->module, pos.file);
  5700. v->SourceCodeLocation.line = ir_const_int(pos.line);
  5701. v->SourceCodeLocation.column = ir_const_int(pos.column);
  5702. v->SourceCodeLocation.procedure = ir_find_or_add_entity_string(proc->module, procedure);
  5703. v->SourceCodeLocation.hash = ir_generate_source_code_location_hash(pos);
  5704. return v;
  5705. }
  5706. irValue *ir_emit_source_code_location(irProcedure *proc, Ast *node) {
  5707. String proc_name = {};
  5708. if (proc->entity) {
  5709. proc_name = proc->entity->token.string;
  5710. }
  5711. TokenPos pos = {};
  5712. if (node) {
  5713. pos = ast_token(node).pos;
  5714. }
  5715. return ir_emit_source_code_location(proc, proc_name, pos);
  5716. }
  5717. void ir_emit_increment(irProcedure *proc, irValue *addr) {
  5718. GB_ASSERT(is_type_pointer(ir_type(addr)));
  5719. Type *type = type_deref(ir_type(addr));
  5720. ir_emit_store(proc, addr, ir_emit_arith(proc, Token_Add, ir_emit_load(proc, addr), v_one, type));
  5721. }
  5722. void ir_init_data_with_defaults(irProcedure *proc, irValue *ptr, irValue *count, Ast *expr) {
  5723. Type *elem_type = type_deref(ir_type(ptr));
  5724. GB_ASSERT(is_type_struct(elem_type) || is_type_array(elem_type));
  5725. irValue *index = ir_add_local_generated(proc, t_int, false);
  5726. ir_emit_store(proc, index, ir_const_int(0));
  5727. irBlock *loop = nullptr;
  5728. irBlock *done = nullptr;
  5729. irBlock *body = nullptr;
  5730. loop = ir_new_block(proc, nullptr, "make.init.loop");
  5731. ir_emit_jump(proc, loop);
  5732. ir_start_block(proc, loop);
  5733. body = ir_new_block(proc, nullptr, "make.init.body");
  5734. done = ir_new_block(proc, nullptr, "make.init.done");
  5735. irValue *cond = ir_emit_comp(proc, Token_Lt, ir_emit_load(proc, index), count);
  5736. ir_emit_if(proc, cond, body, done);
  5737. ir_start_block(proc, body);
  5738. irValue *offset_ptr = ir_emit_ptr_offset(proc, ptr, ir_emit_load(proc, index));
  5739. ir_emit(proc, ir_instr_zero_init(proc, offset_ptr)); // Use simple zero for this
  5740. // ir_emit_zero_init(proc, offset_ptr, expr);
  5741. ir_emit_increment(proc, index);
  5742. ir_emit_jump(proc, loop);
  5743. ir_start_block(proc, done);
  5744. }
  5745. irValue *ir_build_builtin_proc(irProcedure *proc, Ast *expr, TypeAndValue tv, BuiltinProcId id) {
  5746. ast_node(ce, CallExpr, expr);
  5747. switch (id) {
  5748. case BuiltinProc_DIRECTIVE: {
  5749. ast_node(bd, BasicDirective, ce->proc);
  5750. String name = bd->name;
  5751. GB_ASSERT(name == "location");
  5752. String procedure = proc->entity->token.string;
  5753. TokenPos pos = ast_token(ce->proc).pos;
  5754. if (ce->args.count > 0) {
  5755. Ast *ident = unselector_expr(ce->args[0]);
  5756. GB_ASSERT(ident->kind == Ast_Ident);
  5757. Entity *e = entity_of_node(ident);
  5758. GB_ASSERT(e != nullptr);
  5759. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  5760. procedure = e->parent_proc_decl->entity->token.string;
  5761. } else {
  5762. procedure = str_lit("");
  5763. }
  5764. pos = e->token.pos;
  5765. }
  5766. return ir_emit_source_code_location(proc, procedure, pos);
  5767. }
  5768. case BuiltinProc_type_info_of: {
  5769. Ast *arg = ce->args[0];
  5770. TypeAndValue tav = type_and_value_of_expr(arg);
  5771. if (tav.mode == Addressing_Type) {
  5772. Type *t = default_type(type_of_expr(arg));
  5773. return ir_type_info(proc, t);
  5774. }
  5775. GB_ASSERT(is_type_typeid(tav.type));
  5776. auto args = array_make<irValue *>(ir_allocator(), 1);
  5777. args[0] = ir_build_expr(proc, arg);
  5778. return ir_emit_runtime_call(proc, "__type_info_of", args);
  5779. }
  5780. case BuiltinProc_typeid_of: {
  5781. Ast *arg = ce->args[0];
  5782. TypeAndValue tav = type_and_value_of_expr(arg);
  5783. if (tav.mode == Addressing_Type) {
  5784. Type *t = default_type(type_of_expr(arg));
  5785. return ir_typeid(proc->module, t);
  5786. }
  5787. Type *t = base_type(tav.type);
  5788. GB_ASSERT(are_types_identical(t, t_type_info_ptr));
  5789. auto args = array_make<irValue *>(ir_allocator(), 1);
  5790. args[0] = ir_emit_conv(proc, ir_build_expr(proc, arg), t_type_info_ptr);
  5791. return ir_emit_runtime_call(proc, "__typeid_of", args);
  5792. }
  5793. case BuiltinProc_len: {
  5794. irValue *v = ir_build_expr(proc, ce->args[0]);
  5795. Type *t = base_type(ir_type(v));
  5796. if (is_type_pointer(t)) {
  5797. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5798. v = ir_emit_load(proc, v);
  5799. t = type_deref(t);
  5800. }
  5801. if (is_type_cstring(t)) {
  5802. return ir_cstring_len(proc, v);
  5803. } else if (is_type_string(t)) {
  5804. return ir_string_len(proc, v);
  5805. } else if (is_type_array(t)) {
  5806. GB_PANIC("Array lengths are constant");
  5807. } else if (is_type_slice(t)) {
  5808. return ir_slice_len(proc, v);
  5809. } else if (is_type_dynamic_array(t)) {
  5810. return ir_dynamic_array_len(proc, v);
  5811. } else if (is_type_map(t)) {
  5812. return ir_map_len(proc, v);
  5813. } else if (is_type_soa_struct(t)) {
  5814. return ir_soa_struct_len(proc, v);
  5815. }
  5816. GB_PANIC("Unreachable");
  5817. break;
  5818. }
  5819. case BuiltinProc_cap: {
  5820. irValue *v = ir_build_expr(proc, ce->args[0]);
  5821. Type *t = base_type(ir_type(v));
  5822. if (is_type_pointer(t)) {
  5823. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5824. v = ir_emit_load(proc, v);
  5825. t = type_deref(t);
  5826. }
  5827. if (is_type_string(t)) {
  5828. GB_PANIC("Unreachable");
  5829. } else if (is_type_array(t)) {
  5830. GB_PANIC("Array lengths are constant");
  5831. } else if (is_type_slice(t)) {
  5832. return ir_slice_len(proc, v);
  5833. } else if (is_type_dynamic_array(t)) {
  5834. return ir_dynamic_array_cap(proc, v);
  5835. } else if (is_type_map(t)) {
  5836. return ir_map_cap(proc, v);
  5837. } else if (is_type_soa_struct(t)) {
  5838. return ir_soa_struct_cap(proc, v);
  5839. }
  5840. GB_PANIC("Unreachable");
  5841. break;
  5842. }
  5843. case BuiltinProc_swizzle: {
  5844. ir_emit_comment(proc, str_lit("swizzle.begin"));
  5845. irAddr addr = ir_build_addr(proc, ce->args[0]);
  5846. isize index_count = ce->args.count-1;
  5847. if (index_count == 0) {
  5848. return ir_addr_load(proc, addr);
  5849. }
  5850. irValue *src = ir_addr_get_ptr(proc, addr);
  5851. // TODO(bill): Should this be zeroed or not?
  5852. irValue *dst = ir_add_local_generated(proc, tv.type, true);
  5853. for (i32 i = 1; i < ce->args.count; i++) {
  5854. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  5855. GB_ASSERT(is_type_integer(tv.type));
  5856. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  5857. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  5858. i32 dst_index = i-1;
  5859. irValue *src_elem = ir_emit_array_epi(proc, src, src_index);
  5860. irValue *dst_elem = ir_emit_array_epi(proc, dst, dst_index);
  5861. ir_emit_store(proc, dst_elem, ir_emit_load(proc, src_elem));
  5862. }
  5863. ir_emit_comment(proc, str_lit("swizzle.end"));
  5864. return ir_emit_load(proc, dst);
  5865. }
  5866. case BuiltinProc_complex: {
  5867. ir_emit_comment(proc, str_lit("complex"));
  5868. irValue *real = ir_build_expr(proc, ce->args[0]);
  5869. irValue *imag = ir_build_expr(proc, ce->args[1]);
  5870. irValue *dst = ir_add_local_generated(proc, tv.type, false);
  5871. Type *ft = base_complex_elem_type(tv.type);
  5872. real = ir_emit_conv(proc, real, ft);
  5873. imag = ir_emit_conv(proc, imag, ft);
  5874. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 0), real);
  5875. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 1), imag);
  5876. return ir_emit_load(proc, dst);
  5877. }
  5878. case BuiltinProc_quaternion: {
  5879. ir_emit_comment(proc, str_lit("quaternion"));
  5880. irValue *real = ir_build_expr(proc, ce->args[0]);
  5881. irValue *imag = ir_build_expr(proc, ce->args[1]);
  5882. irValue *jmag = ir_build_expr(proc, ce->args[2]);
  5883. irValue *kmag = ir_build_expr(proc, ce->args[3]);
  5884. // @QuaternionLayout
  5885. irValue *dst = ir_add_local_generated(proc, tv.type, false);
  5886. Type *ft = base_complex_elem_type(tv.type);
  5887. real = ir_emit_conv(proc, real, ft);
  5888. imag = ir_emit_conv(proc, imag, ft);
  5889. jmag = ir_emit_conv(proc, jmag, ft);
  5890. kmag = ir_emit_conv(proc, kmag, ft);
  5891. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 3), real);
  5892. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 0), imag);
  5893. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 1), jmag);
  5894. ir_emit_store(proc, ir_emit_struct_ep(proc, dst, 2), kmag);
  5895. return ir_emit_load(proc, dst);
  5896. }
  5897. case BuiltinProc_real: {
  5898. ir_emit_comment(proc, str_lit("real"));
  5899. irValue *val = ir_build_expr(proc, ce->args[0]);
  5900. if (is_type_complex(ir_type(val))) {
  5901. irValue *real = ir_emit_struct_ev(proc, val, 0);
  5902. return ir_emit_conv(proc, real, tv.type);
  5903. } else if (is_type_quaternion(ir_type(val))) {
  5904. // @QuaternionLayout
  5905. irValue *real = ir_emit_struct_ev(proc, val, 3);
  5906. return ir_emit_conv(proc, real, tv.type);
  5907. }
  5908. GB_PANIC("invalid type for real");
  5909. return nullptr;
  5910. }
  5911. case BuiltinProc_imag: {
  5912. ir_emit_comment(proc, str_lit("imag"));
  5913. irValue *val = ir_build_expr(proc, ce->args[0]);
  5914. if (is_type_complex(ir_type(val))) {
  5915. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  5916. return ir_emit_conv(proc, imag, tv.type);
  5917. } else if (is_type_quaternion(ir_type(val))) {
  5918. // @QuaternionLayout
  5919. irValue *imag = ir_emit_struct_ev(proc, val, 0);
  5920. return ir_emit_conv(proc, imag, tv.type);
  5921. }
  5922. GB_PANIC("invalid type for imag");
  5923. return nullptr;
  5924. }
  5925. case BuiltinProc_jmag: {
  5926. ir_emit_comment(proc, str_lit("jmag"));
  5927. irValue *val = ir_build_expr(proc, ce->args[0]);
  5928. if (is_type_quaternion(ir_type(val))) {
  5929. // @QuaternionLayout
  5930. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  5931. return ir_emit_conv(proc, imag, tv.type);
  5932. }
  5933. GB_PANIC("invalid type for jmag");
  5934. return nullptr;
  5935. }
  5936. case BuiltinProc_kmag: {
  5937. ir_emit_comment(proc, str_lit("kmag"));
  5938. irValue *val = ir_build_expr(proc, ce->args[0]);
  5939. if (is_type_quaternion(ir_type(val))) {
  5940. // @QuaternionLayout
  5941. irValue *imag = ir_emit_struct_ev(proc, val, 2);
  5942. return ir_emit_conv(proc, imag, tv.type);
  5943. }
  5944. GB_PANIC("invalid type for kmag");
  5945. return nullptr;
  5946. }
  5947. case BuiltinProc_conj: {
  5948. ir_emit_comment(proc, str_lit("conj"));
  5949. irValue *val = ir_build_expr(proc, ce->args[0]);
  5950. irValue *res = nullptr;
  5951. Type *t = ir_type(val);
  5952. if (is_type_complex(t)) {
  5953. res = ir_add_local_generated(proc, tv.type, false);
  5954. irValue *real = ir_emit_struct_ev(proc, val, 0);
  5955. irValue *imag = ir_emit_struct_ev(proc, val, 1);
  5956. imag = ir_emit_unary_arith(proc, Token_Sub, imag, ir_type(imag));
  5957. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), real);
  5958. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), imag);
  5959. } else if (is_type_quaternion(t)) {
  5960. // @QuaternionLayout
  5961. res = ir_add_local_generated(proc, tv.type, false);
  5962. irValue *real = ir_emit_struct_ev(proc, val, 3);
  5963. irValue *imag = ir_emit_struct_ev(proc, val, 0);
  5964. irValue *jmag = ir_emit_struct_ev(proc, val, 1);
  5965. irValue *kmag = ir_emit_struct_ev(proc, val, 2);
  5966. imag = ir_emit_unary_arith(proc, Token_Sub, imag, ir_type(imag));
  5967. jmag = ir_emit_unary_arith(proc, Token_Sub, jmag, ir_type(jmag));
  5968. kmag = ir_emit_unary_arith(proc, Token_Sub, kmag, ir_type(kmag));
  5969. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 3), real);
  5970. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 0), imag);
  5971. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 1), jmag);
  5972. ir_emit_store(proc, ir_emit_struct_ep(proc, res, 2), kmag);
  5973. }
  5974. return ir_emit_load(proc, res);
  5975. }
  5976. case BuiltinProc_expand_to_tuple: {
  5977. ir_emit_comment(proc, str_lit("expand_to_tuple"));
  5978. irValue *val = ir_build_expr(proc, ce->args[0]);
  5979. Type *t = base_type(ir_type(val));
  5980. if (!is_type_tuple(tv.type)) {
  5981. if (t->kind == Type_Struct) {
  5982. GB_ASSERT(t->Struct.fields.count == 1);
  5983. return ir_emit_struct_ev(proc, val, 0);
  5984. } else if (t->kind == Type_Array) {
  5985. GB_ASSERT(t->Array.count == 1);
  5986. return ir_emit_array_epi(proc, val, 0);
  5987. } else {
  5988. GB_PANIC("Unknown type of expand_to_tuple");
  5989. }
  5990. }
  5991. GB_ASSERT(is_type_tuple(tv.type));
  5992. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5993. irValue *tuple = ir_add_local_generated(proc, tv.type, false);
  5994. if (t->kind == Type_Struct) {
  5995. for_array(src_index, t->Struct.fields) {
  5996. Entity *field = t->Struct.fields[src_index];
  5997. i32 field_index = field->Variable.field_index;
  5998. irValue *f = ir_emit_struct_ev(proc, val, field_index);
  5999. irValue *ep = ir_emit_struct_ep(proc, tuple, cast(i32)src_index);
  6000. ir_emit_store(proc, ep, f);
  6001. }
  6002. } else if (t->kind == Type_Array) {
  6003. // TODO(bill): Clean-up this code
  6004. irValue *ap = ir_address_from_load_or_generate_local(proc, val);
  6005. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  6006. irValue *f = ir_emit_load(proc, ir_emit_array_epi(proc, ap, i));
  6007. irValue *ep = ir_emit_struct_ep(proc, tuple, i);
  6008. ir_emit_store(proc, ep, f);
  6009. }
  6010. } else {
  6011. GB_PANIC("Unknown type of expand_to_tuple");
  6012. }
  6013. return ir_emit_load(proc, tuple);
  6014. }
  6015. case BuiltinProc_min: {
  6016. ir_emit_comment(proc, str_lit("min"));
  6017. Type *t = type_of_expr(expr);
  6018. if (ce->args.count == 2) {
  6019. return ir_emit_min(proc, t, ir_build_expr(proc, ce->args[0]), ir_build_expr(proc, ce->args[1]));
  6020. } else {
  6021. irValue *x = ir_build_expr(proc, ce->args[0]);
  6022. for (isize i = 1; i < ce->args.count; i++) {
  6023. x = ir_emit_min(proc, t, x, ir_build_expr(proc, ce->args[i]));
  6024. }
  6025. return x;
  6026. }
  6027. }
  6028. case BuiltinProc_max: {
  6029. ir_emit_comment(proc, str_lit("max"));
  6030. Type *t = type_of_expr(expr);
  6031. if (ce->args.count == 2) {
  6032. return ir_emit_max(proc, t, ir_build_expr(proc, ce->args[0]), ir_build_expr(proc, ce->args[1]));
  6033. } else {
  6034. irValue *x = ir_build_expr(proc, ce->args[0]);
  6035. for (isize i = 1; i < ce->args.count; i++) {
  6036. x = ir_emit_max(proc, t, x, ir_build_expr(proc, ce->args[i]));
  6037. }
  6038. return x;
  6039. }
  6040. }
  6041. case BuiltinProc_abs: {
  6042. gbAllocator a = ir_allocator();
  6043. irValue *x = ir_build_expr(proc, ce->args[0]);
  6044. Type *t = ir_type(x);
  6045. if (is_type_unsigned(t)) {
  6046. return x;
  6047. }
  6048. ir_emit_comment(proc, str_lit("abs"));
  6049. if (is_type_quaternion(t)) {
  6050. i64 sz = 8*type_size_of(t);
  6051. auto args = array_make<irValue *>(ir_allocator(), 1);
  6052. args[0] = x;
  6053. switch (sz) {
  6054. case 128: return ir_emit_runtime_call(proc, "abs_quaternion128", args);
  6055. case 256: return ir_emit_runtime_call(proc, "abs_quaternion256", args);
  6056. }
  6057. GB_PANIC("Unknown complex type");
  6058. } else if (is_type_complex(t)) {
  6059. i64 sz = 8*type_size_of(t);
  6060. auto args = array_make<irValue *>(ir_allocator(), 1);
  6061. args[0] = x;
  6062. switch (sz) {
  6063. case 64: return ir_emit_runtime_call(proc, "abs_complex64", args);
  6064. case 128: return ir_emit_runtime_call(proc, "abs_complex128", args);
  6065. }
  6066. GB_PANIC("Unknown complex type");
  6067. } else if (is_type_float(t)) {
  6068. i64 sz = 8*type_size_of(t);
  6069. auto args = array_make<irValue *>(ir_allocator(), 1);
  6070. args[0] = x;
  6071. switch (sz) {
  6072. case 32: return ir_emit_runtime_call(proc, "abs_f32", args);
  6073. case 64: return ir_emit_runtime_call(proc, "abs_f64", args);
  6074. }
  6075. GB_PANIC("Unknown float type");
  6076. }
  6077. irValue *zero = ir_emit_conv(proc, v_zero, t);
  6078. irValue *cond = ir_emit_comp(proc, Token_Lt, x, zero);
  6079. irValue *neg = ir_emit(proc, ir_instr_unary_op(proc, Token_Sub, x, t));
  6080. return ir_emit_select(proc, cond, neg, x);
  6081. }
  6082. case BuiltinProc_clamp:
  6083. ir_emit_comment(proc, str_lit("clamp"));
  6084. return ir_emit_clamp(proc, type_of_expr(expr),
  6085. ir_build_expr(proc, ce->args[0]),
  6086. ir_build_expr(proc, ce->args[1]),
  6087. ir_build_expr(proc, ce->args[2]));
  6088. // "Intrinsics"
  6089. case BuiltinProc_cpu_relax:
  6090. return ir_emit(proc, ir_instr_inline_code(proc, id, {}));
  6091. case BuiltinProc_atomic_fence:
  6092. case BuiltinProc_atomic_fence_acq:
  6093. case BuiltinProc_atomic_fence_rel:
  6094. case BuiltinProc_atomic_fence_acqrel:
  6095. return ir_emit(proc, ir_instr_atomic_fence(proc, id));
  6096. case BuiltinProc_atomic_store:
  6097. case BuiltinProc_atomic_store_rel:
  6098. case BuiltinProc_atomic_store_relaxed:
  6099. case BuiltinProc_atomic_store_unordered: {
  6100. irValue *dst = ir_build_expr(proc, ce->args[0]);
  6101. irValue *val = ir_build_expr(proc, ce->args[1]);
  6102. val = ir_emit_conv(proc, val, type_deref(ir_type(dst)));
  6103. return ir_emit(proc, ir_instr_atomic_store(proc, dst, val, id));
  6104. }
  6105. case BuiltinProc_atomic_load:
  6106. case BuiltinProc_atomic_load_acq:
  6107. case BuiltinProc_atomic_load_relaxed:
  6108. case BuiltinProc_atomic_load_unordered: {
  6109. irValue *dst = ir_build_expr(proc, ce->args[0]);
  6110. return ir_emit(proc, ir_instr_atomic_load(proc, dst, id));
  6111. }
  6112. case BuiltinProc_atomic_add:
  6113. case BuiltinProc_atomic_add_acq:
  6114. case BuiltinProc_atomic_add_rel:
  6115. case BuiltinProc_atomic_add_acqrel:
  6116. case BuiltinProc_atomic_add_relaxed:
  6117. case BuiltinProc_atomic_sub:
  6118. case BuiltinProc_atomic_sub_acq:
  6119. case BuiltinProc_atomic_sub_rel:
  6120. case BuiltinProc_atomic_sub_acqrel:
  6121. case BuiltinProc_atomic_sub_relaxed:
  6122. case BuiltinProc_atomic_and:
  6123. case BuiltinProc_atomic_and_acq:
  6124. case BuiltinProc_atomic_and_rel:
  6125. case BuiltinProc_atomic_and_acqrel:
  6126. case BuiltinProc_atomic_and_relaxed:
  6127. case BuiltinProc_atomic_nand:
  6128. case BuiltinProc_atomic_nand_acq:
  6129. case BuiltinProc_atomic_nand_rel:
  6130. case BuiltinProc_atomic_nand_acqrel:
  6131. case BuiltinProc_atomic_nand_relaxed:
  6132. case BuiltinProc_atomic_or:
  6133. case BuiltinProc_atomic_or_acq:
  6134. case BuiltinProc_atomic_or_rel:
  6135. case BuiltinProc_atomic_or_acqrel:
  6136. case BuiltinProc_atomic_or_relaxed:
  6137. case BuiltinProc_atomic_xor:
  6138. case BuiltinProc_atomic_xor_acq:
  6139. case BuiltinProc_atomic_xor_rel:
  6140. case BuiltinProc_atomic_xor_acqrel:
  6141. case BuiltinProc_atomic_xor_relaxed:
  6142. case BuiltinProc_atomic_xchg:
  6143. case BuiltinProc_atomic_xchg_acq:
  6144. case BuiltinProc_atomic_xchg_rel:
  6145. case BuiltinProc_atomic_xchg_acqrel:
  6146. case BuiltinProc_atomic_xchg_relaxed: {
  6147. irValue *dst = ir_build_expr(proc, ce->args[0]);
  6148. irValue *val = ir_build_expr(proc, ce->args[1]);
  6149. val = ir_emit_conv(proc, val, type_deref(ir_type(dst)));
  6150. return ir_emit(proc, ir_instr_atomic_rmw(proc, dst, val, id));
  6151. }
  6152. case BuiltinProc_atomic_cxchg:
  6153. case BuiltinProc_atomic_cxchg_acq:
  6154. case BuiltinProc_atomic_cxchg_rel:
  6155. case BuiltinProc_atomic_cxchg_acqrel:
  6156. case BuiltinProc_atomic_cxchg_relaxed:
  6157. case BuiltinProc_atomic_cxchg_failrelaxed:
  6158. case BuiltinProc_atomic_cxchg_failacq:
  6159. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  6160. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  6161. case BuiltinProc_atomic_cxchgweak:
  6162. case BuiltinProc_atomic_cxchgweak_acq:
  6163. case BuiltinProc_atomic_cxchgweak_rel:
  6164. case BuiltinProc_atomic_cxchgweak_acqrel:
  6165. case BuiltinProc_atomic_cxchgweak_relaxed:
  6166. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  6167. case BuiltinProc_atomic_cxchgweak_failacq:
  6168. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  6169. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  6170. Type *type = expr->tav.type;
  6171. irValue *address = ir_build_expr(proc, ce->args[0]);
  6172. Type *elem = type_deref(ir_type(address));
  6173. irValue *old_value = ir_build_expr(proc, ce->args[1]);
  6174. irValue *new_value = ir_build_expr(proc, ce->args[2]);
  6175. old_value = ir_emit_conv(proc, old_value, elem);
  6176. new_value = ir_emit_conv(proc, new_value, elem);
  6177. return ir_emit(proc, ir_instr_atomic_cxchg(proc, type, address, old_value, new_value, id));
  6178. }
  6179. }
  6180. GB_PANIC("Unhandled built-in procedure");
  6181. return nullptr;
  6182. }
  6183. irValue *ir_build_expr_internal(irProcedure *proc, Ast *expr);
  6184. irValue *ir_build_expr(irProcedure *proc, Ast *expr) {
  6185. u64 prev_state_flags = proc->module->state_flags;
  6186. defer (proc->module->state_flags = prev_state_flags);
  6187. if (expr->state_flags != 0) {
  6188. u64 in = expr->state_flags;
  6189. u64 out = proc->module->state_flags;
  6190. if (in & StateFlag_bounds_check) {
  6191. out |= StateFlag_bounds_check;
  6192. out &= ~StateFlag_no_bounds_check;
  6193. } else if (in & StateFlag_no_bounds_check) {
  6194. out |= StateFlag_no_bounds_check;
  6195. out &= ~StateFlag_bounds_check;
  6196. }
  6197. proc->module->state_flags = out;
  6198. }
  6199. irValue *v = ir_build_expr_internal(proc, expr);
  6200. return v;
  6201. }
  6202. irValue *ir_build_call_expr(irProcedure *proc, Ast *expr) {
  6203. ast_node(ce, CallExpr, expr);
  6204. TypeAndValue tv = type_and_value_of_expr(expr);
  6205. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  6206. AddressingMode proc_mode = proc_tv.mode;
  6207. if (proc_mode == Addressing_Type) {
  6208. GB_ASSERT(ce->args.count == 1);
  6209. irValue *x = ir_build_expr(proc, ce->args[0]);
  6210. irValue *y = ir_emit_conv(proc, x, tv.type);
  6211. return y;
  6212. }
  6213. Ast *p = unparen_expr(ce->proc);
  6214. if (proc_mode == Addressing_Builtin) {
  6215. Entity *e = entity_of_node(p);
  6216. BuiltinProcId id = BuiltinProc_Invalid;
  6217. if (e != nullptr) {
  6218. id = cast(BuiltinProcId)e->Builtin.id;
  6219. } else {
  6220. id = BuiltinProc_DIRECTIVE;
  6221. }
  6222. return ir_build_builtin_proc(proc, expr, tv, id);
  6223. }
  6224. // NOTE(bill): Regular call
  6225. irValue *value = nullptr;
  6226. Ast *proc_expr = unparen_expr(ce->proc);
  6227. if (proc_expr->tav.mode == Addressing_Constant) {
  6228. ExactValue v = proc_expr->tav.value;
  6229. switch (v.kind) {
  6230. case ExactValue_Integer:
  6231. {
  6232. u64 u = big_int_to_u64(&v.value_integer);
  6233. irValue *x = ir_const_uintptr(u);
  6234. x = ir_emit_conv(proc, x, t_rawptr);
  6235. value = ir_emit_conv(proc, x, proc_expr->tav.type);
  6236. break;
  6237. }
  6238. case ExactValue_Pointer:
  6239. {
  6240. u64 u = cast(u64)v.value_pointer;
  6241. irValue *x = ir_const_uintptr(u);
  6242. x = ir_emit_conv(proc, x, t_rawptr);
  6243. value = ir_emit_conv(proc, x, proc_expr->tav.type);
  6244. break;
  6245. }
  6246. }
  6247. }
  6248. if (value == nullptr) {
  6249. value = ir_build_expr(proc, proc_expr);
  6250. }
  6251. GB_ASSERT(value != nullptr);
  6252. Type *proc_type_ = base_type(ir_type(value));
  6253. GB_ASSERT(proc_type_->kind == Type_Proc);
  6254. TypeProc *pt = &proc_type_->Proc;
  6255. set_procedure_abi_types(heap_allocator(), proc_type_);
  6256. if (is_call_expr_field_value(ce)) {
  6257. auto args = array_make<irValue *>(ir_allocator(), pt->param_count);
  6258. for_array(arg_index, ce->args) {
  6259. Ast *arg = ce->args[arg_index];
  6260. ast_node(fv, FieldValue, arg);
  6261. GB_ASSERT(fv->field->kind == Ast_Ident);
  6262. String name = fv->field->Ident.token.string;
  6263. isize index = lookup_procedure_parameter(pt, name);
  6264. GB_ASSERT(index >= 0);
  6265. TypeAndValue tav = type_and_value_of_expr(fv->value);
  6266. if (tav.mode == Addressing_Type) {
  6267. args[index] = ir_value_nil(tav.type);
  6268. } else {
  6269. args[index] = ir_build_expr(proc, fv->value);
  6270. }
  6271. }
  6272. TypeTuple *params = &pt->params->Tuple;
  6273. for (isize i = 0; i < args.count; i++) {
  6274. Entity *e = params->variables[i];
  6275. if (e->kind == Entity_TypeName) {
  6276. args[i] = ir_value_nil(e->type);
  6277. } else if (e->kind == Entity_Constant) {
  6278. continue;
  6279. } else {
  6280. GB_ASSERT(e->kind == Entity_Variable);
  6281. if (args[i] == nullptr) {
  6282. switch (e->Variable.param_value.kind) {
  6283. case ParameterValue_Constant:
  6284. args[i] = ir_value_constant(e->type, e->Variable.param_value.value);
  6285. break;
  6286. case ParameterValue_Nil:
  6287. args[i] = ir_value_nil(e->type);
  6288. break;
  6289. case ParameterValue_Location:
  6290. args[i] = ir_emit_source_code_location(proc, proc->entity->token.string, ast_token(expr).pos);
  6291. break;
  6292. case ParameterValue_Value:
  6293. args[i] = ir_build_expr(proc, e->Variable.param_value.ast_value);
  6294. break;
  6295. }
  6296. } else {
  6297. args[i] = ir_emit_conv(proc, args[i], e->type);
  6298. }
  6299. }
  6300. }
  6301. return ir_emit_call(proc, value, args, ce->inlining, proc->return_ptr_hint_ast == expr);
  6302. }
  6303. isize arg_index = 0;
  6304. isize arg_count = 0;
  6305. for_array(i, ce->args) {
  6306. Ast *arg = ce->args[i];
  6307. TypeAndValue tav = type_and_value_of_expr(arg);
  6308. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  6309. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  6310. Type *at = tav.type;
  6311. if (at->kind == Type_Tuple) {
  6312. arg_count += at->Tuple.variables.count;
  6313. } else {
  6314. arg_count++;
  6315. }
  6316. }
  6317. isize param_count = 0;
  6318. if (pt->params) {
  6319. GB_ASSERT(pt->params->kind == Type_Tuple);
  6320. param_count = pt->params->Tuple.variables.count;
  6321. }
  6322. auto args = array_make<irValue *>(ir_allocator(), cast(isize)gb_max(param_count, arg_count));
  6323. isize variadic_index = pt->variadic_index;
  6324. bool variadic = pt->variadic && variadic_index >= 0;
  6325. bool vari_expand = ce->ellipsis.pos.line != 0;
  6326. bool is_c_vararg = pt->c_vararg;
  6327. String proc_name = {};
  6328. if (proc->entity != nullptr) {
  6329. proc_name = proc->entity->token.string;
  6330. }
  6331. TokenPos pos = ast_token(ce->proc).pos;
  6332. TypeTuple *param_tuple = nullptr;
  6333. if (pt->params) {
  6334. GB_ASSERT(pt->params->kind == Type_Tuple);
  6335. param_tuple = &pt->params->Tuple;
  6336. }
  6337. for_array(i, ce->args) {
  6338. Ast *arg = ce->args[i];
  6339. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  6340. if (arg_tv.mode == Addressing_Type) {
  6341. args[arg_index++] = ir_value_nil(arg_tv.type);
  6342. } else {
  6343. irValue *a = ir_build_expr(proc, arg);
  6344. Type *at = ir_type(a);
  6345. if (at->kind == Type_Tuple) {
  6346. for_array(i, at->Tuple.variables) {
  6347. Entity *e = at->Tuple.variables[i];
  6348. irValue *v = ir_emit_struct_ev(proc, a, cast(i32)i);
  6349. args[arg_index++] = v;
  6350. }
  6351. } else {
  6352. args[arg_index++] = a;
  6353. }
  6354. }
  6355. }
  6356. if (param_count > 0) {
  6357. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  6358. GB_ASSERT(param_count < 1000000);
  6359. if (arg_count < param_count) {
  6360. isize end = cast(isize)param_count;
  6361. if (variadic) {
  6362. end = variadic_index;
  6363. }
  6364. while (arg_index < end) {
  6365. Entity *e = param_tuple->variables[arg_index];
  6366. GB_ASSERT(e->kind == Entity_Variable);
  6367. switch (e->Variable.param_value.kind) {
  6368. case ParameterValue_Constant:
  6369. args[arg_index++] = ir_value_constant(e->type, e->Variable.param_value.value);
  6370. break;
  6371. case ParameterValue_Nil:
  6372. args[arg_index++] = ir_value_nil(e->type);
  6373. break;
  6374. case ParameterValue_Location:
  6375. args[arg_index++] = ir_emit_source_code_location(proc, proc_name, pos);
  6376. break;
  6377. case ParameterValue_Value:
  6378. args[arg_index++] = ir_build_expr(proc, e->Variable.param_value.ast_value);
  6379. break;
  6380. }
  6381. }
  6382. }
  6383. if (is_c_vararg) {
  6384. GB_ASSERT(variadic);
  6385. GB_ASSERT(!vari_expand);
  6386. isize i = 0;
  6387. for (; i < variadic_index; i++) {
  6388. Entity *e = param_tuple->variables[i];
  6389. if (e->kind == Entity_Variable) {
  6390. args[i] = ir_emit_conv(proc, args[i], e->type);
  6391. }
  6392. }
  6393. Type *variadic_type = param_tuple->variables[i]->type;
  6394. GB_ASSERT(is_type_slice(variadic_type));
  6395. variadic_type = base_type(variadic_type)->Slice.elem;
  6396. if (!is_type_any(variadic_type)) {
  6397. for (; i < arg_count; i++) {
  6398. args[i] = ir_emit_conv(proc, args[i], variadic_type);
  6399. }
  6400. } else {
  6401. for (; i < arg_count; i++) {
  6402. args[i] = ir_emit_conv(proc, args[i], default_type(ir_type(args[i])));
  6403. }
  6404. }
  6405. } else if (variadic) {
  6406. isize i = 0;
  6407. for (; i < variadic_index; i++) {
  6408. Entity *e = param_tuple->variables[i];
  6409. if (e->kind == Entity_Variable) {
  6410. args[i] = ir_emit_conv(proc, args[i], e->type);
  6411. }
  6412. }
  6413. if (!vari_expand) {
  6414. Type *variadic_type = param_tuple->variables[i]->type;
  6415. GB_ASSERT(is_type_slice(variadic_type));
  6416. variadic_type = base_type(variadic_type)->Slice.elem;
  6417. for (; i < arg_count; i++) {
  6418. args[i] = ir_emit_conv(proc, args[i], variadic_type);
  6419. }
  6420. }
  6421. } else {
  6422. for (isize i = 0; i < param_count; i++) {
  6423. Entity *e = param_tuple->variables[i];
  6424. if (e->kind == Entity_Variable) {
  6425. GB_ASSERT(args[i] != nullptr);
  6426. args[i] = ir_emit_conv(proc, args[i], e->type);
  6427. }
  6428. }
  6429. }
  6430. if (variadic && !vari_expand && !is_c_vararg) {
  6431. ir_emit_comment(proc, str_lit("variadic call argument generation"));
  6432. gbAllocator allocator = ir_allocator();
  6433. Type *slice_type = param_tuple->variables[variadic_index]->type;
  6434. Type *elem_type = base_type(slice_type)->Slice.elem;
  6435. irValue *slice = ir_add_local_generated(proc, slice_type, true);
  6436. isize slice_len = arg_count+1 - (variadic_index+1);
  6437. if (slice_len > 0) {
  6438. irValue *base_array = ir_add_local_generated(proc, alloc_type_array(elem_type, slice_len), true);
  6439. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  6440. irValue *addr = ir_emit_array_epi(proc, base_array, cast(i32)j);
  6441. ir_emit_store(proc, addr, args[i]);
  6442. }
  6443. irValue *base_elem = ir_emit_array_epi(proc, base_array, 0);
  6444. irValue *len = ir_const_int(slice_len);
  6445. ir_fill_slice(proc, slice, base_elem, len);
  6446. }
  6447. arg_count = param_count;
  6448. args[variadic_index] = ir_emit_load(proc, slice);
  6449. }
  6450. }
  6451. if (variadic && variadic_index+1 < param_count) {
  6452. for (isize i = variadic_index+1; i < param_count; i++) {
  6453. Entity *e = param_tuple->variables[i];
  6454. switch (e->Variable.param_value.kind) {
  6455. case ParameterValue_Constant:
  6456. args[i] = ir_value_constant(e->type, e->Variable.param_value.value);
  6457. break;
  6458. case ParameterValue_Nil:
  6459. args[i] = ir_value_nil(e->type);
  6460. break;
  6461. case ParameterValue_Location:
  6462. args[i] = ir_emit_source_code_location(proc, proc_name, pos);
  6463. break;
  6464. case ParameterValue_Value:
  6465. args[i] = ir_build_expr(proc, e->Variable.param_value.ast_value);
  6466. break;
  6467. }
  6468. }
  6469. }
  6470. isize final_count = param_count;
  6471. if (is_c_vararg) {
  6472. final_count = arg_count;
  6473. }
  6474. auto call_args = array_slice(args, 0, final_count);
  6475. return ir_emit_call(proc, value, call_args, ce->inlining, proc->return_ptr_hint_ast == expr);
  6476. }
  6477. irValue *ir_build_expr_internal(irProcedure *proc, Ast *expr) {
  6478. Ast *original_expr = expr;
  6479. expr = unparen_expr(expr);
  6480. // ir_push_debug_location(proc->module, expr, proc->debug_scope);
  6481. // defer (ir_pop_debug_location(proc->module));
  6482. TypeAndValue tv = type_and_value_of_expr(expr);
  6483. GB_ASSERT(tv.mode != Addressing_Invalid);
  6484. if (tv.mode == Addressing_Type) {
  6485. // HACK TODO(bill): This is hack but it should be safe in virtually all cases
  6486. irValue *v = ir_typeid(proc->module, tv.type);
  6487. return ir_emit_conv(proc, v, t_typeid);
  6488. }
  6489. if (tv.value.kind != ExactValue_Invalid) {
  6490. // NOTE(bill): Edge case
  6491. if (tv.value.kind != ExactValue_Compound &&
  6492. is_type_array(tv.type)) {
  6493. Type *elem = core_array_type(tv.type);
  6494. ExactValue value = convert_exact_value_for_type(tv.value, elem);
  6495. irValue *x = ir_add_module_constant(proc->module, elem, value);
  6496. return ir_emit_conv(proc, x, tv.type);
  6497. }
  6498. if (tv.value.kind == ExactValue_Typeid) {
  6499. irValue *v = ir_typeid(proc->module, tv.value.value_typeid);
  6500. return ir_emit_conv(proc, v, tv.type);
  6501. }
  6502. if (tv.value.kind == ExactValue_Procedure) {
  6503. Ast *expr = tv.value.value_procedure;
  6504. if (expr->kind == Ast_ProcLit) {
  6505. return ir_gen_anonymous_proc_lit(proc->module, str_lit("_proclit"), expr);
  6506. }
  6507. Entity *e = entity_from_expr(expr);
  6508. e = strip_entity_wrapping(e);
  6509. GB_ASSERT(e != nullptr);
  6510. auto *found = map_get(&proc->module->values, hash_entity(e));
  6511. if (found) {
  6512. auto v = *found;
  6513. // NOTE(bill): This is because pointers are already pointers in LLVM
  6514. if (is_type_proc(ir_type(v))) {
  6515. return v;
  6516. }
  6517. return ir_emit_load(proc, v);
  6518. } else if (e != nullptr && e->kind == Entity_Variable) {
  6519. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6520. }
  6521. GB_PANIC("Error in: %.*s(%td:%td) %s\n", LIT(proc->name), e->token.pos.line, e->token.pos.column);
  6522. }
  6523. return ir_add_module_constant(proc->module, tv.type, tv.value);
  6524. }
  6525. if (tv.mode == Addressing_Variable) {
  6526. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6527. }
  6528. if (tv.mode == Addressing_Constant) {
  6529. GB_ASSERT(tv.value.kind == ExactValue_Invalid);
  6530. // NOTE(bill): Zero value constant
  6531. return ir_add_module_constant(proc->module, tv.type, tv.value);
  6532. }
  6533. switch (expr->kind) {
  6534. case_ast_node(bl, BasicLit, expr);
  6535. TokenPos pos = bl->token.pos;
  6536. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  6537. case_end;
  6538. case_ast_node(bd, BasicDirective, expr);
  6539. TokenPos pos = bd->token.pos;
  6540. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  6541. case_end;
  6542. case_ast_node(i, Implicit, expr);
  6543. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6544. case_end;
  6545. case_ast_node(u, Undef, expr);
  6546. return ir_value_undef(tv.type);
  6547. case_end;
  6548. case_ast_node(i, Ident, expr);
  6549. Entity *e = entity_of_node(expr);
  6550. e = strip_entity_wrapping(e);
  6551. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  6552. if (e->kind == Entity_Builtin) {
  6553. Token token = ast_token(expr);
  6554. GB_PANIC("TODO(bill): ir_build_expr Entity_Builtin '%.*s'\n"
  6555. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  6556. LIT(token.pos.file), token.pos.line, token.pos.column);
  6557. return nullptr;
  6558. } else if (e->kind == Entity_Nil) {
  6559. return ir_value_nil(tv.type);
  6560. }
  6561. irValue **found = map_get(&proc->module->values, hash_entity(e));
  6562. if (found) {
  6563. irValue *v = *found;
  6564. if (v->kind == irValue_Proc) {
  6565. return v;
  6566. }
  6567. // if (e->kind == Entity_Variable && e->Variable.param) {
  6568. // return v;
  6569. // }
  6570. return ir_emit_load(proc, v);
  6571. } else if (e != nullptr && e->kind == Entity_Variable) {
  6572. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6573. }
  6574. GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr);
  6575. return nullptr;
  6576. case_end;
  6577. case_ast_node(de, DerefExpr, expr);
  6578. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6579. case_end;
  6580. case_ast_node(se, SelectorExpr, expr);
  6581. TypeAndValue tav = type_and_value_of_expr(expr);
  6582. GB_ASSERT(tav.mode != Addressing_Invalid);
  6583. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6584. case_end;
  6585. case_ast_node(ise, ImplicitSelectorExpr, expr);
  6586. TypeAndValue tav = type_and_value_of_expr(expr);
  6587. GB_ASSERT(tav.mode == Addressing_Constant);
  6588. return ir_add_module_constant(proc->module, tv.type, tv.value);
  6589. case_end;
  6590. case_ast_node(se, SelectorCallExpr, expr);
  6591. GB_ASSERT(se->modified_call);
  6592. TypeAndValue tav = type_and_value_of_expr(expr);
  6593. GB_ASSERT(tav.mode != Addressing_Invalid);
  6594. return ir_build_expr(proc, se->call);
  6595. case_end;
  6596. case_ast_node(te, TernaryExpr, expr);
  6597. ir_emit_comment(proc, str_lit("TernaryExpr"));
  6598. auto edges = array_make<irValue *>(ir_allocator(), 0, 2);
  6599. GB_ASSERT(te->y != nullptr);
  6600. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  6601. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  6602. irBlock *else_ = ir_new_block(proc, nullptr, "if.else");
  6603. irValue *cond = ir_build_cond(proc, te->cond, then, else_);
  6604. ir_start_block(proc, then);
  6605. Type *type = default_type(type_of_expr(expr));
  6606. ir_open_scope(proc);
  6607. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->x), type));
  6608. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6609. ir_emit_jump(proc, done);
  6610. ir_start_block(proc, else_);
  6611. ir_open_scope(proc);
  6612. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->y), type));
  6613. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6614. ir_emit_jump(proc, done);
  6615. ir_start_block(proc, done);
  6616. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  6617. case_end;
  6618. case_ast_node(te, TernaryIfExpr, expr);
  6619. ir_emit_comment(proc, str_lit("TernaryIfExpr"));
  6620. auto edges = array_make<irValue *>(ir_allocator(), 0, 2);
  6621. GB_ASSERT(te->y != nullptr);
  6622. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  6623. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  6624. irBlock *else_ = ir_new_block(proc, nullptr, "if.else");
  6625. irValue *cond = ir_build_cond(proc, te->cond, then, else_);
  6626. ir_start_block(proc, then);
  6627. Type *type = default_type(type_of_expr(expr));
  6628. ir_open_scope(proc);
  6629. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->x), type));
  6630. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6631. ir_emit_jump(proc, done);
  6632. ir_start_block(proc, else_);
  6633. ir_open_scope(proc);
  6634. array_add(&edges, ir_emit_conv(proc, ir_build_expr(proc, te->y), type));
  6635. ir_close_scope(proc, irDeferExit_Default, nullptr);
  6636. ir_emit_jump(proc, done);
  6637. ir_start_block(proc, done);
  6638. return ir_emit(proc, ir_instr_phi(proc, edges, type));
  6639. case_end;
  6640. case_ast_node(te, TernaryWhenExpr, expr);
  6641. TypeAndValue tav = type_and_value_of_expr(te->cond);
  6642. GB_ASSERT(tav.mode == Addressing_Constant);
  6643. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  6644. if (tav.value.value_bool) {
  6645. return ir_build_expr(proc, te->x);
  6646. } else {
  6647. return ir_build_expr(proc, te->y);
  6648. }
  6649. case_end;
  6650. case_ast_node(ta, TypeAssertion, expr);
  6651. TokenPos pos = ast_token(expr).pos;
  6652. Type *type = tv.type;
  6653. irValue *e = ir_build_expr(proc, ta->expr);
  6654. Type *t = type_deref(ir_type(e));
  6655. if (is_type_union(t)) {
  6656. ir_emit_comment(proc, str_lit("cast - union_cast"));
  6657. return ir_emit_union_cast(proc, e, type, pos);
  6658. } else if (is_type_any(t)) {
  6659. ir_emit_comment(proc, str_lit("cast - any_cast"));
  6660. return ir_emit_any_cast(proc, e, type, pos);
  6661. } else {
  6662. GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
  6663. }
  6664. case_end;
  6665. case_ast_node(tc, TypeCast, expr);
  6666. irValue *e = ir_build_expr(proc, tc->expr);
  6667. switch (tc->token.kind) {
  6668. case Token_cast:
  6669. return ir_emit_conv(proc, e, tv.type);
  6670. case Token_transmute:
  6671. return ir_emit_transmute(proc, e, tv.type);
  6672. }
  6673. GB_PANIC("Invalid AST TypeCast");
  6674. case_end;
  6675. case_ast_node(ac, AutoCast, expr);
  6676. return ir_build_expr(proc, ac->expr);
  6677. case_end;
  6678. case_ast_node(ue, UnaryExpr, expr);
  6679. switch (ue->op.kind) {
  6680. case Token_And: {
  6681. Ast *ue_expr = unparen_expr(ue->expr);
  6682. if (ue_expr->kind == Ast_CompoundLit) {
  6683. irValue *v = ir_build_expr(proc, ue->expr);
  6684. Type *type = ir_type(v);
  6685. irValue *ptr = nullptr;
  6686. if (proc->is_startup) {
  6687. ptr = ir_add_global_generated(proc->module, type, v);
  6688. } else {
  6689. ptr = ir_add_local_generated(proc, type, false);
  6690. }
  6691. ir_emit_store(proc, ptr, v);
  6692. return ptr;
  6693. } else if (ue_expr->kind == Ast_TypeAssertion) {
  6694. gbAllocator a = ir_allocator();
  6695. GB_ASSERT(is_type_pointer(tv.type));
  6696. ast_node(ta, TypeAssertion, ue_expr);
  6697. TokenPos pos = ast_token(expr).pos;
  6698. Type *type = type_of_expr(ue_expr);
  6699. GB_ASSERT(!is_type_tuple(type));
  6700. irValue *e = ir_build_expr(proc, ta->expr);
  6701. Type *t = type_deref(ir_type(e));
  6702. if (is_type_union(t)) {
  6703. irValue *v = e;
  6704. if (!is_type_pointer(ir_type(v))) {
  6705. v = ir_address_from_load_or_generate_local(proc, v);
  6706. }
  6707. Type *src_type = type_deref(ir_type(v));
  6708. Type *dst_type = type;
  6709. irValue *src_tag = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, v));
  6710. irValue *dst_tag = ir_const_union_tag(src_type, dst_type);
  6711. irValue *ok = ir_emit_comp(proc, Token_CmpEq, src_tag, dst_tag);
  6712. auto args = array_make<irValue *>(ir_allocator(), 6);
  6713. args[0] = ok;
  6714. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  6715. args[2] = ir_const_int(pos.line);
  6716. args[3] = ir_const_int(pos.column);
  6717. args[4] = ir_typeid(proc->module, src_type);
  6718. args[5] = ir_typeid(proc->module, dst_type);
  6719. ir_emit_runtime_call(proc, "type_assertion_check", args);
  6720. irValue *data_ptr = v;
  6721. return ir_emit_conv(proc, data_ptr, tv.type);
  6722. } else if (is_type_any(t)) {
  6723. irValue *v = e;
  6724. if (is_type_pointer(ir_type(v))) {
  6725. v = ir_emit_load(proc, v);
  6726. }
  6727. irValue *data_ptr = ir_emit_struct_ev(proc, v, 0);
  6728. irValue *any_id = ir_emit_struct_ev(proc, v, 1);
  6729. irValue *id = ir_typeid(proc->module, type);
  6730. irValue *ok = ir_emit_comp(proc, Token_CmpEq, any_id, id);
  6731. auto args = array_make<irValue *>(ir_allocator(), 6);
  6732. args[0] = ok;
  6733. args[1] = ir_find_or_add_entity_string(proc->module, pos.file);
  6734. args[2] = ir_const_int(pos.line);
  6735. args[3] = ir_const_int(pos.column);
  6736. args[4] = any_id;
  6737. args[5] = id;
  6738. ir_emit_runtime_call(proc, "type_assertion_check", args);
  6739. return ir_emit_conv(proc, data_ptr, tv.type);
  6740. } else {
  6741. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  6742. }
  6743. } else if (ue_expr->kind == Ast_IndexExpr) {
  6744. #if 0
  6745. ast_node(ie, IndexExpr, ue_expr);
  6746. if (is_type_slice(ie->expr->tav.type)) {
  6747. auto tav = ie->index->tav;
  6748. if (tav.mode == Addressing_Constant) {
  6749. if (exact_value_to_i64(tav.value) == 0) {
  6750. irValue *s = ir_build_expr(proc, ie->expr);
  6751. if (is_type_pointer(ir_type(s))) {
  6752. s = ir_emit_load(proc, s);
  6753. }
  6754. return ir_slice_elem(proc, s);
  6755. }
  6756. }
  6757. }
  6758. #endif
  6759. }
  6760. bool allow_reference = true;
  6761. irAddr addr = ir_build_addr(proc, ue->expr);
  6762. return ir_addr_get_ptr(proc, addr, allow_reference);
  6763. }
  6764. default:
  6765. return ir_emit_unary_arith(proc, ue->op.kind, ir_build_expr(proc, ue->expr), tv.type);
  6766. }
  6767. case_end;
  6768. case_ast_node(be, BinaryExpr, expr);
  6769. switch (be->op.kind) {
  6770. case Token_Add:
  6771. case Token_Sub:
  6772. case Token_Mul:
  6773. case Token_Quo:
  6774. case Token_Mod:
  6775. case Token_ModMod:
  6776. case Token_And:
  6777. case Token_Or:
  6778. case Token_Xor:
  6779. case Token_AndNot:
  6780. case Token_Shl:
  6781. case Token_Shr: {
  6782. irValue *left = ir_build_expr(proc, be->left);
  6783. Type *type = default_type(tv.type);
  6784. irValue *right = ir_build_expr(proc, be->right);
  6785. return ir_emit_arith(proc, be->op.kind, left, right, type);
  6786. }
  6787. case Token_CmpEq:
  6788. case Token_NotEq:
  6789. case Token_Lt:
  6790. case Token_LtEq:
  6791. case Token_Gt:
  6792. case Token_GtEq: {
  6793. irValue *left = ir_build_expr(proc, be->left);
  6794. Type *type = default_type(tv.type);
  6795. irValue *right = ir_build_expr(proc, be->right);
  6796. irValue *cmp = ir_emit_comp(proc, be->op.kind, left, right);
  6797. return ir_emit_conv(proc, cmp, type);
  6798. }
  6799. case Token_CmpAnd:
  6800. case Token_CmpOr:
  6801. return ir_emit_logical_binary_expr(proc, expr);
  6802. case Token_in:
  6803. case Token_not_in: {
  6804. irValue *left = ir_build_expr(proc, be->left);
  6805. Type *type = default_type(tv.type);
  6806. irValue *right = ir_build_expr(proc, be->right);
  6807. Type *rt = base_type(ir_type(right));
  6808. switch (rt->kind) {
  6809. case Type_Map:
  6810. {
  6811. if (be->op.kind == Token_in) {
  6812. ir_emit_comment(proc, str_lit("map in"));
  6813. } else {
  6814. ir_emit_comment(proc, str_lit("map not_in"));
  6815. }
  6816. irValue *addr = ir_address_from_load_or_generate_local(proc, right);
  6817. irValue *h = ir_gen_map_header(proc, addr, rt);
  6818. irValue *key = ir_gen_map_key(proc, left, rt->Map.key);
  6819. auto args = array_make<irValue *>(ir_allocator(), 2);
  6820. args[0] = h;
  6821. args[1] = key;
  6822. irValue *ptr = ir_emit_runtime_call(proc, "__dynamic_map_get", args);
  6823. if (be->op.kind == Token_in) {
  6824. return ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, ptr, v_raw_nil), t_bool);
  6825. } else {
  6826. return ir_emit_conv(proc, ir_emit_comp(proc, Token_CmpEq, ptr, v_raw_nil), t_bool);
  6827. }
  6828. }
  6829. break;
  6830. case Type_BitSet:
  6831. {
  6832. if (be->op.kind == Token_in) {
  6833. ir_emit_comment(proc, str_lit("bit_set in"));
  6834. } else {
  6835. ir_emit_comment(proc, str_lit("bit_set not_in"));
  6836. }
  6837. Type *key_type = rt->BitSet.elem;
  6838. GB_ASSERT(are_types_identical(ir_type(left), key_type));
  6839. Type *it = bit_set_to_int(rt);
  6840. left = ir_emit_conv(proc, left, it);
  6841. irValue *lower = ir_value_constant(it, exact_value_i64(rt->BitSet.lower));
  6842. irValue *key = ir_emit_arith(proc, Token_Sub, left, lower, it);
  6843. irValue *bit = ir_emit_arith(proc, Token_Shl, v_one, key, it);
  6844. bit = ir_emit_conv(proc, bit, it);
  6845. irValue *old_value = ir_emit_bitcast(proc, right, it);
  6846. irValue *new_value = ir_emit_arith(proc, Token_And, old_value, bit, it);
  6847. if (be->op.kind == Token_in) {
  6848. return ir_emit_conv(proc, ir_emit_comp(proc, Token_NotEq, new_value, v_zero), t_bool);
  6849. } else {
  6850. return ir_emit_conv(proc, ir_emit_comp(proc, Token_CmpEq, new_value, v_zero), t_bool);
  6851. }
  6852. }
  6853. break;
  6854. default:
  6855. GB_PANIC("Invalid 'in' type");
  6856. }
  6857. break;
  6858. }
  6859. default:
  6860. GB_PANIC("Invalid binary expression");
  6861. break;
  6862. }
  6863. case_end;
  6864. case_ast_node(pl, ProcLit, expr);
  6865. return ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  6866. case_end;
  6867. case_ast_node(cl, CompoundLit, expr);
  6868. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6869. case_end;
  6870. case_ast_node(ce, CallExpr, expr);
  6871. irValue *res = ir_build_call_expr(proc, expr);
  6872. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  6873. GB_ASSERT(is_type_tuple(ir_type(res)));
  6874. GB_ASSERT(ir_type(res)->Tuple.variables.count == 2);
  6875. return ir_emit_struct_ev(proc, res, 0);
  6876. }
  6877. return res;
  6878. case_end;
  6879. case_ast_node(se, SliceExpr, expr);
  6880. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6881. case_end;
  6882. case_ast_node(ie, IndexExpr, expr);
  6883. return ir_addr_load(proc, ir_build_addr(proc, expr));
  6884. case_end;
  6885. }
  6886. GB_PANIC("Unexpected expression: %.*s", LIT(ast_strings[expr->kind]));
  6887. return nullptr;
  6888. }
  6889. irValue *ir_get_using_variable(irProcedure *proc, Entity *e) {
  6890. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  6891. String name = e->token.string;
  6892. Entity *parent = e->using_parent;
  6893. Selection sel = lookup_field(parent->type, name, false);
  6894. GB_ASSERT(sel.entity != nullptr);
  6895. irValue **pv = map_get(&proc->module->values, hash_entity(parent));
  6896. irValue *v = nullptr;
  6897. if (pv != nullptr) {
  6898. v = *pv;
  6899. } else {
  6900. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  6901. v = ir_build_addr_ptr(proc, e->using_expr);
  6902. }
  6903. GB_ASSERT(v != nullptr);
  6904. GB_ASSERT(parent->type == type_deref(ir_type(v)));
  6905. return ir_emit_deep_field_gep(proc, v, sel);
  6906. }
  6907. bool ir_is_elem_const(irModule *m, Ast *elem, Type *elem_type) {
  6908. if (!elem_type_can_be_constant(elem_type)) {
  6909. return false;
  6910. }
  6911. if (elem->kind == Ast_FieldValue) {
  6912. elem = elem->FieldValue.value;
  6913. }
  6914. TypeAndValue tav = type_and_value_of_expr(elem);
  6915. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  6916. return tav.value.kind != ExactValue_Invalid && tav.value.kind != ExactValue_Procedure;
  6917. }
  6918. irAddr ir_build_addr_from_entity(irProcedure *proc, Entity *e, Ast *expr) {
  6919. GB_ASSERT(e != nullptr);
  6920. if (e->kind == Entity_Constant) {
  6921. Type *t = default_type(type_of_expr(expr));
  6922. irValue *v = ir_add_module_constant(proc->module, t, e->Constant.value);
  6923. irValue *g = ir_add_global_generated(proc->module, ir_type(v), v);
  6924. return ir_addr(g);
  6925. }
  6926. irValue *v = nullptr;
  6927. irValue **found = map_get(&proc->module->values, hash_entity(e));
  6928. if (found) {
  6929. v = *found;
  6930. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  6931. // NOTE(bill): Calculate the using variable every time
  6932. v = ir_get_using_variable(proc, e);
  6933. }
  6934. if (v == nullptr) {
  6935. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  6936. LIT(proc->name),
  6937. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  6938. GB_PANIC("Unknown value");
  6939. }
  6940. return ir_addr(v);
  6941. }
  6942. struct irCompoundLitElemTempData {
  6943. Ast *expr;
  6944. irValue *value;
  6945. i32 elem_index;
  6946. irValue *gep;
  6947. };
  6948. irAddr ir_build_addr(irProcedure *proc, Ast *expr) {
  6949. switch (expr->kind) {
  6950. case_ast_node(i, Implicit, expr);
  6951. irValue *v = nullptr;
  6952. switch (i->kind) {
  6953. case Token_context:
  6954. v = ir_find_or_generate_context_ptr(proc);
  6955. break;
  6956. }
  6957. GB_ASSERT(v != nullptr);
  6958. return ir_addr_context(v);
  6959. case_end;
  6960. case_ast_node(i, Ident, expr);
  6961. if (is_blank_ident(expr)) {
  6962. irAddr val = {};
  6963. return val;
  6964. }
  6965. String name = i->token.string;
  6966. Entity *e = entity_of_node(expr);
  6967. // GB_ASSERT(name == e->token.string);
  6968. return ir_build_addr_from_entity(proc, e, expr);
  6969. case_end;
  6970. case_ast_node(pe, ParenExpr, expr);
  6971. return ir_build_addr(proc, unparen_expr(expr));
  6972. case_end;
  6973. case_ast_node(se, SelectorExpr, expr);
  6974. ir_emit_comment(proc, str_lit("SelectorExpr"));
  6975. Ast *sel = unparen_expr(se->selector);
  6976. if (sel->kind == Ast_Ident) {
  6977. String selector = sel->Ident.token.string;
  6978. TypeAndValue tav = type_and_value_of_expr(se->expr);
  6979. if (tav.mode == Addressing_Invalid) {
  6980. // NOTE(bill): Imports
  6981. Entity *imp = entity_of_node(se->expr);
  6982. if (imp != nullptr) {
  6983. GB_ASSERT(imp->kind == Entity_ImportName);
  6984. }
  6985. return ir_build_addr(proc, unparen_expr(se->selector));
  6986. }
  6987. Type *type = base_type(tav.type);
  6988. if (tav.mode == Addressing_Type) { // Addressing_Type
  6989. Selection sel = lookup_field(type, selector, true);
  6990. Entity *e = sel.entity;
  6991. GB_ASSERT(e->kind == Entity_Variable);
  6992. GB_ASSERT(e->flags & EntityFlag_TypeField);
  6993. String name = e->token.string;
  6994. if (name == "names") {
  6995. irValue *ti_ptr = ir_type_info(proc, type);
  6996. irValue *variant = ir_emit_struct_ep(proc, ti_ptr, 2);
  6997. irValue *names_ptr = nullptr;
  6998. if (is_type_enum(type)) {
  6999. irValue *enum_info = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
  7000. names_ptr = ir_emit_struct_ep(proc, enum_info, 1);
  7001. } else if (type->kind == Type_Struct) {
  7002. irValue *struct_info = ir_emit_conv(proc, variant, t_type_info_struct_ptr);
  7003. names_ptr = ir_emit_struct_ep(proc, struct_info, 1);
  7004. }
  7005. return ir_addr(names_ptr);
  7006. } else {
  7007. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  7008. }
  7009. GB_PANIC("Unreachable");
  7010. }
  7011. Selection sel = lookup_field(type, selector, false);
  7012. GB_ASSERT(sel.entity != nullptr);
  7013. if (sel.entity->type->kind == Type_BitFieldValue) {
  7014. irAddr addr = ir_build_addr(proc, se->expr);
  7015. Type *bft = type_deref(ir_addr_type(addr));
  7016. if (sel.index.count == 1) {
  7017. GB_ASSERT(is_type_bit_field(bft));
  7018. i32 index = sel.index[0];
  7019. return ir_addr_bit_field(ir_addr_get_ptr(proc, addr), index);
  7020. } else {
  7021. Selection s = sel;
  7022. s.index.count--;
  7023. i32 index = s.index[s.index.count-1];
  7024. irValue *a = ir_addr_get_ptr(proc, addr);
  7025. a = ir_emit_deep_field_gep(proc, a, s);
  7026. return ir_addr_bit_field(a, index);
  7027. }
  7028. } else {
  7029. irAddr addr = ir_build_addr(proc, se->expr);
  7030. if (addr.kind == irAddr_Context) {
  7031. GB_ASSERT(sel.index.count > 0);
  7032. if (addr.ctx.sel.index.count >= 0) {
  7033. sel = selection_combine(addr.ctx.sel, sel);
  7034. }
  7035. addr.ctx.sel = sel;
  7036. return addr;
  7037. } else if (addr.kind == irAddr_SoaVariable) {
  7038. irValue *index = addr.soa.index;
  7039. i32 first_index = sel.index[0];
  7040. Selection sub_sel = sel;
  7041. sub_sel.index.data += 1;
  7042. sub_sel.index.count -= 1;
  7043. irValue *arr = ir_emit_struct_ep(proc, addr.addr, first_index);
  7044. Type *t = base_type(type_deref(ir_type(addr.addr)));
  7045. GB_ASSERT(is_type_soa_struct(t));
  7046. if (addr.soa.index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) {
  7047. irValue *len = ir_soa_struct_len(proc, addr.addr);
  7048. ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), addr.soa.index, len);
  7049. }
  7050. irValue *item = nullptr;
  7051. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7052. item = ir_emit_array_ep(proc, arr, index);
  7053. } else {
  7054. item = ir_emit_load(proc, ir_emit_ptr_offset(proc, arr, index));
  7055. }
  7056. if (sub_sel.index.count > 0) {
  7057. item = ir_emit_deep_field_gep(proc, item, sub_sel);
  7058. }
  7059. return ir_addr(item);
  7060. }
  7061. irValue *a = ir_addr_get_ptr(proc, addr);
  7062. a = ir_emit_deep_field_gep(proc, a, sel);
  7063. return ir_addr(a);
  7064. }
  7065. } else {
  7066. GB_PANIC("Unsupported selector expression");
  7067. }
  7068. case_end;
  7069. case_ast_node(se, SelectorCallExpr, expr);
  7070. GB_ASSERT(se->modified_call);
  7071. TypeAndValue tav = type_and_value_of_expr(expr);
  7072. GB_ASSERT(tav.mode != Addressing_Invalid);
  7073. return ir_build_addr(proc, se->call);
  7074. case_end;
  7075. case_ast_node(ta, TypeAssertion, expr);
  7076. gbAllocator a = ir_allocator();
  7077. TokenPos pos = ast_token(expr).pos;
  7078. irValue *e = ir_build_expr(proc, ta->expr);
  7079. Type *t = type_deref(ir_type(e));
  7080. if (is_type_union(t)) {
  7081. Type *type = type_of_expr(expr);
  7082. irValue *v = ir_add_local_generated(proc, type, false);
  7083. ir_emit_comment(proc, str_lit("cast - union_cast"));
  7084. ir_emit_store(proc, v, ir_emit_union_cast(proc, ir_build_expr(proc, ta->expr), type, pos));
  7085. return ir_addr(v);
  7086. } else if (is_type_any(t)) {
  7087. ir_emit_comment(proc, str_lit("cast - any_cast"));
  7088. Type *type = type_of_expr(expr);
  7089. return ir_emit_any_cast_addr(proc, ir_build_expr(proc, ta->expr), type, pos);
  7090. } else {
  7091. GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e)));
  7092. }
  7093. case_end;
  7094. case_ast_node(ue, UnaryExpr, expr);
  7095. switch (ue->op.kind) {
  7096. case Token_And: {
  7097. return ir_build_addr(proc, ue->expr);
  7098. }
  7099. default:
  7100. GB_PANIC("Invalid unary expression for ir_build_addr");
  7101. }
  7102. case_end;
  7103. case_ast_node(be, BinaryExpr, expr);
  7104. irValue *v = ir_build_expr(proc, expr);
  7105. Type *t = ir_type(v);
  7106. if (is_type_pointer(t)) {
  7107. return ir_addr(v);
  7108. }
  7109. return ir_addr(ir_address_from_load_or_generate_local(proc, v));
  7110. case_end;
  7111. case_ast_node(ie, IndexExpr, expr);
  7112. ir_emit_comment(proc, str_lit("IndexExpr"));
  7113. Type *t = base_type(type_of_expr(ie->expr));
  7114. gbAllocator a = ir_allocator();
  7115. bool deref = is_type_pointer(t);
  7116. t = base_type(type_deref(t));
  7117. if (is_type_soa_struct(t)) {
  7118. // SOA STRUCTURES!!!!
  7119. irValue *val = ir_build_addr_ptr(proc, ie->expr);
  7120. if (deref) {
  7121. val = ir_emit_load(proc, val);
  7122. }
  7123. irValue *index = ir_build_expr(proc, ie->index);
  7124. return ir_addr_soa_variable(val, index, ie->index);
  7125. }
  7126. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  7127. // SOA Structures for slices/dynamic arrays
  7128. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  7129. irValue *field = ir_build_expr(proc, ie->expr);
  7130. irValue *index = ir_build_expr(proc, ie->index);
  7131. if (!build_context.no_bounds_check) {
  7132. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  7133. GB_ASSERT(field->kind == irValue_Instr);
  7134. irInstr *instr = &field->Instr;
  7135. GB_ASSERT(instr->kind == irInstr_Load);
  7136. irValue *a = instr->Load.address;
  7137. GB_ASSERT(a->kind == irValue_Instr);
  7138. irInstr *b = &a->Instr;
  7139. GB_ASSERT(b->kind == irInstr_StructElementPtr);
  7140. irValue *base_struct = b->StructElementPtr.address;
  7141. GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  7142. irValue *len = ir_soa_struct_len(proc, base_struct);
  7143. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7144. }
  7145. irValue *val = ir_emit_ptr_offset(proc, field, index);
  7146. return ir_addr(val);
  7147. }
  7148. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  7149. if (is_type_map(t)) {
  7150. irValue *map_val = ir_build_addr_ptr(proc, ie->expr);
  7151. if (deref) {
  7152. map_val = ir_emit_load(proc, map_val);
  7153. }
  7154. irValue *key = ir_build_expr(proc, ie->index);
  7155. key = ir_emit_conv(proc, key, t->Map.key);
  7156. Type *result_type = type_of_expr(expr);
  7157. return ir_addr_map(map_val, key, t, result_type);
  7158. }
  7159. switch (t->kind) {
  7160. case Type_Array: {
  7161. irValue *array = nullptr;
  7162. array = ir_build_addr_ptr(proc, ie->expr);
  7163. if (deref) {
  7164. array = ir_emit_load(proc, array);
  7165. }
  7166. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7167. irValue *elem = ir_emit_array_ep(proc, array, index);
  7168. auto index_tv = type_and_value_of_expr(ie->index);
  7169. if (index_tv.mode != Addressing_Constant) {
  7170. irValue *len = ir_const_int(t->Array.count);
  7171. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7172. }
  7173. return ir_addr(elem);
  7174. }
  7175. case Type_EnumeratedArray: {
  7176. irValue *array = nullptr;
  7177. array = ir_build_addr_ptr(proc, ie->expr);
  7178. if (deref) {
  7179. array = ir_emit_load(proc, array);
  7180. }
  7181. Type *index_type = t->EnumeratedArray.index;
  7182. auto index_tv = type_and_value_of_expr(ie->index);
  7183. irValue *index = nullptr;
  7184. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  7185. if (index_tv.mode == Addressing_Constant) {
  7186. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  7187. index = ir_value_constant(index_type, idx);
  7188. } else {
  7189. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7190. index = ir_emit_arith(proc, Token_Sub, index, ir_value_constant(index_type, t->EnumeratedArray.min_value), index_type);
  7191. }
  7192. } else {
  7193. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7194. }
  7195. irValue *elem = ir_emit_array_ep(proc, array, index);
  7196. if (index_tv.mode != Addressing_Constant) {
  7197. irValue *len = ir_const_int(t->EnumeratedArray.count);
  7198. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7199. }
  7200. return ir_addr(elem);
  7201. }
  7202. case Type_Slice: {
  7203. irValue *slice = nullptr;
  7204. slice = ir_build_expr(proc, ie->expr);
  7205. if (deref) {
  7206. slice = ir_emit_load(proc, slice);
  7207. }
  7208. irValue *elem = ir_slice_elem(proc, slice);
  7209. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7210. irValue *len = ir_slice_len(proc, slice);
  7211. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7212. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  7213. return ir_addr(v);
  7214. }
  7215. case Type_RelativeSlice: {
  7216. irAddr addr = ir_build_addr(proc, ie->expr);
  7217. if (deref) {
  7218. addr = ir_addr(ir_addr_load(proc, addr));
  7219. }
  7220. irValue *slice = ir_addr_load(proc, addr);
  7221. irValue *elem = ir_slice_elem(proc, slice);
  7222. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7223. irValue *len = ir_slice_len(proc, slice);
  7224. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7225. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  7226. return ir_addr(v);
  7227. }
  7228. case Type_DynamicArray: {
  7229. irValue *dynamic_array = nullptr;
  7230. dynamic_array = ir_build_expr(proc, ie->expr);
  7231. if (deref) {
  7232. dynamic_array = ir_emit_load(proc, dynamic_array);
  7233. }
  7234. irValue *elem = ir_dynamic_array_elem(proc, dynamic_array);
  7235. irValue *len = ir_dynamic_array_len(proc, dynamic_array);
  7236. irValue *index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7237. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7238. irValue *v = ir_emit_ptr_offset(proc, elem, index);
  7239. return ir_addr(v);
  7240. }
  7241. case Type_Basic: { // Basic_string
  7242. irValue *str;
  7243. irValue *elem;
  7244. irValue *len;
  7245. irValue *index;
  7246. str = ir_build_expr(proc, ie->expr);
  7247. if (deref) {
  7248. str = ir_emit_load(proc, str);
  7249. }
  7250. elem = ir_string_elem(proc, str);
  7251. len = ir_string_len(proc, str);
  7252. index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int);
  7253. ir_emit_bounds_check(proc, ast_token(ie->index), index, len);
  7254. return ir_addr(ir_emit_ptr_offset(proc, elem, index));
  7255. }
  7256. }
  7257. case_end;
  7258. case_ast_node(se, SliceExpr, expr);
  7259. ir_emit_comment(proc, str_lit("SliceExpr"));
  7260. gbAllocator a = ir_allocator();
  7261. irValue *low = v_zero;
  7262. irValue *high = nullptr;
  7263. if (se->low != nullptr) low = ir_build_expr(proc, se->low);
  7264. if (se->high != nullptr) high = ir_build_expr(proc, se->high);
  7265. bool no_indices = se->low == nullptr && se->high == nullptr;
  7266. irAddr addr = ir_build_addr(proc, se->expr);
  7267. irValue *base = ir_addr_load(proc, addr);
  7268. Type *type = base_type(ir_type(base));
  7269. if (is_type_pointer(type)) {
  7270. type = base_type(type_deref(type));
  7271. addr = ir_addr(base);
  7272. base = ir_addr_load(proc, addr);
  7273. }
  7274. // TODO(bill): Cleanup like mad!
  7275. switch (type->kind) {
  7276. case Type_Slice: {
  7277. Type *slice_type = type;
  7278. irValue *len = ir_slice_len(proc, base);
  7279. if (high == nullptr) high = len;
  7280. if (!no_indices) {
  7281. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7282. }
  7283. irValue *elem = ir_emit_ptr_offset(proc, ir_slice_elem(proc, base), low);
  7284. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7285. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  7286. ir_fill_slice(proc, slice, elem, new_len);
  7287. return ir_addr(slice);
  7288. }
  7289. case Type_DynamicArray: {
  7290. Type *elem_type = type->DynamicArray.elem;
  7291. Type *slice_type = alloc_type_slice(elem_type);
  7292. irValue *len = ir_dynamic_array_len(proc, base);
  7293. if (high == nullptr) high = len;
  7294. if (!no_indices) {
  7295. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7296. }
  7297. irValue *elem = ir_emit_ptr_offset(proc, ir_dynamic_array_elem(proc, base), low);
  7298. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7299. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  7300. ir_fill_slice(proc, slice, elem, new_len);
  7301. return ir_addr(slice);
  7302. }
  7303. case Type_Array: {
  7304. Type *slice_type = alloc_type_slice(type->Array.elem);
  7305. irValue *len = ir_array_len(proc, base);
  7306. if (high == nullptr) high = len;
  7307. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  7308. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  7309. if (!low_const || !high_const) {
  7310. if (!no_indices) {
  7311. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7312. }
  7313. }
  7314. irValue *elem = ir_emit_ptr_offset(proc, ir_array_elem(proc, ir_addr_get_ptr(proc, addr)), low);
  7315. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7316. irValue *slice = ir_add_local_generated(proc, slice_type, false);
  7317. ir_fill_slice(proc, slice, elem, new_len);
  7318. return ir_addr(slice);
  7319. }
  7320. case Type_Basic: {
  7321. GB_ASSERT(type == t_string);
  7322. irValue *len = ir_string_len(proc, base);
  7323. if (high == nullptr) high = len;
  7324. if (!no_indices) {
  7325. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7326. }
  7327. irValue *elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, base), low);
  7328. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7329. irValue *str = ir_add_local_generated(proc, t_string, false);
  7330. ir_fill_string(proc, str, elem, new_len);
  7331. return ir_addr(str);
  7332. }
  7333. case Type_Struct:
  7334. if (is_type_soa_struct(type)) {
  7335. irValue *len = ir_soa_struct_len(proc, ir_addr_get_ptr(proc, addr));
  7336. if (high == nullptr) high = len;
  7337. if (!no_indices) {
  7338. ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr);
  7339. }
  7340. irValue *dst = ir_add_local_generated(proc, type_of_expr(expr), true);
  7341. if (type->Struct.soa_kind == StructSoa_Fixed) {
  7342. i32 field_count = cast(i32)type->Struct.fields.count;
  7343. for (i32 i = 0; i < field_count; i++) {
  7344. irValue *field_dst = ir_emit_struct_ep(proc, dst, i);
  7345. irValue *field_src = ir_emit_struct_ep(proc, ir_addr_get_ptr(proc, addr), i);
  7346. field_src = ir_emit_array_ep(proc, field_src, low);
  7347. ir_emit_store(proc, field_dst, field_src);
  7348. }
  7349. irValue *len_dst = ir_emit_struct_ep(proc, dst, field_count);
  7350. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7351. ir_emit_store(proc, len_dst, new_len);
  7352. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  7353. if (no_indices) {
  7354. ir_emit_store(proc, dst, base);
  7355. } else {
  7356. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  7357. for (i32 i = 0; i < field_count; i++) {
  7358. irValue *field_dst = ir_emit_struct_ep(proc, dst, i);
  7359. irValue *field_src = ir_emit_struct_ev(proc, base, i);
  7360. field_src = ir_emit_ptr_offset(proc, field_src, low);
  7361. ir_emit_store(proc, field_dst, field_src);
  7362. }
  7363. irValue *len_dst = ir_emit_struct_ep(proc, dst, field_count);
  7364. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7365. ir_emit_store(proc, len_dst, new_len);
  7366. }
  7367. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  7368. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  7369. for (i32 i = 0; i < field_count; i++) {
  7370. irValue *field_dst = ir_emit_struct_ep(proc, dst, i);
  7371. irValue *field_src = ir_emit_struct_ev(proc, base, i);
  7372. field_src = ir_emit_ptr_offset(proc, field_src, low);
  7373. ir_emit_store(proc, field_dst, field_src);
  7374. }
  7375. irValue *len_dst = ir_emit_struct_ep(proc, dst, field_count);
  7376. irValue *new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int);
  7377. ir_emit_store(proc, len_dst, new_len);
  7378. }
  7379. return ir_addr(dst);
  7380. }
  7381. break;
  7382. }
  7383. GB_PANIC("Unknown slicable type");
  7384. case_end;
  7385. case_ast_node(de, DerefExpr, expr);
  7386. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  7387. irAddr addr = ir_build_addr(proc, de->expr);
  7388. addr.relative.deref = true;
  7389. return addr;
  7390. }
  7391. // TODO(bill): Is a ptr copy needed?
  7392. irValue *addr = ir_build_expr(proc, de->expr);
  7393. addr = ir_emit_ptr_offset(proc, addr, v_zero);
  7394. return ir_addr(addr);
  7395. case_end;
  7396. case_ast_node(ce, CallExpr, expr);
  7397. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  7398. irValue *e = ir_build_expr(proc, expr);
  7399. irValue *v = ir_add_local_generated(proc, ir_type(e), false);
  7400. ir_emit_store(proc, v, e);
  7401. return ir_addr(v);
  7402. case_end;
  7403. case_ast_node(cl, CompoundLit, expr);
  7404. ir_emit_comment(proc, str_lit("CompoundLit"));
  7405. Type *type = type_of_expr(expr);
  7406. Type *bt = base_type(type);
  7407. irValue *v = ir_add_local_generated(proc, type, true);
  7408. Type *et = nullptr;
  7409. switch (bt->kind) {
  7410. case Type_Array: et = bt->Array.elem; break;
  7411. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  7412. case Type_Slice: et = bt->Slice.elem; break;
  7413. case Type_BitSet: et = bt->BitSet.elem; break;
  7414. case Type_SimdVector: et = bt->SimdVector.elem; break;
  7415. }
  7416. String proc_name = {};
  7417. if (proc->entity) {
  7418. proc_name = proc->entity->token.string;
  7419. }
  7420. TokenPos pos = ast_token(expr).pos;
  7421. switch (bt->kind) {
  7422. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  7423. case Type_Struct: {
  7424. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  7425. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  7426. bool is_raw_union = is_type_raw_union(bt);
  7427. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  7428. TypeStruct *st = &bt->Struct;
  7429. if (cl->elems.count > 0) {
  7430. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7431. for_array(field_index, cl->elems) {
  7432. Ast *elem = cl->elems[field_index];
  7433. irValue *field_expr = nullptr;
  7434. Entity *field = nullptr;
  7435. isize index = field_index;
  7436. if (elem->kind == Ast_FieldValue) {
  7437. ast_node(fv, FieldValue, elem);
  7438. String name = fv->field->Ident.token.string;
  7439. Selection sel = lookup_field(bt, name, false);
  7440. index = sel.index[0];
  7441. elem = fv->value;
  7442. TypeAndValue tav = type_and_value_of_expr(elem);
  7443. } else {
  7444. TypeAndValue tav = type_and_value_of_expr(elem);
  7445. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  7446. index = sel.index[0];
  7447. }
  7448. field = st->fields[index];
  7449. Type *ft = field->type;
  7450. if (!is_raw_union && !is_type_typeid(ft) && ir_is_elem_const(proc->module, elem, ft)) {
  7451. continue;
  7452. }
  7453. field_expr = ir_build_expr(proc, elem);
  7454. GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
  7455. Type *fet = ir_type(field_expr);
  7456. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  7457. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  7458. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  7459. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  7460. ir_emit_store_union_variant(proc, gep, field_expr, fet);
  7461. } else {
  7462. irValue *fv = ir_emit_conv(proc, field_expr, ft);
  7463. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  7464. ir_emit_store(proc, gep, fv);
  7465. }
  7466. }
  7467. }
  7468. break;
  7469. }
  7470. case Type_Map: {
  7471. if (cl->elems.count == 0) {
  7472. break;
  7473. }
  7474. gbAllocator a = ir_allocator();
  7475. {
  7476. auto args = array_make<irValue *>(a, 3);
  7477. args[0] = ir_gen_map_header(proc, v, type);
  7478. args[1] = ir_const_int(2*cl->elems.count);
  7479. args[2] = ir_emit_source_code_location(proc, proc_name, pos);
  7480. ir_emit_runtime_call(proc, "__dynamic_map_reserve", args);
  7481. }
  7482. for_array(field_index, cl->elems) {
  7483. Ast *elem = cl->elems[field_index];
  7484. ast_node(fv, FieldValue, elem);
  7485. irValue *key = ir_build_expr(proc, fv->field);
  7486. irValue *value = ir_build_expr(proc, fv->value);
  7487. ir_insert_dynamic_map_key_and_value(proc, v, type, key, value, elem);
  7488. }
  7489. break;
  7490. }
  7491. case Type_Array: {
  7492. if (cl->elems.count > 0) {
  7493. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7494. auto temp_data = array_make<irCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7495. defer (array_free(&temp_data));
  7496. // NOTE(bill): Separate value, gep, store into their own chunks
  7497. for_array(i, cl->elems) {
  7498. Ast *elem = cl->elems[i];
  7499. if (elem->kind == Ast_FieldValue) {
  7500. ast_node(fv, FieldValue, elem);
  7501. if (ir_is_elem_const(proc->module, fv->value, et)) {
  7502. continue;
  7503. }
  7504. if (is_ast_range(fv->field)) {
  7505. ast_node(ie, BinaryExpr, fv->field);
  7506. TypeAndValue lo_tav = ie->left->tav;
  7507. TypeAndValue hi_tav = ie->right->tav;
  7508. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7509. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7510. TokenKind op = ie->op.kind;
  7511. i64 lo = exact_value_to_i64(lo_tav.value);
  7512. i64 hi = exact_value_to_i64(hi_tav.value);
  7513. if (op == Token_Ellipsis) {
  7514. hi += 1;
  7515. }
  7516. irValue *value = ir_build_expr(proc, fv->value);
  7517. for (i64 k = lo; k < hi; k++) {
  7518. irCompoundLitElemTempData data = {};
  7519. data.value = value;
  7520. data.elem_index = cast(i32)k;
  7521. array_add(&temp_data, data);
  7522. }
  7523. } else {
  7524. auto tav = fv->field->tav;
  7525. GB_ASSERT(tav.mode == Addressing_Constant);
  7526. i64 index = exact_value_to_i64(tav.value);
  7527. irCompoundLitElemTempData data = {};
  7528. data.value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  7529. data.expr = fv->value;
  7530. data.elem_index = cast(i32)index;
  7531. array_add(&temp_data, data);
  7532. }
  7533. } else {
  7534. if (ir_is_elem_const(proc->module, elem, et)) {
  7535. continue;
  7536. }
  7537. irCompoundLitElemTempData data = {};
  7538. data.expr = elem;
  7539. data.elem_index = cast(i32)i;
  7540. array_add(&temp_data, data);
  7541. }
  7542. }
  7543. for_array(i, temp_data) {
  7544. temp_data[i].gep = ir_emit_array_epi(proc, v, temp_data[i].elem_index);
  7545. }
  7546. for_array(i, temp_data) {
  7547. auto return_ptr_hint_ast = proc->return_ptr_hint_ast;
  7548. auto return_ptr_hint_value = proc->return_ptr_hint_value;
  7549. auto return_ptr_hint_used = proc->return_ptr_hint_used;
  7550. defer (proc->return_ptr_hint_ast = return_ptr_hint_ast);
  7551. defer (proc->return_ptr_hint_value = return_ptr_hint_value);
  7552. defer (proc->return_ptr_hint_used = return_ptr_hint_used);
  7553. irValue *field_expr = temp_data[i].value;
  7554. Ast *expr = temp_data[i].expr;
  7555. proc->return_ptr_hint_value = temp_data[i].gep;
  7556. proc->return_ptr_hint_ast = unparen_expr(expr);
  7557. if (field_expr == nullptr) {
  7558. field_expr = ir_build_expr(proc, expr);
  7559. }
  7560. Type *t = ir_type(field_expr);
  7561. GB_ASSERT(t->kind != Type_Tuple);
  7562. irValue *ev = ir_emit_conv(proc, field_expr, et);
  7563. if (!proc->return_ptr_hint_used) {
  7564. temp_data[i].value = ev;
  7565. }
  7566. }
  7567. for_array(i, temp_data) {
  7568. if (temp_data[i].value != nullptr) {
  7569. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false);
  7570. }
  7571. }
  7572. }
  7573. break;
  7574. }
  7575. case Type_EnumeratedArray: {
  7576. if (cl->elems.count > 0) {
  7577. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7578. auto temp_data = array_make<irCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7579. defer (array_free(&temp_data));
  7580. // NOTE(bill): Separate value, gep, store into their own chunks
  7581. for_array(i, cl->elems) {
  7582. Ast *elem = cl->elems[i];
  7583. if (elem->kind == Ast_FieldValue) {
  7584. ast_node(fv, FieldValue, elem);
  7585. if (ir_is_elem_const(proc->module, fv->value, et)) {
  7586. continue;
  7587. }
  7588. if (is_ast_range(fv->field)) {
  7589. ast_node(ie, BinaryExpr, fv->field);
  7590. TypeAndValue lo_tav = ie->left->tav;
  7591. TypeAndValue hi_tav = ie->right->tav;
  7592. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7593. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7594. TokenKind op = ie->op.kind;
  7595. i64 lo = exact_value_to_i64(lo_tav.value);
  7596. i64 hi = exact_value_to_i64(hi_tav.value);
  7597. if (op == Token_Ellipsis) {
  7598. hi += 1;
  7599. }
  7600. irValue *value = ir_build_expr(proc, fv->value);
  7601. for (i64 k = lo; k < hi; k++) {
  7602. irCompoundLitElemTempData data = {};
  7603. data.value = value;
  7604. data.elem_index = cast(i32)k;
  7605. array_add(&temp_data, data);
  7606. }
  7607. } else {
  7608. auto tav = fv->field->tav;
  7609. GB_ASSERT(tav.mode == Addressing_Constant);
  7610. i64 index = exact_value_to_i64(tav.value);
  7611. irCompoundLitElemTempData data = {};
  7612. data.value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  7613. data.expr = fv->value;
  7614. data.elem_index = cast(i32)index;
  7615. array_add(&temp_data, data);
  7616. }
  7617. } else {
  7618. if (ir_is_elem_const(proc->module, elem, et)) {
  7619. continue;
  7620. }
  7621. irCompoundLitElemTempData data = {};
  7622. data.expr = elem;
  7623. data.elem_index = cast(i32)i;
  7624. array_add(&temp_data, data);
  7625. }
  7626. }
  7627. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  7628. for_array(i, temp_data) {
  7629. i32 index = temp_data[i].elem_index - index_offset;
  7630. temp_data[i].gep = ir_emit_array_epi(proc, v, index);
  7631. }
  7632. for_array(i, temp_data) {
  7633. auto return_ptr_hint_ast = proc->return_ptr_hint_ast;
  7634. auto return_ptr_hint_value = proc->return_ptr_hint_value;
  7635. auto return_ptr_hint_used = proc->return_ptr_hint_used;
  7636. defer (proc->return_ptr_hint_ast = return_ptr_hint_ast);
  7637. defer (proc->return_ptr_hint_value = return_ptr_hint_value);
  7638. defer (proc->return_ptr_hint_used = return_ptr_hint_used);
  7639. irValue *field_expr = temp_data[i].value;
  7640. Ast *expr = temp_data[i].expr;
  7641. proc->return_ptr_hint_value = temp_data[i].gep;
  7642. proc->return_ptr_hint_ast = unparen_expr(expr);
  7643. if (field_expr == nullptr) {
  7644. field_expr = ir_build_expr(proc, expr);
  7645. }
  7646. Type *t = ir_type(field_expr);
  7647. GB_ASSERT(t->kind != Type_Tuple);
  7648. irValue *ev = ir_emit_conv(proc, field_expr, et);
  7649. if (!proc->return_ptr_hint_used) {
  7650. temp_data[i].value = ev;
  7651. }
  7652. }
  7653. for_array(i, temp_data) {
  7654. if (temp_data[i].value != nullptr) {
  7655. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false);
  7656. }
  7657. }
  7658. }
  7659. break;
  7660. }
  7661. case Type_Slice: {
  7662. if (cl->elems.count > 0) {
  7663. Type *elem_type = bt->Slice.elem;
  7664. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  7665. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  7666. irValue *slice = ir_add_module_constant(proc->module, type, exact_value_compound(expr));
  7667. GB_ASSERT(slice->kind == irValue_ConstantSlice);
  7668. irValue *data = ir_emit_array_ep(proc, slice->ConstantSlice.backing_array, v_zero32);
  7669. auto temp_data = array_make<irCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7670. defer (array_free(&temp_data));
  7671. for_array(i, cl->elems) {
  7672. Ast *elem = cl->elems[i];
  7673. if (elem->kind == Ast_FieldValue) {
  7674. ast_node(fv, FieldValue, elem);
  7675. if (ir_is_elem_const(proc->module, fv->value, et)) {
  7676. continue;
  7677. }
  7678. if (is_ast_range(fv->field)) {
  7679. ast_node(ie, BinaryExpr, fv->field);
  7680. TypeAndValue lo_tav = ie->left->tav;
  7681. TypeAndValue hi_tav = ie->right->tav;
  7682. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7683. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7684. TokenKind op = ie->op.kind;
  7685. i64 lo = exact_value_to_i64(lo_tav.value);
  7686. i64 hi = exact_value_to_i64(hi_tav.value);
  7687. if (op == Token_Ellipsis) {
  7688. hi += 1;
  7689. }
  7690. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  7691. for (i64 k = lo; k < hi; k++) {
  7692. irCompoundLitElemTempData data = {};
  7693. data.value = value;
  7694. data.elem_index = cast(i32)k;
  7695. array_add(&temp_data, data);
  7696. }
  7697. } else {
  7698. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  7699. i64 index = exact_value_to_i64(fv->field->tav.value);
  7700. irValue *field_expr = ir_build_expr(proc, fv->value);
  7701. GB_ASSERT(!is_type_tuple(ir_type(field_expr)));
  7702. irValue *ev = ir_emit_conv(proc, field_expr, et);
  7703. irCompoundLitElemTempData data = {};
  7704. data.value = ev;
  7705. data.elem_index = cast(i32)index;
  7706. array_add(&temp_data, data);
  7707. }
  7708. } else {
  7709. if (ir_is_elem_const(proc->module, elem, et)) {
  7710. continue;
  7711. }
  7712. irValue *field_expr = ir_build_expr(proc, elem);
  7713. GB_ASSERT(!is_type_tuple(ir_type(field_expr)));
  7714. irValue *ev = ir_emit_conv(proc, field_expr, et);
  7715. irCompoundLitElemTempData data = {};
  7716. data.value = ev;
  7717. data.elem_index = cast(i32)i;
  7718. array_add(&temp_data, data);
  7719. }
  7720. }
  7721. for_array(i, temp_data) {
  7722. temp_data[i].gep = ir_emit_ptr_offset(proc, data, ir_const_int(temp_data[i].elem_index));
  7723. }
  7724. for_array(i, temp_data) {
  7725. ir_emit_store(proc, temp_data[i].gep, temp_data[i].value);
  7726. }
  7727. irValue *count = ir_const_int(slice->ConstantSlice.count);
  7728. ir_fill_slice(proc, v, data, count);
  7729. }
  7730. break;
  7731. }
  7732. case Type_DynamicArray: {
  7733. if (cl->elems.count == 0) {
  7734. break;
  7735. }
  7736. Type *et = bt->DynamicArray.elem;
  7737. gbAllocator a = ir_allocator();
  7738. irValue *size = ir_const_int(type_size_of(et));
  7739. irValue *align = ir_const_int(type_align_of(et));
  7740. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  7741. {
  7742. auto args = array_make<irValue *>(a, 5);
  7743. args[0] = ir_emit_conv(proc, v, t_rawptr);
  7744. args[1] = size;
  7745. args[2] = align;
  7746. args[3] = ir_const_int(2*item_count); // TODO(bill): Is this too much waste?
  7747. args[4] = ir_emit_source_code_location(proc, proc_name, pos);
  7748. ir_emit_runtime_call(proc, "__dynamic_array_reserve", args);
  7749. }
  7750. irValue *items = ir_generate_array(proc->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  7751. for_array(i, cl->elems) {
  7752. Ast *elem = cl->elems[i];
  7753. if (elem->kind == Ast_FieldValue) {
  7754. ast_node(fv, FieldValue, elem);
  7755. if (is_ast_range(fv->field)) {
  7756. ast_node(ie, BinaryExpr, fv->field);
  7757. TypeAndValue lo_tav = ie->left->tav;
  7758. TypeAndValue hi_tav = ie->right->tav;
  7759. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7760. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7761. TokenKind op = ie->op.kind;
  7762. i64 lo = exact_value_to_i64(lo_tav.value);
  7763. i64 hi = exact_value_to_i64(hi_tav.value);
  7764. if (op == Token_Ellipsis) {
  7765. hi += 1;
  7766. }
  7767. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et);
  7768. for (i64 k = lo; k < hi; k++) {
  7769. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)k);
  7770. ir_emit_store(proc, ep, value);
  7771. }
  7772. } else {
  7773. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  7774. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  7775. irValue *ev = ir_build_expr(proc, fv->value);
  7776. irValue *value = ir_emit_conv(proc, ev, et);
  7777. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)field_index);
  7778. ir_emit_store(proc, ep, value);
  7779. }
  7780. } else {
  7781. irValue *value = ir_emit_conv(proc, ir_build_expr(proc, elem), et);
  7782. irValue *ep = ir_emit_array_epi(proc, items, cast(i32)i);
  7783. ir_emit_store(proc, ep, value);
  7784. }
  7785. }
  7786. {
  7787. auto args = array_make<irValue *>(a, 6);
  7788. args[0] = ir_emit_conv(proc, v, t_rawptr);
  7789. args[1] = size;
  7790. args[2] = align;
  7791. args[3] = ir_emit_conv(proc, items, t_rawptr);
  7792. args[4] = ir_const_int(item_count);
  7793. args[5] = ir_emit_source_code_location(proc, proc_name, pos);
  7794. ir_emit_runtime_call(proc, "__dynamic_array_append", args);
  7795. }
  7796. break;
  7797. }
  7798. case Type_Basic: {
  7799. GB_ASSERT(is_type_any(bt));
  7800. if (cl->elems.count > 0) {
  7801. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7802. String field_names[2] = {
  7803. str_lit("data"),
  7804. str_lit("id"),
  7805. };
  7806. Type *field_types[2] = {
  7807. t_rawptr,
  7808. t_typeid,
  7809. };
  7810. for_array(field_index, cl->elems) {
  7811. Ast *elem = cl->elems[field_index];
  7812. irValue *field_expr = nullptr;
  7813. isize index = field_index;
  7814. if (elem->kind == Ast_FieldValue) {
  7815. ast_node(fv, FieldValue, elem);
  7816. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  7817. index = sel.index[0];
  7818. elem = fv->value;
  7819. } else {
  7820. TypeAndValue tav = type_and_value_of_expr(elem);
  7821. Selection sel = lookup_field(bt, field_names[field_index], false);
  7822. index = sel.index[0];
  7823. }
  7824. field_expr = ir_build_expr(proc, elem);
  7825. GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple);
  7826. Type *ft = field_types[index];
  7827. irValue *fv = ir_emit_conv(proc, field_expr, ft);
  7828. irValue *gep = ir_emit_struct_ep(proc, v, cast(i32)index);
  7829. ir_emit_store(proc, gep, fv);
  7830. }
  7831. }
  7832. break;
  7833. }
  7834. case Type_BitSet: {
  7835. i64 sz = type_size_of(type);
  7836. if (cl->elems.count > 0 && sz > 0) {
  7837. ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr)));
  7838. irValue *lower = ir_value_constant(t_int, exact_value_i64(bt->BitSet.lower));
  7839. for_array(i, cl->elems) {
  7840. Ast *elem = cl->elems[i];
  7841. GB_ASSERT(elem->kind != Ast_FieldValue);
  7842. if (ir_is_elem_const(proc->module, elem, et)) {
  7843. continue;
  7844. }
  7845. irValue *expr = ir_build_expr(proc, elem);
  7846. GB_ASSERT(ir_type(expr)->kind != Type_Tuple);
  7847. Type *it = bit_set_to_int(bt);
  7848. irValue *e = ir_emit_conv(proc, expr, it);
  7849. e = ir_emit_arith(proc, Token_Sub, e, lower, it);
  7850. e = ir_emit_arith(proc, Token_Shl, v_one, e, it);
  7851. irValue *old_value = ir_emit_bitcast(proc, ir_emit_load(proc, v), it);
  7852. irValue *new_value = ir_emit_arith(proc, Token_Or, old_value, e, it);
  7853. new_value = ir_emit_bitcast(proc, new_value, type);
  7854. ir_emit_store(proc, v, new_value);
  7855. }
  7856. }
  7857. break;
  7858. }
  7859. }
  7860. return ir_addr(v);
  7861. case_end;
  7862. case_ast_node(tc, TypeCast, expr);
  7863. Type *type = type_of_expr(expr);
  7864. irValue *x = ir_build_expr(proc, tc->expr);
  7865. irValue *e = nullptr;
  7866. switch (tc->token.kind) {
  7867. case Token_cast:
  7868. e = ir_emit_conv(proc, x, type);
  7869. break;
  7870. case Token_transmute:
  7871. e = ir_emit_transmute(proc, x, type);
  7872. break;
  7873. default:
  7874. GB_PANIC("Invalid AST TypeCast");
  7875. }
  7876. irValue *v = ir_add_local_generated(proc, type, false);
  7877. ir_emit_store(proc, v, e);
  7878. return ir_addr(v);
  7879. case_end;
  7880. case_ast_node(ac, AutoCast, expr);
  7881. return ir_build_addr(proc, ac->expr);
  7882. case_end;
  7883. }
  7884. TokenPos token_pos = ast_token(expr).pos;
  7885. GB_PANIC("Unexpected address expression\n"
  7886. "\tAst: %.*s @ "
  7887. "%.*s(%td:%td)\n",
  7888. LIT(ast_strings[expr->kind]),
  7889. LIT(token_pos.file), token_pos.line, token_pos.column);
  7890. return ir_addr(nullptr);
  7891. }
  7892. void ir_build_assign_op(irProcedure *proc, irAddr const &lhs, irValue *value, TokenKind op) {
  7893. irValue *old_value = ir_addr_load(proc, lhs);
  7894. Type *type = ir_type(old_value);
  7895. irValue *change = value;
  7896. if (is_type_pointer(type) && is_type_integer(ir_type(value))) {
  7897. change = ir_emit_conv(proc, value, default_type(ir_type(value)));
  7898. } else {
  7899. change = ir_emit_conv(proc, value, type);
  7900. }
  7901. irValue *new_value = ir_emit_arith(proc, op, old_value, change, type);
  7902. ir_addr_store(proc, lhs, new_value);
  7903. }
  7904. irValue *ir_build_cond(irProcedure *proc, Ast *cond, irBlock *true_block, irBlock *false_block) {
  7905. switch (cond->kind) {
  7906. case_ast_node(pe, ParenExpr, cond);
  7907. return ir_build_cond(proc, pe->expr, true_block, false_block);
  7908. case_end;
  7909. case_ast_node(ue, UnaryExpr, cond);
  7910. if (ue->op.kind == Token_Not) {
  7911. return ir_build_cond(proc, ue->expr, false_block, true_block);
  7912. }
  7913. case_end;
  7914. case_ast_node(be, BinaryExpr, cond);
  7915. if (be->op.kind == Token_CmpAnd) {
  7916. irBlock *block = ir_new_block(proc, nullptr, "cmp.and");
  7917. ir_build_cond(proc, be->left, block, false_block);
  7918. ir_start_block(proc, block);
  7919. return ir_build_cond(proc, be->right, true_block, false_block);
  7920. } else if (be->op.kind == Token_CmpOr) {
  7921. irBlock *block = ir_new_block(proc, nullptr, "cmp.or");
  7922. ir_build_cond(proc, be->left, true_block, block);
  7923. ir_start_block(proc, block);
  7924. return ir_build_cond(proc, be->right, true_block, false_block);
  7925. }
  7926. case_end;
  7927. }
  7928. irValue *v = ir_build_expr(proc, cond);
  7929. v = ir_emit_conv(proc, v, t_bool);
  7930. ir_emit_if(proc, v, true_block, false_block);
  7931. return v;
  7932. }
  7933. void ir_build_nested_proc(irProcedure *proc, AstProcLit *pd, Entity *e) {
  7934. GB_ASSERT(pd->body != nullptr);
  7935. if (ir_min_dep_entity(proc->module, e) == false) {
  7936. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  7937. return;
  7938. }
  7939. // NOTE(bill): Generate a new name
  7940. // parent.name-guid
  7941. String original_name = e->token.string;
  7942. String pd_name = original_name;
  7943. if (e->Procedure.link_name.len > 0) {
  7944. pd_name = e->Procedure.link_name;
  7945. }
  7946. isize name_len = proc->name.len + 1 + pd_name.len + 1 + 10 + 1;
  7947. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  7948. i32 guid = cast(i32)proc->children.count;
  7949. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(pd_name), guid);
  7950. String name = make_string(name_text, name_len-1);
  7951. set_procedure_abi_types(heap_allocator(), e->type);
  7952. irValue *value = ir_value_procedure(proc->module, e, e->type, pd->type, pd->body, name);
  7953. value->Proc.tags = pd->tags;
  7954. value->Proc.inlining = pd->inlining;
  7955. value->Proc.parent = proc;
  7956. ir_module_add_value(proc->module, e, value);
  7957. array_add(&proc->children, &value->Proc);
  7958. array_add(&proc->module->procs_to_generate, value);
  7959. }
  7960. void ir_build_constant_value_decl(irProcedure *proc, AstValueDecl *vd) {
  7961. if (vd == nullptr || vd->is_mutable) {
  7962. return;
  7963. }
  7964. for_array(i, vd->names) {
  7965. Ast *ident = vd->names[i];
  7966. GB_ASSERT(ident->kind == Ast_Ident);
  7967. Entity *e = entity_of_node(ident);
  7968. GB_ASSERT(e != nullptr);
  7969. switch (e->kind) {
  7970. case Entity_TypeName:
  7971. case Entity_Procedure:
  7972. break;
  7973. default:
  7974. continue;
  7975. }
  7976. if (e->kind == Entity_TypeName) {
  7977. bool polymorphic_struct = false;
  7978. if (e->type != nullptr && e->kind == Entity_TypeName) {
  7979. Type *bt = base_type(e->type);
  7980. if (bt->kind == Type_Struct) {
  7981. polymorphic_struct = bt->Struct.is_polymorphic;
  7982. }
  7983. }
  7984. if (!polymorphic_struct && !ir_min_dep_entity(proc->module, e)) {
  7985. continue;
  7986. }
  7987. // NOTE(bill): Generate a new name
  7988. // parent_proc.name-guid
  7989. String ts_name = e->token.string;
  7990. irModule *m = proc->module;
  7991. isize name_len = proc->name.len + 1 + ts_name.len + 1 + 10 + 1;
  7992. u8 *name_text = gb_alloc_array(ir_allocator(), u8, name_len);
  7993. i32 guid = cast(i32)m->members.entries.count;
  7994. name_len = gb_snprintf(cast(char *)name_text, name_len, "%.*s.%.*s-%d", LIT(proc->name), LIT(ts_name), guid);
  7995. String name = make_string(name_text, name_len-1);
  7996. irValue *value = ir_value_type_name(name, e->type);
  7997. ir_add_entity_name(m, e, name);
  7998. ir_gen_global_type_name(m, e, name);
  7999. } else if (e->kind == Entity_Procedure) {
  8000. CheckerInfo *info = proc->module->info;
  8001. DeclInfo *decl = decl_info_of_entity(e);
  8002. ast_node(pl, ProcLit, decl->proc_lit);
  8003. if (pl->body != nullptr) {
  8004. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  8005. if (found) {
  8006. auto procs = *found;
  8007. for_array(i, procs) {
  8008. Entity *e = procs[i];
  8009. if (!ir_min_dep_entity(proc->module, e)) {
  8010. continue;
  8011. }
  8012. DeclInfo *d = decl_info_of_entity(e);
  8013. ir_build_nested_proc(proc, &d->proc_lit->ProcLit, e);
  8014. }
  8015. } else {
  8016. ir_build_nested_proc(proc, pl, e);
  8017. }
  8018. } else {
  8019. // FFI - Foreign function interace
  8020. String original_name = e->token.string;
  8021. String name = original_name;
  8022. if (e->Procedure.is_foreign) {
  8023. ir_add_foreign_library_path(proc->module, e->Procedure.foreign_library);
  8024. }
  8025. if (e->Procedure.link_name.len > 0) {
  8026. name = e->Procedure.link_name;
  8027. }
  8028. StringHashKey key = string_hash_string(name);
  8029. irValue **prev_value = string_map_get(&proc->module->members, key);
  8030. if (prev_value != nullptr) {
  8031. // NOTE(bill): Don't do mutliple declarations in the IR
  8032. return;
  8033. }
  8034. set_procedure_abi_types(heap_allocator(), e->type);
  8035. irValue *value = ir_value_procedure(proc->module, e, e->type, pl->type, pl->body, name);
  8036. value->Proc.tags = pl->tags;
  8037. value->Proc.inlining = pl->inlining;
  8038. if (value->Proc.is_foreign || value->Proc.is_export) {
  8039. string_map_set(&proc->module->members, key, value);
  8040. } else {
  8041. array_add(&proc->children, &value->Proc);
  8042. }
  8043. ir_module_add_value(proc->module, e, value);
  8044. ir_build_proc(value, proc);
  8045. }
  8046. }
  8047. }
  8048. }
  8049. void ir_build_stmt_list(irProcedure *proc, Array<Ast *> stmts) {
  8050. // NOTE(bill): Precollect constant entities
  8051. for_array(i, stmts) {
  8052. Ast *stmt = stmts[i];
  8053. switch (stmt->kind) {
  8054. case_ast_node(vd, ValueDecl, stmt);
  8055. ir_build_constant_value_decl(proc, vd);
  8056. case_end;
  8057. case_ast_node(fb, ForeignBlockDecl, stmt);
  8058. ast_node(block, BlockStmt, fb->body);
  8059. ir_build_stmt_list(proc, block->stmts);
  8060. case_end;
  8061. }
  8062. }
  8063. for_array(i, stmts) {
  8064. ir_build_stmt(proc, stmts[i]);
  8065. }
  8066. }
  8067. void ir_build_stmt_internal(irProcedure *proc, Ast *node);
  8068. void ir_build_stmt(irProcedure *proc, Ast *node) {
  8069. Ast *prev_stmt = proc->curr_stmt;
  8070. proc->curr_stmt = node;
  8071. u64 prev_state_flags = proc->module->state_flags;
  8072. defer (proc->module->state_flags = prev_state_flags);
  8073. if (node->state_flags != 0) {
  8074. u64 in = node->state_flags;
  8075. u64 out = proc->module->state_flags;
  8076. if (in & StateFlag_bounds_check) {
  8077. out |= StateFlag_bounds_check;
  8078. out &= ~StateFlag_no_bounds_check;
  8079. } else if (in & StateFlag_no_bounds_check) {
  8080. out |= StateFlag_no_bounds_check;
  8081. out &= ~StateFlag_bounds_check;
  8082. }
  8083. proc->module->state_flags = out;
  8084. }
  8085. ir_push_debug_location(proc->module, node, proc->debug_scope);
  8086. ir_build_stmt_internal(proc, node);
  8087. ir_pop_debug_location(proc->module);
  8088. proc->curr_stmt = prev_stmt;
  8089. }
  8090. void ir_build_when_stmt(irProcedure *proc, AstWhenStmt *ws) {
  8091. irValue *cond = ir_build_expr(proc, ws->cond);
  8092. GB_ASSERT(cond->kind == irValue_Constant &&
  8093. is_type_boolean(ir_type(cond)));
  8094. GB_ASSERT(cond->Constant.value.kind == ExactValue_Bool);
  8095. if (cond->Constant.value.value_bool) {
  8096. ir_build_stmt_list(proc, ws->body->BlockStmt.stmts);
  8097. } else if (ws->else_stmt) {
  8098. switch (ws->else_stmt->kind) {
  8099. case Ast_BlockStmt:
  8100. ir_build_stmt_list(proc, ws->else_stmt->BlockStmt.stmts);
  8101. break;
  8102. case Ast_WhenStmt:
  8103. ir_build_when_stmt(proc, &ws->else_stmt->WhenStmt);
  8104. break;
  8105. default:
  8106. GB_PANIC("Invalid 'else' statement in 'when' statement");
  8107. break;
  8108. }
  8109. }
  8110. }
  8111. void ir_build_range_indexed(irProcedure *proc, irValue *expr, Type *val_type, irValue *count_ptr,
  8112. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  8113. irValue *count = nullptr;
  8114. Type *expr_type = base_type(type_deref(ir_type(expr)));
  8115. switch (expr_type->kind) {
  8116. case Type_Array:
  8117. count = ir_const_int(expr_type->Array.count);
  8118. break;
  8119. }
  8120. irValue *val = nullptr;
  8121. irValue *idx = nullptr;
  8122. irBlock *loop = nullptr;
  8123. irBlock *done = nullptr;
  8124. irBlock *body = nullptr;
  8125. irValue *index = ir_add_local_generated(proc, t_int, false);
  8126. ir_emit_store(proc, index, ir_const_int(-1));
  8127. loop = ir_new_block(proc, nullptr, "for.index.loop");
  8128. ir_emit_jump(proc, loop);
  8129. ir_start_block(proc, loop);
  8130. irValue *incr = ir_emit_arith(proc, Token_Add, ir_emit_load(proc, index), v_one, t_int);
  8131. ir_emit_store(proc, index, incr);
  8132. body = ir_new_block(proc, nullptr, "for.index.body");
  8133. done = ir_new_block(proc, nullptr, "for.index.done");
  8134. if (count == nullptr) {
  8135. GB_ASSERT(count_ptr != nullptr);
  8136. count = ir_emit_load(proc, count_ptr);
  8137. }
  8138. irValue *cond = ir_emit_comp(proc, Token_Lt, incr, count);
  8139. ir_emit_if(proc, cond, body, done);
  8140. ir_start_block(proc, body);
  8141. idx = ir_emit_load(proc, index);
  8142. switch (expr_type->kind) {
  8143. case Type_Array: {
  8144. if (val_type != nullptr) {
  8145. val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
  8146. }
  8147. break;
  8148. }
  8149. case Type_EnumeratedArray: {
  8150. if (val_type != nullptr) {
  8151. val = ir_emit_load(proc, ir_emit_array_ep(proc, expr, idx));
  8152. }
  8153. // NOTE(bill): Override the idx value for the enumeration
  8154. Type *index_type =expr_type->EnumeratedArray.index;
  8155. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  8156. idx = ir_emit_arith(proc, Token_Add, idx, ir_value_constant(index_type, expr_type->EnumeratedArray.min_value), index_type);
  8157. }
  8158. idx = ir_emit_conv(proc, idx, expr_type->EnumeratedArray.index);
  8159. break;
  8160. }
  8161. case Type_Slice: {
  8162. if (val_type != nullptr) {
  8163. irValue *elem = ir_slice_elem(proc, expr);
  8164. val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
  8165. }
  8166. break;
  8167. }
  8168. case Type_DynamicArray: {
  8169. if (val_type != nullptr) {
  8170. irValue *elem = ir_emit_struct_ep(proc, expr, 0);
  8171. elem = ir_emit_load(proc, elem);
  8172. val = ir_emit_load(proc, ir_emit_ptr_offset(proc, elem, idx));
  8173. }
  8174. break;
  8175. }
  8176. case Type_Map: {
  8177. irValue *key = ir_add_local_generated(proc, expr_type->Map.key, true);
  8178. irValue *entries = ir_map_entries_ptr(proc, expr);
  8179. irValue *elem = ir_emit_struct_ep(proc, entries, 0);
  8180. elem = ir_emit_load(proc, elem);
  8181. irValue *entry = ir_emit_ptr_offset(proc, elem, idx);
  8182. val = ir_emit_load(proc, ir_emit_struct_ep(proc, entry, 2));
  8183. irValue *hash = ir_emit_struct_ep(proc, entry, 0);
  8184. if (is_type_string(expr_type->Map.key)) {
  8185. irValue *str = ir_emit_struct_ep(proc, hash, 1);
  8186. ir_emit_store(proc, key, ir_emit_load(proc, str));
  8187. } else {
  8188. irValue *hash_ptr = ir_emit_struct_ep(proc, hash, 0);
  8189. hash_ptr = ir_emit_conv(proc, hash_ptr, ir_type(key));
  8190. ir_emit_store(proc, key, ir_emit_load(proc, hash_ptr));
  8191. }
  8192. idx = ir_emit_load(proc, key);
  8193. break;
  8194. }
  8195. default:
  8196. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  8197. break;
  8198. }
  8199. if (val_) *val_ = val;
  8200. if (idx_) *idx_ = idx;
  8201. if (loop_) *loop_ = loop;
  8202. if (done_) *done_ = done;
  8203. }
  8204. void ir_build_range_string(irProcedure *proc, irValue *expr, Type *val_type,
  8205. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  8206. irValue *count = v_zero;
  8207. Type *expr_type = base_type(ir_type(expr));
  8208. switch (expr_type->kind) {
  8209. case Type_Basic:
  8210. count = ir_string_len(proc, expr);
  8211. break;
  8212. default:
  8213. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  8214. break;
  8215. }
  8216. irValue *val = nullptr;
  8217. irValue *idx = nullptr;
  8218. irBlock *loop = nullptr;
  8219. irBlock *done = nullptr;
  8220. irBlock *body = nullptr;
  8221. irValue *offset_ = ir_add_local_generated(proc, t_int, false);
  8222. ir_emit_store(proc, offset_, v_zero);
  8223. loop = ir_new_block(proc, nullptr, "for.string.loop");
  8224. ir_emit_jump(proc, loop);
  8225. ir_start_block(proc, loop);
  8226. body = ir_new_block(proc, nullptr, "for.string.body");
  8227. done = ir_new_block(proc, nullptr, "for.string.done");
  8228. irValue *offset = ir_emit_load(proc, offset_);
  8229. irValue *cond = ir_emit_comp(proc, Token_Lt, offset, count);
  8230. ir_emit_if(proc, cond, body, done);
  8231. ir_start_block(proc, body);
  8232. irValue *str_elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, expr), offset);
  8233. irValue *str_len = ir_emit_arith(proc, Token_Sub, count, offset, t_int);
  8234. auto args = array_make<irValue *>(ir_allocator(), 1);
  8235. args[0] = ir_emit_string(proc, str_elem, str_len);
  8236. irValue *rune_and_len = ir_emit_runtime_call(proc, "string_decode_rune", args);
  8237. irValue *len = ir_emit_struct_ev(proc, rune_and_len, 1);
  8238. ir_emit_store(proc, offset_, ir_emit_arith(proc, Token_Add, offset, len, t_int));
  8239. idx = offset;
  8240. if (val_type != nullptr) {
  8241. val = ir_emit_struct_ev(proc, rune_and_len, 0);
  8242. }
  8243. if (val_) *val_ = val;
  8244. if (idx_) *idx_ = idx;
  8245. if (loop_) *loop_ = loop;
  8246. if (done_) *done_ = done;
  8247. }
  8248. void ir_build_range_interval(irProcedure *proc, AstBinaryExpr *node, Type *val_type,
  8249. irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  8250. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  8251. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  8252. irValue *lower = ir_build_expr(proc, node->left);
  8253. irValue *upper = nullptr;
  8254. irValue *val = nullptr;
  8255. irValue *idx = nullptr;
  8256. irBlock *loop = nullptr;
  8257. irBlock *done = nullptr;
  8258. irBlock *body = nullptr;
  8259. if (val_type == nullptr) {
  8260. val_type = ir_type(lower);
  8261. }
  8262. irValue *value = ir_add_local_generated(proc, val_type, false);
  8263. ir_emit_store(proc, value, lower);
  8264. irValue *index = ir_add_local_generated(proc, t_int, false);
  8265. ir_emit_store(proc, index, ir_const_int(0));
  8266. loop = ir_new_block(proc, nullptr, "for.interval.loop");
  8267. ir_emit_jump(proc, loop);
  8268. ir_start_block(proc, loop);
  8269. body = ir_new_block(proc, nullptr, "for.interval.body");
  8270. done = ir_new_block(proc, nullptr, "for.interval.done");
  8271. TokenKind op = Token_Lt;
  8272. switch (node->op.kind) {
  8273. case Token_Ellipsis: op = Token_LtEq; break;
  8274. case Token_RangeHalf: op = Token_Lt; break;
  8275. default: GB_PANIC("Invalid interval operator"); break;
  8276. }
  8277. upper = ir_build_expr(proc, node->right);
  8278. irValue *curr_value = ir_emit_load(proc, value);
  8279. irValue *cond = ir_emit_comp(proc, op, curr_value, upper);
  8280. ir_emit_if(proc, cond, body, done);
  8281. ir_start_block(proc, body);
  8282. if (value != nullptr) {
  8283. val = ir_emit_load(proc, value);
  8284. }
  8285. idx = ir_emit_load(proc, index);
  8286. ir_emit_increment(proc, value);
  8287. ir_emit_increment(proc, index);
  8288. if (val_) *val_ = val;
  8289. if (idx_) *idx_ = idx;
  8290. if (loop_) *loop_ = loop;
  8291. if (done_) *done_ = done;
  8292. }
  8293. void ir_build_range_enum(irProcedure *proc, Type *enum_type, Type *val_type, irValue **val_, irValue **idx_, irBlock **loop_, irBlock **done_) {
  8294. Type *t = enum_type;
  8295. GB_ASSERT(is_type_enum(t));
  8296. Type *enum_ptr = alloc_type_pointer(t);
  8297. t = base_type(t);
  8298. Type *core_elem = core_type(t);
  8299. GB_ASSERT(t->kind == Type_Enum);
  8300. i64 enum_count = t->Enum.fields.count;
  8301. irValue *max_count = ir_const_int(enum_count);
  8302. irValue *ti = ir_type_info(proc, t);
  8303. irValue *variant = ir_emit_struct_ep(proc, ti, 3);
  8304. irValue *eti_ptr = ir_emit_conv(proc, variant, t_type_info_enum_ptr);
  8305. irValue *values = ir_emit_load(proc, ir_emit_struct_ep(proc, eti_ptr, 2));
  8306. irValue *values_data = ir_slice_elem(proc, values);
  8307. irValue *offset_ = ir_add_local_generated(proc, t_int, false);
  8308. ir_emit_store(proc, offset_, v_zero);
  8309. irBlock *loop = ir_new_block(proc, nullptr, "for.enum.loop");
  8310. ir_emit_jump(proc, loop);
  8311. ir_start_block(proc, loop);
  8312. irBlock *body = ir_new_block(proc, nullptr, "for.enum.body");
  8313. irBlock *done = ir_new_block(proc, nullptr, "for.enum.done");
  8314. irValue *offset = ir_emit_load(proc, offset_);
  8315. irValue *cond = ir_emit_comp(proc, Token_Lt, offset, max_count);
  8316. ir_emit_if(proc, cond, body, done);
  8317. ir_start_block(proc, body);
  8318. irValue *val_ptr = ir_emit_ptr_offset(proc, values_data, offset);
  8319. ir_emit_increment(proc, offset_);
  8320. irValue *val = nullptr;
  8321. if (val_type != nullptr) {
  8322. GB_ASSERT(are_types_identical(enum_type, val_type));
  8323. if (is_type_integer(core_elem)) {
  8324. irValue *i = ir_emit_load(proc, val_ptr);
  8325. val = ir_emit_conv(proc, i, t);
  8326. } else {
  8327. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  8328. }
  8329. }
  8330. if (val_) *val_ = val;
  8331. if (idx_) *idx_ = offset;
  8332. if (loop_) *loop_ = loop;
  8333. if (done_) *done_ = done;
  8334. }
  8335. void ir_build_range_tuple(irProcedure *proc, Ast *expr, Type *val0_type, Type *val1_type,
  8336. irValue **val0_, irValue **val1_, irBlock **loop_, irBlock **done_) {
  8337. irBlock *loop = ir_new_block(proc, nullptr, "for.tuple.loop");
  8338. ir_emit_jump(proc, loop);
  8339. ir_start_block(proc, loop);
  8340. irBlock *body = ir_new_block(proc, nullptr, "for.tuple.body");
  8341. irBlock *done = ir_new_block(proc, nullptr, "for.tuple.done");
  8342. irValue *tuple_value = ir_build_expr(proc, expr);
  8343. Type *tuple = ir_type(tuple_value);
  8344. GB_ASSERT(tuple->kind == Type_Tuple);
  8345. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  8346. i32 cond_index = tuple_count-1;
  8347. irValue *cond = ir_emit_struct_ev(proc, tuple_value, cond_index);
  8348. ir_emit_if(proc, cond, body, done);
  8349. ir_start_block(proc, body);
  8350. irValue *val0 = nullptr;
  8351. if (val0_) *val0_ = ir_emit_struct_ev(proc, tuple_value, 0);
  8352. if (val1_) *val1_ = ir_emit_struct_ev(proc, tuple_value, 1);
  8353. if (loop_) *loop_ = loop;
  8354. if (done_) *done_ = done;
  8355. }
  8356. void ir_store_type_case_implicit(irProcedure *proc, Ast *clause, irValue *value) {
  8357. Entity *e = implicit_entity_of_node(clause);
  8358. GB_ASSERT(e != nullptr);
  8359. if (e->flags & EntityFlag_Value) {
  8360. // by value
  8361. irValue *x = ir_add_local(proc, e, nullptr, false);
  8362. GB_ASSERT(are_types_identical(ir_type(value), e->type));
  8363. ir_emit_store(proc, x, value);
  8364. } else {
  8365. // by reference
  8366. ir_module_add_value(proc->module, e, value);
  8367. }
  8368. }
  8369. irAddr ir_store_range_stmt_val(irProcedure *proc, Ast *stmt_val, irValue *value) {
  8370. Entity *e = entity_of_node(stmt_val);
  8371. if (e == nullptr) {
  8372. return {};
  8373. }
  8374. if ((e->flags & EntityFlag_Value) == 0) {
  8375. if (value->kind == irValue_Instr) {
  8376. if (value->Instr.kind == irInstr_Load) {
  8377. irValue *ptr = value->Instr.Load.address;
  8378. Type *vt = type_deref(ir_type(ptr));
  8379. if (!are_types_identical(vt, e->type)) {
  8380. GB_ASSERT(are_types_identical(base_type(vt), base_type(e->type)));
  8381. ptr = ir_emit_conv(proc, ptr, alloc_type_pointer(e->type));
  8382. }
  8383. ir_module_add_value(proc->module, e, ptr);
  8384. return ir_addr(ptr);
  8385. }
  8386. }
  8387. }
  8388. // by value
  8389. irAddr addr = ir_addr(ir_add_local(proc, e, nullptr, false));
  8390. Type *vt = ir_type(value);
  8391. Type *base_et = base_type(e->type);
  8392. Type *base_vt = base_type(vt);
  8393. if (!are_types_identical(e->type, vt)) {
  8394. if (are_types_identical(base_et, base_vt)) {
  8395. value = ir_emit_conv(proc, value, e->type);
  8396. } else {
  8397. // gb_printf_err("%s\n", expr_to_string(stmt_val));
  8398. // gb_printf_err("Entity: %s -> Value: %s\n", type_to_string(e->type), type_to_string(vt));
  8399. // Token tok = ast_token(stmt_val);
  8400. // gb_printf_err("%.*s(%td:%td)\n", LIT(tok.pos.file), tok.pos.line, tok.pos.column);
  8401. }
  8402. }
  8403. ir_addr_store(proc, addr, value);
  8404. return addr;
  8405. }
  8406. void ir_type_case_body(irProcedure *proc, Ast *label, Ast *clause, irBlock *body, irBlock *done) {
  8407. ast_node(cc, CaseClause, clause);
  8408. ir_push_target_list(proc, label, done, nullptr, nullptr);
  8409. ir_open_scope(proc);
  8410. ir_build_stmt_list(proc, cc->stmts);
  8411. ir_close_scope(proc, irDeferExit_Default, body);
  8412. ir_pop_target_list(proc);
  8413. ir_emit_jump(proc, done);
  8414. }
  8415. void ir_build_stmt_internal(irProcedure *proc, Ast *node) {
  8416. switch (node->kind) {
  8417. case_ast_node(bs, EmptyStmt, node);
  8418. case_end;
  8419. case_ast_node(us, UsingStmt, node);
  8420. case_end;
  8421. case_ast_node(ws, WhenStmt, node);
  8422. ir_build_when_stmt(proc, ws);
  8423. case_end;
  8424. case_ast_node(vd, ValueDecl, node);
  8425. if (vd->is_mutable) {
  8426. irModule *m = proc->module;
  8427. bool is_static = false;
  8428. if (vd->names.count > 0) {
  8429. Entity *e = entity_of_node(vd->names[0]);
  8430. if (e->flags & EntityFlag_Static) {
  8431. // NOTE(bill): If one of the entities is static, they all are
  8432. is_static = true;
  8433. }
  8434. }
  8435. if (is_static) {
  8436. for_array(i, vd->names) {
  8437. irValue *value = nullptr;
  8438. if (vd->values.count > 0) {
  8439. GB_ASSERT(vd->names.count == vd->values.count);
  8440. Ast *ast_value = vd->values[i];
  8441. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  8442. ast_value->tav.mode == Addressing_Invalid);
  8443. value = ir_add_module_constant(m, ast_value->tav.type, ast_value->tav.value);
  8444. }
  8445. Ast *ident = vd->names[i];
  8446. GB_ASSERT(!is_blank_ident(ident));
  8447. Entity *e = entity_of_node(ident);
  8448. GB_ASSERT(e->flags & EntityFlag_Static);
  8449. String name = e->token.string;
  8450. String mangled_name = {};
  8451. {
  8452. gbString str = gb_string_make_length(heap_allocator(), proc->name.text, proc->name.len);
  8453. str = gb_string_appendc(str, "-");
  8454. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  8455. mangled_name.text = cast(u8 *)str;
  8456. mangled_name.len = gb_string_length(str);
  8457. }
  8458. ir_add_entity_name(m, e, mangled_name);
  8459. irValue *g = ir_value_global(e, value);
  8460. g->Global.name = mangled_name;
  8461. g->Global.is_private = true;
  8462. if (e->Variable.thread_local_model != "") {
  8463. g->Global.thread_local_model = e->Variable.thread_local_model;
  8464. } else {
  8465. g->Global.is_internal = true;
  8466. }
  8467. ir_module_add_value(proc->module, e, g);
  8468. string_map_set(&proc->module->members, mangled_name, g);
  8469. }
  8470. return;
  8471. }
  8472. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
  8473. defer (gb_temp_arena_memory_end(tmp));
  8474. if (vd->values.count == 0) { // declared and zero-initialized
  8475. for_array(i, vd->names) {
  8476. Ast *name = vd->names[i];
  8477. if (!is_blank_ident(name)) {
  8478. ir_add_local_for_identifier(proc, name, true);
  8479. }
  8480. }
  8481. } else { // Tuple(s)
  8482. auto lvals = array_make<irAddr>(m->tmp_allocator, 0, vd->names.count);
  8483. auto inits = array_make<irValue *>(m->tmp_allocator, 0, vd->names.count);
  8484. for_array(i, vd->names) {
  8485. Ast *name = vd->names[i];
  8486. irAddr lval = ir_addr(nullptr);
  8487. if (!is_blank_ident(name)) {
  8488. // NOTE(bill, 2020-06-10): This must be zero initialize because of weird LLVM optimization behaviours
  8489. ir_add_local_for_identifier(proc, name, true);
  8490. lval = ir_build_addr(proc, name);
  8491. }
  8492. array_add(&lvals, lval);
  8493. }
  8494. for_array(i, vd->values) {
  8495. irValue *init = ir_build_expr(proc, vd->values[i]);
  8496. Type *t = ir_type(init);
  8497. if (t->kind == Type_Tuple) {
  8498. for_array(i, t->Tuple.variables) {
  8499. Entity *e = t->Tuple.variables[i];
  8500. irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
  8501. array_add(&inits, v);
  8502. }
  8503. } else {
  8504. array_add(&inits, init);
  8505. }
  8506. }
  8507. for_array(i, inits) {
  8508. ir_addr_store(proc, lvals[i], inits[i]);
  8509. }
  8510. }
  8511. }
  8512. case_end;
  8513. case_ast_node(as, AssignStmt, node);
  8514. ir_emit_comment(proc, str_lit("AssignStmt"));
  8515. irModule *m = proc->module;
  8516. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
  8517. switch (as->op.kind) {
  8518. case Token_Eq: {
  8519. auto lvals = array_make<irAddr>(m->tmp_allocator, 0, as->lhs.count);
  8520. for_array(i, as->lhs) {
  8521. Ast *lhs = as->lhs[i];
  8522. irAddr lval = {};
  8523. if (!is_blank_ident(lhs)) {
  8524. lval = ir_build_addr(proc, lhs);
  8525. }
  8526. array_add(&lvals, lval);
  8527. }
  8528. if (as->lhs.count == as->rhs.count) {
  8529. if (as->lhs.count == 1) {
  8530. Ast *rhs = as->rhs[0];
  8531. irValue *init = ir_build_expr(proc, rhs);
  8532. ir_addr_store(proc, lvals[0], init);
  8533. } else {
  8534. auto inits = array_make<irValue *>(m->tmp_allocator, 0, lvals.count);
  8535. for_array(i, as->rhs) {
  8536. irValue *init = ir_build_expr(proc, as->rhs[i]);
  8537. array_add(&inits, init);
  8538. }
  8539. for_array(i, inits) {
  8540. auto lval = lvals[i];
  8541. ir_addr_store(proc, lval, inits[i]);
  8542. }
  8543. }
  8544. } else {
  8545. auto inits = array_make<irValue *>(m->tmp_allocator, 0, lvals.count);
  8546. for_array(i, as->rhs) {
  8547. irValue *init = ir_build_expr(proc, as->rhs[i]);
  8548. Type *t = ir_type(init);
  8549. // TODO(bill): refactor for code reuse as this is repeated a bit
  8550. if (t->kind == Type_Tuple) {
  8551. for_array(i, t->Tuple.variables) {
  8552. Entity *e = t->Tuple.variables[i];
  8553. irValue *v = ir_emit_struct_ev(proc, init, cast(i32)i);
  8554. array_add(&inits, v);
  8555. }
  8556. } else {
  8557. array_add(&inits, init);
  8558. }
  8559. }
  8560. for_array(i, inits) {
  8561. ir_addr_store(proc, lvals[i], inits[i]);
  8562. }
  8563. }
  8564. break;
  8565. }
  8566. default: {
  8567. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  8568. // +=, -=, etc
  8569. i32 op = cast(i32)as->op.kind;
  8570. op += Token_Add - Token_AddEq; // Convert += to +
  8571. if (op == Token_CmpAnd || op == Token_CmpOr) {
  8572. Type *type = as->lhs[0]->tav.type;
  8573. irValue *new_value = ir_emit_logical_binary_expr(proc, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  8574. irAddr lhs = ir_build_addr(proc, as->lhs[0]);
  8575. ir_addr_store(proc, lhs, new_value);
  8576. } else {
  8577. irAddr lhs = ir_build_addr(proc, as->lhs[0]);
  8578. irValue *value = ir_build_expr(proc, as->rhs[0]);
  8579. ir_build_assign_op(proc, lhs, value, cast(TokenKind)op);
  8580. }
  8581. return;
  8582. }
  8583. }
  8584. case_end;
  8585. case_ast_node(es, ExprStmt, node);
  8586. // NOTE(bill): No need to use return value
  8587. ir_build_expr(proc, es->expr);
  8588. case_end;
  8589. case_ast_node(bs, BlockStmt, node);
  8590. if (bs->label != nullptr) {
  8591. irBlock *done = ir_new_block(proc, node, "block.done");
  8592. irTargetList *tl = ir_push_target_list(proc, bs->label, done, nullptr, nullptr);
  8593. tl->is_block = true;
  8594. ir_open_scope(proc);
  8595. ir_build_stmt_list(proc, bs->stmts);
  8596. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8597. ir_emit_jump(proc, done);
  8598. ir_start_block(proc, done);
  8599. } else {
  8600. ir_open_scope(proc);
  8601. ir_build_stmt_list(proc, bs->stmts);
  8602. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8603. }
  8604. case_end;
  8605. case_ast_node(ds, DeferStmt, node);
  8606. ir_emit_comment(proc, str_lit("DeferStmt"));
  8607. isize scope_index = proc->scope_index;
  8608. // TODO(bill): What was the original rationale behind this line?
  8609. // if (ds->stmt->kind == Ast_BlockStmt) scope_index--;
  8610. ir_add_defer_node(proc, scope_index, ds->stmt);
  8611. case_end;
  8612. case_ast_node(rs, ReturnStmt, node);
  8613. ir_emit_comment(proc, str_lit("ReturnStmt"));
  8614. irValue *v = nullptr;
  8615. TypeTuple *tuple = &proc->type->Proc.results->Tuple;
  8616. isize return_count = proc->type->Proc.result_count;
  8617. isize res_count = rs->results.count;
  8618. if (return_count == 0) {
  8619. // No return values
  8620. } else if (return_count == 1) {
  8621. Entity *e = tuple->variables[0];
  8622. if (res_count == 0) {
  8623. irValue **found = map_get(&proc->module->values, hash_entity(e));
  8624. GB_ASSERT(found);
  8625. v = ir_emit_load(proc, *found);
  8626. } else {
  8627. v = ir_build_expr(proc, rs->results[0]);
  8628. v = ir_emit_conv(proc, v, e->type);
  8629. }
  8630. if (proc->type->Proc.has_named_results) {
  8631. // NOTE(bill): store the named values before returning
  8632. if (e->token.string != "") {
  8633. irValue **found = map_get(&proc->module->values, hash_entity(e));
  8634. GB_ASSERT(found != nullptr);
  8635. ir_emit_store(proc, *found, v);
  8636. }
  8637. }
  8638. } else {
  8639. gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena);
  8640. defer (gb_temp_arena_memory_end(tmp));
  8641. auto results = array_make<irValue *>(proc->module->tmp_allocator, 0, return_count);
  8642. if (res_count != 0) {
  8643. for (isize res_index = 0; res_index < res_count; res_index++) {
  8644. irValue *res = ir_build_expr(proc, rs->results[res_index]);
  8645. Type *t = ir_type(res);
  8646. if (t->kind == Type_Tuple) {
  8647. for_array(i, t->Tuple.variables) {
  8648. Entity *e = t->Tuple.variables[i];
  8649. irValue *v = ir_emit_struct_ev(proc, res, cast(i32)i);
  8650. array_add(&results, v);
  8651. }
  8652. } else {
  8653. array_add(&results, res);
  8654. }
  8655. }
  8656. } else {
  8657. for (isize res_index = 0; res_index < return_count; res_index++) {
  8658. Entity *e = tuple->variables[res_index];
  8659. irValue **found = map_get(&proc->module->values, hash_entity(e));
  8660. GB_ASSERT(found);
  8661. irValue *res = ir_emit_load(proc, *found);
  8662. array_add(&results, res);
  8663. }
  8664. }
  8665. GB_ASSERT(results.count == return_count);
  8666. if (proc->type->Proc.has_named_results) {
  8667. // NOTE(bill): store the named values before returning
  8668. for_array(i, tuple->variables) {
  8669. Entity *e = tuple->variables[i];
  8670. if (e->kind != Entity_Variable) {
  8671. continue;
  8672. }
  8673. if (e->token.string == "") {
  8674. continue;
  8675. }
  8676. irValue **found = map_get(&proc->module->values, hash_entity(e));
  8677. GB_ASSERT(found != nullptr);
  8678. ir_emit_store(proc, *found, results[i]);
  8679. }
  8680. }
  8681. Type *ret_type = proc->type->Proc.results;
  8682. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  8683. v = ir_add_local_generated(proc, ret_type, false);
  8684. for_array(i, results) {
  8685. Entity *e = tuple->variables[i];
  8686. irValue *res = ir_emit_conv(proc, results[i], e->type);
  8687. irValue *field = ir_emit_struct_ep(proc, v, cast(i32)i);
  8688. ir_emit_store(proc, field, res);
  8689. }
  8690. v = ir_emit_load(proc, v);
  8691. }
  8692. ir_emit_return(proc, v);
  8693. case_end;
  8694. case_ast_node(is, IfStmt, node);
  8695. ir_emit_comment(proc, str_lit("IfStmt"));
  8696. ir_open_scope(proc); // Scope #1
  8697. if (is->init != nullptr) {
  8698. // TODO(bill): Should this have a separate block to begin with?
  8699. #if 1
  8700. irBlock *init = ir_new_block(proc, node, "if.init");
  8701. ir_emit_jump(proc, init);
  8702. ir_start_block(proc, init);
  8703. #endif
  8704. ir_build_stmt(proc, is->init);
  8705. }
  8706. irBlock *then = ir_new_block(proc, node, "if.then");
  8707. irBlock *done = ir_new_block(proc, node, "if.done");
  8708. irBlock *else_ = done;
  8709. if (is->else_stmt != nullptr) {
  8710. else_ = ir_new_block(proc, is->else_stmt, "if.else");
  8711. }
  8712. ir_build_cond(proc, is->cond, then, else_);
  8713. ir_start_block(proc, then);
  8714. if (is->label != nullptr) {
  8715. irTargetList *tl = ir_push_target_list(proc, is->label, done, nullptr, nullptr);
  8716. tl->is_block = true;
  8717. }
  8718. // ir_open_scope(proc);
  8719. ir_build_stmt(proc, is->body);
  8720. // ir_close_scope(proc, irDeferExit_Default, nullptr);
  8721. ir_emit_jump(proc, done);
  8722. if (is->else_stmt != nullptr) {
  8723. ir_start_block(proc, else_);
  8724. ir_open_scope(proc);
  8725. ir_build_stmt(proc, is->else_stmt);
  8726. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8727. ir_emit_jump(proc, done);
  8728. }
  8729. ir_start_block(proc, done);
  8730. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8731. case_end;
  8732. case_ast_node(fs, ForStmt, node);
  8733. ir_emit_comment(proc, str_lit("ForStmt"));
  8734. ir_open_scope(proc); // Open Scope here
  8735. if (fs->init != nullptr) {
  8736. #if 1
  8737. irBlock *init = ir_new_block(proc, node, "for.init");
  8738. ir_emit_jump(proc, init);
  8739. ir_start_block(proc, init);
  8740. #endif
  8741. ir_build_stmt(proc, fs->init);
  8742. }
  8743. irBlock *body = ir_new_block(proc, node, "for.body");
  8744. irBlock *done = ir_new_block(proc, node, "for.done"); // NOTE(bill): Append later
  8745. irBlock *loop = body;
  8746. if (fs->cond != nullptr) {
  8747. loop = ir_new_block(proc, node, "for.loop");
  8748. }
  8749. irBlock *post = loop;
  8750. if (fs->post != nullptr) {
  8751. post = ir_new_block(proc, node, "for.post");
  8752. }
  8753. ir_emit_jump(proc, loop);
  8754. ir_start_block(proc, loop);
  8755. if (loop != body) {
  8756. ir_build_cond(proc, fs->cond, body, done);
  8757. ir_start_block(proc, body);
  8758. }
  8759. ir_push_target_list(proc, fs->label, done, post, nullptr);
  8760. ir_build_stmt(proc, fs->body);
  8761. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8762. ir_pop_target_list(proc);
  8763. ir_emit_jump(proc, post);
  8764. if (fs->post != nullptr) {
  8765. ir_start_block(proc, post);
  8766. ir_build_stmt(proc, fs->post);
  8767. ir_emit_jump(proc, loop);
  8768. }
  8769. ir_start_block(proc, done);
  8770. case_end;
  8771. case_ast_node(rs, RangeStmt, node);
  8772. ir_emit_comment(proc, str_lit("RangeStmt"));
  8773. ir_open_scope(proc); // Open scope here
  8774. Type *val0_type = nullptr;
  8775. Type *val1_type = nullptr;
  8776. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  8777. val0_type = type_of_expr(rs->val0);
  8778. }
  8779. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  8780. val1_type = type_of_expr(rs->val1);
  8781. }
  8782. if (val0_type != nullptr) {
  8783. ir_add_local_for_identifier(proc, rs->val0, true);
  8784. }
  8785. if (val1_type != nullptr) {
  8786. ir_add_local_for_identifier(proc, rs->val1, true);
  8787. }
  8788. irValue *val = nullptr;
  8789. irValue *key = nullptr;
  8790. irBlock *loop = nullptr;
  8791. irBlock *done = nullptr;
  8792. Ast *expr = unparen_expr(rs->expr);
  8793. bool is_map = false;
  8794. TypeAndValue tav = type_and_value_of_expr(expr);
  8795. if (is_ast_range(expr)) {
  8796. ir_build_range_interval(proc, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  8797. } else if (tav.mode == Addressing_Type) {
  8798. ir_build_range_enum(proc, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  8799. } else {
  8800. Type *expr_type = type_of_expr(expr);
  8801. Type *et = base_type(type_deref(expr_type));
  8802. switch (et->kind) {
  8803. case Type_Map: {
  8804. is_map = true;
  8805. gbAllocator a = ir_allocator();
  8806. irAddr addr = ir_build_addr(proc, expr);
  8807. bool allow_reference = true;
  8808. irValue *map = ir_addr_get_ptr(proc, addr, allow_reference);
  8809. if (is_type_pointer(ir_addr_type(addr))) {
  8810. map = ir_addr_load(proc, addr);
  8811. }
  8812. irValue *entries_ptr = ir_map_entries_ptr(proc, map);
  8813. irValue *count_ptr = ir_emit_struct_ep(proc, entries_ptr, 1);
  8814. ir_build_range_indexed(proc, map, val1_type, count_ptr, &val, &key, &loop, &done);
  8815. break;
  8816. }
  8817. case Type_Array: {
  8818. irValue *count_ptr = nullptr;
  8819. irValue *array = ir_build_addr_ptr(proc, expr);
  8820. if (is_type_pointer(type_deref(ir_type(array)))) {
  8821. array = ir_emit_load(proc, array);
  8822. }
  8823. count_ptr = ir_add_local_generated(proc, t_int, false);
  8824. ir_emit_store(proc, count_ptr, ir_const_int(et->Array.count));
  8825. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  8826. break;
  8827. }
  8828. case Type_EnumeratedArray: {
  8829. irValue *count_ptr = nullptr;
  8830. irValue *array = ir_build_addr_ptr(proc, expr);
  8831. if (is_type_pointer(type_deref(ir_type(array)))) {
  8832. array = ir_emit_load(proc, array);
  8833. }
  8834. count_ptr = ir_add_local_generated(proc, t_int, false);
  8835. ir_emit_store(proc, count_ptr, ir_const_int(et->EnumeratedArray.count));
  8836. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  8837. break;
  8838. }
  8839. case Type_DynamicArray: {
  8840. irValue *count_ptr = nullptr;
  8841. irValue *array = ir_build_addr_ptr(proc, expr);
  8842. if (is_type_pointer(type_deref(ir_type(array)))) {
  8843. array = ir_emit_load(proc, array);
  8844. }
  8845. count_ptr = ir_emit_struct_ep(proc, array, 1);
  8846. ir_build_range_indexed(proc, array, val0_type, count_ptr, &val, &key, &loop, &done);
  8847. break;
  8848. }
  8849. case Type_Slice: {
  8850. irValue *count_ptr = nullptr;
  8851. irValue *slice = ir_build_expr(proc, expr);
  8852. if (is_type_pointer(ir_type(slice))) {
  8853. count_ptr = ir_emit_struct_ep(proc, slice, 1);
  8854. slice = ir_emit_load(proc, slice);
  8855. } else {
  8856. count_ptr = ir_add_local_generated(proc, t_int, false);
  8857. ir_emit_store(proc, count_ptr, ir_slice_len(proc, slice));
  8858. }
  8859. ir_build_range_indexed(proc, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  8860. break;
  8861. }
  8862. case Type_Basic: {
  8863. irValue *string = ir_build_expr(proc, expr);
  8864. if (is_type_pointer(ir_type(string))) {
  8865. string = ir_emit_load(proc, string);
  8866. }
  8867. if (is_type_untyped(expr_type)) {
  8868. irValue *s = ir_add_local_generated(proc, default_type(ir_type(string)), false);
  8869. ir_emit_store(proc, s, string);
  8870. string = ir_emit_load(proc, s);
  8871. }
  8872. Type *t = base_type(ir_type(string));
  8873. GB_ASSERT(!is_type_cstring(t));
  8874. ir_build_range_string(proc, string, val0_type, &val, &key, &loop, &done);
  8875. break;
  8876. }
  8877. case Type_Tuple:
  8878. ir_build_range_tuple(proc, expr, val0_type, val1_type, &val, &key, &loop, &done);
  8879. break;
  8880. default:
  8881. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  8882. break;
  8883. }
  8884. }
  8885. if (is_map) {
  8886. if (val0_type) ir_store_range_stmt_val(proc, rs->val0, key);
  8887. if (val1_type) ir_store_range_stmt_val(proc, rs->val1, val);
  8888. } else {
  8889. if (val0_type) ir_store_range_stmt_val(proc, rs->val0, val);
  8890. if (val1_type) ir_store_range_stmt_val(proc, rs->val1, key);
  8891. }
  8892. ir_push_target_list(proc, rs->label, done, loop, nullptr);
  8893. ir_build_stmt(proc, rs->body);
  8894. ir_close_scope(proc, irDeferExit_Default, nullptr);
  8895. ir_pop_target_list(proc);
  8896. ir_emit_jump(proc, loop);
  8897. ir_start_block(proc, done);
  8898. case_end;
  8899. case_ast_node(rs, InlineRangeStmt, node);
  8900. ir_emit_comment(proc, str_lit("InlineRangeStmt"));
  8901. ir_open_scope(proc); // Open scope here
  8902. irBlock *done = ir_new_block(proc, node, "inline.for.done");
  8903. Type *val0_type = nullptr;
  8904. Type *val1_type = nullptr;
  8905. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  8906. val0_type = type_of_expr(rs->val0);
  8907. }
  8908. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  8909. val1_type = type_of_expr(rs->val1);
  8910. }
  8911. if (val0_type != nullptr) {
  8912. ir_add_local_for_identifier(proc, rs->val0, true);
  8913. }
  8914. if (val1_type != nullptr) {
  8915. ir_add_local_for_identifier(proc, rs->val1, true);
  8916. }
  8917. irValue *val = nullptr;
  8918. irValue *key = nullptr;
  8919. Ast *expr = unparen_expr(rs->expr);
  8920. TypeAndValue tav = type_and_value_of_expr(expr);
  8921. if (is_ast_range(expr)) {
  8922. irAddr val0_addr = {};
  8923. irAddr val1_addr = {};
  8924. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  8925. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  8926. TokenKind op = expr->BinaryExpr.op.kind;
  8927. Ast *start_expr = expr->BinaryExpr.left;
  8928. Ast *end_expr = expr->BinaryExpr.right;
  8929. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  8930. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  8931. ExactValue start = start_expr->tav.value;
  8932. ExactValue end = end_expr->tav.value;
  8933. if (op == Token_Ellipsis) { // .. [start, end]
  8934. ExactValue index = exact_value_i64(0);
  8935. for (ExactValue val = start;
  8936. compare_exact_values(Token_LtEq, val, end);
  8937. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  8938. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  8939. ir_emit_jump(proc, body);
  8940. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, val));
  8941. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, index));
  8942. ir_start_block(proc, body);
  8943. ir_build_stmt(proc, rs->body);
  8944. }
  8945. } else if (op == Token_RangeHalf) { // ..< [start, end)
  8946. ExactValue index = exact_value_i64(0);
  8947. for (ExactValue val = start;
  8948. compare_exact_values(Token_Lt, val, end);
  8949. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  8950. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  8951. ir_emit_jump(proc, body);
  8952. ir_start_block(proc, body);
  8953. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, val));
  8954. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, index));
  8955. ir_build_stmt(proc, rs->body);
  8956. }
  8957. }
  8958. } else if (tav.mode == Addressing_Type) {
  8959. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  8960. Type *et = type_deref(tav.type);
  8961. Type *bet = base_type(et);
  8962. irAddr val0_addr = {};
  8963. irAddr val1_addr = {};
  8964. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  8965. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  8966. for_array(i, bet->Enum.fields) {
  8967. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  8968. ir_emit_jump(proc, body);
  8969. ir_start_block(proc, body);
  8970. Entity *field = bet->Enum.fields[i];
  8971. GB_ASSERT(field->kind == Entity_Constant);
  8972. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, field->Constant.value));
  8973. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(i)));
  8974. ir_build_stmt(proc, rs->body);
  8975. }
  8976. } else {
  8977. irAddr val0_addr = {};
  8978. irAddr val1_addr = {};
  8979. if (val0_type) val0_addr = ir_build_addr(proc, rs->val0);
  8980. if (val1_type) val1_addr = ir_build_addr(proc, rs->val1);
  8981. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  8982. Type *t = base_type(expr->tav.type);
  8983. switch (t->kind) {
  8984. case Type_Basic:
  8985. GB_ASSERT(is_type_string(t));
  8986. {
  8987. ExactValue value = expr->tav.value;
  8988. GB_ASSERT(value.kind == ExactValue_String);
  8989. String str = value.value_string;
  8990. Rune codepoint = 0;
  8991. isize offset = 0;
  8992. do {
  8993. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  8994. ir_emit_jump(proc, body);
  8995. ir_start_block(proc, body);
  8996. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  8997. if (val0_type) ir_addr_store(proc, val0_addr, ir_value_constant(val0_type, exact_value_i64(codepoint)));
  8998. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(offset)));
  8999. ir_build_stmt(proc, rs->body);
  9000. offset += width;
  9001. } while (offset < str.len);
  9002. }
  9003. break;
  9004. case Type_Array:
  9005. if (t->Array.count > 0) {
  9006. irValue *val = ir_build_expr(proc, expr);
  9007. irValue *val_addr = ir_address_from_load_or_generate_local(proc, val);
  9008. for (i64 i = 0; i < t->Array.count; i++) {
  9009. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  9010. ir_emit_jump(proc, body);
  9011. ir_start_block(proc, body);
  9012. if (val0_type) {
  9013. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  9014. irValue *elem = ir_emit_array_epi(proc, val_addr, cast(i32)i);
  9015. ir_addr_store(proc, val0_addr, ir_emit_load(proc, elem));
  9016. }
  9017. if (val1_type) ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, exact_value_i64(i)));
  9018. ir_build_stmt(proc, rs->body);
  9019. }
  9020. }
  9021. break;
  9022. case Type_EnumeratedArray:
  9023. if (t->EnumeratedArray.count > 0) {
  9024. irValue *val = ir_build_expr(proc, expr);
  9025. irValue *val_addr = ir_address_from_load_or_generate_local(proc, val);
  9026. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  9027. irBlock *body = ir_new_block(proc, node, "inline.for.body");
  9028. ir_emit_jump(proc, body);
  9029. ir_start_block(proc, body);
  9030. if (val0_type) {
  9031. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  9032. irValue *elem = ir_emit_array_epi(proc, val_addr, cast(i32)i);
  9033. ir_addr_store(proc, val0_addr, ir_emit_load(proc, elem));
  9034. }
  9035. if (val1_type) {
  9036. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  9037. ir_addr_store(proc, val1_addr, ir_value_constant(val1_type, idx));
  9038. }
  9039. ir_build_stmt(proc, rs->body);
  9040. }
  9041. }
  9042. break;
  9043. default:
  9044. GB_PANIC("Invalid inline for type");
  9045. break;
  9046. }
  9047. }
  9048. ir_emit_jump(proc, done);
  9049. ir_start_block(proc, done);
  9050. ir_close_scope(proc, irDeferExit_Default, nullptr);
  9051. case_end;
  9052. case_ast_node(ss, SwitchStmt, node);
  9053. ir_emit_comment(proc, str_lit("SwitchStmt"));
  9054. if (ss->init != nullptr) {
  9055. ir_build_stmt(proc, ss->init);
  9056. }
  9057. irValue *tag = v_true;
  9058. if (ss->tag != nullptr) {
  9059. tag = ir_build_expr(proc, ss->tag);
  9060. }
  9061. irBlock *done = ir_new_block(proc, node, "switch.done"); // NOTE(bill): Append later
  9062. ast_node(body, BlockStmt, ss->body);
  9063. Array<Ast *> default_stmts = {};
  9064. irBlock *default_fall = nullptr;
  9065. irBlock *default_block = nullptr;
  9066. irBlock *fall = nullptr;
  9067. bool append_fall = false;
  9068. isize case_count = body->stmts.count;
  9069. for_array(i, body->stmts) {
  9070. Ast *clause = body->stmts[i];
  9071. irBlock *body = fall;
  9072. ast_node(cc, CaseClause, clause);
  9073. if (body == nullptr) {
  9074. if (cc->list.count == 0) {
  9075. body = ir_new_block(proc, clause, "switch.dflt.body");
  9076. } else {
  9077. body = ir_new_block(proc, clause, "switch.case.body");
  9078. }
  9079. }
  9080. if (append_fall && body == fall) {
  9081. append_fall = false;
  9082. }
  9083. fall = done;
  9084. if (i+1 < case_count) {
  9085. append_fall = true;
  9086. fall = ir_new_block(proc, clause, "switch.fall.body");
  9087. }
  9088. if (cc->list.count == 0) {
  9089. // default case
  9090. default_stmts = cc->stmts;
  9091. default_fall = fall;
  9092. default_block = body;
  9093. continue;
  9094. }
  9095. irBlock *next_cond = nullptr;
  9096. for_array(j, cc->list) {
  9097. Ast *expr = unparen_expr(cc->list[j]);
  9098. next_cond = ir_new_block(proc, clause, "switch.case.next");
  9099. irValue *cond = v_false;
  9100. if (is_ast_range(expr)) {
  9101. ast_node(ie, BinaryExpr, expr);
  9102. TokenKind op = Token_Invalid;
  9103. switch (ie->op.kind) {
  9104. case Token_Ellipsis: op = Token_LtEq; break;
  9105. case Token_RangeHalf: op = Token_Lt; break;
  9106. default: GB_PANIC("Invalid interval operator"); break;
  9107. }
  9108. irValue *lhs = ir_build_expr(proc, ie->left);
  9109. irValue *rhs = ir_build_expr(proc, ie->right);
  9110. // TODO(bill): do short circuit here
  9111. irValue *cond_lhs = ir_emit_comp(proc, Token_LtEq, lhs, tag);
  9112. irValue *cond_rhs = ir_emit_comp(proc, op, tag, rhs);
  9113. cond = ir_emit_arith(proc, Token_And, cond_lhs, cond_rhs, t_bool);
  9114. } else {
  9115. if (expr->tav.mode == Addressing_Type) {
  9116. GB_ASSERT(is_type_typeid(ir_type(tag)));
  9117. irValue *e = ir_typeid(proc->module, expr->tav.type);
  9118. e = ir_emit_conv(proc, e, ir_type(tag));
  9119. cond = ir_emit_comp(proc, Token_CmpEq, tag, e);
  9120. } else {
  9121. cond = ir_emit_comp(proc, Token_CmpEq, tag, ir_build_expr(proc, expr));
  9122. }
  9123. }
  9124. ir_emit_if(proc, cond, body, next_cond);
  9125. ir_start_block(proc, next_cond);
  9126. }
  9127. ir_start_block(proc, body);
  9128. ir_push_target_list(proc, ss->label, done, nullptr, fall);
  9129. ir_open_scope(proc);
  9130. ir_build_stmt_list(proc, cc->stmts);
  9131. ir_close_scope(proc, irDeferExit_Default, body);
  9132. ir_pop_target_list(proc);
  9133. ir_emit_jump(proc, done);
  9134. proc->curr_block = next_cond;
  9135. // ir_start_block(proc, next_cond);
  9136. }
  9137. if (default_block != nullptr) {
  9138. ir_emit_jump(proc, default_block);
  9139. ir_start_block(proc, default_block);
  9140. ir_push_target_list(proc, ss->label, done, nullptr, default_fall);
  9141. ir_open_scope(proc);
  9142. ir_build_stmt_list(proc, default_stmts);
  9143. ir_close_scope(proc, irDeferExit_Default, default_block);
  9144. ir_pop_target_list(proc);
  9145. }
  9146. ir_emit_jump(proc, done);
  9147. ir_start_block(proc, done);
  9148. case_end;
  9149. case_ast_node(ss, TypeSwitchStmt, node);
  9150. ir_emit_comment(proc, str_lit("TypeSwitchStmt"));
  9151. gbAllocator allocator = ir_allocator();
  9152. ast_node(as, AssignStmt, ss->tag);
  9153. GB_ASSERT(as->lhs.count == 1);
  9154. GB_ASSERT(as->rhs.count == 1);
  9155. irValue *parent = ir_build_expr(proc, as->rhs[0]);
  9156. Type *parent_type = ir_type(parent);
  9157. bool is_parent_ptr = is_type_pointer(ir_type(parent));
  9158. TypeSwitchKind switch_kind = check_valid_type_switch_type(ir_type(parent));
  9159. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  9160. irValue *parent_value = parent;
  9161. irValue *parent_ptr = parent;
  9162. if (!is_parent_ptr) {
  9163. parent_ptr = ir_address_from_load_or_generate_local(proc, parent_ptr);
  9164. }
  9165. irValue *tag_index = nullptr;
  9166. irValue *union_data = nullptr;
  9167. if (switch_kind == TypeSwitch_Union) {
  9168. ir_emit_comment(proc, str_lit("get union's tag"));
  9169. tag_index = ir_emit_load(proc, ir_emit_union_tag_ptr(proc, parent_ptr));
  9170. union_data = ir_emit_conv(proc, parent_ptr, t_rawptr);
  9171. }
  9172. irBlock *start_block = ir_new_block(proc, node, "typeswitch.case.first");
  9173. ir_emit_jump(proc, start_block);
  9174. ir_start_block(proc, start_block);
  9175. // NOTE(bill): Append this later
  9176. irBlock *done = ir_new_block(proc, node, "typeswitch.done");
  9177. Ast *default_ = nullptr;
  9178. ast_node(body, BlockStmt, ss->body);
  9179. gb_local_persist i32 weird_count = 0;
  9180. for_array(i, body->stmts) {
  9181. Ast *clause = body->stmts[i];
  9182. ast_node(cc, CaseClause, clause);
  9183. if (cc->list.count == 0) {
  9184. default_ = clause;
  9185. continue;
  9186. }
  9187. irBlock *body = ir_new_block(proc, clause, "typeswitch.body");
  9188. irBlock *next = nullptr;
  9189. Type *case_type = nullptr;
  9190. for_array(type_index, cc->list) {
  9191. next = ir_new_block(proc, nullptr, "typeswitch.next");
  9192. case_type = type_of_expr(cc->list[type_index]);
  9193. irValue *cond = nullptr;
  9194. if (switch_kind == TypeSwitch_Union) {
  9195. Type *ut = base_type(type_deref(parent_type));
  9196. irValue *variant_tag = ir_const_union_tag(ut, case_type);
  9197. cond = ir_emit_comp(proc, Token_CmpEq, tag_index, variant_tag);
  9198. } else if (switch_kind == TypeSwitch_Any) {
  9199. irValue *any_typeid = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 1));
  9200. irValue *case_typeid = ir_typeid(proc->module, case_type);
  9201. cond = ir_emit_comp(proc, Token_CmpEq, any_typeid, case_typeid);
  9202. }
  9203. GB_ASSERT(cond != nullptr);
  9204. ir_emit_if(proc, cond, body, next);
  9205. ir_start_block(proc, next);
  9206. }
  9207. Entity *case_entity = implicit_entity_of_node(clause);
  9208. irValue *value = parent_value;
  9209. ir_start_block(proc, body);
  9210. // bool any_or_not_ptr = is_type_any(type_deref(parent_type)) || !is_parent_ptr;
  9211. if (cc->list.count == 1) {
  9212. irValue *data = nullptr;
  9213. if (switch_kind == TypeSwitch_Union) {
  9214. data = union_data;
  9215. } else if (switch_kind == TypeSwitch_Any) {
  9216. irValue *any_data = ir_emit_load(proc, ir_emit_struct_ep(proc, parent_ptr, 0));
  9217. data = any_data;
  9218. }
  9219. Type *ct = case_entity->type;
  9220. Type *ct_ptr = alloc_type_pointer(ct);
  9221. value = ir_emit_conv(proc, data, ct_ptr);
  9222. if (case_entity->flags & EntityFlag_Value) {
  9223. // by value
  9224. value = ir_emit_load(proc, value);
  9225. } else {
  9226. // by reference
  9227. }
  9228. }
  9229. ir_store_type_case_implicit(proc, clause, value);
  9230. ir_type_case_body(proc, ss->label, clause, body, done);
  9231. ir_start_block(proc, next);
  9232. }
  9233. if (default_ != nullptr) {
  9234. ir_store_type_case_implicit(proc, default_, parent_value);
  9235. ir_type_case_body(proc, ss->label, default_, proc->curr_block, done);
  9236. } else {
  9237. ir_emit_jump(proc, done);
  9238. }
  9239. ir_start_block(proc, done);
  9240. case_end;
  9241. case_ast_node(bs, BranchStmt, node);
  9242. irBlock *block = nullptr;
  9243. if (bs->label != nullptr) {
  9244. irBranchBlocks bb = ir_lookup_branch_blocks(proc, bs->label);
  9245. switch (bs->token.kind) {
  9246. case Token_break: block = bb.break_; break;
  9247. case Token_continue: block = bb.continue_; break;
  9248. case Token_fallthrough:
  9249. GB_PANIC("fallthrough cannot have a label");
  9250. break;
  9251. }
  9252. } else {
  9253. for (irTargetList *t = proc->target_list; t != nullptr && block == nullptr; t = t->prev) {
  9254. if (t->is_block) {
  9255. continue;
  9256. }
  9257. switch (bs->token.kind) {
  9258. case Token_break: block = t->break_; break;
  9259. case Token_continue: block = t->continue_; break;
  9260. case Token_fallthrough: block = t->fallthrough_; break;
  9261. }
  9262. }
  9263. }
  9264. if (block != nullptr) {
  9265. ir_emit_defer_stmts(proc, irDeferExit_Branch, block);
  9266. }
  9267. switch (bs->token.kind) {
  9268. case Token_break: ir_emit_comment(proc, str_lit("break")); break;
  9269. case Token_continue: ir_emit_comment(proc, str_lit("continue")); break;
  9270. case Token_fallthrough: ir_emit_comment(proc, str_lit("fallthrough")); break;
  9271. }
  9272. ir_emit_jump(proc, block);
  9273. ir_emit_unreachable(proc);
  9274. case_end;
  9275. }
  9276. }
  9277. ////////////////////////////////////////////////////////////////
  9278. //
  9279. // @Procedure
  9280. //
  9281. ////////////////////////////////////////////////////////////////
  9282. void ir_number_proc_registers(irProcedure *proc) {
  9283. // i32 reg_index = proc->parameter_count;
  9284. i32 reg_index = 0;
  9285. for_array(i, proc->blocks) {
  9286. irBlock *b = proc->blocks[i];
  9287. b->index = cast(i32)i;
  9288. for_array(j, b->instrs) {
  9289. irValue *value = b->instrs[j];
  9290. GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name));
  9291. irInstr *instr = &value->Instr;
  9292. if (ir_instr_type(instr) == nullptr) { // NOTE(bill): Ignore non-returning instructions
  9293. value->index = -1;
  9294. continue;
  9295. }
  9296. value->index = reg_index;
  9297. value->index_set = true;
  9298. reg_index++;
  9299. }
  9300. }
  9301. }
  9302. void ir_begin_procedure_body(irProcedure *proc) {
  9303. gbAllocator a = ir_allocator();
  9304. array_add(&proc->module->procs, proc);
  9305. array_init(&proc->blocks, heap_allocator());
  9306. array_init(&proc->defer_stmts, heap_allocator());
  9307. array_init(&proc->children, heap_allocator());
  9308. array_init(&proc->branch_blocks, heap_allocator());
  9309. array_init(&proc->context_stack, heap_allocator());
  9310. DeclInfo *decl = decl_info_of_entity(proc->entity);
  9311. if (decl != nullptr) {
  9312. for_array(i, decl->labels) {
  9313. BlockLabel bl = decl->labels[i];
  9314. irBranchBlocks bb = {bl.label, nullptr, nullptr};
  9315. array_add(&proc->branch_blocks, bb);
  9316. }
  9317. }
  9318. // NOTE(lachsinc): This is somewhat of a fallback/catch-all; We use the procedure's identifer as a debug location..
  9319. // Additional debug locations should be pushed for the procedures statements/expressions themselves.
  9320. if (proc->module->generate_debug_info && proc->entity && proc->entity->identifier) { // TODO(lachsinc): Better way to determine if these procs are main/runtime_startup.
  9321. // TODO(lachsinc): Passing the file for the scope may not be correct for nested procedures? This should probably be
  9322. // handled all inside push_debug_location, with just the Ast * we can pull out everything we need to construct scope/file debug info etc.
  9323. ir_add_debug_info_proc(proc);
  9324. ir_push_debug_location(proc->module, proc->entity->identifier, proc->debug_scope);
  9325. GB_ASSERT_NOT_NULL(proc->debug_scope);
  9326. } else {
  9327. ir_push_debug_location(proc->module, nullptr, nullptr);
  9328. }
  9329. proc->decl_block = ir_new_block(proc, proc->type_expr, "decls");
  9330. ir_start_block(proc, proc->decl_block);
  9331. proc->entry_block = ir_new_block(proc, proc->type_expr, "entry");
  9332. ir_start_block(proc, proc->entry_block);
  9333. i32 parameter_index = 0;
  9334. if (proc->type->Proc.return_by_pointer) {
  9335. // NOTE(bill): this must be the first parameter stored
  9336. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(proc->type->Proc.results));
  9337. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  9338. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  9339. irValue *param = ir_value_param(proc, e, ptr_type, -1);
  9340. param->Param.kind = irParamPass_Pointer;
  9341. ir_module_add_value(proc->module, e, param);
  9342. proc->return_ptr = param;
  9343. }
  9344. GB_ASSERT(proc->type != nullptr);
  9345. if (proc->type->Proc.params != nullptr) {
  9346. TypeTuple *params = &proc->type->Proc.params->Tuple;
  9347. if (proc->type_expr != nullptr) {
  9348. ast_node(pt, ProcType, proc->type_expr);
  9349. isize param_index = 0;
  9350. isize q_index = 0;
  9351. for_array(i, params->variables) {
  9352. ast_node(fl, FieldList, pt->params);
  9353. GB_ASSERT(fl->list.count > 0);
  9354. GB_ASSERT(fl->list[0]->kind == Ast_Field);
  9355. if (q_index == fl->list[param_index]->Field.names.count) {
  9356. q_index = 0;
  9357. param_index++;
  9358. }
  9359. ast_node(field, Field, fl->list[param_index]);
  9360. Ast *name = field->names[q_index++];
  9361. Entity *e = params->variables[i];
  9362. if (e->kind != Entity_Variable) {
  9363. parameter_index += 1;
  9364. continue;
  9365. }
  9366. Type *abi_type = proc->type->Proc.abi_compat_params[i];
  9367. if (e->token.string != "") {
  9368. ir_add_param(proc, e, name, abi_type, parameter_index);
  9369. }
  9370. if (is_type_tuple(abi_type)) {
  9371. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  9372. } else {
  9373. parameter_index += 1;
  9374. }
  9375. }
  9376. } else {
  9377. auto abi_types = proc->type->Proc.abi_compat_params;
  9378. for_array(i, params->variables) {
  9379. Entity *e = params->variables[i];
  9380. if (e->kind != Entity_Variable) {
  9381. parameter_index += 1;
  9382. continue;
  9383. }
  9384. Type *abi_type = e->type;
  9385. if (abi_types.count > 0) {
  9386. abi_type = abi_types[i];
  9387. }
  9388. if (e->token.string != "") {
  9389. ir_add_param(proc, e, nullptr, abi_type, parameter_index);
  9390. }
  9391. if (is_type_tuple(abi_type)) {
  9392. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  9393. } else {
  9394. parameter_index += 1;
  9395. }
  9396. }
  9397. }
  9398. }
  9399. if (proc->type->Proc.has_named_results) {
  9400. GB_ASSERT(proc->type->Proc.result_count > 0);
  9401. TypeTuple *results = &proc->type->Proc.results->Tuple;
  9402. for_array(i, results->variables) {
  9403. Entity *e = results->variables[i];
  9404. if (e->kind != Entity_Variable) {
  9405. continue;
  9406. }
  9407. if (e->token.string != "") {
  9408. GB_ASSERT(!is_blank_ident(e->token));
  9409. irValue *res = ir_add_local(proc, e, e->identifier, true);
  9410. irValue *c = nullptr;
  9411. switch (e->Variable.param_value.kind) {
  9412. case ParameterValue_Constant:
  9413. c = ir_value_constant(e->type, e->Variable.param_value.value);
  9414. break;
  9415. case ParameterValue_Nil:
  9416. c = ir_value_nil(e->type);
  9417. break;
  9418. case ParameterValue_Location:
  9419. GB_PANIC("ParameterValue_Location");
  9420. break;
  9421. }
  9422. if (c != nullptr) {
  9423. ir_emit_store(proc, res, c);
  9424. }
  9425. }
  9426. }
  9427. }
  9428. if (proc->type->Proc.calling_convention == ProcCC_Odin) {
  9429. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  9430. e->flags |= EntityFlag_NoAlias;
  9431. irValue *param = ir_value_param(proc, e, e->type, -1);
  9432. ir_module_add_value(proc->module, e, param);
  9433. irContextData ctx = {param, proc->scope_index};
  9434. array_add(&proc->context_stack, ctx);
  9435. }
  9436. proc->parameter_count = parameter_index;
  9437. }
  9438. bool ir_remove_dead_instr(irProcedure *proc) {
  9439. isize elimination_count = 0;
  9440. retry:
  9441. #if 1
  9442. for_array(i, proc->blocks) {
  9443. irBlock *b = proc->blocks[i];
  9444. b->index = cast(i32)i;
  9445. for (isize j = 0; j < b->instrs.count; /**/) {
  9446. irValue *value = b->instrs[j];
  9447. GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name));
  9448. irInstr *instr = &value->Instr;
  9449. if (value->uses == 0) {
  9450. switch (instr->kind) {
  9451. case irInstr_Load:
  9452. instr->Load.address->uses -= 1;
  9453. array_ordered_remove(&b->instrs, j);
  9454. elimination_count += 1;
  9455. continue;
  9456. case irInstr_Local:
  9457. array_ordered_remove(&b->instrs, j);
  9458. elimination_count += 1;
  9459. continue;
  9460. case irInstr_AtomicLoad:
  9461. instr->AtomicLoad.address->uses -= 1;
  9462. array_ordered_remove(&b->instrs, j);
  9463. elimination_count += 1;
  9464. continue;
  9465. case irInstr_PtrOffset:
  9466. instr->PtrOffset.address->uses -= 1;
  9467. instr->PtrOffset.offset->uses -= 1;
  9468. array_ordered_remove(&b->instrs, j);
  9469. elimination_count += 1;
  9470. continue;
  9471. case irInstr_ArrayElementPtr:
  9472. instr->ArrayElementPtr.address->uses -= 1;
  9473. instr->ArrayElementPtr.elem_index->uses -= 1;
  9474. array_ordered_remove(&b->instrs, j);
  9475. elimination_count += 1;
  9476. continue;
  9477. case irInstr_StructElementPtr:
  9478. instr->StructElementPtr.address->uses -= 1;
  9479. array_ordered_remove(&b->instrs, j);
  9480. elimination_count += 1;
  9481. continue;
  9482. case irInstr_StructExtractValue:
  9483. instr->StructExtractValue.address->uses -= 1;
  9484. array_ordered_remove(&b->instrs, j);
  9485. elimination_count += 1;
  9486. continue;
  9487. case irInstr_UnionTagPtr:
  9488. instr->UnionTagPtr.address->uses -= 1;
  9489. array_ordered_remove(&b->instrs, j);
  9490. elimination_count += 1;
  9491. continue;
  9492. case irInstr_UnionTagValue:
  9493. instr->UnionTagValue.address->uses -= 1;
  9494. array_ordered_remove(&b->instrs, j);
  9495. elimination_count += 1;
  9496. continue;
  9497. // case irInstr_Conv:
  9498. // // instr->Conv.value->uses -= 1;
  9499. // array_ordered_remove(&b->instrs, j);
  9500. // elimination_count += 1;
  9501. // continue;
  9502. // case irInstr_UnaryOp:
  9503. // // instr->UnaryOp.expr->uses -= 1;
  9504. // array_ordered_remove(&b->instrs, j);
  9505. // elimination_count += 1;
  9506. // continue;
  9507. // case irInstr_BinaryOp:
  9508. // // instr->BinaryOp.left->uses -= 1;
  9509. // // instr->BinaryOp.right->uses -= 1;
  9510. // array_ordered_remove(&b->instrs, j);
  9511. // elimination_count += 1;
  9512. // continue;
  9513. }
  9514. }
  9515. j += 1;
  9516. }
  9517. }
  9518. #endif
  9519. if (elimination_count > 0) {
  9520. // gb_printf_err("Retry ir_remove_dead_instr, count: %td; %.*s\n", elimination_count, LIT(proc->name));
  9521. elimination_count = 0;
  9522. goto retry;
  9523. }
  9524. return elimination_count > 0;
  9525. }
  9526. void ir_end_procedure_body(irProcedure *proc) {
  9527. if (proc->type->Proc.result_count == 0) {
  9528. ir_emit_return(proc, nullptr);
  9529. }
  9530. if (proc->curr_block->instrs.count == 0) {
  9531. ir_emit_unreachable(proc);
  9532. }
  9533. GB_ASSERT(proc->scope_index == 0);
  9534. proc->curr_block = proc->decl_block;
  9535. ir_emit_jump(proc, proc->entry_block);
  9536. proc->curr_block = nullptr;
  9537. ir_remove_dead_instr(proc);
  9538. ir_number_proc_registers(proc);
  9539. ir_pop_debug_location(proc->module);
  9540. }
  9541. void ir_insert_code_before_proc(irProcedure* proc, irProcedure *parent) {
  9542. // if (parent == nullptr) {
  9543. // if (proc->name == "main") {
  9544. // ir_emit_startup_runtime(proc);
  9545. // }
  9546. // }
  9547. }
  9548. void ir_build_proc(irValue *value, irProcedure *parent) {
  9549. irProcedure *proc = &value->Proc;
  9550. set_procedure_abi_types(heap_allocator(), proc->type);
  9551. proc->parent = parent;
  9552. if (proc->body != nullptr) {
  9553. u64 prev_state_flags = proc->module->state_flags;
  9554. if (proc->tags != 0) {
  9555. u64 in = proc->tags;
  9556. u64 out = proc->module->state_flags;
  9557. if (in & ProcTag_bounds_check) {
  9558. out |= StateFlag_bounds_check;
  9559. out &= ~StateFlag_no_bounds_check;
  9560. } else if (in & ProcTag_no_bounds_check) {
  9561. out |= StateFlag_no_bounds_check;
  9562. out &= ~StateFlag_bounds_check;
  9563. }
  9564. proc->module->state_flags = out;
  9565. }
  9566. ir_begin_procedure_body(proc);
  9567. ir_insert_code_before_proc(proc, parent);
  9568. ir_build_stmt(proc, proc->body);
  9569. ir_end_procedure_body(proc);
  9570. proc->module->state_flags = prev_state_flags;
  9571. }
  9572. // NOTE(lachsinc): For now we pop the debug location inside ir_end_procedure_body().
  9573. // This may result in debug info being missing for below.
  9574. if (proc->type->Proc.has_proc_default_values) {
  9575. auto *p = &proc->type->Proc;
  9576. if (p->params != nullptr) for_array(i, p->params->Tuple.variables) {
  9577. Entity *f = p->params->Tuple.variables[i];
  9578. if (f->kind == Entity_Variable) {
  9579. ParameterValue pv = f->Variable.param_value;
  9580. if (pv.kind == ParameterValue_Constant && pv.value.kind == ExactValue_Procedure) {
  9581. Ast *expr = f->Variable.param_value.value.value_procedure;
  9582. GB_ASSERT(expr != nullptr);
  9583. if (expr->kind == Ast_ProcLit) {
  9584. ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  9585. }
  9586. }
  9587. }
  9588. }
  9589. if (p->results != nullptr) for_array(i, p->results->Tuple.variables) {
  9590. Entity *f = p->results->Tuple.variables[i];
  9591. if (f->kind == Entity_Variable) {
  9592. ParameterValue pv = f->Variable.param_value;
  9593. if (pv.kind == ParameterValue_Constant && pv.value.kind == ExactValue_Procedure) {
  9594. Ast *expr = f->Variable.param_value.value.value_procedure;
  9595. GB_ASSERT(expr != nullptr);
  9596. if (expr->kind == Ast_ProcLit) {
  9597. ir_gen_anonymous_proc_lit(proc->module, proc->name, expr, proc);
  9598. }
  9599. }
  9600. }
  9601. }
  9602. }
  9603. }
  9604. ////////////////////////////////////////////////////////////////
  9605. //
  9606. // @Module
  9607. //
  9608. ////////////////////////////////////////////////////////////////
  9609. void ir_module_add_value(irModule *m, Entity *e, irValue *v) {
  9610. map_set(&m->values, hash_entity(e), v);
  9611. // TODO(lachsinc): This may not be the most sensible place to do this!
  9612. // it may be more sensible to look for more specific locations that call ir_value_global and assign it a value? maybe?
  9613. // ir_value_global itself doesn't have access to module though.
  9614. if (v->kind == irValue_Global && v->Global.value != nullptr && e->state == EntityState_Resolved) {
  9615. ir_add_debug_info_global(m, v);
  9616. }
  9617. }
  9618. void ir_init_module(irModule *m, Checker *c) {
  9619. // TODO(bill): Determine a decent size for the arena
  9620. isize token_count = c->parser->total_token_count;
  9621. isize arena_size = 4 * token_count * gb_size_of(irValue);
  9622. gb_arena_init_from_allocator(&m->tmp_arena, heap_allocator(), arena_size);
  9623. ir_allocator() = ir_allocator();
  9624. m->tmp_allocator = gb_arena_allocator(&m->tmp_arena);
  9625. m->info = &c->info;
  9626. m->generate_debug_info = false;
  9627. if (build_context.ODIN_DEBUG) {
  9628. m->generate_debug_info = build_context.ODIN_OS == "windows" && build_context.word_size == 8;
  9629. }
  9630. map_init(&m->values, heap_allocator());
  9631. string_map_init(&m->members, heap_allocator());
  9632. map_init(&m->debug_info, heap_allocator());
  9633. map_init(&m->entity_names, heap_allocator());
  9634. map_init(&m->anonymous_proc_lits, heap_allocator());
  9635. array_init(&m->procs, heap_allocator());
  9636. array_init(&m->procs_to_generate, heap_allocator());
  9637. array_init(&m->foreign_library_paths, heap_allocator());
  9638. string_map_init(&m->const_strings, heap_allocator());
  9639. string_map_init(&m->const_string_byte_slices, heap_allocator());
  9640. map_init(&m->constant_value_to_global, heap_allocator());
  9641. // Default states
  9642. m->state_flags = 0;
  9643. m->state_flags |= StateFlag_bounds_check;
  9644. {
  9645. // Add type info data
  9646. {
  9647. isize max_type_info_count = ir_type_info_count(m->info);
  9648. String name = str_lit(IR_TYPE_INFO_DATA_NAME);
  9649. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name), alloc_type_array(t_type_info, max_type_info_count));
  9650. irValue *g = ir_value_global(e, nullptr);
  9651. g->Global.is_private = true;
  9652. ir_module_add_value(m, e, g);
  9653. string_map_set(&m->members, name, g);
  9654. ir_global_type_info_data = g;
  9655. }
  9656. // Type info member buffer
  9657. {
  9658. // NOTE(bill): Removes need for heap allocation by making it global memory
  9659. isize count = 0;
  9660. for_array(entry_index, m->info->type_info_types) {
  9661. Type *t = m->info->type_info_types[entry_index];
  9662. isize index = ir_type_info_index(m->info, t, false);
  9663. if (index < 0) {
  9664. continue;
  9665. }
  9666. switch (t->kind) {
  9667. case Type_Union:
  9668. count += t->Union.variants.count;
  9669. break;
  9670. case Type_Struct:
  9671. count += t->Struct.fields.count;
  9672. break;
  9673. case Type_Tuple:
  9674. count += t->Tuple.variables.count;
  9675. break;
  9676. }
  9677. }
  9678. if (count > 0) {
  9679. {
  9680. String name = str_lit(IR_TYPE_INFO_TYPES_NAME);
  9681. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9682. alloc_type_array(t_type_info_ptr, count));
  9683. irValue *g = ir_value_global(e, nullptr);
  9684. ir_module_add_value(m, e, g);
  9685. string_map_set(&m->members, name, g);
  9686. ir_global_type_info_member_types = g;
  9687. }
  9688. {
  9689. String name = str_lit(IR_TYPE_INFO_NAMES_NAME);
  9690. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9691. alloc_type_array(t_string, count));
  9692. irValue *g = ir_value_global(e, nullptr);
  9693. ir_module_add_value(m, e, g);
  9694. string_map_set(&m->members, name, g);
  9695. ir_global_type_info_member_names = g;
  9696. }
  9697. {
  9698. String name = str_lit(IR_TYPE_INFO_OFFSETS_NAME);
  9699. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9700. alloc_type_array(t_uintptr, count));
  9701. irValue *g = ir_value_global(e, nullptr);
  9702. ir_module_add_value(m, e, g);
  9703. string_map_set(&m->members, name, g);
  9704. ir_global_type_info_member_offsets = g;
  9705. }
  9706. {
  9707. String name = str_lit(IR_TYPE_INFO_USINGS_NAME);
  9708. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9709. alloc_type_array(t_bool, count));
  9710. irValue *g = ir_value_global(e, nullptr);
  9711. ir_module_add_value(m, e, g);
  9712. string_map_set(&m->members, name, g);
  9713. ir_global_type_info_member_usings = g;
  9714. }
  9715. {
  9716. String name = str_lit(IR_TYPE_INFO_TAGS_NAME);
  9717. Entity *e = alloc_entity_variable(nullptr, make_token_ident(name),
  9718. alloc_type_array(t_string, count));
  9719. irValue *g = ir_value_global(e, nullptr);
  9720. ir_module_add_value(m, e, g);
  9721. string_map_set(&m->members, name, g);
  9722. ir_global_type_info_member_tags = g;
  9723. }
  9724. }
  9725. }
  9726. }
  9727. {
  9728. irDebugInfo *di = ir_alloc_debug_info(irDebugInfo_CompileUnit);
  9729. GB_ASSERT(m->info->files.entries.count > 0);
  9730. AstFile *file = m->info->files.entries[0].value;
  9731. di->CompileUnit.file = file; // Zeroth is the init file
  9732. di->CompileUnit.producer = str_lit("odin");
  9733. map_set(&m->debug_info, hash_pointer(m), di);
  9734. m->debug_compile_unit = di;
  9735. irDebugInfo *enums_di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  9736. array_init(&enums_di->DebugInfoArray.elements, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  9737. map_set(&m->debug_info, hash_pointer(enums_di), enums_di);
  9738. m->debug_compile_unit->CompileUnit.enums = enums_di;
  9739. irDebugInfo *globals_di = ir_alloc_debug_info(irDebugInfo_DebugInfoArray);
  9740. array_init(&globals_di->DebugInfoArray.elements, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  9741. map_set(&m->debug_info, hash_pointer(globals_di), globals_di);
  9742. m->debug_compile_unit->CompileUnit.globals = globals_di;
  9743. array_init(&m->debug_location_stack, heap_allocator()); // TODO(lachsinc): ir_allocator() ??
  9744. }
  9745. {
  9746. for_array(i, m->info->files.entries) {
  9747. AstFile *file = m->info->files.entries[i].value;
  9748. ir_add_debug_info_file(m, file);
  9749. }
  9750. }
  9751. }
  9752. void ir_destroy_module(irModule *m) {
  9753. map_destroy(&m->values);
  9754. string_map_destroy(&m->members);
  9755. map_destroy(&m->entity_names);
  9756. map_destroy(&m->anonymous_proc_lits);
  9757. map_destroy(&m->debug_info);
  9758. string_map_destroy(&m->const_strings);
  9759. string_map_destroy(&m->const_string_byte_slices);
  9760. map_destroy(&m->constant_value_to_global);
  9761. array_free(&m->procs);
  9762. array_free(&m->procs_to_generate);
  9763. array_free(&m->foreign_library_paths);
  9764. array_free(&m->debug_location_stack);
  9765. gb_arena_free(&m->tmp_arena);
  9766. }
  9767. ////////////////////////////////////////////////////////////////
  9768. //
  9769. // @Code Generation
  9770. //
  9771. ////////////////////////////////////////////////////////////////
  9772. bool ir_gen_init(irGen *s, Checker *c) {
  9773. if (global_error_collector.count != 0) {
  9774. return false;
  9775. }
  9776. isize tc = c->parser->total_token_count;
  9777. if (tc < 2) {
  9778. return false;
  9779. }
  9780. arena_init(&global_ir_arena, heap_allocator());
  9781. ir_init_module(&s->module, c);
  9782. // s->module.generate_debug_info = false;
  9783. String init_fullpath = c->parser->init_fullpath;
  9784. if (build_context.out_filepath.len == 0) {
  9785. s->output_name = remove_directory_from_path(init_fullpath);
  9786. s->output_name = remove_extension_from_path(s->output_name);
  9787. s->output_name = string_trim_whitespace(s->output_name);
  9788. if (s->output_name.len == 0) {
  9789. s->output_name = c->info.init_scope->pkg->name;
  9790. }
  9791. s->output_base = s->output_name;
  9792. } else {
  9793. s->output_name = build_context.out_filepath;
  9794. s->output_name = string_trim_whitespace(s->output_name);
  9795. if (s->output_name.len == 0) {
  9796. s->output_name = c->info.init_scope->pkg->name;
  9797. }
  9798. isize pos = string_extension_position(s->output_name);
  9799. if (pos < 0) {
  9800. s->output_base = s->output_name;
  9801. } else {
  9802. s->output_base = substring(s->output_name, 0, pos);
  9803. }
  9804. }
  9805. gbAllocator ha = heap_allocator();
  9806. s->output_base = path_to_full_path(ha, s->output_base);
  9807. gbString output_file_path = gb_string_make_length(ha, s->output_base.text, s->output_base.len);
  9808. output_file_path = gb_string_appendc(output_file_path, ".ll");
  9809. defer (gb_string_free(output_file_path));
  9810. gbFileError err = gb_file_create(&s->output_file, output_file_path);
  9811. if (err != gbFileError_None) {
  9812. gb_printf_err("Failed to create file %s\n", output_file_path);
  9813. return false;
  9814. }
  9815. return true;
  9816. }
  9817. void ir_gen_destroy(irGen *s) {
  9818. ir_destroy_module(&s->module);
  9819. gb_file_close(&s->output_file);
  9820. }
  9821. //
  9822. // Type Info stuff
  9823. //
  9824. irValue *ir_get_type_info_ptr(irProcedure *proc, Type *type) {
  9825. i32 index = cast(i32)ir_type_info_index(proc->module->info, type);
  9826. // gb_printf_err("%d %s\n", index, type_to_string(type));
  9827. irValue *ptr = ir_emit_array_epi(proc, ir_global_type_info_data, index);
  9828. return ir_emit_bitcast(proc, ptr, t_type_info_ptr);
  9829. }
  9830. irValue *ir_type_info_member_types_offset(irProcedure *proc, isize count) {
  9831. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_types, ir_global_type_info_member_types_index);
  9832. ir_global_type_info_member_types_index += cast(i32)count;
  9833. return offset;
  9834. }
  9835. irValue *ir_type_info_member_names_offset(irProcedure *proc, isize count) {
  9836. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_names, ir_global_type_info_member_names_index);
  9837. ir_global_type_info_member_names_index += cast(i32)count;
  9838. return offset;
  9839. }
  9840. irValue *ir_type_info_member_offsets_offset(irProcedure *proc, isize count) {
  9841. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_offsets, ir_global_type_info_member_offsets_index);
  9842. ir_global_type_info_member_offsets_index += cast(i32)count;
  9843. return offset;
  9844. }
  9845. irValue *ir_type_info_member_usings_offset(irProcedure *proc, isize count) {
  9846. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_usings, ir_global_type_info_member_usings_index);
  9847. ir_global_type_info_member_usings_index += cast(i32)count;
  9848. return offset;
  9849. }
  9850. irValue *ir_type_info_member_tags_offset(irProcedure *proc, isize count) {
  9851. irValue *offset = ir_emit_array_epi(proc, ir_global_type_info_member_tags, ir_global_type_info_member_tags_index);
  9852. ir_global_type_info_member_tags_index += cast(i32)count;
  9853. return offset;
  9854. }
  9855. void ir_setup_type_info_data(irProcedure *proc) { // NOTE(bill): Setup type_info data
  9856. irModule *m = proc->module;
  9857. gbAllocator a = ir_allocator();
  9858. CheckerInfo *info = m->info;
  9859. if (true) {
  9860. irValue *global_type_table = ir_find_global_variable(proc, str_lit("type_table"));
  9861. Type *type = base_type(type_deref(ir_type(ir_global_type_info_data)));
  9862. GB_ASSERT(is_type_array(type));
  9863. irValue *len = ir_const_int(type->Array.count);
  9864. ir_fill_slice(proc, global_type_table,
  9865. ir_emit_array_epi(proc, ir_global_type_info_data, 0),
  9866. len);
  9867. }
  9868. // Useful types
  9869. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  9870. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  9871. i32 type_info_member_types_index = 0;
  9872. i32 type_info_member_names_index = 0;
  9873. i32 type_info_member_offsets_index = 0;
  9874. for_array(type_info_type_index, info->type_info_types) {
  9875. Type *t = info->type_info_types[type_info_type_index];
  9876. t = default_type(t);
  9877. if (t == t_invalid) {
  9878. continue;
  9879. }
  9880. isize entry_index = ir_type_info_index(info, t, false);
  9881. if (entry_index <= 0) {
  9882. continue;
  9883. }
  9884. irValue *tag = nullptr;
  9885. irValue *ti_ptr = ir_emit_array_epi(proc, ir_global_type_info_data, cast(i32)entry_index);
  9886. irValue *variant_ptr = ir_emit_struct_ep(proc, ti_ptr, 3);
  9887. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 0), ir_const_int(type_size_of(t)));
  9888. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 1), ir_const_int(type_align_of(t)));
  9889. ir_emit_store(proc, ir_emit_struct_ep(proc, ti_ptr, 2), ir_typeid(proc->module, t));
  9890. switch (t->kind) {
  9891. case Type_Named: {
  9892. ir_emit_comment(proc, str_lit("Type_Info_Named"));
  9893. tag = ir_emit_conv(proc, variant_ptr, t_type_info_named_ptr);
  9894. // TODO(bill): Which is better? The mangled name or actual name?
  9895. irValue *name = ir_const_string(proc->module, t->Named.type_name->token.string);
  9896. irValue *gtip = ir_get_type_info_ptr(proc, t->Named.base);
  9897. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), name);
  9898. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), gtip);
  9899. break;
  9900. }
  9901. case Type_Basic:
  9902. ir_emit_comment(proc, str_lit("Type_Info_Basic"));
  9903. switch (t->Basic.kind) {
  9904. case Basic_bool:
  9905. case Basic_b8:
  9906. case Basic_b16:
  9907. case Basic_b32:
  9908. case Basic_b64:
  9909. tag = ir_emit_conv(proc, variant_ptr, t_type_info_boolean_ptr);
  9910. break;
  9911. case Basic_i8:
  9912. case Basic_u8:
  9913. case Basic_i16:
  9914. case Basic_u16:
  9915. case Basic_i32:
  9916. case Basic_u32:
  9917. case Basic_i64:
  9918. case Basic_u64:
  9919. case Basic_i128:
  9920. case Basic_u128:
  9921. case Basic_i16le:
  9922. case Basic_u16le:
  9923. case Basic_i32le:
  9924. case Basic_u32le:
  9925. case Basic_i64le:
  9926. case Basic_u64le:
  9927. case Basic_i128le:
  9928. case Basic_u128le:
  9929. case Basic_i16be:
  9930. case Basic_u16be:
  9931. case Basic_i32be:
  9932. case Basic_u32be:
  9933. case Basic_i64be:
  9934. case Basic_u64be:
  9935. case Basic_i128be:
  9936. case Basic_u128be:
  9937. case Basic_int:
  9938. case Basic_uint:
  9939. case Basic_uintptr: {
  9940. tag = ir_emit_conv(proc, variant_ptr, t_type_info_integer_ptr);
  9941. irValue *is_signed = ir_const_bool((t->Basic.flags & BasicFlag_Unsigned) == 0);
  9942. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), is_signed);
  9943. // NOTE(bill): This is matches the runtime layout
  9944. u8 endianness_value = 0;
  9945. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9946. endianness_value = 1;
  9947. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9948. endianness_value = 2;
  9949. }
  9950. irValue *endianness = ir_const_u8(endianness_value);
  9951. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), endianness);
  9952. break;
  9953. }
  9954. case Basic_rune:
  9955. tag = ir_emit_conv(proc, variant_ptr, t_type_info_rune_ptr);
  9956. break;
  9957. // case Basic_f16:
  9958. case Basic_f32:
  9959. case Basic_f64:
  9960. case Basic_f32le:
  9961. case Basic_f64le:
  9962. case Basic_f32be:
  9963. case Basic_f64be:
  9964. {
  9965. tag = ir_emit_conv(proc, variant_ptr, t_type_info_float_ptr);
  9966. // NOTE(bill): This is matches the runtime layout
  9967. u8 endianness_value = 0;
  9968. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9969. endianness_value = 1;
  9970. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9971. endianness_value = 2;
  9972. }
  9973. irValue *endianness = ir_const_u8(endianness_value);
  9974. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), endianness);
  9975. }
  9976. break;
  9977. // case Basic_complex32:
  9978. case Basic_complex64:
  9979. case Basic_complex128:
  9980. tag = ir_emit_conv(proc, variant_ptr, t_type_info_complex_ptr);
  9981. break;
  9982. case Basic_quaternion128:
  9983. case Basic_quaternion256:
  9984. tag = ir_emit_conv(proc, variant_ptr, t_type_info_quaternion_ptr);
  9985. break;
  9986. case Basic_rawptr:
  9987. tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
  9988. break;
  9989. case Basic_string:
  9990. tag = ir_emit_conv(proc, variant_ptr, t_type_info_string_ptr);
  9991. break;
  9992. case Basic_cstring:
  9993. tag = ir_emit_conv(proc, variant_ptr, t_type_info_string_ptr);
  9994. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), v_true); // is_cstring
  9995. break;
  9996. case Basic_any:
  9997. tag = ir_emit_conv(proc, variant_ptr, t_type_info_any_ptr);
  9998. break;
  9999. case Basic_typeid:
  10000. tag = ir_emit_conv(proc, variant_ptr, t_type_info_typeid_ptr);
  10001. break;
  10002. }
  10003. break;
  10004. case Type_Pointer: {
  10005. ir_emit_comment(proc, str_lit("Type_Info_Pointer"));
  10006. tag = ir_emit_conv(proc, variant_ptr, t_type_info_pointer_ptr);
  10007. irValue *gep = ir_get_type_info_ptr(proc, t->Pointer.elem);
  10008. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  10009. break;
  10010. }
  10011. case Type_Array: {
  10012. ir_emit_comment(proc, str_lit("Type_Info_Array"));
  10013. tag = ir_emit_conv(proc, variant_ptr, t_type_info_array_ptr);
  10014. irValue *gep = ir_get_type_info_ptr(proc, t->Array.elem);
  10015. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  10016. i64 ez = type_size_of(t->Array.elem);
  10017. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  10018. ir_emit_store(proc, elem_size, ir_const_int(ez));
  10019. irValue *count = ir_emit_struct_ep(proc, tag, 2);
  10020. ir_emit_store(proc, count, ir_const_int(t->Array.count));
  10021. break;
  10022. }
  10023. case Type_EnumeratedArray: {
  10024. ir_emit_comment(proc, str_lit("Type_Info_Enumerated_Array"));
  10025. tag = ir_emit_conv(proc, variant_ptr, t_type_info_enumerated_array_ptr);
  10026. irValue *elem = ir_get_type_info_ptr(proc, t->EnumeratedArray.elem);
  10027. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), elem);
  10028. irValue *index = ir_get_type_info_ptr(proc, t->EnumeratedArray.index);
  10029. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), index);
  10030. i64 ez = type_size_of(t->EnumeratedArray.elem);
  10031. irValue *elem_size = ir_emit_struct_ep(proc, tag, 2);
  10032. ir_emit_store(proc, elem_size, ir_const_int(ez));
  10033. irValue *count = ir_emit_struct_ep(proc, tag, 3);
  10034. ir_emit_store(proc, count, ir_const_int(t->EnumeratedArray.count));
  10035. irValue *min_value = ir_emit_struct_ep(proc, tag, 4);
  10036. irValue *max_value = ir_emit_struct_ep(proc, tag, 5);
  10037. irValue *min_v = ir_value_constant(t_i64, t->EnumeratedArray.min_value);
  10038. irValue *max_v = ir_value_constant(t_i64, t->EnumeratedArray.max_value);
  10039. ir_emit_store(proc, min_value, min_v);
  10040. ir_emit_store(proc, max_value, max_v);
  10041. break;
  10042. }
  10043. case Type_DynamicArray: {
  10044. ir_emit_comment(proc, str_lit("Type_Info_Dynamic_Array"));
  10045. tag = ir_emit_conv(proc, variant_ptr, t_type_info_dynamic_array_ptr);
  10046. irValue *gep = ir_get_type_info_ptr(proc, t->DynamicArray.elem);
  10047. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  10048. i64 ez = type_size_of(t->DynamicArray.elem);
  10049. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  10050. ir_emit_store(proc, elem_size, ir_const_int(ez));
  10051. break;
  10052. }
  10053. case Type_Slice: {
  10054. ir_emit_comment(proc, str_lit("Type_Info_Slice"));
  10055. tag = ir_emit_conv(proc, variant_ptr, t_type_info_slice_ptr);
  10056. irValue *gep = ir_get_type_info_ptr(proc, t->Slice.elem);
  10057. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), gep);
  10058. i64 ez = type_size_of(t->Slice.elem);
  10059. irValue *elem_size = ir_emit_struct_ep(proc, tag, 1);
  10060. ir_emit_store(proc, elem_size, ir_const_int(ez));
  10061. break;
  10062. }
  10063. case Type_Proc: {
  10064. ir_emit_comment(proc, str_lit("Type_Info_Proc"));
  10065. tag = ir_emit_conv(proc, variant_ptr, t_type_info_procedure_ptr);
  10066. irValue *params = ir_emit_struct_ep(proc, tag, 0);
  10067. irValue *results = ir_emit_struct_ep(proc, tag, 1);
  10068. irValue *variadic = ir_emit_struct_ep(proc, tag, 2);
  10069. irValue *convention = ir_emit_struct_ep(proc, tag, 3);
  10070. if (t->Proc.params != nullptr) {
  10071. ir_emit_store(proc, params, ir_get_type_info_ptr(proc, t->Proc.params));
  10072. }
  10073. if (t->Proc.results != nullptr) {
  10074. ir_emit_store(proc, results, ir_get_type_info_ptr(proc, t->Proc.results));
  10075. }
  10076. ir_emit_store(proc, variadic, ir_const_bool(t->Proc.variadic));
  10077. ir_emit_store(proc, convention, ir_const_u8(t->Proc.calling_convention));
  10078. // TODO(bill): TypeInfo for procedures
  10079. break;
  10080. }
  10081. case Type_Tuple: {
  10082. ir_emit_comment(proc, str_lit("Type_Info_Tuple"));
  10083. tag = ir_emit_conv(proc, variant_ptr, t_type_info_tuple_ptr);
  10084. irValue *memory_types = ir_type_info_member_types_offset(proc, t->Tuple.variables.count);
  10085. irValue *memory_names = ir_type_info_member_names_offset(proc, t->Tuple.variables.count);
  10086. for_array(i, t->Tuple.variables) {
  10087. // NOTE(bill): offset is not used for tuples
  10088. Entity *f = t->Tuple.variables[i];
  10089. irValue *index = ir_const_int(i);
  10090. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  10091. ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
  10092. if (f->token.string.len > 0) {
  10093. irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
  10094. ir_emit_store(proc, name, ir_const_string(proc->module, f->token.string));
  10095. }
  10096. }
  10097. irValue *count = ir_const_int(t->Tuple.variables.count);
  10098. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, count);
  10099. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, count);
  10100. break;
  10101. }
  10102. case Type_Enum:
  10103. ir_emit_comment(proc, str_lit("Type_Info_Enum"));
  10104. tag = ir_emit_conv(proc, variant_ptr, t_type_info_enum_ptr);
  10105. {
  10106. GB_ASSERT(t->Enum.base_type != nullptr);
  10107. irValue *base = ir_type_info(proc, t->Enum.base_type);
  10108. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), base);
  10109. if (t->Enum.fields.count > 0) {
  10110. auto fields = t->Enum.fields;
  10111. irValue *name_array = ir_generate_array(m, t_string, fields.count,
  10112. str_lit("$enum_names"), cast(i64)entry_index);
  10113. irValue *value_array = ir_generate_array(m, t_type_info_enum_value, fields.count,
  10114. str_lit("$enum_values"), cast(i64)entry_index);
  10115. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10116. for_array(i, fields) {
  10117. irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
  10118. irValue *value_ep = ir_emit_array_epi(proc, value_array, cast(i32)i);
  10119. ExactValue value = fields[i]->Constant.value;
  10120. irValue *v = ir_value_constant(t_i64, value);
  10121. ir_emit_store(proc, value_ep, v);
  10122. ir_emit_store(proc, name_ep, ir_const_string(proc->module, fields[i]->token.string));
  10123. }
  10124. irValue *v_count = ir_const_int(fields.count);
  10125. irValue *names = ir_emit_struct_ep(proc, tag, 1);
  10126. irValue *name_array_elem = ir_array_elem(proc, name_array);
  10127. ir_fill_slice(proc, names, name_array_elem, v_count);
  10128. irValue *values = ir_emit_struct_ep(proc, tag, 2);
  10129. irValue *value_array_elem = ir_array_elem(proc, value_array);
  10130. ir_fill_slice(proc, values, value_array_elem, v_count);
  10131. }
  10132. }
  10133. break;
  10134. case Type_Union: {
  10135. ir_emit_comment(proc, str_lit("Type_Info_Union"));
  10136. tag = ir_emit_conv(proc, variant_ptr, t_type_info_union_ptr);
  10137. {
  10138. irValue *variant_types = ir_emit_struct_ep(proc, tag, 0);
  10139. irValue *tag_offset_ptr = ir_emit_struct_ep(proc, tag, 1);
  10140. irValue *tag_type_ptr = ir_emit_struct_ep(proc, tag, 2);
  10141. irValue *custom_align_ptr = ir_emit_struct_ep(proc, tag, 3);
  10142. irValue *no_nil_ptr = ir_emit_struct_ep(proc, tag, 4);
  10143. irValue *maybe_ptr = ir_emit_struct_ep(proc, tag, 5);
  10144. isize variant_count = gb_max(0, t->Union.variants.count);
  10145. irValue *memory_types = ir_type_info_member_types_offset(proc, variant_count);
  10146. // NOTE(bill): Zeroth is nil so ignore it
  10147. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10148. Type *vt = t->Union.variants[variant_index];
  10149. irValue *tip = ir_get_type_info_ptr(proc, vt);
  10150. irValue *index = ir_const_int(variant_index);
  10151. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  10152. ir_emit_store(proc, type_info, ir_type_info(proc, vt));
  10153. }
  10154. irValue *count = ir_const_int(variant_count);
  10155. ir_fill_slice(proc, variant_types, memory_types, count);
  10156. i64 tag_size = union_tag_size(t);
  10157. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10158. if (tag_size > 0) {
  10159. ir_emit_store(proc, tag_offset_ptr, ir_const_uintptr(tag_offset));
  10160. ir_emit_store(proc, tag_type_ptr, ir_type_info(proc, union_tag_type(t)));
  10161. }
  10162. irValue *is_custom_align = ir_const_bool(t->Union.custom_align != 0);
  10163. ir_emit_store(proc, custom_align_ptr, is_custom_align);
  10164. ir_emit_store(proc, no_nil_ptr, ir_const_bool(t->Union.no_nil));
  10165. ir_emit_store(proc, maybe_ptr, ir_const_bool(t->Union.maybe));
  10166. }
  10167. break;
  10168. }
  10169. case Type_Struct: {
  10170. ir_emit_comment(proc, str_lit("Type_Info_Struct"));
  10171. tag = ir_emit_conv(proc, variant_ptr, t_type_info_struct_ptr);
  10172. {
  10173. irValue *is_packed = ir_const_bool(t->Struct.is_packed);
  10174. irValue *is_raw_union = ir_const_bool(t->Struct.is_raw_union);
  10175. irValue *is_custom_align = ir_const_bool(t->Struct.custom_align != 0);
  10176. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 5), is_packed);
  10177. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 6), is_raw_union);
  10178. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 7), is_custom_align);
  10179. if (t->Struct.soa_kind != StructSoa_None) {
  10180. irValue *kind = ir_emit_struct_ep(proc, tag, 8);
  10181. Type *kind_type = type_deref(ir_type(kind));
  10182. irValue *soa_kind = ir_value_constant(kind_type, exact_value_i64(t->Struct.soa_kind));
  10183. irValue *soa_type = ir_type_info(proc, t->Struct.soa_elem);
  10184. irValue *soa_len = ir_const_int(t->Struct.soa_count);
  10185. ir_emit_store(proc, kind, soa_kind);
  10186. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 9), soa_type);
  10187. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 10), soa_len);
  10188. }
  10189. }
  10190. isize count = t->Struct.fields.count;
  10191. if (count > 0) {
  10192. irValue *memory_types = ir_type_info_member_types_offset (proc, count);
  10193. irValue *memory_names = ir_type_info_member_names_offset (proc, count);
  10194. irValue *memory_offsets = ir_type_info_member_offsets_offset(proc, count);
  10195. irValue *memory_usings = ir_type_info_member_usings_offset (proc, count);
  10196. irValue *memory_tags = ir_type_info_member_tags_offset (proc, count);
  10197. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10198. for (isize source_index = 0; source_index < count; source_index++) {
  10199. // TODO(bill): Order fields in source order not layout order
  10200. Entity *f = t->Struct.fields[source_index];
  10201. irValue *tip = ir_get_type_info_ptr(proc, f->type);
  10202. i64 foffset = 0;
  10203. if (!t->Struct.is_raw_union) {
  10204. foffset = t->Struct.offsets[f->Variable.field_index];
  10205. }
  10206. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10207. irValue *index = ir_const_int(source_index);
  10208. irValue *type_info = ir_emit_ptr_offset(proc, memory_types, index);
  10209. irValue *offset = ir_emit_ptr_offset(proc, memory_offsets, index);
  10210. irValue *is_using = ir_emit_ptr_offset(proc, memory_usings, index);
  10211. ir_emit_store(proc, type_info, ir_type_info(proc, f->type));
  10212. if (f->token.string.len > 0) {
  10213. irValue *name = ir_emit_ptr_offset(proc, memory_names, index);
  10214. ir_emit_store(proc, name, ir_const_string(proc->module, f->token.string));
  10215. }
  10216. ir_emit_store(proc, offset, ir_const_uintptr(foffset));
  10217. ir_emit_store(proc, is_using, ir_const_bool((f->flags&EntityFlag_Using) != 0));
  10218. if (t->Struct.tags.count > 0) {
  10219. String tag_string = t->Struct.tags[source_index];
  10220. if (tag_string.len > 0) {
  10221. irValue *tag_ptr = ir_emit_ptr_offset(proc, memory_tags, index);
  10222. ir_emit_store(proc, tag_ptr, ir_const_string(proc->module, tag_string));
  10223. }
  10224. }
  10225. }
  10226. irValue *cv = ir_const_int(count);
  10227. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 0), memory_types, cv);
  10228. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 1), memory_names, cv);
  10229. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 2), memory_offsets, cv);
  10230. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 3), memory_usings, cv);
  10231. ir_fill_slice(proc, ir_emit_struct_ep(proc, tag, 4), memory_tags, cv);
  10232. }
  10233. break;
  10234. }
  10235. case Type_Map: {
  10236. ir_emit_comment(proc, str_lit("Type_Info_Map"));
  10237. tag = ir_emit_conv(proc, variant_ptr, t_type_info_map_ptr);
  10238. init_map_internal_types(t);
  10239. irValue *key = ir_emit_struct_ep(proc, tag, 0);
  10240. irValue *value = ir_emit_struct_ep(proc, tag, 1);
  10241. irValue *generated_struct = ir_emit_struct_ep(proc, tag, 2);
  10242. ir_emit_store(proc, key, ir_get_type_info_ptr(proc, t->Map.key));
  10243. ir_emit_store(proc, value, ir_get_type_info_ptr(proc, t->Map.value));
  10244. ir_emit_store(proc, generated_struct, ir_get_type_info_ptr(proc, t->Map.generated_struct_type));
  10245. break;
  10246. }
  10247. case Type_BitField: {
  10248. ir_emit_comment(proc, str_lit("Type_Info_Bit_Field"));
  10249. tag = ir_emit_conv(proc, variant_ptr, t_type_info_bit_field_ptr);
  10250. // names: []string;
  10251. // bits: []u32;
  10252. // offsets: []u32;
  10253. isize count = t->BitField.fields.count;
  10254. if (count > 0) {
  10255. auto fields = t->BitField.fields;
  10256. irValue *name_array = ir_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  10257. irValue *bit_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  10258. irValue *offset_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  10259. for (isize i = 0; i < count; i++) {
  10260. Entity *f = fields[i];
  10261. GB_ASSERT(f->type != nullptr);
  10262. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  10263. irValue *name_ep = ir_emit_array_epi(proc, name_array, cast(i32)i);
  10264. irValue *bit_ep = ir_emit_array_epi(proc, bit_array, cast(i32)i);
  10265. irValue *offset_ep = ir_emit_array_epi(proc, offset_array, cast(i32)i);
  10266. ir_emit_store(proc, name_ep, ir_const_string(proc->module, f->token.string));
  10267. ir_emit_store(proc, bit_ep, ir_const_i32(f->type->BitFieldValue.bits));
  10268. ir_emit_store(proc, offset_ep, ir_const_i32(t->BitField.offsets[i]));
  10269. }
  10270. irValue *v_count = ir_const_int(count);
  10271. irValue *names = ir_emit_struct_ep(proc, tag, 0);
  10272. irValue *name_array_elem = ir_array_elem(proc, name_array);
  10273. ir_fill_slice(proc, names, name_array_elem, v_count);
  10274. irValue *bits = ir_emit_struct_ep(proc, tag, 1);
  10275. irValue *bit_array_elem = ir_array_elem(proc, bit_array);
  10276. ir_fill_slice(proc, bits, bit_array_elem, v_count);
  10277. irValue *offsets = ir_emit_struct_ep(proc, tag, 2);
  10278. irValue *offset_array_elem = ir_array_elem(proc, offset_array);
  10279. ir_fill_slice(proc, offsets, offset_array_elem, v_count);
  10280. }
  10281. break;
  10282. }
  10283. case Type_BitSet:
  10284. ir_emit_comment(proc, str_lit("Type_Info_Bit_Set"));
  10285. tag = ir_emit_conv(proc, variant_ptr, t_type_info_bit_set_ptr);
  10286. GB_ASSERT(is_type_typed(t->BitSet.elem));
  10287. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->BitSet.elem));
  10288. if (t->BitSet.underlying != nullptr) {
  10289. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), ir_get_type_info_ptr(proc, t->BitSet.underlying));
  10290. }
  10291. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), ir_const_i64(t->BitSet.lower));
  10292. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 3), ir_const_i64(t->BitSet.upper));
  10293. break;
  10294. case Type_Opaque:
  10295. ir_emit_comment(proc, str_lit("Type_Opaque"));
  10296. tag = ir_emit_conv(proc, variant_ptr, t_type_info_opaque_ptr);
  10297. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->Opaque.elem));
  10298. break;
  10299. case Type_SimdVector:
  10300. ir_emit_comment(proc, str_lit("Type_SimdVector"));
  10301. tag = ir_emit_conv(proc, variant_ptr, t_type_info_simd_vector_ptr);
  10302. if (t->SimdVector.is_x86_mmx) {
  10303. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 3), v_true);
  10304. } else {
  10305. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->SimdVector.elem));
  10306. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 1), ir_const_int(type_size_of(t->SimdVector.elem)));
  10307. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 2), ir_const_int(t->SimdVector.count));
  10308. }
  10309. break;
  10310. case Type_RelativePointer:
  10311. ir_emit_comment(proc, str_lit("Type_RelativePointer"));
  10312. tag = ir_emit_conv(proc, variant_ptr, t_type_info_relative_pointer_ptr);
  10313. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->RelativePointer.pointer_type));
  10314. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->RelativePointer.base_integer));
  10315. break;
  10316. case Type_RelativeSlice:
  10317. ir_emit_comment(proc, str_lit("Type_RelativeSlice"));
  10318. tag = ir_emit_conv(proc, variant_ptr, t_type_info_relative_slice_ptr);
  10319. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->RelativePointer.pointer_type));
  10320. ir_emit_store(proc, ir_emit_struct_ep(proc, tag, 0), ir_get_type_info_ptr(proc, t->RelativePointer.base_integer));
  10321. break;
  10322. }
  10323. if (tag != nullptr) {
  10324. Type *tag_type = type_deref(ir_type(tag));
  10325. GB_ASSERT(is_type_named(tag_type));
  10326. ir_emit_store_union_variant(proc, variant_ptr, ir_emit_load(proc, tag), tag_type);
  10327. } else {
  10328. if (t != t_llvm_bool) {
  10329. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  10330. }
  10331. }
  10332. }
  10333. }
  10334. void ir_gen_tree(irGen *s) {
  10335. irModule *m = &s->module;
  10336. CheckerInfo *info = m->info;
  10337. gbAllocator a = ir_allocator();
  10338. if (v_zero == nullptr) {
  10339. v_zero = ir_const_int (0);
  10340. v_one = ir_const_int (1);
  10341. v_zero32 = ir_const_i32 (0);
  10342. v_one32 = ir_const_i32 (1);
  10343. v_two32 = ir_const_i32 (2);
  10344. v_false = ir_const_bool(false);
  10345. v_true = ir_const_bool(true);
  10346. v_raw_nil = ir_value_constant(t_rawptr, exact_value_pointer(0));
  10347. }
  10348. isize global_variable_max_count = 0;
  10349. Entity *entry_point = info->entry_point;
  10350. bool has_dll_main = false;
  10351. bool has_win_main = false;
  10352. for_array(i, info->entities) {
  10353. Entity *e = info->entities[i];
  10354. String name = e->token.string;
  10355. bool is_global = e->pkg != nullptr;
  10356. if (e->kind == Entity_Variable) {
  10357. global_variable_max_count++;
  10358. } else if (e->kind == Entity_Procedure && !is_global) {
  10359. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  10360. GB_ASSERT(e == entry_point);
  10361. // entry_point = e;
  10362. }
  10363. if (e->Procedure.is_export ||
  10364. (e->Procedure.link_name.len > 0) ||
  10365. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  10366. if (!has_dll_main && name == "DllMain") {
  10367. has_dll_main = true;
  10368. } else if (!has_win_main && name == "WinMain") {
  10369. has_win_main = true;
  10370. }
  10371. }
  10372. }
  10373. }
  10374. // Add global default context
  10375. m->global_default_context = ir_add_global_generated(m, t_context, nullptr);
  10376. struct irGlobalVariable {
  10377. irValue *var, *init;
  10378. DeclInfo *decl;
  10379. };
  10380. auto global_variables = array_make<irGlobalVariable>(m->tmp_allocator, 0, global_variable_max_count);
  10381. m->entry_point_entity = entry_point;
  10382. m->min_dep_set = info->minimum_dependency_set;
  10383. for_array(i, info->variable_init_order) {
  10384. DeclInfo *d = info->variable_init_order[i];
  10385. Entity *e = d->entity;
  10386. if ((e->scope->flags & ScopeFlag_File) == 0) {
  10387. continue;
  10388. }
  10389. if (!ir_min_dep_entity(m, e)) {
  10390. continue;
  10391. }
  10392. DeclInfo *decl = decl_info_of_entity(e);
  10393. if (decl == nullptr) {
  10394. continue;
  10395. }
  10396. GB_ASSERT(e->kind == Entity_Variable);
  10397. bool is_foreign = e->Variable.is_foreign;
  10398. bool is_export = e->Variable.is_export;
  10399. bool no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  10400. String name = e->token.string;
  10401. if (e->Variable.link_name.len > 0) {
  10402. name = e->Variable.link_name;
  10403. }
  10404. if (!no_name_mangle) {
  10405. name = ir_mangle_name(s, e);
  10406. }
  10407. ir_add_entity_name(m, e, name);
  10408. irValue *g = ir_value_global(e, nullptr);
  10409. g->Global.name = name;
  10410. g->Global.thread_local_model = e->Variable.thread_local_model;
  10411. g->Global.is_foreign = is_foreign;
  10412. g->Global.is_export = is_export;
  10413. irGlobalVariable var = {};
  10414. var.var = g;
  10415. var.decl = decl;
  10416. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  10417. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  10418. if (tav.mode != Addressing_Invalid) {
  10419. if (tav.value.kind != ExactValue_Invalid) {
  10420. ExactValue v = tav.value;
  10421. g->Global.value = ir_add_module_constant(m, tav.type, v);
  10422. }
  10423. }
  10424. }
  10425. array_add(&global_variables, var);
  10426. ir_module_add_value(m, e, g);
  10427. string_map_set(&m->members, name, g);
  10428. }
  10429. for_array(i, info->entities) {
  10430. Entity * e = info->entities[i];
  10431. String name = e->token.string;
  10432. DeclInfo *decl = e->decl_info;
  10433. Scope * scope = e->scope;
  10434. if ((scope->flags & ScopeFlag_File) == 0) {
  10435. continue;
  10436. }
  10437. Scope *package_scope = scope->parent;
  10438. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  10439. switch (e->kind) {
  10440. case Entity_Variable:
  10441. // NOTE(bill): Handled above as it requires a specific load order
  10442. continue;
  10443. case Entity_ProcGroup:
  10444. continue;
  10445. case Entity_Procedure:
  10446. break;
  10447. }
  10448. bool polymorphic_struct = false;
  10449. if (e->type != nullptr && e->kind == Entity_TypeName) {
  10450. Type *bt = base_type(e->type);
  10451. if (bt->kind == Type_Struct) {
  10452. polymorphic_struct = is_type_polymorphic(bt);
  10453. }
  10454. }
  10455. if (!polymorphic_struct && !ir_min_dep_entity(m, e)) {
  10456. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  10457. continue;
  10458. }
  10459. String original_name = name;
  10460. #if 0
  10461. if (!package_scope->is_global || polymorphic_struct || is_type_polymorphic(e->type)) {
  10462. if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  10463. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  10464. // Handle later
  10465. } else {
  10466. name = ir_mangle_name(s, e);
  10467. }
  10468. }
  10469. #else
  10470. if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  10471. // Okay
  10472. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  10473. // Handle later
  10474. } else {
  10475. name = ir_mangle_name(s, e);
  10476. }
  10477. #endif
  10478. ir_add_entity_name(m, e, name);
  10479. switch (e->kind) {
  10480. case Entity_TypeName:
  10481. ir_gen_global_type_name(m, e, name);
  10482. break;
  10483. case Entity_Procedure: {
  10484. ast_node(pl, ProcLit, decl->proc_lit);
  10485. String original_name = name;
  10486. Ast *body = pl->body;
  10487. if (e->Procedure.is_foreign) {
  10488. name = e->token.string; // NOTE(bill): Don't use the mangled name
  10489. ir_add_foreign_library_path(m, e->Procedure.foreign_library);
  10490. }
  10491. if (e->Procedure.link_name.len > 0) {
  10492. name = e->Procedure.link_name;
  10493. }
  10494. Ast *type_expr = pl->type;
  10495. set_procedure_abi_types(heap_allocator(), e->type);
  10496. irValue *p = ir_value_procedure(m, e, e->type, type_expr, body, name);
  10497. p->Proc.tags = pl->tags;
  10498. p->Proc.inlining = pl->inlining;
  10499. p->Proc.is_export = e->Procedure.is_export;
  10500. ir_module_add_value(m, e, p);
  10501. StringHashKey hash_name = string_hash_string(name);
  10502. if (string_map_get(&m->members, hash_name) == nullptr) {
  10503. string_map_set(&m->members, hash_name, p);
  10504. }
  10505. break;
  10506. }
  10507. }
  10508. }
  10509. for_array(i, m->members.entries) {
  10510. auto *entry = &m->members.entries[i];
  10511. irValue *v = entry->value;
  10512. if (v->kind == irValue_Proc) {
  10513. ir_build_proc(v, nullptr);
  10514. }
  10515. }
  10516. irDebugInfo *compile_unit = m->debug_info.entries[0].value;
  10517. GB_ASSERT(compile_unit->kind == irDebugInfo_CompileUnit);
  10518. for_array(i, m->info->required_foreign_imports_through_force) {
  10519. Entity *e = m->info->required_foreign_imports_through_force[i];
  10520. ir_add_foreign_library_path(m, e);
  10521. }
  10522. #if defined(GB_SYSTEM_WINDOWS)
  10523. if (build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main) {
  10524. // DllMain :: proc(inst: rawptr, reason: u32, reserved: rawptr) -> i32
  10525. String name = str_lit("DllMain");
  10526. Type *proc_params = alloc_type_tuple();
  10527. Type *proc_results = alloc_type_tuple();
  10528. Scope *proc_scope = gb_alloc_item(a, Scope);
  10529. array_init(&proc_params->Tuple.variables, a, 3);
  10530. array_init(&proc_results->Tuple.variables, a, 1);
  10531. proc_params->Tuple.variables[0] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false, false);
  10532. proc_params->Tuple.variables[1] = alloc_entity_param(proc_scope, make_token_ident(str_lit("reason")), t_i32, false, false);
  10533. proc_params->Tuple.variables[2] = alloc_entity_param(proc_scope, blank_token, t_rawptr, false, false);
  10534. proc_results->Tuple.variables[0] = alloc_entity_param(proc_scope, empty_token, t_i32, false, false);
  10535. Type *proc_type = alloc_type_proc(proc_scope,
  10536. proc_params, 3,
  10537. proc_results, 1, false, ProcCC_StdCall);
  10538. // TODO(bill): make this more robust
  10539. proc_type->Proc.abi_compat_params = array_make<Type *>(a, proc_params->Tuple.variables.count);
  10540. for_array(i, proc_params->Tuple.variables) {
  10541. proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
  10542. }
  10543. proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
  10544. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10545. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10546. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10547. p->Proc.is_startup = true;
  10548. map_set(&m->values, hash_entity(e), p);
  10549. string_map_set(&m->members, name, p);
  10550. irProcedure *proc = &p->Proc;
  10551. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  10552. proc->is_entry_point = true;
  10553. e->Procedure.link_name = name;
  10554. ir_begin_procedure_body(proc);
  10555. defer (ir_end_procedure_body(proc));
  10556. // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
  10557. // DLL_PROCESS_ATTACH == 1
  10558. irAddr reason_addr = ir_build_addr_from_entity(proc, proc_params->Tuple.variables[1], nullptr);
  10559. irValue *cond = ir_emit_comp(proc, Token_CmpEq, ir_addr_load(proc, reason_addr), v_one32);
  10560. irBlock *then = ir_new_block(proc, nullptr, "if.then");
  10561. irBlock *done = ir_new_block(proc, nullptr, "if.done"); // NOTE(bill): Append later
  10562. ir_emit_if(proc, cond, then, done);
  10563. ir_start_block(proc, then);
  10564. {
  10565. irValue **found = map_get(&m->values, hash_entity(entry_point));
  10566. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  10567. if (found != nullptr) {
  10568. Array<irValue *> args = {};
  10569. ir_emit_call(proc, *found, args);
  10570. }
  10571. }
  10572. ir_emit_jump(proc, done);
  10573. ir_start_block(proc, done);
  10574. ir_emit_return(proc, v_one32);
  10575. }
  10576. #endif
  10577. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  10578. // main :: proc(argc: i32, argv: ^^u8) -> i32
  10579. String name = str_lit("main");
  10580. #if 0
  10581. if (str_eq_ignore_case(cross_compile_target, str_lit("Essence"))) {
  10582. // This is a bit hacky,
  10583. // because this makes this function the first function run in the executable
  10584. // so it won't actually have the argc/argv arguments.
  10585. name = str_lit("ProgramEntry");
  10586. }
  10587. #endif
  10588. Type *proc_params = alloc_type_tuple();
  10589. Type *proc_results = alloc_type_tuple();
  10590. Scope *proc_scope = gb_alloc_item(a, Scope);
  10591. array_init(&proc_params->Tuple.variables, a, 2);
  10592. array_init(&proc_results->Tuple.variables, a, 1);
  10593. Type *cstring_ptr = alloc_type_pointer(t_cstring);
  10594. proc_params->Tuple.variables[0] = alloc_entity_param(proc_scope, make_token_ident(str_lit("argc")), t_i32, false, false);
  10595. proc_params->Tuple.variables[1] = alloc_entity_param(proc_scope, make_token_ident(str_lit("argv")), cstring_ptr, false, false);
  10596. proc_results->Tuple.variables[0] = alloc_entity_param(proc_scope, empty_token, t_i32, false, false);
  10597. Type *proc_type = alloc_type_proc(proc_scope,
  10598. proc_params, 2,
  10599. proc_results, 1, false, ProcCC_CDecl);
  10600. // TODO(bill): make this more robust
  10601. proc_type->Proc.abi_compat_params = array_make<Type *>(a, proc_params->Tuple.variables.count);
  10602. for_array(i, proc_params->Tuple.variables) {
  10603. proc_type->Proc.abi_compat_params[i] = proc_params->Tuple.variables[i]->type;
  10604. }
  10605. proc_type->Proc.abi_compat_result_type = proc_results->Tuple.variables[0]->type;
  10606. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10607. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10608. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10609. p->Proc.is_startup = true;
  10610. map_set(&m->values, hash_entity(e), p);
  10611. string_map_set(&m->members, name, p);
  10612. irProcedure *proc = &p->Proc;
  10613. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  10614. proc->is_entry_point = true;
  10615. e->Procedure.link_name = name;
  10616. ir_begin_procedure_body(proc);
  10617. defer (ir_end_procedure_body(proc));
  10618. // NOTE(bill): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
  10619. // DLL_PROCESS_ATTACH == 1
  10620. irValue *argc = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[0])));
  10621. irValue *argv = ir_emit_load(proc, *map_get(&proc->module->values, hash_entity(proc_params->Tuple.variables[1])));
  10622. irValue *global_args = ir_find_global_variable(proc, str_lit("args__"));
  10623. ir_fill_slice(proc, global_args, argv, ir_emit_conv(proc, argc, t_int));
  10624. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  10625. {
  10626. irValue **found = map_get(&proc->module->values, hash_entity(entry_point));
  10627. if (found != nullptr) {
  10628. Array<irValue *> args = {};
  10629. ir_emit_call(proc, *found, args);
  10630. }
  10631. }
  10632. ir_emit_return(proc, v_zero32);
  10633. }
  10634. #if defined(GB_SYSTEM_WINDOWS)
  10635. if (build_context.build_mode != BuildMode_DynamicLibrary && build_context.no_crt) {
  10636. s->print_chkstk = true;
  10637. {
  10638. // void mainCRTStartup(void)
  10639. String name = str_lit("mainCRTStartup");
  10640. Type *proc_params = alloc_type_tuple();
  10641. Type *proc_results = alloc_type_tuple();
  10642. Type *proc_type = alloc_type_proc(nullptr,
  10643. nullptr, 0,
  10644. nullptr, 0,
  10645. false,
  10646. ProcCC_StdCall);
  10647. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10648. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10649. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10650. p->Proc.is_startup = true;
  10651. m->entry_point_entity = e;
  10652. map_set(&m->values, hash_entity(e), p);
  10653. string_map_set(&m->members, name, p);
  10654. irProcedure *proc = &p->Proc;
  10655. // proc->tags = ProcTag_no_inline; // TODO(bill): is no_inline a good idea?
  10656. e->Procedure.link_name = name;
  10657. ir_begin_procedure_body(proc);
  10658. ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime));
  10659. irValue **found = map_get(&proc->module->values, hash_entity(entry_point));
  10660. if (found != nullptr) {
  10661. Array<irValue *> args = {};
  10662. ir_emit_call(proc, *found, args);
  10663. }
  10664. ir_end_procedure_body(proc);
  10665. }
  10666. }
  10667. #endif
  10668. { // Startup Runtime
  10669. // Cleanup(bill): probably better way of doing code insertion
  10670. String name = str_lit(IR_STARTUP_RUNTIME_PROC_NAME);
  10671. Type *proc_type = alloc_type_proc(gb_alloc_item(a, Scope),
  10672. nullptr, 0,
  10673. nullptr, 0, false,
  10674. ProcCC_Contextless);
  10675. Ast *body = alloc_ast_node(nullptr, Ast_Invalid);
  10676. Entity *e = alloc_entity_procedure(nullptr, make_token_ident(name), proc_type, 0);
  10677. irValue *p = ir_value_procedure(m, e, proc_type, nullptr, body, name);
  10678. p->Proc.is_startup = true;
  10679. map_set(&m->values, hash_entity(e), p);
  10680. string_map_set(&m->members, name, p);
  10681. irProcedure *proc = &p->Proc;
  10682. proc->inlining = ProcInlining_no_inline; // TODO(bill): is no_inline a good idea?
  10683. ir_begin_procedure_body(proc);
  10684. defer (ir_end_procedure_body(proc));
  10685. ir_emit_init_context(proc);
  10686. ir_setup_type_info_data(proc);
  10687. for_array(i, global_variables) {
  10688. irGlobalVariable *var = &global_variables[i];
  10689. if (var->decl->init_expr != nullptr) {
  10690. var->init = ir_build_expr(proc, var->decl->init_expr);
  10691. }
  10692. Entity *e = var->var->Global.entity;
  10693. GB_ASSERT(e->kind == Entity_Variable);
  10694. if (e->Variable.is_foreign) {
  10695. Entity *fl = e->Procedure.foreign_library;
  10696. ir_add_foreign_library_path(m, fl);
  10697. }
  10698. if (e->flags & EntityFlag_Static) {
  10699. var->var->Global.is_internal = true;
  10700. }
  10701. if (var->init != nullptr) {
  10702. Type *t = type_deref(ir_type(var->var));
  10703. if (is_type_any(t)) {
  10704. // NOTE(bill): Edge case for 'any' type
  10705. Type *var_type = default_type(ir_type(var->init));
  10706. irValue *g = ir_add_global_generated(proc->module, var_type, var->init);
  10707. ir_emit_store(proc, g, var->init);
  10708. irValue *data = ir_emit_struct_ep(proc, var->var, 0);
  10709. irValue *ti = ir_emit_struct_ep(proc, var->var, 1);
  10710. ir_emit_store(proc, data, ir_emit_conv(proc, g, t_rawptr));
  10711. ir_emit_store(proc, ti, ir_type_info(proc, var_type));
  10712. } else {
  10713. ir_emit_store(proc, var->var, ir_emit_conv(proc, var->init, t));
  10714. }
  10715. }
  10716. }
  10717. }
  10718. for_array(i, m->procs_to_generate) {
  10719. irValue *p = m->procs_to_generate[i];
  10720. ir_build_proc(p, p->Proc.parent);
  10721. }
  10722. GB_ASSERT_MSG(m->debug_location_stack.count == 0, "Debug location stack contains unpopped entries.");
  10723. // Number debug info
  10724. for_array(i, m->debug_info.entries) {
  10725. auto *entry = &m->debug_info.entries[i];
  10726. irDebugInfo *di = entry->value;
  10727. di->id = cast(i32)(i+1);
  10728. }
  10729. // 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");
  10730. }