llvm_backend.cpp 403 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044
  1. #include "llvm_backend.hpp"
  2. #include "llvm_abi.cpp"
  3. gb_global lbAddr lb_global_type_info_data = {};
  4. gb_global lbAddr lb_global_type_info_member_types = {};
  5. gb_global lbAddr lb_global_type_info_member_names = {};
  6. gb_global lbAddr lb_global_type_info_member_offsets = {};
  7. gb_global lbAddr lb_global_type_info_member_usings = {};
  8. gb_global lbAddr lb_global_type_info_member_tags = {};
  9. gb_global isize lb_global_type_info_data_index = 0;
  10. gb_global isize lb_global_type_info_member_types_index = 0;
  11. gb_global isize lb_global_type_info_member_names_index = 0;
  12. gb_global isize lb_global_type_info_member_offsets_index = 0;
  13. gb_global isize lb_global_type_info_member_usings_index = 0;
  14. gb_global isize lb_global_type_info_member_tags_index = 0;
  15. struct lbLoopData {
  16. lbAddr idx_addr;
  17. lbValue idx;
  18. lbBlock *body;
  19. lbBlock *done;
  20. lbBlock *loop;
  21. };
  22. struct lbCompoundLitElemTempData {
  23. Ast * expr;
  24. lbValue value;
  25. i32 elem_index;
  26. lbValue gep;
  27. };
  28. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  29. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  30. LLVMValueRef llvm_zero(lbModule *m) {
  31. return LLVMConstInt(lb_type(m, t_int), 0, false);
  32. }
  33. LLVMValueRef llvm_one(lbModule *m) {
  34. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  35. }
  36. lbValue lb_zero(lbModule *m, Type *t) {
  37. lbValue v = {};
  38. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  39. v.type = t;
  40. return v;
  41. }
  42. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  43. lbValue v = lb_find_or_add_entity_string(m, str);
  44. unsigned indices[1] = {0};
  45. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  46. }
  47. bool lb_is_instr_terminating(LLVMValueRef instr) {
  48. if (instr != nullptr) {
  49. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  50. switch (op) {
  51. case LLVMRet:
  52. case LLVMBr:
  53. case LLVMSwitch:
  54. case LLVMIndirectBr:
  55. case LLVMInvoke:
  56. case LLVMUnreachable:
  57. case LLVMCallBr:
  58. return true;
  59. }
  60. }
  61. return false;
  62. }
  63. lbAddr lb_addr(lbValue addr) {
  64. lbAddr v = {lbAddr_Default, addr};
  65. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  66. GB_ASSERT(is_type_pointer(addr.type));
  67. v.kind = lbAddr_RelativePointer;
  68. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  69. GB_ASSERT(is_type_pointer(addr.type));
  70. v.kind = lbAddr_RelativeSlice;
  71. }
  72. return v;
  73. }
  74. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  75. lbAddr v = {lbAddr_Map, addr};
  76. v.map.key = map_key;
  77. v.map.type = map_type;
  78. v.map.result = map_result;
  79. return v;
  80. }
  81. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  82. lbAddr v = {lbAddr_SoaVariable, addr};
  83. v.soa.index = index;
  84. v.soa.index_expr = index_expr;
  85. return v;
  86. }
  87. Type *lb_addr_type(lbAddr const &addr) {
  88. if (addr.addr.value == nullptr) {
  89. return nullptr;
  90. }
  91. if (addr.kind == lbAddr_Map) {
  92. Type *t = base_type(addr.map.type);
  93. GB_ASSERT(is_type_map(t));
  94. return t->Map.value;
  95. }
  96. return type_deref(addr.addr.type);
  97. }
  98. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  99. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  100. }
  101. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  102. if (addr.addr.value == nullptr) {
  103. GB_PANIC("Illegal addr -> nullptr");
  104. return {};
  105. }
  106. switch (addr.kind) {
  107. case lbAddr_Map: {
  108. Type *map_type = base_type(addr.map.type);
  109. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  110. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  111. auto args = array_make<lbValue>(permanent_allocator(), 2);
  112. args[0] = h;
  113. args[1] = key;
  114. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  115. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  116. }
  117. case lbAddr_RelativePointer: {
  118. Type *rel_ptr = base_type(lb_addr_type(addr));
  119. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  120. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  121. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  122. offset = lb_emit_load(p, offset);
  123. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  124. offset = lb_emit_conv(p, offset, t_i64);
  125. }
  126. offset = lb_emit_conv(p, offset, t_uintptr);
  127. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  128. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  129. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  130. // NOTE(bill): nil check
  131. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  132. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  133. return final_ptr;
  134. }
  135. case lbAddr_Context:
  136. GB_PANIC("lbAddr_Context should be handled elsewhere");
  137. }
  138. return addr.addr;
  139. }
  140. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  141. lbAddr addr = lb_build_addr(p, expr);
  142. return lb_addr_get_ptr(p, addr);
  143. }
  144. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  145. if (build_context.no_bounds_check) {
  146. return;
  147. }
  148. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  149. return;
  150. }
  151. index = lb_emit_conv(p, index, t_int);
  152. len = lb_emit_conv(p, len, t_int);
  153. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  154. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  155. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  156. auto args = array_make<lbValue>(permanent_allocator(), 5);
  157. args[0] = file;
  158. args[1] = line;
  159. args[2] = column;
  160. args[3] = index;
  161. args[4] = len;
  162. lb_emit_runtime_call(p, "bounds_check_error", args);
  163. }
  164. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  165. if (build_context.no_bounds_check) {
  166. return;
  167. }
  168. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  169. return;
  170. }
  171. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  172. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  173. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  174. high = lb_emit_conv(p, high, t_int);
  175. if (!lower_value_used) {
  176. auto args = array_make<lbValue>(permanent_allocator(), 5);
  177. args[0] = file;
  178. args[1] = line;
  179. args[2] = column;
  180. args[3] = high;
  181. args[4] = len;
  182. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  183. } else {
  184. // No need to convert unless used
  185. low = lb_emit_conv(p, low, t_int);
  186. auto args = array_make<lbValue>(permanent_allocator(), 6);
  187. args[0] = file;
  188. args[1] = line;
  189. args[2] = column;
  190. args[3] = low;
  191. args[4] = high;
  192. args[5] = len;
  193. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  194. }
  195. }
  196. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  197. if (addr.addr.value == nullptr) {
  198. return;
  199. }
  200. GB_ASSERT(value.type != nullptr);
  201. if (is_type_untyped_undef(value.type)) {
  202. Type *t = lb_addr_type(addr);
  203. value.type = t;
  204. value.value = LLVMGetUndef(lb_type(p->module, t));
  205. } else if (is_type_untyped_nil(value.type)) {
  206. Type *t = lb_addr_type(addr);
  207. value.type = t;
  208. value.value = LLVMConstNull(lb_type(p->module, t));
  209. }
  210. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  211. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  212. }
  213. if (addr.kind == lbAddr_RelativePointer) {
  214. Type *rel_ptr = base_type(lb_addr_type(addr));
  215. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  216. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  217. GB_ASSERT(is_type_pointer(addr.addr.type));
  218. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  219. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  220. lbValue offset = {};
  221. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  222. offset.type = t_uintptr;
  223. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  224. offset = lb_emit_conv(p, offset, t_i64);
  225. }
  226. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  227. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  228. offset = lb_emit_select(p,
  229. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  230. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  231. offset
  232. );
  233. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  234. return;
  235. } else if (addr.kind == lbAddr_RelativeSlice) {
  236. Type *rel_ptr = base_type(lb_addr_type(addr));
  237. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  238. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  239. GB_ASSERT(is_type_pointer(addr.addr.type));
  240. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  241. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  242. lbValue offset = {};
  243. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  244. offset.type = t_uintptr;
  245. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  246. offset = lb_emit_conv(p, offset, t_i64);
  247. }
  248. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  249. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  250. offset = lb_emit_select(p,
  251. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  252. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  253. offset
  254. );
  255. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  256. lbValue len = lb_slice_len(p, value);
  257. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  258. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  259. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  260. return;
  261. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  262. lbValue ptr = addr.addr;
  263. lbValue index = addr.index_set.index;
  264. Ast *node = addr.index_set.node;
  265. ast_node(ce, CallExpr, node);
  266. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  267. proc_type = base_type(proc_type);
  268. GB_ASSERT(is_type_proc(proc_type));
  269. TypeProc *pt = &proc_type->Proc;
  270. isize arg_count = 3;
  271. isize param_count = 0;
  272. if (pt->params) {
  273. GB_ASSERT(pt->params->kind == Type_Tuple);
  274. param_count = pt->params->Tuple.variables.count;
  275. }
  276. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  277. args[0] = ptr;
  278. args[1] = index;
  279. args[2] = value;
  280. isize arg_index = arg_count;
  281. if (arg_count < param_count) {
  282. lbModule *m = p->module;
  283. String proc_name = {};
  284. if (p->entity != nullptr) {
  285. proc_name = p->entity->token.string;
  286. }
  287. TokenPos pos = ast_token(ce->proc).pos;
  288. TypeTuple *param_tuple = &pt->params->Tuple;
  289. isize end = cast(isize)param_count;
  290. while (arg_index < end) {
  291. Entity *e = param_tuple->variables[arg_index];
  292. GB_ASSERT(e->kind == Entity_Variable);
  293. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  294. }
  295. }
  296. Entity *e = entity_from_expr(ce->proc);
  297. GB_ASSERT(e != nullptr);
  298. GB_ASSERT(is_type_polymorphic(e->type));
  299. {
  300. lbValue *found = nullptr;
  301. if (p->module != e->code_gen_module) {
  302. gb_mutex_lock(&p->module->mutex);
  303. }
  304. GB_ASSERT(e->code_gen_module != nullptr);
  305. found = map_get(&e->code_gen_module->values, hash_entity(e));
  306. if (p->module != e->code_gen_module) {
  307. gb_mutex_unlock(&p->module->mutex);
  308. }
  309. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  310. lb_emit_call(p, *found, args);
  311. }
  312. return;
  313. } else if (addr.kind == lbAddr_Map) {
  314. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  315. return;
  316. } else if (addr.kind == lbAddr_Context) {
  317. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  318. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  319. lb_addr_store(p, next_addr, old);
  320. lb_push_context_onto_stack(p, next_addr);
  321. lbValue next = lb_addr_get_ptr(p, next_addr);
  322. if (addr.ctx.sel.index.count > 0) {
  323. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  324. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  325. lb_emit_store(p, lhs, rhs);
  326. } else {
  327. lbValue lhs = next;
  328. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  329. lb_emit_store(p, lhs, rhs);
  330. }
  331. return;
  332. } else if (addr.kind == lbAddr_SoaVariable) {
  333. Type *t = type_deref(addr.addr.type);
  334. t = base_type(t);
  335. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  336. Type *elem_type = t->Struct.soa_elem;
  337. value = lb_emit_conv(p, value, elem_type);
  338. elem_type = base_type(elem_type);
  339. lbValue index = addr.soa.index;
  340. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  341. Type *t = base_type(type_deref(addr.addr.type));
  342. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  343. lbValue len = lb_soa_struct_len(p, addr.addr);
  344. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  345. }
  346. isize field_count = 0;
  347. switch (elem_type->kind) {
  348. case Type_Struct:
  349. field_count = elem_type->Struct.fields.count;
  350. break;
  351. case Type_Array:
  352. field_count = elem_type->Array.count;
  353. break;
  354. }
  355. for (isize i = 0; i < field_count; i++) {
  356. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  357. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  358. if (t->Struct.soa_kind == StructSoa_Fixed) {
  359. dst = lb_emit_array_ep(p, dst, index);
  360. lb_emit_store(p, dst, src);
  361. } else {
  362. lbValue field = lb_emit_load(p, dst);
  363. dst = lb_emit_ptr_offset(p, field, index);
  364. lb_emit_store(p, dst, src);
  365. }
  366. }
  367. return;
  368. }
  369. GB_ASSERT(value.value != nullptr);
  370. value = lb_emit_conv(p, value, lb_addr_type(addr));
  371. // if (lb_is_const_or_global(value)) {
  372. // // NOTE(bill): Just bypass the actual storage and set the initializer
  373. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  374. // LLVMValueRef dst = addr.addr.value;
  375. // LLVMValueRef src = value.value;
  376. // LLVMSetInitializer(dst, src);
  377. // return;
  378. // }
  379. // }
  380. lb_emit_store(p, addr.addr, value);
  381. }
  382. void lb_const_store(lbValue ptr, lbValue value) {
  383. GB_ASSERT(lb_is_const(ptr));
  384. GB_ASSERT(lb_is_const(value));
  385. GB_ASSERT(is_type_pointer(ptr.type));
  386. LLVMSetInitializer(ptr.value, value.value);
  387. }
  388. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  389. GB_ASSERT(value.value != nullptr);
  390. Type *a = type_deref(ptr.type);
  391. if (is_type_boolean(a)) {
  392. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  393. value = lb_emit_conv(p, value, a);
  394. }
  395. Type *ca = core_type(a);
  396. if (ca->kind == Type_Basic) {
  397. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  398. }
  399. if (is_type_proc(a)) {
  400. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  401. // stored as regular pointer with no procedure information
  402. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  403. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  404. LLVMBuildStore(p->builder, v, ptr.value);
  405. } else {
  406. Type *ca = core_type(a);
  407. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  408. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  409. } else {
  410. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  411. }
  412. LLVMBuildStore(p->builder, value.value, ptr.value);
  413. }
  414. }
  415. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  416. lbModule *m = p->module;
  417. GB_ASSERT(value.value != nullptr);
  418. Type *t = type_deref(value.type);
  419. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  420. return lbValue{v, t};
  421. }
  422. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  423. GB_ASSERT(addr.addr.value != nullptr);
  424. if (addr.kind == lbAddr_RelativePointer) {
  425. Type *rel_ptr = base_type(lb_addr_type(addr));
  426. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  427. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  428. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  429. offset = lb_emit_load(p, offset);
  430. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  431. offset = lb_emit_conv(p, offset, t_i64);
  432. }
  433. offset = lb_emit_conv(p, offset, t_uintptr);
  434. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  435. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  436. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  437. // NOTE(bill): nil check
  438. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  439. lbValue final_ptr = {};
  440. final_ptr.type = absolute_ptr.type;
  441. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  442. return lb_emit_load(p, final_ptr);
  443. } else if (addr.kind == lbAddr_RelativeSlice) {
  444. Type *rel_ptr = base_type(lb_addr_type(addr));
  445. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  446. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  447. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  448. lbValue offset = lb_emit_load(p, offset_ptr);
  449. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  450. offset = lb_emit_conv(p, offset, t_i64);
  451. }
  452. offset = lb_emit_conv(p, offset, t_uintptr);
  453. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  454. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  455. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  456. Type *slice_elem = slice_type->Slice.elem;
  457. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  458. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  459. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  460. // NOTE(bill): nil check
  461. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  462. lbValue data = {};
  463. data.type = absolute_ptr.type;
  464. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  465. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  466. len = lb_emit_conv(p, len, t_int);
  467. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  468. lb_fill_slice(p, slice, data, len);
  469. return lb_addr_load(p, slice);
  470. } else if (addr.kind == lbAddr_Map) {
  471. Type *map_type = base_type(addr.map.type);
  472. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  473. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  474. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  475. auto args = array_make<lbValue>(permanent_allocator(), 2);
  476. args[0] = h;
  477. args[1] = key;
  478. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  479. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  480. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  481. lbBlock *then = lb_create_block(p, "map.get.then");
  482. lbBlock *done = lb_create_block(p, "map.get.done");
  483. lb_emit_if(p, ok, then, done);
  484. lb_start_block(p, then);
  485. {
  486. // TODO(bill): mem copy it instead?
  487. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  488. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  489. lb_emit_store(p, gep0, lb_emit_load(p, value));
  490. }
  491. lb_emit_jump(p, done);
  492. lb_start_block(p, done);
  493. if (is_type_tuple(addr.map.result)) {
  494. return lb_addr_load(p, v);
  495. } else {
  496. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  497. return lb_emit_load(p, single);
  498. }
  499. } else if (addr.kind == lbAddr_Context) {
  500. lbValue a = addr.addr;
  501. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  502. if (addr.ctx.sel.index.count > 0) {
  503. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  504. return lb_emit_load(p, b);
  505. } else {
  506. return lb_emit_load(p, a);
  507. }
  508. } else if (addr.kind == lbAddr_SoaVariable) {
  509. Type *t = type_deref(addr.addr.type);
  510. t = base_type(t);
  511. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  512. Type *elem = t->Struct.soa_elem;
  513. lbValue len = {};
  514. if (t->Struct.soa_kind == StructSoa_Fixed) {
  515. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  516. } else {
  517. lbValue v = lb_emit_load(p, addr.addr);
  518. len = lb_soa_struct_len(p, v);
  519. }
  520. lbAddr res = lb_add_local_generated(p, elem, true);
  521. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  522. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  523. }
  524. if (t->Struct.soa_kind == StructSoa_Fixed) {
  525. for_array(i, t->Struct.fields) {
  526. Entity *field = t->Struct.fields[i];
  527. Type *base_type = field->type;
  528. GB_ASSERT(base_type->kind == Type_Array);
  529. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  530. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  531. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  532. lbValue src = lb_emit_load(p, src_ptr);
  533. lb_emit_store(p, dst, src);
  534. }
  535. } else {
  536. isize field_count = t->Struct.fields.count;
  537. if (t->Struct.soa_kind == StructSoa_Slice) {
  538. field_count -= 1;
  539. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  540. field_count -= 3;
  541. }
  542. for (isize i = 0; i < field_count; i++) {
  543. Entity *field = t->Struct.fields[i];
  544. Type *base_type = field->type;
  545. GB_ASSERT(base_type->kind == Type_Pointer);
  546. Type *elem = base_type->Pointer.elem;
  547. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  548. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  549. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  550. lbValue src = lb_emit_load(p, src_ptr);
  551. src = lb_emit_load(p, src);
  552. lb_emit_store(p, dst, src);
  553. }
  554. }
  555. return lb_addr_load(p, res);
  556. }
  557. if (is_type_proc(addr.addr.type)) {
  558. return addr.addr;
  559. }
  560. return lb_emit_load(p, addr.addr);
  561. }
  562. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  563. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  564. }
  565. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  566. Type *t = u.type;
  567. GB_ASSERT_MSG(is_type_pointer(t) &&
  568. is_type_union(type_deref(t)), "%s", type_to_string(t));
  569. Type *ut = type_deref(t);
  570. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  571. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  572. GB_ASSERT(type_size_of(ut) > 0);
  573. Type *tag_type = union_tag_type(ut);
  574. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  575. unsigned element_count = LLVMCountStructElementTypes(uvt);
  576. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  577. lbValue tag_ptr = {};
  578. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  579. tag_ptr.type = alloc_type_pointer(tag_type);
  580. return tag_ptr;
  581. }
  582. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  583. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  584. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  585. return lb_emit_load(p, tag_ptr);
  586. }
  587. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  588. Type *t = type_deref(parent.type);
  589. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  590. // No tag needed!
  591. } else {
  592. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  593. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  594. }
  595. }
  596. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  597. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  598. lb_emit_store(p, underlying, variant);
  599. lb_emit_store_union_variant_tag(p, parent, variant_type);
  600. }
  601. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  602. unsigned field_count = LLVMCountStructElementTypes(src);
  603. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  604. LLVMGetStructElementTypes(src, fields);
  605. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  606. }
  607. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  608. switch (alignment) {
  609. case 1:
  610. return LLVMArrayType(lb_type(m, t_u8), 0);
  611. case 2:
  612. return LLVMArrayType(lb_type(m, t_u16), 0);
  613. case 4:
  614. return LLVMArrayType(lb_type(m, t_u32), 0);
  615. case 8:
  616. return LLVMArrayType(lb_type(m, t_u64), 0);
  617. case 16:
  618. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  619. default:
  620. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  621. break;
  622. }
  623. return nullptr;
  624. }
  625. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  626. if (!elem_type_can_be_constant(elem_type)) {
  627. return false;
  628. }
  629. if (elem->kind == Ast_FieldValue) {
  630. elem = elem->FieldValue.value;
  631. }
  632. TypeAndValue tav = type_and_value_of_expr(elem);
  633. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  634. return tav.value.kind != ExactValue_Invalid;
  635. }
  636. String lb_mangle_name(lbModule *m, Entity *e) {
  637. String name = e->token.string;
  638. AstPackage *pkg = e->pkg;
  639. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  640. String pkgn = pkg->name;
  641. GB_ASSERT(!rune_is_digit(pkgn[0]));
  642. if (pkgn == "llvm") {
  643. pkgn = str_lit("llvm$");
  644. }
  645. isize max_len = pkgn.len + 1 + name.len + 1;
  646. bool require_suffix_id = is_type_polymorphic(e->type, true);
  647. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  648. require_suffix_id = true;
  649. } else if (is_blank_ident(e->token)) {
  650. require_suffix_id = true;
  651. }if (e->flags & EntityFlag_NotExported) {
  652. require_suffix_id = true;
  653. }
  654. if (require_suffix_id) {
  655. max_len += 21;
  656. }
  657. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  658. isize new_name_len = gb_snprintf(
  659. new_name, max_len,
  660. "%.*s.%.*s", LIT(pkgn), LIT(name)
  661. );
  662. if (require_suffix_id) {
  663. char *str = new_name + new_name_len-1;
  664. isize len = max_len-new_name_len;
  665. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  666. new_name_len += extra-1;
  667. }
  668. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  669. return mangled_name;
  670. }
  671. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  672. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  673. // and as a result, the declaration does not have time to determine what it should be
  674. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  675. if (e->TypeName.ir_mangled_name.len != 0) {
  676. return e->TypeName.ir_mangled_name;
  677. }
  678. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  679. if (p == nullptr) {
  680. Entity *proc = nullptr;
  681. if (e->parent_proc_decl != nullptr) {
  682. proc = e->parent_proc_decl->entity;
  683. } else {
  684. Scope *scope = e->scope;
  685. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  686. scope = scope->parent;
  687. }
  688. GB_ASSERT(scope != nullptr);
  689. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  690. proc = scope->procedure_entity;
  691. }
  692. GB_ASSERT(proc->kind == Entity_Procedure);
  693. if (proc->code_gen_procedure != nullptr) {
  694. p = proc->code_gen_procedure;
  695. }
  696. }
  697. // NOTE(bill): Generate a new name
  698. // parent_proc.name-guid
  699. String ts_name = e->token.string;
  700. if (p != nullptr) {
  701. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  702. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  703. u32 guid = ++p->module->nested_type_name_guid;
  704. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  705. String name = make_string(cast(u8 *)name_text, name_len-1);
  706. e->TypeName.ir_mangled_name = name;
  707. return name;
  708. } else {
  709. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  710. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  711. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  712. static u32 guid = 0;
  713. guid += 1;
  714. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  715. String name = make_string(cast(u8 *)name_text, name_len-1);
  716. e->TypeName.ir_mangled_name = name;
  717. return name;
  718. }
  719. }
  720. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  721. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  722. return e->TypeName.ir_mangled_name;
  723. }
  724. GB_ASSERT(e != nullptr);
  725. if (e->pkg == nullptr) {
  726. return e->token.string;
  727. }
  728. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  729. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  730. }
  731. String name = {};
  732. bool no_name_mangle = false;
  733. if (e->kind == Entity_Variable) {
  734. bool is_foreign = e->Variable.is_foreign;
  735. bool is_export = e->Variable.is_export;
  736. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  737. if (e->Variable.link_name.len > 0) {
  738. return e->Variable.link_name;
  739. }
  740. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  741. return e->Procedure.link_name;
  742. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  743. no_name_mangle = true;
  744. }
  745. if (!no_name_mangle) {
  746. name = lb_mangle_name(m, e);
  747. }
  748. if (name.len == 0) {
  749. name = e->token.string;
  750. }
  751. if (e->kind == Entity_TypeName) {
  752. e->TypeName.ir_mangled_name = name;
  753. } else if (e->kind == Entity_Procedure) {
  754. e->Procedure.link_name = name;
  755. }
  756. return name;
  757. }
  758. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  759. Type *original_type = type;
  760. LLVMContextRef ctx = m->ctx;
  761. i64 size = type_size_of(type); // Check size
  762. GB_ASSERT(type != t_invalid);
  763. switch (type->kind) {
  764. case Type_Basic:
  765. switch (type->Basic.kind) {
  766. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  767. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  768. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  769. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  770. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  771. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  772. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  773. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  774. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  775. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  776. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  777. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  778. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  779. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  780. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  781. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  782. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  783. // Basic_f16,
  784. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  785. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  786. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  787. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  788. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  789. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  790. // Basic_complex32,
  791. case Basic_complex64:
  792. {
  793. char const *name = "..complex64";
  794. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  795. if (type != nullptr) {
  796. return type;
  797. }
  798. type = LLVMStructCreateNamed(ctx, name);
  799. LLVMTypeRef fields[2] = {
  800. lb_type(m, t_f32),
  801. lb_type(m, t_f32),
  802. };
  803. LLVMStructSetBody(type, fields, 2, false);
  804. return type;
  805. }
  806. case Basic_complex128:
  807. {
  808. char const *name = "..complex128";
  809. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  810. if (type != nullptr) {
  811. return type;
  812. }
  813. type = LLVMStructCreateNamed(ctx, name);
  814. LLVMTypeRef fields[2] = {
  815. lb_type(m, t_f64),
  816. lb_type(m, t_f64),
  817. };
  818. LLVMStructSetBody(type, fields, 2, false);
  819. return type;
  820. }
  821. case Basic_quaternion128:
  822. {
  823. char const *name = "..quaternion128";
  824. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  825. if (type != nullptr) {
  826. return type;
  827. }
  828. type = LLVMStructCreateNamed(ctx, name);
  829. LLVMTypeRef fields[4] = {
  830. lb_type(m, t_f32),
  831. lb_type(m, t_f32),
  832. lb_type(m, t_f32),
  833. lb_type(m, t_f32),
  834. };
  835. LLVMStructSetBody(type, fields, 4, false);
  836. return type;
  837. }
  838. case Basic_quaternion256:
  839. {
  840. char const *name = "..quaternion256";
  841. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  842. if (type != nullptr) {
  843. return type;
  844. }
  845. type = LLVMStructCreateNamed(ctx, name);
  846. LLVMTypeRef fields[4] = {
  847. lb_type(m, t_f64),
  848. lb_type(m, t_f64),
  849. lb_type(m, t_f64),
  850. lb_type(m, t_f64),
  851. };
  852. LLVMStructSetBody(type, fields, 4, false);
  853. return type;
  854. }
  855. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  856. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  857. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  858. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  859. case Basic_string:
  860. {
  861. char const *name = "..string";
  862. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  863. if (type != nullptr) {
  864. return type;
  865. }
  866. type = LLVMStructCreateNamed(ctx, name);
  867. LLVMTypeRef fields[2] = {
  868. LLVMPointerType(lb_type(m, t_u8), 0),
  869. lb_type(m, t_int),
  870. };
  871. LLVMStructSetBody(type, fields, 2, false);
  872. return type;
  873. }
  874. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  875. case Basic_any:
  876. {
  877. char const *name = "..any";
  878. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  879. if (type != nullptr) {
  880. return type;
  881. }
  882. type = LLVMStructCreateNamed(ctx, name);
  883. LLVMTypeRef fields[2] = {
  884. lb_type(m, t_rawptr),
  885. lb_type(m, t_typeid),
  886. };
  887. LLVMStructSetBody(type, fields, 2, false);
  888. return type;
  889. }
  890. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  891. // Endian Specific Types
  892. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  893. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  894. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  895. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  896. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  897. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  898. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  899. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  900. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  901. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  902. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  903. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  904. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  905. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  906. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  907. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  908. // Untyped types
  909. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  910. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  911. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  912. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  913. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  914. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  915. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  916. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  917. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  918. }
  919. break;
  920. case Type_Named:
  921. {
  922. Type *base = base_type(type->Named.base);
  923. switch (base->kind) {
  924. case Type_Basic:
  925. return lb_type_internal(m, base);
  926. case Type_Named:
  927. case Type_Generic:
  928. GB_PANIC("INVALID TYPE");
  929. break;
  930. case Type_Pointer:
  931. case Type_Array:
  932. case Type_EnumeratedArray:
  933. case Type_Slice:
  934. case Type_DynamicArray:
  935. case Type_Map:
  936. case Type_Enum:
  937. case Type_BitSet:
  938. case Type_SimdVector:
  939. return lb_type_internal(m, base);
  940. // TODO(bill): Deal with this correctly. Can this be named?
  941. case Type_Proc:
  942. return lb_type_internal(m, base);
  943. case Type_Tuple:
  944. return lb_type_internal(m, base);
  945. }
  946. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  947. if (found) {
  948. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  949. if (kind == LLVMStructTypeKind) {
  950. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  951. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  952. if (llvm_type != nullptr) {
  953. return llvm_type;
  954. }
  955. llvm_type = LLVMStructCreateNamed(ctx, name);
  956. map_set(&m->types, hash_type(type), llvm_type);
  957. lb_clone_struct_type(llvm_type, *found);
  958. return llvm_type;
  959. }
  960. }
  961. switch (base->kind) {
  962. case Type_Struct:
  963. case Type_Union:
  964. {
  965. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  966. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  967. if (llvm_type != nullptr) {
  968. return llvm_type;
  969. }
  970. llvm_type = LLVMStructCreateNamed(ctx, name);
  971. map_set(&m->types, hash_type(type), llvm_type);
  972. lb_clone_struct_type(llvm_type, lb_type(m, base));
  973. return llvm_type;
  974. }
  975. }
  976. return lb_type_internal(m, base);
  977. }
  978. case Type_Pointer:
  979. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  980. case Type_Array: {
  981. m->internal_type_level -= 1;
  982. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  983. m->internal_type_level += 1;
  984. return t;
  985. }
  986. case Type_EnumeratedArray: {
  987. m->internal_type_level -= 1;
  988. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  989. m->internal_type_level += 1;
  990. return t;
  991. }
  992. case Type_Slice:
  993. {
  994. LLVMTypeRef fields[2] = {
  995. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  996. lb_type(m, t_int), // len
  997. };
  998. return LLVMStructTypeInContext(ctx, fields, 2, false);
  999. }
  1000. break;
  1001. case Type_DynamicArray:
  1002. {
  1003. LLVMTypeRef fields[4] = {
  1004. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1005. lb_type(m, t_int), // len
  1006. lb_type(m, t_int), // cap
  1007. lb_type(m, t_allocator), // allocator
  1008. };
  1009. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1010. }
  1011. break;
  1012. case Type_Map:
  1013. return lb_type(m, type->Map.internal_type);
  1014. case Type_Struct:
  1015. {
  1016. if (type->Struct.is_raw_union) {
  1017. unsigned field_count = 2;
  1018. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1019. i64 alignment = type_align_of(type);
  1020. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1021. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1022. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1023. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1024. }
  1025. isize offset = 0;
  1026. if (type->Struct.custom_align > 0) {
  1027. offset = 1;
  1028. }
  1029. m->internal_type_level += 1;
  1030. defer (m->internal_type_level -= 1);
  1031. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1032. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1033. for_array(i, type->Struct.fields) {
  1034. Entity *field = type->Struct.fields[i];
  1035. fields[i+offset] = lb_type(m, field->type);
  1036. }
  1037. if (type->Struct.custom_align > 0) {
  1038. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1039. }
  1040. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1041. }
  1042. break;
  1043. case Type_Union:
  1044. if (type->Union.variants.count == 0) {
  1045. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1046. } else {
  1047. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1048. // LLVM takes the first element's alignment as the entire alignment (like C)
  1049. i64 align = type_align_of(type);
  1050. i64 size = type_size_of(type);
  1051. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1052. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1053. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1054. }
  1055. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1056. LLVMTypeRef fields[3] = {};
  1057. unsigned field_count = 1;
  1058. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1059. if (is_type_union_maybe_pointer(type)) {
  1060. field_count += 1;
  1061. fields[1] = lb_type(m, type->Union.variants[0]);
  1062. } else {
  1063. field_count += 2;
  1064. if (block_size == align) {
  1065. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1066. } else {
  1067. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1068. }
  1069. fields[2] = lb_type(m, union_tag_type(type));
  1070. }
  1071. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1072. }
  1073. break;
  1074. case Type_Enum:
  1075. return lb_type(m, base_enum_type(type));
  1076. case Type_Tuple:
  1077. if (type->Tuple.variables.count == 1) {
  1078. return lb_type(m, type->Tuple.variables[0]->type);
  1079. } else {
  1080. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1081. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1082. for_array(i, type->Tuple.variables) {
  1083. Entity *field = type->Tuple.variables[i];
  1084. LLVMTypeRef param_type = nullptr;
  1085. param_type = lb_type(m, field->type);
  1086. fields[i] = param_type;
  1087. }
  1088. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1089. }
  1090. case Type_Proc:
  1091. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1092. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1093. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1094. } else {
  1095. unsigned param_count = 0;
  1096. if (type->Proc.calling_convention == ProcCC_Odin) {
  1097. param_count += 1;
  1098. }
  1099. if (type->Proc.param_count != 0) {
  1100. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1101. for_array(i, type->Proc.params->Tuple.variables) {
  1102. Entity *e = type->Proc.params->Tuple.variables[i];
  1103. if (e->kind != Entity_Variable) {
  1104. continue;
  1105. }
  1106. param_count += 1;
  1107. }
  1108. }
  1109. m->internal_type_level += 1;
  1110. defer (m->internal_type_level -= 1);
  1111. LLVMTypeRef ret = nullptr;
  1112. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1113. if (type->Proc.result_count != 0) {
  1114. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1115. ret = lb_type(m, single_ret);
  1116. if (ret != nullptr) {
  1117. if (is_type_boolean(single_ret) &&
  1118. is_calling_convention_none(type->Proc.calling_convention) &&
  1119. type_size_of(single_ret) <= 1) {
  1120. ret = LLVMInt1TypeInContext(m->ctx);
  1121. }
  1122. }
  1123. }
  1124. isize param_index = 0;
  1125. if (type->Proc.param_count != 0) {
  1126. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1127. for_array(i, type->Proc.params->Tuple.variables) {
  1128. Entity *e = type->Proc.params->Tuple.variables[i];
  1129. if (e->kind != Entity_Variable) {
  1130. continue;
  1131. }
  1132. Type *e_type = reduce_tuple_to_single_type(e->type);
  1133. LLVMTypeRef param_type = nullptr;
  1134. if (is_type_boolean(e_type) &&
  1135. type_size_of(e_type) <= 1) {
  1136. param_type = LLVMInt1TypeInContext(m->ctx);
  1137. } else {
  1138. if (is_type_proc(e_type)) {
  1139. param_type = lb_type(m, t_rawptr);
  1140. } else {
  1141. param_type = lb_type(m, e_type);
  1142. }
  1143. }
  1144. params[param_index++] = param_type;
  1145. }
  1146. }
  1147. if (param_index < param_count) {
  1148. params[param_index++] = lb_type(m, t_rawptr);
  1149. // params[param_index++] = lb_type(m, t_context_ptr);
  1150. }
  1151. GB_ASSERT(param_index == param_count);
  1152. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1153. map_set(&m->function_type_map, hash_type(type), ft);
  1154. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1155. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1156. // LLVMTypeRef new_ret = LLVMGetReturnType(new_abi_fn_type);
  1157. // LLVMTypeRef old_ret = LLVMGetReturnType(old_abi_fn_type);
  1158. // unsigned new_count = LLVMCountParamTypes(new_abi_fn_type);
  1159. // unsigned old_count = LLVMCountParamTypes(old_abi_fn_type);
  1160. // GB_ASSERT_MSG(new_count == old_count, "%u %u, %s %s", new_count, old_count, LLVMPrintTypeToString(new_abi_fn_type), LLVMPrintTypeToString(old_abi_fn_type));
  1161. return new_abi_fn_ptr_type;
  1162. }
  1163. break;
  1164. case Type_BitSet:
  1165. {
  1166. Type *ut = bit_set_to_int(type);
  1167. return lb_type(m, ut);
  1168. }
  1169. case Type_SimdVector:
  1170. if (type->SimdVector.is_x86_mmx) {
  1171. return LLVMX86MMXTypeInContext(ctx);
  1172. }
  1173. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1174. case Type_RelativePointer:
  1175. return lb_type_internal(m, type->RelativePointer.base_integer);
  1176. case Type_RelativeSlice:
  1177. {
  1178. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1179. unsigned field_count = 2;
  1180. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1181. fields[0] = base_integer;
  1182. fields[1] = base_integer;
  1183. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1184. }
  1185. }
  1186. GB_PANIC("Invalid type %s", type_to_string(type));
  1187. return LLVMInt32TypeInContext(ctx);
  1188. }
  1189. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1190. type = default_type(type);
  1191. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1192. if (found) {
  1193. return *found;
  1194. }
  1195. LLVMTypeRef llvm_type = nullptr;
  1196. m->internal_type_level += 1;
  1197. llvm_type = lb_type_internal(m, type);
  1198. m->internal_type_level -= 1;
  1199. if (m->internal_type_level == 0) {
  1200. map_set(&m->types, hash_type(type), llvm_type);
  1201. if (is_type_named(type)) {
  1202. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1203. }
  1204. }
  1205. return llvm_type;
  1206. }
  1207. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1208. Type *original_type = type;
  1209. LLVMContextRef ctx = m->ctx;
  1210. i64 size = type_size_of(type); // Check size
  1211. GB_ASSERT(type != t_invalid);
  1212. switch (type->kind) {
  1213. case Type_Basic:
  1214. switch (type->Basic.kind) {
  1215. case Basic_llvm_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "llvm bool", 9, 1, 0, LLVMDIFlagZero);
  1216. case Basic_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "bool", 4, 8, 0, LLVMDIFlagZero);
  1217. case Basic_b8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b8", 2, 8, 0, LLVMDIFlagZero);
  1218. case Basic_b16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b16", 3, 16, 0, LLVMDIFlagZero);
  1219. case Basic_b32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b32", 3, 32, 0, LLVMDIFlagZero);
  1220. case Basic_b64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b64", 3, 64, 0, LLVMDIFlagZero);
  1221. case Basic_i8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i8", 2, 8, 0, LLVMDIFlagZero);
  1222. case Basic_u8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u8", 2, 8, 0, LLVMDIFlagZero);
  1223. case Basic_i16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16", 3, 16, 0, LLVMDIFlagZero);
  1224. case Basic_u16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16", 3, 16, 0, LLVMDIFlagZero);
  1225. case Basic_i32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32", 3, 32, 0, LLVMDIFlagZero);
  1226. case Basic_u32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32", 3, 32, 0, LLVMDIFlagZero);
  1227. case Basic_i64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64", 3, 64, 0, LLVMDIFlagZero);
  1228. case Basic_u64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64", 3, 64, 0, LLVMDIFlagZero);
  1229. case Basic_i128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128", 4, 128, 0, LLVMDIFlagZero);
  1230. case Basic_u128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128", 4, 128, 0, LLVMDIFlagZero);
  1231. case Basic_rune: return LLVMDIBuilderCreateBasicType(m->debug_builder, "rune", 4, 32, 0, LLVMDIFlagZero);
  1232. // Basic_f16,
  1233. case Basic_f32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32", 3, 32, 0, LLVMDIFlagZero);
  1234. case Basic_f64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64", 3, 64, 0, LLVMDIFlagZero);
  1235. // Basic_complex32,
  1236. case Basic_complex64:
  1237. {
  1238. return nullptr;
  1239. // char const *name = "..complex64";
  1240. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1241. // if (type != nullptr) {
  1242. // return type;
  1243. // }
  1244. // type = LLVMStructCreateNamed(ctx, name);
  1245. // LLVMTypeRef fields[2] = {
  1246. // lb_type(m, t_f32),
  1247. // lb_type(m, t_f32),
  1248. // };
  1249. // LLVMStructSetBody(type, fields, 2, false);
  1250. // return type;
  1251. }
  1252. case Basic_complex128:
  1253. {
  1254. return nullptr;
  1255. // char const *name = "..complex128";
  1256. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1257. // if (type != nullptr) {
  1258. // return type;
  1259. // }
  1260. // type = LLVMStructCreateNamed(ctx, name);
  1261. // LLVMTypeRef fields[2] = {
  1262. // lb_type(m, t_f64),
  1263. // lb_type(m, t_f64),
  1264. // };
  1265. // LLVMStructSetBody(type, fields, 2, false);
  1266. // return type;
  1267. }
  1268. case Basic_quaternion128:
  1269. {
  1270. return nullptr;
  1271. // char const *name = "..quaternion128";
  1272. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1273. // if (type != nullptr) {
  1274. // return type;
  1275. // }
  1276. // type = LLVMStructCreateNamed(ctx, name);
  1277. // LLVMTypeRef fields[4] = {
  1278. // lb_type(m, t_f32),
  1279. // lb_type(m, t_f32),
  1280. // lb_type(m, t_f32),
  1281. // lb_type(m, t_f32),
  1282. // };
  1283. // LLVMStructSetBody(type, fields, 4, false);
  1284. // return type;
  1285. }
  1286. case Basic_quaternion256:
  1287. {
  1288. return nullptr;
  1289. // char const *name = "..quaternion256";
  1290. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1291. // if (type != nullptr) {
  1292. // return type;
  1293. // }
  1294. // type = LLVMStructCreateNamed(ctx, name);
  1295. // LLVMTypeRef fields[4] = {
  1296. // lb_type(m, t_f64),
  1297. // lb_type(m, t_f64),
  1298. // lb_type(m, t_f64),
  1299. // lb_type(m, t_f64),
  1300. // };
  1301. // LLVMStructSetBody(type, fields, 4, false);
  1302. // return type;
  1303. }
  1304. case Basic_int: return LLVMDIBuilderCreateBasicType(m->debug_builder, "int", 3, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1305. case Basic_uint: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uint", 4, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1306. case Basic_uintptr: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uintptr", 7, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1307. case Basic_rawptr:
  1308. return nullptr;
  1309. // return LLVMPointerType(LLVMInt8Type(), 0);
  1310. case Basic_string:
  1311. {
  1312. return nullptr;
  1313. // char const *name = "..string";
  1314. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1315. // if (type != nullptr) {
  1316. // return type;
  1317. // }
  1318. // type = LLVMStructCreateNamed(ctx, name);
  1319. // LLVMTypeRef fields[2] = {
  1320. // LLVMPointerType(lb_type(m, t_u8), 0),
  1321. // lb_type(m, t_int),
  1322. // };
  1323. // LLVMStructSetBody(type, fields, 2, false);
  1324. // return type;
  1325. }
  1326. case Basic_cstring:
  1327. return nullptr;
  1328. // return LLVMPointerType(LLVMInt8Type(), 0);
  1329. case Basic_any:
  1330. {
  1331. return nullptr;
  1332. // char const *name = "..any";
  1333. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1334. // if (type != nullptr) {
  1335. // return type;
  1336. // }
  1337. // type = LLVMStructCreateNamed(ctx, name);
  1338. // LLVMTypeRef fields[2] = {
  1339. // lb_type(m, t_rawptr),
  1340. // lb_type(m, t_typeid),
  1341. // };
  1342. // LLVMStructSetBody(type, fields, 2, false);
  1343. // return type;
  1344. }
  1345. case Basic_typeid: return LLVMDIBuilderCreateBasicType(m->debug_builder, "typeid", 6, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1346. // Endian Specific Types
  1347. case Basic_i16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1348. case Basic_u16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1349. case Basic_i32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1350. case Basic_u32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1351. case Basic_i64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1352. case Basic_u64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1353. case Basic_i128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1354. case Basic_u128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1355. case Basic_i16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1356. case Basic_u16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1357. case Basic_i32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1358. case Basic_u32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1359. case Basic_i64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1360. case Basic_u64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1361. case Basic_i128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1362. case Basic_u128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1363. // Untyped types
  1364. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1365. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1366. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1367. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1368. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1369. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1370. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1371. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1372. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1373. }
  1374. break;
  1375. case Type_Named:
  1376. {
  1377. return nullptr;
  1378. // Type *base = base_type(type->Named.base);
  1379. // switch (base->kind) {
  1380. // case Type_Basic:
  1381. // return lb_type(m, base);
  1382. // case Type_Named:
  1383. // case Type_Generic:
  1384. // case Type_BitFieldValue:
  1385. // GB_PANIC("INVALID TYPE");
  1386. // break;
  1387. // case Type_Opaque:
  1388. // return lb_type(m, base->Opaque.elem);
  1389. // case Type_Pointer:
  1390. // case Type_Array:
  1391. // case Type_EnumeratedArray:
  1392. // case Type_Slice:
  1393. // case Type_DynamicArray:
  1394. // case Type_Map:
  1395. // case Type_Enum:
  1396. // case Type_BitSet:
  1397. // case Type_SimdVector:
  1398. // return lb_type(m, base);
  1399. // // TODO(bill): Deal with this correctly. Can this be named?
  1400. // case Type_Proc:
  1401. // return lb_type(m, base);
  1402. // case Type_Tuple:
  1403. // return lb_type(m, base);
  1404. // }
  1405. // LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1406. // if (found) {
  1407. // LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1408. // if (kind == LLVMStructTypeKind) {
  1409. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1410. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1411. // if (llvm_type != nullptr) {
  1412. // return llvm_type;
  1413. // }
  1414. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1415. // map_set(&m->types, hash_type(type), llvm_type);
  1416. // lb_clone_struct_type(llvm_type, *found);
  1417. // return llvm_type;
  1418. // }
  1419. // }
  1420. // switch (base->kind) {
  1421. // case Type_Struct:
  1422. // case Type_Union:
  1423. // case Type_BitField:
  1424. // {
  1425. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1426. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1427. // if (llvm_type != nullptr) {
  1428. // return llvm_type;
  1429. // }
  1430. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1431. // map_set(&m->types, hash_type(type), llvm_type);
  1432. // lb_clone_struct_type(llvm_type, lb_type(m, base));
  1433. // return llvm_type;
  1434. // }
  1435. // }
  1436. // return lb_type(m, base);
  1437. }
  1438. case Type_Pointer:
  1439. return nullptr;
  1440. // return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1441. case Type_Array:
  1442. return nullptr;
  1443. // return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1444. case Type_EnumeratedArray:
  1445. return nullptr;
  1446. // return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1447. case Type_Slice:
  1448. {
  1449. return nullptr;
  1450. // LLVMTypeRef fields[2] = {
  1451. // LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1452. // lb_type(m, t_int), // len
  1453. // };
  1454. // return LLVMStructTypeInContext(ctx, fields, 2, false);
  1455. }
  1456. break;
  1457. case Type_DynamicArray:
  1458. {
  1459. return nullptr;
  1460. // LLVMTypeRef fields[4] = {
  1461. // LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1462. // lb_type(m, t_int), // len
  1463. // lb_type(m, t_int), // cap
  1464. // lb_type(m, t_allocator), // allocator
  1465. // };
  1466. // return LLVMStructTypeInContext(ctx, fields, 4, false);
  1467. }
  1468. break;
  1469. case Type_Map:
  1470. return nullptr;
  1471. // return lb_type(m, type->Map.internal_type);
  1472. case Type_Struct:
  1473. {
  1474. return nullptr;
  1475. // if (type->Struct.is_raw_union) {
  1476. // unsigned field_count = 2;
  1477. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1478. // i64 alignment = type_align_of(type);
  1479. // unsigned size_of_union = cast(unsigned)type_size_of(type);
  1480. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1481. // fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1482. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1483. // }
  1484. // isize offset = 0;
  1485. // if (type->Struct.custom_align > 0) {
  1486. // offset = 1;
  1487. // }
  1488. // unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1489. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1490. // GB_ASSERT(fields != nullptr);
  1491. // defer (gb_free(heap_allocator(), fields));
  1492. // for_array(i, type->Struct.fields) {
  1493. // Entity *field = type->Struct.fields[i];
  1494. // fields[i+offset] = lb_type(m, field->type);
  1495. // }
  1496. // if (type->Struct.custom_align > 0) {
  1497. // fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1498. // }
  1499. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1500. }
  1501. break;
  1502. case Type_Union:
  1503. return nullptr;
  1504. // if (type->Union.variants.count == 0) {
  1505. // return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1506. // } else {
  1507. // // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1508. // // LLVM takes the first element's alignment as the entire alignment (like C)
  1509. // i64 align = type_align_of(type);
  1510. // i64 size = type_size_of(type);
  1511. // if (is_type_union_maybe_pointer_original_alignment(type)) {
  1512. // LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1513. // return LLVMStructTypeInContext(ctx, fields, 1, false);
  1514. // }
  1515. // unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1516. // LLVMTypeRef fields[3] = {};
  1517. // unsigned field_count = 1;
  1518. // fields[0] = lb_alignment_prefix_type_hack(m, align);
  1519. // if (is_type_union_maybe_pointer(type)) {
  1520. // field_count += 1;
  1521. // fields[1] = lb_type(m, type->Union.variants[0]);
  1522. // } else {
  1523. // field_count += 2;
  1524. // if (block_size == align) {
  1525. // fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1526. // } else {
  1527. // fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1528. // }
  1529. // fields[2] = lb_type(m, union_tag_type(type));
  1530. // }
  1531. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1532. // }
  1533. // break;
  1534. case Type_Enum:
  1535. return nullptr;
  1536. // return lb_type(m, base_enum_type(type));
  1537. case Type_Tuple:
  1538. return nullptr;
  1539. // if (type->Tuple.variables.count == 1) {
  1540. // return lb_type(m, type->Tuple.variables[0]->type);
  1541. // } else {
  1542. // unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1543. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1544. // defer (gb_free(heap_allocator(), fields));
  1545. // for_array(i, type->Tuple.variables) {
  1546. // Entity *field = type->Tuple.variables[i];
  1547. // fields[i] = lb_type(m, field->type);
  1548. // }
  1549. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1550. // }
  1551. case Type_Proc:
  1552. {
  1553. return nullptr;
  1554. // set_procedure_abi_types(type);
  1555. // LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1556. // isize offset = 0;
  1557. // if (type->Proc.return_by_pointer) {
  1558. // offset = 1;
  1559. // } else if (type->Proc.abi_compat_result_type != nullptr) {
  1560. // return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1561. // }
  1562. // isize extra_param_count = offset;
  1563. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1564. // extra_param_count += 1;
  1565. // }
  1566. // isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1567. // LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1568. // defer (gb_free(heap_allocator(), param_types));
  1569. // isize param_index = offset;
  1570. // for_array(i, type->Proc.abi_compat_params) {
  1571. // Type *param = type->Proc.abi_compat_params[i];
  1572. // if (param == nullptr) {
  1573. // continue;
  1574. // }
  1575. // param_types[param_index++] = lb_type(m, param);
  1576. // }
  1577. // if (type->Proc.return_by_pointer) {
  1578. // param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  1579. // }
  1580. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1581. // param_types[param_index++] = lb_type(m, t_context_ptr);
  1582. // }
  1583. // LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  1584. // return LLVMPointerType(t, 0);
  1585. }
  1586. break;
  1587. case Type_BitSet:
  1588. return nullptr;
  1589. // return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)type_size_of(type));
  1590. case Type_SimdVector:
  1591. return nullptr;
  1592. // if (type->SimdVector.is_x86_mmx) {
  1593. // return LLVMX86MMXTypeInContext(ctx);
  1594. // }
  1595. // return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1596. }
  1597. GB_PANIC("Invalid type %s", type_to_string(type));
  1598. return nullptr;
  1599. }
  1600. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1601. LLVMTypeRef t = lb_type(m, type);
  1602. LLVMMetadataRef *found = map_get(&m->debug_values, hash_pointer(t));
  1603. if (found != nullptr) {
  1604. return *found;
  1605. }
  1606. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1607. map_set(&m->debug_values, hash_pointer(t), dt);
  1608. return dt;
  1609. }
  1610. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1611. if (e != nullptr) {
  1612. map_set(&m->values, hash_entity(e), val);
  1613. }
  1614. }
  1615. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1616. if (name.len > 0) {
  1617. string_map_set(&m->members, name, val);
  1618. }
  1619. }
  1620. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1621. string_map_set(&m->members, key, val);
  1622. }
  1623. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1624. if (p->entity != nullptr) {
  1625. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1626. }
  1627. string_map_set(&m->procedures, p->name, p);
  1628. }
  1629. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  1630. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  1631. LLVMValueRef values[2] = {
  1632. str_elem.value,
  1633. str_len.value,
  1634. };
  1635. lbValue res = {};
  1636. res.type = t_string;
  1637. res.value = LLVMConstNamedStruct(lb_type(p->module, t_string), values, gb_count_of(values));
  1638. return res;
  1639. } else {
  1640. lbAddr res = lb_add_local_generated(p, t_string, false);
  1641. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  1642. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  1643. return lb_addr_load(p, res);
  1644. }
  1645. }
  1646. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1647. String s = make_string_c(name);
  1648. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  1649. // and the current LLVM C API does not expose this functionality yet.
  1650. // It is better to ignore the attributes for the time being
  1651. if (s == "byval") {
  1652. return nullptr;
  1653. } else if (s == "byref") {
  1654. return nullptr;
  1655. } else if (s == "preallocated") {
  1656. return nullptr;
  1657. } else if (s == "sret") {
  1658. return nullptr;
  1659. }
  1660. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1661. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1662. return LLVMCreateEnumAttribute(ctx, kind, value);
  1663. }
  1664. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1665. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1666. GB_ASSERT(attr != nullptr);
  1667. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1668. }
  1669. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1670. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  1671. }
  1672. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  1673. if (p->abi_function_type != nullptr) {
  1674. return;
  1675. }
  1676. auto hash = hash_type(p->type);
  1677. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  1678. if (ft_found == nullptr) {
  1679. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  1680. ft_found = map_get(&m->function_type_map, hash);
  1681. }
  1682. GB_ASSERT(ft_found != nullptr);
  1683. p->abi_function_type = *ft_found;
  1684. GB_ASSERT(p->abi_function_type != nullptr);
  1685. }
  1686. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  1687. GB_ASSERT(entity != nullptr);
  1688. String link_name = lb_get_entity_name(m, entity);
  1689. {
  1690. StringHashKey key = string_hash_string(link_name);
  1691. lbValue *found = string_map_get(&m->members, key);
  1692. if (found) {
  1693. lb_add_entity(m, entity, *found);
  1694. lbProcedure **p_found = string_map_get(&m->procedures, key);
  1695. GB_ASSERT(p_found != nullptr);
  1696. return *p_found;
  1697. }
  1698. }
  1699. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1700. p->module = m;
  1701. entity->code_gen_module = m;
  1702. entity->code_gen_procedure = p;
  1703. p->entity = entity;
  1704. p->name = link_name;
  1705. DeclInfo *decl = entity->decl_info;
  1706. ast_node(pl, ProcLit, decl->proc_lit);
  1707. Type *pt = base_type(entity->type);
  1708. GB_ASSERT(pt->kind == Type_Proc);
  1709. set_procedure_abi_types(entity->type);
  1710. p->type = entity->type;
  1711. p->type_expr = decl->type_expr;
  1712. p->body = pl->body;
  1713. p->tags = pt->Proc.tags;
  1714. p->inlining = ProcInlining_none;
  1715. p->is_foreign = entity->Procedure.is_foreign;
  1716. p->is_export = entity->Procedure.is_export;
  1717. p->is_entry_point = false;
  1718. gbAllocator a = heap_allocator();
  1719. p->children.allocator = a;
  1720. p->params.allocator = a;
  1721. p->defer_stmts.allocator = a;
  1722. p->blocks.allocator = a;
  1723. p->branch_blocks.allocator = a;
  1724. p->context_stack.allocator = a;
  1725. if (p->is_foreign) {
  1726. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  1727. }
  1728. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  1729. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1730. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1731. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1732. lb_ensure_abi_function_type(m, p);
  1733. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  1734. if (false) {
  1735. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1736. // TODO(bill): Clean up this logic
  1737. if (build_context.metrics.os != TargetOs_js) {
  1738. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1739. }
  1740. LLVMSetFunctionCallConv(p->value, cc_kind);
  1741. }
  1742. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1743. // // TODO(bill): Clean up this logic
  1744. // if (build_context.metrics.os != TargetOs_js) {
  1745. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1746. // }
  1747. // LLVMSetFunctionCallConv(p->value, cc_kind);
  1748. lbValue proc_value = {p->value, p->type};
  1749. lb_add_entity(m, entity, proc_value);
  1750. lb_add_member(m, p->name, proc_value);
  1751. lb_add_procedure_value(m, p);
  1752. if (p->is_export) {
  1753. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  1754. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  1755. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  1756. if (build_context.metrics.os == TargetOs_js) {
  1757. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  1758. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  1759. }
  1760. }
  1761. if (p->is_foreign) {
  1762. if (build_context.metrics.os == TargetOs_js) {
  1763. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  1764. char const *module_name = "env";
  1765. if (entity->Procedure.foreign_library != nullptr) {
  1766. Entity *foreign_library = entity->Procedure.foreign_library;
  1767. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1768. if (foreign_library->LibraryName.paths.count > 0) {
  1769. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  1770. }
  1771. }
  1772. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  1773. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  1774. }
  1775. }
  1776. // NOTE(bill): offset==0 is the return value
  1777. isize offset = 1;
  1778. if (pt->Proc.return_by_pointer) {
  1779. offset = 2;
  1780. }
  1781. isize parameter_index = 0;
  1782. if (pt->Proc.param_count) {
  1783. TypeTuple *params = &pt->Proc.params->Tuple;
  1784. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1785. Entity *e = params->variables[i];
  1786. Type *original_type = e->type;
  1787. Type *abi_type = pt->Proc.abi_compat_params[i];
  1788. if (e->kind != Entity_Variable) continue;
  1789. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1790. continue;
  1791. }
  1792. if (is_type_tuple(abi_type)) {
  1793. for_array(j, abi_type->Tuple.variables) {
  1794. Type *tft = abi_type->Tuple.variables[j]->type;
  1795. if (e->flags&EntityFlag_NoAlias) {
  1796. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1797. }
  1798. }
  1799. parameter_index += abi_type->Tuple.variables.count;
  1800. } else {
  1801. if (e->flags&EntityFlag_NoAlias) {
  1802. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1803. }
  1804. parameter_index += 1;
  1805. }
  1806. }
  1807. }
  1808. { // Debug Information
  1809. unsigned line = cast(unsigned)entity->token.pos.line;
  1810. LLVMMetadataRef file = nullptr;
  1811. if (entity->file != nullptr) {
  1812. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1813. }
  1814. LLVMMetadataRef scope = nullptr;
  1815. LLVMMetadataRef type = nullptr;
  1816. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1817. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1818. cast(char const *)entity->token.string.text, entity->token.string.len,
  1819. cast(char const *)p->name.text, p->name.len,
  1820. file, line, type,
  1821. true, p->body == nullptr,
  1822. line, LLVMDIFlagZero, false
  1823. );
  1824. GB_ASSERT(res != nullptr);
  1825. map_set(&m->debug_values, hash_pointer(p), res);
  1826. }
  1827. return p;
  1828. }
  1829. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1830. {
  1831. lbValue *found = string_map_get(&m->members, link_name);
  1832. GB_ASSERT(found == nullptr);
  1833. }
  1834. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1835. p->module = m;
  1836. p->name = link_name;
  1837. p->type = type;
  1838. p->type_expr = nullptr;
  1839. p->body = nullptr;
  1840. p->tags = 0;
  1841. p->inlining = ProcInlining_none;
  1842. p->is_foreign = false;
  1843. p->is_export = false;
  1844. p->is_entry_point = false;
  1845. gbAllocator a = permanent_allocator();
  1846. p->children.allocator = a;
  1847. p->params.allocator = a;
  1848. p->defer_stmts.allocator = a;
  1849. p->blocks.allocator = a;
  1850. p->branch_blocks.allocator = a;
  1851. p->context_stack.allocator = a;
  1852. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  1853. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1854. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1855. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1856. Type *pt = p->type;
  1857. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1858. // TODO(bill): Clean up this logic
  1859. if (build_context.metrics.os != TargetOs_js) {
  1860. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1861. }
  1862. LLVMSetFunctionCallConv(p->value, cc_kind);
  1863. lbValue proc_value = {p->value, p->type};
  1864. lb_add_member(m, p->name, proc_value);
  1865. lb_add_procedure_value(m, p);
  1866. // NOTE(bill): offset==0 is the return value
  1867. isize offset = 1;
  1868. if (pt->Proc.return_by_pointer) {
  1869. lb_add_proc_attribute_at_index(p, 1, "sret");
  1870. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1871. offset = 2;
  1872. }
  1873. isize parameter_index = 0;
  1874. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1875. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1876. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1877. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1878. }
  1879. return p;
  1880. }
  1881. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  1882. lbParamPasskind kind = lbParamPass_Value;
  1883. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  1884. if (is_type_pointer(abi_type)) {
  1885. GB_ASSERT(e->kind == Entity_Variable);
  1886. Type *av = core_type(type_deref(abi_type));
  1887. if (are_types_identical(av, core_type(e->type))) {
  1888. kind = lbParamPass_Pointer;
  1889. if (e->flags&EntityFlag_Value) {
  1890. kind = lbParamPass_ConstRef;
  1891. }
  1892. } else {
  1893. kind = lbParamPass_BitCast;
  1894. }
  1895. } else if (is_type_integer(abi_type)) {
  1896. kind = lbParamPass_Integer;
  1897. } else if (abi_type == t_llvm_bool) {
  1898. kind = lbParamPass_Value;
  1899. } else if (is_type_boolean(abi_type)) {
  1900. kind = lbParamPass_Integer;
  1901. } else if (is_type_simd_vector(abi_type)) {
  1902. kind = lbParamPass_BitCast;
  1903. } else if (is_type_float(abi_type)) {
  1904. kind = lbParamPass_BitCast;
  1905. } else if (is_type_tuple(abi_type)) {
  1906. kind = lbParamPass_Tuple;
  1907. } else if (is_type_proc(abi_type)) {
  1908. kind = lbParamPass_Value;
  1909. } else {
  1910. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  1911. }
  1912. }
  1913. if (kind_) *kind_ = kind;
  1914. lbValue res = {};
  1915. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  1916. res.type = abi_type;
  1917. return res;
  1918. }
  1919. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1920. lbParamPasskind kind = lbParamPass_Value;
  1921. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  1922. array_add(&p->params, v);
  1923. lbValue res = {};
  1924. switch (kind) {
  1925. case lbParamPass_Value: {
  1926. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1927. lbValue x = v;
  1928. if (abi_type == t_llvm_bool) {
  1929. x = lb_emit_conv(p, x, t_bool);
  1930. }
  1931. lb_addr_store(p, l, x);
  1932. return x;
  1933. }
  1934. case lbParamPass_Pointer:
  1935. lb_add_entity(p->module, e, v);
  1936. return lb_emit_load(p, v);
  1937. case lbParamPass_Integer: {
  1938. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1939. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  1940. lb_emit_store(p, iptr, v);
  1941. return lb_addr_load(p, l);
  1942. }
  1943. case lbParamPass_ConstRef:
  1944. lb_add_entity(p->module, e, v);
  1945. return lb_emit_load(p, v);
  1946. case lbParamPass_BitCast: {
  1947. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1948. lbValue x = lb_emit_transmute(p, v, e->type);
  1949. lb_addr_store(p, l, x);
  1950. return x;
  1951. }
  1952. case lbParamPass_Tuple: {
  1953. lbAddr l = lb_add_local(p, e->type, e, true, index);
  1954. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  1955. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  1956. if (abi_type->Tuple.variables.count > 0) {
  1957. array_pop(&p->params);
  1958. }
  1959. for_array(i, abi_type->Tuple.variables) {
  1960. Type *t = abi_type->Tuple.variables[i]->type;
  1961. GB_ASSERT(!is_type_tuple(t));
  1962. lbParamPasskind elem_kind = lbParamPass_Value;
  1963. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  1964. array_add(&p->params, elem);
  1965. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  1966. lb_emit_store(p, dst, elem);
  1967. }
  1968. return lb_addr_load(p, l);
  1969. }
  1970. }
  1971. GB_PANIC("Unreachable");
  1972. return {};
  1973. }
  1974. void lb_start_block(lbProcedure *p, lbBlock *b) {
  1975. GB_ASSERT(b != nullptr);
  1976. if (!b->appended) {
  1977. b->appended = true;
  1978. LLVMAppendExistingBasicBlock(p->value, b->block);
  1979. }
  1980. LLVMPositionBuilderAtEnd(p->builder, b->block);
  1981. p->curr_block = b;
  1982. }
  1983. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  1984. LLVMContextRef ctx = p->module->ctx;
  1985. LLVMTypeRef src_type = LLVMTypeOf(val);
  1986. if (src_type == dst_type) {
  1987. return val;
  1988. }
  1989. i64 src_size = lb_sizeof(src_type);
  1990. i64 dst_size = lb_sizeof(dst_type);
  1991. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  1992. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  1993. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  1994. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  1995. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  1996. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  1997. }
  1998. if (src_size != dst_size && (lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  1999. // Okay
  2000. } else {
  2001. GB_ASSERT_MSG(src_size == dst_size, "%s == %s", LLVMPrintTypeToString(src_type), LLVMPrintTypeToString(dst_type));
  2002. }
  2003. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2004. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2005. if (src_kind == dst_kind) {
  2006. if (src_kind == LLVMPointerTypeKind) {
  2007. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2008. } else if (src_kind == LLVMArrayTypeKind) {
  2009. // ignore
  2010. } else if (src_kind != LLVMStructTypeKind) {
  2011. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2012. }
  2013. } else {
  2014. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2015. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2016. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2017. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2018. }
  2019. }
  2020. if (LLVMIsALoadInst(val)) {
  2021. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2022. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2023. return LLVMBuildLoad(p->builder, val_ptr, "");
  2024. } else {
  2025. GB_ASSERT(p->decl_block != p->curr_block);
  2026. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2027. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2028. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2029. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2030. max_align = gb_max(max_align, 4);
  2031. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2032. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2033. LLVMBuildStore(p->builder, val, nptr);
  2034. return LLVMBuildLoad(p->builder, ptr, "");
  2035. }
  2036. }
  2037. void lb_begin_procedure_body(lbProcedure *p) {
  2038. DeclInfo *decl = decl_info_of_entity(p->entity);
  2039. if (decl != nullptr) {
  2040. for_array(i, decl->labels) {
  2041. BlockLabel bl = decl->labels[i];
  2042. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2043. array_add(&p->branch_blocks, bb);
  2044. }
  2045. }
  2046. if (p->tags != 0) {
  2047. u64 in = p->tags;
  2048. u64 out = p->module->state_flags;
  2049. if (in & ProcTag_bounds_check) {
  2050. out |= StateFlag_bounds_check;
  2051. out &= ~StateFlag_no_bounds_check;
  2052. } else if (in & ProcTag_no_bounds_check) {
  2053. out |= StateFlag_no_bounds_check;
  2054. out &= ~StateFlag_bounds_check;
  2055. }
  2056. p->module->state_flags = out;
  2057. }
  2058. p->builder = LLVMCreateBuilder();
  2059. p->decl_block = lb_create_block(p, "decls", true);
  2060. p->entry_block = lb_create_block(p, "entry", true);
  2061. lb_start_block(p, p->entry_block);
  2062. GB_ASSERT(p->type != nullptr);
  2063. lb_ensure_abi_function_type(p->module, p);
  2064. {
  2065. lbFunctionType *ft = p->abi_function_type;
  2066. unsigned param_offset = 0;
  2067. lbValue return_ptr_value = {};
  2068. if (ft->ret.kind == lbArg_Indirect) {
  2069. // NOTE(bill): this must be parameter 0
  2070. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2071. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2072. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2073. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2074. return_ptr_value.type = ptr_type;
  2075. p->return_ptr = lb_addr(return_ptr_value);
  2076. lb_add_entity(p->module, e, return_ptr_value);
  2077. param_offset += 1;
  2078. }
  2079. if (p->type->Proc.params != nullptr) {
  2080. TypeTuple *params = &p->type->Proc.params->Tuple;
  2081. unsigned param_index = 0;
  2082. for_array(i, params->variables) {
  2083. Entity *e = params->variables[i];
  2084. if (e->kind != Entity_Variable) {
  2085. continue;
  2086. }
  2087. lbArgType *arg_type = &ft->args[param_index];
  2088. if (arg_type->kind == lbArg_Ignore) {
  2089. continue;
  2090. } else if (arg_type->kind == lbArg_Direct) {
  2091. lbParamPasskind kind = lbParamPass_Value;
  2092. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2093. if (param_type != arg_type->type) {
  2094. kind = lbParamPass_BitCast;
  2095. }
  2096. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2097. value = OdinLLVMBuildTransmute(p, value, param_type);
  2098. lbValue param = {};
  2099. param.value = value;
  2100. param.type = e->type;
  2101. array_add(&p->params, param);
  2102. if (e->token.string.len != 0) {
  2103. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2104. lb_addr_store(p, l, param);
  2105. }
  2106. param_index += 1;
  2107. } else if (arg_type->kind == lbArg_Indirect) {
  2108. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2109. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2110. lbValue param = {};
  2111. param.value = value;
  2112. param.type = e->type;
  2113. array_add(&p->params, param);
  2114. lbValue ptr = {};
  2115. ptr.value = value_ptr;
  2116. ptr.type = alloc_type_pointer(e->type);
  2117. lb_add_entity(p->module, e, ptr);
  2118. param_index += 1;
  2119. }
  2120. }
  2121. }
  2122. if (p->type->Proc.has_named_results) {
  2123. GB_ASSERT(p->type->Proc.result_count > 0);
  2124. TypeTuple *results = &p->type->Proc.results->Tuple;
  2125. for_array(i, results->variables) {
  2126. Entity *e = results->variables[i];
  2127. GB_ASSERT(e->kind == Entity_Variable);
  2128. if (e->token.string != "") {
  2129. GB_ASSERT(!is_blank_ident(e->token));
  2130. lbAddr res = {};
  2131. if (return_ptr_value.value) {
  2132. lbValue ptr = return_ptr_value;
  2133. if (results->variables.count != 1) {
  2134. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2135. }
  2136. res = lb_addr(ptr);
  2137. lb_add_entity(p->module, e, ptr);
  2138. } else {
  2139. res = lb_add_local(p, e->type, e);
  2140. }
  2141. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2142. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2143. lb_addr_store(p, res, c);
  2144. }
  2145. }
  2146. }
  2147. }
  2148. }
  2149. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2150. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  2151. e->flags |= EntityFlag_NoAlias;
  2152. lbValue param = {};
  2153. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  2154. param.type = e->type;
  2155. lb_add_entity(p->module, e, param);
  2156. lbAddr ctx_addr = {};
  2157. ctx_addr.kind = lbAddr_Context;
  2158. ctx_addr.addr = param;
  2159. lbContextData ctx = {ctx_addr, p->scope_index};
  2160. array_add(&p->context_stack, ctx);
  2161. }
  2162. lb_start_block(p, p->entry_block);
  2163. }
  2164. void lb_end_procedure_body(lbProcedure *p) {
  2165. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2166. LLVMBuildBr(p->builder, p->entry_block->block);
  2167. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2168. // Make sure there is a "ret void" at the end of a procedure with no return type
  2169. if (p->type->Proc.result_count == 0) {
  2170. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2171. if (!lb_is_instr_terminating(instr)) {
  2172. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2173. LLVMBuildRetVoid(p->builder);
  2174. }
  2175. }
  2176. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2177. LLVMBasicBlockRef block = nullptr;
  2178. // Make sure every block terminates, and if not, make it unreachable
  2179. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2180. LLVMValueRef instr = LLVMGetLastInstruction(block);
  2181. if (instr == nullptr) {
  2182. LLVMPositionBuilderAtEnd(p->builder, block);
  2183. LLVMBuildUnreachable(p->builder);
  2184. }
  2185. }
  2186. p->curr_block = nullptr;
  2187. p->module->state_flags = 0;
  2188. }
  2189. void lb_end_procedure(lbProcedure *p) {
  2190. LLVMDisposeBuilder(p->builder);
  2191. }
  2192. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2193. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2194. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2195. array_add(&from->succs, to);
  2196. array_add(&to->preds, from);
  2197. }
  2198. }
  2199. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2200. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2201. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2202. b->appended = false;
  2203. if (append) {
  2204. b->appended = true;
  2205. LLVMAppendExistingBasicBlock(p->value, b->block);
  2206. }
  2207. b->scope = p->curr_scope;
  2208. b->scope_index = p->scope_index;
  2209. b->preds.allocator = heap_allocator();
  2210. b->succs.allocator = heap_allocator();
  2211. array_add(&p->blocks, b);
  2212. return b;
  2213. }
  2214. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2215. if (p->curr_block == nullptr) {
  2216. return;
  2217. }
  2218. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2219. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2220. return;
  2221. }
  2222. lb_add_edge(p->curr_block, target_block);
  2223. LLVMBuildBr(p->builder, target_block->block);
  2224. p->curr_block = nullptr;
  2225. }
  2226. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2227. lbBlock *b = p->curr_block;
  2228. if (b == nullptr) {
  2229. return;
  2230. }
  2231. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2232. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2233. return;
  2234. }
  2235. lb_add_edge(b, true_block);
  2236. lb_add_edge(b, false_block);
  2237. LLVMValueRef cv = cond.value;
  2238. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2239. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2240. }
  2241. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2242. GB_ASSERT(cond != nullptr);
  2243. GB_ASSERT(true_block != nullptr);
  2244. GB_ASSERT(false_block != nullptr);
  2245. switch (cond->kind) {
  2246. case_ast_node(pe, ParenExpr, cond);
  2247. return lb_build_cond(p, pe->expr, true_block, false_block);
  2248. case_end;
  2249. case_ast_node(ue, UnaryExpr, cond);
  2250. if (ue->op.kind == Token_Not) {
  2251. return lb_build_cond(p, ue->expr, false_block, true_block);
  2252. }
  2253. case_end;
  2254. case_ast_node(be, BinaryExpr, cond);
  2255. if (be->op.kind == Token_CmpAnd) {
  2256. lbBlock *block = lb_create_block(p, "cmp.and");
  2257. lb_build_cond(p, be->left, block, false_block);
  2258. lb_start_block(p, block);
  2259. return lb_build_cond(p, be->right, true_block, false_block);
  2260. } else if (be->op.kind == Token_CmpOr) {
  2261. lbBlock *block = lb_create_block(p, "cmp.or");
  2262. lb_build_cond(p, be->left, true_block, block);
  2263. lb_start_block(p, block);
  2264. return lb_build_cond(p, be->right, true_block, false_block);
  2265. }
  2266. case_end;
  2267. }
  2268. lbValue v = lb_build_expr(p, cond);
  2269. // v = lb_emit_conv(p, v, t_bool);
  2270. v = lb_emit_conv(p, v, t_llvm_bool);
  2271. lb_emit_if(p, v, true_block, false_block);
  2272. return v;
  2273. }
  2274. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2275. GB_ASSERT(p->decl_block != p->curr_block);
  2276. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2277. char const *name = "";
  2278. if (e != nullptr) {
  2279. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2280. }
  2281. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2282. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2283. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2284. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2285. LLVMSetAlignment(ptr, alignment);
  2286. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2287. if (zero_init) {
  2288. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2289. switch (kind) {
  2290. case LLVMStructTypeKind:
  2291. case LLVMArrayTypeKind:
  2292. {
  2293. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2294. LLVMTypeRef type_i8 = LLVMInt8TypeInContext(p->module->ctx);
  2295. LLVMTypeRef type_i32 = LLVMInt32TypeInContext(p->module->ctx);
  2296. i32 sz = cast(i32)type_size_of(type);
  2297. LLVMBuildMemSet(p->builder, ptr, LLVMConstNull(type_i8), LLVMConstInt(type_i32, sz, false), alignment);
  2298. }
  2299. break;
  2300. default:
  2301. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2302. }
  2303. }
  2304. lbValue val = {};
  2305. val.value = ptr;
  2306. val.type = alloc_type_pointer(type);
  2307. if (e != nullptr) {
  2308. lb_add_entity(p->module, e, val);
  2309. }
  2310. return lb_addr(val);
  2311. }
  2312. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2313. return lb_add_local(p, type, nullptr, zero_init);
  2314. }
  2315. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2316. GB_ASSERT(pd->body != nullptr);
  2317. lbModule *m = p->module;
  2318. auto *min_dep_set = &m->info->minimum_dependency_set;
  2319. if (ptr_set_exists(min_dep_set, e) == false) {
  2320. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2321. return;
  2322. }
  2323. // NOTE(bill): Generate a new name
  2324. // parent.name-guid
  2325. String original_name = e->token.string;
  2326. String pd_name = original_name;
  2327. if (e->Procedure.link_name.len > 0) {
  2328. pd_name = e->Procedure.link_name;
  2329. }
  2330. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2331. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2332. i32 guid = cast(i32)p->children.count;
  2333. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2334. String name = make_string(cast(u8 *)name_text, name_len-1);
  2335. set_procedure_abi_types(e->type);
  2336. e->Procedure.link_name = name;
  2337. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2338. e->code_gen_procedure = nested_proc;
  2339. lbValue value = {};
  2340. value.value = nested_proc->value;
  2341. value.type = nested_proc->type;
  2342. lb_add_entity(m, e, value);
  2343. array_add(&p->children, nested_proc);
  2344. array_add(&m->procedures_to_generate, nested_proc);
  2345. }
  2346. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2347. if (e == nullptr) {
  2348. return;
  2349. }
  2350. GB_ASSERT(e->kind == Entity_LibraryName);
  2351. GB_ASSERT(e->flags & EntityFlag_Used);
  2352. for_array(i, e->LibraryName.paths) {
  2353. String library_path = e->LibraryName.paths[i];
  2354. if (library_path.len == 0) {
  2355. continue;
  2356. }
  2357. bool ok = true;
  2358. for_array(path_index, m->foreign_library_paths) {
  2359. String path = m->foreign_library_paths[path_index];
  2360. #if defined(GB_SYSTEM_WINDOWS)
  2361. if (str_eq_ignore_case(path, library_path)) {
  2362. #else
  2363. if (str_eq(path, library_path)) {
  2364. #endif
  2365. ok = false;
  2366. break;
  2367. }
  2368. }
  2369. if (ok) {
  2370. array_add(&m->foreign_library_paths, library_path);
  2371. }
  2372. }
  2373. }
  2374. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2375. if (vd == nullptr || vd->is_mutable) {
  2376. return;
  2377. }
  2378. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2379. static i32 global_guid = 0;
  2380. for_array(i, vd->names) {
  2381. Ast *ident = vd->names[i];
  2382. GB_ASSERT(ident->kind == Ast_Ident);
  2383. Entity *e = entity_of_node(ident);
  2384. GB_ASSERT(e != nullptr);
  2385. if (e->kind != Entity_TypeName) {
  2386. continue;
  2387. }
  2388. bool polymorphic_struct = false;
  2389. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2390. Type *bt = base_type(e->type);
  2391. if (bt->kind == Type_Struct) {
  2392. polymorphic_struct = bt->Struct.is_polymorphic;
  2393. }
  2394. }
  2395. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2396. continue;
  2397. }
  2398. if (e->TypeName.ir_mangled_name.len != 0) {
  2399. // NOTE(bill): Already set
  2400. continue;
  2401. }
  2402. lb_set_nested_type_name_ir_mangled_name(e, p);
  2403. }
  2404. for_array(i, vd->names) {
  2405. Ast *ident = vd->names[i];
  2406. GB_ASSERT(ident->kind == Ast_Ident);
  2407. Entity *e = entity_of_node(ident);
  2408. GB_ASSERT(e != nullptr);
  2409. if (e->kind != Entity_Procedure) {
  2410. continue;
  2411. }
  2412. CheckerInfo *info = p->module->info;
  2413. DeclInfo *decl = decl_info_of_entity(e);
  2414. ast_node(pl, ProcLit, decl->proc_lit);
  2415. if (pl->body != nullptr) {
  2416. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2417. if (found) {
  2418. auto procs = *found;
  2419. for_array(i, procs) {
  2420. Entity *e = procs[i];
  2421. if (!ptr_set_exists(min_dep_set, e)) {
  2422. continue;
  2423. }
  2424. DeclInfo *d = decl_info_of_entity(e);
  2425. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2426. }
  2427. } else {
  2428. lb_build_nested_proc(p, pl, e);
  2429. }
  2430. } else {
  2431. // FFI - Foreign function interace
  2432. String original_name = e->token.string;
  2433. String name = original_name;
  2434. if (e->Procedure.is_foreign) {
  2435. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2436. }
  2437. if (e->Procedure.link_name.len > 0) {
  2438. name = e->Procedure.link_name;
  2439. }
  2440. lbValue *prev_value = string_map_get(&p->module->members, name);
  2441. if (prev_value != nullptr) {
  2442. // NOTE(bill): Don't do mutliple declarations in the IR
  2443. return;
  2444. }
  2445. set_procedure_abi_types(e->type);
  2446. e->Procedure.link_name = name;
  2447. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2448. lbValue value = {};
  2449. value.value = nested_proc->value;
  2450. value.type = nested_proc->type;
  2451. array_add(&p->module->procedures_to_generate, nested_proc);
  2452. if (p != nullptr) {
  2453. array_add(&p->children, nested_proc);
  2454. } else {
  2455. string_map_set(&p->module->members, name, value);
  2456. }
  2457. }
  2458. }
  2459. }
  2460. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  2461. for_array(i, stmts) {
  2462. Ast *stmt = stmts[i];
  2463. switch (stmt->kind) {
  2464. case_ast_node(vd, ValueDecl, stmt);
  2465. lb_build_constant_value_decl(p, vd);
  2466. case_end;
  2467. case_ast_node(fb, ForeignBlockDecl, stmt);
  2468. ast_node(block, BlockStmt, fb->body);
  2469. lb_build_stmt_list(p, block->stmts);
  2470. case_end;
  2471. }
  2472. }
  2473. for_array(i, stmts) {
  2474. lb_build_stmt(p, stmts[i]);
  2475. }
  2476. }
  2477. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2478. GB_ASSERT(ident->kind == Ast_Ident);
  2479. Entity *e = entity_of_node(ident);
  2480. GB_ASSERT(e->kind == Entity_Label);
  2481. for_array(i, p->branch_blocks) {
  2482. lbBranchBlocks *b = &p->branch_blocks[i];
  2483. if (b->label == e->Label.node) {
  2484. return *b;
  2485. }
  2486. }
  2487. GB_PANIC("Unreachable");
  2488. lbBranchBlocks empty = {};
  2489. return empty;
  2490. }
  2491. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2492. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  2493. tl->prev = p->target_list;
  2494. tl->break_ = break_;
  2495. tl->continue_ = continue_;
  2496. tl->fallthrough_ = fallthrough_;
  2497. p->target_list = tl;
  2498. if (label != nullptr) { // Set label blocks
  2499. GB_ASSERT(label->kind == Ast_Label);
  2500. for_array(i, p->branch_blocks) {
  2501. lbBranchBlocks *b = &p->branch_blocks[i];
  2502. GB_ASSERT(b->label != nullptr && label != nullptr);
  2503. GB_ASSERT(b->label->kind == Ast_Label);
  2504. if (b->label == label) {
  2505. b->break_ = break_;
  2506. b->continue_ = continue_;
  2507. return tl;
  2508. }
  2509. }
  2510. GB_PANIC("Unreachable");
  2511. }
  2512. return tl;
  2513. }
  2514. void lb_pop_target_list(lbProcedure *p) {
  2515. p->target_list = p->target_list->prev;
  2516. }
  2517. void lb_open_scope(lbProcedure *p) {
  2518. p->scope_index += 1;
  2519. }
  2520. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  2521. lb_emit_defer_stmts(p, kind, block);
  2522. GB_ASSERT(p->scope_index > 0);
  2523. // NOTE(bill): Remove `context`s made in that scope
  2524. while (p->context_stack.count > 0) {
  2525. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  2526. if (ctx->scope_index >= p->scope_index) {
  2527. array_pop(&p->context_stack);
  2528. } else {
  2529. break;
  2530. }
  2531. }
  2532. p->scope_index -= 1;
  2533. }
  2534. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  2535. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  2536. GB_ASSERT(is_type_boolean(tv.type));
  2537. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  2538. if (tv.value.value_bool) {
  2539. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  2540. } else if (ws->else_stmt) {
  2541. switch (ws->else_stmt->kind) {
  2542. case Ast_BlockStmt:
  2543. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  2544. break;
  2545. case Ast_WhenStmt:
  2546. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  2547. break;
  2548. default:
  2549. GB_PANIC("Invalid 'else' statement in 'when' statement");
  2550. break;
  2551. }
  2552. }
  2553. }
  2554. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  2555. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2556. lbModule *m = p->module;
  2557. lbValue count = {};
  2558. Type *expr_type = base_type(type_deref(expr.type));
  2559. switch (expr_type->kind) {
  2560. case Type_Array:
  2561. count = lb_const_int(m, t_int, expr_type->Array.count);
  2562. break;
  2563. }
  2564. lbValue val = {};
  2565. lbValue idx = {};
  2566. lbBlock *loop = nullptr;
  2567. lbBlock *done = nullptr;
  2568. lbBlock *body = nullptr;
  2569. lbAddr index = lb_add_local_generated(p, t_int, false);
  2570. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  2571. loop = lb_create_block(p, "for.index.loop");
  2572. lb_emit_jump(p, loop);
  2573. lb_start_block(p, loop);
  2574. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  2575. lb_addr_store(p, index, incr);
  2576. body = lb_create_block(p, "for.index.body");
  2577. done = lb_create_block(p, "for.index.done");
  2578. if (count.value == nullptr) {
  2579. GB_ASSERT(count_ptr.value != nullptr);
  2580. count = lb_emit_load(p, count_ptr);
  2581. }
  2582. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  2583. lb_emit_if(p, cond, body, done);
  2584. lb_start_block(p, body);
  2585. idx = lb_addr_load(p, index);
  2586. switch (expr_type->kind) {
  2587. case Type_Array: {
  2588. if (val_type != nullptr) {
  2589. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2590. }
  2591. break;
  2592. }
  2593. case Type_EnumeratedArray: {
  2594. if (val_type != nullptr) {
  2595. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2596. // NOTE(bill): Override the idx value for the enumeration
  2597. Type *index_type = expr_type->EnumeratedArray.index;
  2598. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  2599. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  2600. }
  2601. }
  2602. break;
  2603. }
  2604. case Type_Slice: {
  2605. if (val_type != nullptr) {
  2606. lbValue elem = lb_slice_elem(p, expr);
  2607. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2608. }
  2609. break;
  2610. }
  2611. case Type_DynamicArray: {
  2612. if (val_type != nullptr) {
  2613. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  2614. elem = lb_emit_load(p, elem);
  2615. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2616. }
  2617. break;
  2618. }
  2619. case Type_Map: {
  2620. lbValue entries = lb_map_entries_ptr(p, expr);
  2621. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  2622. elem = lb_emit_load(p, elem);
  2623. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  2624. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  2625. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  2626. break;
  2627. }
  2628. default:
  2629. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  2630. break;
  2631. }
  2632. if (val_) *val_ = val;
  2633. if (idx_) *idx_ = idx;
  2634. if (loop_) *loop_ = loop;
  2635. if (done_) *done_ = done;
  2636. }
  2637. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  2638. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2639. lbModule *m = p->module;
  2640. lbValue count = lb_const_int(m, t_int, 0);
  2641. Type *expr_type = base_type(expr.type);
  2642. switch (expr_type->kind) {
  2643. case Type_Basic:
  2644. count = lb_string_len(p, expr);
  2645. break;
  2646. default:
  2647. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  2648. break;
  2649. }
  2650. lbValue val = {};
  2651. lbValue idx = {};
  2652. lbBlock *loop = nullptr;
  2653. lbBlock *done = nullptr;
  2654. lbBlock *body = nullptr;
  2655. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2656. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2657. loop = lb_create_block(p, "for.string.loop");
  2658. lb_emit_jump(p, loop);
  2659. lb_start_block(p, loop);
  2660. body = lb_create_block(p, "for.string.body");
  2661. done = lb_create_block(p, "for.string.done");
  2662. lbValue offset = lb_addr_load(p, offset_);
  2663. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  2664. lb_emit_if(p, cond, body, done);
  2665. lb_start_block(p, body);
  2666. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  2667. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  2668. auto args = array_make<lbValue>(permanent_allocator(), 1);
  2669. args[0] = lb_emit_string(p, str_elem, str_len);
  2670. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  2671. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  2672. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  2673. idx = offset;
  2674. if (val_type != nullptr) {
  2675. val = lb_emit_struct_ev(p, rune_and_len, 0);
  2676. }
  2677. if (val_) *val_ = val;
  2678. if (idx_) *idx_ = idx;
  2679. if (loop_) *loop_ = loop;
  2680. if (done_) *done_ = done;
  2681. }
  2682. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  2683. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2684. lbModule *m = p->module;
  2685. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  2686. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  2687. lbValue lower = lb_build_expr(p, node->left);
  2688. lbValue upper = {};
  2689. lbValue val = {};
  2690. lbValue idx = {};
  2691. lbBlock *loop = nullptr;
  2692. lbBlock *done = nullptr;
  2693. lbBlock *body = nullptr;
  2694. if (val_type == nullptr) {
  2695. val_type = lower.type;
  2696. }
  2697. lbAddr value = lb_add_local_generated(p, val_type, false);
  2698. lb_addr_store(p, value, lower);
  2699. lbAddr index = lb_add_local_generated(p, t_int, false);
  2700. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  2701. loop = lb_create_block(p, "for.interval.loop");
  2702. lb_emit_jump(p, loop);
  2703. lb_start_block(p, loop);
  2704. body = lb_create_block(p, "for.interval.body");
  2705. done = lb_create_block(p, "for.interval.done");
  2706. TokenKind op = Token_Lt;
  2707. switch (node->op.kind) {
  2708. case Token_Ellipsis: op = Token_LtEq; break;
  2709. case Token_RangeHalf: op = Token_Lt; break;
  2710. default: GB_PANIC("Invalid interval operator"); break;
  2711. }
  2712. upper = lb_build_expr(p, node->right);
  2713. lbValue curr_value = lb_addr_load(p, value);
  2714. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  2715. lb_emit_if(p, cond, body, done);
  2716. lb_start_block(p, body);
  2717. val = lb_addr_load(p, value);
  2718. idx = lb_addr_load(p, index);
  2719. lb_emit_increment(p, value.addr);
  2720. lb_emit_increment(p, index.addr);
  2721. if (val_) *val_ = val;
  2722. if (idx_) *idx_ = idx;
  2723. if (loop_) *loop_ = loop;
  2724. if (done_) *done_ = done;
  2725. }
  2726. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2727. lbModule *m = p->module;
  2728. Type *t = enum_type;
  2729. GB_ASSERT(is_type_enum(t));
  2730. Type *enum_ptr = alloc_type_pointer(t);
  2731. t = base_type(t);
  2732. Type *core_elem = core_type(t);
  2733. GB_ASSERT(t->kind == Type_Enum);
  2734. i64 enum_count = t->Enum.fields.count;
  2735. lbValue max_count = lb_const_int(m, t_int, enum_count);
  2736. lbValue ti = lb_type_info(m, t);
  2737. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  2738. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  2739. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  2740. lbValue values_data = lb_slice_elem(p, values);
  2741. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2742. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2743. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  2744. lb_emit_jump(p, loop);
  2745. lb_start_block(p, loop);
  2746. lbBlock *body = lb_create_block(p, "for.enum.body");
  2747. lbBlock *done = lb_create_block(p, "for.enum.done");
  2748. lbValue offset = lb_addr_load(p, offset_);
  2749. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  2750. lb_emit_if(p, cond, body, done);
  2751. lb_start_block(p, body);
  2752. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  2753. lb_emit_increment(p, offset_.addr);
  2754. lbValue val = {};
  2755. if (val_type != nullptr) {
  2756. GB_ASSERT(are_types_identical(enum_type, val_type));
  2757. if (is_type_integer(core_elem)) {
  2758. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  2759. val = lb_emit_conv(p, i, t);
  2760. } else {
  2761. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  2762. }
  2763. }
  2764. if (val_) *val_ = val;
  2765. if (idx_) *idx_ = offset;
  2766. if (loop_) *loop_ = loop;
  2767. if (done_) *done_ = done;
  2768. }
  2769. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  2770. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  2771. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  2772. lb_emit_jump(p, loop);
  2773. lb_start_block(p, loop);
  2774. lbBlock *body = lb_create_block(p, "for.tuple.body");
  2775. lbBlock *done = lb_create_block(p, "for.tuple.done");
  2776. lbValue tuple_value = lb_build_expr(p, expr);
  2777. Type *tuple = tuple_value.type;
  2778. GB_ASSERT(tuple->kind == Type_Tuple);
  2779. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  2780. i32 cond_index = tuple_count-1;
  2781. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  2782. lb_emit_if(p, cond, body, done);
  2783. lb_start_block(p, body);
  2784. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  2785. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  2786. if (loop_) *loop_ = loop;
  2787. if (done_) *done_ = done;
  2788. }
  2789. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  2790. lb_open_scope(p);
  2791. Type *val0_type = nullptr;
  2792. Type *val1_type = nullptr;
  2793. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2794. val0_type = type_of_expr(rs->val0);
  2795. }
  2796. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2797. val1_type = type_of_expr(rs->val1);
  2798. }
  2799. if (val0_type != nullptr) {
  2800. Entity *e = entity_of_node(rs->val0);
  2801. lb_add_local(p, e->type, e, true);
  2802. }
  2803. if (val1_type != nullptr) {
  2804. Entity *e = entity_of_node(rs->val1);
  2805. lb_add_local(p, e->type, e, true);
  2806. }
  2807. lbValue val = {};
  2808. lbValue key = {};
  2809. lbBlock *loop = nullptr;
  2810. lbBlock *done = nullptr;
  2811. Ast *expr = unparen_expr(rs->expr);
  2812. bool is_map = false;
  2813. TypeAndValue tav = type_and_value_of_expr(expr);
  2814. if (is_ast_range(expr)) {
  2815. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  2816. } else if (tav.mode == Addressing_Type) {
  2817. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  2818. } else {
  2819. Type *expr_type = type_of_expr(expr);
  2820. Type *et = base_type(type_deref(expr_type));
  2821. switch (et->kind) {
  2822. case Type_Map: {
  2823. is_map = true;
  2824. lbValue map = lb_build_addr_ptr(p, expr);
  2825. if (is_type_pointer(type_deref(map.type))) {
  2826. map = lb_emit_load(p, map);
  2827. }
  2828. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  2829. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  2830. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  2831. break;
  2832. }
  2833. case Type_Array: {
  2834. lbValue array = lb_build_addr_ptr(p, expr);
  2835. if (is_type_pointer(type_deref(array.type))) {
  2836. array = lb_emit_load(p, array);
  2837. }
  2838. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2839. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  2840. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2841. break;
  2842. }
  2843. case Type_EnumeratedArray: {
  2844. lbValue array = lb_build_addr_ptr(p, expr);
  2845. if (is_type_pointer(type_deref(array.type))) {
  2846. array = lb_emit_load(p, array);
  2847. }
  2848. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2849. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  2850. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2851. break;
  2852. }
  2853. case Type_DynamicArray: {
  2854. lbValue count_ptr = {};
  2855. lbValue array = lb_build_addr_ptr(p, expr);
  2856. if (is_type_pointer(type_deref(array.type))) {
  2857. array = lb_emit_load(p, array);
  2858. }
  2859. count_ptr = lb_emit_struct_ep(p, array, 1);
  2860. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  2861. break;
  2862. }
  2863. case Type_Slice: {
  2864. lbValue count_ptr = {};
  2865. lbValue slice = lb_build_expr(p, expr);
  2866. if (is_type_pointer(slice.type)) {
  2867. count_ptr = lb_emit_struct_ep(p, slice, 1);
  2868. slice = lb_emit_load(p, slice);
  2869. } else {
  2870. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  2871. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  2872. }
  2873. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  2874. break;
  2875. }
  2876. case Type_Basic: {
  2877. lbValue string = lb_build_expr(p, expr);
  2878. if (is_type_pointer(string.type)) {
  2879. string = lb_emit_load(p, string);
  2880. }
  2881. if (is_type_untyped(expr_type)) {
  2882. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  2883. lb_addr_store(p, s, string);
  2884. string = lb_addr_load(p, s);
  2885. }
  2886. Type *t = base_type(string.type);
  2887. GB_ASSERT(!is_type_cstring(t));
  2888. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  2889. break;
  2890. }
  2891. case Type_Tuple:
  2892. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  2893. break;
  2894. default:
  2895. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  2896. break;
  2897. }
  2898. }
  2899. if (is_map) {
  2900. if (val0_type) lb_store_range_stmt_val(p, rs->val0, key);
  2901. if (val1_type) lb_store_range_stmt_val(p, rs->val1, val);
  2902. } else {
  2903. if (val0_type) lb_store_range_stmt_val(p, rs->val0, val);
  2904. if (val1_type) lb_store_range_stmt_val(p, rs->val1, key);
  2905. }
  2906. lb_push_target_list(p, rs->label, done, loop, nullptr);
  2907. lb_build_stmt(p, rs->body);
  2908. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2909. lb_pop_target_list(p);
  2910. lb_emit_jump(p, loop);
  2911. lb_start_block(p, done);
  2912. }
  2913. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  2914. lbModule *m = p->module;
  2915. lb_open_scope(p); // Open scope here
  2916. Type *val0_type = nullptr;
  2917. Type *val1_type = nullptr;
  2918. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2919. val0_type = type_of_expr(rs->val0);
  2920. }
  2921. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2922. val1_type = type_of_expr(rs->val1);
  2923. }
  2924. if (val0_type != nullptr) {
  2925. Entity *e = entity_of_node(rs->val0);
  2926. lb_add_local(p, e->type, e, true);
  2927. }
  2928. if (val1_type != nullptr) {
  2929. Entity *e = entity_of_node(rs->val1);
  2930. lb_add_local(p, e->type, e, true);
  2931. }
  2932. lbValue val = {};
  2933. lbValue key = {};
  2934. lbBlock *loop = nullptr;
  2935. lbBlock *done = nullptr;
  2936. Ast *expr = unparen_expr(rs->expr);
  2937. TypeAndValue tav = type_and_value_of_expr(expr);
  2938. if (is_ast_range(expr)) {
  2939. lbAddr val0_addr = {};
  2940. lbAddr val1_addr = {};
  2941. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2942. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2943. TokenKind op = expr->BinaryExpr.op.kind;
  2944. Ast *start_expr = expr->BinaryExpr.left;
  2945. Ast *end_expr = expr->BinaryExpr.right;
  2946. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  2947. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  2948. ExactValue start = start_expr->tav.value;
  2949. ExactValue end = end_expr->tav.value;
  2950. if (op == Token_Ellipsis) { // .. [start, end]
  2951. ExactValue index = exact_value_i64(0);
  2952. for (ExactValue val = start;
  2953. compare_exact_values(Token_LtEq, val, end);
  2954. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2955. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2956. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2957. lb_build_stmt(p, rs->body);
  2958. }
  2959. } else if (op == Token_RangeHalf) { // ..< [start, end)
  2960. ExactValue index = exact_value_i64(0);
  2961. for (ExactValue val = start;
  2962. compare_exact_values(Token_Lt, val, end);
  2963. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2964. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2965. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2966. lb_build_stmt(p, rs->body);
  2967. }
  2968. }
  2969. } else if (tav.mode == Addressing_Type) {
  2970. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  2971. Type *et = type_deref(tav.type);
  2972. Type *bet = base_type(et);
  2973. lbAddr val0_addr = {};
  2974. lbAddr val1_addr = {};
  2975. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2976. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2977. for_array(i, bet->Enum.fields) {
  2978. Entity *field = bet->Enum.fields[i];
  2979. GB_ASSERT(field->kind == Entity_Constant);
  2980. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  2981. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2982. lb_build_stmt(p, rs->body);
  2983. }
  2984. } else {
  2985. lbAddr val0_addr = {};
  2986. lbAddr val1_addr = {};
  2987. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2988. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2989. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  2990. Type *t = base_type(expr->tav.type);
  2991. switch (t->kind) {
  2992. case Type_Basic:
  2993. GB_ASSERT(is_type_string(t));
  2994. {
  2995. ExactValue value = expr->tav.value;
  2996. GB_ASSERT(value.kind == ExactValue_String);
  2997. String str = value.value_string;
  2998. Rune codepoint = 0;
  2999. isize offset = 0;
  3000. do {
  3001. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3002. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3003. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3004. lb_build_stmt(p, rs->body);
  3005. offset += width;
  3006. } while (offset < str.len);
  3007. }
  3008. break;
  3009. case Type_Array:
  3010. if (t->Array.count > 0) {
  3011. lbValue val = lb_build_expr(p, expr);
  3012. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3013. for (i64 i = 0; i < t->Array.count; i++) {
  3014. if (val0_type) {
  3015. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3016. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3017. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3018. }
  3019. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3020. lb_build_stmt(p, rs->body);
  3021. }
  3022. }
  3023. break;
  3024. case Type_EnumeratedArray:
  3025. if (t->EnumeratedArray.count > 0) {
  3026. lbValue val = lb_build_expr(p, expr);
  3027. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3028. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3029. if (val0_type) {
  3030. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3031. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3032. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3033. }
  3034. if (val1_type) {
  3035. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3036. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3037. }
  3038. lb_build_stmt(p, rs->body);
  3039. }
  3040. }
  3041. break;
  3042. default:
  3043. GB_PANIC("Invalid '#unroll for' type");
  3044. break;
  3045. }
  3046. }
  3047. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3048. }
  3049. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  3050. if (ss->init != nullptr) {
  3051. lb_build_stmt(p, ss->init);
  3052. }
  3053. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3054. if (ss->tag != nullptr) {
  3055. tag = lb_build_expr(p, ss->tag);
  3056. }
  3057. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3058. ast_node(body, BlockStmt, ss->body);
  3059. Slice<Ast *> default_stmts = {};
  3060. lbBlock *default_fall = nullptr;
  3061. lbBlock *default_block = nullptr;
  3062. lbBlock *fall = nullptr;
  3063. isize case_count = body->stmts.count;
  3064. for_array(i, body->stmts) {
  3065. Ast *clause = body->stmts[i];
  3066. ast_node(cc, CaseClause, clause);
  3067. lbBlock *body = fall;
  3068. if (body == nullptr) {
  3069. body = lb_create_block(p, "switch.case.body");
  3070. }
  3071. fall = done;
  3072. if (i+1 < case_count) {
  3073. fall = lb_create_block(p, "switch.fall.body");
  3074. }
  3075. if (cc->list.count == 0) {
  3076. // default case
  3077. default_stmts = cc->stmts;
  3078. default_fall = fall;
  3079. default_block = body;
  3080. continue;
  3081. }
  3082. lbBlock *next_cond = nullptr;
  3083. for_array(j, cc->list) {
  3084. Ast *expr = unparen_expr(cc->list[j]);
  3085. next_cond = lb_create_block(p, "switch.case.next");
  3086. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3087. if (is_ast_range(expr)) {
  3088. ast_node(ie, BinaryExpr, expr);
  3089. TokenKind op = Token_Invalid;
  3090. switch (ie->op.kind) {
  3091. case Token_Ellipsis: op = Token_LtEq; break;
  3092. case Token_RangeHalf: op = Token_Lt; break;
  3093. default: GB_PANIC("Invalid interval operator"); break;
  3094. }
  3095. lbValue lhs = lb_build_expr(p, ie->left);
  3096. lbValue rhs = lb_build_expr(p, ie->right);
  3097. // TODO(bill): do short circuit here
  3098. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3099. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3100. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3101. } else {
  3102. if (expr->tav.mode == Addressing_Type) {
  3103. GB_ASSERT(is_type_typeid(tag.type));
  3104. lbValue e = lb_typeid(p->module, expr->tav.type);
  3105. e = lb_emit_conv(p, e, tag.type);
  3106. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3107. } else {
  3108. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3109. }
  3110. }
  3111. lb_emit_if(p, cond, body, next_cond);
  3112. lb_start_block(p, next_cond);
  3113. }
  3114. lb_start_block(p, body);
  3115. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3116. lb_open_scope(p);
  3117. lb_build_stmt_list(p, cc->stmts);
  3118. lb_close_scope(p, lbDeferExit_Default, body);
  3119. lb_pop_target_list(p);
  3120. lb_emit_jump(p, done);
  3121. lb_start_block(p, next_cond);
  3122. }
  3123. if (default_block != nullptr) {
  3124. lb_emit_jump(p, default_block);
  3125. lb_start_block(p, default_block);
  3126. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3127. lb_open_scope(p);
  3128. lb_build_stmt_list(p, default_stmts);
  3129. lb_close_scope(p, lbDeferExit_Default, default_block);
  3130. lb_pop_target_list(p);
  3131. }
  3132. lb_emit_jump(p, done);
  3133. lb_start_block(p, done);
  3134. }
  3135. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3136. Entity *e = implicit_entity_of_node(clause);
  3137. GB_ASSERT(e != nullptr);
  3138. if (e->flags & EntityFlag_Value) {
  3139. // by value
  3140. GB_ASSERT(are_types_identical(e->type, value.type));
  3141. lbAddr x = lb_add_local(p, e->type, e, false);
  3142. lb_addr_store(p, x, value);
  3143. } else {
  3144. // by reference
  3145. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3146. lb_add_entity(p->module, e, value);
  3147. }
  3148. }
  3149. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3150. Entity *e = entity_of_node(stmt_val);
  3151. if (e == nullptr) {
  3152. return {};
  3153. }
  3154. if ((e->flags & EntityFlag_Value) == 0) {
  3155. if (LLVMIsALoadInst(value.value)) {
  3156. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3157. lb_add_entity(p->module, e, ptr);
  3158. return lb_addr(ptr);
  3159. }
  3160. }
  3161. // by value
  3162. lbAddr addr = lb_add_local(p, e->type, e, false);
  3163. lb_addr_store(p, addr, value);
  3164. return addr;
  3165. }
  3166. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3167. ast_node(cc, CaseClause, clause);
  3168. lb_push_target_list(p, label, done, nullptr, nullptr);
  3169. lb_open_scope(p);
  3170. lb_build_stmt_list(p, cc->stmts);
  3171. lb_close_scope(p, lbDeferExit_Default, body);
  3172. lb_pop_target_list(p);
  3173. lb_emit_jump(p, done);
  3174. }
  3175. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3176. lbModule *m = p->module;
  3177. ast_node(as, AssignStmt, ss->tag);
  3178. GB_ASSERT(as->lhs.count == 1);
  3179. GB_ASSERT(as->rhs.count == 1);
  3180. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3181. bool is_parent_ptr = is_type_pointer(parent.type);
  3182. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3183. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3184. lbValue parent_value = parent;
  3185. lbValue parent_ptr = parent;
  3186. if (!is_parent_ptr) {
  3187. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3188. }
  3189. lbValue tag_index = {};
  3190. lbValue union_data = {};
  3191. if (switch_kind == TypeSwitch_Union) {
  3192. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3193. tag_index = lb_emit_load(p, tag_ptr);
  3194. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3195. }
  3196. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3197. lb_emit_jump(p, start_block);
  3198. lb_start_block(p, start_block);
  3199. // NOTE(bill): Append this later
  3200. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3201. Ast *default_ = nullptr;
  3202. ast_node(body, BlockStmt, ss->body);
  3203. gb_local_persist i32 weird_count = 0;
  3204. for_array(i, body->stmts) {
  3205. Ast *clause = body->stmts[i];
  3206. ast_node(cc, CaseClause, clause);
  3207. if (cc->list.count == 0) {
  3208. default_ = clause;
  3209. continue;
  3210. }
  3211. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3212. lbBlock *next = nullptr;
  3213. Type *case_type = nullptr;
  3214. for_array(type_index, cc->list) {
  3215. next = lb_create_block(p, "typeswitch.next");
  3216. case_type = type_of_expr(cc->list[type_index]);
  3217. lbValue cond = {};
  3218. if (switch_kind == TypeSwitch_Union) {
  3219. Type *ut = base_type(type_deref(parent.type));
  3220. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3221. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3222. } else if (switch_kind == TypeSwitch_Any) {
  3223. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3224. lbValue case_typeid = lb_typeid(m, case_type);
  3225. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3226. }
  3227. GB_ASSERT(cond.value != nullptr);
  3228. lb_emit_if(p, cond, body, next);
  3229. lb_start_block(p, next);
  3230. }
  3231. Entity *case_entity = implicit_entity_of_node(clause);
  3232. lbValue value = parent_value;
  3233. lb_start_block(p, body);
  3234. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3235. if (cc->list.count == 1) {
  3236. lbValue data = {};
  3237. if (switch_kind == TypeSwitch_Union) {
  3238. data = union_data;
  3239. } else if (switch_kind == TypeSwitch_Any) {
  3240. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3241. data = any_data;
  3242. }
  3243. Type *ct = case_entity->type;
  3244. Type *ct_ptr = alloc_type_pointer(ct);
  3245. value = lb_emit_conv(p, data, ct_ptr);
  3246. if (!by_reference) {
  3247. value = lb_emit_load(p, value);
  3248. }
  3249. }
  3250. lb_store_type_case_implicit(p, clause, value);
  3251. lb_type_case_body(p, ss->label, clause, body, done);
  3252. lb_start_block(p, next);
  3253. }
  3254. if (default_ != nullptr) {
  3255. lb_store_type_case_implicit(p, default_, parent_value);
  3256. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3257. } else {
  3258. lb_emit_jump(p, done);
  3259. }
  3260. lb_start_block(p, done);
  3261. }
  3262. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3263. lbModule *m = p->module;
  3264. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3265. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3266. type = default_type(type);
  3267. lbValue short_circuit = {};
  3268. if (op == Token_CmpAnd) {
  3269. lb_build_cond(p, left, rhs, done);
  3270. short_circuit = lb_const_bool(m, type, false);
  3271. } else if (op == Token_CmpOr) {
  3272. lb_build_cond(p, left, done, rhs);
  3273. short_circuit = lb_const_bool(m, type, true);
  3274. }
  3275. if (rhs->preds.count == 0) {
  3276. lb_start_block(p, done);
  3277. return short_circuit;
  3278. }
  3279. if (done->preds.count == 0) {
  3280. lb_start_block(p, rhs);
  3281. return lb_build_expr(p, right);
  3282. }
  3283. Array<LLVMValueRef> incoming_values = {};
  3284. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3285. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3286. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3287. for_array(i, done->preds) {
  3288. incoming_values[i] = short_circuit.value;
  3289. incoming_blocks[i] = done->preds[i]->block;
  3290. }
  3291. lb_start_block(p, rhs);
  3292. lbValue edge = lb_build_expr(p, right);
  3293. incoming_values[done->preds.count] = edge.value;
  3294. incoming_blocks[done->preds.count] = p->curr_block->block;
  3295. lb_emit_jump(p, done);
  3296. lb_start_block(p, done);
  3297. lbValue res = {};
  3298. res.type = type;
  3299. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3300. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3301. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3302. return res;
  3303. }
  3304. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3305. Ast *prev_stmt = p->curr_stmt;
  3306. defer (p->curr_stmt = prev_stmt);
  3307. p->curr_stmt = node;
  3308. if (p->curr_block != nullptr) {
  3309. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3310. if (lb_is_instr_terminating(last_instr)) {
  3311. return;
  3312. }
  3313. }
  3314. u64 prev_state_flags = p->module->state_flags;
  3315. defer (p->module->state_flags = prev_state_flags);
  3316. if (node->state_flags != 0) {
  3317. u64 in = node->state_flags;
  3318. u64 out = p->module->state_flags;
  3319. if (in & StateFlag_bounds_check) {
  3320. out |= StateFlag_bounds_check;
  3321. out &= ~StateFlag_no_bounds_check;
  3322. } else if (in & StateFlag_no_bounds_check) {
  3323. out |= StateFlag_no_bounds_check;
  3324. out &= ~StateFlag_bounds_check;
  3325. }
  3326. p->module->state_flags = out;
  3327. }
  3328. switch (node->kind) {
  3329. case_ast_node(bs, EmptyStmt, node);
  3330. case_end;
  3331. case_ast_node(us, UsingStmt, node);
  3332. case_end;
  3333. case_ast_node(ws, WhenStmt, node);
  3334. lb_build_when_stmt(p, ws);
  3335. case_end;
  3336. case_ast_node(bs, BlockStmt, node);
  3337. if (bs->label != nullptr) {
  3338. lbBlock *done = lb_create_block(p, "block.done");
  3339. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3340. tl->is_block = true;
  3341. lb_open_scope(p);
  3342. lb_build_stmt_list(p, bs->stmts);
  3343. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3344. lb_emit_jump(p, done);
  3345. lb_start_block(p, done);
  3346. } else {
  3347. lb_open_scope(p);
  3348. lb_build_stmt_list(p, bs->stmts);
  3349. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3350. }
  3351. case_end;
  3352. case_ast_node(vd, ValueDecl, node);
  3353. if (!vd->is_mutable) {
  3354. return;
  3355. }
  3356. bool is_static = false;
  3357. if (vd->names.count > 0) {
  3358. Entity *e = entity_of_node(vd->names[0]);
  3359. if (e->flags & EntityFlag_Static) {
  3360. // NOTE(bill): If one of the entities is static, they all are
  3361. is_static = true;
  3362. }
  3363. }
  3364. if (is_static) {
  3365. for_array(i, vd->names) {
  3366. lbValue value = {};
  3367. if (vd->values.count > 0) {
  3368. GB_ASSERT(vd->names.count == vd->values.count);
  3369. Ast *ast_value = vd->values[i];
  3370. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3371. ast_value->tav.mode == Addressing_Invalid);
  3372. bool allow_local = false;
  3373. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3374. }
  3375. Ast *ident = vd->names[i];
  3376. GB_ASSERT(!is_blank_ident(ident));
  3377. Entity *e = entity_of_node(ident);
  3378. GB_ASSERT(e->flags & EntityFlag_Static);
  3379. String name = e->token.string;
  3380. String mangled_name = {};
  3381. {
  3382. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  3383. str = gb_string_appendc(str, "-");
  3384. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3385. mangled_name.text = cast(u8 *)str;
  3386. mangled_name.len = gb_string_length(str);
  3387. }
  3388. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  3389. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3390. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3391. if (value.value != nullptr) {
  3392. LLVMSetInitializer(global, value.value);
  3393. } else {
  3394. }
  3395. if (e->Variable.thread_local_model != "") {
  3396. LLVMSetThreadLocal(global, true);
  3397. String m = e->Variable.thread_local_model;
  3398. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3399. if (m == "default") {
  3400. mode = LLVMGeneralDynamicTLSModel;
  3401. } else if (m == "localdynamic") {
  3402. mode = LLVMLocalDynamicTLSModel;
  3403. } else if (m == "initialexec") {
  3404. mode = LLVMInitialExecTLSModel;
  3405. } else if (m == "localexec") {
  3406. mode = LLVMLocalExecTLSModel;
  3407. } else {
  3408. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3409. }
  3410. LLVMSetThreadLocalMode(global, mode);
  3411. } else {
  3412. LLVMSetLinkage(global, LLVMInternalLinkage);
  3413. }
  3414. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3415. lb_add_entity(p->module, e, global_val);
  3416. lb_add_member(p->module, mangled_name, global_val);
  3417. }
  3418. return;
  3419. }
  3420. if (vd->values.count == 0) { // declared and zero-initialized
  3421. for_array(i, vd->names) {
  3422. Ast *name = vd->names[i];
  3423. if (!is_blank_ident(name)) {
  3424. Entity *e = entity_of_node(name);
  3425. lb_add_local(p, e->type, e, true);
  3426. }
  3427. }
  3428. } else { // Tuple(s)
  3429. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  3430. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  3431. for_array(i, vd->names) {
  3432. Ast *name = vd->names[i];
  3433. lbAddr lval = {};
  3434. if (!is_blank_ident(name)) {
  3435. Entity *e = entity_of_node(name);
  3436. lval = lb_add_local(p, e->type, e, false);
  3437. }
  3438. array_add(&lvals, lval);
  3439. }
  3440. for_array(i, vd->values) {
  3441. lbValue init = lb_build_expr(p, vd->values[i]);
  3442. Type *t = init.type;
  3443. if (t->kind == Type_Tuple) {
  3444. for_array(i, t->Tuple.variables) {
  3445. Entity *e = t->Tuple.variables[i];
  3446. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3447. array_add(&inits, v);
  3448. }
  3449. } else {
  3450. array_add(&inits, init);
  3451. }
  3452. }
  3453. for_array(i, inits) {
  3454. lbAddr lval = lvals[i];
  3455. lbValue init = inits[i];
  3456. lb_addr_store(p, lval, init);
  3457. }
  3458. }
  3459. case_end;
  3460. case_ast_node(as, AssignStmt, node);
  3461. if (as->op.kind == Token_Eq) {
  3462. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  3463. for_array(i, as->lhs) {
  3464. Ast *lhs = as->lhs[i];
  3465. lbAddr lval = {};
  3466. if (!is_blank_ident(lhs)) {
  3467. lval = lb_build_addr(p, lhs);
  3468. }
  3469. array_add(&lvals, lval);
  3470. }
  3471. if (as->lhs.count == as->rhs.count) {
  3472. if (as->lhs.count == 1) {
  3473. lbAddr lval = lvals[0];
  3474. Ast *rhs = as->rhs[0];
  3475. lbValue init = lb_build_expr(p, rhs);
  3476. lb_addr_store(p, lvals[0], init);
  3477. } else {
  3478. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3479. for_array(i, as->rhs) {
  3480. lbValue init = lb_build_expr(p, as->rhs[i]);
  3481. array_add(&inits, init);
  3482. }
  3483. for_array(i, inits) {
  3484. lbAddr lval = lvals[i];
  3485. lbValue init = inits[i];
  3486. lb_addr_store(p, lval, init);
  3487. }
  3488. }
  3489. } else {
  3490. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3491. for_array(i, as->rhs) {
  3492. lbValue init = lb_build_expr(p, as->rhs[i]);
  3493. Type *t = init.type;
  3494. // TODO(bill): refactor for code reuse as this is repeated a bit
  3495. if (t->kind == Type_Tuple) {
  3496. for_array(i, t->Tuple.variables) {
  3497. Entity *e = t->Tuple.variables[i];
  3498. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3499. array_add(&inits, v);
  3500. }
  3501. } else {
  3502. array_add(&inits, init);
  3503. }
  3504. }
  3505. for_array(i, inits) {
  3506. lbAddr lval = lvals[i];
  3507. lbValue init = inits[i];
  3508. lb_addr_store(p, lval, init);
  3509. }
  3510. }
  3511. } else {
  3512. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  3513. // +=, -=, etc
  3514. i32 op = cast(i32)as->op.kind;
  3515. op += Token_Add - Token_AddEq; // Convert += to +
  3516. if (op == Token_CmpAnd || op == Token_CmpOr) {
  3517. Type *type = as->lhs[0]->tav.type;
  3518. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  3519. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3520. lb_addr_store(p, lhs, new_value);
  3521. } else {
  3522. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3523. lbValue value = lb_build_expr(p, as->rhs[0]);
  3524. lbValue old_value = lb_addr_load(p, lhs);
  3525. Type *type = old_value.type;
  3526. lbValue change = lb_emit_conv(p, value, type);
  3527. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  3528. lb_addr_store(p, lhs, new_value);
  3529. }
  3530. return;
  3531. }
  3532. case_end;
  3533. case_ast_node(es, ExprStmt, node);
  3534. lb_build_expr(p, es->expr);
  3535. case_end;
  3536. case_ast_node(ds, DeferStmt, node);
  3537. isize scope_index = p->scope_index;
  3538. lb_add_defer_node(p, scope_index, ds->stmt);
  3539. case_end;
  3540. case_ast_node(rs, ReturnStmt, node);
  3541. lbValue res = {};
  3542. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  3543. isize return_count = p->type->Proc.result_count;
  3544. isize res_count = rs->results.count;
  3545. if (return_count == 0) {
  3546. // No return values
  3547. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3548. LLVMBuildRetVoid(p->builder);
  3549. return;
  3550. } else if (return_count == 1) {
  3551. Entity *e = tuple->variables[0];
  3552. if (res_count == 0) {
  3553. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3554. GB_ASSERT(found);
  3555. res = lb_emit_load(p, *found);
  3556. } else {
  3557. res = lb_build_expr(p, rs->results[0]);
  3558. res = lb_emit_conv(p, res, e->type);
  3559. }
  3560. if (p->type->Proc.has_named_results) {
  3561. // NOTE(bill): store the named values before returning
  3562. if (e->token.string != "") {
  3563. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3564. GB_ASSERT(found != nullptr);
  3565. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  3566. }
  3567. }
  3568. } else {
  3569. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  3570. if (res_count != 0) {
  3571. for (isize res_index = 0; res_index < res_count; res_index++) {
  3572. lbValue res = lb_build_expr(p, rs->results[res_index]);
  3573. Type *t = res.type;
  3574. if (t->kind == Type_Tuple) {
  3575. for_array(i, t->Tuple.variables) {
  3576. Entity *e = t->Tuple.variables[i];
  3577. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  3578. array_add(&results, v);
  3579. }
  3580. } else {
  3581. array_add(&results, res);
  3582. }
  3583. }
  3584. } else {
  3585. for (isize res_index = 0; res_index < return_count; res_index++) {
  3586. Entity *e = tuple->variables[res_index];
  3587. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3588. GB_ASSERT(found);
  3589. lbValue res = lb_emit_load(p, *found);
  3590. array_add(&results, res);
  3591. }
  3592. }
  3593. GB_ASSERT(results.count == return_count);
  3594. if (p->type->Proc.has_named_results) {
  3595. // NOTE(bill): store the named values before returning
  3596. for_array(i, p->type->Proc.results->Tuple.variables) {
  3597. Entity *e = p->type->Proc.results->Tuple.variables[i];
  3598. if (e->kind != Entity_Variable) {
  3599. continue;
  3600. }
  3601. if (e->token.string == "") {
  3602. continue;
  3603. }
  3604. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3605. GB_ASSERT(found != nullptr);
  3606. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  3607. }
  3608. }
  3609. Type *ret_type = p->type->Proc.results;
  3610. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3611. res = lb_add_local_generated(p, ret_type, false).addr;
  3612. for_array(i, results) {
  3613. Entity *e = tuple->variables[i];
  3614. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  3615. lbValue val = lb_emit_conv(p, results[i], e->type);
  3616. lb_emit_store(p, field, val);
  3617. }
  3618. res = lb_emit_load(p, res);
  3619. }
  3620. lb_ensure_abi_function_type(p->module, p);
  3621. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  3622. if (res.value != nullptr) {
  3623. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  3624. } else {
  3625. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  3626. }
  3627. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3628. LLVMBuildRetVoid(p->builder);
  3629. } else {
  3630. LLVMValueRef ret_val = res.value;
  3631. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  3632. if (p->abi_function_type->ret.cast_type != nullptr) {
  3633. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  3634. }
  3635. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3636. LLVMBuildRet(p->builder, ret_val);
  3637. }
  3638. case_end;
  3639. case_ast_node(is, IfStmt, node);
  3640. lb_open_scope(p); // Scope #1
  3641. if (is->init != nullptr) {
  3642. // TODO(bill): Should this have a separate block to begin with?
  3643. #if 1
  3644. lbBlock *init = lb_create_block(p, "if.init");
  3645. lb_emit_jump(p, init);
  3646. lb_start_block(p, init);
  3647. #endif
  3648. lb_build_stmt(p, is->init);
  3649. }
  3650. lbBlock *then = lb_create_block(p, "if.then");
  3651. lbBlock *done = lb_create_block(p, "if.done");
  3652. lbBlock *else_ = done;
  3653. if (is->else_stmt != nullptr) {
  3654. else_ = lb_create_block(p, "if.else");
  3655. }
  3656. lb_build_cond(p, is->cond, then, else_);
  3657. lb_start_block(p, then);
  3658. if (is->label != nullptr) {
  3659. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  3660. tl->is_block = true;
  3661. }
  3662. lb_build_stmt(p, is->body);
  3663. lb_emit_jump(p, done);
  3664. if (is->else_stmt != nullptr) {
  3665. lb_start_block(p, else_);
  3666. lb_open_scope(p);
  3667. lb_build_stmt(p, is->else_stmt);
  3668. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3669. lb_emit_jump(p, done);
  3670. }
  3671. lb_start_block(p, done);
  3672. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3673. case_end;
  3674. case_ast_node(fs, ForStmt, node);
  3675. lb_open_scope(p); // Open Scope here
  3676. if (fs->init != nullptr) {
  3677. #if 1
  3678. lbBlock *init = lb_create_block(p, "for.init");
  3679. lb_emit_jump(p, init);
  3680. lb_start_block(p, init);
  3681. #endif
  3682. lb_build_stmt(p, fs->init);
  3683. }
  3684. lbBlock *body = lb_create_block(p, "for.body");
  3685. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  3686. lbBlock *loop = body;
  3687. if (fs->cond != nullptr) {
  3688. loop = lb_create_block(p, "for.loop");
  3689. }
  3690. lbBlock *post = loop;
  3691. if (fs->post != nullptr) {
  3692. post = lb_create_block(p, "for.post");
  3693. }
  3694. lb_emit_jump(p, loop);
  3695. lb_start_block(p, loop);
  3696. if (loop != body) {
  3697. lb_build_cond(p, fs->cond, body, done);
  3698. lb_start_block(p, body);
  3699. }
  3700. lb_push_target_list(p, fs->label, done, post, nullptr);
  3701. lb_build_stmt(p, fs->body);
  3702. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3703. lb_pop_target_list(p);
  3704. lb_emit_jump(p, post);
  3705. if (fs->post != nullptr) {
  3706. lb_start_block(p, post);
  3707. lb_build_stmt(p, fs->post);
  3708. lb_emit_jump(p, loop);
  3709. }
  3710. lb_start_block(p, done);
  3711. case_end;
  3712. case_ast_node(rs, RangeStmt, node);
  3713. lb_build_range_stmt(p, rs);
  3714. case_end;
  3715. case_ast_node(rs, InlineRangeStmt, node);
  3716. lb_build_inline_range_stmt(p, rs);
  3717. case_end;
  3718. case_ast_node(ss, SwitchStmt, node);
  3719. lb_build_switch_stmt(p, ss);
  3720. case_end;
  3721. case_ast_node(ss, TypeSwitchStmt, node);
  3722. lb_build_type_switch_stmt(p, ss);
  3723. case_end;
  3724. case_ast_node(bs, BranchStmt, node);
  3725. lbBlock *block = nullptr;
  3726. if (bs->label != nullptr) {
  3727. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  3728. switch (bs->token.kind) {
  3729. case Token_break: block = bb.break_; break;
  3730. case Token_continue: block = bb.continue_; break;
  3731. case Token_fallthrough:
  3732. GB_PANIC("fallthrough cannot have a label");
  3733. break;
  3734. }
  3735. } else {
  3736. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  3737. if (t->is_block) {
  3738. continue;
  3739. }
  3740. switch (bs->token.kind) {
  3741. case Token_break: block = t->break_; break;
  3742. case Token_continue: block = t->continue_; break;
  3743. case Token_fallthrough: block = t->fallthrough_; break;
  3744. }
  3745. }
  3746. }
  3747. if (block != nullptr) {
  3748. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  3749. }
  3750. lb_emit_jump(p, block);
  3751. case_end;
  3752. }
  3753. }
  3754. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  3755. cond = lb_emit_conv(p, cond, t_llvm_bool);
  3756. lbValue res = {};
  3757. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  3758. res.type = x.type;
  3759. return res;
  3760. }
  3761. lbValue lb_const_nil(lbModule *m, Type *type) {
  3762. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  3763. return lbValue{v, type};
  3764. }
  3765. lbValue lb_const_undef(lbModule *m, Type *type) {
  3766. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  3767. return lbValue{v, type};
  3768. }
  3769. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  3770. lbValue res = {};
  3771. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  3772. res.type = type;
  3773. return res;
  3774. }
  3775. lbValue lb_const_string(lbModule *m, String const &value) {
  3776. return lb_const_value(m, t_string, exact_value_string(value));
  3777. }
  3778. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  3779. lbValue res = {};
  3780. res.value = LLVMConstInt(lb_type(m, type), value, false);
  3781. res.type = type;
  3782. return res;
  3783. }
  3784. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  3785. GB_ASSERT(type_size_of(type) == 4);
  3786. u32 u = bit_cast<u32>(f);
  3787. if (is_type_different_to_arch_endianness(type)) {
  3788. u = gb_endian_swap32(u);
  3789. }
  3790. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  3791. return LLVMConstBitCast(i, lb_type(m, type));
  3792. }
  3793. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3794. x = lb_emit_conv(p, x, t);
  3795. y = lb_emit_conv(p, y, t);
  3796. if (is_type_float(t)) {
  3797. i64 sz = 8*type_size_of(t);
  3798. auto args = array_make<lbValue>(permanent_allocator(), 2);
  3799. args[0] = x;
  3800. args[1] = y;
  3801. switch (sz) {
  3802. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  3803. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  3804. }
  3805. GB_PANIC("Unknown float type");
  3806. }
  3807. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  3808. }
  3809. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3810. x = lb_emit_conv(p, x, t);
  3811. y = lb_emit_conv(p, y, t);
  3812. if (is_type_float(t)) {
  3813. i64 sz = 8*type_size_of(t);
  3814. auto args = array_make<lbValue>(permanent_allocator(), 2);
  3815. args[0] = x;
  3816. args[1] = y;
  3817. switch (sz) {
  3818. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  3819. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  3820. }
  3821. GB_PANIC("Unknown float type");
  3822. }
  3823. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  3824. }
  3825. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  3826. lbValue z = {};
  3827. z = lb_emit_max(p, t, x, min);
  3828. z = lb_emit_min(p, t, z, max);
  3829. return z;
  3830. }
  3831. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  3832. StringHashKey key = string_hash_string(str);
  3833. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  3834. if (found != nullptr) {
  3835. return *found;
  3836. } else {
  3837. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  3838. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3839. cast(char const *)str.text,
  3840. cast(unsigned)str.len,
  3841. false);
  3842. isize max_len = 7+8+1;
  3843. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  3844. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3845. len -= 1;
  3846. m->global_array_index++;
  3847. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3848. LLVMSetInitializer(global_data, data);
  3849. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  3850. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3851. string_map_set(&m->const_strings, key, ptr);
  3852. return ptr;
  3853. }
  3854. }
  3855. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  3856. LLVMValueRef ptr = nullptr;
  3857. if (str.len != 0) {
  3858. ptr = lb_find_or_add_entity_string_ptr(m, str);
  3859. } else {
  3860. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  3861. }
  3862. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3863. LLVMValueRef values[2] = {ptr, str_len};
  3864. lbValue res = {};
  3865. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  3866. res.type = t_string;
  3867. return res;
  3868. }
  3869. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  3870. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  3871. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3872. cast(char const *)str.text,
  3873. cast(unsigned)str.len,
  3874. false);
  3875. char *name = nullptr;
  3876. {
  3877. isize max_len = 7+8+1;
  3878. name = gb_alloc_array(permanent_allocator(), char, max_len);
  3879. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3880. len -= 1;
  3881. m->global_array_index++;
  3882. }
  3883. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3884. LLVMSetInitializer(global_data, data);
  3885. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  3886. LLVMValueRef ptr = nullptr;
  3887. if (str.len != 0) {
  3888. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3889. } else {
  3890. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  3891. }
  3892. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3893. LLVMValueRef values[2] = {ptr, len};
  3894. lbValue res = {};
  3895. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  3896. res.type = t_u8_slice;
  3897. return res;
  3898. }
  3899. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  3900. isize index = type_info_index(info, type, false);
  3901. if (index >= 0) {
  3902. auto *set = &info->minimum_dependency_type_info_set;
  3903. for_array(i, set->entries) {
  3904. if (set->entries[i].ptr == index) {
  3905. return i+1;
  3906. }
  3907. }
  3908. }
  3909. if (err_on_not_found) {
  3910. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  3911. }
  3912. return -1;
  3913. }
  3914. lbValue lb_typeid(lbModule *m, Type *type) {
  3915. type = default_type(type);
  3916. u64 id = cast(u64)lb_type_info_index(m->info, type);
  3917. GB_ASSERT(id >= 0);
  3918. u64 kind = Typeid_Invalid;
  3919. u64 named = is_type_named(type) && type->kind != Type_Basic;
  3920. u64 special = 0;
  3921. u64 reserved = 0;
  3922. Type *bt = base_type(type);
  3923. TypeKind tk = bt->kind;
  3924. switch (tk) {
  3925. case Type_Basic: {
  3926. u32 flags = bt->Basic.flags;
  3927. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  3928. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  3929. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  3930. if (flags & BasicFlag_Float) kind = Typeid_Float;
  3931. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  3932. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  3933. if (flags & BasicFlag_String) kind = Typeid_String;
  3934. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  3935. } break;
  3936. case Type_Pointer: kind = Typeid_Pointer; break;
  3937. case Type_Array: kind = Typeid_Array; break;
  3938. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  3939. case Type_Slice: kind = Typeid_Slice; break;
  3940. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  3941. case Type_Map: kind = Typeid_Map; break;
  3942. case Type_Struct: kind = Typeid_Struct; break;
  3943. case Type_Enum: kind = Typeid_Enum; break;
  3944. case Type_Union: kind = Typeid_Union; break;
  3945. case Type_Tuple: kind = Typeid_Tuple; break;
  3946. case Type_Proc: kind = Typeid_Procedure; break;
  3947. case Type_BitSet: kind = Typeid_Bit_Set; break;
  3948. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  3949. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  3950. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  3951. }
  3952. if (is_type_cstring(type)) {
  3953. special = 1;
  3954. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  3955. special = 1;
  3956. }
  3957. u64 data = 0;
  3958. if (build_context.word_size == 4) {
  3959. GB_ASSERT(id <= (1u<<24u));
  3960. data |= (id &~ (1u<<24)) << 0u; // index
  3961. data |= (kind &~ (1u<<5)) << 24u; // kind
  3962. data |= (named &~ (1u<<1)) << 29u; // kind
  3963. data |= (special &~ (1u<<1)) << 30u; // kind
  3964. data |= (reserved &~ (1u<<1)) << 31u; // kind
  3965. } else {
  3966. GB_ASSERT(build_context.word_size == 8);
  3967. GB_ASSERT(id <= (1ull<<56u));
  3968. data |= (id &~ (1ull<<56)) << 0ul; // index
  3969. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  3970. data |= (named &~ (1ull<<1)) << 61ull; // kind
  3971. data |= (special &~ (1ull<<1)) << 62ull; // kind
  3972. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  3973. }
  3974. lbValue res = {};
  3975. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  3976. res.type = t_typeid;
  3977. return res;
  3978. }
  3979. lbValue lb_type_info(lbModule *m, Type *type) {
  3980. type = default_type(type);
  3981. isize index = lb_type_info_index(m->info, type);
  3982. GB_ASSERT(index >= 0);
  3983. LLVMTypeRef it = lb_type(m, t_int);
  3984. LLVMValueRef indices[2] = {
  3985. LLVMConstInt(it, 0, false),
  3986. LLVMConstInt(it, index, true),
  3987. };
  3988. lbValue value = {};
  3989. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  3990. value.type = t_type_info_ptr;
  3991. return value;
  3992. }
  3993. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  3994. bool is_local = allow_local && m->curr_procedure != nullptr;
  3995. bool is_const = true;
  3996. if (is_local) {
  3997. for (isize i = 0; i < count; i++) {
  3998. GB_ASSERT(values[i] != nullptr);
  3999. if (!LLVMIsConstant(values[i])) {
  4000. is_const = false;
  4001. break;
  4002. }
  4003. }
  4004. }
  4005. if (!is_const) {
  4006. lbProcedure *p = m->curr_procedure;
  4007. GB_ASSERT(p != nullptr);
  4008. lbAddr v = lb_add_local_generated(p, type, false);
  4009. lbValue ptr = lb_addr_get_ptr(p, v);
  4010. for (isize i = 0; i < count; i++) {
  4011. lbValue elem = lb_emit_array_epi(p, ptr, i);
  4012. LLVMBuildStore(p->builder, values[i], elem.value);
  4013. }
  4014. return lb_addr_load(p, v).value;
  4015. }
  4016. return LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)count);
  4017. }
  4018. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4019. LLVMContextRef ctx = m->ctx;
  4020. type = default_type(type);
  4021. Type *original_type = type;
  4022. lbValue res = {};
  4023. res.type = original_type;
  4024. type = core_type(type);
  4025. value = convert_exact_value_for_type(value, type);
  4026. if (value.kind == ExactValue_Typeid) {
  4027. return lb_typeid(m, value.value_typeid);
  4028. }
  4029. if (value.kind == ExactValue_Invalid) {
  4030. return lb_const_nil(m, type);
  4031. }
  4032. if (value.kind == ExactValue_Procedure) {
  4033. Ast *expr = unparen_expr(value.value_procedure);
  4034. if (expr->kind == Ast_ProcLit) {
  4035. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4036. }
  4037. Entity *e = entity_from_expr(expr);
  4038. e = strip_entity_wrapping(e);
  4039. GB_ASSERT(e != nullptr);
  4040. auto *found = map_get(&m->values, hash_entity(e));
  4041. if (found) {
  4042. return *found;
  4043. }
  4044. GB_PANIC("Error in: %.*s(%td:%td), missing procedure %.*s\n", LIT(e->token.pos.file), e->token.pos.line, e->token.pos.column, LIT(e->token.string));
  4045. }
  4046. bool is_local = allow_local && m->curr_procedure != nullptr;
  4047. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4048. if (is_type_slice(type)) {
  4049. if (value.kind == ExactValue_String) {
  4050. GB_ASSERT(is_type_u8_slice(type));
  4051. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4052. return res;
  4053. } else {
  4054. ast_node(cl, CompoundLit, value.value_compound);
  4055. isize count = cl->elems.count;
  4056. if (count == 0) {
  4057. return lb_const_nil(m, type);
  4058. }
  4059. count = gb_max(cl->max_count, count);
  4060. Type *elem = base_type(type)->Slice.elem;
  4061. Type *t = alloc_type_array(elem, count);
  4062. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4063. LLVMValueRef array_data = nullptr;
  4064. if (is_local) {
  4065. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4066. // its backing data on the stack
  4067. lbProcedure *p = m->curr_procedure;
  4068. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4069. LLVMTypeRef llvm_type = lb_type(m, t);
  4070. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4071. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4072. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4073. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4074. {
  4075. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4076. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4077. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4078. lbAddr slice = lb_add_local_generated(p, type, false);
  4079. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4080. return lb_addr_load(p, slice);
  4081. }
  4082. } else {
  4083. isize max_len = 7+8+1;
  4084. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4085. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4086. m->global_array_index++;
  4087. String name = make_string(cast(u8 *)str, len-1);
  4088. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4089. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4090. LLVMSetInitializer(array_data, backing_array.value);
  4091. lbValue g = {};
  4092. g.value = array_data;
  4093. g.type = t;
  4094. lb_add_entity(m, e, g);
  4095. lb_add_member(m, name, g);
  4096. {
  4097. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4098. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4099. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4100. LLVMValueRef values[2] = {ptr, len};
  4101. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4102. return res;
  4103. }
  4104. }
  4105. }
  4106. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4107. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4108. i64 count = type->Array.count;
  4109. Type *elem = type->Array.elem;
  4110. LLVMTypeRef et = lb_type(m, elem);
  4111. Rune rune;
  4112. isize offset = 0;
  4113. isize width = 1;
  4114. String s = value.value_string;
  4115. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4116. for (i64 i = 0; i < count && offset < s.len; i++) {
  4117. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4118. offset += width;
  4119. elems[i] = LLVMConstInt(et, rune, true);
  4120. }
  4121. GB_ASSERT(offset == s.len);
  4122. res.value = LLVMConstArray(et, elems, cast(unsigned)count);
  4123. return res;
  4124. }
  4125. GB_PANIC("HERE!\n");
  4126. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4127. cast(char const *)value.value_string.text,
  4128. cast(unsigned)value.value_string.len,
  4129. false /*DontNullTerminate*/);
  4130. res.value = data;
  4131. return res;
  4132. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4133. GB_ASSERT(type->Array.count == value.value_string.len);
  4134. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4135. cast(char const *)value.value_string.text,
  4136. cast(unsigned)value.value_string.len,
  4137. true /*DontNullTerminate*/);
  4138. res.value = data;
  4139. return res;
  4140. } else if (is_type_array(type) &&
  4141. value.kind != ExactValue_Invalid &&
  4142. value.kind != ExactValue_String &&
  4143. value.kind != ExactValue_Compound) {
  4144. i64 count = type->Array.count;
  4145. Type *elem = type->Array.elem;
  4146. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4147. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4148. for (i64 i = 0; i < count; i++) {
  4149. elems[i] = single_elem.value;
  4150. }
  4151. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  4152. return res;
  4153. }
  4154. switch (value.kind) {
  4155. case ExactValue_Invalid:
  4156. res.value = LLVMConstNull(lb_type(m, original_type));
  4157. return res;
  4158. case ExactValue_Bool:
  4159. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4160. return res;
  4161. case ExactValue_String:
  4162. {
  4163. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4164. lbValue res = {};
  4165. res.type = default_type(original_type);
  4166. if (is_type_cstring(res.type)) {
  4167. res.value = ptr;
  4168. } else {
  4169. if (value.value_string.len == 0) {
  4170. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4171. }
  4172. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4173. LLVMValueRef values[2] = {ptr, str_len};
  4174. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4175. }
  4176. return res;
  4177. }
  4178. case ExactValue_Integer:
  4179. if (is_type_pointer(type)) {
  4180. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4181. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4182. } else {
  4183. unsigned len = cast(unsigned)value.value_integer.len;
  4184. if (len == 0) {
  4185. u64 word = 0;
  4186. res.value = LLVMConstNull(lb_type(m, original_type));
  4187. } else {
  4188. u64 *words = big_int_ptr(&value.value_integer);
  4189. if (is_type_different_to_arch_endianness(type)) {
  4190. // NOTE(bill): Swap byte order for different endianness
  4191. i64 sz = type_size_of(type);
  4192. isize byte_len = gb_size_of(u64)*len;
  4193. u8 *old_bytes = cast(u8 *)words;
  4194. // TODO(bill): Use a different allocator here for a temporary allocation
  4195. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4196. for (i64 i = 0; i < sz; i++) {
  4197. new_bytes[i] = old_bytes[sz-1-i];
  4198. }
  4199. words = cast(u64 *)new_bytes;
  4200. }
  4201. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4202. if (value.value_integer.neg) {
  4203. res.value = LLVMConstNeg(res.value);
  4204. }
  4205. }
  4206. }
  4207. return res;
  4208. case ExactValue_Float:
  4209. if (type_size_of(type) == 4) {
  4210. f32 f = cast(f32)value.value_float;
  4211. res.value = lb_const_f32(m, f, type);
  4212. return res;
  4213. }
  4214. if (is_type_different_to_arch_endianness(type)) {
  4215. u64 u = bit_cast<u64>(value.value_float);
  4216. u = gb_endian_swap64(u);
  4217. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4218. } else {
  4219. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4220. }
  4221. return res;
  4222. case ExactValue_Complex:
  4223. {
  4224. LLVMValueRef values[2] = {};
  4225. switch (8*type_size_of(type)) {
  4226. case 64:
  4227. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  4228. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  4229. break;
  4230. case 128:
  4231. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  4232. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  4233. break;
  4234. }
  4235. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4236. return res;
  4237. }
  4238. break;
  4239. case ExactValue_Quaternion:
  4240. {
  4241. LLVMValueRef values[4] = {};
  4242. switch (8*type_size_of(type)) {
  4243. case 128:
  4244. // @QuaternionLayout
  4245. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  4246. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  4247. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  4248. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  4249. break;
  4250. case 256:
  4251. // @QuaternionLayout
  4252. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  4253. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  4254. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  4255. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  4256. break;
  4257. }
  4258. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  4259. return res;
  4260. }
  4261. break;
  4262. case ExactValue_Pointer:
  4263. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4264. return res;
  4265. case ExactValue_Compound:
  4266. if (is_type_slice(type)) {
  4267. return lb_const_value(m, type, value, allow_local);
  4268. } else if (is_type_array(type)) {
  4269. ast_node(cl, CompoundLit, value.value_compound);
  4270. Type *elem_type = type->Array.elem;
  4271. isize elem_count = cl->elems.count;
  4272. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4273. return lb_const_nil(m, original_type);
  4274. }
  4275. if (cl->elems[0]->kind == Ast_FieldValue) {
  4276. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4277. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4278. isize value_index = 0;
  4279. for (i64 i = 0; i < type->Array.count; i++) {
  4280. bool found = false;
  4281. for (isize j = 0; j < elem_count; j++) {
  4282. Ast *elem = cl->elems[j];
  4283. ast_node(fv, FieldValue, elem);
  4284. if (is_ast_range(fv->field)) {
  4285. ast_node(ie, BinaryExpr, fv->field);
  4286. TypeAndValue lo_tav = ie->left->tav;
  4287. TypeAndValue hi_tav = ie->right->tav;
  4288. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4289. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4290. TokenKind op = ie->op.kind;
  4291. i64 lo = exact_value_to_i64(lo_tav.value);
  4292. i64 hi = exact_value_to_i64(hi_tav.value);
  4293. if (op == Token_Ellipsis) {
  4294. hi += 1;
  4295. }
  4296. if (lo == i) {
  4297. TypeAndValue tav = fv->value->tav;
  4298. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4299. for (i64 k = lo; k < hi; k++) {
  4300. values[value_index++] = val;
  4301. }
  4302. found = true;
  4303. i += (hi-lo-1);
  4304. break;
  4305. }
  4306. } else {
  4307. TypeAndValue index_tav = fv->field->tav;
  4308. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4309. i64 index = exact_value_to_i64(index_tav.value);
  4310. if (index == i) {
  4311. TypeAndValue tav = fv->value->tav;
  4312. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4313. values[value_index++] = val;
  4314. found = true;
  4315. break;
  4316. }
  4317. }
  4318. }
  4319. if (!found) {
  4320. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4321. }
  4322. }
  4323. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4324. return res;
  4325. } else {
  4326. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4327. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4328. for (isize i = 0; i < elem_count; i++) {
  4329. TypeAndValue tav = cl->elems[i]->tav;
  4330. GB_ASSERT(tav.mode != Addressing_Invalid);
  4331. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4332. }
  4333. for (isize i = elem_count; i < type->Array.count; i++) {
  4334. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4335. }
  4336. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4337. return res;
  4338. }
  4339. } else if (is_type_enumerated_array(type)) {
  4340. ast_node(cl, CompoundLit, value.value_compound);
  4341. Type *elem_type = type->EnumeratedArray.elem;
  4342. isize elem_count = cl->elems.count;
  4343. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4344. return lb_const_nil(m, original_type);
  4345. }
  4346. if (cl->elems[0]->kind == Ast_FieldValue) {
  4347. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4348. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4349. isize value_index = 0;
  4350. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4351. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4352. for (i64 i = total_lo; i <= total_hi; i++) {
  4353. bool found = false;
  4354. for (isize j = 0; j < elem_count; j++) {
  4355. Ast *elem = cl->elems[j];
  4356. ast_node(fv, FieldValue, elem);
  4357. if (is_ast_range(fv->field)) {
  4358. ast_node(ie, BinaryExpr, fv->field);
  4359. TypeAndValue lo_tav = ie->left->tav;
  4360. TypeAndValue hi_tav = ie->right->tav;
  4361. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4362. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4363. TokenKind op = ie->op.kind;
  4364. i64 lo = exact_value_to_i64(lo_tav.value);
  4365. i64 hi = exact_value_to_i64(hi_tav.value);
  4366. if (op == Token_Ellipsis) {
  4367. hi += 1;
  4368. }
  4369. if (lo == i) {
  4370. TypeAndValue tav = fv->value->tav;
  4371. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4372. for (i64 k = lo; k < hi; k++) {
  4373. values[value_index++] = val;
  4374. }
  4375. found = true;
  4376. i += (hi-lo-1);
  4377. break;
  4378. }
  4379. } else {
  4380. TypeAndValue index_tav = fv->field->tav;
  4381. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4382. i64 index = exact_value_to_i64(index_tav.value);
  4383. if (index == i) {
  4384. TypeAndValue tav = fv->value->tav;
  4385. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4386. values[value_index++] = val;
  4387. found = true;
  4388. break;
  4389. }
  4390. }
  4391. }
  4392. if (!found) {
  4393. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4394. }
  4395. }
  4396. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4397. return res;
  4398. } else {
  4399. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4400. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4401. for (isize i = 0; i < elem_count; i++) {
  4402. TypeAndValue tav = cl->elems[i]->tav;
  4403. GB_ASSERT(tav.mode != Addressing_Invalid);
  4404. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4405. }
  4406. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4407. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4408. }
  4409. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4410. return res;
  4411. }
  4412. } else if (is_type_simd_vector(type)) {
  4413. ast_node(cl, CompoundLit, value.value_compound);
  4414. Type *elem_type = type->SimdVector.elem;
  4415. isize elem_count = cl->elems.count;
  4416. if (elem_count == 0) {
  4417. return lb_const_nil(m, original_type);
  4418. }
  4419. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4420. isize total_elem_count = type->SimdVector.count;
  4421. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  4422. for (isize i = 0; i < elem_count; i++) {
  4423. TypeAndValue tav = cl->elems[i]->tav;
  4424. GB_ASSERT(tav.mode != Addressing_Invalid);
  4425. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4426. }
  4427. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  4428. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4429. }
  4430. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  4431. return res;
  4432. } else if (is_type_struct(type)) {
  4433. ast_node(cl, CompoundLit, value.value_compound);
  4434. if (cl->elems.count == 0) {
  4435. return lb_const_nil(m, original_type);
  4436. }
  4437. isize offset = 0;
  4438. if (type->Struct.custom_align > 0) {
  4439. offset = 1;
  4440. }
  4441. isize value_count = type->Struct.fields.count + offset;
  4442. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  4443. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  4444. if (cl->elems.count > 0) {
  4445. if (cl->elems[0]->kind == Ast_FieldValue) {
  4446. isize elem_count = cl->elems.count;
  4447. for (isize i = 0; i < elem_count; i++) {
  4448. ast_node(fv, FieldValue, cl->elems[i]);
  4449. String name = fv->field->Ident.token.string;
  4450. TypeAndValue tav = fv->value->tav;
  4451. GB_ASSERT(tav.mode != Addressing_Invalid);
  4452. Selection sel = lookup_field(type, name, false);
  4453. Entity *f = type->Struct.fields[sel.index[0]];
  4454. if (elem_type_can_be_constant(f->type)) {
  4455. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  4456. visited[offset+f->Variable.field_index] = true;
  4457. }
  4458. }
  4459. } else {
  4460. for_array(i, cl->elems) {
  4461. Entity *f = type->Struct.fields[i];
  4462. TypeAndValue tav = cl->elems[i]->tav;
  4463. ExactValue val = {};
  4464. if (tav.mode != Addressing_Invalid) {
  4465. val = tav.value;
  4466. }
  4467. if (elem_type_can_be_constant(f->type)) {
  4468. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  4469. visited[offset+f->Variable.field_index] = true;
  4470. }
  4471. }
  4472. }
  4473. }
  4474. for (isize i = 0; i < type->Struct.fields.count; i++) {
  4475. if (!visited[offset+i]) {
  4476. GB_ASSERT(values[offset+i] == nullptr);
  4477. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  4478. }
  4479. }
  4480. if (type->Struct.custom_align > 0) {
  4481. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  4482. }
  4483. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  4484. return res;
  4485. } else if (is_type_bit_set(type)) {
  4486. ast_node(cl, CompoundLit, value.value_compound);
  4487. if (cl->elems.count == 0) {
  4488. return lb_const_nil(m, original_type);
  4489. }
  4490. i64 sz = type_size_of(type);
  4491. if (sz == 0) {
  4492. return lb_const_nil(m, original_type);
  4493. }
  4494. u64 bits = 0;
  4495. for_array(i, cl->elems) {
  4496. Ast *e = cl->elems[i];
  4497. GB_ASSERT(e->kind != Ast_FieldValue);
  4498. TypeAndValue tav = e->tav;
  4499. if (tav.mode != Addressing_Constant) {
  4500. continue;
  4501. }
  4502. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  4503. i64 v = big_int_to_i64(&tav.value.value_integer);
  4504. i64 lower = type->BitSet.lower;
  4505. bits |= 1ull<<cast(u64)(v-lower);
  4506. }
  4507. if (is_type_different_to_arch_endianness(type)) {
  4508. i64 size = type_size_of(type);
  4509. switch (size) {
  4510. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  4511. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  4512. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  4513. }
  4514. }
  4515. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  4516. return res;
  4517. } else {
  4518. return lb_const_nil(m, original_type);
  4519. }
  4520. break;
  4521. case ExactValue_Procedure:
  4522. {
  4523. Ast *expr = value.value_procedure;
  4524. GB_ASSERT(expr != nullptr);
  4525. if (expr->kind == Ast_ProcLit) {
  4526. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4527. }
  4528. }
  4529. break;
  4530. case ExactValue_Typeid:
  4531. return lb_typeid(m, value.value_typeid);
  4532. }
  4533. return lb_const_nil(m, original_type);
  4534. }
  4535. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  4536. lbModule *m = p->module;
  4537. LLVMValueRef fields[4] = {};
  4538. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  4539. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  4540. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  4541. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  4542. lbValue res = {};
  4543. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  4544. res.type = t_source_code_location;
  4545. return res;
  4546. }
  4547. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  4548. String proc_name = {};
  4549. if (p->entity) {
  4550. proc_name = p->entity->token.string;
  4551. }
  4552. TokenPos pos = {};
  4553. if (node) {
  4554. pos = ast_token(node).pos;
  4555. }
  4556. return lb_emit_source_code_location(p, proc_name, pos);
  4557. }
  4558. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  4559. switch (op) {
  4560. case Token_Add:
  4561. return x;
  4562. case Token_Not: // Boolean not
  4563. case Token_Xor: // Bitwise not
  4564. case Token_Sub: // Number negation
  4565. break;
  4566. case Token_Pointer:
  4567. GB_PANIC("This should be handled elsewhere");
  4568. break;
  4569. }
  4570. if (is_type_array(x.type)) {
  4571. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  4572. Type *tl = base_type(x.type);
  4573. lbValue val = lb_address_from_load_or_generate_local(p, x);
  4574. GB_ASSERT(is_type_array(type));
  4575. Type *elem_type = base_array_type(type);
  4576. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4577. lbAddr res_addr = lb_add_local_generated(p, type, false);
  4578. lbValue res = lb_addr_get_ptr(p, res_addr);
  4579. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4580. i32 count = cast(i32)tl->Array.count;
  4581. if (inline_array_arith) {
  4582. // inline
  4583. for (i32 i = 0; i < count; i++) {
  4584. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  4585. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4586. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  4587. }
  4588. } else {
  4589. auto loop_data = lb_loop_start(p, count, t_i32);
  4590. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  4591. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4592. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  4593. lb_loop_end(p, loop_data);
  4594. }
  4595. return lb_emit_load(p, res);
  4596. }
  4597. if (op == Token_Xor) {
  4598. lbValue cmp = {};
  4599. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  4600. cmp.type = x.type;
  4601. return lb_emit_conv(p, cmp, type);
  4602. }
  4603. if (op == Token_Not) {
  4604. lbValue cmp = {};
  4605. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  4606. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  4607. cmp.type = t_llvm_bool;
  4608. return lb_emit_conv(p, cmp, type);
  4609. }
  4610. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4611. Type *platform_type = integer_endian_type_to_platform_type(type);
  4612. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4613. lbValue res = {};
  4614. res.value = LLVMBuildNeg(p->builder, v.value, "");
  4615. res.type = platform_type;
  4616. return lb_emit_byte_swap(p, res, type);
  4617. }
  4618. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4619. Type *platform_type = integer_endian_type_to_platform_type(type);
  4620. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4621. lbValue res = {};
  4622. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  4623. res.type = platform_type;
  4624. return lb_emit_byte_swap(p, res, type);
  4625. }
  4626. lbValue res = {};
  4627. switch (op) {
  4628. case Token_Not: // Boolean not
  4629. case Token_Xor: // Bitwise not
  4630. res.value = LLVMBuildNot(p->builder, x.value, "");
  4631. res.type = x.type;
  4632. return res;
  4633. case Token_Sub: // Number negation
  4634. if (is_type_integer(x.type)) {
  4635. res.value = LLVMBuildNeg(p->builder, x.value, "");
  4636. } else if (is_type_float(x.type)) {
  4637. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  4638. } else if (is_type_complex(x.type)) {
  4639. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4640. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4641. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4642. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4643. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4644. return lb_addr_load(p, addr);
  4645. } else if (is_type_quaternion(x.type)) {
  4646. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4647. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4648. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  4649. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  4650. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4651. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4652. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4653. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  4654. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  4655. return lb_addr_load(p, addr);
  4656. } else {
  4657. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  4658. }
  4659. res.type = x.type;
  4660. return res;
  4661. }
  4662. return res;
  4663. }
  4664. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  4665. lbModule *m = p->module;
  4666. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  4667. lhs = lb_emit_conv(p, lhs, type);
  4668. rhs = lb_emit_conv(p, rhs, type);
  4669. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  4670. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4671. GB_ASSERT(is_type_array(type));
  4672. Type *elem_type = base_array_type(type);
  4673. lbAddr res = lb_add_local_generated(p, type, false);
  4674. i64 count = base_type(type)->Array.count;
  4675. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4676. if (inline_array_arith) {
  4677. for (i64 i = 0; i < count; i++) {
  4678. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  4679. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  4680. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  4681. lbValue a = lb_emit_load(p, a_ptr);
  4682. lbValue b = lb_emit_load(p, b_ptr);
  4683. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4684. lb_emit_store(p, dst_ptr, c);
  4685. }
  4686. } else {
  4687. auto loop_data = lb_loop_start(p, count, t_i32);
  4688. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  4689. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  4690. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  4691. lbValue a = lb_emit_load(p, a_ptr);
  4692. lbValue b = lb_emit_load(p, b_ptr);
  4693. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4694. lb_emit_store(p, dst_ptr, c);
  4695. lb_loop_end(p, loop_data);
  4696. }
  4697. return lb_addr_load(p, res);
  4698. } else if (is_type_complex(type)) {
  4699. lhs = lb_emit_conv(p, lhs, type);
  4700. rhs = lb_emit_conv(p, rhs, type);
  4701. Type *ft = base_complex_elem_type(type);
  4702. if (op == Token_Quo) {
  4703. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4704. args[0] = lhs;
  4705. args[1] = rhs;
  4706. switch (type_size_of(ft)) {
  4707. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  4708. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  4709. default: GB_PANIC("Unknown float type"); break;
  4710. }
  4711. }
  4712. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4713. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  4714. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  4715. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  4716. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  4717. lbValue real = {};
  4718. lbValue imag = {};
  4719. switch (op) {
  4720. case Token_Add:
  4721. real = lb_emit_arith(p, Token_Add, a, c, ft);
  4722. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  4723. break;
  4724. case Token_Sub:
  4725. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  4726. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  4727. break;
  4728. case Token_Mul: {
  4729. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  4730. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  4731. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  4732. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  4733. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  4734. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  4735. break;
  4736. }
  4737. }
  4738. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  4739. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  4740. return lb_addr_load(p, res);
  4741. } else if (is_type_quaternion(type)) {
  4742. lhs = lb_emit_conv(p, lhs, type);
  4743. rhs = lb_emit_conv(p, rhs, type);
  4744. Type *ft = base_complex_elem_type(type);
  4745. if (op == Token_Add || op == Token_Sub) {
  4746. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4747. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  4748. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  4749. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  4750. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  4751. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  4752. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  4753. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  4754. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  4755. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  4756. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  4757. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  4758. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  4759. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  4760. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  4761. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  4762. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  4763. return lb_addr_load(p, res);
  4764. } else if (op == Token_Mul) {
  4765. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4766. args[0] = lhs;
  4767. args[1] = rhs;
  4768. switch (8*type_size_of(ft)) {
  4769. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  4770. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  4771. default: GB_PANIC("Unknown float type"); break;
  4772. }
  4773. } else if (op == Token_Quo) {
  4774. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4775. args[0] = lhs;
  4776. args[1] = rhs;
  4777. switch (8*type_size_of(ft)) {
  4778. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  4779. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  4780. default: GB_PANIC("Unknown float type"); break;
  4781. }
  4782. }
  4783. }
  4784. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4785. switch (op) {
  4786. case Token_AndNot:
  4787. case Token_And:
  4788. case Token_Or:
  4789. case Token_Xor:
  4790. goto handle_op;
  4791. }
  4792. Type *platform_type = integer_endian_type_to_platform_type(type);
  4793. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4794. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4795. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4796. return lb_emit_byte_swap(p, res, type);
  4797. }
  4798. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4799. Type *platform_type = integer_endian_type_to_platform_type(type);
  4800. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4801. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4802. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4803. return lb_emit_byte_swap(p, res, type);
  4804. }
  4805. handle_op:
  4806. lhs = lb_emit_conv(p, lhs, type);
  4807. rhs = lb_emit_conv(p, rhs, type);
  4808. lbValue res = {};
  4809. res.type = type;
  4810. switch (op) {
  4811. case Token_Add:
  4812. if (is_type_float(type)) {
  4813. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  4814. return res;
  4815. }
  4816. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  4817. return res;
  4818. case Token_Sub:
  4819. if (is_type_float(type)) {
  4820. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  4821. return res;
  4822. }
  4823. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  4824. return res;
  4825. case Token_Mul:
  4826. if (is_type_float(type)) {
  4827. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  4828. return res;
  4829. }
  4830. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  4831. return res;
  4832. case Token_Quo:
  4833. if (is_type_float(type)) {
  4834. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  4835. return res;
  4836. } else if (is_type_unsigned(type)) {
  4837. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  4838. return res;
  4839. }
  4840. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  4841. return res;
  4842. case Token_Mod:
  4843. if (is_type_float(type)) {
  4844. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  4845. return res;
  4846. } else if (is_type_unsigned(type)) {
  4847. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  4848. return res;
  4849. }
  4850. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  4851. return res;
  4852. case Token_ModMod:
  4853. if (is_type_unsigned(type)) {
  4854. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  4855. return res;
  4856. } else {
  4857. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  4858. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  4859. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  4860. res.value = c;
  4861. return res;
  4862. }
  4863. case Token_And:
  4864. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  4865. return res;
  4866. case Token_Or:
  4867. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  4868. return res;
  4869. case Token_Xor:
  4870. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  4871. return res;
  4872. case Token_Shl:
  4873. {
  4874. rhs = lb_emit_conv(p, rhs, lhs.type);
  4875. LLVMValueRef lhsval = lhs.value;
  4876. LLVMValueRef bits = rhs.value;
  4877. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  4878. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  4879. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  4880. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  4881. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  4882. return res;
  4883. }
  4884. case Token_Shr:
  4885. {
  4886. rhs = lb_emit_conv(p, rhs, lhs.type);
  4887. LLVMValueRef lhsval = lhs.value;
  4888. LLVMValueRef bits = rhs.value;
  4889. bool is_unsigned = is_type_unsigned(type);
  4890. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  4891. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  4892. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  4893. if (is_unsigned) {
  4894. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  4895. } else {
  4896. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  4897. }
  4898. return res;
  4899. }
  4900. case Token_AndNot:
  4901. {
  4902. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  4903. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  4904. return res;
  4905. }
  4906. break;
  4907. }
  4908. GB_PANIC("unhandled operator of lb_emit_arith");
  4909. return {};
  4910. }
  4911. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  4912. ast_node(be, BinaryExpr, expr);
  4913. TypeAndValue tv = type_and_value_of_expr(expr);
  4914. switch (be->op.kind) {
  4915. case Token_Add:
  4916. case Token_Sub:
  4917. case Token_Mul:
  4918. case Token_Quo:
  4919. case Token_Mod:
  4920. case Token_ModMod:
  4921. case Token_And:
  4922. case Token_Or:
  4923. case Token_Xor:
  4924. case Token_AndNot:
  4925. case Token_Shl:
  4926. case Token_Shr: {
  4927. Type *type = default_type(tv.type);
  4928. lbValue left = lb_build_expr(p, be->left);
  4929. lbValue right = lb_build_expr(p, be->right);
  4930. return lb_emit_arith(p, be->op.kind, left, right, type);
  4931. }
  4932. case Token_CmpEq:
  4933. case Token_NotEq:
  4934. case Token_Lt:
  4935. case Token_LtEq:
  4936. case Token_Gt:
  4937. case Token_GtEq:
  4938. {
  4939. lbValue left = {};
  4940. lbValue right = {};
  4941. if (be->left->tav.mode == Addressing_Type) {
  4942. left = lb_typeid(p->module, be->left->tav.type);
  4943. }
  4944. if (be->right->tav.mode == Addressing_Type) {
  4945. right = lb_typeid(p->module, be->right->tav.type);
  4946. }
  4947. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  4948. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  4949. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  4950. Type *type = default_type(tv.type);
  4951. return lb_emit_conv(p, cmp, type);
  4952. }
  4953. case Token_CmpAnd:
  4954. case Token_CmpOr:
  4955. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  4956. case Token_in:
  4957. case Token_not_in:
  4958. {
  4959. lbValue left = lb_build_expr(p, be->left);
  4960. Type *type = default_type(tv.type);
  4961. lbValue right = lb_build_expr(p, be->right);
  4962. Type *rt = base_type(right.type);
  4963. switch (rt->kind) {
  4964. case Type_Map:
  4965. {
  4966. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  4967. lbValue h = lb_gen_map_header(p, addr, rt);
  4968. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  4969. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4970. args[0] = h;
  4971. args[1] = key;
  4972. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  4973. if (be->op.kind == Token_in) {
  4974. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  4975. } else {
  4976. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  4977. }
  4978. }
  4979. break;
  4980. case Type_BitSet:
  4981. {
  4982. Type *key_type = rt->BitSet.elem;
  4983. GB_ASSERT(are_types_identical(left.type, key_type));
  4984. Type *it = bit_set_to_int(rt);
  4985. left = lb_emit_conv(p, left, it);
  4986. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  4987. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  4988. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  4989. bit = lb_emit_conv(p, bit, it);
  4990. lbValue old_value = lb_emit_transmute(p, right, it);
  4991. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  4992. if (be->op.kind == Token_in) {
  4993. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  4994. } else {
  4995. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  4996. }
  4997. }
  4998. break;
  4999. default:
  5000. GB_PANIC("Invalid 'in' type");
  5001. }
  5002. break;
  5003. }
  5004. break;
  5005. default:
  5006. GB_PANIC("Invalid binary expression");
  5007. break;
  5008. }
  5009. return {};
  5010. }
  5011. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5012. Type *prev_src = src;
  5013. // Type *prev_dst = dst;
  5014. src = base_type(type_deref(src));
  5015. // dst = base_type(type_deref(dst));
  5016. bool src_is_ptr = src != prev_src;
  5017. // bool dst_is_ptr = dst != prev_dst;
  5018. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5019. for_array(i, src->Struct.fields) {
  5020. Entity *f = src->Struct.fields[i];
  5021. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5022. if (are_types_identical(dst, f->type)) {
  5023. return f->token.string;
  5024. }
  5025. if (src_is_ptr && is_type_pointer(dst)) {
  5026. if (are_types_identical(type_deref(dst), f->type)) {
  5027. return f->token.string;
  5028. }
  5029. }
  5030. if (is_type_struct(f->type)) {
  5031. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5032. if (name.len > 0) {
  5033. return name;
  5034. }
  5035. }
  5036. }
  5037. }
  5038. return str_lit("");
  5039. }
  5040. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5041. GB_ASSERT(is_type_pointer(value.type));
  5042. GB_ASSERT(is_type_pointer(t));
  5043. GB_ASSERT(lb_is_const(value));
  5044. lbValue res = {};
  5045. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5046. res.type = t;
  5047. return res;
  5048. }
  5049. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5050. lbModule *m = p->module;
  5051. t = reduce_tuple_to_single_type(t);
  5052. Type *src_type = value.type;
  5053. if (are_types_identical(t, src_type)) {
  5054. return value;
  5055. }
  5056. Type *src = core_type(src_type);
  5057. Type *dst = core_type(t);
  5058. GB_ASSERT(src != nullptr);
  5059. GB_ASSERT(dst != nullptr);
  5060. if (is_type_untyped_nil(src)) {
  5061. return lb_const_nil(m, t);
  5062. }
  5063. if (is_type_untyped_undef(src)) {
  5064. return lb_const_undef(m, t);
  5065. }
  5066. if (LLVMIsConstant(value.value)) {
  5067. if (is_type_any(dst)) {
  5068. Type *st = default_type(src_type);
  5069. lbAddr default_value = lb_add_local_generated(p, st, false);
  5070. lb_addr_store(p, default_value, value);
  5071. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5072. lbValue id = lb_typeid(m, st);
  5073. lbAddr res = lb_add_local_generated(p, t, false);
  5074. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5075. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5076. lb_emit_store(p, a0, data);
  5077. lb_emit_store(p, a1, id);
  5078. return lb_addr_load(p, res);
  5079. } else if (dst->kind == Type_Basic) {
  5080. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5081. String str = lb_get_const_string(m, value);
  5082. lbValue res = {};
  5083. res.type = t;
  5084. res.value = llvm_cstring(m, str);
  5085. return res;
  5086. }
  5087. // if (is_type_float(dst)) {
  5088. // return value;
  5089. // } else if (is_type_integer(dst)) {
  5090. // return value;
  5091. // }
  5092. // ExactValue ev = value->Constant.value;
  5093. // if (is_type_float(dst)) {
  5094. // ev = exact_value_to_float(ev);
  5095. // } else if (is_type_complex(dst)) {
  5096. // ev = exact_value_to_complex(ev);
  5097. // } else if (is_type_quaternion(dst)) {
  5098. // ev = exact_value_to_quaternion(ev);
  5099. // } else if (is_type_string(dst)) {
  5100. // // Handled elsewhere
  5101. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5102. // } else if (is_type_integer(dst)) {
  5103. // ev = exact_value_to_integer(ev);
  5104. // } else if (is_type_pointer(dst)) {
  5105. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5106. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5107. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5108. // }
  5109. // return lb_const_value(p->module, t, ev);
  5110. }
  5111. }
  5112. if (are_types_identical(src, dst)) {
  5113. if (!are_types_identical(src_type, t)) {
  5114. return lb_emit_transmute(p, value, t);
  5115. }
  5116. return value;
  5117. }
  5118. // bool <-> llvm bool
  5119. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5120. lbValue res = {};
  5121. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5122. res.type = dst;
  5123. return res;
  5124. }
  5125. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5126. lbValue res = {};
  5127. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5128. res.type = dst;
  5129. return res;
  5130. }
  5131. // integer -> integer
  5132. if (is_type_integer(src) && is_type_integer(dst)) {
  5133. GB_ASSERT(src->kind == Type_Basic &&
  5134. dst->kind == Type_Basic);
  5135. i64 sz = type_size_of(default_type(src));
  5136. i64 dz = type_size_of(default_type(dst));
  5137. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5138. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5139. value = lb_emit_byte_swap(p, value, platform_src_type);
  5140. }
  5141. LLVMOpcode op = LLVMTrunc;
  5142. if (dz < sz) {
  5143. op = LLVMTrunc;
  5144. } else if (dz == sz) {
  5145. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5146. // NOTE(bill): Copy the value just for type correctness
  5147. op = LLVMBitCast;
  5148. } else if (dz > sz) {
  5149. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5150. }
  5151. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5152. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5153. lbValue res = {};
  5154. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5155. res.type = t;
  5156. return lb_emit_byte_swap(p, res, t);
  5157. } else {
  5158. lbValue res = {};
  5159. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5160. res.type = t;
  5161. return res;
  5162. }
  5163. }
  5164. // boolean -> boolean/integer
  5165. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5166. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5167. lbValue res = {};
  5168. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5169. res.type = t;
  5170. return res;
  5171. }
  5172. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5173. return lb_emit_transmute(p, value, dst);
  5174. }
  5175. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5176. return lb_emit_transmute(p, value, dst);
  5177. }
  5178. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5179. return lb_emit_transmute(p, value, dst);
  5180. }
  5181. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5182. return lb_emit_transmute(p, value, dst);
  5183. }
  5184. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5185. lbValue c = lb_emit_conv(p, value, t_cstring);
  5186. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5187. args[0] = c;
  5188. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5189. return lb_emit_conv(p, s, dst);
  5190. }
  5191. // integer -> boolean
  5192. if (is_type_integer(src) && is_type_boolean(dst)) {
  5193. lbValue res = {};
  5194. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5195. res.type = t_llvm_bool;
  5196. return lb_emit_conv(p, res, t);
  5197. }
  5198. // float -> float
  5199. if (is_type_float(src) && is_type_float(dst)) {
  5200. i64 sz = type_size_of(src);
  5201. i64 dz = type_size_of(dst);
  5202. if (dz == sz) {
  5203. if (types_have_same_internal_endian(src, dst)) {
  5204. lbValue res = {};
  5205. res.type = t;
  5206. res.value = value.value;
  5207. return res;
  5208. } else {
  5209. return lb_emit_byte_swap(p, value, t);
  5210. }
  5211. }
  5212. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5213. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5214. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5215. lbValue res = {};
  5216. res = lb_emit_conv(p, value, platform_src_type);
  5217. res = lb_emit_conv(p, res, platform_dst_type);
  5218. if (is_type_different_to_arch_endianness(dst)) {
  5219. res = lb_emit_byte_swap(p, res, t);
  5220. }
  5221. return lb_emit_conv(p, res, t);
  5222. }
  5223. lbValue res = {};
  5224. res.type = t;
  5225. if (dz >= sz) {
  5226. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5227. } else {
  5228. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5229. }
  5230. return res;
  5231. }
  5232. if (is_type_complex(src) && is_type_complex(dst)) {
  5233. Type *ft = base_complex_elem_type(dst);
  5234. lbAddr gen = lb_add_local_generated(p, dst, false);
  5235. lbValue gp = lb_addr_get_ptr(p, gen);
  5236. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5237. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5238. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5239. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5240. return lb_addr_load(p, gen);
  5241. }
  5242. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5243. // @QuaternionLayout
  5244. Type *ft = base_complex_elem_type(dst);
  5245. lbAddr gen = lb_add_local_generated(p, dst, false);
  5246. lbValue gp = lb_addr_get_ptr(p, gen);
  5247. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5248. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5249. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5250. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5251. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5252. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5253. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5254. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5255. return lb_addr_load(p, gen);
  5256. }
  5257. if (is_type_float(src) && is_type_complex(dst)) {
  5258. Type *ft = base_complex_elem_type(dst);
  5259. lbAddr gen = lb_add_local_generated(p, dst, true);
  5260. lbValue gp = lb_addr_get_ptr(p, gen);
  5261. lbValue real = lb_emit_conv(p, value, ft);
  5262. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5263. return lb_addr_load(p, gen);
  5264. }
  5265. if (is_type_float(src) && is_type_quaternion(dst)) {
  5266. Type *ft = base_complex_elem_type(dst);
  5267. lbAddr gen = lb_add_local_generated(p, dst, true);
  5268. lbValue gp = lb_addr_get_ptr(p, gen);
  5269. lbValue real = lb_emit_conv(p, value, ft);
  5270. // @QuaternionLayout
  5271. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5272. return lb_addr_load(p, gen);
  5273. }
  5274. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5275. Type *ft = base_complex_elem_type(dst);
  5276. lbAddr gen = lb_add_local_generated(p, dst, true);
  5277. lbValue gp = lb_addr_get_ptr(p, gen);
  5278. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5279. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5280. // @QuaternionLayout
  5281. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5282. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5283. return lb_addr_load(p, gen);
  5284. }
  5285. // float <-> integer
  5286. if (is_type_float(src) && is_type_integer(dst)) {
  5287. lbValue res = {};
  5288. res.type = t;
  5289. if (is_type_unsigned(dst)) {
  5290. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5291. } else {
  5292. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5293. }
  5294. return res;
  5295. }
  5296. if (is_type_integer(src) && is_type_float(dst)) {
  5297. lbValue res = {};
  5298. res.type = t;
  5299. if (is_type_unsigned(src)) {
  5300. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5301. } else {
  5302. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5303. }
  5304. return res;
  5305. }
  5306. // Pointer <-> uintptr
  5307. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5308. lbValue res = {};
  5309. res.type = t;
  5310. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5311. return res;
  5312. }
  5313. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5314. lbValue res = {};
  5315. res.type = t;
  5316. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5317. return res;
  5318. }
  5319. #if 1
  5320. if (is_type_union(dst)) {
  5321. for_array(i, dst->Union.variants) {
  5322. Type *vt = dst->Union.variants[i];
  5323. if (are_types_identical(vt, src_type)) {
  5324. lbAddr parent = lb_add_local_generated(p, t, true);
  5325. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5326. return lb_addr_load(p, parent);
  5327. }
  5328. }
  5329. }
  5330. #endif
  5331. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5332. // subtype polymorphism casting
  5333. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5334. Type *st = type_deref(src_type);
  5335. Type *pst = st;
  5336. st = type_deref(st);
  5337. bool st_is_ptr = is_type_pointer(src_type);
  5338. st = base_type(st);
  5339. Type *dt = t;
  5340. bool dt_is_ptr = type_deref(dt) != dt;
  5341. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5342. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  5343. if (field_name.len > 0) {
  5344. // NOTE(bill): It can be casted
  5345. Selection sel = lookup_field(st, field_name, false, true);
  5346. if (sel.entity != nullptr) {
  5347. if (st_is_ptr) {
  5348. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  5349. Type *rt = res.type;
  5350. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5351. res = lb_emit_load(p, res);
  5352. }
  5353. return res;
  5354. } else {
  5355. if (is_type_pointer(value.type)) {
  5356. Type *rt = value.type;
  5357. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5358. value = lb_emit_load(p, value);
  5359. } else {
  5360. value = lb_emit_deep_field_gep(p, value, sel);
  5361. return lb_emit_load(p, value);
  5362. }
  5363. }
  5364. return lb_emit_deep_field_ev(p, value, sel);
  5365. }
  5366. } else {
  5367. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5368. }
  5369. }
  5370. }
  5371. // Pointer <-> Pointer
  5372. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5373. lbValue res = {};
  5374. res.type = t;
  5375. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5376. return res;
  5377. }
  5378. // proc <-> proc
  5379. if (is_type_proc(src) && is_type_proc(dst)) {
  5380. lbValue res = {};
  5381. res.type = t;
  5382. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5383. return res;
  5384. }
  5385. // pointer -> proc
  5386. if (is_type_pointer(src) && is_type_proc(dst)) {
  5387. lbValue res = {};
  5388. res.type = t;
  5389. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5390. return res;
  5391. }
  5392. // proc -> pointer
  5393. if (is_type_proc(src) && is_type_pointer(dst)) {
  5394. lbValue res = {};
  5395. res.type = t;
  5396. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5397. return res;
  5398. }
  5399. // []byte/[]u8 <-> string
  5400. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5401. return lb_emit_transmute(p, value, t);
  5402. }
  5403. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5404. return lb_emit_transmute(p, value, t);
  5405. }
  5406. if (is_type_array(dst)) {
  5407. Type *elem = dst->Array.elem;
  5408. lbValue e = lb_emit_conv(p, value, elem);
  5409. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5410. lbAddr v = lb_add_local_generated(p, t, false);
  5411. isize index_count = cast(isize)dst->Array.count;
  5412. for (isize i = 0; i < index_count; i++) {
  5413. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  5414. lb_emit_store(p, elem, e);
  5415. }
  5416. return lb_addr_load(p, v);
  5417. }
  5418. if (is_type_any(dst)) {
  5419. if (is_type_untyped_nil(src)) {
  5420. return lb_const_nil(p->module, t);
  5421. }
  5422. if (is_type_untyped_undef(src)) {
  5423. return lb_const_undef(p->module, t);
  5424. }
  5425. lbAddr result = lb_add_local_generated(p, t, true);
  5426. Type *st = default_type(src_type);
  5427. lbValue data = lb_address_from_load_or_generate_local(p, value);
  5428. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  5429. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5430. data = lb_emit_conv(p, data, t_rawptr);
  5431. lbValue id = lb_typeid(p->module, st);
  5432. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  5433. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  5434. lb_emit_store(p, any_data, data);
  5435. lb_emit_store(p, any_id, id);
  5436. return lb_addr_load(p, result);
  5437. }
  5438. i64 src_sz = type_size_of(src);
  5439. i64 dst_sz = type_size_of(dst);
  5440. if (src_sz == dst_sz) {
  5441. // bit_set <-> integer
  5442. if (is_type_integer(src) && is_type_bit_set(dst)) {
  5443. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  5444. res.type = dst;
  5445. return res;
  5446. }
  5447. if (is_type_bit_set(src) && is_type_integer(dst)) {
  5448. lbValue bs = value;
  5449. bs.type = bit_set_to_int(src);
  5450. return lb_emit_conv(p, bs, dst);
  5451. }
  5452. // typeid <-> integer
  5453. if (is_type_integer(src) && is_type_typeid(dst)) {
  5454. return lb_emit_transmute(p, value, dst);
  5455. }
  5456. if (is_type_typeid(src) && is_type_integer(dst)) {
  5457. return lb_emit_transmute(p, value, dst);
  5458. }
  5459. }
  5460. if (is_type_untyped(src)) {
  5461. if (is_type_string(src) && is_type_string(dst)) {
  5462. lbAddr result = lb_add_local_generated(p, t, false);
  5463. lb_addr_store(p, result, value);
  5464. return lb_addr_load(p, result);
  5465. }
  5466. }
  5467. gb_printf_err("%.*s\n", LIT(p->name));
  5468. gb_printf_err("lb_emit_conv: src -> dst\n");
  5469. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5470. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5471. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  5472. gb_printf_err("Not Identical %p != %p\n", src, dst);
  5473. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5474. type_to_string(src_type), type_to_string(t),
  5475. LIT(p->name));
  5476. return {};
  5477. }
  5478. bool lb_is_type_aggregate(Type *t) {
  5479. t = base_type(t);
  5480. switch (t->kind) {
  5481. case Type_Basic:
  5482. switch (t->Basic.kind) {
  5483. case Basic_string:
  5484. case Basic_any:
  5485. return true;
  5486. // case Basic_complex32:
  5487. case Basic_complex64:
  5488. case Basic_complex128:
  5489. case Basic_quaternion128:
  5490. case Basic_quaternion256:
  5491. return true;
  5492. }
  5493. break;
  5494. case Type_Pointer:
  5495. return false;
  5496. case Type_Array:
  5497. case Type_Slice:
  5498. case Type_Struct:
  5499. case Type_Union:
  5500. case Type_Tuple:
  5501. case Type_DynamicArray:
  5502. case Type_Map:
  5503. case Type_SimdVector:
  5504. return true;
  5505. case Type_Named:
  5506. return lb_is_type_aggregate(t->Named.base);
  5507. }
  5508. return false;
  5509. }
  5510. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  5511. Type *src_type = value.type;
  5512. if (are_types_identical(t, src_type)) {
  5513. return value;
  5514. }
  5515. lbValue res = {};
  5516. res.type = t;
  5517. Type *src = base_type(src_type);
  5518. Type *dst = base_type(t);
  5519. lbModule *m = p->module;
  5520. i64 sz = type_size_of(src);
  5521. i64 dz = type_size_of(dst);
  5522. if (sz != dz) {
  5523. LLVMTypeRef s = lb_type(m, src);
  5524. LLVMTypeRef d = lb_type(m, dst);
  5525. i64 llvm_sz = lb_sizeof(s);
  5526. i64 llvm_dz = lb_sizeof(d);
  5527. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  5528. }
  5529. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5530. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5531. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5532. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5533. return res;
  5534. }
  5535. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5536. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5537. return res;
  5538. }
  5539. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5540. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5541. return res;
  5542. }
  5543. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5544. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5545. return res;
  5546. }
  5547. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5548. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5549. return res;
  5550. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5551. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5552. return res;
  5553. }
  5554. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5555. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  5556. return res;
  5557. }
  5558. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  5559. lbValue s = lb_address_from_load_or_generate_local(p, value);
  5560. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  5561. return lb_emit_load(p, d);
  5562. }
  5563. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  5564. // GB_PANIC("lb_emit_transmute");
  5565. return res;
  5566. }
  5567. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  5568. GB_ASSERT(addr.kind == lbAddr_Context);
  5569. GB_ASSERT(addr.ctx.sel.index.count == 0);
  5570. lbModule *m = p->module;
  5571. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5572. args[0] = addr.addr;
  5573. lb_emit_runtime_call(p, "__init_context", args);
  5574. }
  5575. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  5576. ctx.kind = lbAddr_Context;
  5577. lbContextData cd = {ctx, p->scope_index};
  5578. array_add(&p->context_stack, cd);
  5579. }
  5580. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  5581. if (p->context_stack.count > 0) {
  5582. return p->context_stack[p->context_stack.count-1].ctx;
  5583. }
  5584. Type *pt = base_type(p->type);
  5585. GB_ASSERT(pt->kind == Type_Proc);
  5586. {
  5587. lbAddr c = lb_add_local_generated(p, t_context, false);
  5588. c.kind = lbAddr_Context;
  5589. lb_emit_init_context(p, c);
  5590. lb_push_context_onto_stack(p, c);
  5591. return c;
  5592. }
  5593. }
  5594. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  5595. if (LLVMIsALoadInst(value.value)) {
  5596. lbValue res = {};
  5597. res.value = LLVMGetOperand(value.value, 0);
  5598. res.type = alloc_type_pointer(value.type);
  5599. return res;
  5600. }
  5601. GB_ASSERT(is_type_typed(value.type));
  5602. lbAddr res = lb_add_local_generated(p, value.type, false);
  5603. lb_addr_store(p, res, value);
  5604. return res.addr;
  5605. }
  5606. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  5607. if (LLVMIsALoadInst(value.value)) {
  5608. lbValue res = {};
  5609. res.value = LLVMGetOperand(value.value, 0);
  5610. res.type = alloc_type_pointer(value.type);
  5611. return res;
  5612. }
  5613. GB_PANIC("lb_address_from_load");
  5614. return {};
  5615. }
  5616. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  5617. i64 type_alignment = type_align_of(new_type);
  5618. if (alignment < type_alignment) {
  5619. alignment = type_alignment;
  5620. }
  5621. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  5622. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  5623. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  5624. lb_addr_store(p, ptr, val);
  5625. // ptr.kind = lbAddr_Context;
  5626. return ptr.addr;
  5627. }
  5628. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  5629. GB_ASSERT(is_type_pointer(s.type));
  5630. Type *t = base_type(type_deref(s.type));
  5631. Type *result_type = nullptr;
  5632. if (is_type_relative_pointer(t)) {
  5633. s = lb_addr_get_ptr(p, lb_addr(s));
  5634. }
  5635. if (is_type_struct(t)) {
  5636. result_type = get_struct_field_type(t, index);
  5637. } else if (is_type_union(t)) {
  5638. GB_ASSERT(index == -1);
  5639. return lb_emit_union_tag_ptr(p, s);
  5640. } else if (is_type_tuple(t)) {
  5641. GB_ASSERT(t->Tuple.variables.count > 0);
  5642. result_type = t->Tuple.variables[index]->type;
  5643. } else if (is_type_complex(t)) {
  5644. Type *ft = base_complex_elem_type(t);
  5645. switch (index) {
  5646. case 0: result_type = ft; break;
  5647. case 1: result_type = ft; break;
  5648. }
  5649. } else if (is_type_quaternion(t)) {
  5650. Type *ft = base_complex_elem_type(t);
  5651. switch (index) {
  5652. case 0: result_type = ft; break;
  5653. case 1: result_type = ft; break;
  5654. case 2: result_type = ft; break;
  5655. case 3: result_type = ft; break;
  5656. }
  5657. } else if (is_type_slice(t)) {
  5658. switch (index) {
  5659. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5660. case 1: result_type = t_int; break;
  5661. }
  5662. } else if (is_type_string(t)) {
  5663. switch (index) {
  5664. case 0: result_type = t_u8_ptr; break;
  5665. case 1: result_type = t_int; break;
  5666. }
  5667. } else if (is_type_any(t)) {
  5668. switch (index) {
  5669. case 0: result_type = t_rawptr; break;
  5670. case 1: result_type = t_typeid; break;
  5671. }
  5672. } else if (is_type_dynamic_array(t)) {
  5673. switch (index) {
  5674. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5675. case 1: result_type = t_int; break;
  5676. case 2: result_type = t_int; break;
  5677. case 3: result_type = t_allocator; break;
  5678. }
  5679. } else if (is_type_map(t)) {
  5680. init_map_internal_types(t);
  5681. Type *itp = alloc_type_pointer(t->Map.internal_type);
  5682. s = lb_emit_transmute(p, s, itp);
  5683. Type *gst = t->Map.internal_type;
  5684. GB_ASSERT(gst->kind == Type_Struct);
  5685. switch (index) {
  5686. case 0: result_type = get_struct_field_type(gst, 0); break;
  5687. case 1: result_type = get_struct_field_type(gst, 1); break;
  5688. }
  5689. } else if (is_type_array(t)) {
  5690. return lb_emit_array_epi(p, s, index);
  5691. } else if (is_type_relative_slice(t)) {
  5692. switch (index) {
  5693. case 0: result_type = t->RelativeSlice.base_integer; break;
  5694. case 1: result_type = t->RelativeSlice.base_integer; break;
  5695. }
  5696. } else {
  5697. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  5698. }
  5699. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  5700. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5701. index += 1;
  5702. }
  5703. if (lb_is_const(s)) {
  5704. lbModule *m = p->module;
  5705. lbValue res = {};
  5706. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  5707. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  5708. res.type = alloc_type_pointer(result_type);
  5709. return res;
  5710. } else {
  5711. lbValue res = {};
  5712. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  5713. res.type = alloc_type_pointer(result_type);
  5714. return res;
  5715. }
  5716. }
  5717. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  5718. if (LLVMIsALoadInst(s.value)) {
  5719. lbValue res = {};
  5720. res.value = LLVMGetOperand(s.value, 0);
  5721. res.type = alloc_type_pointer(s.type);
  5722. lbValue ptr = lb_emit_struct_ep(p, res, index);
  5723. return lb_emit_load(p, ptr);
  5724. }
  5725. Type *t = base_type(s.type);
  5726. Type *result_type = nullptr;
  5727. switch (t->kind) {
  5728. case Type_Basic:
  5729. switch (t->Basic.kind) {
  5730. case Basic_string:
  5731. switch (index) {
  5732. case 0: result_type = t_u8_ptr; break;
  5733. case 1: result_type = t_int; break;
  5734. }
  5735. break;
  5736. case Basic_any:
  5737. switch (index) {
  5738. case 0: result_type = t_rawptr; break;
  5739. case 1: result_type = t_typeid; break;
  5740. }
  5741. break;
  5742. case Basic_complex64: case Basic_complex128:
  5743. {
  5744. Type *ft = base_complex_elem_type(t);
  5745. switch (index) {
  5746. case 0: result_type = ft; break;
  5747. case 1: result_type = ft; break;
  5748. }
  5749. break;
  5750. }
  5751. case Basic_quaternion128: case Basic_quaternion256:
  5752. {
  5753. Type *ft = base_complex_elem_type(t);
  5754. switch (index) {
  5755. case 0: result_type = ft; break;
  5756. case 1: result_type = ft; break;
  5757. case 2: result_type = ft; break;
  5758. case 3: result_type = ft; break;
  5759. }
  5760. break;
  5761. }
  5762. }
  5763. break;
  5764. case Type_Struct:
  5765. result_type = get_struct_field_type(t, index);
  5766. break;
  5767. case Type_Union:
  5768. GB_ASSERT(index == -1);
  5769. // return lb_emit_union_tag_value(p, s);
  5770. GB_PANIC("lb_emit_union_tag_value");
  5771. case Type_Tuple:
  5772. GB_ASSERT(t->Tuple.variables.count > 0);
  5773. result_type = t->Tuple.variables[index]->type;
  5774. if (t->Tuple.variables.count == 1) {
  5775. return s;
  5776. }
  5777. break;
  5778. case Type_Slice:
  5779. switch (index) {
  5780. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5781. case 1: result_type = t_int; break;
  5782. }
  5783. break;
  5784. case Type_DynamicArray:
  5785. switch (index) {
  5786. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5787. case 1: result_type = t_int; break;
  5788. case 2: result_type = t_int; break;
  5789. case 3: result_type = t_allocator; break;
  5790. }
  5791. break;
  5792. case Type_Map:
  5793. {
  5794. init_map_internal_types(t);
  5795. Type *gst = t->Map.generated_struct_type;
  5796. switch (index) {
  5797. case 0: result_type = get_struct_field_type(gst, 0); break;
  5798. case 1: result_type = get_struct_field_type(gst, 1); break;
  5799. }
  5800. }
  5801. break;
  5802. case Type_Array:
  5803. result_type = t->Array.elem;
  5804. break;
  5805. default:
  5806. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  5807. break;
  5808. }
  5809. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  5810. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5811. index += 1;
  5812. }
  5813. lbValue res = {};
  5814. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  5815. res.type = result_type;
  5816. return res;
  5817. }
  5818. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  5819. GB_ASSERT(sel.index.count > 0);
  5820. Type *type = type_deref(e.type);
  5821. for_array(i, sel.index) {
  5822. i32 index = cast(i32)sel.index[i];
  5823. if (is_type_pointer(type)) {
  5824. type = type_deref(type);
  5825. e = lb_emit_load(p, e);
  5826. }
  5827. type = core_type(type);
  5828. if (is_type_quaternion(type)) {
  5829. e = lb_emit_struct_ep(p, e, index);
  5830. } else if (is_type_raw_union(type)) {
  5831. type = get_struct_field_type(type, index);
  5832. GB_ASSERT(is_type_pointer(e.type));
  5833. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  5834. } else if (is_type_struct(type)) {
  5835. type = get_struct_field_type(type, index);
  5836. e = lb_emit_struct_ep(p, e, index);
  5837. } else if (type->kind == Type_Union) {
  5838. GB_ASSERT(index == -1);
  5839. type = t_type_info_ptr;
  5840. e = lb_emit_struct_ep(p, e, index);
  5841. } else if (type->kind == Type_Tuple) {
  5842. type = type->Tuple.variables[index]->type;
  5843. e = lb_emit_struct_ep(p, e, index);
  5844. } else if (type->kind == Type_Basic) {
  5845. switch (type->Basic.kind) {
  5846. case Basic_any: {
  5847. if (index == 0) {
  5848. type = t_rawptr;
  5849. } else if (index == 1) {
  5850. type = t_type_info_ptr;
  5851. }
  5852. e = lb_emit_struct_ep(p, e, index);
  5853. break;
  5854. }
  5855. case Basic_string:
  5856. e = lb_emit_struct_ep(p, e, index);
  5857. break;
  5858. default:
  5859. GB_PANIC("un-gep-able type %s", type_to_string(type));
  5860. break;
  5861. }
  5862. } else if (type->kind == Type_Slice) {
  5863. e = lb_emit_struct_ep(p, e, index);
  5864. } else if (type->kind == Type_DynamicArray) {
  5865. e = lb_emit_struct_ep(p, e, index);
  5866. } else if (type->kind == Type_Array) {
  5867. e = lb_emit_array_epi(p, e, index);
  5868. } else if (type->kind == Type_Map) {
  5869. e = lb_emit_struct_ep(p, e, index);
  5870. } else if (type->kind == Type_RelativePointer) {
  5871. e = lb_emit_struct_ep(p, e, index);
  5872. } else {
  5873. GB_PANIC("un-gep-able type %s", type_to_string(type));
  5874. }
  5875. }
  5876. return e;
  5877. }
  5878. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  5879. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  5880. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  5881. return lb_emit_load(p, res);
  5882. }
  5883. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  5884. // NOTE(bill): The prev block may defer injection before it's terminator
  5885. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  5886. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  5887. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  5888. return;
  5889. }
  5890. isize prev_context_stack_count = p->context_stack.count;
  5891. defer (p->context_stack.count = prev_context_stack_count);
  5892. p->context_stack.count = d.context_stack_count;
  5893. lbBlock *b = lb_create_block(p, "defer");
  5894. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  5895. lb_emit_jump(p, b);
  5896. }
  5897. lb_start_block(p, b);
  5898. if (d.kind == lbDefer_Node) {
  5899. lb_build_stmt(p, d.stmt);
  5900. } else if (d.kind == lbDefer_Instr) {
  5901. // NOTE(bill): Need to make a new copy
  5902. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  5903. LLVMInsertIntoBuilder(p->builder, instr);
  5904. } else if (d.kind == lbDefer_Proc) {
  5905. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  5906. }
  5907. }
  5908. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  5909. isize count = p->defer_stmts.count;
  5910. isize i = count;
  5911. while (i --> 0) {
  5912. lbDefer d = p->defer_stmts[i];
  5913. isize prev_context_stack_count = p->context_stack.count;
  5914. defer (p->context_stack.count = prev_context_stack_count);
  5915. p->context_stack.count = d.context_stack_count;
  5916. if (kind == lbDeferExit_Default) {
  5917. if (p->scope_index == d.scope_index &&
  5918. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  5919. lb_build_defer_stmt(p, d);
  5920. array_pop(&p->defer_stmts);
  5921. continue;
  5922. } else {
  5923. break;
  5924. }
  5925. } else if (kind == lbDeferExit_Return) {
  5926. lb_build_defer_stmt(p, d);
  5927. } else if (kind == lbDeferExit_Branch) {
  5928. GB_ASSERT(block != nullptr);
  5929. isize lower_limit = block->scope_index;
  5930. if (lower_limit < d.scope_index) {
  5931. lb_build_defer_stmt(p, d);
  5932. }
  5933. }
  5934. }
  5935. }
  5936. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  5937. lbDefer d = {lbDefer_Node};
  5938. d.scope_index = scope_index;
  5939. d.context_stack_count = p->context_stack.count;
  5940. d.block = p->curr_block;
  5941. d.stmt = stmt;
  5942. array_add(&p->defer_stmts, d);
  5943. return d;
  5944. }
  5945. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  5946. lbDefer d = {lbDefer_Proc};
  5947. d.scope_index = p->scope_index;
  5948. d.block = p->curr_block;
  5949. d.proc.deferred = deferred;
  5950. d.proc.result_as_args = result_as_args;
  5951. array_add(&p->defer_stmts, d);
  5952. return d;
  5953. }
  5954. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  5955. Array<lbValue> array = {};
  5956. Type *t = base_type(value.type);
  5957. if (t == nullptr) {
  5958. // Do nothing
  5959. } else if (is_type_tuple(t)) {
  5960. GB_ASSERT(t->kind == Type_Tuple);
  5961. auto *rt = &t->Tuple;
  5962. if (rt->variables.count > 0) {
  5963. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  5964. for_array(i, rt->variables) {
  5965. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  5966. array[i] = elem;
  5967. }
  5968. }
  5969. } else {
  5970. array = array_make<lbValue>(permanent_allocator(), 1);
  5971. array[0] = value;
  5972. }
  5973. return array;
  5974. }
  5975. lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array<lbValue> const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) {
  5976. unsigned arg_count = cast(unsigned)processed_args.count;
  5977. if (return_ptr.value != nullptr) {
  5978. arg_count += 1;
  5979. }
  5980. if (context_ptr.addr.value != nullptr) {
  5981. arg_count += 1;
  5982. }
  5983. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  5984. isize arg_index = 0;
  5985. if (return_ptr.value != nullptr) {
  5986. args[arg_index++] = return_ptr.value;
  5987. }
  5988. for_array(i, processed_args) {
  5989. lbValue arg = processed_args[i];
  5990. args[arg_index++] = arg.value;
  5991. }
  5992. if (context_ptr.addr.value != nullptr) {
  5993. LLVMValueRef cp = context_ptr.addr.value;
  5994. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  5995. args[arg_index++] = cp;
  5996. }
  5997. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  5998. GB_ASSERT(curr_block != p->decl_block->block);
  5999. {
  6000. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6001. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6002. LLVMValueRef fn = value.value;
  6003. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6004. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6005. }
  6006. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6007. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6008. LLVMValueRef ret = LLVMBuildCall2(p->builder, ft, fn, args, arg_count, "");;
  6009. lbValue res = {};
  6010. res.value = ret;
  6011. res.type = abi_rt;
  6012. return res;
  6013. }
  6014. }
  6015. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6016. String name = make_string_c(c_name);
  6017. AstPackage *pkg = p->module->info->runtime_package;
  6018. Entity *e = scope_lookup_current(pkg->scope, name);
  6019. lbValue *found = nullptr;
  6020. if (p->module != e->code_gen_module) {
  6021. gb_mutex_lock(&p->module->mutex);
  6022. }
  6023. GB_ASSERT(e->code_gen_module != nullptr);
  6024. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6025. if (p->module != e->code_gen_module) {
  6026. gb_mutex_unlock(&p->module->mutex);
  6027. }
  6028. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6029. return lb_emit_call(p, *found, args);
  6030. }
  6031. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6032. lbModule *m = p->module;
  6033. Type *pt = base_type(value.type);
  6034. GB_ASSERT(pt->kind == Type_Proc);
  6035. Type *results = pt->Proc.results;
  6036. if (p->entity != nullptr) {
  6037. if (p->entity->flags & EntityFlag_Disabled) {
  6038. return {};
  6039. }
  6040. }
  6041. lbAddr context_ptr = {};
  6042. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6043. context_ptr = lb_find_or_generate_context_ptr(p);
  6044. }
  6045. defer (if (pt->Proc.diverging) {
  6046. LLVMBuildUnreachable(p->builder);
  6047. });
  6048. set_procedure_abi_types(pt);
  6049. bool is_c_vararg = pt->Proc.c_vararg;
  6050. isize param_count = pt->Proc.param_count;
  6051. if (is_c_vararg) {
  6052. GB_ASSERT(param_count-1 <= args.count);
  6053. param_count -= 1;
  6054. } else {
  6055. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6056. }
  6057. lbValue result = {};
  6058. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6059. {
  6060. lbFunctionType **ft_found = nullptr;
  6061. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6062. if (!ft_found) {
  6063. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6064. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6065. }
  6066. GB_ASSERT(ft_found != nullptr);
  6067. lbFunctionType *ft = *ft_found;
  6068. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6069. unsigned param_index = 0;
  6070. for (isize i = 0; i < param_count; i++) {
  6071. Entity *e = pt->Proc.params->Tuple.variables[i];
  6072. if (e->kind != Entity_Variable) {
  6073. continue;
  6074. }
  6075. GB_ASSERT(e->flags & EntityFlag_Param);
  6076. Type *original_type = e->type;
  6077. lbArgType *arg = &ft->args[param_index];
  6078. if (arg->kind == lbArg_Ignore) {
  6079. continue;
  6080. }
  6081. lbValue x = lb_emit_conv(p, args[i], original_type);
  6082. LLVMTypeRef xt = lb_type(p->module, x.type);
  6083. if (arg->kind == lbArg_Direct) {
  6084. LLVMTypeRef abi_type = arg->cast_type;
  6085. if (!abi_type) {
  6086. abi_type = arg->type;
  6087. }
  6088. if (xt == abi_type) {
  6089. array_add(&processed_args, x);
  6090. } else {
  6091. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6092. array_add(&processed_args, x);
  6093. }
  6094. } else if (arg->kind == lbArg_Indirect) {
  6095. lbValue ptr = {};
  6096. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6097. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6098. // i.e. `T const &` in C++
  6099. ptr = lb_address_from_load_or_generate_local(p, x);
  6100. } else {
  6101. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6102. }
  6103. array_add(&processed_args, ptr);
  6104. }
  6105. param_index += 1;
  6106. }
  6107. if (inlining == ProcInlining_none) {
  6108. inlining = p->inlining;
  6109. }
  6110. Type *rt = reduce_tuple_to_single_type(results);
  6111. if (return_by_pointer) {
  6112. lbValue return_ptr = {};
  6113. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6114. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6115. return_ptr = p->return_ptr_hint_value;
  6116. p->return_ptr_hint_used = true;
  6117. }
  6118. }
  6119. if (return_ptr.value == nullptr) {
  6120. lbAddr r = lb_add_local_generated(p, rt, true);
  6121. return_ptr = r.addr;
  6122. }
  6123. GB_ASSERT(is_type_pointer(return_ptr.type));
  6124. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6125. result = lb_emit_load(p, return_ptr);
  6126. } else if (rt != nullptr) {
  6127. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  6128. if (ft->ret.cast_type) {
  6129. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  6130. }
  6131. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  6132. result.type = rt;
  6133. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  6134. result.type = t_llvm_bool;
  6135. }
  6136. if (!is_type_tuple(rt)) {
  6137. result = lb_emit_conv(p, result, rt);
  6138. }
  6139. } else {
  6140. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  6141. }
  6142. }
  6143. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6144. if (found != nullptr) {
  6145. Entity *e = *found;
  6146. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6147. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6148. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6149. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6150. GB_ASSERT(deferred_found != nullptr);
  6151. lbValue deferred = *deferred_found;
  6152. auto in_args = args;
  6153. Array<lbValue> result_as_args = {};
  6154. switch (kind) {
  6155. case DeferredProcedure_none:
  6156. break;
  6157. case DeferredProcedure_in:
  6158. result_as_args = in_args;
  6159. break;
  6160. case DeferredProcedure_out:
  6161. result_as_args = lb_value_to_array(p, result);
  6162. break;
  6163. case DeferredProcedure_in_out:
  6164. {
  6165. auto out_args = lb_value_to_array(p, result);
  6166. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  6167. array_copy(&result_as_args, in_args, 0);
  6168. array_copy(&result_as_args, out_args, in_args.count);
  6169. }
  6170. break;
  6171. }
  6172. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6173. }
  6174. }
  6175. return result;
  6176. }
  6177. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6178. Type *t = s.type;
  6179. GB_ASSERT(is_type_pointer(t));
  6180. Type *st = base_type(type_deref(t));
  6181. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6182. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6183. LLVMValueRef indices[2] = {};
  6184. indices[0] = llvm_zero(p->module);
  6185. indices[1] = lb_emit_conv(p, index, t_int).value;
  6186. Type *ptr = base_array_type(st);
  6187. lbValue res = {};
  6188. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6189. res.type = alloc_type_pointer(ptr);
  6190. return res;
  6191. }
  6192. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6193. Type *t = s.type;
  6194. GB_ASSERT(is_type_pointer(t));
  6195. Type *st = base_type(type_deref(t));
  6196. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6197. GB_ASSERT(0 <= index);
  6198. Type *ptr = base_array_type(st);
  6199. LLVMValueRef indices[2] = {
  6200. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6201. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6202. };
  6203. lbValue res = {};
  6204. if (lb_is_const(s)) {
  6205. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6206. } else {
  6207. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6208. }
  6209. res.type = alloc_type_pointer(ptr);
  6210. return res;
  6211. }
  6212. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6213. LLVMValueRef indices[1] = {index.value};
  6214. lbValue res = {};
  6215. res.type = ptr.type;
  6216. if (lb_is_const(ptr) && lb_is_const(index)) {
  6217. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6218. } else {
  6219. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6220. }
  6221. return res;
  6222. }
  6223. LLVMValueRef llvm_const_slice(lbValue data, lbValue len) {
  6224. GB_ASSERT(is_type_pointer(data.type));
  6225. GB_ASSERT(are_types_identical(len.type, t_int));
  6226. LLVMValueRef vals[2] = {
  6227. data.value,
  6228. len.value,
  6229. };
  6230. return LLVMConstStruct(vals, gb_count_of(vals), false);
  6231. }
  6232. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6233. Type *t = lb_addr_type(slice);
  6234. GB_ASSERT(is_type_slice(t));
  6235. lbValue ptr = lb_addr_get_ptr(p, slice);
  6236. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6237. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6238. }
  6239. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6240. Type *t = lb_addr_type(string);
  6241. GB_ASSERT(is_type_string(t));
  6242. lbValue ptr = lb_addr_get_ptr(p, string);
  6243. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6244. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6245. }
  6246. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6247. Type *t = base_type(string.type);
  6248. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6249. return lb_emit_struct_ev(p, string, 0);
  6250. }
  6251. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6252. Type *t = base_type(string.type);
  6253. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6254. return lb_emit_struct_ev(p, string, 1);
  6255. }
  6256. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6257. GB_ASSERT(is_type_cstring(value.type));
  6258. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6259. args[0] = lb_emit_conv(p, value, t_cstring);
  6260. return lb_emit_runtime_call(p, "cstring_len", args);
  6261. }
  6262. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6263. Type *t = type_deref(array_ptr.type);
  6264. GB_ASSERT(is_type_array(t));
  6265. return lb_emit_struct_ep(p, array_ptr, 0);
  6266. }
  6267. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6268. GB_ASSERT(is_type_slice(slice.type));
  6269. return lb_emit_struct_ev(p, slice, 0);
  6270. }
  6271. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6272. GB_ASSERT(is_type_slice(slice.type));
  6273. return lb_emit_struct_ev(p, slice, 1);
  6274. }
  6275. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6276. GB_ASSERT(is_type_dynamic_array(da.type));
  6277. return lb_emit_struct_ev(p, da, 0);
  6278. }
  6279. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6280. GB_ASSERT(is_type_dynamic_array(da.type));
  6281. return lb_emit_struct_ev(p, da, 1);
  6282. }
  6283. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6284. GB_ASSERT(is_type_dynamic_array(da.type));
  6285. return lb_emit_struct_ev(p, da, 2);
  6286. }
  6287. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6288. GB_ASSERT(is_type_dynamic_array(da.type));
  6289. return lb_emit_struct_ev(p, da, 3);
  6290. }
  6291. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6292. Type *t = base_type(value.type);
  6293. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6294. init_map_internal_types(t);
  6295. Type *gst = t->Map.generated_struct_type;
  6296. i32 index = 1;
  6297. lbValue entries = lb_emit_struct_ev(p, value, index);
  6298. return entries;
  6299. }
  6300. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6301. Type *t = base_type(type_deref(value.type));
  6302. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6303. init_map_internal_types(t);
  6304. Type *gst = t->Map.generated_struct_type;
  6305. i32 index = 1;
  6306. lbValue entries = lb_emit_struct_ep(p, value, index);
  6307. return entries;
  6308. }
  6309. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  6310. lbValue entries = lb_map_entries(p, value);
  6311. return lb_dynamic_array_len(p, entries);
  6312. }
  6313. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  6314. lbValue entries = lb_map_entries(p, value);
  6315. return lb_dynamic_array_cap(p, entries);
  6316. }
  6317. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  6318. Type *t = base_type(value.type);
  6319. bool is_ptr = false;
  6320. if (is_type_pointer(t)) {
  6321. is_ptr = true;
  6322. t = base_type(type_deref(t));
  6323. }
  6324. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6325. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6326. }
  6327. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  6328. t->Struct.soa_kind == StructSoa_Dynamic);
  6329. isize n = 0;
  6330. Type *elem = base_type(t->Struct.soa_elem);
  6331. if (elem->kind == Type_Struct) {
  6332. n = elem->Struct.fields.count;
  6333. } else if (elem->kind == Type_Array) {
  6334. n = elem->Array.count;
  6335. } else {
  6336. GB_PANIC("Unreachable");
  6337. }
  6338. if (is_ptr) {
  6339. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6340. return lb_emit_load(p, v);
  6341. }
  6342. return lb_emit_struct_ev(p, value, cast(i32)n);
  6343. }
  6344. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  6345. Type *t = base_type(value.type);
  6346. bool is_ptr = false;
  6347. if (is_type_pointer(t)) {
  6348. is_ptr = true;
  6349. t = base_type(type_deref(t));
  6350. }
  6351. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6352. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6353. }
  6354. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  6355. isize n = 0;
  6356. Type *elem = base_type(t->Struct.soa_elem);
  6357. if (elem->kind == Type_Struct) {
  6358. n = elem->Struct.fields.count+1;
  6359. } else if (elem->kind == Type_Array) {
  6360. n = elem->Array.count+1;
  6361. } else {
  6362. GB_PANIC("Unreachable");
  6363. }
  6364. if (is_ptr) {
  6365. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6366. return lb_emit_load(p, v);
  6367. }
  6368. return lb_emit_struct_ev(p, value, cast(i32)n);
  6369. }
  6370. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  6371. ast_node(ce, CallExpr, expr);
  6372. switch (id) {
  6373. case BuiltinProc_DIRECTIVE: {
  6374. ast_node(bd, BasicDirective, ce->proc);
  6375. String name = bd->name;
  6376. GB_ASSERT(name == "location");
  6377. String procedure = p->entity->token.string;
  6378. TokenPos pos = ast_token(ce->proc).pos;
  6379. if (ce->args.count > 0) {
  6380. Ast *ident = unselector_expr(ce->args[0]);
  6381. GB_ASSERT(ident->kind == Ast_Ident);
  6382. Entity *e = entity_of_node(ident);
  6383. GB_ASSERT(e != nullptr);
  6384. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  6385. procedure = e->parent_proc_decl->entity->token.string;
  6386. } else {
  6387. procedure = str_lit("");
  6388. }
  6389. pos = e->token.pos;
  6390. }
  6391. return lb_emit_source_code_location(p, procedure, pos);
  6392. }
  6393. case BuiltinProc_type_info_of: {
  6394. Ast *arg = ce->args[0];
  6395. TypeAndValue tav = type_and_value_of_expr(arg);
  6396. if (tav.mode == Addressing_Type) {
  6397. Type *t = default_type(type_of_expr(arg));
  6398. return lb_type_info(p->module, t);
  6399. }
  6400. GB_ASSERT(is_type_typeid(tav.type));
  6401. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6402. args[0] = lb_build_expr(p, arg);
  6403. return lb_emit_runtime_call(p, "__type_info_of", args);
  6404. }
  6405. case BuiltinProc_typeid_of: {
  6406. Ast *arg = ce->args[0];
  6407. TypeAndValue tav = type_and_value_of_expr(arg);
  6408. GB_ASSERT(tav.mode == Addressing_Type);
  6409. Type *t = default_type(type_of_expr(arg));
  6410. return lb_typeid(p->module, t);
  6411. }
  6412. case BuiltinProc_len: {
  6413. lbValue v = lb_build_expr(p, ce->args[0]);
  6414. Type *t = base_type(v.type);
  6415. if (is_type_pointer(t)) {
  6416. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6417. v = lb_emit_load(p, v);
  6418. t = type_deref(t);
  6419. }
  6420. if (is_type_cstring(t)) {
  6421. return lb_cstring_len(p, v);
  6422. } else if (is_type_string(t)) {
  6423. return lb_string_len(p, v);
  6424. } else if (is_type_array(t)) {
  6425. GB_PANIC("Array lengths are constant");
  6426. } else if (is_type_slice(t)) {
  6427. return lb_slice_len(p, v);
  6428. } else if (is_type_dynamic_array(t)) {
  6429. return lb_dynamic_array_len(p, v);
  6430. } else if (is_type_map(t)) {
  6431. return lb_map_len(p, v);
  6432. } else if (is_type_soa_struct(t)) {
  6433. return lb_soa_struct_len(p, v);
  6434. }
  6435. GB_PANIC("Unreachable");
  6436. break;
  6437. }
  6438. case BuiltinProc_cap: {
  6439. lbValue v = lb_build_expr(p, ce->args[0]);
  6440. Type *t = base_type(v.type);
  6441. if (is_type_pointer(t)) {
  6442. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6443. v = lb_emit_load(p, v);
  6444. t = type_deref(t);
  6445. }
  6446. if (is_type_string(t)) {
  6447. GB_PANIC("Unreachable");
  6448. } else if (is_type_array(t)) {
  6449. GB_PANIC("Array lengths are constant");
  6450. } else if (is_type_slice(t)) {
  6451. return lb_slice_len(p, v);
  6452. } else if (is_type_dynamic_array(t)) {
  6453. return lb_dynamic_array_cap(p, v);
  6454. } else if (is_type_map(t)) {
  6455. return lb_map_cap(p, v);
  6456. } else if (is_type_soa_struct(t)) {
  6457. return lb_soa_struct_cap(p, v);
  6458. }
  6459. GB_PANIC("Unreachable");
  6460. break;
  6461. }
  6462. case BuiltinProc_swizzle: {
  6463. isize index_count = ce->args.count-1;
  6464. if (is_type_simd_vector(tv.type)) {
  6465. lbValue vec = lb_build_expr(p, ce->args[0]);
  6466. if (index_count == 0) {
  6467. return vec;
  6468. }
  6469. unsigned mask_len = cast(unsigned)index_count;
  6470. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  6471. for (isize i = 1; i < ce->args.count; i++) {
  6472. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6473. GB_ASSERT(is_type_integer(tv.type));
  6474. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6475. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  6476. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  6477. }
  6478. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  6479. LLVMValueRef v1 = vec.value;
  6480. LLVMValueRef v2 = vec.value;
  6481. lbValue res = {};
  6482. res.type = tv.type;
  6483. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  6484. return res;
  6485. }
  6486. lbAddr addr = lb_build_addr(p, ce->args[0]);
  6487. if (index_count == 0) {
  6488. return lb_addr_load(p, addr);
  6489. }
  6490. lbValue src = lb_addr_get_ptr(p, addr);
  6491. // TODO(bill): Should this be zeroed or not?
  6492. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  6493. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  6494. for (i32 i = 1; i < ce->args.count; i++) {
  6495. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6496. GB_ASSERT(is_type_integer(tv.type));
  6497. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6498. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  6499. i32 dst_index = i-1;
  6500. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  6501. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  6502. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  6503. }
  6504. return lb_addr_load(p, dst);
  6505. }
  6506. case BuiltinProc_complex: {
  6507. lbValue real = lb_build_expr(p, ce->args[0]);
  6508. lbValue imag = lb_build_expr(p, ce->args[1]);
  6509. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6510. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6511. Type *ft = base_complex_elem_type(tv.type);
  6512. real = lb_emit_conv(p, real, ft);
  6513. imag = lb_emit_conv(p, imag, ft);
  6514. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  6515. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  6516. return lb_emit_load(p, dst);
  6517. }
  6518. case BuiltinProc_quaternion: {
  6519. lbValue real = lb_build_expr(p, ce->args[0]);
  6520. lbValue imag = lb_build_expr(p, ce->args[1]);
  6521. lbValue jmag = lb_build_expr(p, ce->args[2]);
  6522. lbValue kmag = lb_build_expr(p, ce->args[3]);
  6523. // @QuaternionLayout
  6524. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6525. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6526. Type *ft = base_complex_elem_type(tv.type);
  6527. real = lb_emit_conv(p, real, ft);
  6528. imag = lb_emit_conv(p, imag, ft);
  6529. jmag = lb_emit_conv(p, jmag, ft);
  6530. kmag = lb_emit_conv(p, kmag, ft);
  6531. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  6532. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  6533. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  6534. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  6535. return lb_emit_load(p, dst);
  6536. }
  6537. case BuiltinProc_real: {
  6538. lbValue val = lb_build_expr(p, ce->args[0]);
  6539. if (is_type_complex(val.type)) {
  6540. lbValue real = lb_emit_struct_ev(p, val, 0);
  6541. return lb_emit_conv(p, real, tv.type);
  6542. } else if (is_type_quaternion(val.type)) {
  6543. // @QuaternionLayout
  6544. lbValue real = lb_emit_struct_ev(p, val, 3);
  6545. return lb_emit_conv(p, real, tv.type);
  6546. }
  6547. GB_PANIC("invalid type for real");
  6548. return {};
  6549. }
  6550. case BuiltinProc_imag: {
  6551. lbValue val = lb_build_expr(p, ce->args[0]);
  6552. if (is_type_complex(val.type)) {
  6553. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6554. return lb_emit_conv(p, imag, tv.type);
  6555. } else if (is_type_quaternion(val.type)) {
  6556. // @QuaternionLayout
  6557. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6558. return lb_emit_conv(p, imag, tv.type);
  6559. }
  6560. GB_PANIC("invalid type for imag");
  6561. return {};
  6562. }
  6563. case BuiltinProc_jmag: {
  6564. lbValue val = lb_build_expr(p, ce->args[0]);
  6565. if (is_type_quaternion(val.type)) {
  6566. // @QuaternionLayout
  6567. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6568. return lb_emit_conv(p, imag, tv.type);
  6569. }
  6570. GB_PANIC("invalid type for jmag");
  6571. return {};
  6572. }
  6573. case BuiltinProc_kmag: {
  6574. lbValue val = lb_build_expr(p, ce->args[0]);
  6575. if (is_type_quaternion(val.type)) {
  6576. // @QuaternionLayout
  6577. lbValue imag = lb_emit_struct_ev(p, val, 2);
  6578. return lb_emit_conv(p, imag, tv.type);
  6579. }
  6580. GB_PANIC("invalid type for kmag");
  6581. return {};
  6582. }
  6583. case BuiltinProc_conj: {
  6584. lbValue val = lb_build_expr(p, ce->args[0]);
  6585. lbValue res = {};
  6586. Type *t = val.type;
  6587. if (is_type_complex(t)) {
  6588. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6589. lbValue real = lb_emit_struct_ev(p, val, 0);
  6590. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6591. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6592. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  6593. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  6594. } else if (is_type_quaternion(t)) {
  6595. // @QuaternionLayout
  6596. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6597. lbValue real = lb_emit_struct_ev(p, val, 3);
  6598. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6599. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  6600. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  6601. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6602. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  6603. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  6604. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  6605. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  6606. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  6607. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  6608. }
  6609. return lb_emit_load(p, res);
  6610. }
  6611. case BuiltinProc_expand_to_tuple: {
  6612. lbValue val = lb_build_expr(p, ce->args[0]);
  6613. Type *t = base_type(val.type);
  6614. if (!is_type_tuple(tv.type)) {
  6615. if (t->kind == Type_Struct) {
  6616. GB_ASSERT(t->Struct.fields.count == 1);
  6617. return lb_emit_struct_ev(p, val, 0);
  6618. } else if (t->kind == Type_Array) {
  6619. GB_ASSERT(t->Array.count == 1);
  6620. return lb_emit_array_epi(p, val, 0);
  6621. } else {
  6622. GB_PANIC("Unknown type of expand_to_tuple");
  6623. }
  6624. }
  6625. GB_ASSERT(is_type_tuple(tv.type));
  6626. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6627. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6628. if (t->kind == Type_Struct) {
  6629. for_array(src_index, t->Struct.fields) {
  6630. Entity *field = t->Struct.fields[src_index];
  6631. i32 field_index = field->Variable.field_index;
  6632. lbValue f = lb_emit_struct_ev(p, val, field_index);
  6633. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  6634. lb_emit_store(p, ep, f);
  6635. }
  6636. } else if (t->kind == Type_Array) {
  6637. // TODO(bill): Clean-up this code
  6638. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  6639. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  6640. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  6641. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  6642. lb_emit_store(p, ep, f);
  6643. }
  6644. } else {
  6645. GB_PANIC("Unknown type of expand_to_tuple");
  6646. }
  6647. return lb_emit_load(p, tuple);
  6648. }
  6649. case BuiltinProc_min: {
  6650. Type *t = type_of_expr(expr);
  6651. if (ce->args.count == 2) {
  6652. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6653. } else {
  6654. lbValue x = lb_build_expr(p, ce->args[0]);
  6655. for (isize i = 1; i < ce->args.count; i++) {
  6656. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  6657. }
  6658. return x;
  6659. }
  6660. }
  6661. case BuiltinProc_max: {
  6662. Type *t = type_of_expr(expr);
  6663. if (ce->args.count == 2) {
  6664. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6665. } else {
  6666. lbValue x = lb_build_expr(p, ce->args[0]);
  6667. for (isize i = 1; i < ce->args.count; i++) {
  6668. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  6669. }
  6670. return x;
  6671. }
  6672. }
  6673. case BuiltinProc_abs: {
  6674. lbValue x = lb_build_expr(p, ce->args[0]);
  6675. Type *t = x.type;
  6676. if (is_type_unsigned(t)) {
  6677. return x;
  6678. }
  6679. if (is_type_quaternion(t)) {
  6680. i64 sz = 8*type_size_of(t);
  6681. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6682. args[0] = x;
  6683. switch (sz) {
  6684. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  6685. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  6686. }
  6687. GB_PANIC("Unknown complex type");
  6688. } else if (is_type_complex(t)) {
  6689. i64 sz = 8*type_size_of(t);
  6690. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6691. args[0] = x;
  6692. switch (sz) {
  6693. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  6694. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  6695. }
  6696. GB_PANIC("Unknown complex type");
  6697. } else if (is_type_float(t)) {
  6698. i64 sz = 8*type_size_of(t);
  6699. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6700. args[0] = x;
  6701. switch (sz) {
  6702. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  6703. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  6704. }
  6705. GB_PANIC("Unknown float type");
  6706. }
  6707. lbValue zero = lb_const_nil(p->module, t);
  6708. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  6709. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  6710. return lb_emit_select(p, cond, neg, x);
  6711. }
  6712. case BuiltinProc_clamp:
  6713. return lb_emit_clamp(p, type_of_expr(expr),
  6714. lb_build_expr(p, ce->args[0]),
  6715. lb_build_expr(p, ce->args[1]),
  6716. lb_build_expr(p, ce->args[2]));
  6717. // "Intrinsics"
  6718. case BuiltinProc_alloca:
  6719. {
  6720. lbValue sz = lb_build_expr(p, ce->args[0]);
  6721. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  6722. lbValue res = {};
  6723. res.type = t_u8_ptr;
  6724. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  6725. LLVMSetAlignment(res.value, cast(unsigned)al);
  6726. return res;
  6727. }
  6728. case BuiltinProc_cpu_relax:
  6729. if (build_context.metrics.arch == TargetArch_386 ||
  6730. build_context.metrics.arch == TargetArch_amd64) {
  6731. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  6732. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  6733. cast(char *)"pause", 5,
  6734. cast(char *)"", 0,
  6735. /*HasSideEffects*/true, /*IsAlignStack*/false,
  6736. LLVMInlineAsmDialectATT
  6737. );
  6738. GB_ASSERT(the_asm != nullptr);
  6739. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  6740. }
  6741. return {};
  6742. case BuiltinProc_atomic_fence:
  6743. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  6744. return {};
  6745. case BuiltinProc_atomic_fence_acq:
  6746. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  6747. return {};
  6748. case BuiltinProc_atomic_fence_rel:
  6749. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  6750. return {};
  6751. case BuiltinProc_atomic_fence_acqrel:
  6752. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  6753. return {};
  6754. case BuiltinProc_atomic_store:
  6755. case BuiltinProc_atomic_store_rel:
  6756. case BuiltinProc_atomic_store_relaxed:
  6757. case BuiltinProc_atomic_store_unordered: {
  6758. lbValue dst = lb_build_expr(p, ce->args[0]);
  6759. lbValue val = lb_build_expr(p, ce->args[1]);
  6760. val = lb_emit_conv(p, val, type_deref(dst.type));
  6761. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  6762. switch (id) {
  6763. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  6764. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  6765. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  6766. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  6767. }
  6768. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  6769. return {};
  6770. }
  6771. case BuiltinProc_atomic_load:
  6772. case BuiltinProc_atomic_load_acq:
  6773. case BuiltinProc_atomic_load_relaxed:
  6774. case BuiltinProc_atomic_load_unordered: {
  6775. lbValue dst = lb_build_expr(p, ce->args[0]);
  6776. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  6777. switch (id) {
  6778. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  6779. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  6780. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  6781. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  6782. }
  6783. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  6784. lbValue res = {};
  6785. res.value = instr;
  6786. res.type = type_deref(dst.type);
  6787. return res;
  6788. }
  6789. case BuiltinProc_atomic_add:
  6790. case BuiltinProc_atomic_add_acq:
  6791. case BuiltinProc_atomic_add_rel:
  6792. case BuiltinProc_atomic_add_acqrel:
  6793. case BuiltinProc_atomic_add_relaxed:
  6794. case BuiltinProc_atomic_sub:
  6795. case BuiltinProc_atomic_sub_acq:
  6796. case BuiltinProc_atomic_sub_rel:
  6797. case BuiltinProc_atomic_sub_acqrel:
  6798. case BuiltinProc_atomic_sub_relaxed:
  6799. case BuiltinProc_atomic_and:
  6800. case BuiltinProc_atomic_and_acq:
  6801. case BuiltinProc_atomic_and_rel:
  6802. case BuiltinProc_atomic_and_acqrel:
  6803. case BuiltinProc_atomic_and_relaxed:
  6804. case BuiltinProc_atomic_nand:
  6805. case BuiltinProc_atomic_nand_acq:
  6806. case BuiltinProc_atomic_nand_rel:
  6807. case BuiltinProc_atomic_nand_acqrel:
  6808. case BuiltinProc_atomic_nand_relaxed:
  6809. case BuiltinProc_atomic_or:
  6810. case BuiltinProc_atomic_or_acq:
  6811. case BuiltinProc_atomic_or_rel:
  6812. case BuiltinProc_atomic_or_acqrel:
  6813. case BuiltinProc_atomic_or_relaxed:
  6814. case BuiltinProc_atomic_xor:
  6815. case BuiltinProc_atomic_xor_acq:
  6816. case BuiltinProc_atomic_xor_rel:
  6817. case BuiltinProc_atomic_xor_acqrel:
  6818. case BuiltinProc_atomic_xor_relaxed:
  6819. case BuiltinProc_atomic_xchg:
  6820. case BuiltinProc_atomic_xchg_acq:
  6821. case BuiltinProc_atomic_xchg_rel:
  6822. case BuiltinProc_atomic_xchg_acqrel:
  6823. case BuiltinProc_atomic_xchg_relaxed: {
  6824. lbValue dst = lb_build_expr(p, ce->args[0]);
  6825. lbValue val = lb_build_expr(p, ce->args[1]);
  6826. val = lb_emit_conv(p, val, type_deref(dst.type));
  6827. LLVMAtomicRMWBinOp op = {};
  6828. LLVMAtomicOrdering ordering = {};
  6829. switch (id) {
  6830. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6831. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  6832. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  6833. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6834. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  6835. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6836. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  6837. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  6838. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6839. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  6840. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6841. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  6842. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  6843. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6844. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  6845. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6846. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  6847. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  6848. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6849. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  6850. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6851. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  6852. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  6853. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6854. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  6855. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6856. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  6857. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  6858. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6859. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  6860. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6861. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  6862. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  6863. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6864. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  6865. }
  6866. lbValue res = {};
  6867. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  6868. res.type = tv.type;
  6869. return res;
  6870. }
  6871. case BuiltinProc_atomic_cxchg:
  6872. case BuiltinProc_atomic_cxchg_acq:
  6873. case BuiltinProc_atomic_cxchg_rel:
  6874. case BuiltinProc_atomic_cxchg_acqrel:
  6875. case BuiltinProc_atomic_cxchg_relaxed:
  6876. case BuiltinProc_atomic_cxchg_failrelaxed:
  6877. case BuiltinProc_atomic_cxchg_failacq:
  6878. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  6879. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  6880. case BuiltinProc_atomic_cxchgweak:
  6881. case BuiltinProc_atomic_cxchgweak_acq:
  6882. case BuiltinProc_atomic_cxchgweak_rel:
  6883. case BuiltinProc_atomic_cxchgweak_acqrel:
  6884. case BuiltinProc_atomic_cxchgweak_relaxed:
  6885. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  6886. case BuiltinProc_atomic_cxchgweak_failacq:
  6887. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  6888. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  6889. Type *type = expr->tav.type;
  6890. lbValue address = lb_build_expr(p, ce->args[0]);
  6891. Type *elem = type_deref(address.type);
  6892. lbValue old_value = lb_build_expr(p, ce->args[1]);
  6893. lbValue new_value = lb_build_expr(p, ce->args[2]);
  6894. old_value = lb_emit_conv(p, old_value, elem);
  6895. new_value = lb_emit_conv(p, new_value, elem);
  6896. LLVMAtomicOrdering success_ordering = {};
  6897. LLVMAtomicOrdering failure_ordering = {};
  6898. LLVMBool weak = false;
  6899. switch (id) {
  6900. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6901. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6902. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6903. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6904. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6905. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6906. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  6907. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6908. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6909. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6910. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6911. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6912. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6913. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6914. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6915. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  6916. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6917. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6918. }
  6919. // TODO(bill): Figure out how to make it weak
  6920. LLVMBool single_threaded = weak;
  6921. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  6922. p->builder, address.value,
  6923. old_value.value, new_value.value,
  6924. success_ordering,
  6925. failure_ordering,
  6926. single_threaded
  6927. );
  6928. GB_ASSERT(tv.type->kind == Type_Tuple);
  6929. Type *fix_typed = alloc_type_tuple();
  6930. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  6931. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  6932. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  6933. lbValue res = {};
  6934. res.value = value;
  6935. res.type = fix_typed;
  6936. return res;
  6937. }
  6938. case BuiltinProc_type_equal_proc:
  6939. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  6940. case BuiltinProc_type_hasher_proc:
  6941. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  6942. }
  6943. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  6944. return {};
  6945. }
  6946. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  6947. switch (param_value.kind) {
  6948. case ParameterValue_Constant:
  6949. if (is_type_constant_type(parameter_type)) {
  6950. return lb_const_value(p->module, parameter_type, param_value.value);
  6951. } else {
  6952. ExactValue ev = param_value.value;
  6953. lbValue arg = {};
  6954. Type *type = type_of_expr(param_value.original_ast_expr);
  6955. if (type != nullptr) {
  6956. arg = lb_const_value(p->module, type, ev);
  6957. } else {
  6958. arg = lb_const_value(p->module, parameter_type, param_value.value);
  6959. }
  6960. return lb_emit_conv(p, arg, parameter_type);
  6961. }
  6962. case ParameterValue_Nil:
  6963. return lb_const_nil(p->module, parameter_type);
  6964. case ParameterValue_Location:
  6965. {
  6966. String proc_name = {};
  6967. if (p->entity != nullptr) {
  6968. proc_name = p->entity->token.string;
  6969. }
  6970. return lb_emit_source_code_location(p, proc_name, pos);
  6971. }
  6972. case ParameterValue_Value:
  6973. return lb_build_expr(p, param_value.ast_value);
  6974. }
  6975. return lb_const_nil(p->module, parameter_type);
  6976. }
  6977. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  6978. lbModule *m = p->module;
  6979. TypeAndValue tv = type_and_value_of_expr(expr);
  6980. ast_node(ce, CallExpr, expr);
  6981. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  6982. AddressingMode proc_mode = proc_tv.mode;
  6983. if (proc_mode == Addressing_Type) {
  6984. GB_ASSERT(ce->args.count == 1);
  6985. lbValue x = lb_build_expr(p, ce->args[0]);
  6986. lbValue y = lb_emit_conv(p, x, tv.type);
  6987. return y;
  6988. }
  6989. Ast *pexpr = unparen_expr(ce->proc);
  6990. if (proc_mode == Addressing_Builtin) {
  6991. Entity *e = entity_of_node(pexpr);
  6992. BuiltinProcId id = BuiltinProc_Invalid;
  6993. if (e != nullptr) {
  6994. id = cast(BuiltinProcId)e->Builtin.id;
  6995. } else {
  6996. id = BuiltinProc_DIRECTIVE;
  6997. }
  6998. return lb_build_builtin_proc(p, expr, tv, id);
  6999. }
  7000. // NOTE(bill): Regular call
  7001. lbValue value = {};
  7002. Ast *proc_expr = unparen_expr(ce->proc);
  7003. if (proc_expr->tav.mode == Addressing_Constant) {
  7004. ExactValue v = proc_expr->tav.value;
  7005. switch (v.kind) {
  7006. case ExactValue_Integer:
  7007. {
  7008. u64 u = big_int_to_u64(&v.value_integer);
  7009. lbValue x = {};
  7010. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7011. x.type = t_uintptr;
  7012. x = lb_emit_conv(p, x, t_rawptr);
  7013. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7014. break;
  7015. }
  7016. case ExactValue_Pointer:
  7017. {
  7018. u64 u = cast(u64)v.value_pointer;
  7019. lbValue x = {};
  7020. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7021. x.type = t_uintptr;
  7022. x = lb_emit_conv(p, x, t_rawptr);
  7023. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7024. break;
  7025. }
  7026. }
  7027. }
  7028. if (value.value == nullptr) {
  7029. value = lb_build_expr(p, proc_expr);
  7030. }
  7031. GB_ASSERT(value.value != nullptr);
  7032. Type *proc_type_ = base_type(value.type);
  7033. GB_ASSERT(proc_type_->kind == Type_Proc);
  7034. TypeProc *pt = &proc_type_->Proc;
  7035. set_procedure_abi_types(proc_type_);
  7036. if (is_call_expr_field_value(ce)) {
  7037. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  7038. for_array(arg_index, ce->args) {
  7039. Ast *arg = ce->args[arg_index];
  7040. ast_node(fv, FieldValue, arg);
  7041. GB_ASSERT(fv->field->kind == Ast_Ident);
  7042. String name = fv->field->Ident.token.string;
  7043. isize index = lookup_procedure_parameter(pt, name);
  7044. GB_ASSERT(index >= 0);
  7045. TypeAndValue tav = type_and_value_of_expr(fv->value);
  7046. if (tav.mode == Addressing_Type) {
  7047. args[index] = lb_const_nil(m, tav.type);
  7048. } else {
  7049. args[index] = lb_build_expr(p, fv->value);
  7050. }
  7051. }
  7052. TypeTuple *params = &pt->params->Tuple;
  7053. for (isize i = 0; i < args.count; i++) {
  7054. Entity *e = params->variables[i];
  7055. if (e->kind == Entity_TypeName) {
  7056. args[i] = lb_const_nil(m, e->type);
  7057. } else if (e->kind == Entity_Constant) {
  7058. continue;
  7059. } else {
  7060. GB_ASSERT(e->kind == Entity_Variable);
  7061. if (args[i].value == nullptr) {
  7062. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7063. } else {
  7064. args[i] = lb_emit_conv(p, args[i], e->type);
  7065. }
  7066. }
  7067. }
  7068. for (isize i = 0; i < args.count; i++) {
  7069. Entity *e = params->variables[i];
  7070. if (args[i].type == nullptr) {
  7071. continue;
  7072. } else if (is_type_untyped_nil(args[i].type)) {
  7073. args[i] = lb_const_nil(m, e->type);
  7074. } else if (is_type_untyped_undef(args[i].type)) {
  7075. args[i] = lb_const_undef(m, e->type);
  7076. }
  7077. }
  7078. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  7079. }
  7080. isize arg_index = 0;
  7081. isize arg_count = 0;
  7082. for_array(i, ce->args) {
  7083. Ast *arg = ce->args[i];
  7084. TypeAndValue tav = type_and_value_of_expr(arg);
  7085. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  7086. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  7087. Type *at = tav.type;
  7088. if (at->kind == Type_Tuple) {
  7089. arg_count += at->Tuple.variables.count;
  7090. } else {
  7091. arg_count++;
  7092. }
  7093. }
  7094. isize param_count = 0;
  7095. if (pt->params) {
  7096. GB_ASSERT(pt->params->kind == Type_Tuple);
  7097. param_count = pt->params->Tuple.variables.count;
  7098. }
  7099. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  7100. isize variadic_index = pt->variadic_index;
  7101. bool variadic = pt->variadic && variadic_index >= 0;
  7102. bool vari_expand = ce->ellipsis.pos.line != 0;
  7103. bool is_c_vararg = pt->c_vararg;
  7104. String proc_name = {};
  7105. if (p->entity != nullptr) {
  7106. proc_name = p->entity->token.string;
  7107. }
  7108. TokenPos pos = ast_token(ce->proc).pos;
  7109. TypeTuple *param_tuple = nullptr;
  7110. if (pt->params) {
  7111. GB_ASSERT(pt->params->kind == Type_Tuple);
  7112. param_tuple = &pt->params->Tuple;
  7113. }
  7114. for_array(i, ce->args) {
  7115. Ast *arg = ce->args[i];
  7116. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  7117. if (arg_tv.mode == Addressing_Type) {
  7118. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  7119. } else {
  7120. lbValue a = lb_build_expr(p, arg);
  7121. Type *at = a.type;
  7122. if (at->kind == Type_Tuple) {
  7123. for_array(i, at->Tuple.variables) {
  7124. Entity *e = at->Tuple.variables[i];
  7125. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  7126. args[arg_index++] = v;
  7127. }
  7128. } else {
  7129. args[arg_index++] = a;
  7130. }
  7131. }
  7132. }
  7133. if (param_count > 0) {
  7134. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7135. GB_ASSERT(param_count < 1000000);
  7136. if (arg_count < param_count) {
  7137. isize end = cast(isize)param_count;
  7138. if (variadic) {
  7139. end = variadic_index;
  7140. }
  7141. while (arg_index < end) {
  7142. Entity *e = param_tuple->variables[arg_index];
  7143. GB_ASSERT(e->kind == Entity_Variable);
  7144. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7145. }
  7146. }
  7147. if (is_c_vararg) {
  7148. GB_ASSERT(variadic);
  7149. GB_ASSERT(!vari_expand);
  7150. isize i = 0;
  7151. for (; i < variadic_index; i++) {
  7152. Entity *e = param_tuple->variables[i];
  7153. if (e->kind == Entity_Variable) {
  7154. args[i] = lb_emit_conv(p, args[i], e->type);
  7155. }
  7156. }
  7157. Type *variadic_type = param_tuple->variables[i]->type;
  7158. GB_ASSERT(is_type_slice(variadic_type));
  7159. variadic_type = base_type(variadic_type)->Slice.elem;
  7160. if (!is_type_any(variadic_type)) {
  7161. for (; i < arg_count; i++) {
  7162. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7163. }
  7164. } else {
  7165. for (; i < arg_count; i++) {
  7166. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7167. }
  7168. }
  7169. } else if (variadic) {
  7170. isize i = 0;
  7171. for (; i < variadic_index; i++) {
  7172. Entity *e = param_tuple->variables[i];
  7173. if (e->kind == Entity_Variable) {
  7174. args[i] = lb_emit_conv(p, args[i], e->type);
  7175. }
  7176. }
  7177. if (!vari_expand) {
  7178. Type *variadic_type = param_tuple->variables[i]->type;
  7179. GB_ASSERT(is_type_slice(variadic_type));
  7180. variadic_type = base_type(variadic_type)->Slice.elem;
  7181. for (; i < arg_count; i++) {
  7182. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7183. }
  7184. }
  7185. } else {
  7186. for (isize i = 0; i < param_count; i++) {
  7187. Entity *e = param_tuple->variables[i];
  7188. if (e->kind == Entity_Variable) {
  7189. if (args[i].value == nullptr) {
  7190. continue;
  7191. }
  7192. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7193. args[i] = lb_emit_conv(p, args[i], e->type);
  7194. }
  7195. }
  7196. }
  7197. if (variadic && !vari_expand && !is_c_vararg) {
  7198. // variadic call argument generation
  7199. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7200. Type *elem_type = base_type(slice_type)->Slice.elem;
  7201. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7202. isize slice_len = arg_count+1 - (variadic_index+1);
  7203. if (slice_len > 0) {
  7204. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7205. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7206. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7207. lb_emit_store(p, addr, args[i]);
  7208. }
  7209. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7210. lbValue len = lb_const_int(m, t_int, slice_len);
  7211. lb_fill_slice(p, slice, base_elem, len);
  7212. }
  7213. arg_count = param_count;
  7214. args[variadic_index] = lb_addr_load(p, slice);
  7215. }
  7216. }
  7217. if (variadic && variadic_index+1 < param_count) {
  7218. for (isize i = variadic_index+1; i < param_count; i++) {
  7219. Entity *e = param_tuple->variables[i];
  7220. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7221. }
  7222. }
  7223. isize final_count = param_count;
  7224. if (is_c_vararg) {
  7225. final_count = arg_count;
  7226. }
  7227. if (param_tuple != nullptr) {
  7228. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7229. Entity *e = param_tuple->variables[i];
  7230. if (args[i].type == nullptr) {
  7231. continue;
  7232. } else if (is_type_untyped_nil(args[i].type)) {
  7233. args[i] = lb_const_nil(m, e->type);
  7234. } else if (is_type_untyped_undef(args[i].type)) {
  7235. args[i] = lb_const_undef(m, e->type);
  7236. }
  7237. }
  7238. }
  7239. auto call_args = array_slice(args, 0, final_count);
  7240. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  7241. }
  7242. bool lb_is_const(lbValue value) {
  7243. LLVMValueRef v = value.value;
  7244. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  7245. // TODO(bill): Is this correct behaviour?
  7246. return true;
  7247. }
  7248. if (LLVMIsConstant(v)) {
  7249. return true;
  7250. }
  7251. return false;
  7252. }
  7253. bool lb_is_const_or_global(lbValue value) {
  7254. if (lb_is_const(value)) {
  7255. return true;
  7256. }
  7257. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  7258. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  7259. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  7260. return false;
  7261. }
  7262. LLVMTypeRef elem = LLVMGetElementType(t);
  7263. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  7264. }
  7265. return false;
  7266. }
  7267. bool lb_is_const_nil(lbValue value) {
  7268. LLVMValueRef v = value.value;
  7269. if (LLVMIsConstant(v)) {
  7270. if (LLVMIsAConstantAggregateZero(v)) {
  7271. return true;
  7272. } else if (LLVMIsAConstantPointerNull(v)) {
  7273. return true;
  7274. }
  7275. }
  7276. return false;
  7277. }
  7278. String lb_get_const_string(lbModule *m, lbValue value) {
  7279. GB_ASSERT(lb_is_const(value));
  7280. Type *t = base_type(value.type);
  7281. GB_ASSERT(are_types_identical(t, t_string));
  7282. unsigned ptr_indices[1] = {0};
  7283. unsigned len_indices[1] = {1};
  7284. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  7285. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  7286. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  7287. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  7288. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  7289. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  7290. size_t length = 0;
  7291. char const *text = LLVMGetAsString(underlying_ptr, &length);
  7292. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  7293. return make_string(cast(u8 const *)text, real_length);
  7294. }
  7295. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  7296. GB_ASSERT(is_type_pointer(addr.type));
  7297. Type *type = type_deref(addr.type);
  7298. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  7299. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  7300. }
  7301. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7302. AstPackage *pkg = m->info->runtime_package;
  7303. Entity *e = scope_lookup_current(pkg->scope, name);
  7304. lbValue *found = nullptr;
  7305. if (m != e->code_gen_module) {
  7306. gb_mutex_lock(&m->mutex);
  7307. }
  7308. GB_ASSERT(e->code_gen_module != nullptr);
  7309. found = map_get(&e->code_gen_module->values, hash_entity(e));
  7310. if (m != e->code_gen_module) {
  7311. gb_mutex_unlock(&m->mutex);
  7312. }
  7313. GB_ASSERT(found != nullptr);
  7314. return found->value;
  7315. }
  7316. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  7317. Type *vt = core_type(value.type);
  7318. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  7319. // TODO(bill): lb_emit_byte_swap
  7320. lbValue res = {};
  7321. res.type = platform_type;
  7322. res.value = value.value;
  7323. int sz = cast(int)type_size_of(vt);
  7324. if (sz > 1) {
  7325. if (is_type_float(platform_type)) {
  7326. String name = {};
  7327. switch (sz) {
  7328. case 4: name = str_lit("bswap_f32"); break;
  7329. case 8: name = str_lit("bswap_f64"); break;
  7330. default: GB_PANIC("unhandled byteswap size"); break;
  7331. }
  7332. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7333. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7334. } else {
  7335. GB_ASSERT(is_type_integer(platform_type));
  7336. String name = {};
  7337. switch (sz) {
  7338. case 2: name = str_lit("bswap_16"); break;
  7339. case 4: name = str_lit("bswap_32"); break;
  7340. case 8: name = str_lit("bswap_64"); break;
  7341. case 16: name = str_lit("bswap_128"); break;
  7342. default: GB_PANIC("unhandled byteswap size"); break;
  7343. }
  7344. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7345. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7346. }
  7347. }
  7348. return res;
  7349. }
  7350. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  7351. lbLoopData data = {};
  7352. lbValue max = lb_const_int(p->module, t_int, count);
  7353. data.idx_addr = lb_add_local_generated(p, index_type, true);
  7354. data.body = lb_create_block(p, "loop.body");
  7355. data.done = lb_create_block(p, "loop.done");
  7356. data.loop = lb_create_block(p, "loop.loop");
  7357. lb_emit_jump(p, data.loop);
  7358. lb_start_block(p, data.loop);
  7359. data.idx = lb_addr_load(p, data.idx_addr);
  7360. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  7361. lb_emit_if(p, cond, data.body, data.done);
  7362. lb_start_block(p, data.body);
  7363. return data;
  7364. }
  7365. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  7366. if (data.idx_addr.addr.value != nullptr) {
  7367. lb_emit_increment(p, data.idx_addr.addr);
  7368. lb_emit_jump(p, data.loop);
  7369. lb_start_block(p, data.done);
  7370. }
  7371. }
  7372. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  7373. lbValue res = {};
  7374. res.type = t_llvm_bool;
  7375. Type *t = x.type;
  7376. if (is_type_pointer(t)) {
  7377. if (op_kind == Token_CmpEq) {
  7378. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7379. } else if (op_kind == Token_NotEq) {
  7380. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7381. }
  7382. return res;
  7383. } else if (is_type_cstring(t)) {
  7384. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  7385. if (op_kind == Token_CmpEq) {
  7386. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  7387. } else if (op_kind == Token_NotEq) {
  7388. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  7389. }
  7390. return res;
  7391. } else if (is_type_proc(t)) {
  7392. if (op_kind == Token_CmpEq) {
  7393. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7394. } else if (op_kind == Token_NotEq) {
  7395. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7396. }
  7397. return res;
  7398. } else if (is_type_any(t)) {
  7399. // TODO(bill): is this correct behaviour for nil comparison for any?
  7400. lbValue data = lb_emit_struct_ev(p, x, 0);
  7401. lbValue ti = lb_emit_struct_ev(p, x, 1);
  7402. if (op_kind == Token_CmpEq) {
  7403. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  7404. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  7405. res.value = LLVMBuildOr(p->builder, a, b, "");
  7406. return res;
  7407. } else if (op_kind == Token_NotEq) {
  7408. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  7409. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  7410. res.value = LLVMBuildAnd(p->builder, a, b, "");
  7411. return res;
  7412. }
  7413. } else if (is_type_slice(t)) {
  7414. lbValue len = lb_emit_struct_ev(p, x, 1);
  7415. if (op_kind == Token_CmpEq) {
  7416. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7417. return res;
  7418. } else if (op_kind == Token_NotEq) {
  7419. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7420. return res;
  7421. }
  7422. } else if (is_type_dynamic_array(t)) {
  7423. lbValue cap = lb_emit_struct_ev(p, x, 2);
  7424. if (op_kind == Token_CmpEq) {
  7425. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7426. return res;
  7427. } else if (op_kind == Token_NotEq) {
  7428. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7429. return res;
  7430. }
  7431. } else if (is_type_map(t)) {
  7432. lbValue cap = lb_map_cap(p, x);
  7433. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  7434. } else if (is_type_union(t)) {
  7435. if (type_size_of(t) == 0) {
  7436. if (op_kind == Token_CmpEq) {
  7437. return lb_const_bool(p->module, t_llvm_bool, true);
  7438. } else if (op_kind == Token_NotEq) {
  7439. return lb_const_bool(p->module, t_llvm_bool, false);
  7440. }
  7441. } else {
  7442. lbValue tag = lb_emit_union_tag_value(p, x);
  7443. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  7444. }
  7445. } else if (is_type_typeid(t)) {
  7446. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  7447. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  7448. } else if (is_type_soa_struct(t)) {
  7449. Type *bt = base_type(t);
  7450. if (bt->Struct.soa_kind == StructSoa_Slice) {
  7451. lbValue len = lb_soa_struct_len(p, x);
  7452. if (op_kind == Token_CmpEq) {
  7453. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7454. return res;
  7455. } else if (op_kind == Token_NotEq) {
  7456. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7457. return res;
  7458. }
  7459. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  7460. lbValue cap = lb_soa_struct_cap(p, x);
  7461. if (op_kind == Token_CmpEq) {
  7462. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7463. return res;
  7464. } else if (op_kind == Token_NotEq) {
  7465. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7466. return res;
  7467. }
  7468. }
  7469. } else if (is_type_struct(t) && type_has_nil(t)) {
  7470. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7471. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7472. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7473. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7474. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7475. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7476. return res;
  7477. }
  7478. return {};
  7479. }
  7480. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  7481. Type *original_type = type;
  7482. type = base_type(type);
  7483. GB_ASSERT(is_type_comparable(type));
  7484. Type *pt = alloc_type_pointer(type);
  7485. LLVMTypeRef ptr_type = lb_type(m, pt);
  7486. auto key = hash_type(type);
  7487. lbProcedure **found = map_get(&m->equal_procs, key);
  7488. lbProcedure *compare_proc = nullptr;
  7489. if (found) {
  7490. compare_proc = *found;
  7491. GB_ASSERT(compare_proc != nullptr);
  7492. return {compare_proc->value, compare_proc->type};
  7493. }
  7494. static u32 proc_index = 0;
  7495. char buf[16] = {};
  7496. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  7497. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  7498. String proc_name = make_string_c(str);
  7499. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  7500. map_set(&m->equal_procs, key, p);
  7501. lb_begin_procedure_body(p);
  7502. LLVMValueRef x = LLVMGetParam(p->value, 0);
  7503. LLVMValueRef y = LLVMGetParam(p->value, 1);
  7504. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  7505. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  7506. lbValue lhs = {x, pt};
  7507. lbValue rhs = {y, pt};
  7508. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  7509. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  7510. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  7511. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  7512. lb_start_block(p, block_same_ptr);
  7513. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  7514. lb_start_block(p, block_diff_ptr);
  7515. if (type->kind == Type_Struct) {
  7516. type_set_offsets(type);
  7517. lbBlock *block_false = lb_create_block(p, "bfalse");
  7518. lbValue res = lb_const_bool(m, t_bool, true);
  7519. for_array(i, type->Struct.fields) {
  7520. lbBlock *next_block = lb_create_block(p, "btrue");
  7521. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  7522. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  7523. lbValue left = lb_emit_load(p, pleft);
  7524. lbValue right = lb_emit_load(p, pright);
  7525. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  7526. lb_emit_if(p, ok, next_block, block_false);
  7527. lb_emit_jump(p, next_block);
  7528. lb_start_block(p, next_block);
  7529. }
  7530. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  7531. lb_start_block(p, block_false);
  7532. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  7533. } else {
  7534. lbValue left = lb_emit_load(p, lhs);
  7535. lbValue right = lb_emit_load(p, rhs);
  7536. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  7537. ok = lb_emit_conv(p, ok, t_bool);
  7538. LLVMBuildRet(p->builder, ok.value);
  7539. }
  7540. lb_end_procedure_body(p);
  7541. compare_proc = p;
  7542. return {compare_proc->value, compare_proc->type};
  7543. }
  7544. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  7545. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  7546. i64 sz = type_size_of(type);
  7547. if (1 <= sz && sz <= 16) {
  7548. char name[20] = {};
  7549. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  7550. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7551. args[0] = data;
  7552. args[1] = seed;
  7553. return lb_emit_runtime_call(p, name, args);
  7554. }
  7555. auto args = array_make<lbValue>(permanent_allocator(), 3);
  7556. args[0] = data;
  7557. args[1] = seed;
  7558. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  7559. return lb_emit_runtime_call(p, "default_hasher_n", args);
  7560. }
  7561. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  7562. Type *original_type = type;
  7563. type = core_type(type);
  7564. GB_ASSERT(is_type_valid_for_keys(type));
  7565. Type *pt = alloc_type_pointer(type);
  7566. LLVMTypeRef ptr_type = lb_type(m, pt);
  7567. auto key = hash_type(type);
  7568. lbProcedure **found = map_get(&m->hasher_procs, key);
  7569. if (found) {
  7570. GB_ASSERT(*found != nullptr);
  7571. return {(*found)->value, (*found)->type};
  7572. }
  7573. static u32 proc_index = 0;
  7574. char buf[16] = {};
  7575. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  7576. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  7577. String proc_name = make_string_c(str);
  7578. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  7579. map_set(&m->hasher_procs, key, p);
  7580. lb_begin_procedure_body(p);
  7581. defer (lb_end_procedure_body(p));
  7582. LLVMValueRef x = LLVMGetParam(p->value, 0);
  7583. LLVMValueRef y = LLVMGetParam(p->value, 1);
  7584. lbValue data = {x, t_rawptr};
  7585. lbValue seed = {y, t_uintptr};
  7586. if (is_type_simple_compare(type)) {
  7587. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  7588. LLVMBuildRet(p->builder, res.value);
  7589. return {p->value, p->type};
  7590. }
  7591. if (type->kind == Type_Struct) {
  7592. type_set_offsets(type);
  7593. data = lb_emit_conv(p, data, t_u8_ptr);
  7594. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7595. for_array(i, type->Struct.fields) {
  7596. i64 offset = type->Struct.offsets[i];
  7597. Entity *field = type->Struct.fields[i];
  7598. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  7599. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  7600. args[0] = ptr;
  7601. args[1] = seed;
  7602. seed = lb_emit_call(p, field_hasher, args);
  7603. }
  7604. LLVMBuildRet(p->builder, seed.value);
  7605. } else if (type->kind == Type_Array) {
  7606. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  7607. lb_addr_store(p, pres, seed);
  7608. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7609. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  7610. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  7611. data = lb_emit_conv(p, data, pt);
  7612. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  7613. args[0] = ptr;
  7614. args[1] = lb_addr_load(p, pres);
  7615. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  7616. lb_addr_store(p, pres, new_seed);
  7617. lb_loop_end(p, loop_data);
  7618. lbValue res = lb_addr_load(p, pres);
  7619. LLVMBuildRet(p->builder, res.value);
  7620. } else if (type->kind == Type_EnumeratedArray) {
  7621. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  7622. lb_addr_store(p, res, seed);
  7623. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7624. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  7625. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  7626. data = lb_emit_conv(p, data, pt);
  7627. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  7628. args[0] = ptr;
  7629. args[1] = lb_addr_load(p, res);
  7630. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  7631. lb_addr_store(p, res, new_seed);
  7632. lb_loop_end(p, loop_data);
  7633. lbValue vres = lb_addr_load(p, res);
  7634. LLVMBuildRet(p->builder, vres.value);
  7635. } else if (is_type_cstring(type)) {
  7636. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7637. args[0] = data;
  7638. args[1] = seed;
  7639. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  7640. LLVMBuildRet(p->builder, res.value);
  7641. } else if (is_type_string(type)) {
  7642. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7643. args[0] = data;
  7644. args[1] = seed;
  7645. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  7646. LLVMBuildRet(p->builder, res.value);
  7647. } else {
  7648. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  7649. }
  7650. return {p->value, p->type};
  7651. }
  7652. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  7653. Type *a = core_type(left.type);
  7654. Type *b = core_type(right.type);
  7655. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  7656. lbValue nil_check = {};
  7657. if (is_type_untyped_nil(left.type)) {
  7658. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  7659. } else if (is_type_untyped_nil(right.type)) {
  7660. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  7661. }
  7662. if (nil_check.value != nullptr) {
  7663. return nil_check;
  7664. }
  7665. if (are_types_identical(a, b)) {
  7666. // NOTE(bill): No need for a conversion
  7667. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  7668. left = lb_emit_conv(p, left, right.type);
  7669. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  7670. right = lb_emit_conv(p, right, left.type);
  7671. } else {
  7672. Type *lt = left.type;
  7673. Type *rt = right.type;
  7674. // if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  7675. // Type *blt = base_type(lt);
  7676. // Type *brt = base_type(rt);
  7677. // i64 bits = gb_max(blt->BitSet.bits, brt->BitSet.bits);
  7678. // i64 bytes = bits / 8;
  7679. // switch (bytes) {
  7680. // case 1:
  7681. // left = lb_emit_conv(p, left, t_u8);
  7682. // right = lb_emit_conv(p, right, t_u8);
  7683. // break;
  7684. // case 2:
  7685. // left = lb_emit_conv(p, left, t_u16);
  7686. // right = lb_emit_conv(p, right, t_u16);
  7687. // break;
  7688. // case 4:
  7689. // left = lb_emit_conv(p, left, t_u32);
  7690. // right = lb_emit_conv(p, right, t_u32);
  7691. // break;
  7692. // case 8:
  7693. // left = lb_emit_conv(p, left, t_u64);
  7694. // right = lb_emit_conv(p, right, t_u64);
  7695. // break;
  7696. // default: GB_PANIC("Unknown integer size"); break;
  7697. // }
  7698. // }
  7699. lt = left.type;
  7700. rt = right.type;
  7701. i64 ls = type_size_of(lt);
  7702. i64 rs = type_size_of(rt);
  7703. if (ls < rs) {
  7704. left = lb_emit_conv(p, left, rt);
  7705. } else if (ls > rs) {
  7706. right = lb_emit_conv(p, right, lt);
  7707. } else {
  7708. right = lb_emit_conv(p, right, lt);
  7709. }
  7710. }
  7711. if (is_type_array(a)) {
  7712. Type *tl = base_type(a);
  7713. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  7714. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  7715. TokenKind cmp_op = Token_And;
  7716. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  7717. if (op_kind == Token_NotEq) {
  7718. res = lb_const_bool(p->module, t_llvm_bool, false);
  7719. cmp_op = Token_Or;
  7720. } else if (op_kind == Token_CmpEq) {
  7721. res = lb_const_bool(p->module, t_llvm_bool, true);
  7722. cmp_op = Token_And;
  7723. }
  7724. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  7725. i32 count = cast(i32)tl->Array.count;
  7726. if (inline_array_arith) {
  7727. // inline
  7728. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7729. lb_addr_store(p, val, res);
  7730. for (i32 i = 0; i < count; i++) {
  7731. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  7732. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  7733. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7734. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7735. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7736. }
  7737. return lb_addr_load(p, val);
  7738. } else {
  7739. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  7740. // TODO(bill): Test to see if this is actually faster!!!!
  7741. auto args = array_make<lbValue>(permanent_allocator(), 3);
  7742. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7743. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  7744. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  7745. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  7746. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  7747. return lb_emit_conv(p, res, t_bool);
  7748. } else {
  7749. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7750. lb_addr_store(p, val, res);
  7751. auto loop_data = lb_loop_start(p, count, t_i32);
  7752. {
  7753. lbValue i = loop_data.idx;
  7754. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  7755. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  7756. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7757. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7758. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7759. }
  7760. lb_loop_end(p, loop_data);
  7761. return lb_addr_load(p, val);
  7762. }
  7763. }
  7764. }
  7765. if (is_type_struct(a) && is_type_comparable(a)) {
  7766. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  7767. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  7768. lbValue res = {};
  7769. if (is_type_simple_compare(a)) {
  7770. // TODO(bill): Test to see if this is actually faster!!!!
  7771. auto args = array_make<lbValue>(permanent_allocator(), 3);
  7772. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  7773. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  7774. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  7775. res = lb_emit_runtime_call(p, "memory_equal", args);
  7776. } else {
  7777. lbValue value = lb_get_equal_proc_for_type(p->module, a);
  7778. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7779. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  7780. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  7781. res = lb_emit_call(p, value, args);
  7782. }
  7783. if (op_kind == Token_NotEq) {
  7784. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  7785. }
  7786. return res;
  7787. }
  7788. if (is_type_string(a)) {
  7789. if (is_type_cstring(a)) {
  7790. left = lb_emit_conv(p, left, t_string);
  7791. right = lb_emit_conv(p, right, t_string);
  7792. }
  7793. char const *runtime_procedure = nullptr;
  7794. switch (op_kind) {
  7795. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  7796. case Token_NotEq: runtime_procedure = "string_ne"; break;
  7797. case Token_Lt: runtime_procedure = "string_lt"; break;
  7798. case Token_Gt: runtime_procedure = "string_gt"; break;
  7799. case Token_LtEq: runtime_procedure = "string_le"; break;
  7800. case Token_GtEq: runtime_procedure = "string_gt"; break;
  7801. }
  7802. GB_ASSERT(runtime_procedure != nullptr);
  7803. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7804. args[0] = left;
  7805. args[1] = right;
  7806. return lb_emit_runtime_call(p, runtime_procedure, args);
  7807. }
  7808. if (is_type_complex(a)) {
  7809. char const *runtime_procedure = "";
  7810. i64 sz = 8*type_size_of(a);
  7811. switch (sz) {
  7812. case 64:
  7813. switch (op_kind) {
  7814. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  7815. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  7816. }
  7817. break;
  7818. case 128:
  7819. switch (op_kind) {
  7820. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  7821. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  7822. }
  7823. break;
  7824. }
  7825. GB_ASSERT(runtime_procedure != nullptr);
  7826. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7827. args[0] = left;
  7828. args[1] = right;
  7829. return lb_emit_runtime_call(p, runtime_procedure, args);
  7830. }
  7831. if (is_type_quaternion(a)) {
  7832. char const *runtime_procedure = "";
  7833. i64 sz = 8*type_size_of(a);
  7834. switch (sz) {
  7835. case 128:
  7836. switch (op_kind) {
  7837. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  7838. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  7839. }
  7840. break;
  7841. case 256:
  7842. switch (op_kind) {
  7843. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  7844. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  7845. }
  7846. break;
  7847. }
  7848. GB_ASSERT(runtime_procedure != nullptr);
  7849. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7850. args[0] = left;
  7851. args[1] = right;
  7852. return lb_emit_runtime_call(p, runtime_procedure, args);
  7853. }
  7854. if (is_type_bit_set(a)) {
  7855. switch (op_kind) {
  7856. case Token_Lt:
  7857. case Token_LtEq:
  7858. case Token_Gt:
  7859. case Token_GtEq:
  7860. {
  7861. Type *it = bit_set_to_int(a);
  7862. lbValue lhs = lb_emit_transmute(p, left, it);
  7863. lbValue rhs = lb_emit_transmute(p, right, it);
  7864. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  7865. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  7866. // (lhs & rhs) == lhs
  7867. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  7868. res.type = t_llvm_bool;
  7869. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  7870. // (lhs & rhs) == rhs
  7871. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  7872. res.type = t_llvm_bool;
  7873. }
  7874. // NOTE(bill): Strict subsets
  7875. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  7876. // res &~ (lhs == rhs)
  7877. lbValue eq = {};
  7878. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  7879. eq.type = t_llvm_bool;
  7880. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  7881. }
  7882. return res;
  7883. }
  7884. case Token_CmpEq:
  7885. case Token_NotEq:
  7886. {
  7887. LLVMIntPredicate pred = {};
  7888. switch (op_kind) {
  7889. case Token_CmpEq: pred = LLVMIntEQ; break;
  7890. case Token_NotEq: pred = LLVMIntNE; break;
  7891. }
  7892. lbValue res = {};
  7893. res.type = t_llvm_bool;
  7894. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7895. return res;
  7896. }
  7897. }
  7898. }
  7899. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  7900. Type *t = left.type;
  7901. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  7902. Type *platform_type = integer_endian_type_to_platform_type(t);
  7903. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  7904. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  7905. left = x;
  7906. right = y;
  7907. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  7908. Type *platform_type = integer_endian_type_to_platform_type(t);
  7909. lbValue x = lb_emit_conv(p, left, platform_type);
  7910. lbValue y = lb_emit_conv(p, right, platform_type);
  7911. left = x;
  7912. right = y;
  7913. }
  7914. }
  7915. a = core_type(left.type);
  7916. b = core_type(right.type);
  7917. lbValue res = {};
  7918. res.type = t_llvm_bool;
  7919. if (is_type_integer(a) ||
  7920. is_type_boolean(a) ||
  7921. is_type_pointer(a) ||
  7922. is_type_proc(a) ||
  7923. is_type_enum(a)) {
  7924. LLVMIntPredicate pred = {};
  7925. if (is_type_unsigned(left.type)) {
  7926. switch (op_kind) {
  7927. case Token_Gt: pred = LLVMIntUGT; break;
  7928. case Token_GtEq: pred = LLVMIntUGE; break;
  7929. case Token_Lt: pred = LLVMIntULT; break;
  7930. case Token_LtEq: pred = LLVMIntULE; break;
  7931. }
  7932. } else {
  7933. switch (op_kind) {
  7934. case Token_Gt: pred = LLVMIntSGT; break;
  7935. case Token_GtEq: pred = LLVMIntSGE; break;
  7936. case Token_Lt: pred = LLVMIntSLT; break;
  7937. case Token_LtEq: pred = LLVMIntSLE; break;
  7938. }
  7939. }
  7940. switch (op_kind) {
  7941. case Token_CmpEq: pred = LLVMIntEQ; break;
  7942. case Token_NotEq: pred = LLVMIntNE; break;
  7943. }
  7944. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7945. } else if (is_type_float(a)) {
  7946. LLVMRealPredicate pred = {};
  7947. switch (op_kind) {
  7948. case Token_CmpEq: pred = LLVMRealOEQ; break;
  7949. case Token_Gt: pred = LLVMRealOGT; break;
  7950. case Token_GtEq: pred = LLVMRealOGE; break;
  7951. case Token_Lt: pred = LLVMRealOLT; break;
  7952. case Token_LtEq: pred = LLVMRealOLE; break;
  7953. case Token_NotEq: pred = LLVMRealONE; break;
  7954. }
  7955. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  7956. } else if (is_type_typeid(a)) {
  7957. LLVMIntPredicate pred = {};
  7958. switch (op_kind) {
  7959. case Token_Gt: pred = LLVMIntUGT; break;
  7960. case Token_GtEq: pred = LLVMIntUGE; break;
  7961. case Token_Lt: pred = LLVMIntULT; break;
  7962. case Token_LtEq: pred = LLVMIntULE; break;
  7963. case Token_CmpEq: pred = LLVMIntEQ; break;
  7964. case Token_NotEq: pred = LLVMIntNE; break;
  7965. }
  7966. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7967. } else {
  7968. GB_PANIC("Unhandled comparison kind %s (%s) %.*s %s (%s)", type_to_string(left.type), type_to_string(base_type(left.type)), LIT(token_strings[op_kind]), type_to_string(right.type), type_to_string(base_type(right.type)));
  7969. }
  7970. return res;
  7971. }
  7972. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  7973. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  7974. if (found != nullptr) {
  7975. lbValue value = {};
  7976. value.value = (*found)->value;
  7977. value.type = (*found)->type;
  7978. return value;
  7979. }
  7980. ast_node(pl, ProcLit, expr);
  7981. // NOTE(bill): Generate a new name
  7982. // parent$count
  7983. isize name_len = prefix_name.len + 1 + 8 + 1;
  7984. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  7985. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  7986. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  7987. String name = make_string((u8 *)name_text, name_len-1);
  7988. Type *type = type_of_expr(expr);
  7989. set_procedure_abi_types(type);
  7990. Token token = {};
  7991. token.pos = ast_token(expr).pos;
  7992. token.kind = Token_Ident;
  7993. token.string = name;
  7994. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  7995. e->decl_info = pl->decl;
  7996. lbProcedure *p = lb_create_procedure(m, e);
  7997. lbValue value = {};
  7998. value.value = p->value;
  7999. value.type = p->type;
  8000. array_add(&m->procedures_to_generate, p);
  8001. if (parent != nullptr) {
  8002. array_add(&parent->children, p);
  8003. } else {
  8004. string_map_set(&m->members, name, value);
  8005. }
  8006. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  8007. return value;
  8008. }
  8009. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  8010. lbModule *m = p->module;
  8011. Type *src_type = value.type;
  8012. bool is_ptr = is_type_pointer(src_type);
  8013. bool is_tuple = true;
  8014. Type *tuple = type;
  8015. if (type->kind != Type_Tuple) {
  8016. is_tuple = false;
  8017. tuple = make_optional_ok_type(type);
  8018. }
  8019. lbAddr v = lb_add_local_generated(p, tuple, true);
  8020. if (is_ptr) {
  8021. value = lb_emit_load(p, value);
  8022. }
  8023. Type *src = base_type(type_deref(src_type));
  8024. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  8025. Type *dst = tuple->Tuple.variables[0]->type;
  8026. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  8027. lbValue tag = {};
  8028. lbValue dst_tag = {};
  8029. lbValue cond = {};
  8030. lbValue data = {};
  8031. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8032. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8033. if (is_type_union_maybe_pointer(src)) {
  8034. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8035. } else {
  8036. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  8037. dst_tag = lb_const_union_tag(m, src, dst);
  8038. }
  8039. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  8040. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  8041. if (data.value != nullptr) {
  8042. GB_ASSERT(is_type_union_maybe_pointer(src));
  8043. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  8044. } else {
  8045. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  8046. }
  8047. lb_emit_if(p, cond, ok_block, end_block);
  8048. lb_start_block(p, ok_block);
  8049. if (data.value == nullptr) {
  8050. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8051. }
  8052. lb_emit_store(p, gep0, data);
  8053. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8054. lb_emit_jump(p, end_block);
  8055. lb_start_block(p, end_block);
  8056. if (!is_tuple) {
  8057. if (do_conversion_check) {
  8058. // NOTE(bill): Panic on invalid conversion
  8059. Type *dst_type = tuple->Tuple.variables[0]->type;
  8060. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8061. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8062. args[0] = ok;
  8063. args[1] = lb_const_string(m, pos.file);
  8064. args[2] = lb_const_int(m, t_int, pos.line);
  8065. args[3] = lb_const_int(m, t_int, pos.column);
  8066. args[4] = lb_typeid(m, src_type);
  8067. args[5] = lb_typeid(m, dst_type);
  8068. args[6] = lb_emit_conv(p, value_, t_rawptr);
  8069. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8070. }
  8071. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  8072. }
  8073. return lb_addr_load(p, v);
  8074. }
  8075. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8076. lbModule *m = p->module;
  8077. Type *src_type = value.type;
  8078. if (is_type_pointer(src_type)) {
  8079. value = lb_emit_load(p, value);
  8080. }
  8081. bool is_tuple = true;
  8082. Type *tuple = type;
  8083. if (type->kind != Type_Tuple) {
  8084. is_tuple = false;
  8085. tuple = make_optional_ok_type(type);
  8086. }
  8087. Type *dst_type = tuple->Tuple.variables[0]->type;
  8088. lbAddr v = lb_add_local_generated(p, tuple, true);
  8089. lbValue dst_typeid = lb_typeid(m, dst_type);
  8090. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  8091. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  8092. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  8093. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  8094. lb_emit_if(p, cond, ok_block, end_block);
  8095. lb_start_block(p, ok_block);
  8096. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8097. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8098. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  8099. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  8100. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  8101. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8102. lb_emit_jump(p, end_block);
  8103. lb_start_block(p, end_block);
  8104. if (!is_tuple) {
  8105. // NOTE(bill): Panic on invalid conversion
  8106. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8107. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8108. args[0] = ok;
  8109. args[1] = lb_const_string(m, pos.file);
  8110. args[2] = lb_const_int(m, t_int, pos.line);
  8111. args[3] = lb_const_int(m, t_int, pos.column);
  8112. args[4] = any_typeid;
  8113. args[5] = dst_typeid;
  8114. args[6] = lb_emit_struct_ev(p, value, 0);;
  8115. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8116. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  8117. }
  8118. return v;
  8119. }
  8120. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8121. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  8122. }
  8123. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  8124. lbModule *m = p->module;
  8125. u64 prev_state_flags = p->module->state_flags;
  8126. defer (p->module->state_flags = prev_state_flags);
  8127. if (expr->state_flags != 0) {
  8128. u64 in = expr->state_flags;
  8129. u64 out = p->module->state_flags;
  8130. if (in & StateFlag_bounds_check) {
  8131. out |= StateFlag_bounds_check;
  8132. out &= ~StateFlag_no_bounds_check;
  8133. } else if (in & StateFlag_no_bounds_check) {
  8134. out |= StateFlag_no_bounds_check;
  8135. out &= ~StateFlag_bounds_check;
  8136. }
  8137. p->module->state_flags = out;
  8138. }
  8139. expr = unparen_expr(expr);
  8140. TokenPos expr_pos = ast_token(expr).pos;
  8141. TypeAndValue tv = type_and_value_of_expr(expr);
  8142. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %.*s(%td:%td)\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), LIT(expr_pos.file), expr_pos.line, expr_pos.column, LIT(p->name), type_to_string(p->type));
  8143. if (tv.value.kind != ExactValue_Invalid) {
  8144. // NOTE(bill): Short on constant values
  8145. return lb_const_value(p->module, tv.type, tv.value);
  8146. }
  8147. switch (expr->kind) {
  8148. case_ast_node(bl, BasicLit, expr);
  8149. TokenPos pos = bl->token.pos;
  8150. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  8151. case_end;
  8152. case_ast_node(bd, BasicDirective, expr);
  8153. TokenPos pos = bd->token.pos;
  8154. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  8155. case_end;
  8156. case_ast_node(i, Implicit, expr);
  8157. return lb_addr_load(p, lb_build_addr(p, expr));
  8158. case_end;
  8159. case_ast_node(u, Undef, expr)
  8160. lbValue res = {};
  8161. if (is_type_untyped(tv.type)) {
  8162. res.value = nullptr;
  8163. res.type = t_untyped_undef;
  8164. } else {
  8165. res.value = LLVMGetUndef(lb_type(m, tv.type));
  8166. res.type = tv.type;
  8167. }
  8168. return res;
  8169. case_end;
  8170. case_ast_node(i, Ident, expr);
  8171. Entity *e = entity_from_expr(expr);
  8172. e = strip_entity_wrapping(e);
  8173. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  8174. if (e->kind == Entity_Builtin) {
  8175. Token token = ast_token(expr);
  8176. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  8177. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  8178. LIT(token.pos.file), token.pos.line, token.pos.column);
  8179. return {};
  8180. } else if (e->kind == Entity_Nil) {
  8181. lbValue res = {};
  8182. res.value = nullptr;
  8183. res.type = e->type;
  8184. return res;
  8185. }
  8186. GB_ASSERT(e->kind != Entity_ProcGroup);
  8187. auto *found = map_get(&p->module->values, hash_entity(e));
  8188. if (found) {
  8189. auto v = *found;
  8190. // NOTE(bill): This is because pointers are already pointers in LLVM
  8191. if (is_type_proc(v.type)) {
  8192. return v;
  8193. }
  8194. return lb_emit_load(p, v);
  8195. } else if (e != nullptr && e->kind == Entity_Variable) {
  8196. return lb_addr_load(p, lb_build_addr(p, expr));
  8197. }
  8198. gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  8199. String pkg = {};
  8200. if (e->pkg) {
  8201. pkg = e->pkg->name;
  8202. }
  8203. GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(pkg), LIT(e->token.string), e, type_to_string(e->type), expr);
  8204. return {};
  8205. case_end;
  8206. case_ast_node(de, DerefExpr, expr);
  8207. return lb_addr_load(p, lb_build_addr(p, expr));
  8208. case_end;
  8209. case_ast_node(se, SelectorExpr, expr);
  8210. TypeAndValue tav = type_and_value_of_expr(expr);
  8211. GB_ASSERT(tav.mode != Addressing_Invalid);
  8212. return lb_addr_load(p, lb_build_addr(p, expr));
  8213. case_end;
  8214. case_ast_node(ise, ImplicitSelectorExpr, expr);
  8215. TypeAndValue tav = type_and_value_of_expr(expr);
  8216. GB_ASSERT(tav.mode == Addressing_Constant);
  8217. return lb_const_value(p->module, tv.type, tv.value);
  8218. case_end;
  8219. case_ast_node(se, SelectorCallExpr, expr);
  8220. GB_ASSERT(se->modified_call);
  8221. TypeAndValue tav = type_and_value_of_expr(expr);
  8222. GB_ASSERT(tav.mode != Addressing_Invalid);
  8223. return lb_build_expr(p, se->call);
  8224. case_end;
  8225. case_ast_node(te, TernaryExpr, expr);
  8226. LLVMValueRef incoming_values[2] = {};
  8227. LLVMBasicBlockRef incoming_blocks[2] = {};
  8228. GB_ASSERT(te->y != nullptr);
  8229. lbBlock *then = lb_create_block(p, "if.then");
  8230. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8231. lbBlock *else_ = lb_create_block(p, "if.else");
  8232. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8233. lb_start_block(p, then);
  8234. Type *type = default_type(type_of_expr(expr));
  8235. lb_open_scope(p);
  8236. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8237. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8238. lb_emit_jump(p, done);
  8239. lb_start_block(p, else_);
  8240. lb_open_scope(p);
  8241. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8242. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8243. lb_emit_jump(p, done);
  8244. lb_start_block(p, done);
  8245. lbValue res = {};
  8246. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8247. res.type = type;
  8248. GB_ASSERT(p->curr_block->preds.count >= 2);
  8249. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8250. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8251. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8252. return res;
  8253. case_end;
  8254. case_ast_node(te, TernaryIfExpr, expr);
  8255. LLVMValueRef incoming_values[2] = {};
  8256. LLVMBasicBlockRef incoming_blocks[2] = {};
  8257. GB_ASSERT(te->y != nullptr);
  8258. lbBlock *then = lb_create_block(p, "if.then");
  8259. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8260. lbBlock *else_ = lb_create_block(p, "if.else");
  8261. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8262. lb_start_block(p, then);
  8263. Type *type = default_type(type_of_expr(expr));
  8264. lb_open_scope(p);
  8265. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8266. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8267. lb_emit_jump(p, done);
  8268. lb_start_block(p, else_);
  8269. lb_open_scope(p);
  8270. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8271. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8272. lb_emit_jump(p, done);
  8273. lb_start_block(p, done);
  8274. lbValue res = {};
  8275. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8276. res.type = type;
  8277. GB_ASSERT(p->curr_block->preds.count >= 2);
  8278. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8279. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8280. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8281. return res;
  8282. case_end;
  8283. case_ast_node(te, TernaryWhenExpr, expr);
  8284. TypeAndValue tav = type_and_value_of_expr(te->cond);
  8285. GB_ASSERT(tav.mode == Addressing_Constant);
  8286. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  8287. if (tav.value.value_bool) {
  8288. return lb_build_expr(p, te->x);
  8289. } else {
  8290. return lb_build_expr(p, te->y);
  8291. }
  8292. case_end;
  8293. case_ast_node(ta, TypeAssertion, expr);
  8294. TokenPos pos = ast_token(expr).pos;
  8295. Type *type = tv.type;
  8296. lbValue e = lb_build_expr(p, ta->expr);
  8297. Type *t = type_deref(e.type);
  8298. if (is_type_union(t)) {
  8299. return lb_emit_union_cast(p, e, type, pos);
  8300. } else if (is_type_any(t)) {
  8301. return lb_emit_any_cast(p, e, type, pos);
  8302. } else {
  8303. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8304. }
  8305. case_end;
  8306. case_ast_node(tc, TypeCast, expr);
  8307. lbValue e = lb_build_expr(p, tc->expr);
  8308. switch (tc->token.kind) {
  8309. case Token_cast:
  8310. return lb_emit_conv(p, e, tv.type);
  8311. case Token_transmute:
  8312. return lb_emit_transmute(p, e, tv.type);
  8313. }
  8314. GB_PANIC("Invalid AST TypeCast");
  8315. case_end;
  8316. case_ast_node(ac, AutoCast, expr);
  8317. return lb_build_expr(p, ac->expr);
  8318. case_end;
  8319. case_ast_node(ue, UnaryExpr, expr);
  8320. switch (ue->op.kind) {
  8321. case Token_And: {
  8322. Ast *ue_expr = unparen_expr(ue->expr);
  8323. if (ue_expr->kind == Ast_CompoundLit) {
  8324. lbValue v = lb_build_expr(p, ue->expr);
  8325. Type *type = v.type;
  8326. lbAddr addr = {};
  8327. if (p->is_startup) {
  8328. addr = lb_add_global_generated(p->module, type, v);
  8329. } else {
  8330. addr = lb_add_local_generated(p, type, false);
  8331. }
  8332. lb_addr_store(p, addr, v);
  8333. return addr.addr;
  8334. } else if (ue_expr->kind == Ast_TypeAssertion) {
  8335. GB_ASSERT(is_type_pointer(tv.type));
  8336. ast_node(ta, TypeAssertion, ue_expr);
  8337. TokenPos pos = ast_token(expr).pos;
  8338. Type *type = type_of_expr(ue_expr);
  8339. GB_ASSERT(!is_type_tuple(type));
  8340. lbValue e = lb_build_expr(p, ta->expr);
  8341. Type *t = type_deref(e.type);
  8342. if (is_type_union(t)) {
  8343. lbValue v = e;
  8344. if (!is_type_pointer(v.type)) {
  8345. v = lb_address_from_load_or_generate_local(p, v);
  8346. }
  8347. Type *src_type = type_deref(v.type);
  8348. Type *dst_type = type;
  8349. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  8350. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  8351. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  8352. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8353. args[0] = ok;
  8354. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8355. args[2] = lb_const_int(p->module, t_int, pos.line);
  8356. args[3] = lb_const_int(p->module, t_int, pos.column);
  8357. args[4] = lb_typeid(p->module, src_type);
  8358. args[5] = lb_typeid(p->module, dst_type);
  8359. lb_emit_runtime_call(p, "type_assertion_check", args);
  8360. lbValue data_ptr = v;
  8361. return lb_emit_conv(p, data_ptr, tv.type);
  8362. } else if (is_type_any(t)) {
  8363. lbValue v = e;
  8364. if (is_type_pointer(v.type)) {
  8365. v = lb_emit_load(p, v);
  8366. }
  8367. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  8368. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  8369. lbValue id = lb_typeid(p->module, type);
  8370. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  8371. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8372. args[0] = ok;
  8373. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8374. args[2] = lb_const_int(p->module, t_int, pos.line);
  8375. args[3] = lb_const_int(p->module, t_int, pos.column);
  8376. args[4] = any_id;
  8377. args[5] = id;
  8378. lb_emit_runtime_call(p, "type_assertion_check", args);
  8379. return lb_emit_conv(p, data_ptr, tv.type);
  8380. } else {
  8381. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  8382. }
  8383. }
  8384. return lb_build_addr_ptr(p, ue->expr);
  8385. }
  8386. default:
  8387. {
  8388. lbValue v = lb_build_expr(p, ue->expr);
  8389. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  8390. }
  8391. }
  8392. case_end;
  8393. case_ast_node(be, BinaryExpr, expr);
  8394. return lb_build_binary_expr(p, expr);
  8395. case_end;
  8396. case_ast_node(pl, ProcLit, expr);
  8397. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  8398. case_end;
  8399. case_ast_node(cl, CompoundLit, expr);
  8400. return lb_addr_load(p, lb_build_addr(p, expr));
  8401. case_end;
  8402. case_ast_node(ce, CallExpr, expr);
  8403. lbValue res = lb_build_call_expr(p, expr);
  8404. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  8405. GB_ASSERT(is_type_tuple(res.type));
  8406. GB_ASSERT(res.type->Tuple.variables.count == 2);
  8407. return lb_emit_struct_ev(p, res, 0);
  8408. }
  8409. return res;
  8410. case_end;
  8411. case_ast_node(se, SliceExpr, expr);
  8412. return lb_addr_load(p, lb_build_addr(p, expr));
  8413. case_end;
  8414. case_ast_node(ie, IndexExpr, expr);
  8415. return lb_addr_load(p, lb_build_addr(p, expr));
  8416. case_end;
  8417. case_ast_node(ia, InlineAsmExpr, expr);
  8418. Type *t = type_of_expr(expr);
  8419. GB_ASSERT(is_type_asm_proc(t));
  8420. String asm_string = {};
  8421. String constraints_string = {};
  8422. TypeAndValue tav;
  8423. tav = type_and_value_of_expr(ia->asm_string);
  8424. GB_ASSERT(is_type_string(tav.type));
  8425. GB_ASSERT(tav.value.kind == ExactValue_String);
  8426. asm_string = tav.value.value_string;
  8427. tav = type_and_value_of_expr(ia->constraints_string);
  8428. GB_ASSERT(is_type_string(tav.type));
  8429. GB_ASSERT(tav.value.kind == ExactValue_String);
  8430. constraints_string = tav.value.value_string;
  8431. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  8432. switch (ia->dialect) {
  8433. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  8434. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  8435. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  8436. default: GB_PANIC("Unhandled inline asm dialect"); break;
  8437. }
  8438. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  8439. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8440. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  8441. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  8442. ia->has_side_effects, ia->is_align_stack, dialect
  8443. );
  8444. GB_ASSERT(the_asm != nullptr);
  8445. return {the_asm, t};
  8446. case_end;
  8447. }
  8448. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  8449. return {};
  8450. }
  8451. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  8452. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  8453. String name = e->token.string;
  8454. Entity *parent = e->using_parent;
  8455. Selection sel = lookup_field(parent->type, name, false);
  8456. GB_ASSERT(sel.entity != nullptr);
  8457. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  8458. lbValue v = {};
  8459. if (pv != nullptr) {
  8460. v = *pv;
  8461. } else {
  8462. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  8463. v = lb_build_addr_ptr(p, e->using_expr);
  8464. }
  8465. GB_ASSERT(v.value != nullptr);
  8466. GB_ASSERT(parent->type == type_deref(v.type));
  8467. return lb_emit_deep_field_gep(p, v, sel);
  8468. }
  8469. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  8470. GB_ASSERT(e != nullptr);
  8471. if (e->kind == Entity_Constant) {
  8472. Type *t = default_type(type_of_expr(expr));
  8473. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  8474. lbAddr g = lb_add_global_generated(p->module, t, v);
  8475. return g;
  8476. }
  8477. lbValue v = {};
  8478. lbValue *found = map_get(&p->module->values, hash_entity(e));
  8479. if (found) {
  8480. v = *found;
  8481. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  8482. // NOTE(bill): Calculate the using variable every time
  8483. v = lb_get_using_variable(p, e);
  8484. }
  8485. if (v.value == nullptr) {
  8486. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  8487. LIT(p->name),
  8488. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  8489. GB_PANIC("Unknown value");
  8490. }
  8491. return lb_addr(v);
  8492. }
  8493. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  8494. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  8495. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  8496. map_type = base_type(map_type);
  8497. GB_ASSERT(map_type->kind == Type_Map);
  8498. Type *key_type = map_type->Map.key;
  8499. Type *val_type = map_type->Map.value;
  8500. // NOTE(bill): Removes unnecessary allocation if split gep
  8501. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  8502. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  8503. lb_emit_store(p, gep0, m);
  8504. i64 entry_size = type_size_of (map_type->Map.entry_type);
  8505. i64 entry_align = type_align_of (map_type->Map.entry_type);
  8506. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  8507. i64 key_size = type_size_of (map_type->Map.key);
  8508. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  8509. i64 value_size = type_size_of (map_type->Map.value);
  8510. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  8511. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  8512. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  8513. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  8514. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  8515. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  8516. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  8517. return lb_addr_load(p, h);
  8518. }
  8519. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  8520. if (true) {
  8521. return {};
  8522. }
  8523. lbValue hashed_key = {};
  8524. if (lb_is_const(key)) {
  8525. u64 hash = 0xcbf29ce484222325;
  8526. if (is_type_cstring(key_type)) {
  8527. size_t length = 0;
  8528. char const *text = LLVMGetAsString(key.value, &length);
  8529. hash = fnv64a(text, cast(isize)length);
  8530. } else if (is_type_string(key_type)) {
  8531. unsigned data_indices[] = {0};
  8532. unsigned len_indices[] = {1};
  8533. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  8534. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  8535. isize length = LLVMConstIntGetSExtValue(len);
  8536. char const *text = nullptr;
  8537. if (false && length != 0) {
  8538. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  8539. return {};
  8540. }
  8541. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  8542. size_t ulength = 0;
  8543. text = LLVMGetAsString(data, &ulength);
  8544. gb_printf_err("%td %td %s\n", length, ulength, text);
  8545. length = gb_min(length, cast(isize)ulength);
  8546. }
  8547. hash = fnv64a(text, cast(isize)length);
  8548. } else {
  8549. return {};
  8550. }
  8551. // TODO(bill): other const hash types
  8552. if (build_context.word_size == 4) {
  8553. hash &= 0xffffffffull;
  8554. }
  8555. hashed_key = lb_const_int(m, t_uintptr, hash);
  8556. }
  8557. return hashed_key;
  8558. }
  8559. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  8560. Type *hash_type = t_u64;
  8561. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  8562. lbValue vp = lb_addr_get_ptr(p, v);
  8563. Type *t = base_type(key.type);
  8564. key = lb_emit_conv(p, key, key_type);
  8565. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  8566. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  8567. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  8568. if (hashed_key.value == nullptr) {
  8569. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  8570. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8571. args[0] = key_ptr;
  8572. args[1] = lb_const_int(p->module, t_uintptr, 0);
  8573. hashed_key = lb_emit_call(p, hasher, args);
  8574. }
  8575. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  8576. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  8577. return lb_addr_load(p, v);
  8578. }
  8579. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  8580. lbValue map_key, lbValue map_value, Ast *node) {
  8581. map_type = base_type(map_type);
  8582. GB_ASSERT(map_type->kind == Type_Map);
  8583. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  8584. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  8585. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  8586. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  8587. lb_addr_store(p, value_addr, v);
  8588. auto args = array_make<lbValue>(permanent_allocator(), 4);
  8589. args[0] = h;
  8590. args[1] = key;
  8591. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  8592. args[3] = lb_emit_source_code_location(p, node);
  8593. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  8594. }
  8595. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  8596. expr = unparen_expr(expr);
  8597. switch (expr->kind) {
  8598. case_ast_node(i, Implicit, expr);
  8599. lbAddr v = {};
  8600. switch (i->kind) {
  8601. case Token_context:
  8602. v = lb_find_or_generate_context_ptr(p);
  8603. break;
  8604. }
  8605. GB_ASSERT(v.addr.value != nullptr);
  8606. return v;
  8607. case_end;
  8608. case_ast_node(i, Ident, expr);
  8609. if (is_blank_ident(expr)) {
  8610. lbAddr val = {};
  8611. return val;
  8612. }
  8613. String name = i->token.string;
  8614. Entity *e = entity_of_node(expr);
  8615. return lb_build_addr_from_entity(p, e, expr);
  8616. case_end;
  8617. case_ast_node(se, SelectorExpr, expr);
  8618. Ast *sel = unparen_expr(se->selector);
  8619. if (sel->kind == Ast_Ident) {
  8620. String selector = sel->Ident.token.string;
  8621. TypeAndValue tav = type_and_value_of_expr(se->expr);
  8622. if (tav.mode == Addressing_Invalid) {
  8623. // NOTE(bill): Imports
  8624. Entity *imp = entity_of_node(se->expr);
  8625. if (imp != nullptr) {
  8626. GB_ASSERT(imp->kind == Entity_ImportName);
  8627. }
  8628. return lb_build_addr(p, unparen_expr(se->selector));
  8629. }
  8630. Type *type = base_type(tav.type);
  8631. if (tav.mode == Addressing_Type) { // Addressing_Type
  8632. Selection sel = lookup_field(type, selector, true);
  8633. Entity *e = sel.entity;
  8634. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  8635. GB_ASSERT(e->flags & EntityFlag_TypeField);
  8636. String name = e->token.string;
  8637. /*if (name == "names") {
  8638. lbValue ti_ptr = lb_type_info(m, type);
  8639. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  8640. lbValue names_ptr = nullptr;
  8641. if (is_type_enum(type)) {
  8642. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  8643. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  8644. } else if (type->kind == Type_Struct) {
  8645. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  8646. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  8647. }
  8648. return ir_addr(names_ptr);
  8649. } else */{
  8650. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  8651. }
  8652. GB_PANIC("Unreachable");
  8653. }
  8654. Selection sel = lookup_field(type, selector, false);
  8655. GB_ASSERT(sel.entity != nullptr);
  8656. {
  8657. lbAddr addr = lb_build_addr(p, se->expr);
  8658. if (addr.kind == lbAddr_Map) {
  8659. lbValue v = lb_addr_load(p, addr);
  8660. lbValue a = lb_address_from_load_or_generate_local(p, v);
  8661. a = lb_emit_deep_field_gep(p, a, sel);
  8662. return lb_addr(a);
  8663. } else if (addr.kind == lbAddr_Context) {
  8664. GB_ASSERT(sel.index.count > 0);
  8665. if (addr.ctx.sel.index.count >= 0) {
  8666. sel = selection_combine(addr.ctx.sel, sel);
  8667. }
  8668. addr.ctx.sel = sel;
  8669. addr.kind = lbAddr_Context;
  8670. return addr;
  8671. } else if (addr.kind == lbAddr_SoaVariable) {
  8672. lbValue index = addr.soa.index;
  8673. i32 first_index = sel.index[0];
  8674. Selection sub_sel = sel;
  8675. sub_sel.index.data += 1;
  8676. sub_sel.index.count -= 1;
  8677. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  8678. Type *t = base_type(type_deref(addr.addr.type));
  8679. GB_ASSERT(is_type_soa_struct(t));
  8680. // TODO(bill): Bounds check
  8681. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  8682. lbValue len = lb_soa_struct_len(p, addr.addr);
  8683. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  8684. }
  8685. lbValue item = {};
  8686. if (t->Struct.soa_kind == StructSoa_Fixed) {
  8687. item = lb_emit_array_ep(p, arr, index);
  8688. } else {
  8689. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  8690. }
  8691. if (sub_sel.index.count > 0) {
  8692. item = lb_emit_deep_field_gep(p, item, sub_sel);
  8693. }
  8694. return lb_addr(item);
  8695. }
  8696. lbValue a = lb_addr_get_ptr(p, addr);
  8697. a = lb_emit_deep_field_gep(p, a, sel);
  8698. return lb_addr(a);
  8699. }
  8700. } else {
  8701. GB_PANIC("Unsupported selector expression");
  8702. }
  8703. case_end;
  8704. case_ast_node(se, SelectorCallExpr, expr);
  8705. GB_ASSERT(se->modified_call);
  8706. TypeAndValue tav = type_and_value_of_expr(expr);
  8707. GB_ASSERT(tav.mode != Addressing_Invalid);
  8708. return lb_build_addr(p, se->call);
  8709. case_end;
  8710. case_ast_node(ta, TypeAssertion, expr);
  8711. TokenPos pos = ast_token(expr).pos;
  8712. lbValue e = lb_build_expr(p, ta->expr);
  8713. Type *t = type_deref(e.type);
  8714. if (is_type_union(t)) {
  8715. Type *type = type_of_expr(expr);
  8716. lbAddr v = lb_add_local_generated(p, type, false);
  8717. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  8718. return v;
  8719. } else if (is_type_any(t)) {
  8720. Type *type = type_of_expr(expr);
  8721. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  8722. } else {
  8723. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8724. }
  8725. case_end;
  8726. case_ast_node(ue, UnaryExpr, expr);
  8727. switch (ue->op.kind) {
  8728. case Token_And: {
  8729. return lb_build_addr(p, ue->expr);
  8730. }
  8731. default:
  8732. GB_PANIC("Invalid unary expression for lb_build_addr");
  8733. }
  8734. case_end;
  8735. case_ast_node(be, BinaryExpr, expr);
  8736. lbValue v = lb_build_expr(p, expr);
  8737. Type *t = v.type;
  8738. if (is_type_pointer(t)) {
  8739. return lb_addr(v);
  8740. }
  8741. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  8742. case_end;
  8743. case_ast_node(ie, IndexExpr, expr);
  8744. Type *t = base_type(type_of_expr(ie->expr));
  8745. bool deref = is_type_pointer(t);
  8746. t = base_type(type_deref(t));
  8747. if (is_type_soa_struct(t)) {
  8748. // SOA STRUCTURES!!!!
  8749. lbValue val = lb_build_addr_ptr(p, ie->expr);
  8750. if (deref) {
  8751. val = lb_emit_load(p, val);
  8752. }
  8753. lbValue index = lb_build_expr(p, ie->index);
  8754. return lb_addr_soa_variable(val, index, ie->index);
  8755. }
  8756. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  8757. // SOA Structures for slices/dynamic arrays
  8758. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  8759. lbValue field = lb_build_expr(p, ie->expr);
  8760. lbValue index = lb_build_expr(p, ie->index);
  8761. if (!build_context.no_bounds_check) {
  8762. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  8763. // GB_ASSERT(LLVMIsALoadInst(field.value));
  8764. // lbValue a = {};
  8765. // a.value = LLVMGetOperand(field.value, 0);
  8766. // a.type = alloc_type_pointer(field.type);
  8767. // irInstr *b = &a->Instr;
  8768. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  8769. // lbValue base_struct = b->StructElementPtr.address;
  8770. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  8771. // lbValue len = ir_soa_struct_len(p, base_struct);
  8772. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8773. }
  8774. lbValue val = lb_emit_ptr_offset(p, field, index);
  8775. return lb_addr(val);
  8776. }
  8777. if (!is_type_indexable(t)) {
  8778. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8779. if (found != nullptr) {
  8780. if (found->kind == TypeAtomOp_index_get) {
  8781. return lb_build_addr(p, found->node);
  8782. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  8783. return lb_addr(lb_build_expr(p, found->node));
  8784. } else if (found->kind == TypeAtomOp_index_set) {
  8785. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  8786. if (deref) {
  8787. ptr = lb_emit_load(p, ptr);
  8788. }
  8789. lbAddr addr = {lbAddr_AtomOp_index_set};
  8790. addr.addr = ptr;
  8791. addr.index_set.index = lb_build_expr(p, ie->index);
  8792. addr.index_set.node = found->node;
  8793. return addr;
  8794. }
  8795. }
  8796. }
  8797. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  8798. if (is_type_map(t)) {
  8799. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  8800. if (deref) {
  8801. map_val = lb_emit_load(p, map_val);
  8802. }
  8803. lbValue key = lb_build_expr(p, ie->index);
  8804. key = lb_emit_conv(p, key, t->Map.key);
  8805. Type *result_type = type_of_expr(expr);
  8806. return lb_addr_map(map_val, key, t, result_type);
  8807. }
  8808. switch (t->kind) {
  8809. case Type_Array: {
  8810. lbValue array = {};
  8811. array = lb_build_addr_ptr(p, ie->expr);
  8812. if (deref) {
  8813. array = lb_emit_load(p, array);
  8814. }
  8815. lbValue index = lb_build_expr(p, ie->index);
  8816. index = lb_emit_conv(p, index, t_int);
  8817. lbValue elem = lb_emit_array_ep(p, array, index);
  8818. auto index_tv = type_and_value_of_expr(ie->index);
  8819. if (index_tv.mode != Addressing_Constant) {
  8820. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  8821. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8822. }
  8823. return lb_addr(elem);
  8824. }
  8825. case Type_EnumeratedArray: {
  8826. lbValue array = {};
  8827. array = lb_build_addr_ptr(p, ie->expr);
  8828. if (deref) {
  8829. array = lb_emit_load(p, array);
  8830. }
  8831. Type *index_type = t->EnumeratedArray.index;
  8832. auto index_tv = type_and_value_of_expr(ie->index);
  8833. lbValue index = {};
  8834. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  8835. if (index_tv.mode == Addressing_Constant) {
  8836. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  8837. index = lb_const_value(p->module, index_type, idx);
  8838. } else {
  8839. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8840. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  8841. }
  8842. } else {
  8843. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8844. }
  8845. lbValue elem = lb_emit_array_ep(p, array, index);
  8846. if (index_tv.mode != Addressing_Constant) {
  8847. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  8848. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8849. }
  8850. return lb_addr(elem);
  8851. }
  8852. case Type_Slice: {
  8853. lbValue slice = {};
  8854. slice = lb_build_expr(p, ie->expr);
  8855. if (deref) {
  8856. slice = lb_emit_load(p, slice);
  8857. }
  8858. lbValue elem = lb_slice_elem(p, slice);
  8859. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8860. lbValue len = lb_slice_len(p, slice);
  8861. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8862. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8863. return lb_addr(v);
  8864. }
  8865. case Type_RelativeSlice: {
  8866. lbAddr slice_addr = {};
  8867. if (deref) {
  8868. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  8869. } else {
  8870. slice_addr = lb_build_addr(p, ie->expr);
  8871. }
  8872. lbValue slice = lb_addr_load(p, slice_addr);
  8873. lbValue elem = lb_slice_elem(p, slice);
  8874. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8875. lbValue len = lb_slice_len(p, slice);
  8876. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8877. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8878. return lb_addr(v);
  8879. }
  8880. case Type_DynamicArray: {
  8881. lbValue dynamic_array = {};
  8882. dynamic_array = lb_build_expr(p, ie->expr);
  8883. if (deref) {
  8884. dynamic_array = lb_emit_load(p, dynamic_array);
  8885. }
  8886. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  8887. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  8888. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8889. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8890. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8891. return lb_addr(v);
  8892. }
  8893. case Type_Basic: { // Basic_string
  8894. lbValue str;
  8895. lbValue elem;
  8896. lbValue len;
  8897. lbValue index;
  8898. str = lb_build_expr(p, ie->expr);
  8899. if (deref) {
  8900. str = lb_emit_load(p, str);
  8901. }
  8902. elem = lb_string_elem(p, str);
  8903. len = lb_string_len(p, str);
  8904. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8905. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8906. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  8907. }
  8908. }
  8909. case_end;
  8910. case_ast_node(se, SliceExpr, expr);
  8911. lbValue low = lb_const_int(p->module, t_int, 0);
  8912. lbValue high = {};
  8913. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  8914. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  8915. bool no_indices = se->low == nullptr && se->high == nullptr;
  8916. {
  8917. Type *type = base_type(type_of_expr(se->expr));
  8918. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  8919. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  8920. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  8921. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8922. if (found) {
  8923. lbValue base = lb_build_expr(p, found->node);
  8924. Type *slice_type = base.type;
  8925. lbValue len = lb_slice_len(p, base);
  8926. if (high.value == nullptr) high = len;
  8927. if (!no_indices) {
  8928. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8929. }
  8930. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8931. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8932. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8933. lb_fill_slice(p, slice, elem, new_len);
  8934. return slice;
  8935. }
  8936. }
  8937. }
  8938. }
  8939. lbAddr addr = lb_build_addr(p, se->expr);
  8940. lbValue base = lb_addr_load(p, addr);
  8941. Type *type = base_type(base.type);
  8942. if (is_type_pointer(type)) {
  8943. type = base_type(type_deref(type));
  8944. addr = lb_addr(base);
  8945. base = lb_addr_load(p, addr);
  8946. }
  8947. switch (type->kind) {
  8948. case Type_Slice: {
  8949. Type *slice_type = type;
  8950. lbValue len = lb_slice_len(p, base);
  8951. if (high.value == nullptr) high = len;
  8952. if (!no_indices) {
  8953. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8954. }
  8955. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8956. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8957. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8958. lb_fill_slice(p, slice, elem, new_len);
  8959. return slice;
  8960. }
  8961. case Type_RelativeSlice:
  8962. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  8963. break;
  8964. case Type_DynamicArray: {
  8965. Type *elem_type = type->DynamicArray.elem;
  8966. Type *slice_type = alloc_type_slice(elem_type);
  8967. lbValue len = lb_dynamic_array_len(p, base);
  8968. if (high.value == nullptr) high = len;
  8969. if (!no_indices) {
  8970. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8971. }
  8972. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  8973. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8974. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8975. lb_fill_slice(p, slice, elem, new_len);
  8976. return slice;
  8977. }
  8978. case Type_Array: {
  8979. Type *slice_type = alloc_type_slice(type->Array.elem);
  8980. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  8981. if (high.value == nullptr) high = len;
  8982. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  8983. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  8984. if (!low_const || !high_const) {
  8985. if (!no_indices) {
  8986. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8987. }
  8988. }
  8989. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  8990. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8991. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8992. lb_fill_slice(p, slice, elem, new_len);
  8993. return slice;
  8994. }
  8995. case Type_Basic: {
  8996. GB_ASSERT(type == t_string);
  8997. lbValue len = lb_string_len(p, base);
  8998. if (high.value == nullptr) high = len;
  8999. if (!no_indices) {
  9000. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9001. }
  9002. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  9003. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9004. lbAddr str = lb_add_local_generated(p, t_string, false);
  9005. lb_fill_string(p, str, elem, new_len);
  9006. return str;
  9007. }
  9008. case Type_Struct:
  9009. if (is_type_soa_struct(type)) {
  9010. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  9011. if (high.value == nullptr) high = len;
  9012. if (!no_indices) {
  9013. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9014. }
  9015. #if 1
  9016. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  9017. if (type->Struct.soa_kind == StructSoa_Fixed) {
  9018. i32 field_count = cast(i32)type->Struct.fields.count;
  9019. for (i32 i = 0; i < field_count; i++) {
  9020. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9021. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  9022. field_src = lb_emit_array_ep(p, field_src, low);
  9023. lb_emit_store(p, field_dst, field_src);
  9024. }
  9025. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9026. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9027. lb_emit_store(p, len_dst, new_len);
  9028. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  9029. if (no_indices) {
  9030. lb_addr_store(p, dst, base);
  9031. } else {
  9032. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  9033. for (i32 i = 0; i < field_count; i++) {
  9034. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9035. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9036. field_src = lb_emit_ptr_offset(p, field_src, low);
  9037. lb_emit_store(p, field_dst, field_src);
  9038. }
  9039. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9040. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9041. lb_emit_store(p, len_dst, new_len);
  9042. }
  9043. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  9044. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  9045. for (i32 i = 0; i < field_count; i++) {
  9046. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9047. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9048. field_src = lb_emit_ptr_offset(p, field_src, low);
  9049. lb_emit_store(p, field_dst, field_src);
  9050. }
  9051. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9052. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9053. lb_emit_store(p, len_dst, new_len);
  9054. }
  9055. return dst;
  9056. #endif
  9057. }
  9058. break;
  9059. }
  9060. GB_PANIC("Unknown slicable type");
  9061. case_end;
  9062. case_ast_node(de, DerefExpr, expr);
  9063. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  9064. lbAddr addr = lb_build_addr(p, de->expr);
  9065. addr.relative.deref = true;
  9066. return addr;
  9067. }
  9068. lbValue addr = lb_build_expr(p, de->expr);
  9069. return lb_addr(addr);
  9070. case_end;
  9071. case_ast_node(ce, CallExpr, expr);
  9072. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  9073. lbValue e = lb_build_expr(p, expr);
  9074. lbAddr v = lb_add_local_generated(p, e.type, false);
  9075. lb_addr_store(p, v, e);
  9076. return v;
  9077. case_end;
  9078. case_ast_node(cl, CompoundLit, expr);
  9079. Type *type = type_of_expr(expr);
  9080. Type *bt = base_type(type);
  9081. lbAddr v = lb_add_local_generated(p, type, true);
  9082. Type *et = nullptr;
  9083. switch (bt->kind) {
  9084. case Type_Array: et = bt->Array.elem; break;
  9085. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  9086. case Type_Slice: et = bt->Slice.elem; break;
  9087. case Type_BitSet: et = bt->BitSet.elem; break;
  9088. case Type_SimdVector: et = bt->SimdVector.elem; break;
  9089. }
  9090. String proc_name = {};
  9091. if (p->entity) {
  9092. proc_name = p->entity->token.string;
  9093. }
  9094. TokenPos pos = ast_token(expr).pos;
  9095. switch (bt->kind) {
  9096. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  9097. case Type_Struct: {
  9098. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  9099. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  9100. bool is_raw_union = is_type_raw_union(bt);
  9101. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  9102. TypeStruct *st = &bt->Struct;
  9103. if (cl->elems.count > 0) {
  9104. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9105. for_array(field_index, cl->elems) {
  9106. Ast *elem = cl->elems[field_index];
  9107. lbValue field_expr = {};
  9108. Entity *field = nullptr;
  9109. isize index = field_index;
  9110. if (elem->kind == Ast_FieldValue) {
  9111. ast_node(fv, FieldValue, elem);
  9112. String name = fv->field->Ident.token.string;
  9113. Selection sel = lookup_field(bt, name, false);
  9114. index = sel.index[0];
  9115. elem = fv->value;
  9116. TypeAndValue tav = type_and_value_of_expr(elem);
  9117. } else {
  9118. TypeAndValue tav = type_and_value_of_expr(elem);
  9119. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  9120. index = sel.index[0];
  9121. }
  9122. field = st->fields[index];
  9123. Type *ft = field->type;
  9124. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  9125. continue;
  9126. }
  9127. field_expr = lb_build_expr(p, elem);
  9128. Type *fet = field_expr.type;
  9129. GB_ASSERT(fet->kind != Type_Tuple);
  9130. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  9131. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  9132. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  9133. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9134. lb_emit_store_union_variant(p, gep, field_expr, fet);
  9135. } else {
  9136. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9137. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9138. lb_emit_store(p, gep, fv);
  9139. }
  9140. }
  9141. }
  9142. break;
  9143. }
  9144. case Type_Map: {
  9145. if (cl->elems.count == 0) {
  9146. break;
  9147. }
  9148. {
  9149. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9150. args[0] = lb_gen_map_header(p, v.addr, type);
  9151. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  9152. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  9153. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  9154. }
  9155. for_array(field_index, cl->elems) {
  9156. Ast *elem = cl->elems[field_index];
  9157. ast_node(fv, FieldValue, elem);
  9158. lbValue key = lb_build_expr(p, fv->field);
  9159. lbValue value = lb_build_expr(p, fv->value);
  9160. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  9161. }
  9162. break;
  9163. }
  9164. case Type_Array: {
  9165. if (cl->elems.count > 0) {
  9166. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9167. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9168. // NOTE(bill): Separate value, gep, store into their own chunks
  9169. for_array(i, cl->elems) {
  9170. Ast *elem = cl->elems[i];
  9171. if (elem->kind == Ast_FieldValue) {
  9172. ast_node(fv, FieldValue, elem);
  9173. if (lb_is_elem_const(fv->value, et)) {
  9174. continue;
  9175. }
  9176. if (is_ast_range(fv->field)) {
  9177. ast_node(ie, BinaryExpr, fv->field);
  9178. TypeAndValue lo_tav = ie->left->tav;
  9179. TypeAndValue hi_tav = ie->right->tav;
  9180. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9181. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9182. TokenKind op = ie->op.kind;
  9183. i64 lo = exact_value_to_i64(lo_tav.value);
  9184. i64 hi = exact_value_to_i64(hi_tav.value);
  9185. if (op == Token_Ellipsis) {
  9186. hi += 1;
  9187. }
  9188. lbValue value = lb_build_expr(p, fv->value);
  9189. for (i64 k = lo; k < hi; k++) {
  9190. lbCompoundLitElemTempData data = {};
  9191. data.value = value;
  9192. data.elem_index = cast(i32)k;
  9193. array_add(&temp_data, data);
  9194. }
  9195. } else {
  9196. auto tav = fv->field->tav;
  9197. GB_ASSERT(tav.mode == Addressing_Constant);
  9198. i64 index = exact_value_to_i64(tav.value);
  9199. lbValue value = lb_build_expr(p, fv->value);
  9200. lbCompoundLitElemTempData data = {};
  9201. data.value = lb_emit_conv(p, value, et);
  9202. data.expr = fv->value;
  9203. data.elem_index = cast(i32)index;
  9204. array_add(&temp_data, data);
  9205. }
  9206. } else {
  9207. if (lb_is_elem_const(elem, et)) {
  9208. continue;
  9209. }
  9210. lbCompoundLitElemTempData data = {};
  9211. data.expr = elem;
  9212. data.elem_index = cast(i32)i;
  9213. array_add(&temp_data, data);
  9214. }
  9215. }
  9216. for_array(i, temp_data) {
  9217. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  9218. }
  9219. for_array(i, temp_data) {
  9220. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9221. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9222. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9223. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9224. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9225. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9226. lbValue field_expr = temp_data[i].value;
  9227. Ast *expr = temp_data[i].expr;
  9228. p->return_ptr_hint_value = temp_data[i].gep;
  9229. p->return_ptr_hint_ast = unparen_expr(expr);
  9230. if (field_expr.value == nullptr) {
  9231. field_expr = lb_build_expr(p, expr);
  9232. }
  9233. Type *t = field_expr.type;
  9234. GB_ASSERT(t->kind != Type_Tuple);
  9235. lbValue ev = lb_emit_conv(p, field_expr, et);
  9236. if (!p->return_ptr_hint_used) {
  9237. temp_data[i].value = ev;
  9238. }
  9239. }
  9240. for_array(i, temp_data) {
  9241. if (temp_data[i].value.value != nullptr) {
  9242. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9243. }
  9244. }
  9245. }
  9246. break;
  9247. }
  9248. case Type_EnumeratedArray: {
  9249. if (cl->elems.count > 0) {
  9250. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9251. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9252. // NOTE(bill): Separate value, gep, store into their own chunks
  9253. for_array(i, cl->elems) {
  9254. Ast *elem = cl->elems[i];
  9255. if (elem->kind == Ast_FieldValue) {
  9256. ast_node(fv, FieldValue, elem);
  9257. if (lb_is_elem_const(fv->value, et)) {
  9258. continue;
  9259. }
  9260. if (is_ast_range(fv->field)) {
  9261. ast_node(ie, BinaryExpr, fv->field);
  9262. TypeAndValue lo_tav = ie->left->tav;
  9263. TypeAndValue hi_tav = ie->right->tav;
  9264. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9265. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9266. TokenKind op = ie->op.kind;
  9267. i64 lo = exact_value_to_i64(lo_tav.value);
  9268. i64 hi = exact_value_to_i64(hi_tav.value);
  9269. if (op == Token_Ellipsis) {
  9270. hi += 1;
  9271. }
  9272. lbValue value = lb_build_expr(p, fv->value);
  9273. for (i64 k = lo; k < hi; k++) {
  9274. lbCompoundLitElemTempData data = {};
  9275. data.value = value;
  9276. data.elem_index = cast(i32)k;
  9277. array_add(&temp_data, data);
  9278. }
  9279. } else {
  9280. auto tav = fv->field->tav;
  9281. GB_ASSERT(tav.mode == Addressing_Constant);
  9282. i64 index = exact_value_to_i64(tav.value);
  9283. lbValue value = lb_build_expr(p, fv->value);
  9284. lbCompoundLitElemTempData data = {};
  9285. data.value = lb_emit_conv(p, value, et);
  9286. data.expr = fv->value;
  9287. data.elem_index = cast(i32)index;
  9288. array_add(&temp_data, data);
  9289. }
  9290. } else {
  9291. if (lb_is_elem_const(elem, et)) {
  9292. continue;
  9293. }
  9294. lbCompoundLitElemTempData data = {};
  9295. data.expr = elem;
  9296. data.elem_index = cast(i32)i;
  9297. array_add(&temp_data, data);
  9298. }
  9299. }
  9300. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  9301. for_array(i, temp_data) {
  9302. i32 index = temp_data[i].elem_index - index_offset;
  9303. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  9304. }
  9305. for_array(i, temp_data) {
  9306. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9307. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9308. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9309. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9310. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9311. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9312. lbValue field_expr = temp_data[i].value;
  9313. Ast *expr = temp_data[i].expr;
  9314. p->return_ptr_hint_value = temp_data[i].gep;
  9315. p->return_ptr_hint_ast = unparen_expr(expr);
  9316. if (field_expr.value == nullptr) {
  9317. field_expr = lb_build_expr(p, expr);
  9318. }
  9319. Type *t = field_expr.type;
  9320. GB_ASSERT(t->kind != Type_Tuple);
  9321. lbValue ev = lb_emit_conv(p, field_expr, et);
  9322. if (!p->return_ptr_hint_used) {
  9323. temp_data[i].value = ev;
  9324. }
  9325. }
  9326. for_array(i, temp_data) {
  9327. if (temp_data[i].value.value != nullptr) {
  9328. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9329. }
  9330. }
  9331. }
  9332. break;
  9333. }
  9334. case Type_Slice: {
  9335. if (cl->elems.count > 0) {
  9336. Type *elem_type = bt->Slice.elem;
  9337. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  9338. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  9339. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  9340. lbValue data = lb_slice_elem(p, slice);
  9341. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9342. for_array(i, cl->elems) {
  9343. Ast *elem = cl->elems[i];
  9344. if (elem->kind == Ast_FieldValue) {
  9345. ast_node(fv, FieldValue, elem);
  9346. if (lb_is_elem_const(fv->value, et)) {
  9347. continue;
  9348. }
  9349. if (is_ast_range(fv->field)) {
  9350. ast_node(ie, BinaryExpr, fv->field);
  9351. TypeAndValue lo_tav = ie->left->tav;
  9352. TypeAndValue hi_tav = ie->right->tav;
  9353. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9354. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9355. TokenKind op = ie->op.kind;
  9356. i64 lo = exact_value_to_i64(lo_tav.value);
  9357. i64 hi = exact_value_to_i64(hi_tav.value);
  9358. if (op == Token_Ellipsis) {
  9359. hi += 1;
  9360. }
  9361. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9362. for (i64 k = lo; k < hi; k++) {
  9363. lbCompoundLitElemTempData data = {};
  9364. data.value = value;
  9365. data.elem_index = cast(i32)k;
  9366. array_add(&temp_data, data);
  9367. }
  9368. } else {
  9369. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9370. i64 index = exact_value_to_i64(fv->field->tav.value);
  9371. lbValue field_expr = lb_build_expr(p, fv->value);
  9372. GB_ASSERT(!is_type_tuple(field_expr.type));
  9373. lbValue ev = lb_emit_conv(p, field_expr, et);
  9374. lbCompoundLitElemTempData data = {};
  9375. data.value = ev;
  9376. data.elem_index = cast(i32)index;
  9377. array_add(&temp_data, data);
  9378. }
  9379. } else {
  9380. if (lb_is_elem_const(elem, et)) {
  9381. continue;
  9382. }
  9383. lbValue field_expr = lb_build_expr(p, elem);
  9384. GB_ASSERT(!is_type_tuple(field_expr.type));
  9385. lbValue ev = lb_emit_conv(p, field_expr, et);
  9386. lbCompoundLitElemTempData data = {};
  9387. data.value = ev;
  9388. data.elem_index = cast(i32)i;
  9389. array_add(&temp_data, data);
  9390. }
  9391. }
  9392. for_array(i, temp_data) {
  9393. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  9394. }
  9395. for_array(i, temp_data) {
  9396. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9397. }
  9398. {
  9399. lbValue count = {};
  9400. count.type = t_int;
  9401. if (lb_is_const(slice)) {
  9402. unsigned indices[1] = {1};
  9403. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  9404. } else {
  9405. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  9406. }
  9407. lb_fill_slice(p, v, data, count);
  9408. }
  9409. }
  9410. break;
  9411. }
  9412. case Type_DynamicArray: {
  9413. if (cl->elems.count == 0) {
  9414. break;
  9415. }
  9416. Type *et = bt->DynamicArray.elem;
  9417. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  9418. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  9419. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  9420. {
  9421. auto args = array_make<lbValue>(permanent_allocator(), 5);
  9422. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  9423. args[1] = size;
  9424. args[2] = align;
  9425. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  9426. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  9427. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  9428. }
  9429. lbValue items = lb_generate_local_array(p, et, item_count);
  9430. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  9431. for_array(i, cl->elems) {
  9432. Ast *elem = cl->elems[i];
  9433. if (elem->kind == Ast_FieldValue) {
  9434. ast_node(fv, FieldValue, elem);
  9435. if (is_ast_range(fv->field)) {
  9436. ast_node(ie, BinaryExpr, fv->field);
  9437. TypeAndValue lo_tav = ie->left->tav;
  9438. TypeAndValue hi_tav = ie->right->tav;
  9439. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9440. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9441. TokenKind op = ie->op.kind;
  9442. i64 lo = exact_value_to_i64(lo_tav.value);
  9443. i64 hi = exact_value_to_i64(hi_tav.value);
  9444. if (op == Token_Ellipsis) {
  9445. hi += 1;
  9446. }
  9447. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9448. for (i64 k = lo; k < hi; k++) {
  9449. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  9450. lb_emit_store(p, ep, value);
  9451. }
  9452. } else {
  9453. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9454. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  9455. lbValue ev = lb_build_expr(p, fv->value);
  9456. lbValue value = lb_emit_conv(p, ev, et);
  9457. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  9458. lb_emit_store(p, ep, value);
  9459. }
  9460. } else {
  9461. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  9462. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  9463. lb_emit_store(p, ep, value);
  9464. }
  9465. }
  9466. {
  9467. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9468. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  9469. args[1] = size;
  9470. args[2] = align;
  9471. args[3] = lb_emit_conv(p, items, t_rawptr);
  9472. args[4] = lb_const_int(p->module, t_int, item_count);
  9473. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  9474. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  9475. }
  9476. break;
  9477. }
  9478. case Type_Basic: {
  9479. GB_ASSERT(is_type_any(bt));
  9480. if (cl->elems.count > 0) {
  9481. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9482. String field_names[2] = {
  9483. str_lit("data"),
  9484. str_lit("id"),
  9485. };
  9486. Type *field_types[2] = {
  9487. t_rawptr,
  9488. t_typeid,
  9489. };
  9490. for_array(field_index, cl->elems) {
  9491. Ast *elem = cl->elems[field_index];
  9492. lbValue field_expr = {};
  9493. isize index = field_index;
  9494. if (elem->kind == Ast_FieldValue) {
  9495. ast_node(fv, FieldValue, elem);
  9496. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  9497. index = sel.index[0];
  9498. elem = fv->value;
  9499. } else {
  9500. TypeAndValue tav = type_and_value_of_expr(elem);
  9501. Selection sel = lookup_field(bt, field_names[field_index], false);
  9502. index = sel.index[0];
  9503. }
  9504. field_expr = lb_build_expr(p, elem);
  9505. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  9506. Type *ft = field_types[index];
  9507. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9508. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9509. lb_emit_store(p, gep, fv);
  9510. }
  9511. }
  9512. break;
  9513. }
  9514. case Type_BitSet: {
  9515. i64 sz = type_size_of(type);
  9516. if (cl->elems.count > 0 && sz > 0) {
  9517. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9518. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  9519. for_array(i, cl->elems) {
  9520. Ast *elem = cl->elems[i];
  9521. GB_ASSERT(elem->kind != Ast_FieldValue);
  9522. if (lb_is_elem_const(elem, et)) {
  9523. continue;
  9524. }
  9525. lbValue expr = lb_build_expr(p, elem);
  9526. GB_ASSERT(expr.type->kind != Type_Tuple);
  9527. Type *it = bit_set_to_int(bt);
  9528. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  9529. lbValue e = lb_emit_conv(p, expr, it);
  9530. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  9531. e = lb_emit_arith(p, Token_Shl, one, e, it);
  9532. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  9533. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  9534. new_value = lb_emit_transmute(p, new_value, type);
  9535. lb_addr_store(p, v, new_value);
  9536. }
  9537. }
  9538. break;
  9539. }
  9540. }
  9541. return v;
  9542. case_end;
  9543. case_ast_node(tc, TypeCast, expr);
  9544. Type *type = type_of_expr(expr);
  9545. lbValue x = lb_build_expr(p, tc->expr);
  9546. lbValue e = {};
  9547. switch (tc->token.kind) {
  9548. case Token_cast:
  9549. e = lb_emit_conv(p, x, type);
  9550. break;
  9551. case Token_transmute:
  9552. e = lb_emit_transmute(p, x, type);
  9553. break;
  9554. default:
  9555. GB_PANIC("Invalid AST TypeCast");
  9556. }
  9557. lbAddr v = lb_add_local_generated(p, type, false);
  9558. lb_addr_store(p, v, e);
  9559. return v;
  9560. case_end;
  9561. case_ast_node(ac, AutoCast, expr);
  9562. return lb_build_addr(p, ac->expr);
  9563. case_end;
  9564. }
  9565. TokenPos token_pos = ast_token(expr).pos;
  9566. GB_PANIC("Unexpected address expression\n"
  9567. "\tAst: %.*s @ "
  9568. "%.*s(%td:%td)\n",
  9569. LIT(ast_strings[expr->kind]),
  9570. LIT(token_pos.file), token_pos.line, token_pos.column);
  9571. return {};
  9572. }
  9573. void lb_init_module(lbModule *m, Checker *c) {
  9574. m->info = &c->info;
  9575. m->ctx = LLVMGetGlobalContext();
  9576. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  9577. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  9578. m->state_flags = 0;
  9579. m->state_flags |= StateFlag_bounds_check;
  9580. gb_mutex_init(&m->mutex);
  9581. gbAllocator a = heap_allocator();
  9582. map_init(&m->types, a);
  9583. map_init(&m->llvm_types, a);
  9584. map_init(&m->values, a);
  9585. string_map_init(&m->members, a);
  9586. map_init(&m->procedure_values, a);
  9587. string_map_init(&m->procedures, a);
  9588. string_map_init(&m->const_strings, a);
  9589. map_init(&m->anonymous_proc_lits, a);
  9590. map_init(&m->function_type_map, a);
  9591. map_init(&m->equal_procs, a);
  9592. map_init(&m->hasher_procs, a);
  9593. array_init(&m->procedures_to_generate, a);
  9594. array_init(&m->foreign_library_paths, a);
  9595. map_init(&m->debug_values, a);
  9596. }
  9597. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  9598. if (global_error_collector.count != 0) {
  9599. return false;
  9600. }
  9601. isize tc = c->parser->total_token_count;
  9602. if (tc < 2) {
  9603. return false;
  9604. }
  9605. String init_fullpath = c->parser->init_fullpath;
  9606. if (build_context.out_filepath.len == 0) {
  9607. gen->output_name = remove_directory_from_path(init_fullpath);
  9608. gen->output_name = remove_extension_from_path(gen->output_name);
  9609. gen->output_name = string_trim_whitespace(gen->output_name);
  9610. if (gen->output_name.len == 0) {
  9611. gen->output_name = c->info.init_scope->pkg->name;
  9612. }
  9613. gen->output_base = gen->output_name;
  9614. } else {
  9615. gen->output_name = build_context.out_filepath;
  9616. gen->output_name = string_trim_whitespace(gen->output_name);
  9617. if (gen->output_name.len == 0) {
  9618. gen->output_name = c->info.init_scope->pkg->name;
  9619. }
  9620. isize pos = string_extension_position(gen->output_name);
  9621. if (pos < 0) {
  9622. gen->output_base = gen->output_name;
  9623. } else {
  9624. gen->output_base = substring(gen->output_name, 0, pos);
  9625. }
  9626. }
  9627. gbAllocator ha = heap_allocator();
  9628. array_init(&gen->output_object_paths, ha);
  9629. gen->output_base = path_to_full_path(ha, gen->output_base);
  9630. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  9631. output_file_path = gb_string_appendc(output_file_path, ".obj");
  9632. defer (gb_string_free(output_file_path));
  9633. gen->info = &c->info;
  9634. lb_init_module(&gen->module, c);
  9635. return true;
  9636. }
  9637. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  9638. GB_ASSERT(type != nullptr);
  9639. type = default_type(type);
  9640. isize max_len = 7+8+1;
  9641. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  9642. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  9643. m->global_generated_index++;
  9644. String name = make_string(str, len-1);
  9645. Scope *scope = nullptr;
  9646. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  9647. lbValue g = {};
  9648. g.type = alloc_type_pointer(type);
  9649. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  9650. if (value.value != nullptr) {
  9651. GB_ASSERT(LLVMIsConstant(value.value));
  9652. LLVMSetInitializer(g.value, value.value);
  9653. } else {
  9654. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  9655. }
  9656. lb_add_entity(m, e, g);
  9657. lb_add_member(m, name, g);
  9658. return lb_addr(g);
  9659. }
  9660. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  9661. AstPackage *p = m->info->runtime_package;
  9662. Entity *e = scope_lookup_current(p->scope, name);
  9663. lbValue *found = map_get(&m->values, hash_entity(e));
  9664. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  9665. lbValue value = *found;
  9666. return value;
  9667. }
  9668. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  9669. i32 index = cast(i32)lb_type_info_index(m->info, type);
  9670. GB_ASSERT(index >= 0);
  9671. // gb_printf_err("%d %s\n", index, type_to_string(type));
  9672. LLVMValueRef indices[2] = {
  9673. LLVMConstInt(lb_type(m, t_int), 0, false),
  9674. LLVMConstInt(lb_type(m, t_int), index, false),
  9675. };
  9676. lbValue res = {};
  9677. res.type = t_type_info_ptr;
  9678. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  9679. return res;
  9680. }
  9681. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  9682. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  9683. lb_global_type_info_member_types_index += cast(i32)count;
  9684. return offset;
  9685. }
  9686. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  9687. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  9688. lb_global_type_info_member_names_index += cast(i32)count;
  9689. return offset;
  9690. }
  9691. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  9692. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  9693. lb_global_type_info_member_offsets_index += cast(i32)count;
  9694. return offset;
  9695. }
  9696. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  9697. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  9698. lb_global_type_info_member_usings_index += cast(i32)count;
  9699. return offset;
  9700. }
  9701. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  9702. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  9703. lb_global_type_info_member_tags_index += cast(i32)count;
  9704. return offset;
  9705. }
  9706. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  9707. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  9708. return lb_addr_get_ptr(p, addr);
  9709. }
  9710. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  9711. Token token = {Token_Ident};
  9712. isize name_len = prefix.len + 1 + 20;
  9713. auto suffix_id = cast(unsigned long long)id;
  9714. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  9715. gb_snprintf(text, name_len,
  9716. "%.*s-%llu", LIT(prefix), suffix_id);
  9717. text[name_len] = 0;
  9718. String s = make_string_c(text);
  9719. Type *t = alloc_type_array(elem_type, count);
  9720. lbValue g = {};
  9721. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  9722. g.type = alloc_type_pointer(t);
  9723. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  9724. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  9725. string_map_set(&m->members, s, g);
  9726. return g;
  9727. }
  9728. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  9729. lbModule *m = p->module;
  9730. LLVMContextRef ctx = m->ctx;
  9731. CheckerInfo *info = m->info;
  9732. {
  9733. // NOTE(bill): Set the type_table slice with the global backing array
  9734. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  9735. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  9736. GB_ASSERT(is_type_array(type));
  9737. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  9738. LLVMValueRef values[2] = {
  9739. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  9740. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  9741. };
  9742. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  9743. LLVMSetInitializer(global_type_table.value, slice);
  9744. }
  9745. // Useful types
  9746. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  9747. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  9748. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  9749. Type *t_type_info_flags = type_info_flags_entity->type;
  9750. i32 type_info_member_types_index = 0;
  9751. i32 type_info_member_names_index = 0;
  9752. i32 type_info_member_offsets_index = 0;
  9753. for_array(type_info_type_index, info->type_info_types) {
  9754. Type *t = info->type_info_types[type_info_type_index];
  9755. if (t == nullptr || t == t_invalid) {
  9756. continue;
  9757. }
  9758. isize entry_index = lb_type_info_index(info, t, false);
  9759. if (entry_index <= 0) {
  9760. continue;
  9761. }
  9762. lbValue tag = {};
  9763. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  9764. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  9765. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  9766. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  9767. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  9768. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  9769. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  9770. switch (t->kind) {
  9771. case Type_Named: {
  9772. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  9773. LLVMValueRef pkg_name = nullptr;
  9774. if (t->Named.type_name->pkg) {
  9775. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  9776. } else {
  9777. pkg_name = LLVMConstNull(lb_type(m, t_string));
  9778. }
  9779. String proc_name = {};
  9780. if (t->Named.type_name->parent_proc_decl) {
  9781. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  9782. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  9783. proc_name = decl->entity->token.string;
  9784. }
  9785. }
  9786. TokenPos pos = t->Named.type_name->token.pos;
  9787. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  9788. LLVMValueRef vals[4] = {
  9789. lb_const_string(p->module, t->Named.type_name->token.string).value,
  9790. lb_get_type_info_ptr(m, t->Named.base).value,
  9791. pkg_name,
  9792. loc.value
  9793. };
  9794. lbValue res = {};
  9795. res.type = type_deref(tag.type);
  9796. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9797. lb_emit_store(p, tag, res);
  9798. break;
  9799. }
  9800. case Type_Basic:
  9801. switch (t->Basic.kind) {
  9802. case Basic_bool:
  9803. case Basic_b8:
  9804. case Basic_b16:
  9805. case Basic_b32:
  9806. case Basic_b64:
  9807. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  9808. break;
  9809. case Basic_i8:
  9810. case Basic_u8:
  9811. case Basic_i16:
  9812. case Basic_u16:
  9813. case Basic_i32:
  9814. case Basic_u32:
  9815. case Basic_i64:
  9816. case Basic_u64:
  9817. case Basic_i128:
  9818. case Basic_u128:
  9819. case Basic_i16le:
  9820. case Basic_u16le:
  9821. case Basic_i32le:
  9822. case Basic_u32le:
  9823. case Basic_i64le:
  9824. case Basic_u64le:
  9825. case Basic_i128le:
  9826. case Basic_u128le:
  9827. case Basic_i16be:
  9828. case Basic_u16be:
  9829. case Basic_i32be:
  9830. case Basic_u32be:
  9831. case Basic_i64be:
  9832. case Basic_u64be:
  9833. case Basic_i128be:
  9834. case Basic_u128be:
  9835. case Basic_int:
  9836. case Basic_uint:
  9837. case Basic_uintptr: {
  9838. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  9839. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  9840. // NOTE(bill): This is matches the runtime layout
  9841. u8 endianness_value = 0;
  9842. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9843. endianness_value = 1;
  9844. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9845. endianness_value = 2;
  9846. }
  9847. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9848. LLVMValueRef vals[2] = {
  9849. is_signed.value,
  9850. endianness.value,
  9851. };
  9852. lbValue res = {};
  9853. res.type = type_deref(tag.type);
  9854. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9855. lb_emit_store(p, tag, res);
  9856. break;
  9857. }
  9858. case Basic_rune:
  9859. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  9860. break;
  9861. // case Basic_f16:
  9862. case Basic_f32:
  9863. case Basic_f64:
  9864. case Basic_f32le:
  9865. case Basic_f64le:
  9866. case Basic_f32be:
  9867. case Basic_f64be:
  9868. {
  9869. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  9870. // NOTE(bill): This is matches the runtime layout
  9871. u8 endianness_value = 0;
  9872. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9873. endianness_value = 1;
  9874. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9875. endianness_value = 2;
  9876. }
  9877. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9878. LLVMValueRef vals[1] = {
  9879. endianness.value,
  9880. };
  9881. lbValue res = {};
  9882. res.type = type_deref(tag.type);
  9883. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9884. lb_emit_store(p, tag, res);
  9885. }
  9886. break;
  9887. // case Basic_complex32:
  9888. case Basic_complex64:
  9889. case Basic_complex128:
  9890. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  9891. break;
  9892. case Basic_quaternion128:
  9893. case Basic_quaternion256:
  9894. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  9895. break;
  9896. case Basic_rawptr:
  9897. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9898. break;
  9899. case Basic_string:
  9900. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9901. break;
  9902. case Basic_cstring:
  9903. {
  9904. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9905. LLVMValueRef vals[1] = {
  9906. lb_const_bool(m, t_bool, true).value,
  9907. };
  9908. lbValue res = {};
  9909. res.type = type_deref(tag.type);
  9910. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9911. lb_emit_store(p, tag, res);
  9912. }
  9913. break;
  9914. case Basic_any:
  9915. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  9916. break;
  9917. case Basic_typeid:
  9918. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  9919. break;
  9920. }
  9921. break;
  9922. case Type_Pointer: {
  9923. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9924. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  9925. LLVMValueRef vals[1] = {
  9926. gep.value,
  9927. };
  9928. lbValue res = {};
  9929. res.type = type_deref(tag.type);
  9930. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9931. lb_emit_store(p, tag, res);
  9932. break;
  9933. }
  9934. case Type_Array: {
  9935. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  9936. i64 ez = type_size_of(t->Array.elem);
  9937. LLVMValueRef vals[3] = {
  9938. lb_get_type_info_ptr(m, t->Array.elem).value,
  9939. lb_const_int(m, t_int, ez).value,
  9940. lb_const_int(m, t_int, t->Array.count).value,
  9941. };
  9942. lbValue res = {};
  9943. res.type = type_deref(tag.type);
  9944. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9945. lb_emit_store(p, tag, res);
  9946. break;
  9947. }
  9948. case Type_EnumeratedArray: {
  9949. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  9950. LLVMValueRef vals[6] = {
  9951. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  9952. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  9953. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  9954. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  9955. // Unions
  9956. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9957. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9958. };
  9959. lbValue res = {};
  9960. res.type = type_deref(tag.type);
  9961. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9962. lb_emit_store(p, tag, res);
  9963. // NOTE(bill): Union assignment
  9964. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  9965. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  9966. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  9967. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  9968. lb_emit_store(p, min_value, min_v);
  9969. lb_emit_store(p, max_value, max_v);
  9970. break;
  9971. }
  9972. case Type_DynamicArray: {
  9973. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  9974. LLVMValueRef vals[2] = {
  9975. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  9976. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  9977. };
  9978. lbValue res = {};
  9979. res.type = type_deref(tag.type);
  9980. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9981. lb_emit_store(p, tag, res);
  9982. break;
  9983. }
  9984. case Type_Slice: {
  9985. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  9986. LLVMValueRef vals[2] = {
  9987. lb_get_type_info_ptr(m, t->Slice.elem).value,
  9988. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  9989. };
  9990. lbValue res = {};
  9991. res.type = type_deref(tag.type);
  9992. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9993. lb_emit_store(p, tag, res);
  9994. break;
  9995. }
  9996. case Type_Proc: {
  9997. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  9998. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9999. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10000. if (t->Proc.params != nullptr) {
  10001. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  10002. }
  10003. if (t->Proc.results != nullptr) {
  10004. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  10005. }
  10006. LLVMValueRef vals[4] = {
  10007. params,
  10008. results,
  10009. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  10010. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  10011. };
  10012. lbValue res = {};
  10013. res.type = type_deref(tag.type);
  10014. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10015. lb_emit_store(p, tag, res);
  10016. break;
  10017. }
  10018. case Type_Tuple: {
  10019. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  10020. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  10021. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  10022. for_array(i, t->Tuple.variables) {
  10023. // NOTE(bill): offset is not used for tuples
  10024. Entity *f = t->Tuple.variables[i];
  10025. lbValue index = lb_const_int(m, t_int, i);
  10026. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10027. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  10028. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10029. if (f->token.string.len > 0) {
  10030. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10031. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10032. }
  10033. }
  10034. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  10035. LLVMValueRef types_slice = llvm_const_slice(memory_types, count);
  10036. LLVMValueRef names_slice = llvm_const_slice(memory_names, count);
  10037. LLVMValueRef vals[2] = {
  10038. types_slice,
  10039. names_slice,
  10040. };
  10041. lbValue res = {};
  10042. res.type = type_deref(tag.type);
  10043. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10044. lb_emit_store(p, tag, res);
  10045. break;
  10046. }
  10047. case Type_Enum:
  10048. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  10049. {
  10050. GB_ASSERT(t->Enum.base_type != nullptr);
  10051. // GB_ASSERT_MSG(type_size_of(t_type_info_enum_value) == 16, "%lld == 16", cast(long long)type_size_of(t_type_info_enum_value));
  10052. LLVMValueRef vals[3] = {};
  10053. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  10054. if (t->Enum.fields.count > 0) {
  10055. auto fields = t->Enum.fields;
  10056. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  10057. str_lit("$enum_names"), cast(i64)entry_index);
  10058. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  10059. str_lit("$enum_values"), cast(i64)entry_index);
  10060. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10061. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10062. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10063. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  10064. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  10065. for_array(i, fields) {
  10066. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  10067. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  10068. }
  10069. LLVMValueRef name_init = LLVMConstArray(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  10070. LLVMValueRef value_init = LLVMConstArray(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  10071. LLVMSetInitializer(name_array.value, name_init);
  10072. LLVMSetInitializer(value_array.value, value_init);
  10073. lbValue v_count = lb_const_int(m, t_int, fields.count);
  10074. vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count);
  10075. vals[2] = llvm_const_slice(lb_array_elem(p, value_array), v_count);
  10076. } else {
  10077. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  10078. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  10079. }
  10080. lbValue res = {};
  10081. res.type = type_deref(tag.type);
  10082. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10083. lb_emit_store(p, tag, res);
  10084. }
  10085. break;
  10086. case Type_Union: {
  10087. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  10088. {
  10089. LLVMValueRef vals[6] = {};
  10090. isize variant_count = gb_max(0, t->Union.variants.count);
  10091. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  10092. // NOTE(bill): Zeroth is nil so ignore it
  10093. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10094. Type *vt = t->Union.variants[variant_index];
  10095. lbValue tip = lb_get_type_info_ptr(m, vt);
  10096. lbValue index = lb_const_int(m, t_int, variant_index);
  10097. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10098. lb_emit_store(p, type_info, lb_type_info(m, vt));
  10099. }
  10100. lbValue count = lb_const_int(m, t_int, variant_count);
  10101. vals[0] = llvm_const_slice(memory_types, count);
  10102. i64 tag_size = union_tag_size(t);
  10103. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10104. if (tag_size > 0) {
  10105. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  10106. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  10107. } else {
  10108. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  10109. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10110. }
  10111. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  10112. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  10113. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  10114. lbValue res = {};
  10115. res.type = type_deref(tag.type);
  10116. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10117. lb_emit_store(p, tag, res);
  10118. }
  10119. break;
  10120. }
  10121. case Type_Struct: {
  10122. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  10123. LLVMValueRef vals[12] = {};
  10124. {
  10125. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  10126. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  10127. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  10128. vals[5] = is_packed.value;
  10129. vals[6] = is_raw_union.value;
  10130. vals[7] = is_custom_align.value;
  10131. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  10132. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  10133. }
  10134. if (t->Struct.soa_kind != StructSoa_None) {
  10135. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  10136. Type *kind_type = type_deref(kind.type);
  10137. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  10138. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  10139. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  10140. vals[9] = soa_kind.value;
  10141. vals[10] = soa_type.value;
  10142. vals[11] = soa_len.value;
  10143. }
  10144. }
  10145. isize count = t->Struct.fields.count;
  10146. if (count > 0) {
  10147. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  10148. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  10149. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  10150. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  10151. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  10152. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10153. for (isize source_index = 0; source_index < count; source_index++) {
  10154. // TODO(bill): Order fields in source order not layout order
  10155. Entity *f = t->Struct.fields[source_index];
  10156. lbValue tip = lb_get_type_info_ptr(m, f->type);
  10157. i64 foffset = 0;
  10158. if (!t->Struct.is_raw_union) {
  10159. foffset = t->Struct.offsets[f->Variable.field_index];
  10160. }
  10161. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10162. lbValue index = lb_const_int(m, t_int, source_index);
  10163. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10164. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  10165. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  10166. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10167. if (f->token.string.len > 0) {
  10168. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10169. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10170. }
  10171. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  10172. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  10173. if (t->Struct.tags.count > 0) {
  10174. String tag_string = t->Struct.tags[source_index];
  10175. if (tag_string.len > 0) {
  10176. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  10177. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  10178. }
  10179. }
  10180. }
  10181. lbValue cv = lb_const_int(m, t_int, count);
  10182. vals[0] = llvm_const_slice(memory_types, cv);
  10183. vals[1] = llvm_const_slice(memory_names, cv);
  10184. vals[2] = llvm_const_slice(memory_offsets, cv);
  10185. vals[3] = llvm_const_slice(memory_usings, cv);
  10186. vals[4] = llvm_const_slice(memory_tags, cv);
  10187. }
  10188. for (isize i = 0; i < gb_count_of(vals); i++) {
  10189. if (vals[i] == nullptr) {
  10190. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  10191. }
  10192. }
  10193. lbValue res = {};
  10194. res.type = type_deref(tag.type);
  10195. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10196. lb_emit_store(p, tag, res);
  10197. break;
  10198. }
  10199. case Type_Map: {
  10200. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  10201. init_map_internal_types(t);
  10202. LLVMValueRef vals[5] = {
  10203. lb_get_type_info_ptr(m, t->Map.key).value,
  10204. lb_get_type_info_ptr(m, t->Map.value).value,
  10205. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  10206. lb_get_equal_proc_for_type(m, t->Map.key).value,
  10207. lb_get_hasher_proc_for_type(m, t->Map.key).value
  10208. };
  10209. lbValue res = {};
  10210. res.type = type_deref(tag.type);
  10211. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10212. lb_emit_store(p, tag, res);
  10213. break;
  10214. }
  10215. case Type_BitSet:
  10216. {
  10217. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  10218. GB_ASSERT(is_type_typed(t->BitSet.elem));
  10219. LLVMValueRef vals[4] = {
  10220. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  10221. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  10222. lb_const_int(m, t_i64, t->BitSet.lower).value,
  10223. lb_const_int(m, t_i64, t->BitSet.upper).value,
  10224. };
  10225. if (t->BitSet.underlying != nullptr) {
  10226. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  10227. }
  10228. lbValue res = {};
  10229. res.type = type_deref(tag.type);
  10230. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10231. lb_emit_store(p, tag, res);
  10232. }
  10233. break;
  10234. case Type_SimdVector:
  10235. {
  10236. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  10237. LLVMValueRef vals[4] = {};
  10238. if (t->SimdVector.is_x86_mmx) {
  10239. vals[3] = lb_const_bool(m, t_bool, true).value;
  10240. } else {
  10241. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  10242. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  10243. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  10244. }
  10245. lbValue res = {};
  10246. res.type = type_deref(tag.type);
  10247. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10248. lb_emit_store(p, tag, res);
  10249. }
  10250. break;
  10251. case Type_RelativePointer:
  10252. {
  10253. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  10254. LLVMValueRef vals[2] = {
  10255. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  10256. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  10257. };
  10258. lbValue res = {};
  10259. res.type = type_deref(tag.type);
  10260. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10261. lb_emit_store(p, tag, res);
  10262. }
  10263. break;
  10264. case Type_RelativeSlice:
  10265. {
  10266. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  10267. LLVMValueRef vals[2] = {
  10268. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  10269. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  10270. };
  10271. lbValue res = {};
  10272. res.type = type_deref(tag.type);
  10273. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10274. lb_emit_store(p, tag, res);
  10275. }
  10276. break;
  10277. }
  10278. if (tag.value != nullptr) {
  10279. Type *tag_type = type_deref(tag.type);
  10280. GB_ASSERT(is_type_named(tag_type));
  10281. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  10282. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  10283. } else {
  10284. if (t != t_llvm_bool) {
  10285. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  10286. }
  10287. }
  10288. }
  10289. }
  10290. void lb_generate_code(lbGenerator *gen) {
  10291. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  10292. TIME_SECTION("LLVM Initializtion");
  10293. lbModule *m = &gen->module;
  10294. LLVMModuleRef mod = gen->module.mod;
  10295. CheckerInfo *info = gen->info;
  10296. auto *min_dep_set = &info->minimum_dependency_set;
  10297. LLVMInitializeAllTargetInfos();
  10298. LLVMInitializeAllTargets();
  10299. LLVMInitializeAllTargetMCs();
  10300. LLVMInitializeAllAsmPrinters();
  10301. LLVMInitializeAllAsmParsers();
  10302. LLVMInitializeAllDisassemblers();
  10303. LLVMInitializeNativeTarget();
  10304. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  10305. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  10306. LLVMSetTarget(mod, target_triple);
  10307. LLVMTargetRef target = {};
  10308. char *llvm_error = nullptr;
  10309. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  10310. GB_ASSERT(target != nullptr);
  10311. TIME_SECTION("LLVM Create Target Machine");
  10312. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  10313. if (build_context.metrics.arch == TargetArch_wasm32) {
  10314. code_mode = LLVMCodeModelJITDefault;
  10315. }
  10316. char const *host_cpu_name = LLVMGetHostCPUName();
  10317. char const *llvm_cpu = "generic";
  10318. char const *llvm_features = "";
  10319. if (build_context.microarch.len != 0) {
  10320. if (build_context.microarch == "native") {
  10321. llvm_cpu = host_cpu_name;
  10322. } else {
  10323. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  10324. }
  10325. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  10326. llvm_features = LLVMGetHostCPUFeatures();
  10327. }
  10328. }
  10329. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  10330. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  10331. switch (build_context.optimization_level) {
  10332. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  10333. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  10334. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  10335. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  10336. }
  10337. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, llvm_cpu, llvm_features, code_gen_level, LLVMRelocDefault, code_mode);
  10338. defer (LLVMDisposeTargetMachine(target_machine));
  10339. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  10340. { // Debug Info
  10341. for_array(i, info->files.entries) {
  10342. AstFile *f = info->files.entries[i].value;
  10343. String fullpath = f->fullpath;
  10344. String filename = filename_from_path(fullpath);
  10345. String directory = directory_from_path(fullpath);
  10346. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  10347. cast(char const *)filename.text, filename.len,
  10348. cast(char const *)directory.text, directory.len);
  10349. map_set(&m->debug_values, hash_pointer(f), res);
  10350. f->llvm_metadata = res;
  10351. }
  10352. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  10353. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  10354. "odin", 4,
  10355. false, "", 0,
  10356. 1, "", 0,
  10357. LLVMDWARFEmissionFull, 0, true,
  10358. true
  10359. #if LLVM_VERSION_MAJOR > 10
  10360. , "", 0,
  10361. "", 0
  10362. #endif
  10363. );
  10364. }
  10365. TIME_SECTION("LLVM Global Variables");
  10366. {
  10367. { // Add type info data
  10368. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  10369. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  10370. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  10371. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  10372. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10373. LLVMSetLinkage(g, LLVMInternalLinkage);
  10374. lbValue value = {};
  10375. value.value = g;
  10376. value.type = alloc_type_pointer(t);
  10377. lb_global_type_info_data = lb_addr(value);
  10378. }
  10379. { // Type info member buffer
  10380. // NOTE(bill): Removes need for heap allocation by making it global memory
  10381. isize count = 0;
  10382. for_array(entry_index, m->info->type_info_types) {
  10383. Type *t = m->info->type_info_types[entry_index];
  10384. isize index = lb_type_info_index(m->info, t, false);
  10385. if (index < 0) {
  10386. continue;
  10387. }
  10388. switch (t->kind) {
  10389. case Type_Union:
  10390. count += t->Union.variants.count;
  10391. break;
  10392. case Type_Struct:
  10393. count += t->Struct.fields.count;
  10394. break;
  10395. case Type_Tuple:
  10396. count += t->Tuple.variables.count;
  10397. break;
  10398. }
  10399. }
  10400. if (count > 0) {
  10401. {
  10402. char const *name = LB_TYPE_INFO_TYPES_NAME;
  10403. Type *t = alloc_type_array(t_type_info_ptr, count);
  10404. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10405. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10406. LLVMSetLinkage(g, LLVMInternalLinkage);
  10407. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  10408. }
  10409. {
  10410. char const *name = LB_TYPE_INFO_NAMES_NAME;
  10411. Type *t = alloc_type_array(t_string, count);
  10412. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10413. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10414. LLVMSetLinkage(g, LLVMInternalLinkage);
  10415. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  10416. }
  10417. {
  10418. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  10419. Type *t = alloc_type_array(t_uintptr, count);
  10420. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10421. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10422. LLVMSetLinkage(g, LLVMInternalLinkage);
  10423. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  10424. }
  10425. {
  10426. char const *name = LB_TYPE_INFO_USINGS_NAME;
  10427. Type *t = alloc_type_array(t_bool, count);
  10428. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10429. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10430. LLVMSetLinkage(g, LLVMInternalLinkage);
  10431. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  10432. }
  10433. {
  10434. char const *name = LB_TYPE_INFO_TAGS_NAME;
  10435. Type *t = alloc_type_array(t_string, count);
  10436. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10437. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10438. LLVMSetLinkage(g, LLVMInternalLinkage);
  10439. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  10440. }
  10441. }
  10442. }
  10443. }
  10444. isize global_variable_max_count = 0;
  10445. Entity *entry_point = info->entry_point;
  10446. bool has_dll_main = false;
  10447. bool has_win_main = false;
  10448. for_array(i, info->entities) {
  10449. Entity *e = info->entities[i];
  10450. String name = e->token.string;
  10451. bool is_global = e->pkg != nullptr;
  10452. if (e->kind == Entity_Variable) {
  10453. global_variable_max_count++;
  10454. } else if (e->kind == Entity_Procedure && !is_global) {
  10455. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  10456. GB_ASSERT(e == entry_point);
  10457. // entry_point = e;
  10458. }
  10459. if (e->Procedure.is_export ||
  10460. (e->Procedure.link_name.len > 0) ||
  10461. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  10462. if (!has_dll_main && name == "DllMain") {
  10463. has_dll_main = true;
  10464. } else if (!has_win_main && name == "WinMain") {
  10465. has_win_main = true;
  10466. }
  10467. }
  10468. }
  10469. }
  10470. struct GlobalVariable {
  10471. lbValue var;
  10472. lbValue init;
  10473. DeclInfo *decl;
  10474. bool is_initialized;
  10475. };
  10476. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  10477. for_array(i, info->variable_init_order) {
  10478. DeclInfo *d = info->variable_init_order[i];
  10479. Entity *e = d->entity;
  10480. if ((e->scope->flags & ScopeFlag_File) == 0) {
  10481. continue;
  10482. }
  10483. if (!ptr_set_exists(min_dep_set, e)) {
  10484. continue;
  10485. }
  10486. DeclInfo *decl = decl_info_of_entity(e);
  10487. if (decl == nullptr) {
  10488. continue;
  10489. }
  10490. GB_ASSERT(e->kind == Entity_Variable);
  10491. bool is_foreign = e->Variable.is_foreign;
  10492. bool is_export = e->Variable.is_export;
  10493. String name = lb_get_entity_name(m, e);
  10494. lbValue g = {};
  10495. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  10496. g.type = alloc_type_pointer(e->type);
  10497. if (e->Variable.thread_local_model != "") {
  10498. LLVMSetThreadLocal(g.value, true);
  10499. String m = e->Variable.thread_local_model;
  10500. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  10501. if (m == "default") {
  10502. mode = LLVMGeneralDynamicTLSModel;
  10503. } else if (m == "localdynamic") {
  10504. mode = LLVMLocalDynamicTLSModel;
  10505. } else if (m == "initialexec") {
  10506. mode = LLVMInitialExecTLSModel;
  10507. } else if (m == "localexec") {
  10508. mode = LLVMLocalExecTLSModel;
  10509. } else {
  10510. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  10511. }
  10512. LLVMSetThreadLocalMode(g.value, mode);
  10513. }
  10514. if (is_foreign) {
  10515. LLVMSetExternallyInitialized(g.value, true);
  10516. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  10517. } else {
  10518. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  10519. }
  10520. if (is_export) {
  10521. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  10522. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  10523. }
  10524. if (e->flags & EntityFlag_Static) {
  10525. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  10526. }
  10527. GlobalVariable var = {};
  10528. var.var = g;
  10529. var.decl = decl;
  10530. if (decl->init_expr != nullptr) {
  10531. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  10532. if (!is_type_any(e->type)) {
  10533. if (tav.mode != Addressing_Invalid) {
  10534. if (tav.value.kind != ExactValue_Invalid) {
  10535. ExactValue v = tav.value;
  10536. lbValue init = lb_const_value(m, tav.type, v);
  10537. LLVMSetInitializer(g.value, init.value);
  10538. var.is_initialized = true;
  10539. }
  10540. }
  10541. }
  10542. if (!var.is_initialized &&
  10543. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  10544. var.is_initialized = true;
  10545. }
  10546. }
  10547. array_add(&global_variables, var);
  10548. lb_add_entity(m, e, g);
  10549. lb_add_member(m, name, g);
  10550. }
  10551. TIME_SECTION("LLVM Global Procedures and Types");
  10552. for_array(i, info->entities) {
  10553. Entity *e = info->entities[i];
  10554. String name = e->token.string;
  10555. DeclInfo *decl = e->decl_info;
  10556. Scope * scope = e->scope;
  10557. if ((scope->flags & ScopeFlag_File) == 0) {
  10558. continue;
  10559. }
  10560. Scope *package_scope = scope->parent;
  10561. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  10562. switch (e->kind) {
  10563. case Entity_Variable:
  10564. // NOTE(bill): Handled above as it requires a specific load order
  10565. continue;
  10566. case Entity_ProcGroup:
  10567. continue;
  10568. case Entity_TypeName:
  10569. case Entity_Procedure:
  10570. break;
  10571. }
  10572. bool polymorphic_struct = false;
  10573. if (e->type != nullptr && e->kind == Entity_TypeName) {
  10574. Type *bt = base_type(e->type);
  10575. if (bt->kind == Type_Struct) {
  10576. polymorphic_struct = is_type_polymorphic(bt);
  10577. }
  10578. }
  10579. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  10580. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  10581. continue;
  10582. }
  10583. String mangled_name = lb_get_entity_name(m, e);
  10584. switch (e->kind) {
  10585. case Entity_TypeName:
  10586. lb_type(m, e->type);
  10587. break;
  10588. case Entity_Procedure:
  10589. {
  10590. lbProcedure *p = lb_create_procedure(m, e);
  10591. array_add(&m->procedures_to_generate, p);
  10592. }
  10593. break;
  10594. }
  10595. }
  10596. TIME_SECTION("LLVM Registry Initializtion");
  10597. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  10598. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  10599. defer (LLVMDisposePassManager(default_function_pass_manager));
  10600. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  10601. {
  10602. auto dfpm = default_function_pass_manager;
  10603. if (build_context.optimization_level == 0) {
  10604. LLVMAddMemCpyOptPass(dfpm);
  10605. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10606. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10607. LLVMAddAggressiveInstCombinerPass(dfpm);
  10608. LLVMAddEarlyCSEPass(dfpm);
  10609. LLVMAddEarlyCSEMemSSAPass(dfpm);
  10610. LLVMAddConstantPropagationPass(dfpm);
  10611. LLVMAddAggressiveDCEPass(dfpm);
  10612. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10613. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10614. LLVMAddCFGSimplificationPass(dfpm);
  10615. // LLVMAddInstructionCombiningPass(dfpm);
  10616. LLVMAddSLPVectorizePass(dfpm);
  10617. LLVMAddLoopVectorizePass(dfpm);
  10618. LLVMAddScalarizerPass(dfpm);
  10619. LLVMAddLoopIdiomPass(dfpm);
  10620. } else {
  10621. bool do_extra_passes = true;
  10622. int repeat_count = cast(int)build_context.optimization_level;
  10623. do {
  10624. LLVMAddMemCpyOptPass(dfpm);
  10625. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10626. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10627. LLVMAddAlignmentFromAssumptionsPass(dfpm);
  10628. LLVMAddEarlyCSEPass(dfpm);
  10629. LLVMAddEarlyCSEMemSSAPass(dfpm);
  10630. LLVMAddConstantPropagationPass(dfpm);
  10631. if (do_extra_passes) {
  10632. LLVMAddAggressiveInstCombinerPass(dfpm);
  10633. LLVMAddAggressiveDCEPass(dfpm);
  10634. }
  10635. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10636. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10637. LLVMAddCFGSimplificationPass(dfpm);
  10638. LLVMAddTailCallEliminationPass(dfpm);
  10639. if (do_extra_passes) {
  10640. LLVMAddSLPVectorizePass(dfpm);
  10641. LLVMAddLoopVectorizePass(dfpm);
  10642. LLVMAddConstantPropagationPass(dfpm);
  10643. LLVMAddScalarizerPass(dfpm);
  10644. LLVMAddLoopIdiomPass(dfpm);
  10645. LLVMAddAggressiveInstCombinerPass(dfpm);
  10646. LLVMAddLowerExpectIntrinsicPass(dfpm);
  10647. LLVMAddDeadStoreEliminationPass(dfpm);
  10648. LLVMAddReassociatePass(dfpm);
  10649. LLVMAddAddDiscriminatorsPass(dfpm);
  10650. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10651. LLVMAddCorrelatedValuePropagationPass(dfpm);
  10652. }
  10653. } while (repeat_count --> 0);
  10654. }
  10655. }
  10656. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  10657. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  10658. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  10659. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  10660. {
  10661. auto dfpm = default_function_pass_manager_without_memcpy;
  10662. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10663. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10664. LLVMAddAggressiveInstCombinerPass(dfpm);
  10665. LLVMAddConstantPropagationPass(dfpm);
  10666. LLVMAddAggressiveDCEPass(dfpm);
  10667. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10668. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10669. LLVMAddCFGSimplificationPass(dfpm);
  10670. // LLVMAddUnifyFunctionExitNodesPass(dfpm);
  10671. }
  10672. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  10673. TIME_SECTION("LLVM Runtime Type Information Creation");
  10674. lbProcedure *startup_type_info = nullptr;
  10675. lbProcedure *startup_runtime = nullptr;
  10676. { // Startup Type Info
  10677. Type *params = alloc_type_tuple();
  10678. Type *results = alloc_type_tuple();
  10679. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10680. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  10681. p->is_startup = true;
  10682. startup_type_info = p;
  10683. lb_begin_procedure_body(p);
  10684. lb_setup_type_info_data(p);
  10685. lb_end_procedure_body(p);
  10686. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10687. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10688. LLVMDumpValue(p->value);
  10689. gb_printf_err("\n\n\n\n");
  10690. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10691. }
  10692. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10693. }
  10694. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  10695. { // Startup Runtime
  10696. Type *params = alloc_type_tuple();
  10697. Type *results = alloc_type_tuple();
  10698. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10699. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  10700. p->is_startup = true;
  10701. startup_runtime = p;
  10702. lb_begin_procedure_body(p);
  10703. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  10704. for_array(i, global_variables) {
  10705. auto *var = &global_variables[i];
  10706. if (var->is_initialized) {
  10707. continue;
  10708. }
  10709. Entity *e = var->decl->entity;
  10710. GB_ASSERT(e->kind == Entity_Variable);
  10711. if (var->decl->init_expr != nullptr) {
  10712. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  10713. lbValue init = lb_build_expr(p, var->decl->init_expr);
  10714. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  10715. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  10716. if (lb_is_const_or_global(init)) {
  10717. if (!var->is_initialized) {
  10718. LLVMSetInitializer(var->var.value, init.value);
  10719. var->is_initialized = true;
  10720. continue;
  10721. }
  10722. } else {
  10723. var->init = init;
  10724. }
  10725. }
  10726. if (var->init.value != nullptr) {
  10727. GB_ASSERT(!var->is_initialized);
  10728. Type *t = type_deref(var->var.type);
  10729. if (is_type_any(t)) {
  10730. // NOTE(bill): Edge case for 'any' type
  10731. Type *var_type = default_type(var->init.type);
  10732. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  10733. lb_addr_store(p, g, var->init);
  10734. lbValue gp = lb_addr_get_ptr(p, g);
  10735. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  10736. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  10737. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  10738. lb_emit_store(p, ti, lb_type_info(m, var_type));
  10739. } else {
  10740. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  10741. LLVMTypeRef vt = LLVMGetElementType(pvt);
  10742. lbValue src0 = lb_emit_conv(p, var->init, t);
  10743. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  10744. LLVMValueRef dst = var->var.value;
  10745. LLVMBuildStore(p->builder, src, dst);
  10746. }
  10747. var->is_initialized = true;
  10748. }
  10749. }
  10750. lb_end_procedure_body(p);
  10751. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10752. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10753. LLVMDumpValue(p->value);
  10754. gb_printf_err("\n\n\n\n");
  10755. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10756. }
  10757. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10758. /*{
  10759. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  10760. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  10761. instr != last_instr;
  10762. instr = LLVMGetNextInstruction(instr)) {
  10763. if (LLVMIsAAllocaInst(instr)) {
  10764. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  10765. LLVMValueRef sz_val = LLVMSizeOf(type);
  10766. GB_ASSERT(LLVMIsConstant(sz_val));
  10767. gb_printf_err(">> 0x%p\n", sz_val);
  10768. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  10769. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  10770. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  10771. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  10772. gb_printf_err(">> %ll\n", sz);
  10773. }
  10774. }
  10775. }*/
  10776. }
  10777. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  10778. TIME_SECTION("LLVM DLL main");
  10779. Type *params = alloc_type_tuple();
  10780. Type *results = alloc_type_tuple();
  10781. String name = str_lit("main");
  10782. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  10783. name = str_lit("mainCRTStartup");
  10784. } else {
  10785. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  10786. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  10787. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  10788. }
  10789. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  10790. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  10791. Type *proc_type = alloc_type_proc(nullptr,
  10792. params, params->Tuple.variables.count,
  10793. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  10794. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  10795. p->is_startup = true;
  10796. lb_begin_procedure_body(p);
  10797. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  10798. if (build_context.command_kind == Command_test) {
  10799. for_array(i, m->info->testing_procedures) {
  10800. Entity *e = m->info->testing_procedures[i];
  10801. lbValue *found = map_get(&m->values, hash_entity(e));
  10802. GB_ASSERT(found != nullptr);
  10803. lb_emit_call(p, *found, {});
  10804. }
  10805. } else {
  10806. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  10807. GB_ASSERT(found != nullptr);
  10808. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  10809. }
  10810. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  10811. lb_end_procedure_body(p);
  10812. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10813. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10814. LLVMDumpValue(p->value);
  10815. gb_printf_err("\n\n\n\n");
  10816. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10817. }
  10818. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10819. }
  10820. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  10821. TIME_SECTION("LLVM Procedure Generation");
  10822. for_array(i, m->procedures_to_generate) {
  10823. lbProcedure *p = m->procedures_to_generate[i];
  10824. if (p->is_done) {
  10825. continue;
  10826. }
  10827. if (p->body != nullptr) { // Build Procedure
  10828. m->curr_procedure = p;
  10829. lb_begin_procedure_body(p);
  10830. lb_build_stmt(p, p->body);
  10831. lb_end_procedure_body(p);
  10832. p->is_done = true;
  10833. m->curr_procedure = nullptr;
  10834. }
  10835. lb_end_procedure(p);
  10836. // Add Flags
  10837. if (p->body != nullptr) {
  10838. if (p->name == "memcpy" || p->name == "memmove" ||
  10839. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  10840. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  10841. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  10842. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  10843. }
  10844. }
  10845. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10846. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  10847. LLVMDumpValue(p->value);
  10848. gb_printf_err("\n\n\n\n");
  10849. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  10850. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10851. }
  10852. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  10853. gb_exit(1);
  10854. }
  10855. }
  10856. TIME_SECTION("LLVM Function Pass");
  10857. {
  10858. for_array(i, m->procedures_to_generate) {
  10859. lbProcedure *p = m->procedures_to_generate[i];
  10860. if (p->body != nullptr) { // Build Procedure
  10861. for (i32 i = 0; i <= build_context.optimization_level; i++) {
  10862. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  10863. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  10864. } else {
  10865. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10866. }
  10867. }
  10868. }
  10869. }
  10870. for_array(i, m->equal_procs.entries) {
  10871. lbProcedure *p = m->equal_procs.entries[i].value;
  10872. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10873. }
  10874. for_array(i, m->hasher_procs.entries) {
  10875. lbProcedure *p = m->hasher_procs.entries[i].value;
  10876. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10877. }
  10878. }
  10879. TIME_SECTION("LLVM Module Pass");
  10880. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  10881. defer (LLVMDisposePassManager(module_pass_manager));
  10882. LLVMAddAlwaysInlinerPass(module_pass_manager);
  10883. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  10884. LLVMAddAnalysisPasses(target_machine, module_pass_manager);
  10885. if (build_context.optimization_level >= 2) {
  10886. LLVMAddArgumentPromotionPass(module_pass_manager);
  10887. LLVMAddConstantMergePass(module_pass_manager);
  10888. LLVMAddGlobalDCEPass(module_pass_manager);
  10889. LLVMAddDeadArgEliminationPass(module_pass_manager);
  10890. }
  10891. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  10892. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  10893. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level);
  10894. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level);
  10895. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  10896. LLVMRunPassManager(module_pass_manager, mod);
  10897. llvm_error = nullptr;
  10898. defer (LLVMDisposeMessage(llvm_error));
  10899. String filepath_obj = {};
  10900. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  10901. if (build_context.build_mode == BuildMode_Assembly) {
  10902. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  10903. code_gen_file_type = LLVMAssemblyFile;
  10904. } else {
  10905. switch (build_context.metrics.os) {
  10906. case TargetOs_windows:
  10907. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  10908. break;
  10909. case TargetOs_darwin:
  10910. case TargetOs_linux:
  10911. case TargetOs_essence:
  10912. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  10913. break;
  10914. case TargetOs_js:
  10915. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  10916. break;
  10917. }
  10918. }
  10919. LLVMDIBuilderFinalize(m->debug_builder);
  10920. if (LLVMVerifyModule(mod, LLVMReturnStatusAction, &llvm_error)) {
  10921. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  10922. if (build_context.keep_temp_files) {
  10923. TIME_SECTION("LLVM Print Module to File");
  10924. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  10925. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10926. gb_exit(1);
  10927. return;
  10928. }
  10929. }
  10930. gb_exit(1);
  10931. return;
  10932. }
  10933. llvm_error = nullptr;
  10934. if (build_context.keep_temp_files) {
  10935. TIME_SECTION("LLVM Print Module to File");
  10936. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  10937. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10938. gb_exit(1);
  10939. return;
  10940. }
  10941. }
  10942. TIME_SECTION("LLVM Object Generation");
  10943. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  10944. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10945. gb_exit(1);
  10946. return;
  10947. }
  10948. array_add(&gen->output_object_paths, filepath_obj);
  10949. for_array(i, m->info->required_foreign_imports_through_force) {
  10950. Entity *e = m->info->required_foreign_imports_through_force[i];
  10951. lb_add_foreign_library_path(m, e);
  10952. }
  10953. #undef TIME_SECTION
  10954. }