llvm_backend.cpp 463 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757
  1. #include "llvm_backend.hpp"
  2. #include "llvm_abi.cpp"
  3. #include "llvm_backend_opt.cpp"
  4. gb_global lbAddr lb_global_type_info_data = {};
  5. gb_global lbAddr lb_global_type_info_member_types = {};
  6. gb_global lbAddr lb_global_type_info_member_names = {};
  7. gb_global lbAddr lb_global_type_info_member_offsets = {};
  8. gb_global lbAddr lb_global_type_info_member_usings = {};
  9. gb_global lbAddr lb_global_type_info_member_tags = {};
  10. gb_global isize lb_global_type_info_data_index = 0;
  11. gb_global isize lb_global_type_info_member_types_index = 0;
  12. gb_global isize lb_global_type_info_member_names_index = 0;
  13. gb_global isize lb_global_type_info_member_offsets_index = 0;
  14. gb_global isize lb_global_type_info_member_usings_index = 0;
  15. gb_global isize lb_global_type_info_member_tags_index = 0;
  16. struct lbLoopData {
  17. lbAddr idx_addr;
  18. lbValue idx;
  19. lbBlock *body;
  20. lbBlock *done;
  21. lbBlock *loop;
  22. };
  23. struct lbCompoundLitElemTempData {
  24. Ast * expr;
  25. lbValue value;
  26. i32 elem_index;
  27. lbValue gep;
  28. };
  29. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  30. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  31. LLVMValueRef llvm_zero(lbModule *m) {
  32. return LLVMConstInt(lb_type(m, t_int), 0, false);
  33. }
  34. LLVMValueRef llvm_one(lbModule *m) {
  35. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  36. }
  37. lbValue lb_zero(lbModule *m, Type *t) {
  38. lbValue v = {};
  39. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  40. v.type = t;
  41. return v;
  42. }
  43. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  44. lbValue v = lb_find_or_add_entity_string(m, str);
  45. unsigned indices[1] = {0};
  46. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  47. }
  48. bool lb_is_instr_terminating(LLVMValueRef instr) {
  49. if (instr != nullptr) {
  50. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  51. switch (op) {
  52. case LLVMRet:
  53. case LLVMBr:
  54. case LLVMSwitch:
  55. case LLVMIndirectBr:
  56. case LLVMInvoke:
  57. case LLVMUnreachable:
  58. case LLVMCallBr:
  59. return true;
  60. }
  61. }
  62. return false;
  63. }
  64. lbAddr lb_addr(lbValue addr) {
  65. lbAddr v = {lbAddr_Default, addr};
  66. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  67. GB_ASSERT(is_type_pointer(addr.type));
  68. v.kind = lbAddr_RelativePointer;
  69. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  70. GB_ASSERT(is_type_pointer(addr.type));
  71. v.kind = lbAddr_RelativeSlice;
  72. }
  73. return v;
  74. }
  75. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  76. lbAddr v = {lbAddr_Map, addr};
  77. v.map.key = map_key;
  78. v.map.type = map_type;
  79. v.map.result = map_result;
  80. return v;
  81. }
  82. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  83. lbAddr v = {lbAddr_SoaVariable, addr};
  84. v.soa.index = index;
  85. v.soa.index_expr = index_expr;
  86. return v;
  87. }
  88. Type *lb_addr_type(lbAddr const &addr) {
  89. if (addr.addr.value == nullptr) {
  90. return nullptr;
  91. }
  92. if (addr.kind == lbAddr_Map) {
  93. Type *t = base_type(addr.map.type);
  94. GB_ASSERT(is_type_map(t));
  95. return t->Map.value;
  96. }
  97. return type_deref(addr.addr.type);
  98. }
  99. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  100. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  101. }
  102. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  103. if (addr.addr.value == nullptr) {
  104. GB_PANIC("Illegal addr -> nullptr");
  105. return {};
  106. }
  107. switch (addr.kind) {
  108. case lbAddr_Map: {
  109. Type *map_type = base_type(addr.map.type);
  110. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  111. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  112. auto args = array_make<lbValue>(permanent_allocator(), 2);
  113. args[0] = h;
  114. args[1] = key;
  115. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  116. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  117. }
  118. case lbAddr_RelativePointer: {
  119. Type *rel_ptr = base_type(lb_addr_type(addr));
  120. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  121. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  122. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  123. offset = lb_emit_load(p, offset);
  124. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  125. offset = lb_emit_conv(p, offset, t_i64);
  126. }
  127. offset = lb_emit_conv(p, offset, t_uintptr);
  128. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  129. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  130. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  131. // NOTE(bill): nil check
  132. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  133. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  134. return final_ptr;
  135. }
  136. case lbAddr_SoaVariable: {
  137. // TODO(bill): FIX THIS HACK
  138. return lb_address_from_load(p, lb_addr_load(p, addr));
  139. }
  140. case lbAddr_Context:
  141. GB_PANIC("lbAddr_Context should be handled elsewhere");
  142. }
  143. return addr.addr;
  144. }
  145. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  146. lbAddr addr = lb_build_addr(p, expr);
  147. return lb_addr_get_ptr(p, addr);
  148. }
  149. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  150. if (build_context.no_bounds_check) {
  151. return;
  152. }
  153. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  154. return;
  155. }
  156. index = lb_emit_conv(p, index, t_int);
  157. len = lb_emit_conv(p, len, t_int);
  158. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  159. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  160. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  161. auto args = array_make<lbValue>(permanent_allocator(), 5);
  162. args[0] = file;
  163. args[1] = line;
  164. args[2] = column;
  165. args[3] = index;
  166. args[4] = len;
  167. lb_emit_runtime_call(p, "bounds_check_error", args);
  168. }
  169. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  170. if (build_context.no_bounds_check) {
  171. return;
  172. }
  173. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  174. return;
  175. }
  176. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  177. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  178. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  179. high = lb_emit_conv(p, high, t_int);
  180. if (!lower_value_used) {
  181. auto args = array_make<lbValue>(permanent_allocator(), 5);
  182. args[0] = file;
  183. args[1] = line;
  184. args[2] = column;
  185. args[3] = high;
  186. args[4] = len;
  187. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  188. } else {
  189. // No need to convert unless used
  190. low = lb_emit_conv(p, low, t_int);
  191. auto args = array_make<lbValue>(permanent_allocator(), 6);
  192. args[0] = file;
  193. args[1] = line;
  194. args[2] = column;
  195. args[3] = low;
  196. args[4] = high;
  197. args[5] = len;
  198. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  199. }
  200. }
  201. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  202. if (addr.addr.value == nullptr) {
  203. return;
  204. }
  205. GB_ASSERT(value.type != nullptr);
  206. if (is_type_untyped_undef(value.type)) {
  207. Type *t = lb_addr_type(addr);
  208. value.type = t;
  209. value.value = LLVMGetUndef(lb_type(p->module, t));
  210. } else if (is_type_untyped_nil(value.type)) {
  211. Type *t = lb_addr_type(addr);
  212. value.type = t;
  213. value.value = LLVMConstNull(lb_type(p->module, t));
  214. }
  215. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  216. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  217. }
  218. if (addr.kind == lbAddr_RelativePointer) {
  219. Type *rel_ptr = base_type(lb_addr_type(addr));
  220. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  221. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  222. GB_ASSERT(is_type_pointer(addr.addr.type));
  223. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  224. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  225. lbValue offset = {};
  226. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  227. offset.type = t_uintptr;
  228. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  229. offset = lb_emit_conv(p, offset, t_i64);
  230. }
  231. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  232. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  233. offset = lb_emit_select(p,
  234. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  235. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  236. offset
  237. );
  238. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  239. return;
  240. } else if (addr.kind == lbAddr_RelativeSlice) {
  241. Type *rel_ptr = base_type(lb_addr_type(addr));
  242. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  243. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  244. GB_ASSERT(is_type_pointer(addr.addr.type));
  245. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  246. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  247. lbValue offset = {};
  248. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  249. offset.type = t_uintptr;
  250. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  251. offset = lb_emit_conv(p, offset, t_i64);
  252. }
  253. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  254. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  255. offset = lb_emit_select(p,
  256. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  257. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  258. offset
  259. );
  260. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  261. lbValue len = lb_slice_len(p, value);
  262. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  263. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  264. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  265. return;
  266. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  267. lbValue ptr = addr.addr;
  268. lbValue index = addr.index_set.index;
  269. Ast *node = addr.index_set.node;
  270. ast_node(ce, CallExpr, node);
  271. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  272. proc_type = base_type(proc_type);
  273. GB_ASSERT(is_type_proc(proc_type));
  274. TypeProc *pt = &proc_type->Proc;
  275. isize arg_count = 3;
  276. isize param_count = 0;
  277. if (pt->params) {
  278. GB_ASSERT(pt->params->kind == Type_Tuple);
  279. param_count = pt->params->Tuple.variables.count;
  280. }
  281. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  282. args[0] = ptr;
  283. args[1] = index;
  284. args[2] = value;
  285. isize arg_index = arg_count;
  286. if (arg_count < param_count) {
  287. lbModule *m = p->module;
  288. String proc_name = {};
  289. if (p->entity != nullptr) {
  290. proc_name = p->entity->token.string;
  291. }
  292. TokenPos pos = ast_token(ce->proc).pos;
  293. TypeTuple *param_tuple = &pt->params->Tuple;
  294. isize end = cast(isize)param_count;
  295. while (arg_index < end) {
  296. Entity *e = param_tuple->variables[arg_index];
  297. GB_ASSERT(e->kind == Entity_Variable);
  298. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  299. }
  300. }
  301. Entity *e = entity_from_expr(ce->proc);
  302. GB_ASSERT(e != nullptr);
  303. GB_ASSERT(is_type_polymorphic(e->type));
  304. {
  305. lbValue *found = nullptr;
  306. if (p->module != e->code_gen_module) {
  307. gb_mutex_lock(&p->module->mutex);
  308. }
  309. GB_ASSERT(e->code_gen_module != nullptr);
  310. found = map_get(&e->code_gen_module->values, hash_entity(e));
  311. if (p->module != e->code_gen_module) {
  312. gb_mutex_unlock(&p->module->mutex);
  313. }
  314. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  315. lb_emit_call(p, *found, args);
  316. }
  317. return;
  318. } else if (addr.kind == lbAddr_Map) {
  319. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  320. return;
  321. } else if (addr.kind == lbAddr_Context) {
  322. lbAddr old_addr = lb_find_or_generate_context_ptr(p);
  323. // IMPORTANT NOTE(bill, 2021-04-22): reuse unused 'context' variables to minimize stack usage
  324. // This has to be done manually since the optimizer cannot determine when this is possible
  325. bool create_new = true;
  326. for_array(i, p->context_stack) {
  327. lbContextData *ctx_data = &p->context_stack[i];
  328. if (ctx_data->ctx.addr.value == old_addr.addr.value) {
  329. if (ctx_data->uses > 0) {
  330. create_new = true;
  331. } else if (p->scope_index > ctx_data->scope_index) {
  332. create_new = true;
  333. } else {
  334. // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses);
  335. create_new = false;
  336. }
  337. break;
  338. }
  339. }
  340. lbValue next = {};
  341. if (create_new) {
  342. lbValue old = lb_addr_load(p, old_addr);
  343. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  344. lb_addr_store(p, next_addr, old);
  345. lb_push_context_onto_stack(p, next_addr);
  346. next = next_addr.addr;
  347. } else {
  348. next = old_addr.addr;
  349. }
  350. if (addr.ctx.sel.index.count > 0) {
  351. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  352. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  353. lb_emit_store(p, lhs, rhs);
  354. } else {
  355. lbValue lhs = next;
  356. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  357. lb_emit_store(p, lhs, rhs);
  358. }
  359. return;
  360. } else if (addr.kind == lbAddr_SoaVariable) {
  361. Type *t = type_deref(addr.addr.type);
  362. t = base_type(t);
  363. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  364. Type *elem_type = t->Struct.soa_elem;
  365. value = lb_emit_conv(p, value, elem_type);
  366. elem_type = base_type(elem_type);
  367. lbValue index = addr.soa.index;
  368. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  369. Type *t = base_type(type_deref(addr.addr.type));
  370. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  371. lbValue len = lb_soa_struct_len(p, addr.addr);
  372. if (addr.soa.index_expr != nullptr) {
  373. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  374. }
  375. }
  376. isize field_count = 0;
  377. switch (elem_type->kind) {
  378. case Type_Struct:
  379. field_count = elem_type->Struct.fields.count;
  380. break;
  381. case Type_Array:
  382. field_count = elem_type->Array.count;
  383. break;
  384. }
  385. for (isize i = 0; i < field_count; i++) {
  386. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  387. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  388. if (t->Struct.soa_kind == StructSoa_Fixed) {
  389. dst = lb_emit_array_ep(p, dst, index);
  390. lb_emit_store(p, dst, src);
  391. } else {
  392. lbValue field = lb_emit_load(p, dst);
  393. dst = lb_emit_ptr_offset(p, field, index);
  394. lb_emit_store(p, dst, src);
  395. }
  396. }
  397. return;
  398. }
  399. GB_ASSERT(value.value != nullptr);
  400. value = lb_emit_conv(p, value, lb_addr_type(addr));
  401. // if (lb_is_const_or_global(value)) {
  402. // // NOTE(bill): Just bypass the actual storage and set the initializer
  403. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  404. // LLVMValueRef dst = addr.addr.value;
  405. // LLVMValueRef src = value.value;
  406. // LLVMSetInitializer(dst, src);
  407. // return;
  408. // }
  409. // }
  410. lb_emit_store(p, addr.addr, value);
  411. }
  412. void lb_const_store(lbValue ptr, lbValue value) {
  413. GB_ASSERT(lb_is_const(ptr));
  414. GB_ASSERT(lb_is_const(value));
  415. GB_ASSERT(is_type_pointer(ptr.type));
  416. LLVMSetInitializer(ptr.value, value.value);
  417. }
  418. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  419. GB_ASSERT(value.value != nullptr);
  420. Type *a = type_deref(ptr.type);
  421. if (is_type_boolean(a)) {
  422. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  423. value = lb_emit_conv(p, value, a);
  424. }
  425. Type *ca = core_type(a);
  426. if (ca->kind == Type_Basic) {
  427. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  428. }
  429. if (is_type_proc(a)) {
  430. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  431. // stored as regular pointer with no procedure information
  432. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  433. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  434. LLVMBuildStore(p->builder, v, ptr.value);
  435. } else {
  436. Type *ca = core_type(a);
  437. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  438. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  439. } else {
  440. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  441. }
  442. LLVMBuildStore(p->builder, value.value, ptr.value);
  443. }
  444. }
  445. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  446. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  447. }
  448. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  449. lbModule *m = p->module;
  450. GB_ASSERT(value.value != nullptr);
  451. GB_ASSERT(is_type_pointer(value.type));
  452. Type *t = type_deref(value.type);
  453. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  454. return lbValue{v, t};
  455. }
  456. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  457. GB_ASSERT(addr.addr.value != nullptr);
  458. if (addr.kind == lbAddr_RelativePointer) {
  459. Type *rel_ptr = base_type(lb_addr_type(addr));
  460. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  461. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  462. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  463. offset = lb_emit_load(p, offset);
  464. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  465. offset = lb_emit_conv(p, offset, t_i64);
  466. }
  467. offset = lb_emit_conv(p, offset, t_uintptr);
  468. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  469. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  470. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  471. // NOTE(bill): nil check
  472. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  473. lbValue final_ptr = {};
  474. final_ptr.type = absolute_ptr.type;
  475. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  476. return lb_emit_load(p, final_ptr);
  477. } else if (addr.kind == lbAddr_RelativeSlice) {
  478. Type *rel_ptr = base_type(lb_addr_type(addr));
  479. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  480. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  481. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  482. lbValue offset = lb_emit_load(p, offset_ptr);
  483. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  484. offset = lb_emit_conv(p, offset, t_i64);
  485. }
  486. offset = lb_emit_conv(p, offset, t_uintptr);
  487. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  488. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  489. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  490. Type *slice_elem = slice_type->Slice.elem;
  491. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  492. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  493. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  494. // NOTE(bill): nil check
  495. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  496. lbValue data = {};
  497. data.type = absolute_ptr.type;
  498. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  499. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  500. len = lb_emit_conv(p, len, t_int);
  501. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  502. lb_fill_slice(p, slice, data, len);
  503. return lb_addr_load(p, slice);
  504. } else if (addr.kind == lbAddr_Map) {
  505. Type *map_type = base_type(addr.map.type);
  506. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  507. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  508. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  509. auto args = array_make<lbValue>(permanent_allocator(), 2);
  510. args[0] = h;
  511. args[1] = key;
  512. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  513. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  514. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  515. lbBlock *then = lb_create_block(p, "map.get.then");
  516. lbBlock *done = lb_create_block(p, "map.get.done");
  517. lb_emit_if(p, ok, then, done);
  518. lb_start_block(p, then);
  519. {
  520. // TODO(bill): mem copy it instead?
  521. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  522. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  523. lb_emit_store(p, gep0, lb_emit_load(p, value));
  524. }
  525. lb_emit_jump(p, done);
  526. lb_start_block(p, done);
  527. if (is_type_tuple(addr.map.result)) {
  528. return lb_addr_load(p, v);
  529. } else {
  530. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  531. return lb_emit_load(p, single);
  532. }
  533. } else if (addr.kind == lbAddr_Context) {
  534. lbValue a = addr.addr;
  535. for_array(i, p->context_stack) {
  536. lbContextData *ctx_data = &p->context_stack[i];
  537. if (ctx_data->ctx.addr.value == a.value) {
  538. ctx_data->uses += 1;
  539. break;
  540. }
  541. }
  542. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  543. if (addr.ctx.sel.index.count > 0) {
  544. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  545. return lb_emit_load(p, b);
  546. } else {
  547. return lb_emit_load(p, a);
  548. }
  549. } else if (addr.kind == lbAddr_SoaVariable) {
  550. Type *t = type_deref(addr.addr.type);
  551. t = base_type(t);
  552. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  553. Type *elem = t->Struct.soa_elem;
  554. lbValue len = {};
  555. if (t->Struct.soa_kind == StructSoa_Fixed) {
  556. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  557. } else {
  558. lbValue v = lb_emit_load(p, addr.addr);
  559. len = lb_soa_struct_len(p, v);
  560. }
  561. lbAddr res = lb_add_local_generated(p, elem, true);
  562. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  563. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  564. }
  565. if (t->Struct.soa_kind == StructSoa_Fixed) {
  566. for_array(i, t->Struct.fields) {
  567. Entity *field = t->Struct.fields[i];
  568. Type *base_type = field->type;
  569. GB_ASSERT(base_type->kind == Type_Array);
  570. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  571. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  572. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  573. lbValue src = lb_emit_load(p, src_ptr);
  574. lb_emit_store(p, dst, src);
  575. }
  576. } else {
  577. isize field_count = t->Struct.fields.count;
  578. if (t->Struct.soa_kind == StructSoa_Slice) {
  579. field_count -= 1;
  580. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  581. field_count -= 3;
  582. }
  583. for (isize i = 0; i < field_count; i++) {
  584. Entity *field = t->Struct.fields[i];
  585. Type *base_type = field->type;
  586. GB_ASSERT(base_type->kind == Type_Pointer);
  587. Type *elem = base_type->Pointer.elem;
  588. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  589. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  590. lbValue src = lb_emit_load(p, src_ptr);
  591. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  592. src = lb_emit_load(p, src);
  593. lb_emit_store(p, dst, src);
  594. }
  595. }
  596. return lb_addr_load(p, res);
  597. }
  598. if (is_type_proc(addr.addr.type)) {
  599. return addr.addr;
  600. }
  601. return lb_emit_load(p, addr.addr);
  602. }
  603. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  604. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  605. }
  606. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  607. Type *t = u.type;
  608. GB_ASSERT_MSG(is_type_pointer(t) &&
  609. is_type_union(type_deref(t)), "%s", type_to_string(t));
  610. Type *ut = type_deref(t);
  611. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  612. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  613. GB_ASSERT(type_size_of(ut) > 0);
  614. Type *tag_type = union_tag_type(ut);
  615. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  616. unsigned element_count = LLVMCountStructElementTypes(uvt);
  617. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  618. lbValue tag_ptr = {};
  619. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  620. tag_ptr.type = alloc_type_pointer(tag_type);
  621. return tag_ptr;
  622. }
  623. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  624. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  625. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  626. return lb_emit_load(p, tag_ptr);
  627. }
  628. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  629. Type *t = type_deref(parent.type);
  630. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  631. // No tag needed!
  632. } else {
  633. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  634. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  635. }
  636. }
  637. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  638. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  639. lb_emit_store(p, underlying, variant);
  640. lb_emit_store_union_variant_tag(p, parent, variant_type);
  641. }
  642. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  643. unsigned field_count = LLVMCountStructElementTypes(src);
  644. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  645. LLVMGetStructElementTypes(src, fields);
  646. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  647. }
  648. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  649. switch (alignment) {
  650. case 1:
  651. return LLVMArrayType(lb_type(m, t_u8), 0);
  652. case 2:
  653. return LLVMArrayType(lb_type(m, t_u16), 0);
  654. case 4:
  655. return LLVMArrayType(lb_type(m, t_u32), 0);
  656. case 8:
  657. return LLVMArrayType(lb_type(m, t_u64), 0);
  658. case 16:
  659. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  660. default:
  661. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  662. break;
  663. }
  664. return nullptr;
  665. }
  666. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  667. if (!elem_type_can_be_constant(elem_type)) {
  668. return false;
  669. }
  670. if (elem->kind == Ast_FieldValue) {
  671. elem = elem->FieldValue.value;
  672. }
  673. TypeAndValue tav = type_and_value_of_expr(elem);
  674. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  675. return tav.value.kind != ExactValue_Invalid;
  676. }
  677. String lb_mangle_name(lbModule *m, Entity *e) {
  678. String name = e->token.string;
  679. AstPackage *pkg = e->pkg;
  680. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  681. String pkgn = pkg->name;
  682. GB_ASSERT(!rune_is_digit(pkgn[0]));
  683. if (pkgn == "llvm") {
  684. pkgn = str_lit("llvm$");
  685. }
  686. isize max_len = pkgn.len + 1 + name.len + 1;
  687. bool require_suffix_id = is_type_polymorphic(e->type, true);
  688. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  689. require_suffix_id = true;
  690. } else if (is_blank_ident(e->token)) {
  691. require_suffix_id = true;
  692. }if (e->flags & EntityFlag_NotExported) {
  693. require_suffix_id = true;
  694. }
  695. if (require_suffix_id) {
  696. max_len += 21;
  697. }
  698. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  699. isize new_name_len = gb_snprintf(
  700. new_name, max_len,
  701. "%.*s.%.*s", LIT(pkgn), LIT(name)
  702. );
  703. if (require_suffix_id) {
  704. char *str = new_name + new_name_len-1;
  705. isize len = max_len-new_name_len;
  706. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  707. new_name_len += extra-1;
  708. }
  709. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  710. return mangled_name;
  711. }
  712. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  713. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  714. // and as a result, the declaration does not have time to determine what it should be
  715. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  716. if (e->TypeName.ir_mangled_name.len != 0) {
  717. return e->TypeName.ir_mangled_name;
  718. }
  719. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  720. if (p == nullptr) {
  721. Entity *proc = nullptr;
  722. if (e->parent_proc_decl != nullptr) {
  723. proc = e->parent_proc_decl->entity;
  724. } else {
  725. Scope *scope = e->scope;
  726. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  727. scope = scope->parent;
  728. }
  729. GB_ASSERT(scope != nullptr);
  730. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  731. proc = scope->procedure_entity;
  732. }
  733. GB_ASSERT(proc->kind == Entity_Procedure);
  734. if (proc->code_gen_procedure != nullptr) {
  735. p = proc->code_gen_procedure;
  736. }
  737. }
  738. // NOTE(bill): Generate a new name
  739. // parent_proc.name-guid
  740. String ts_name = e->token.string;
  741. if (p != nullptr) {
  742. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  743. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  744. u32 guid = ++p->module->nested_type_name_guid;
  745. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  746. String name = make_string(cast(u8 *)name_text, name_len-1);
  747. e->TypeName.ir_mangled_name = name;
  748. return name;
  749. } else {
  750. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  751. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  752. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  753. static u32 guid = 0;
  754. guid += 1;
  755. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  756. String name = make_string(cast(u8 *)name_text, name_len-1);
  757. e->TypeName.ir_mangled_name = name;
  758. return name;
  759. }
  760. }
  761. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  762. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  763. return e->TypeName.ir_mangled_name;
  764. }
  765. GB_ASSERT(e != nullptr);
  766. if (e->pkg == nullptr) {
  767. return e->token.string;
  768. }
  769. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  770. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  771. }
  772. String name = {};
  773. bool no_name_mangle = false;
  774. if (e->kind == Entity_Variable) {
  775. bool is_foreign = e->Variable.is_foreign;
  776. bool is_export = e->Variable.is_export;
  777. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  778. if (e->Variable.link_name.len > 0) {
  779. return e->Variable.link_name;
  780. }
  781. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  782. return e->Procedure.link_name;
  783. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  784. no_name_mangle = true;
  785. }
  786. if (!no_name_mangle) {
  787. name = lb_mangle_name(m, e);
  788. }
  789. if (name.len == 0) {
  790. name = e->token.string;
  791. }
  792. if (e->kind == Entity_TypeName) {
  793. e->TypeName.ir_mangled_name = name;
  794. } else if (e->kind == Entity_Procedure) {
  795. e->Procedure.link_name = name;
  796. }
  797. return name;
  798. }
  799. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  800. Type *original_type = type;
  801. LLVMContextRef ctx = m->ctx;
  802. i64 size = type_size_of(type); // Check size
  803. GB_ASSERT(type != t_invalid);
  804. switch (type->kind) {
  805. case Type_Basic:
  806. switch (type->Basic.kind) {
  807. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  808. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  809. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  810. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  811. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  812. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  813. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  814. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  815. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  816. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  817. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  818. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  819. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  820. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  821. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  822. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  823. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  824. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  825. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  826. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  827. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  828. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  829. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  830. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  831. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  832. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  833. case Basic_complex32:
  834. {
  835. char const *name = "..complex32";
  836. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  837. if (type != nullptr) {
  838. return type;
  839. }
  840. type = LLVMStructCreateNamed(ctx, name);
  841. LLVMTypeRef fields[2] = {
  842. lb_type(m, t_f16),
  843. lb_type(m, t_f16),
  844. };
  845. LLVMStructSetBody(type, fields, 2, false);
  846. return type;
  847. }
  848. case Basic_complex64:
  849. {
  850. char const *name = "..complex64";
  851. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  852. if (type != nullptr) {
  853. return type;
  854. }
  855. type = LLVMStructCreateNamed(ctx, name);
  856. LLVMTypeRef fields[2] = {
  857. lb_type(m, t_f32),
  858. lb_type(m, t_f32),
  859. };
  860. LLVMStructSetBody(type, fields, 2, false);
  861. return type;
  862. }
  863. case Basic_complex128:
  864. {
  865. char const *name = "..complex128";
  866. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  867. if (type != nullptr) {
  868. return type;
  869. }
  870. type = LLVMStructCreateNamed(ctx, name);
  871. LLVMTypeRef fields[2] = {
  872. lb_type(m, t_f64),
  873. lb_type(m, t_f64),
  874. };
  875. LLVMStructSetBody(type, fields, 2, false);
  876. return type;
  877. }
  878. case Basic_quaternion64:
  879. {
  880. char const *name = "..quaternion64";
  881. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  882. if (type != nullptr) {
  883. return type;
  884. }
  885. type = LLVMStructCreateNamed(ctx, name);
  886. LLVMTypeRef fields[4] = {
  887. lb_type(m, t_f16),
  888. lb_type(m, t_f16),
  889. lb_type(m, t_f16),
  890. lb_type(m, t_f16),
  891. };
  892. LLVMStructSetBody(type, fields, 4, false);
  893. return type;
  894. }
  895. case Basic_quaternion128:
  896. {
  897. char const *name = "..quaternion128";
  898. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  899. if (type != nullptr) {
  900. return type;
  901. }
  902. type = LLVMStructCreateNamed(ctx, name);
  903. LLVMTypeRef fields[4] = {
  904. lb_type(m, t_f32),
  905. lb_type(m, t_f32),
  906. lb_type(m, t_f32),
  907. lb_type(m, t_f32),
  908. };
  909. LLVMStructSetBody(type, fields, 4, false);
  910. return type;
  911. }
  912. case Basic_quaternion256:
  913. {
  914. char const *name = "..quaternion256";
  915. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  916. if (type != nullptr) {
  917. return type;
  918. }
  919. type = LLVMStructCreateNamed(ctx, name);
  920. LLVMTypeRef fields[4] = {
  921. lb_type(m, t_f64),
  922. lb_type(m, t_f64),
  923. lb_type(m, t_f64),
  924. lb_type(m, t_f64),
  925. };
  926. LLVMStructSetBody(type, fields, 4, false);
  927. return type;
  928. }
  929. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  930. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  931. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  932. case Basic_rawptr: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  933. case Basic_string:
  934. {
  935. char const *name = "..string";
  936. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  937. if (type != nullptr) {
  938. return type;
  939. }
  940. type = LLVMStructCreateNamed(ctx, name);
  941. LLVMTypeRef fields[2] = {
  942. LLVMPointerType(lb_type(m, t_u8), 0),
  943. lb_type(m, t_int),
  944. };
  945. LLVMStructSetBody(type, fields, 2, false);
  946. return type;
  947. }
  948. case Basic_cstring: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  949. case Basic_any:
  950. {
  951. char const *name = "..any";
  952. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  953. if (type != nullptr) {
  954. return type;
  955. }
  956. type = LLVMStructCreateNamed(ctx, name);
  957. LLVMTypeRef fields[2] = {
  958. lb_type(m, t_rawptr),
  959. lb_type(m, t_typeid),
  960. };
  961. LLVMStructSetBody(type, fields, 2, false);
  962. return type;
  963. }
  964. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  965. // Endian Specific Types
  966. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  967. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  968. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  969. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  970. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  971. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  972. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  973. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  974. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  975. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  976. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  977. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  978. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  979. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  980. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  981. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  982. // Untyped types
  983. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  984. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  985. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  986. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  987. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  988. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  989. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  990. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  991. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  992. }
  993. break;
  994. case Type_Named:
  995. {
  996. Type *base = base_type(type->Named.base);
  997. switch (base->kind) {
  998. case Type_Basic:
  999. return lb_type_internal(m, base);
  1000. case Type_Named:
  1001. case Type_Generic:
  1002. GB_PANIC("INVALID TYPE");
  1003. break;
  1004. case Type_Pointer:
  1005. case Type_Array:
  1006. case Type_EnumeratedArray:
  1007. case Type_Slice:
  1008. case Type_DynamicArray:
  1009. case Type_Map:
  1010. case Type_Enum:
  1011. case Type_BitSet:
  1012. case Type_SimdVector:
  1013. return lb_type_internal(m, base);
  1014. // TODO(bill): Deal with this correctly. Can this be named?
  1015. case Type_Proc:
  1016. return lb_type_internal(m, base);
  1017. case Type_Tuple:
  1018. return lb_type_internal(m, base);
  1019. }
  1020. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1021. if (found) {
  1022. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1023. if (kind == LLVMStructTypeKind) {
  1024. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1025. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1026. if (llvm_type != nullptr) {
  1027. return llvm_type;
  1028. }
  1029. llvm_type = LLVMStructCreateNamed(ctx, name);
  1030. map_set(&m->types, hash_type(type), llvm_type);
  1031. lb_clone_struct_type(llvm_type, *found);
  1032. return llvm_type;
  1033. }
  1034. }
  1035. switch (base->kind) {
  1036. case Type_Struct:
  1037. case Type_Union:
  1038. {
  1039. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1040. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1041. if (llvm_type != nullptr) {
  1042. return llvm_type;
  1043. }
  1044. llvm_type = LLVMStructCreateNamed(ctx, name);
  1045. map_set(&m->types, hash_type(type), llvm_type);
  1046. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1047. return llvm_type;
  1048. }
  1049. }
  1050. return lb_type_internal(m, base);
  1051. }
  1052. case Type_Pointer:
  1053. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1054. case Type_Array: {
  1055. m->internal_type_level -= 1;
  1056. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1057. m->internal_type_level += 1;
  1058. return t;
  1059. }
  1060. case Type_EnumeratedArray: {
  1061. m->internal_type_level -= 1;
  1062. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1063. m->internal_type_level += 1;
  1064. return t;
  1065. }
  1066. case Type_Slice:
  1067. {
  1068. LLVMTypeRef fields[2] = {
  1069. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1070. lb_type(m, t_int), // len
  1071. };
  1072. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1073. }
  1074. break;
  1075. case Type_DynamicArray:
  1076. {
  1077. LLVMTypeRef fields[4] = {
  1078. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1079. lb_type(m, t_int), // len
  1080. lb_type(m, t_int), // cap
  1081. lb_type(m, t_allocator), // allocator
  1082. };
  1083. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1084. }
  1085. break;
  1086. case Type_Map:
  1087. return lb_type(m, type->Map.internal_type);
  1088. case Type_Struct:
  1089. {
  1090. if (type->Struct.is_raw_union) {
  1091. unsigned field_count = 2;
  1092. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1093. i64 alignment = type_align_of(type);
  1094. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1095. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1096. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1097. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1098. }
  1099. isize offset = 0;
  1100. if (type->Struct.custom_align > 0) {
  1101. offset = 1;
  1102. }
  1103. m->internal_type_level += 1;
  1104. defer (m->internal_type_level -= 1);
  1105. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1106. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1107. for_array(i, type->Struct.fields) {
  1108. Entity *field = type->Struct.fields[i];
  1109. fields[i+offset] = lb_type(m, field->type);
  1110. }
  1111. if (type->Struct.custom_align > 0) {
  1112. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1113. }
  1114. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1115. }
  1116. break;
  1117. case Type_Union:
  1118. if (type->Union.variants.count == 0) {
  1119. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1120. } else {
  1121. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1122. // LLVM takes the first element's alignment as the entire alignment (like C)
  1123. i64 align = type_align_of(type);
  1124. i64 size = type_size_of(type);
  1125. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1126. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1127. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1128. }
  1129. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1130. LLVMTypeRef fields[3] = {};
  1131. unsigned field_count = 1;
  1132. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1133. if (is_type_union_maybe_pointer(type)) {
  1134. field_count += 1;
  1135. fields[1] = lb_type(m, type->Union.variants[0]);
  1136. } else {
  1137. field_count += 2;
  1138. if (block_size == align) {
  1139. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1140. } else {
  1141. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1142. }
  1143. fields[2] = lb_type(m, union_tag_type(type));
  1144. }
  1145. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1146. }
  1147. break;
  1148. case Type_Enum:
  1149. return lb_type(m, base_enum_type(type));
  1150. case Type_Tuple:
  1151. if (type->Tuple.variables.count == 1) {
  1152. return lb_type(m, type->Tuple.variables[0]->type);
  1153. } else {
  1154. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1155. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1156. for_array(i, type->Tuple.variables) {
  1157. Entity *field = type->Tuple.variables[i];
  1158. LLVMTypeRef param_type = nullptr;
  1159. param_type = lb_type(m, field->type);
  1160. fields[i] = param_type;
  1161. }
  1162. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1163. }
  1164. case Type_Proc:
  1165. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1166. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1167. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1168. } else {
  1169. unsigned param_count = 0;
  1170. if (type->Proc.calling_convention == ProcCC_Odin) {
  1171. param_count += 1;
  1172. }
  1173. if (type->Proc.param_count != 0) {
  1174. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1175. for_array(i, type->Proc.params->Tuple.variables) {
  1176. Entity *e = type->Proc.params->Tuple.variables[i];
  1177. if (e->kind != Entity_Variable) {
  1178. continue;
  1179. }
  1180. if (e->flags & EntityFlag_CVarArg) {
  1181. continue;
  1182. }
  1183. param_count += 1;
  1184. }
  1185. }
  1186. m->internal_type_level += 1;
  1187. defer (m->internal_type_level -= 1);
  1188. LLVMTypeRef ret = nullptr;
  1189. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1190. if (type->Proc.result_count != 0) {
  1191. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1192. ret = lb_type(m, single_ret);
  1193. if (ret != nullptr) {
  1194. if (is_type_boolean(single_ret) &&
  1195. is_calling_convention_none(type->Proc.calling_convention) &&
  1196. type_size_of(single_ret) <= 1) {
  1197. ret = LLVMInt1TypeInContext(m->ctx);
  1198. }
  1199. }
  1200. }
  1201. isize param_index = 0;
  1202. if (type->Proc.param_count != 0) {
  1203. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1204. for_array(i, type->Proc.params->Tuple.variables) {
  1205. Entity *e = type->Proc.params->Tuple.variables[i];
  1206. if (e->kind != Entity_Variable) {
  1207. continue;
  1208. }
  1209. if (e->flags & EntityFlag_CVarArg) {
  1210. continue;
  1211. }
  1212. Type *e_type = reduce_tuple_to_single_type(e->type);
  1213. LLVMTypeRef param_type = nullptr;
  1214. if (is_type_boolean(e_type) &&
  1215. type_size_of(e_type) <= 1) {
  1216. param_type = LLVMInt1TypeInContext(m->ctx);
  1217. } else {
  1218. if (is_type_proc(e_type)) {
  1219. param_type = lb_type(m, t_rawptr);
  1220. } else {
  1221. param_type = lb_type(m, e_type);
  1222. }
  1223. }
  1224. params[param_index++] = param_type;
  1225. }
  1226. }
  1227. if (param_index < param_count) {
  1228. params[param_index++] = lb_type(m, t_rawptr);
  1229. }
  1230. GB_ASSERT(param_index == param_count);
  1231. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1232. {
  1233. for_array(j, ft->args) {
  1234. auto arg = ft->args[j];
  1235. GB_ASSERT_MSG(LLVMGetTypeContext(arg.type) == ft->ctx,
  1236. "\n\t%s %td/%td"
  1237. "\n\tArgTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1238. LLVMPrintTypeToString(arg.type),
  1239. j, ft->args.count,
  1240. LLVMGetTypeContext(arg.type), ft->ctx, LLVMGetGlobalContext());
  1241. }
  1242. GB_ASSERT_MSG(LLVMGetTypeContext(ft->ret.type) == ft->ctx,
  1243. "\n\t%s"
  1244. "\n\tRetTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1245. LLVMPrintTypeToString(ft->ret.type),
  1246. LLVMGetTypeContext(ft->ret.type), ft->ctx, LLVMGetGlobalContext());
  1247. }
  1248. map_set(&m->function_type_map, hash_type(type), ft);
  1249. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1250. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1251. GB_ASSERT_MSG(LLVMGetTypeContext(new_abi_fn_type) == m->ctx,
  1252. "\n\tFuncTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1253. LLVMGetTypeContext(new_abi_fn_type), m->ctx, LLVMGetGlobalContext());
  1254. return new_abi_fn_ptr_type;
  1255. }
  1256. break;
  1257. case Type_BitSet:
  1258. {
  1259. Type *ut = bit_set_to_int(type);
  1260. return lb_type(m, ut);
  1261. }
  1262. case Type_SimdVector:
  1263. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1264. case Type_RelativePointer:
  1265. return lb_type_internal(m, type->RelativePointer.base_integer);
  1266. case Type_RelativeSlice:
  1267. {
  1268. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1269. unsigned field_count = 2;
  1270. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1271. fields[0] = base_integer;
  1272. fields[1] = base_integer;
  1273. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1274. }
  1275. }
  1276. GB_PANIC("Invalid type %s", type_to_string(type));
  1277. return LLVMInt32TypeInContext(ctx);
  1278. }
  1279. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1280. type = default_type(type);
  1281. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1282. if (found) {
  1283. return *found;
  1284. }
  1285. LLVMTypeRef llvm_type = nullptr;
  1286. m->internal_type_level += 1;
  1287. llvm_type = lb_type_internal(m, type);
  1288. m->internal_type_level -= 1;
  1289. if (m->internal_type_level == 0) {
  1290. map_set(&m->types, hash_type(type), llvm_type);
  1291. if (is_type_named(type)) {
  1292. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1293. }
  1294. }
  1295. return llvm_type;
  1296. }
  1297. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1298. if (key == nullptr) {
  1299. return nullptr;
  1300. }
  1301. auto found = map_get(&m->debug_values, hash_pointer(key));
  1302. if (found) {
  1303. return *found;
  1304. }
  1305. return nullptr;
  1306. }
  1307. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1308. if (key != nullptr) {
  1309. map_set(&m->debug_values, hash_pointer(key), value);
  1310. }
  1311. }
  1312. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1313. if (node == nullptr) {
  1314. return nullptr;
  1315. }
  1316. return lb_get_llvm_metadata(m, node->file);
  1317. }
  1318. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1319. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1320. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1321. Scope *s = p->scope_stack[i];
  1322. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1323. if (md) {
  1324. return md;
  1325. }
  1326. }
  1327. return p->debug_info;
  1328. }
  1329. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1330. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1331. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1332. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1333. }
  1334. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1335. GB_ASSERT(node != nullptr);
  1336. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1337. }
  1338. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1339. Type *original_type = type;
  1340. LLVMContextRef ctx = m->ctx;
  1341. i64 size = type_size_of(type); // Check size
  1342. GB_ASSERT(type != t_invalid);
  1343. unsigned const word_size = cast(unsigned)build_context.word_size;
  1344. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1345. GB_ASSERT(type->kind == Type_Proc);
  1346. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1347. unsigned parameter_count = 1;
  1348. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1349. Entity *e = type->Proc.params->Tuple.variables[i];
  1350. if (e->kind == Entity_Variable) {
  1351. parameter_count += 1;
  1352. }
  1353. }
  1354. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1355. unsigned param_index = 0;
  1356. if (type->Proc.result_count == 0) {
  1357. parameters[param_index++] = nullptr;
  1358. } else {
  1359. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1360. }
  1361. LLVMMetadataRef parent_scope = nullptr;
  1362. LLVMMetadataRef scope = nullptr;
  1363. LLVMMetadataRef file = nullptr;
  1364. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1365. Entity *e = type->Proc.params->Tuple.variables[i];
  1366. if (e->kind != Entity_Variable) {
  1367. continue;
  1368. }
  1369. parameters[param_index] = lb_debug_type(m, e->type);
  1370. param_index += 1;
  1371. }
  1372. LLVMDIFlags flags = LLVMDIFlagZero;
  1373. if (type->Proc.diverging) {
  1374. flags = LLVMDIFlagNoReturn;
  1375. }
  1376. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1377. }
  1378. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1379. unsigned field_line = 1;
  1380. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1381. AstPackage *pkg = m->info->runtime_package;
  1382. GB_ASSERT(pkg->files.count != 0);
  1383. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1384. LLVMMetadataRef scope = file;
  1385. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1386. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1387. field_flags, lb_debug_type(m, type)
  1388. );
  1389. }
  1390. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1391. AstPackage *pkg = m->info->runtime_package;
  1392. GB_ASSERT(pkg->files.count != 0);
  1393. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1394. LLVMMetadataRef scope = file;
  1395. return LLVMDIBuilderCreateStructType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, 1, size_in_bits, align_in_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1396. }
  1397. LLVMMetadataRef lb_debug_type_basic_type(lbModule *m, String const &name, u64 size_in_bits, LLVMDWARFTypeEncoding encoding, LLVMDIFlags flags = LLVMDIFlagZero) {
  1398. LLVMMetadataRef basic_type = LLVMDIBuilderCreateBasicType(m->debug_builder, cast(char const *)name.text, name.len, size_in_bits, encoding, flags);
  1399. #if 1
  1400. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, basic_type, cast(char const *)name.text, name.len, nullptr, 0, nullptr, cast(u32)size_in_bits);
  1401. return final_decl;
  1402. #else
  1403. return basic_type;
  1404. #endif
  1405. }
  1406. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1407. Type *original_type = type;
  1408. LLVMContextRef ctx = m->ctx;
  1409. i64 size = type_size_of(type); // Check size
  1410. GB_ASSERT(type != t_invalid);
  1411. unsigned const word_size = cast(unsigned)build_context.word_size;
  1412. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1413. switch (type->kind) {
  1414. case Type_Basic:
  1415. switch (type->Basic.kind) {
  1416. case Basic_llvm_bool: return lb_debug_type_basic_type(m, str_lit("llvm bool"), 1, LLVMDWARFTypeEncoding_Boolean);
  1417. case Basic_bool: return lb_debug_type_basic_type(m, str_lit("bool"), 8, LLVMDWARFTypeEncoding_Boolean);
  1418. case Basic_b8: return lb_debug_type_basic_type(m, str_lit("b8"), 8, LLVMDWARFTypeEncoding_Boolean);
  1419. case Basic_b16: return lb_debug_type_basic_type(m, str_lit("b16"), 16, LLVMDWARFTypeEncoding_Boolean);
  1420. case Basic_b32: return lb_debug_type_basic_type(m, str_lit("b32"), 32, LLVMDWARFTypeEncoding_Boolean);
  1421. case Basic_b64: return lb_debug_type_basic_type(m, str_lit("b64"), 64, LLVMDWARFTypeEncoding_Boolean);
  1422. case Basic_i8: return lb_debug_type_basic_type(m, str_lit("i8"), 8, LLVMDWARFTypeEncoding_Signed);
  1423. case Basic_u8: return lb_debug_type_basic_type(m, str_lit("u8"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1424. case Basic_i16: return lb_debug_type_basic_type(m, str_lit("i16"), 16, LLVMDWARFTypeEncoding_Signed);
  1425. case Basic_u16: return lb_debug_type_basic_type(m, str_lit("u16"), 16, LLVMDWARFTypeEncoding_Unsigned);
  1426. case Basic_i32: return lb_debug_type_basic_type(m, str_lit("i32"), 32, LLVMDWARFTypeEncoding_Signed);
  1427. case Basic_u32: return lb_debug_type_basic_type(m, str_lit("u32"), 32, LLVMDWARFTypeEncoding_Unsigned);
  1428. case Basic_i64: return lb_debug_type_basic_type(m, str_lit("i64"), 64, LLVMDWARFTypeEncoding_Signed);
  1429. case Basic_u64: return lb_debug_type_basic_type(m, str_lit("u64"), 64, LLVMDWARFTypeEncoding_Unsigned);
  1430. case Basic_i128: return lb_debug_type_basic_type(m, str_lit("i128"), 128, LLVMDWARFTypeEncoding_Signed);
  1431. case Basic_u128: return lb_debug_type_basic_type(m, str_lit("u128"), 128, LLVMDWARFTypeEncoding_Unsigned);
  1432. case Basic_rune: return lb_debug_type_basic_type(m, str_lit("rune"), 32, LLVMDWARFTypeEncoding_Utf);
  1433. case Basic_f16: return lb_debug_type_basic_type(m, str_lit("f16"), 16, LLVMDWARFTypeEncoding_Float);
  1434. case Basic_f32: return lb_debug_type_basic_type(m, str_lit("f32"), 32, LLVMDWARFTypeEncoding_Float);
  1435. case Basic_f64: return lb_debug_type_basic_type(m, str_lit("f64"), 64, LLVMDWARFTypeEncoding_Float);
  1436. case Basic_int: return lb_debug_type_basic_type(m, str_lit("int"), word_bits, LLVMDWARFTypeEncoding_Signed);
  1437. case Basic_uint: return lb_debug_type_basic_type(m, str_lit("uint"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1438. case Basic_uintptr: return lb_debug_type_basic_type(m, str_lit("uintptr"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1439. case Basic_typeid:
  1440. return lb_debug_type_basic_type(m, str_lit("typeid"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1441. // Endian Specific Types
  1442. case Basic_i16le: return lb_debug_type_basic_type(m, str_lit("i16le"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1443. case Basic_u16le: return lb_debug_type_basic_type(m, str_lit("u16le"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1444. case Basic_i32le: return lb_debug_type_basic_type(m, str_lit("i32le"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1445. case Basic_u32le: return lb_debug_type_basic_type(m, str_lit("u32le"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1446. case Basic_i64le: return lb_debug_type_basic_type(m, str_lit("i64le"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1447. case Basic_u64le: return lb_debug_type_basic_type(m, str_lit("u64le"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1448. case Basic_i128le: return lb_debug_type_basic_type(m, str_lit("i128le"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1449. case Basic_u128le: return lb_debug_type_basic_type(m, str_lit("u128le"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1450. case Basic_f16le: return lb_debug_type_basic_type(m, str_lit("f16le"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1451. case Basic_f32le: return lb_debug_type_basic_type(m, str_lit("f32le"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1452. case Basic_f64le: return lb_debug_type_basic_type(m, str_lit("f64le"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1453. case Basic_i16be: return lb_debug_type_basic_type(m, str_lit("i16be"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1454. case Basic_u16be: return lb_debug_type_basic_type(m, str_lit("u16be"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1455. case Basic_i32be: return lb_debug_type_basic_type(m, str_lit("i32be"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1456. case Basic_u32be: return lb_debug_type_basic_type(m, str_lit("u32be"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1457. case Basic_i64be: return lb_debug_type_basic_type(m, str_lit("i64be"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1458. case Basic_u64be: return lb_debug_type_basic_type(m, str_lit("u64be"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1459. case Basic_i128be: return lb_debug_type_basic_type(m, str_lit("i128be"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1460. case Basic_u128be: return lb_debug_type_basic_type(m, str_lit("u128be"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1461. case Basic_f16be: return lb_debug_type_basic_type(m, str_lit("f16be"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1462. case Basic_f32be: return lb_debug_type_basic_type(m, str_lit("f32be"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1463. case Basic_f64be: return lb_debug_type_basic_type(m, str_lit("f64be"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1464. case Basic_complex32:
  1465. {
  1466. LLVMMetadataRef elements[2] = {};
  1467. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f16, 0);
  1468. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 4);
  1469. return lb_debug_basic_struct(m, str_lit("complex32"), 64, 32, elements, gb_count_of(elements));
  1470. }
  1471. case Basic_complex64:
  1472. {
  1473. LLVMMetadataRef elements[2] = {};
  1474. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1475. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1476. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1477. }
  1478. case Basic_complex128:
  1479. {
  1480. LLVMMetadataRef elements[2] = {};
  1481. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1482. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1483. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1484. }
  1485. case Basic_quaternion64:
  1486. {
  1487. LLVMMetadataRef elements[4] = {};
  1488. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 0);
  1489. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f16, 4);
  1490. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f16, 8);
  1491. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f16, 12);
  1492. return lb_debug_basic_struct(m, str_lit("quaternion64"), 128, 32, elements, gb_count_of(elements));
  1493. }
  1494. case Basic_quaternion128:
  1495. {
  1496. LLVMMetadataRef elements[4] = {};
  1497. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1498. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1499. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1500. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1501. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1502. }
  1503. case Basic_quaternion256:
  1504. {
  1505. LLVMMetadataRef elements[4] = {};
  1506. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1507. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1508. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1509. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1510. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1511. }
  1512. case Basic_rawptr:
  1513. {
  1514. LLVMMetadataRef void_type = lb_debug_type_basic_type(m, str_lit("void"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1515. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1516. }
  1517. case Basic_string:
  1518. {
  1519. LLVMMetadataRef elements[2] = {};
  1520. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1521. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1522. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1523. }
  1524. case Basic_cstring:
  1525. {
  1526. LLVMMetadataRef char_type = lb_debug_type_basic_type(m, str_lit("char"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1527. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1528. }
  1529. case Basic_any:
  1530. {
  1531. LLVMMetadataRef elements[2] = {};
  1532. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1533. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1534. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1535. }
  1536. // Untyped types
  1537. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1538. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1539. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1540. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1541. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1542. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1543. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1544. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1545. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1546. default: GB_PANIC("Basic Unhandled"); break;
  1547. }
  1548. break;
  1549. case Type_Named:
  1550. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1551. case Type_Pointer:
  1552. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1553. case Type_Array:
  1554. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1555. type->Array.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->Array.elem), nullptr, 0);
  1556. case Type_EnumeratedArray: {
  1557. LLVMMetadataRef array_type = LLVMDIBuilderCreateArrayType(m->debug_builder,
  1558. type->EnumeratedArray.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->EnumeratedArray.elem), nullptr, 0);
  1559. gbString name = type_to_string(type, temporary_allocator());
  1560. return LLVMDIBuilderCreateTypedef(m->debug_builder, array_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1561. }
  1562. case Type_Struct:
  1563. case Type_Union:
  1564. case Type_Slice:
  1565. case Type_DynamicArray:
  1566. case Type_Map:
  1567. case Type_BitSet:
  1568. {
  1569. unsigned tag = DW_TAG_structure_type;
  1570. if (is_type_raw_union(type) || is_type_union(type)) {
  1571. tag = DW_TAG_union_type;
  1572. }
  1573. u64 size_in_bits = cast(u64)(8*type_size_of(type));
  1574. u32 align_in_bits = cast(u32)(8*type_size_of(type));
  1575. LLVMDIFlags flags = LLVMDIFlagZero;
  1576. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1577. m->debug_builder, tag, "", 0, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1578. );
  1579. lbIncompleteDebugType idt = {};
  1580. idt.type = type;
  1581. idt.metadata = temp_forward_decl;
  1582. array_add(&m->debug_incomplete_types, idt);
  1583. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1584. return temp_forward_decl;
  1585. }
  1586. case Type_Enum:
  1587. {
  1588. LLVMMetadataRef scope = nullptr;
  1589. LLVMMetadataRef file = nullptr;
  1590. unsigned line = 0;
  1591. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1592. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1593. Type *bt = base_enum_type(type);
  1594. LLVMBool is_unsigned = is_type_unsigned(bt);
  1595. for (unsigned i = 0; i < element_count; i++) {
  1596. Entity *f = type->Enum.fields[i];
  1597. GB_ASSERT(f->kind == Entity_Constant);
  1598. String name = f->token.string;
  1599. i64 value = exact_value_to_i64(f->Constant.value);
  1600. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1601. }
  1602. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1603. return LLVMDIBuilderCreateEnumerationType(m->debug_builder, scope, "", 0, file, line, 8*type_size_of(type), 8*cast(unsigned)type_align_of(type), elements, element_count, class_type);
  1604. }
  1605. case Type_Tuple:
  1606. if (type->Tuple.variables.count == 1) {
  1607. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1608. } else {
  1609. type_set_offsets(type);
  1610. LLVMMetadataRef parent_scope = nullptr;
  1611. LLVMMetadataRef scope = nullptr;
  1612. LLVMMetadataRef file = nullptr;
  1613. unsigned line = 0;
  1614. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1615. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1616. LLVMDIFlags flags = LLVMDIFlagZero;
  1617. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1618. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1619. for (unsigned i = 0; i < element_count; i++) {
  1620. Entity *f = type->Tuple.variables[i];
  1621. GB_ASSERT(f->kind == Entity_Variable);
  1622. String name = f->token.string;
  1623. unsigned field_line = 0;
  1624. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1625. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1626. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1627. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1628. field_flags, lb_debug_type(m, f->type)
  1629. );
  1630. }
  1631. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1632. size_in_bits, align_in_bits, flags,
  1633. nullptr, elements, element_count, 0, nullptr,
  1634. "", 0
  1635. );
  1636. }
  1637. case Type_Proc:
  1638. {
  1639. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1640. LLVMMetadataRef pointer_type = LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1641. gbString name = type_to_string(type, temporary_allocator());
  1642. return LLVMDIBuilderCreateTypedef(m->debug_builder, pointer_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1643. }
  1644. break;
  1645. case Type_SimdVector:
  1646. return LLVMDIBuilderCreateVectorType(m->debug_builder, cast(unsigned)type->SimdVector.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->SimdVector.elem), nullptr, 0);
  1647. case Type_RelativePointer: {
  1648. LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativePointer.base_integer);
  1649. gbString name = type_to_string(type, temporary_allocator());
  1650. return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1651. }
  1652. case Type_RelativeSlice:
  1653. {
  1654. unsigned element_count = 0;
  1655. LLVMMetadataRef elements[2] = {};
  1656. Type *base_integer = type->RelativeSlice.base_integer;
  1657. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1658. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1659. gbString name = type_to_string(type, temporary_allocator());
  1660. return LLVMDIBuilderCreateStructType(m->debug_builder, nullptr, name, gb_string_length(name), nullptr, 0, 2*word_bits, word_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1661. }
  1662. }
  1663. GB_PANIC("Invalid type %s", type_to_string(type));
  1664. return nullptr;
  1665. }
  1666. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1667. GB_ASSERT(type != nullptr);
  1668. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1669. if (found != nullptr) {
  1670. return found;
  1671. }
  1672. if (type->kind == Type_Named) {
  1673. LLVMMetadataRef file = nullptr;
  1674. unsigned line = 0;
  1675. LLVMMetadataRef scope = nullptr;
  1676. if (type->Named.type_name != nullptr) {
  1677. Entity *e = type->Named.type_name;
  1678. scope = lb_get_llvm_metadata(m, e->scope);
  1679. if (scope != nullptr) {
  1680. file = LLVMDIScopeGetFile(scope);
  1681. }
  1682. line = cast(unsigned)e->token.pos.line;
  1683. }
  1684. // TODO(bill): location data for Type_Named
  1685. u64 size_in_bits = 8*type_size_of(type);
  1686. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1687. String name = type->Named.name;
  1688. char const *name_text = cast(char const *)name.text;
  1689. size_t name_len = cast(size_t)name.len;
  1690. unsigned tag = DW_TAG_structure_type;
  1691. if (is_type_raw_union(type) || is_type_union(type)) {
  1692. tag = DW_TAG_union_type;
  1693. }
  1694. LLVMDIFlags flags = LLVMDIFlagZero;
  1695. Type *bt = base_type(type->Named.base);
  1696. lbIncompleteDebugType idt = {};
  1697. idt.type = type;
  1698. switch (bt->kind) {
  1699. case Type_Enum:
  1700. {
  1701. LLVMMetadataRef scope = nullptr;
  1702. LLVMMetadataRef file = nullptr;
  1703. unsigned line = 0;
  1704. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1705. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1706. Type *ct = base_enum_type(type);
  1707. LLVMBool is_unsigned = is_type_unsigned(ct);
  1708. for (unsigned i = 0; i < element_count; i++) {
  1709. Entity *f = bt->Enum.fields[i];
  1710. GB_ASSERT(f->kind == Entity_Constant);
  1711. String name = f->token.string;
  1712. i64 value = exact_value_to_i64(f->Constant.value);
  1713. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1714. }
  1715. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1716. return LLVMDIBuilderCreateEnumerationType(m->debug_builder, scope, name_text, name_len, file, line, 8*type_size_of(type), 8*cast(unsigned)type_align_of(type), elements, element_count, class_type);
  1717. }
  1718. case Type_Basic:
  1719. case Type_Pointer:
  1720. case Type_Array:
  1721. case Type_EnumeratedArray:
  1722. case Type_Tuple:
  1723. case Type_Proc:
  1724. case Type_SimdVector:
  1725. case Type_RelativePointer:
  1726. case Type_RelativeSlice:
  1727. {
  1728. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1729. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1730. lb_set_llvm_metadata(m, type, final_decl);
  1731. return final_decl;
  1732. }
  1733. case Type_Slice:
  1734. case Type_DynamicArray:
  1735. case Type_Map:
  1736. case Type_Struct:
  1737. case Type_Union:
  1738. case Type_BitSet:
  1739. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1740. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1741. );
  1742. idt.metadata = temp_forward_decl;
  1743. array_add(&m->debug_incomplete_types, idt);
  1744. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1745. return temp_forward_decl;
  1746. }
  1747. }
  1748. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1749. lb_set_llvm_metadata(m, type, dt);
  1750. return dt;
  1751. }
  1752. void lb_debug_complete_types(lbModule *m) {
  1753. unsigned const word_size = cast(unsigned)build_context.word_size;
  1754. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1755. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1756. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1757. GB_ASSERT(idt.type != nullptr);
  1758. GB_ASSERT(idt.metadata != nullptr);
  1759. Type *t = idt.type;
  1760. Type *bt = base_type(t);
  1761. LLVMMetadataRef parent_scope = nullptr;
  1762. LLVMMetadataRef file = nullptr;
  1763. unsigned line_number = 0;
  1764. u64 size_in_bits = 8*type_size_of(t);
  1765. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1766. LLVMDIFlags flags = LLVMDIFlagZero;
  1767. LLVMMetadataRef derived_from = nullptr;
  1768. LLVMMetadataRef *elements = nullptr;
  1769. unsigned element_count = 0;
  1770. unsigned runtime_lang = 0; // Objective-C runtime version
  1771. char const *unique_id = "";
  1772. LLVMMetadataRef vtable_holder = nullptr;
  1773. size_t unique_id_len = 0;
  1774. LLVMMetadataRef record_scope = nullptr;
  1775. switch (bt->kind) {
  1776. case Type_Slice:
  1777. case Type_DynamicArray:
  1778. case Type_Map:
  1779. case Type_Struct:
  1780. case Type_Union:
  1781. case Type_BitSet: {
  1782. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1783. String name = str_lit("<anonymous-struct>");
  1784. if (t->kind == Type_Named) {
  1785. name = t->Named.name;
  1786. if (t->Named.type_name && t->Named.type_name->pkg && t->Named.type_name->pkg->name.len != 0) {
  1787. name = concatenate3_strings(temporary_allocator(), t->Named.type_name->pkg->name, str_lit("."), t->Named.name);
  1788. }
  1789. LLVMMetadataRef file = nullptr;
  1790. unsigned line = 0;
  1791. LLVMMetadataRef file_scope = nullptr;
  1792. if (t->Named.type_name != nullptr) {
  1793. Entity *e = t->Named.type_name;
  1794. file_scope = lb_get_llvm_metadata(m, e->scope);
  1795. if (file_scope != nullptr) {
  1796. file = LLVMDIScopeGetFile(file_scope);
  1797. }
  1798. line = cast(unsigned)e->token.pos.line;
  1799. }
  1800. // TODO(bill): location data for Type_Named
  1801. } else {
  1802. name = make_string_c(type_to_string(t, temporary_allocator()));
  1803. }
  1804. switch (bt->kind) {
  1805. case Type_Slice:
  1806. element_count = 2;
  1807. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1808. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->Slice.elem), 0*word_bits);
  1809. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1810. break;
  1811. case Type_DynamicArray:
  1812. element_count = 4;
  1813. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1814. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->DynamicArray.elem), 0*word_bits);
  1815. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1816. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1817. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1818. break;
  1819. case Type_Map:
  1820. bt = bt->Map.internal_type;
  1821. /*fallthrough*/
  1822. case Type_Struct:
  1823. if (file == nullptr) {
  1824. if (bt->Struct.node) {
  1825. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1826. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1827. }
  1828. }
  1829. type_set_offsets(bt);
  1830. {
  1831. isize element_offset = 0;
  1832. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  1833. switch (bt->Struct.soa_kind) {
  1834. case StructSoa_Slice: element_offset = 1; break;
  1835. case StructSoa_Dynamic: element_offset = 3; break;
  1836. }
  1837. element_count = cast(unsigned)(bt->Struct.fields.count + element_offset);
  1838. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1839. switch (bt->Struct.soa_kind) {
  1840. case StructSoa_Slice:
  1841. elements[0] = LLVMDIBuilderCreateMemberType(
  1842. m->debug_builder, record_scope,
  1843. ".len", 4,
  1844. file, 0,
  1845. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1846. 8*type_size_of(bt)-word_bits,
  1847. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1848. );
  1849. break;
  1850. case StructSoa_Dynamic:
  1851. elements[0] = LLVMDIBuilderCreateMemberType(
  1852. m->debug_builder, record_scope,
  1853. ".len", 4,
  1854. file, 0,
  1855. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1856. 8*type_size_of(bt)-word_bits + 0*word_bits,
  1857. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1858. );
  1859. elements[1] = LLVMDIBuilderCreateMemberType(
  1860. m->debug_builder, record_scope,
  1861. ".cap", 4,
  1862. file, 0,
  1863. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1864. 8*type_size_of(bt)-word_bits + 1*word_bits,
  1865. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1866. );
  1867. elements[3] = LLVMDIBuilderCreateMemberType(
  1868. m->debug_builder, record_scope,
  1869. ".allocator", 12,
  1870. file, 0,
  1871. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1872. 8*type_size_of(bt)-word_bits + 2*word_bits,
  1873. LLVMDIFlagZero, lb_debug_type(m, t_allocator)
  1874. );
  1875. break;
  1876. }
  1877. for_array(j, bt->Struct.fields) {
  1878. Entity *f = bt->Struct.fields[j];
  1879. String fname = f->token.string;
  1880. unsigned field_line = 0;
  1881. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1882. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  1883. elements[element_offset+j] = LLVMDIBuilderCreateMemberType(
  1884. m->debug_builder, record_scope,
  1885. cast(char const *)fname.text, cast(size_t)fname.len,
  1886. file, field_line,
  1887. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  1888. offset_in_bits,
  1889. field_flags, lb_debug_type(m, f->type)
  1890. );
  1891. }
  1892. }
  1893. break;
  1894. case Type_Union:
  1895. {
  1896. if (file == nullptr) {
  1897. GB_ASSERT(bt->Union.node != nullptr);
  1898. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  1899. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  1900. }
  1901. isize index_offset = 1;
  1902. if (is_type_union_maybe_pointer(bt)) {
  1903. index_offset = 0;
  1904. }
  1905. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  1906. element_count = cast(unsigned)bt->Union.variants.count;
  1907. if (index_offset > 0) {
  1908. element_count += 1;
  1909. }
  1910. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1911. if (index_offset > 0) {
  1912. Type *tag_type = union_tag_type(bt);
  1913. unsigned field_line = 0;
  1914. u64 offset_in_bits = 8*cast(u64)bt->Union.variant_block_size;
  1915. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1916. elements[0] = LLVMDIBuilderCreateMemberType(
  1917. m->debug_builder, record_scope,
  1918. "tag", 3,
  1919. file, field_line,
  1920. 8*cast(u64)type_size_of(tag_type), 8*cast(u32)type_align_of(tag_type),
  1921. offset_in_bits,
  1922. field_flags, lb_debug_type(m, tag_type)
  1923. );
  1924. }
  1925. for_array(j, bt->Union.variants) {
  1926. Type *variant = bt->Union.variants[j];
  1927. unsigned field_index = cast(unsigned)(index_offset+j);
  1928. char name[16] = {};
  1929. gb_snprintf(name, gb_size_of(name), "v%u", field_index);
  1930. isize name_len = gb_strlen(name);
  1931. unsigned field_line = 0;
  1932. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1933. u64 offset_in_bits = 0;
  1934. elements[field_index] = LLVMDIBuilderCreateMemberType(
  1935. m->debug_builder, record_scope,
  1936. name, name_len,
  1937. file, field_line,
  1938. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  1939. offset_in_bits,
  1940. field_flags, lb_debug_type(m, variant)
  1941. );
  1942. }
  1943. }
  1944. break;
  1945. case Type_BitSet:
  1946. {
  1947. if (file == nullptr) {
  1948. GB_ASSERT(bt->BitSet.node != nullptr);
  1949. file = lb_get_llvm_metadata(m, bt->BitSet.node->file);
  1950. line_number = cast(unsigned)ast_token(bt->BitSet.node).pos.line;
  1951. }
  1952. LLVMMetadataRef bit_set_field_type = lb_debug_type(m, t_bool);
  1953. LLVMMetadataRef scope = file;
  1954. Type *elem = base_type(bt->BitSet.elem);
  1955. if (elem->kind == Type_Enum) {
  1956. element_count = cast(unsigned)elem->Enum.fields.count;
  1957. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1958. for_array(i, elem->Enum.fields) {
  1959. Entity *f = elem->Enum.fields[i];
  1960. GB_ASSERT(f->kind == Entity_Constant);
  1961. i64 val = exact_value_to_i64(f->Constant.value);
  1962. String name = f->token.string;
  1963. u64 offset_in_bits = cast(u64)(val - bt->BitSet.lower);
  1964. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1965. m->debug_builder,
  1966. scope,
  1967. cast(char const *)name.text, name.len,
  1968. file, line_number,
  1969. 1,
  1970. offset_in_bits,
  1971. 0,
  1972. LLVMDIFlagZero,
  1973. bit_set_field_type
  1974. );
  1975. }
  1976. } else {
  1977. char name[32] = {};
  1978. GB_ASSERT(is_type_integer(elem));
  1979. i64 count = bt->BitSet.upper - bt->BitSet.lower + 1;
  1980. GB_ASSERT(0 <= count);
  1981. element_count = cast(unsigned)count;
  1982. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1983. for (unsigned i = 0; i < element_count; i++) {
  1984. u64 offset_in_bits = i;
  1985. i64 val = bt->BitSet.lower + cast(i64)i;
  1986. gb_snprintf(name, gb_count_of(name), "%lld", cast(long long)val);
  1987. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1988. m->debug_builder,
  1989. scope,
  1990. name, gb_strlen(name),
  1991. file, line_number,
  1992. 1,
  1993. offset_in_bits,
  1994. 0,
  1995. LLVMDIFlagZero,
  1996. bit_set_field_type
  1997. );
  1998. }
  1999. }
  2000. }
  2001. }
  2002. LLVMMetadataRef final_metadata = nullptr;
  2003. if (is_union) {
  2004. final_metadata = LLVMDIBuilderCreateUnionType(
  2005. m->debug_builder,
  2006. parent_scope,
  2007. cast(char const *)name.text, cast(size_t)name.len,
  2008. file, line_number,
  2009. size_in_bits, align_in_bits,
  2010. flags,
  2011. elements, element_count,
  2012. runtime_lang,
  2013. unique_id, unique_id_len
  2014. );
  2015. } else {
  2016. final_metadata = LLVMDIBuilderCreateStructType(
  2017. m->debug_builder,
  2018. parent_scope,
  2019. cast(char const *)name.text, cast(size_t)name.len,
  2020. file, line_number,
  2021. size_in_bits, align_in_bits,
  2022. flags,
  2023. derived_from,
  2024. elements, element_count,
  2025. runtime_lang,
  2026. vtable_holder,
  2027. unique_id, unique_id_len
  2028. );
  2029. }
  2030. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  2031. lb_set_llvm_metadata(m, idt.type, final_metadata);
  2032. } break;
  2033. default:
  2034. GB_PANIC("invalid incomplete debug type");
  2035. break;
  2036. }
  2037. }
  2038. array_clear(&m->debug_incomplete_types);
  2039. }
  2040. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  2041. if (e != nullptr) {
  2042. map_set(&m->values, hash_entity(e), val);
  2043. }
  2044. }
  2045. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  2046. if (name.len > 0) {
  2047. string_map_set(&m->members, name, val);
  2048. }
  2049. }
  2050. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  2051. string_map_set(&m->members, key, val);
  2052. }
  2053. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  2054. if (p->entity != nullptr) {
  2055. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  2056. }
  2057. string_map_set(&m->procedures, p->name, p);
  2058. }
  2059. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  2060. LLVMTypeRef src = LLVMTypeOf(val);
  2061. if (src == dst) {
  2062. return val;
  2063. }
  2064. if (LLVMIsNull(val)) {
  2065. return LLVMConstNull(dst);
  2066. }
  2067. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  2068. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  2069. switch (kind) {
  2070. case LLVMPointerTypeKind:
  2071. return LLVMConstPointerCast(val, dst);
  2072. case LLVMStructTypeKind:
  2073. return LLVMConstBitCast(val, dst);
  2074. default:
  2075. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  2076. }
  2077. return val;
  2078. }
  2079. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  2080. unsigned value_count = cast(unsigned)value_count_;
  2081. unsigned elem_count = LLVMCountStructElementTypes(t);
  2082. GB_ASSERT(value_count == elem_count);
  2083. for (unsigned i = 0; i < elem_count; i++) {
  2084. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  2085. values[i] = llvm_const_cast(values[i], elem_type);
  2086. }
  2087. return LLVMConstNamedStruct(t, values, value_count);
  2088. }
  2089. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  2090. unsigned value_count = cast(unsigned)value_count_;
  2091. for (unsigned i = 0; i < value_count; i++) {
  2092. values[i] = llvm_const_cast(values[i], elem_type);
  2093. }
  2094. return LLVMConstArray(elem_type, values, value_count);
  2095. }
  2096. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  2097. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  2098. LLVMValueRef values[2] = {
  2099. str_elem.value,
  2100. str_len.value,
  2101. };
  2102. lbValue res = {};
  2103. res.type = t_string;
  2104. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  2105. return res;
  2106. } else {
  2107. lbAddr res = lb_add_local_generated(p, t_string, false);
  2108. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  2109. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  2110. return lb_addr_load(p, res);
  2111. }
  2112. }
  2113. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  2114. String s = make_string_c(name);
  2115. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2116. // and the current LLVM C API does not expose this functionality yet.
  2117. // It is better to ignore the attributes for the time being
  2118. if (s == "byval") {
  2119. return nullptr;
  2120. } else if (s == "byref") {
  2121. return nullptr;
  2122. } else if (s == "preallocated") {
  2123. return nullptr;
  2124. } else if (s == "sret") {
  2125. return nullptr;
  2126. }
  2127. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2128. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2129. return LLVMCreateEnumAttribute(ctx, kind, value);
  2130. }
  2131. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  2132. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  2133. GB_ASSERT(attr != nullptr);
  2134. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  2135. }
  2136. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  2137. lb_add_proc_attribute_at_index(p, index, name, 0);
  2138. }
  2139. void lb_add_attribute_to_proc(lbModule *m, LLVMValueRef proc_value, char const *name, u64 value=0) {
  2140. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(m->ctx, name, value));
  2141. }
  2142. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2143. if (p->abi_function_type != nullptr) {
  2144. return;
  2145. }
  2146. auto hash = hash_type(p->type);
  2147. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  2148. if (ft_found == nullptr) {
  2149. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2150. ft_found = map_get(&m->function_type_map, hash);
  2151. }
  2152. GB_ASSERT(ft_found != nullptr);
  2153. p->abi_function_type = *ft_found;
  2154. GB_ASSERT(p->abi_function_type != nullptr);
  2155. }
  2156. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  2157. GB_ASSERT(entity != nullptr);
  2158. String link_name = lb_get_entity_name(m, entity);
  2159. {
  2160. StringHashKey key = string_hash_string(link_name);
  2161. lbValue *found = string_map_get(&m->members, key);
  2162. if (found) {
  2163. lb_add_entity(m, entity, *found);
  2164. lbProcedure **p_found = string_map_get(&m->procedures, key);
  2165. GB_ASSERT(p_found != nullptr);
  2166. return *p_found;
  2167. }
  2168. }
  2169. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2170. p->module = m;
  2171. entity->code_gen_module = m;
  2172. entity->code_gen_procedure = p;
  2173. p->entity = entity;
  2174. p->name = link_name;
  2175. DeclInfo *decl = entity->decl_info;
  2176. ast_node(pl, ProcLit, decl->proc_lit);
  2177. Type *pt = base_type(entity->type);
  2178. GB_ASSERT(pt->kind == Type_Proc);
  2179. p->type = entity->type;
  2180. p->type_expr = decl->type_expr;
  2181. p->body = pl->body;
  2182. p->inlining = pl->inlining;
  2183. p->is_foreign = entity->Procedure.is_foreign;
  2184. p->is_export = entity->Procedure.is_export;
  2185. p->is_entry_point = false;
  2186. gbAllocator a = heap_allocator();
  2187. p->children.allocator = a;
  2188. p->params.allocator = a;
  2189. p->defer_stmts.allocator = a;
  2190. p->blocks.allocator = a;
  2191. p->branch_blocks.allocator = a;
  2192. p->context_stack.allocator = a;
  2193. p->scope_stack.allocator = a;
  2194. if (p->is_foreign) {
  2195. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2196. }
  2197. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2198. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2199. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2200. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2201. lb_ensure_abi_function_type(m, p);
  2202. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2203. if (false) {
  2204. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2205. // TODO(bill): Clean up this logic
  2206. if (build_context.metrics.os != TargetOs_js) {
  2207. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2208. }
  2209. LLVMSetFunctionCallConv(p->value, cc_kind);
  2210. }
  2211. if (pt->Proc.diverging) {
  2212. lb_add_attribute_to_proc(m, p->value, "noreturn");
  2213. }
  2214. if (pt->Proc.calling_convention == ProcCC_Naked) {
  2215. lb_add_attribute_to_proc(m, p->value, "naked");
  2216. }
  2217. switch (p->inlining) {
  2218. case ProcInlining_inline:
  2219. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  2220. break;
  2221. case ProcInlining_no_inline:
  2222. lb_add_attribute_to_proc(m, p->value, "noinline");
  2223. break;
  2224. }
  2225. if (entity->flags & EntityFlag_Cold) {
  2226. lb_add_attribute_to_proc(m, p->value, "cold");
  2227. }
  2228. switch (entity->Procedure.optimization_mode) {
  2229. case ProcedureOptimizationMode_None:
  2230. lb_add_attribute_to_proc(m, p->value, "optnone");
  2231. break;
  2232. case ProcedureOptimizationMode_Minimal:
  2233. lb_add_attribute_to_proc(m, p->value, "optnone");
  2234. break;
  2235. case ProcedureOptimizationMode_Size:
  2236. lb_add_attribute_to_proc(m, p->value, "optsize");
  2237. break;
  2238. case ProcedureOptimizationMode_Speed:
  2239. // TODO(bill): handle this correctly
  2240. lb_add_attribute_to_proc(m, p->value, "optsize");
  2241. break;
  2242. }
  2243. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2244. // // TODO(bill): Clean up this logic
  2245. // if (build_context.metrics.os != TargetOs_js) {
  2246. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2247. // }
  2248. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2249. lbValue proc_value = {p->value, p->type};
  2250. lb_add_entity(m, entity, proc_value);
  2251. lb_add_member(m, p->name, proc_value);
  2252. lb_add_procedure_value(m, p);
  2253. if (p->is_export) {
  2254. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2255. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2256. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2257. if (build_context.metrics.os == TargetOs_js) {
  2258. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2259. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2260. }
  2261. }
  2262. if (p->is_foreign) {
  2263. if (build_context.metrics.os == TargetOs_js) {
  2264. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2265. char const *module_name = "env";
  2266. if (entity->Procedure.foreign_library != nullptr) {
  2267. Entity *foreign_library = entity->Procedure.foreign_library;
  2268. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2269. if (foreign_library->LibraryName.paths.count > 0) {
  2270. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2271. }
  2272. }
  2273. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2274. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2275. }
  2276. }
  2277. // NOTE(bill): offset==0 is the return value
  2278. isize offset = 1;
  2279. if (pt->Proc.return_by_pointer) {
  2280. offset = 2;
  2281. }
  2282. isize parameter_index = 0;
  2283. if (pt->Proc.param_count) {
  2284. TypeTuple *params = &pt->Proc.params->Tuple;
  2285. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2286. Entity *e = params->variables[i];
  2287. Type *original_type = e->type;
  2288. if (e->kind != Entity_Variable) continue;
  2289. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2290. continue;
  2291. }
  2292. if (e->flags&EntityFlag_NoAlias) {
  2293. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2294. }
  2295. parameter_index += 1;
  2296. }
  2297. }
  2298. if (m->debug_builder) { // Debug Information
  2299. Type *bt = base_type(p->type);
  2300. unsigned line = cast(unsigned)entity->token.pos.line;
  2301. LLVMMetadataRef scope = nullptr;
  2302. LLVMMetadataRef file = nullptr;
  2303. LLVMMetadataRef type = nullptr;
  2304. scope = p->module->debug_compile_unit;
  2305. type = lb_debug_type_internal_proc(m, bt);
  2306. if (entity->file != nullptr) {
  2307. file = lb_get_llvm_metadata(m, entity->file);
  2308. scope = file;
  2309. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2310. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2311. scope = file;
  2312. } else if (entity->scope != nullptr) {
  2313. file = lb_get_llvm_metadata(m, entity->scope->file);
  2314. scope = file;
  2315. }
  2316. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2317. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2318. LLVMBool is_local_to_unit = false;
  2319. LLVMBool is_definition = p->body != nullptr;
  2320. unsigned scope_line = line;
  2321. u32 flags = LLVMDIFlagStaticMember;
  2322. LLVMBool is_optimized = false;
  2323. if (bt->Proc.diverging) {
  2324. flags |= LLVMDIFlagNoReturn;
  2325. }
  2326. if (p->body == nullptr) {
  2327. flags |= LLVMDIFlagPrototyped;
  2328. is_optimized = false;
  2329. }
  2330. if (p->body != nullptr) {
  2331. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2332. cast(char const *)entity->token.string.text, entity->token.string.len,
  2333. cast(char const *)p->name.text, p->name.len,
  2334. file, line, type,
  2335. is_local_to_unit, is_definition,
  2336. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2337. );
  2338. GB_ASSERT(p->debug_info != nullptr);
  2339. LLVMSetSubprogram(p->value, p->debug_info);
  2340. lb_set_llvm_metadata(m, p, p->debug_info);
  2341. }
  2342. }
  2343. return p;
  2344. }
  2345. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2346. {
  2347. lbValue *found = string_map_get(&m->members, link_name);
  2348. GB_ASSERT(found == nullptr);
  2349. }
  2350. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2351. p->module = m;
  2352. p->name = link_name;
  2353. p->type = type;
  2354. p->type_expr = nullptr;
  2355. p->body = nullptr;
  2356. p->tags = 0;
  2357. p->inlining = ProcInlining_none;
  2358. p->is_foreign = false;
  2359. p->is_export = false;
  2360. p->is_entry_point = false;
  2361. gbAllocator a = permanent_allocator();
  2362. p->children.allocator = a;
  2363. p->params.allocator = a;
  2364. p->defer_stmts.allocator = a;
  2365. p->blocks.allocator = a;
  2366. p->branch_blocks.allocator = a;
  2367. p->context_stack.allocator = a;
  2368. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2369. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2370. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2371. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2372. Type *pt = p->type;
  2373. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2374. // TODO(bill): Clean up this logic
  2375. if (build_context.metrics.os != TargetOs_js) {
  2376. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2377. }
  2378. LLVMSetFunctionCallConv(p->value, cc_kind);
  2379. lbValue proc_value = {p->value, p->type};
  2380. lb_add_member(m, p->name, proc_value);
  2381. lb_add_procedure_value(m, p);
  2382. // NOTE(bill): offset==0 is the return value
  2383. isize offset = 1;
  2384. if (pt->Proc.return_by_pointer) {
  2385. lb_add_proc_attribute_at_index(p, 1, "sret");
  2386. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2387. offset = 2;
  2388. }
  2389. isize parameter_index = 0;
  2390. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2391. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2392. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2393. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2394. }
  2395. return p;
  2396. }
  2397. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2398. lbParamPasskind kind = lbParamPass_Value;
  2399. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2400. if (is_type_pointer(abi_type)) {
  2401. GB_ASSERT(e->kind == Entity_Variable);
  2402. Type *av = core_type(type_deref(abi_type));
  2403. if (are_types_identical(av, core_type(e->type))) {
  2404. kind = lbParamPass_Pointer;
  2405. if (e->flags&EntityFlag_Value) {
  2406. kind = lbParamPass_ConstRef;
  2407. }
  2408. } else {
  2409. kind = lbParamPass_BitCast;
  2410. }
  2411. } else if (is_type_integer(abi_type)) {
  2412. kind = lbParamPass_Integer;
  2413. } else if (abi_type == t_llvm_bool) {
  2414. kind = lbParamPass_Value;
  2415. } else if (is_type_boolean(abi_type)) {
  2416. kind = lbParamPass_Integer;
  2417. } else if (is_type_simd_vector(abi_type)) {
  2418. kind = lbParamPass_BitCast;
  2419. } else if (is_type_float(abi_type)) {
  2420. kind = lbParamPass_BitCast;
  2421. } else if (is_type_tuple(abi_type)) {
  2422. kind = lbParamPass_Tuple;
  2423. } else if (is_type_proc(abi_type)) {
  2424. kind = lbParamPass_Value;
  2425. } else {
  2426. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2427. }
  2428. }
  2429. if (kind_) *kind_ = kind;
  2430. lbValue res = {};
  2431. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2432. res.type = abi_type;
  2433. return res;
  2434. }
  2435. Type *struct_type_from_systemv_distribute_struct_fields(Type *abi_type) {
  2436. GB_ASSERT(is_type_tuple(abi_type));
  2437. Type *final_type = alloc_type_struct();
  2438. final_type->Struct.fields = abi_type->Tuple.variables;
  2439. return final_type;
  2440. }
  2441. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  2442. lbParamPasskind kind = lbParamPass_Value;
  2443. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  2444. array_add(&p->params, v);
  2445. lbValue res = {};
  2446. switch (kind) {
  2447. case lbParamPass_Value: {
  2448. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2449. lbValue x = v;
  2450. if (abi_type == t_llvm_bool) {
  2451. x = lb_emit_conv(p, x, t_bool);
  2452. }
  2453. lb_addr_store(p, l, x);
  2454. return x;
  2455. }
  2456. case lbParamPass_Pointer:
  2457. lb_add_entity(p->module, e, v);
  2458. return lb_emit_load(p, v);
  2459. case lbParamPass_Integer: {
  2460. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2461. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  2462. lb_emit_store(p, iptr, v);
  2463. return lb_addr_load(p, l);
  2464. }
  2465. case lbParamPass_ConstRef:
  2466. lb_add_entity(p->module, e, v);
  2467. return lb_emit_load(p, v);
  2468. case lbParamPass_BitCast: {
  2469. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2470. lbValue x = lb_emit_transmute(p, v, e->type);
  2471. lb_addr_store(p, l, x);
  2472. return x;
  2473. }
  2474. case lbParamPass_Tuple: {
  2475. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2476. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2477. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2478. if (abi_type->Tuple.variables.count > 0) {
  2479. array_pop(&p->params);
  2480. }
  2481. for_array(i, abi_type->Tuple.variables) {
  2482. Type *t = abi_type->Tuple.variables[i]->type;
  2483. GB_ASSERT(!is_type_tuple(t));
  2484. lbParamPasskind elem_kind = lbParamPass_Value;
  2485. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2486. array_add(&p->params, elem);
  2487. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2488. lb_emit_store(p, dst, elem);
  2489. }
  2490. return lb_addr_load(p, l);
  2491. }
  2492. }
  2493. GB_PANIC("Unreachable");
  2494. return {};
  2495. }
  2496. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2497. GB_ASSERT(b != nullptr);
  2498. if (!b->appended) {
  2499. b->appended = true;
  2500. LLVMAppendExistingBasicBlock(p->value, b->block);
  2501. }
  2502. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2503. p->curr_block = b;
  2504. }
  2505. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2506. LLVMContextRef ctx = p->module->ctx;
  2507. LLVMTypeRef src_type = LLVMTypeOf(val);
  2508. if (src_type == dst_type) {
  2509. return val;
  2510. }
  2511. i64 src_size = lb_sizeof(src_type);
  2512. i64 dst_size = lb_sizeof(dst_type);
  2513. i64 src_align = lb_alignof(src_type);
  2514. i64 dst_align = lb_alignof(dst_type);
  2515. if (LLVMIsALoadInst(val)) {
  2516. src_align = gb_min(src_align, LLVMGetAlignment(val));
  2517. }
  2518. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2519. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2520. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2521. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2522. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2523. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2524. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2525. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2526. }
  2527. if (src_size != dst_size) {
  2528. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2529. // Okay
  2530. } else {
  2531. goto general_end;
  2532. }
  2533. }
  2534. if (src_kind == dst_kind) {
  2535. if (src_kind == LLVMPointerTypeKind) {
  2536. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2537. } else if (src_kind == LLVMArrayTypeKind) {
  2538. // ignore
  2539. } else if (src_kind != LLVMStructTypeKind) {
  2540. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2541. }
  2542. } else {
  2543. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2544. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2545. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2546. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2547. }
  2548. }
  2549. general_end:;
  2550. // make the alignment big if necessary
  2551. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  2552. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2553. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  2554. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  2555. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  2556. }
  2557. }
  2558. src_size = align_formula(src_size, src_align);
  2559. dst_size = align_formula(dst_size, dst_align);
  2560. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  2561. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2562. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2563. LLVMValueRef loaded_val = LLVMBuildLoad(p->builder, val_ptr, "");
  2564. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  2565. return loaded_val;
  2566. } else {
  2567. GB_ASSERT(p->decl_block != p->curr_block);
  2568. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2569. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2570. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2571. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2572. max_align = gb_max(max_align, 4);
  2573. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2574. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2575. LLVMBuildStore(p->builder, val, nptr);
  2576. return LLVMBuildLoad(p->builder, ptr, "");
  2577. }
  2578. }
  2579. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2580. if (p->debug_info == nullptr) {
  2581. return;
  2582. }
  2583. if (type == nullptr) {
  2584. return;
  2585. }
  2586. if (type == t_invalid) {
  2587. return;
  2588. }
  2589. if (p->body == nullptr) {
  2590. return;
  2591. }
  2592. lbModule *m = p->module;
  2593. String const &name = token.string;
  2594. if (name == "" || name == "_") {
  2595. return;
  2596. }
  2597. if (lb_get_llvm_metadata(m, ptr) != nullptr) {
  2598. // Already been set
  2599. return;
  2600. }
  2601. AstFile *file = p->body->file;
  2602. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2603. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2604. GB_ASSERT(llvm_scope != nullptr);
  2605. if (llvm_file == nullptr) {
  2606. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2607. }
  2608. if (llvm_file == nullptr) {
  2609. return;
  2610. }
  2611. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2612. LLVMDIFlags flags = LLVMDIFlagZero;
  2613. LLVMBool always_preserve = build_context.optimization_level == 0;
  2614. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2615. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2616. m->debug_builder, llvm_scope,
  2617. cast(char const *)name.text, cast(size_t)name.len,
  2618. llvm_file, token.pos.line,
  2619. debug_type,
  2620. always_preserve, flags, alignment_in_bits
  2621. );
  2622. LLVMValueRef storage = ptr;
  2623. LLVMValueRef instr = ptr;
  2624. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2625. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2626. lb_set_llvm_metadata(m, ptr, llvm_expr);
  2627. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2628. }
  2629. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2630. if (!p->debug_info || !p->body) {
  2631. return;
  2632. }
  2633. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2634. if (!loc) {
  2635. return;
  2636. }
  2637. TokenPos pos = {};
  2638. pos.file_id = p->body->file ? p->body->file->id : 0;
  2639. pos.line = LLVMDILocationGetLine(loc);
  2640. pos.column = LLVMDILocationGetColumn(loc);
  2641. Token token = {};
  2642. token.kind = Token_context;
  2643. token.string = str_lit("context");
  2644. token.pos = pos;
  2645. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2646. }
  2647. void lb_begin_procedure_body(lbProcedure *p) {
  2648. DeclInfo *decl = decl_info_of_entity(p->entity);
  2649. if (decl != nullptr) {
  2650. for_array(i, decl->labels) {
  2651. BlockLabel bl = decl->labels[i];
  2652. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2653. array_add(&p->branch_blocks, bb);
  2654. }
  2655. }
  2656. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  2657. p->decl_block = lb_create_block(p, "decls", true);
  2658. p->entry_block = lb_create_block(p, "entry", true);
  2659. lb_start_block(p, p->entry_block);
  2660. GB_ASSERT(p->type != nullptr);
  2661. lb_ensure_abi_function_type(p->module, p);
  2662. {
  2663. lbFunctionType *ft = p->abi_function_type;
  2664. unsigned param_offset = 0;
  2665. lbValue return_ptr_value = {};
  2666. if (ft->ret.kind == lbArg_Indirect) {
  2667. // NOTE(bill): this must be parameter 0
  2668. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2669. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2670. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2671. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2672. return_ptr_value.type = ptr_type;
  2673. p->return_ptr = lb_addr(return_ptr_value);
  2674. lb_add_entity(p->module, e, return_ptr_value);
  2675. param_offset += 1;
  2676. }
  2677. if (p->type->Proc.params != nullptr) {
  2678. TypeTuple *params = &p->type->Proc.params->Tuple;
  2679. unsigned param_index = 0;
  2680. for_array(i, params->variables) {
  2681. Entity *e = params->variables[i];
  2682. if (e->kind != Entity_Variable) {
  2683. continue;
  2684. }
  2685. lbArgType *arg_type = &ft->args[param_index];
  2686. if (arg_type->kind == lbArg_Ignore) {
  2687. continue;
  2688. } else if (arg_type->kind == lbArg_Direct) {
  2689. lbParamPasskind kind = lbParamPass_Value;
  2690. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2691. if (param_type != arg_type->type) {
  2692. kind = lbParamPass_BitCast;
  2693. }
  2694. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2695. value = OdinLLVMBuildTransmute(p, value, param_type);
  2696. lbValue param = {};
  2697. param.value = value;
  2698. param.type = e->type;
  2699. array_add(&p->params, param);
  2700. if (e->token.string.len != 0) {
  2701. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2702. lb_addr_store(p, l, param);
  2703. }
  2704. param_index += 1;
  2705. } else if (arg_type->kind == lbArg_Indirect) {
  2706. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2707. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2708. lbValue param = {};
  2709. param.value = value;
  2710. param.type = e->type;
  2711. array_add(&p->params, param);
  2712. lbValue ptr = {};
  2713. ptr.value = value_ptr;
  2714. ptr.type = alloc_type_pointer(e->type);
  2715. lb_add_entity(p->module, e, ptr);
  2716. param_index += 1;
  2717. }
  2718. }
  2719. }
  2720. if (p->type->Proc.has_named_results) {
  2721. GB_ASSERT(p->type->Proc.result_count > 0);
  2722. TypeTuple *results = &p->type->Proc.results->Tuple;
  2723. for_array(i, results->variables) {
  2724. Entity *e = results->variables[i];
  2725. GB_ASSERT(e->kind == Entity_Variable);
  2726. if (e->token.string != "") {
  2727. GB_ASSERT(!is_blank_ident(e->token));
  2728. lbAddr res = {};
  2729. if (return_ptr_value.value) {
  2730. lbValue ptr = return_ptr_value;
  2731. if (results->variables.count != 1) {
  2732. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2733. }
  2734. res = lb_addr(ptr);
  2735. lb_add_entity(p->module, e, ptr);
  2736. } else {
  2737. res = lb_add_local(p, e->type, e);
  2738. }
  2739. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2740. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2741. lb_addr_store(p, res, c);
  2742. }
  2743. }
  2744. }
  2745. }
  2746. }
  2747. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2748. lb_push_context_onto_stack_from_implicit_parameter(p);
  2749. }
  2750. lb_start_block(p, p->entry_block);
  2751. if (p->debug_info != nullptr) {
  2752. TokenPos pos = {};
  2753. if (p->body != nullptr) {
  2754. pos = ast_token(p->body).pos;
  2755. } else if (p->type_expr != nullptr) {
  2756. pos = ast_token(p->type_expr).pos;
  2757. } else if (p->entity != nullptr) {
  2758. pos = p->entity->token.pos;
  2759. }
  2760. if (pos.file_id != 0) {
  2761. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2762. }
  2763. if (p->context_stack.count != 0) {
  2764. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2765. }
  2766. }
  2767. }
  2768. void lb_end_procedure_body(lbProcedure *p) {
  2769. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2770. LLVMBuildBr(p->builder, p->entry_block->block);
  2771. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2772. // Make sure there is a "ret void" at the end of a procedure with no return type
  2773. if (p->type->Proc.result_count == 0) {
  2774. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2775. if (!lb_is_instr_terminating(instr)) {
  2776. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2777. LLVMBuildRetVoid(p->builder);
  2778. }
  2779. }
  2780. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2781. LLVMBasicBlockRef block = nullptr;
  2782. // Make sure every block terminates, and if not, make it unreachable
  2783. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2784. LLVMValueRef instr = LLVMGetLastInstruction(block);
  2785. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  2786. LLVMPositionBuilderAtEnd(p->builder, block);
  2787. LLVMBuildUnreachable(p->builder);
  2788. }
  2789. }
  2790. p->curr_block = nullptr;
  2791. p->state_flags = 0;
  2792. }
  2793. void lb_end_procedure(lbProcedure *p) {
  2794. LLVMDisposeBuilder(p->builder);
  2795. }
  2796. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2797. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2798. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2799. array_add(&from->succs, to);
  2800. array_add(&to->preds, from);
  2801. }
  2802. }
  2803. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2804. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2805. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2806. b->appended = false;
  2807. if (append) {
  2808. b->appended = true;
  2809. LLVMAppendExistingBasicBlock(p->value, b->block);
  2810. }
  2811. b->scope = p->curr_scope;
  2812. b->scope_index = p->scope_index;
  2813. b->preds.allocator = heap_allocator();
  2814. b->succs.allocator = heap_allocator();
  2815. array_add(&p->blocks, b);
  2816. return b;
  2817. }
  2818. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2819. if (p->curr_block == nullptr) {
  2820. return;
  2821. }
  2822. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2823. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2824. return;
  2825. }
  2826. lb_add_edge(p->curr_block, target_block);
  2827. LLVMBuildBr(p->builder, target_block->block);
  2828. p->curr_block = nullptr;
  2829. }
  2830. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2831. lbBlock *b = p->curr_block;
  2832. if (b == nullptr) {
  2833. return;
  2834. }
  2835. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2836. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2837. return;
  2838. }
  2839. lb_add_edge(b, true_block);
  2840. lb_add_edge(b, false_block);
  2841. LLVMValueRef cv = cond.value;
  2842. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2843. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2844. }
  2845. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2846. GB_ASSERT(cond != nullptr);
  2847. GB_ASSERT(true_block != nullptr);
  2848. GB_ASSERT(false_block != nullptr);
  2849. switch (cond->kind) {
  2850. case_ast_node(pe, ParenExpr, cond);
  2851. return lb_build_cond(p, pe->expr, true_block, false_block);
  2852. case_end;
  2853. case_ast_node(ue, UnaryExpr, cond);
  2854. if (ue->op.kind == Token_Not) {
  2855. return lb_build_cond(p, ue->expr, false_block, true_block);
  2856. }
  2857. case_end;
  2858. case_ast_node(be, BinaryExpr, cond);
  2859. if (be->op.kind == Token_CmpAnd) {
  2860. lbBlock *block = lb_create_block(p, "cmp.and");
  2861. lb_build_cond(p, be->left, block, false_block);
  2862. lb_start_block(p, block);
  2863. return lb_build_cond(p, be->right, true_block, false_block);
  2864. } else if (be->op.kind == Token_CmpOr) {
  2865. lbBlock *block = lb_create_block(p, "cmp.or");
  2866. lb_build_cond(p, be->left, true_block, block);
  2867. lb_start_block(p, block);
  2868. return lb_build_cond(p, be->right, true_block, false_block);
  2869. }
  2870. case_end;
  2871. }
  2872. lbValue v = lb_build_expr(p, cond);
  2873. // v = lb_emit_conv(p, v, t_bool);
  2874. v = lb_emit_conv(p, v, t_llvm_bool);
  2875. lb_emit_if(p, v, true_block, false_block);
  2876. return v;
  2877. }
  2878. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2879. GB_ASSERT(p->decl_block != p->curr_block);
  2880. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2881. char const *name = "";
  2882. if (e != nullptr) {
  2883. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2884. }
  2885. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2886. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2887. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2888. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2889. LLVMSetAlignment(ptr, alignment);
  2890. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2891. if (!zero_init) {
  2892. // If there is any padding of any kind, just zero init regardless of zero_init parameter
  2893. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2894. if (kind == LLVMStructTypeKind) {
  2895. i64 sz = type_size_of(type);
  2896. if (type_size_of_struct_pretend_is_packed(type) != sz) {
  2897. zero_init = true;
  2898. }
  2899. } else if (kind == LLVMArrayTypeKind) {
  2900. zero_init = true;
  2901. }
  2902. }
  2903. if (zero_init) {
  2904. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2905. switch (kind) {
  2906. case LLVMStructTypeKind:
  2907. case LLVMArrayTypeKind:
  2908. {
  2909. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2910. LLVMTypeRef type_i8 = LLVMInt8TypeInContext(p->module->ctx);
  2911. LLVMTypeRef type_i32 = LLVMInt32TypeInContext(p->module->ctx);
  2912. i32 sz = cast(i32)type_size_of(type);
  2913. LLVMBuildMemSet(p->builder, ptr, LLVMConstNull(type_i8), LLVMConstInt(type_i32, sz, false), alignment);
  2914. }
  2915. break;
  2916. default:
  2917. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2918. break;
  2919. }
  2920. }
  2921. lbValue val = {};
  2922. val.value = ptr;
  2923. val.type = alloc_type_pointer(type);
  2924. if (e != nullptr) {
  2925. lb_add_entity(p->module, e, val);
  2926. lb_add_debug_local_variable(p, ptr, type, e->token);
  2927. }
  2928. return lb_addr(val);
  2929. }
  2930. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2931. return lb_add_local(p, type, nullptr, zero_init);
  2932. }
  2933. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2934. GB_ASSERT(pd->body != nullptr);
  2935. lbModule *m = p->module;
  2936. auto *min_dep_set = &m->info->minimum_dependency_set;
  2937. if (ptr_set_exists(min_dep_set, e) == false) {
  2938. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2939. return;
  2940. }
  2941. // NOTE(bill): Generate a new name
  2942. // parent.name-guid
  2943. String original_name = e->token.string;
  2944. String pd_name = original_name;
  2945. if (e->Procedure.link_name.len > 0) {
  2946. pd_name = e->Procedure.link_name;
  2947. }
  2948. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2949. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2950. i32 guid = cast(i32)p->children.count;
  2951. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2952. String name = make_string(cast(u8 *)name_text, name_len-1);
  2953. e->Procedure.link_name = name;
  2954. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2955. e->code_gen_procedure = nested_proc;
  2956. lbValue value = {};
  2957. value.value = nested_proc->value;
  2958. value.type = nested_proc->type;
  2959. lb_add_entity(m, e, value);
  2960. array_add(&p->children, nested_proc);
  2961. array_add(&m->procedures_to_generate, nested_proc);
  2962. }
  2963. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2964. if (e == nullptr) {
  2965. return;
  2966. }
  2967. GB_ASSERT(e->kind == Entity_LibraryName);
  2968. GB_ASSERT(e->flags & EntityFlag_Used);
  2969. for_array(i, e->LibraryName.paths) {
  2970. String library_path = e->LibraryName.paths[i];
  2971. if (library_path.len == 0) {
  2972. continue;
  2973. }
  2974. bool ok = true;
  2975. for_array(path_index, m->foreign_library_paths) {
  2976. String path = m->foreign_library_paths[path_index];
  2977. #if defined(GB_SYSTEM_WINDOWS)
  2978. if (str_eq_ignore_case(path, library_path)) {
  2979. #else
  2980. if (str_eq(path, library_path)) {
  2981. #endif
  2982. ok = false;
  2983. break;
  2984. }
  2985. }
  2986. if (ok) {
  2987. array_add(&m->foreign_library_paths, library_path);
  2988. }
  2989. }
  2990. }
  2991. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2992. if (vd == nullptr || vd->is_mutable) {
  2993. return;
  2994. }
  2995. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2996. static i32 global_guid = 0;
  2997. for_array(i, vd->names) {
  2998. Ast *ident = vd->names[i];
  2999. GB_ASSERT(ident->kind == Ast_Ident);
  3000. Entity *e = entity_of_node(ident);
  3001. GB_ASSERT(e != nullptr);
  3002. if (e->kind != Entity_TypeName) {
  3003. continue;
  3004. }
  3005. bool polymorphic_struct = false;
  3006. if (e->type != nullptr && e->kind == Entity_TypeName) {
  3007. Type *bt = base_type(e->type);
  3008. if (bt->kind == Type_Struct) {
  3009. polymorphic_struct = bt->Struct.is_polymorphic;
  3010. }
  3011. }
  3012. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  3013. continue;
  3014. }
  3015. if (e->TypeName.ir_mangled_name.len != 0) {
  3016. // NOTE(bill): Already set
  3017. continue;
  3018. }
  3019. lb_set_nested_type_name_ir_mangled_name(e, p);
  3020. }
  3021. for_array(i, vd->names) {
  3022. Ast *ident = vd->names[i];
  3023. GB_ASSERT(ident->kind == Ast_Ident);
  3024. Entity *e = entity_of_node(ident);
  3025. GB_ASSERT(e != nullptr);
  3026. if (e->kind != Entity_Procedure) {
  3027. continue;
  3028. }
  3029. GB_ASSERT (vd->values[i] != nullptr);
  3030. Ast *value = unparen_expr(vd->values[i]);
  3031. if (value->kind != Ast_ProcLit) {
  3032. continue; // It's an alias
  3033. }
  3034. CheckerInfo *info = p->module->info;
  3035. DeclInfo *decl = decl_info_of_entity(e);
  3036. ast_node(pl, ProcLit, decl->proc_lit);
  3037. if (pl->body != nullptr) {
  3038. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  3039. if (found) {
  3040. auto procs = *found;
  3041. for_array(i, procs) {
  3042. Entity *e = procs[i];
  3043. if (!ptr_set_exists(min_dep_set, e)) {
  3044. continue;
  3045. }
  3046. DeclInfo *d = decl_info_of_entity(e);
  3047. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  3048. }
  3049. } else {
  3050. lb_build_nested_proc(p, pl, e);
  3051. }
  3052. } else {
  3053. // FFI - Foreign function interace
  3054. String original_name = e->token.string;
  3055. String name = original_name;
  3056. if (e->Procedure.is_foreign) {
  3057. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  3058. }
  3059. if (e->Procedure.link_name.len > 0) {
  3060. name = e->Procedure.link_name;
  3061. }
  3062. lbValue *prev_value = string_map_get(&p->module->members, name);
  3063. if (prev_value != nullptr) {
  3064. // NOTE(bill): Don't do mutliple declarations in the IR
  3065. return;
  3066. }
  3067. e->Procedure.link_name = name;
  3068. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3069. lbValue value = {};
  3070. value.value = nested_proc->value;
  3071. value.type = nested_proc->type;
  3072. array_add(&p->module->procedures_to_generate, nested_proc);
  3073. if (p != nullptr) {
  3074. array_add(&p->children, nested_proc);
  3075. } else {
  3076. string_map_set(&p->module->members, name, value);
  3077. }
  3078. }
  3079. }
  3080. }
  3081. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  3082. for_array(i, stmts) {
  3083. Ast *stmt = stmts[i];
  3084. switch (stmt->kind) {
  3085. case_ast_node(vd, ValueDecl, stmt);
  3086. lb_build_constant_value_decl(p, vd);
  3087. case_end;
  3088. case_ast_node(fb, ForeignBlockDecl, stmt);
  3089. ast_node(block, BlockStmt, fb->body);
  3090. lb_build_stmt_list(p, block->stmts);
  3091. case_end;
  3092. }
  3093. }
  3094. for_array(i, stmts) {
  3095. lb_build_stmt(p, stmts[i]);
  3096. }
  3097. }
  3098. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  3099. GB_ASSERT(ident->kind == Ast_Ident);
  3100. Entity *e = entity_of_node(ident);
  3101. GB_ASSERT(e->kind == Entity_Label);
  3102. for_array(i, p->branch_blocks) {
  3103. lbBranchBlocks *b = &p->branch_blocks[i];
  3104. if (b->label == e->Label.node) {
  3105. return *b;
  3106. }
  3107. }
  3108. GB_PANIC("Unreachable");
  3109. lbBranchBlocks empty = {};
  3110. return empty;
  3111. }
  3112. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  3113. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  3114. tl->prev = p->target_list;
  3115. tl->break_ = break_;
  3116. tl->continue_ = continue_;
  3117. tl->fallthrough_ = fallthrough_;
  3118. p->target_list = tl;
  3119. if (label != nullptr) { // Set label blocks
  3120. GB_ASSERT(label->kind == Ast_Label);
  3121. for_array(i, p->branch_blocks) {
  3122. lbBranchBlocks *b = &p->branch_blocks[i];
  3123. GB_ASSERT(b->label != nullptr && label != nullptr);
  3124. GB_ASSERT(b->label->kind == Ast_Label);
  3125. if (b->label == label) {
  3126. b->break_ = break_;
  3127. b->continue_ = continue_;
  3128. return tl;
  3129. }
  3130. }
  3131. GB_PANIC("Unreachable");
  3132. }
  3133. return tl;
  3134. }
  3135. void lb_pop_target_list(lbProcedure *p) {
  3136. p->target_list = p->target_list->prev;
  3137. }
  3138. void lb_open_scope(lbProcedure *p, Scope *s) {
  3139. lbModule *m = p->module;
  3140. if (m->debug_builder) {
  3141. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  3142. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  3143. Token token = ast_token(s->node);
  3144. unsigned line = cast(unsigned)token.pos.line;
  3145. unsigned column = cast(unsigned)token.pos.column;
  3146. LLVMMetadataRef file = nullptr;
  3147. if (s->node->file != nullptr) {
  3148. file = lb_get_llvm_metadata(m, s->node->file);
  3149. }
  3150. LLVMMetadataRef scope = nullptr;
  3151. if (p->scope_stack.count > 0) {
  3152. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  3153. }
  3154. if (scope == nullptr) {
  3155. scope = lb_get_llvm_metadata(m, p);
  3156. }
  3157. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  3158. if (m->debug_builder) {
  3159. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  3160. file, line, column
  3161. );
  3162. lb_set_llvm_metadata(m, s, res);
  3163. }
  3164. }
  3165. }
  3166. p->scope_index += 1;
  3167. array_add(&p->scope_stack, s);
  3168. }
  3169. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  3170. lb_emit_defer_stmts(p, kind, block);
  3171. GB_ASSERT(p->scope_index > 0);
  3172. // NOTE(bill): Remove `context`s made in that scope
  3173. while (p->context_stack.count > 0) {
  3174. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  3175. if (ctx->scope_index >= p->scope_index) {
  3176. array_pop(&p->context_stack);
  3177. } else {
  3178. break;
  3179. }
  3180. }
  3181. p->scope_index -= 1;
  3182. array_pop(&p->scope_stack);
  3183. }
  3184. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  3185. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  3186. GB_ASSERT(is_type_boolean(tv.type));
  3187. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  3188. if (tv.value.value_bool) {
  3189. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  3190. } else if (ws->else_stmt) {
  3191. switch (ws->else_stmt->kind) {
  3192. case Ast_BlockStmt:
  3193. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  3194. break;
  3195. case Ast_WhenStmt:
  3196. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  3197. break;
  3198. default:
  3199. GB_PANIC("Invalid 'else' statement in 'when' statement");
  3200. break;
  3201. }
  3202. }
  3203. }
  3204. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  3205. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3206. lbModule *m = p->module;
  3207. lbValue count = {};
  3208. Type *expr_type = base_type(type_deref(expr.type));
  3209. switch (expr_type->kind) {
  3210. case Type_Array:
  3211. count = lb_const_int(m, t_int, expr_type->Array.count);
  3212. break;
  3213. }
  3214. lbValue val = {};
  3215. lbValue idx = {};
  3216. lbBlock *loop = nullptr;
  3217. lbBlock *done = nullptr;
  3218. lbBlock *body = nullptr;
  3219. lbAddr index = lb_add_local_generated(p, t_int, false);
  3220. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  3221. loop = lb_create_block(p, "for.index.loop");
  3222. lb_emit_jump(p, loop);
  3223. lb_start_block(p, loop);
  3224. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  3225. lb_addr_store(p, index, incr);
  3226. body = lb_create_block(p, "for.index.body");
  3227. done = lb_create_block(p, "for.index.done");
  3228. if (count.value == nullptr) {
  3229. GB_ASSERT(count_ptr.value != nullptr);
  3230. count = lb_emit_load(p, count_ptr);
  3231. }
  3232. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3233. lb_emit_if(p, cond, body, done);
  3234. lb_start_block(p, body);
  3235. idx = lb_addr_load(p, index);
  3236. switch (expr_type->kind) {
  3237. case Type_Array: {
  3238. if (val_type != nullptr) {
  3239. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3240. }
  3241. break;
  3242. }
  3243. case Type_EnumeratedArray: {
  3244. if (val_type != nullptr) {
  3245. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3246. // NOTE(bill): Override the idx value for the enumeration
  3247. Type *index_type = expr_type->EnumeratedArray.index;
  3248. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3249. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3250. }
  3251. }
  3252. break;
  3253. }
  3254. case Type_Slice: {
  3255. if (val_type != nullptr) {
  3256. lbValue elem = lb_slice_elem(p, expr);
  3257. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3258. }
  3259. break;
  3260. }
  3261. case Type_DynamicArray: {
  3262. if (val_type != nullptr) {
  3263. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3264. elem = lb_emit_load(p, elem);
  3265. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3266. }
  3267. break;
  3268. }
  3269. case Type_Map: {
  3270. lbValue entries = lb_map_entries_ptr(p, expr);
  3271. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3272. elem = lb_emit_load(p, elem);
  3273. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3274. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3275. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3276. break;
  3277. }
  3278. case Type_Struct: {
  3279. GB_ASSERT(is_type_soa_struct(expr_type));
  3280. break;
  3281. }
  3282. default:
  3283. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3284. break;
  3285. }
  3286. if (val_) *val_ = val;
  3287. if (idx_) *idx_ = idx;
  3288. if (loop_) *loop_ = loop;
  3289. if (done_) *done_ = done;
  3290. }
  3291. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3292. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3293. lbModule *m = p->module;
  3294. lbValue count = lb_const_int(m, t_int, 0);
  3295. Type *expr_type = base_type(expr.type);
  3296. switch (expr_type->kind) {
  3297. case Type_Basic:
  3298. count = lb_string_len(p, expr);
  3299. break;
  3300. default:
  3301. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3302. break;
  3303. }
  3304. lbValue val = {};
  3305. lbValue idx = {};
  3306. lbBlock *loop = nullptr;
  3307. lbBlock *done = nullptr;
  3308. lbBlock *body = nullptr;
  3309. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3310. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3311. loop = lb_create_block(p, "for.string.loop");
  3312. lb_emit_jump(p, loop);
  3313. lb_start_block(p, loop);
  3314. body = lb_create_block(p, "for.string.body");
  3315. done = lb_create_block(p, "for.string.done");
  3316. lbValue offset = lb_addr_load(p, offset_);
  3317. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3318. lb_emit_if(p, cond, body, done);
  3319. lb_start_block(p, body);
  3320. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3321. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3322. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3323. args[0] = lb_emit_string(p, str_elem, str_len);
  3324. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3325. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3326. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3327. idx = offset;
  3328. if (val_type != nullptr) {
  3329. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3330. }
  3331. if (val_) *val_ = val;
  3332. if (idx_) *idx_ = idx;
  3333. if (loop_) *loop_ = loop;
  3334. if (done_) *done_ = done;
  3335. }
  3336. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  3337. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3338. lbModule *m = p->module;
  3339. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  3340. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  3341. lbValue lower = lb_build_expr(p, node->left);
  3342. lbValue upper = {};
  3343. lbValue val = {};
  3344. lbValue idx = {};
  3345. lbBlock *loop = nullptr;
  3346. lbBlock *done = nullptr;
  3347. lbBlock *body = nullptr;
  3348. if (val_type == nullptr) {
  3349. val_type = lower.type;
  3350. }
  3351. lbAddr value = lb_add_local_generated(p, val_type, false);
  3352. lb_addr_store(p, value, lower);
  3353. lbAddr index = lb_add_local_generated(p, t_int, false);
  3354. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3355. loop = lb_create_block(p, "for.interval.loop");
  3356. lb_emit_jump(p, loop);
  3357. lb_start_block(p, loop);
  3358. body = lb_create_block(p, "for.interval.body");
  3359. done = lb_create_block(p, "for.interval.done");
  3360. TokenKind op = Token_Lt;
  3361. switch (node->op.kind) {
  3362. case Token_Ellipsis: op = Token_LtEq; break;
  3363. case Token_RangeHalf: op = Token_Lt; break;
  3364. default: GB_PANIC("Invalid interval operator"); break;
  3365. }
  3366. upper = lb_build_expr(p, node->right);
  3367. lbValue curr_value = lb_addr_load(p, value);
  3368. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3369. lb_emit_if(p, cond, body, done);
  3370. lb_start_block(p, body);
  3371. val = lb_addr_load(p, value);
  3372. idx = lb_addr_load(p, index);
  3373. lb_emit_increment(p, value.addr);
  3374. lb_emit_increment(p, index.addr);
  3375. if (val_) *val_ = val;
  3376. if (idx_) *idx_ = idx;
  3377. if (loop_) *loop_ = loop;
  3378. if (done_) *done_ = done;
  3379. }
  3380. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3381. lbModule *m = p->module;
  3382. Type *t = enum_type;
  3383. GB_ASSERT(is_type_enum(t));
  3384. Type *enum_ptr = alloc_type_pointer(t);
  3385. t = base_type(t);
  3386. Type *core_elem = core_type(t);
  3387. GB_ASSERT(t->kind == Type_Enum);
  3388. i64 enum_count = t->Enum.fields.count;
  3389. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3390. lbValue ti = lb_type_info(m, t);
  3391. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3392. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3393. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3394. lbValue values_data = lb_slice_elem(p, values);
  3395. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3396. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3397. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3398. lb_emit_jump(p, loop);
  3399. lb_start_block(p, loop);
  3400. lbBlock *body = lb_create_block(p, "for.enum.body");
  3401. lbBlock *done = lb_create_block(p, "for.enum.done");
  3402. lbValue offset = lb_addr_load(p, offset_);
  3403. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3404. lb_emit_if(p, cond, body, done);
  3405. lb_start_block(p, body);
  3406. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3407. lb_emit_increment(p, offset_.addr);
  3408. lbValue val = {};
  3409. if (val_type != nullptr) {
  3410. GB_ASSERT(are_types_identical(enum_type, val_type));
  3411. if (is_type_integer(core_elem)) {
  3412. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3413. val = lb_emit_conv(p, i, t);
  3414. } else {
  3415. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3416. }
  3417. }
  3418. if (val_) *val_ = val;
  3419. if (idx_) *idx_ = offset;
  3420. if (loop_) *loop_ = loop;
  3421. if (done_) *done_ = done;
  3422. }
  3423. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3424. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3425. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3426. lb_emit_jump(p, loop);
  3427. lb_start_block(p, loop);
  3428. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3429. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3430. lbValue tuple_value = lb_build_expr(p, expr);
  3431. Type *tuple = tuple_value.type;
  3432. GB_ASSERT(tuple->kind == Type_Tuple);
  3433. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3434. i32 cond_index = tuple_count-1;
  3435. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3436. lb_emit_if(p, cond, body, done);
  3437. lb_start_block(p, body);
  3438. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3439. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3440. if (loop_) *loop_ = loop;
  3441. if (done_) *done_ = done;
  3442. }
  3443. void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3444. Ast *expr = unparen_expr(rs->expr);
  3445. TypeAndValue tav = type_and_value_of_expr(expr);
  3446. lbBlock *loop = nullptr;
  3447. lbBlock *body = nullptr;
  3448. lbBlock *done = nullptr;
  3449. lb_open_scope(p, scope);
  3450. Type *val_types[2] = {};
  3451. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3452. val_types[0] = type_of_expr(rs->vals[0]);
  3453. }
  3454. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3455. val_types[1] = type_of_expr(rs->vals[1]);
  3456. }
  3457. lbAddr array = lb_build_addr(p, expr);
  3458. if (is_type_pointer(type_deref(lb_addr_type(array)))) {
  3459. array = lb_addr(lb_addr_load(p, array));
  3460. }
  3461. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  3462. lbAddr index = lb_add_local_generated(p, t_int, false);
  3463. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  3464. loop = lb_create_block(p, "for.soa.loop");
  3465. lb_emit_jump(p, loop);
  3466. lb_start_block(p, loop);
  3467. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  3468. lb_addr_store(p, index, incr);
  3469. body = lb_create_block(p, "for.soa.body");
  3470. done = lb_create_block(p, "for.soa.done");
  3471. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3472. lb_emit_if(p, cond, body, done);
  3473. lb_start_block(p, body);
  3474. if (val_types[0]) {
  3475. Entity *e = entity_of_node(rs->vals[0]);
  3476. if (e != nullptr) {
  3477. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  3478. map_set(&p->module->soa_values, hash_entity(e), soa_val);
  3479. }
  3480. }
  3481. if (val_types[1]) {
  3482. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  3483. }
  3484. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3485. lb_build_stmt(p, rs->body);
  3486. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3487. lb_pop_target_list(p);
  3488. lb_emit_jump(p, loop);
  3489. lb_start_block(p, done);
  3490. }
  3491. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3492. Ast *expr = unparen_expr(rs->expr);
  3493. Type *expr_type = type_of_expr(expr);
  3494. if (expr_type != nullptr) {
  3495. Type *et = base_type(type_deref(expr_type));
  3496. if (is_type_soa_struct(et)) {
  3497. lb_build_range_stmt_struct_soa(p, rs, scope);
  3498. return;
  3499. }
  3500. }
  3501. lb_open_scope(p, scope);
  3502. Type *val0_type = nullptr;
  3503. Type *val1_type = nullptr;
  3504. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3505. val0_type = type_of_expr(rs->vals[0]);
  3506. }
  3507. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3508. val1_type = type_of_expr(rs->vals[1]);
  3509. }
  3510. if (val0_type != nullptr) {
  3511. Entity *e = entity_of_node(rs->vals[0]);
  3512. lb_add_local(p, e->type, e, true);
  3513. }
  3514. if (val1_type != nullptr) {
  3515. Entity *e = entity_of_node(rs->vals[1]);
  3516. lb_add_local(p, e->type, e, true);
  3517. }
  3518. lbValue val = {};
  3519. lbValue key = {};
  3520. lbBlock *loop = nullptr;
  3521. lbBlock *done = nullptr;
  3522. bool is_map = false;
  3523. TypeAndValue tav = type_and_value_of_expr(expr);
  3524. if (is_ast_range(expr)) {
  3525. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  3526. } else if (tav.mode == Addressing_Type) {
  3527. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3528. } else {
  3529. Type *expr_type = type_of_expr(expr);
  3530. Type *et = base_type(type_deref(expr_type));
  3531. switch (et->kind) {
  3532. case Type_Map: {
  3533. is_map = true;
  3534. lbValue map = lb_build_addr_ptr(p, expr);
  3535. if (is_type_pointer(type_deref(map.type))) {
  3536. map = lb_emit_load(p, map);
  3537. }
  3538. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3539. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3540. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3541. break;
  3542. }
  3543. case Type_Array: {
  3544. lbValue array = lb_build_addr_ptr(p, expr);
  3545. if (is_type_pointer(type_deref(array.type))) {
  3546. array = lb_emit_load(p, array);
  3547. }
  3548. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3549. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3550. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3551. break;
  3552. }
  3553. case Type_EnumeratedArray: {
  3554. lbValue array = lb_build_addr_ptr(p, expr);
  3555. if (is_type_pointer(type_deref(array.type))) {
  3556. array = lb_emit_load(p, array);
  3557. }
  3558. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3559. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3560. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3561. break;
  3562. }
  3563. case Type_DynamicArray: {
  3564. lbValue count_ptr = {};
  3565. lbValue array = lb_build_addr_ptr(p, expr);
  3566. if (is_type_pointer(type_deref(array.type))) {
  3567. array = lb_emit_load(p, array);
  3568. }
  3569. count_ptr = lb_emit_struct_ep(p, array, 1);
  3570. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3571. break;
  3572. }
  3573. case Type_Slice: {
  3574. lbValue count_ptr = {};
  3575. lbValue slice = lb_build_expr(p, expr);
  3576. if (is_type_pointer(slice.type)) {
  3577. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3578. slice = lb_emit_load(p, slice);
  3579. } else {
  3580. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3581. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3582. }
  3583. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3584. break;
  3585. }
  3586. case Type_Basic: {
  3587. lbValue string = lb_build_expr(p, expr);
  3588. if (is_type_pointer(string.type)) {
  3589. string = lb_emit_load(p, string);
  3590. }
  3591. if (is_type_untyped(expr_type)) {
  3592. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3593. lb_addr_store(p, s, string);
  3594. string = lb_addr_load(p, s);
  3595. }
  3596. Type *t = base_type(string.type);
  3597. GB_ASSERT(!is_type_cstring(t));
  3598. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3599. break;
  3600. }
  3601. case Type_Tuple:
  3602. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3603. break;
  3604. default:
  3605. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3606. break;
  3607. }
  3608. }
  3609. if (is_map) {
  3610. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  3611. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  3612. } else {
  3613. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3614. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  3615. }
  3616. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3617. lb_build_stmt(p, rs->body);
  3618. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3619. lb_pop_target_list(p);
  3620. lb_emit_jump(p, loop);
  3621. lb_start_block(p, done);
  3622. }
  3623. void lb_build_inline_range_stmt(lbProcedure *p, AstUnrollRangeStmt *rs, Scope *scope) {
  3624. lbModule *m = p->module;
  3625. lb_open_scope(p, scope); // Open scope here
  3626. Type *val0_type = nullptr;
  3627. Type *val1_type = nullptr;
  3628. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3629. val0_type = type_of_expr(rs->val0);
  3630. }
  3631. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3632. val1_type = type_of_expr(rs->val1);
  3633. }
  3634. if (val0_type != nullptr) {
  3635. Entity *e = entity_of_node(rs->val0);
  3636. lb_add_local(p, e->type, e, true);
  3637. }
  3638. if (val1_type != nullptr) {
  3639. Entity *e = entity_of_node(rs->val1);
  3640. lb_add_local(p, e->type, e, true);
  3641. }
  3642. lbValue val = {};
  3643. lbValue key = {};
  3644. lbBlock *loop = nullptr;
  3645. lbBlock *done = nullptr;
  3646. Ast *expr = unparen_expr(rs->expr);
  3647. TypeAndValue tav = type_and_value_of_expr(expr);
  3648. if (is_ast_range(expr)) {
  3649. lbAddr val0_addr = {};
  3650. lbAddr val1_addr = {};
  3651. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3652. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3653. TokenKind op = expr->BinaryExpr.op.kind;
  3654. Ast *start_expr = expr->BinaryExpr.left;
  3655. Ast *end_expr = expr->BinaryExpr.right;
  3656. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3657. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3658. ExactValue start = start_expr->tav.value;
  3659. ExactValue end = end_expr->tav.value;
  3660. if (op == Token_Ellipsis) { // .. [start, end]
  3661. ExactValue index = exact_value_i64(0);
  3662. for (ExactValue val = start;
  3663. compare_exact_values(Token_LtEq, val, end);
  3664. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3665. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3666. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3667. lb_build_stmt(p, rs->body);
  3668. }
  3669. } else if (op == Token_RangeHalf) { // ..< [start, end)
  3670. ExactValue index = exact_value_i64(0);
  3671. for (ExactValue val = start;
  3672. compare_exact_values(Token_Lt, val, end);
  3673. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3674. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3675. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3676. lb_build_stmt(p, rs->body);
  3677. }
  3678. }
  3679. } else if (tav.mode == Addressing_Type) {
  3680. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3681. Type *et = type_deref(tav.type);
  3682. Type *bet = base_type(et);
  3683. lbAddr val0_addr = {};
  3684. lbAddr val1_addr = {};
  3685. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3686. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3687. for_array(i, bet->Enum.fields) {
  3688. Entity *field = bet->Enum.fields[i];
  3689. GB_ASSERT(field->kind == Entity_Constant);
  3690. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3691. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3692. lb_build_stmt(p, rs->body);
  3693. }
  3694. } else {
  3695. lbAddr val0_addr = {};
  3696. lbAddr val1_addr = {};
  3697. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3698. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3699. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3700. Type *t = base_type(expr->tav.type);
  3701. switch (t->kind) {
  3702. case Type_Basic:
  3703. GB_ASSERT(is_type_string(t));
  3704. {
  3705. ExactValue value = expr->tav.value;
  3706. GB_ASSERT(value.kind == ExactValue_String);
  3707. String str = value.value_string;
  3708. Rune codepoint = 0;
  3709. isize offset = 0;
  3710. do {
  3711. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3712. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3713. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3714. lb_build_stmt(p, rs->body);
  3715. offset += width;
  3716. } while (offset < str.len);
  3717. }
  3718. break;
  3719. case Type_Array:
  3720. if (t->Array.count > 0) {
  3721. lbValue val = lb_build_expr(p, expr);
  3722. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3723. for (i64 i = 0; i < t->Array.count; i++) {
  3724. if (val0_type) {
  3725. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3726. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3727. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3728. }
  3729. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3730. lb_build_stmt(p, rs->body);
  3731. }
  3732. }
  3733. break;
  3734. case Type_EnumeratedArray:
  3735. if (t->EnumeratedArray.count > 0) {
  3736. lbValue val = lb_build_expr(p, expr);
  3737. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3738. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3739. if (val0_type) {
  3740. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3741. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3742. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3743. }
  3744. if (val1_type) {
  3745. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3746. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3747. }
  3748. lb_build_stmt(p, rs->body);
  3749. }
  3750. }
  3751. break;
  3752. default:
  3753. GB_PANIC("Invalid '#unroll for' type");
  3754. break;
  3755. }
  3756. }
  3757. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3758. }
  3759. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  3760. lb_open_scope(p, scope);
  3761. if (ss->init != nullptr) {
  3762. lb_build_stmt(p, ss->init);
  3763. }
  3764. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3765. if (ss->tag != nullptr) {
  3766. tag = lb_build_expr(p, ss->tag);
  3767. }
  3768. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3769. ast_node(body, BlockStmt, ss->body);
  3770. Slice<Ast *> default_stmts = {};
  3771. lbBlock *default_fall = nullptr;
  3772. lbBlock *default_block = nullptr;
  3773. lbBlock *fall = nullptr;
  3774. isize case_count = body->stmts.count;
  3775. for_array(i, body->stmts) {
  3776. Ast *clause = body->stmts[i];
  3777. ast_node(cc, CaseClause, clause);
  3778. lbBlock *body = fall;
  3779. if (body == nullptr) {
  3780. body = lb_create_block(p, "switch.case.body");
  3781. }
  3782. fall = done;
  3783. if (i+1 < case_count) {
  3784. fall = lb_create_block(p, "switch.fall.body");
  3785. }
  3786. if (cc->list.count == 0) {
  3787. // default case
  3788. default_stmts = cc->stmts;
  3789. default_fall = fall;
  3790. default_block = body;
  3791. continue;
  3792. }
  3793. lbBlock *next_cond = nullptr;
  3794. for_array(j, cc->list) {
  3795. Ast *expr = unparen_expr(cc->list[j]);
  3796. next_cond = lb_create_block(p, "switch.case.next");
  3797. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3798. if (is_ast_range(expr)) {
  3799. ast_node(ie, BinaryExpr, expr);
  3800. TokenKind op = Token_Invalid;
  3801. switch (ie->op.kind) {
  3802. case Token_Ellipsis: op = Token_LtEq; break;
  3803. case Token_RangeHalf: op = Token_Lt; break;
  3804. default: GB_PANIC("Invalid interval operator"); break;
  3805. }
  3806. lbValue lhs = lb_build_expr(p, ie->left);
  3807. lbValue rhs = lb_build_expr(p, ie->right);
  3808. // TODO(bill): do short circuit here
  3809. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3810. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3811. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3812. } else {
  3813. if (expr->tav.mode == Addressing_Type) {
  3814. GB_ASSERT(is_type_typeid(tag.type));
  3815. lbValue e = lb_typeid(p->module, expr->tav.type);
  3816. e = lb_emit_conv(p, e, tag.type);
  3817. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3818. } else {
  3819. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3820. }
  3821. }
  3822. lb_emit_if(p, cond, body, next_cond);
  3823. lb_start_block(p, next_cond);
  3824. }
  3825. lb_start_block(p, body);
  3826. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3827. lb_open_scope(p, body->scope);
  3828. lb_build_stmt_list(p, cc->stmts);
  3829. lb_close_scope(p, lbDeferExit_Default, body);
  3830. lb_pop_target_list(p);
  3831. lb_emit_jump(p, done);
  3832. lb_start_block(p, next_cond);
  3833. }
  3834. if (default_block != nullptr) {
  3835. lb_emit_jump(p, default_block);
  3836. lb_start_block(p, default_block);
  3837. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3838. lb_open_scope(p, default_block->scope);
  3839. lb_build_stmt_list(p, default_stmts);
  3840. lb_close_scope(p, lbDeferExit_Default, default_block);
  3841. lb_pop_target_list(p);
  3842. }
  3843. lb_emit_jump(p, done);
  3844. lb_close_scope(p, lbDeferExit_Default, done);
  3845. lb_start_block(p, done);
  3846. }
  3847. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3848. Entity *e = implicit_entity_of_node(clause);
  3849. GB_ASSERT(e != nullptr);
  3850. if (e->flags & EntityFlag_Value) {
  3851. // by value
  3852. GB_ASSERT(are_types_identical(e->type, value.type));
  3853. lbAddr x = lb_add_local(p, e->type, e, false);
  3854. lb_addr_store(p, x, value);
  3855. } else {
  3856. // by reference
  3857. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3858. lb_add_entity(p->module, e, value);
  3859. }
  3860. }
  3861. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3862. Entity *e = entity_of_node(stmt_val);
  3863. if (e == nullptr) {
  3864. return {};
  3865. }
  3866. if ((e->flags & EntityFlag_Value) == 0) {
  3867. if (LLVMIsALoadInst(value.value)) {
  3868. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3869. lb_add_entity(p->module, e, ptr);
  3870. return lb_addr(ptr);
  3871. }
  3872. }
  3873. // by value
  3874. lbAddr addr = lb_add_local(p, e->type, e, false);
  3875. lb_addr_store(p, addr, value);
  3876. return addr;
  3877. }
  3878. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3879. ast_node(cc, CaseClause, clause);
  3880. lb_push_target_list(p, label, done, nullptr, nullptr);
  3881. lb_open_scope(p, body->scope);
  3882. lb_build_stmt_list(p, cc->stmts);
  3883. lb_close_scope(p, lbDeferExit_Default, body);
  3884. lb_pop_target_list(p);
  3885. lb_emit_jump(p, done);
  3886. }
  3887. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3888. lbModule *m = p->module;
  3889. ast_node(as, AssignStmt, ss->tag);
  3890. GB_ASSERT(as->lhs.count == 1);
  3891. GB_ASSERT(as->rhs.count == 1);
  3892. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3893. bool is_parent_ptr = is_type_pointer(parent.type);
  3894. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3895. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3896. lbValue parent_value = parent;
  3897. lbValue parent_ptr = parent;
  3898. if (!is_parent_ptr) {
  3899. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3900. }
  3901. lbValue tag_index = {};
  3902. lbValue union_data = {};
  3903. if (switch_kind == TypeSwitch_Union) {
  3904. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3905. if (is_type_union_maybe_pointer(type_deref(parent_ptr.type))) {
  3906. tag_index = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, union_data), t_int);
  3907. } else {
  3908. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3909. tag_index = lb_emit_load(p, tag_ptr);
  3910. }
  3911. }
  3912. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3913. lb_emit_jump(p, start_block);
  3914. lb_start_block(p, start_block);
  3915. // NOTE(bill): Append this later
  3916. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3917. Ast *default_ = nullptr;
  3918. ast_node(body, BlockStmt, ss->body);
  3919. gb_local_persist i32 weird_count = 0;
  3920. for_array(i, body->stmts) {
  3921. Ast *clause = body->stmts[i];
  3922. ast_node(cc, CaseClause, clause);
  3923. if (cc->list.count == 0) {
  3924. default_ = clause;
  3925. continue;
  3926. }
  3927. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3928. lbBlock *next = nullptr;
  3929. Type *case_type = nullptr;
  3930. for_array(type_index, cc->list) {
  3931. next = lb_create_block(p, "typeswitch.next");
  3932. case_type = type_of_expr(cc->list[type_index]);
  3933. lbValue cond = {};
  3934. if (switch_kind == TypeSwitch_Union) {
  3935. Type *ut = base_type(type_deref(parent.type));
  3936. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3937. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3938. } else if (switch_kind == TypeSwitch_Any) {
  3939. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3940. lbValue case_typeid = lb_typeid(m, case_type);
  3941. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3942. }
  3943. GB_ASSERT(cond.value != nullptr);
  3944. lb_emit_if(p, cond, body, next);
  3945. lb_start_block(p, next);
  3946. }
  3947. Entity *case_entity = implicit_entity_of_node(clause);
  3948. lbValue value = parent_value;
  3949. lb_start_block(p, body);
  3950. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3951. if (cc->list.count == 1) {
  3952. lbValue data = {};
  3953. if (switch_kind == TypeSwitch_Union) {
  3954. data = union_data;
  3955. } else if (switch_kind == TypeSwitch_Any) {
  3956. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3957. data = any_data;
  3958. }
  3959. Type *ct = case_entity->type;
  3960. Type *ct_ptr = alloc_type_pointer(ct);
  3961. value = lb_emit_conv(p, data, ct_ptr);
  3962. if (!by_reference) {
  3963. value = lb_emit_load(p, value);
  3964. }
  3965. }
  3966. lb_store_type_case_implicit(p, clause, value);
  3967. lb_type_case_body(p, ss->label, clause, body, done);
  3968. lb_start_block(p, next);
  3969. }
  3970. if (default_ != nullptr) {
  3971. lb_store_type_case_implicit(p, default_, parent_value);
  3972. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3973. } else {
  3974. lb_emit_jump(p, done);
  3975. }
  3976. lb_start_block(p, done);
  3977. }
  3978. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3979. lbModule *m = p->module;
  3980. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3981. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3982. type = default_type(type);
  3983. lbValue short_circuit = {};
  3984. if (op == Token_CmpAnd) {
  3985. lb_build_cond(p, left, rhs, done);
  3986. short_circuit = lb_const_bool(m, type, false);
  3987. } else if (op == Token_CmpOr) {
  3988. lb_build_cond(p, left, done, rhs);
  3989. short_circuit = lb_const_bool(m, type, true);
  3990. }
  3991. if (rhs->preds.count == 0) {
  3992. lb_start_block(p, done);
  3993. return short_circuit;
  3994. }
  3995. if (done->preds.count == 0) {
  3996. lb_start_block(p, rhs);
  3997. return lb_build_expr(p, right);
  3998. }
  3999. Array<LLVMValueRef> incoming_values = {};
  4000. Array<LLVMBasicBlockRef> incoming_blocks = {};
  4001. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  4002. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  4003. for_array(i, done->preds) {
  4004. incoming_values[i] = short_circuit.value;
  4005. incoming_blocks[i] = done->preds[i]->block;
  4006. }
  4007. lb_start_block(p, rhs);
  4008. lbValue edge = lb_build_expr(p, right);
  4009. incoming_values[done->preds.count] = edge.value;
  4010. incoming_blocks[done->preds.count] = p->curr_block->block;
  4011. lb_emit_jump(p, done);
  4012. lb_start_block(p, done);
  4013. lbValue res = {};
  4014. res.type = type;
  4015. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  4016. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  4017. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  4018. return res;
  4019. }
  4020. void lb_build_stmt(lbProcedure *p, Ast *node) {
  4021. Ast *prev_stmt = p->curr_stmt;
  4022. defer (p->curr_stmt = prev_stmt);
  4023. p->curr_stmt = node;
  4024. if (p->curr_block != nullptr) {
  4025. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  4026. if (lb_is_instr_terminating(last_instr)) {
  4027. return;
  4028. }
  4029. }
  4030. LLVMMetadataRef prev_debug_location = nullptr;
  4031. if (p->debug_info != nullptr) {
  4032. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  4033. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  4034. }
  4035. defer (if (prev_debug_location != nullptr) {
  4036. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  4037. });
  4038. u16 prev_state_flags = p->state_flags;
  4039. defer (p->state_flags = prev_state_flags);
  4040. if (node->state_flags != 0) {
  4041. u16 in = node->state_flags;
  4042. u16 out = p->state_flags;
  4043. if (in & StateFlag_bounds_check) {
  4044. out |= StateFlag_bounds_check;
  4045. out &= ~StateFlag_no_bounds_check;
  4046. } else if (in & StateFlag_no_bounds_check) {
  4047. out |= StateFlag_no_bounds_check;
  4048. out &= ~StateFlag_bounds_check;
  4049. }
  4050. p->state_flags = out;
  4051. }
  4052. switch (node->kind) {
  4053. case_ast_node(bs, EmptyStmt, node);
  4054. case_end;
  4055. case_ast_node(us, UsingStmt, node);
  4056. case_end;
  4057. case_ast_node(ws, WhenStmt, node);
  4058. lb_build_when_stmt(p, ws);
  4059. case_end;
  4060. case_ast_node(bs, BlockStmt, node);
  4061. lbBlock *done = nullptr;
  4062. if (bs->label != nullptr) {
  4063. done = lb_create_block(p, "block.done");
  4064. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  4065. tl->is_block = true;
  4066. }
  4067. lb_open_scope(p, node->scope);
  4068. lb_build_stmt_list(p, bs->stmts);
  4069. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4070. if (done != nullptr) {
  4071. lb_emit_jump(p, done);
  4072. lb_start_block(p, done);
  4073. }
  4074. case_end;
  4075. case_ast_node(vd, ValueDecl, node);
  4076. if (!vd->is_mutable) {
  4077. return;
  4078. }
  4079. bool is_static = false;
  4080. if (vd->names.count > 0) {
  4081. Entity *e = entity_of_node(vd->names[0]);
  4082. if (e->flags & EntityFlag_Static) {
  4083. // NOTE(bill): If one of the entities is static, they all are
  4084. is_static = true;
  4085. }
  4086. }
  4087. if (is_static) {
  4088. for_array(i, vd->names) {
  4089. lbValue value = {};
  4090. if (vd->values.count > 0) {
  4091. GB_ASSERT(vd->names.count == vd->values.count);
  4092. Ast *ast_value = vd->values[i];
  4093. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  4094. ast_value->tav.mode == Addressing_Invalid);
  4095. bool allow_local = false;
  4096. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  4097. }
  4098. Ast *ident = vd->names[i];
  4099. GB_ASSERT(!is_blank_ident(ident));
  4100. Entity *e = entity_of_node(ident);
  4101. GB_ASSERT(e->flags & EntityFlag_Static);
  4102. String name = e->token.string;
  4103. String mangled_name = {};
  4104. {
  4105. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  4106. str = gb_string_appendc(str, "-");
  4107. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  4108. mangled_name.text = cast(u8 *)str;
  4109. mangled_name.len = gb_string_length(str);
  4110. }
  4111. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  4112. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  4113. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  4114. if (value.value != nullptr) {
  4115. LLVMSetInitializer(global, value.value);
  4116. } else {
  4117. }
  4118. if (e->Variable.thread_local_model != "") {
  4119. LLVMSetThreadLocal(global, true);
  4120. String m = e->Variable.thread_local_model;
  4121. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  4122. if (m == "default") {
  4123. mode = LLVMGeneralDynamicTLSModel;
  4124. } else if (m == "localdynamic") {
  4125. mode = LLVMLocalDynamicTLSModel;
  4126. } else if (m == "initialexec") {
  4127. mode = LLVMInitialExecTLSModel;
  4128. } else if (m == "localexec") {
  4129. mode = LLVMLocalExecTLSModel;
  4130. } else {
  4131. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  4132. }
  4133. LLVMSetThreadLocalMode(global, mode);
  4134. } else {
  4135. LLVMSetLinkage(global, LLVMInternalLinkage);
  4136. }
  4137. lbValue global_val = {global, alloc_type_pointer(e->type)};
  4138. lb_add_entity(p->module, e, global_val);
  4139. lb_add_member(p->module, mangled_name, global_val);
  4140. }
  4141. return;
  4142. }
  4143. if (vd->values.count == 0) { // declared and zero-initialized
  4144. for_array(i, vd->names) {
  4145. Ast *name = vd->names[i];
  4146. if (!is_blank_ident(name)) {
  4147. Entity *e = entity_of_node(name);
  4148. lb_add_local(p, e->type, e, true);
  4149. }
  4150. }
  4151. } else { // Tuple(s)
  4152. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  4153. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  4154. for_array(i, vd->names) {
  4155. Ast *name = vd->names[i];
  4156. lbAddr lval = {};
  4157. if (!is_blank_ident(name)) {
  4158. Entity *e = entity_of_node(name);
  4159. lval = lb_add_local(p, e->type, e, false);
  4160. }
  4161. array_add(&lvals, lval);
  4162. }
  4163. for_array(i, vd->values) {
  4164. lbValue init = lb_build_expr(p, vd->values[i]);
  4165. Type *t = init.type;
  4166. if (t->kind == Type_Tuple) {
  4167. for_array(i, t->Tuple.variables) {
  4168. Entity *e = t->Tuple.variables[i];
  4169. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4170. array_add(&inits, v);
  4171. }
  4172. } else {
  4173. array_add(&inits, init);
  4174. }
  4175. }
  4176. for_array(i, inits) {
  4177. lbAddr lval = lvals[i];
  4178. lbValue init = inits[i];
  4179. lb_addr_store(p, lval, init);
  4180. }
  4181. }
  4182. case_end;
  4183. case_ast_node(as, AssignStmt, node);
  4184. if (as->op.kind == Token_Eq) {
  4185. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  4186. for_array(i, as->lhs) {
  4187. Ast *lhs = as->lhs[i];
  4188. lbAddr lval = {};
  4189. if (!is_blank_ident(lhs)) {
  4190. lval = lb_build_addr(p, lhs);
  4191. }
  4192. array_add(&lvals, lval);
  4193. }
  4194. if (as->lhs.count == as->rhs.count) {
  4195. if (as->lhs.count == 1) {
  4196. lbAddr lval = lvals[0];
  4197. Ast *rhs = as->rhs[0];
  4198. lbValue init = lb_build_expr(p, rhs);
  4199. lb_addr_store(p, lvals[0], init);
  4200. } else {
  4201. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4202. for_array(i, as->rhs) {
  4203. lbValue init = lb_build_expr(p, as->rhs[i]);
  4204. array_add(&inits, init);
  4205. }
  4206. for_array(i, inits) {
  4207. lbAddr lval = lvals[i];
  4208. lbValue init = inits[i];
  4209. lb_addr_store(p, lval, init);
  4210. }
  4211. }
  4212. } else {
  4213. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4214. for_array(i, as->rhs) {
  4215. lbValue init = lb_build_expr(p, as->rhs[i]);
  4216. Type *t = init.type;
  4217. // TODO(bill): refactor for code reuse as this is repeated a bit
  4218. if (t->kind == Type_Tuple) {
  4219. for_array(i, t->Tuple.variables) {
  4220. Entity *e = t->Tuple.variables[i];
  4221. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4222. array_add(&inits, v);
  4223. }
  4224. } else {
  4225. array_add(&inits, init);
  4226. }
  4227. }
  4228. for_array(i, inits) {
  4229. lbAddr lval = lvals[i];
  4230. lbValue init = inits[i];
  4231. lb_addr_store(p, lval, init);
  4232. }
  4233. }
  4234. } else {
  4235. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  4236. // +=, -=, etc
  4237. i32 op = cast(i32)as->op.kind;
  4238. op += Token_Add - Token_AddEq; // Convert += to +
  4239. if (op == Token_CmpAnd || op == Token_CmpOr) {
  4240. Type *type = as->lhs[0]->tav.type;
  4241. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  4242. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4243. lb_addr_store(p, lhs, new_value);
  4244. } else {
  4245. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4246. lbValue value = lb_build_expr(p, as->rhs[0]);
  4247. lbValue old_value = lb_addr_load(p, lhs);
  4248. Type *type = old_value.type;
  4249. lbValue change = lb_emit_conv(p, value, type);
  4250. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  4251. lb_addr_store(p, lhs, new_value);
  4252. }
  4253. return;
  4254. }
  4255. case_end;
  4256. case_ast_node(es, ExprStmt, node);
  4257. lb_build_expr(p, es->expr);
  4258. case_end;
  4259. case_ast_node(ds, DeferStmt, node);
  4260. isize scope_index = p->scope_index;
  4261. lb_add_defer_node(p, scope_index, ds->stmt);
  4262. case_end;
  4263. case_ast_node(rs, ReturnStmt, node);
  4264. lbValue res = {};
  4265. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  4266. isize return_count = p->type->Proc.result_count;
  4267. isize res_count = rs->results.count;
  4268. if (return_count == 0) {
  4269. // No return values
  4270. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4271. LLVMBuildRetVoid(p->builder);
  4272. return;
  4273. } else if (return_count == 1) {
  4274. Entity *e = tuple->variables[0];
  4275. if (res_count == 0) {
  4276. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4277. GB_ASSERT(found);
  4278. res = lb_emit_load(p, *found);
  4279. } else {
  4280. res = lb_build_expr(p, rs->results[0]);
  4281. res = lb_emit_conv(p, res, e->type);
  4282. }
  4283. if (p->type->Proc.has_named_results) {
  4284. // NOTE(bill): store the named values before returning
  4285. if (e->token.string != "") {
  4286. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4287. GB_ASSERT(found != nullptr);
  4288. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  4289. }
  4290. }
  4291. } else {
  4292. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4293. if (res_count != 0) {
  4294. for (isize res_index = 0; res_index < res_count; res_index++) {
  4295. lbValue res = lb_build_expr(p, rs->results[res_index]);
  4296. Type *t = res.type;
  4297. if (t->kind == Type_Tuple) {
  4298. for_array(i, t->Tuple.variables) {
  4299. Entity *e = t->Tuple.variables[i];
  4300. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4301. array_add(&results, v);
  4302. }
  4303. } else {
  4304. array_add(&results, res);
  4305. }
  4306. }
  4307. } else {
  4308. for (isize res_index = 0; res_index < return_count; res_index++) {
  4309. Entity *e = tuple->variables[res_index];
  4310. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4311. GB_ASSERT(found);
  4312. lbValue res = lb_emit_load(p, *found);
  4313. array_add(&results, res);
  4314. }
  4315. }
  4316. GB_ASSERT(results.count == return_count);
  4317. if (p->type->Proc.has_named_results) {
  4318. // NOTE(bill): store the named values before returning
  4319. for_array(i, p->type->Proc.results->Tuple.variables) {
  4320. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4321. if (e->kind != Entity_Variable) {
  4322. continue;
  4323. }
  4324. if (e->token.string == "") {
  4325. continue;
  4326. }
  4327. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4328. GB_ASSERT(found != nullptr);
  4329. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  4330. }
  4331. }
  4332. Type *ret_type = p->type->Proc.results;
  4333. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4334. res = lb_add_local_generated(p, ret_type, false).addr;
  4335. for_array(i, results) {
  4336. Entity *e = tuple->variables[i];
  4337. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  4338. lbValue val = lb_emit_conv(p, results[i], e->type);
  4339. lb_emit_store(p, field, val);
  4340. }
  4341. res = lb_emit_load(p, res);
  4342. }
  4343. lb_ensure_abi_function_type(p->module, p);
  4344. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  4345. if (res.value != nullptr) {
  4346. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4347. } else {
  4348. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4349. }
  4350. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4351. LLVMBuildRetVoid(p->builder);
  4352. } else {
  4353. LLVMValueRef ret_val = res.value;
  4354. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4355. if (p->abi_function_type->ret.cast_type != nullptr) {
  4356. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4357. }
  4358. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4359. LLVMBuildRet(p->builder, ret_val);
  4360. }
  4361. case_end;
  4362. case_ast_node(is, IfStmt, node);
  4363. lb_open_scope(p, node->scope); // Scope #1
  4364. if (is->init != nullptr) {
  4365. // TODO(bill): Should this have a separate block to begin with?
  4366. #if 1
  4367. lbBlock *init = lb_create_block(p, "if.init");
  4368. lb_emit_jump(p, init);
  4369. lb_start_block(p, init);
  4370. #endif
  4371. lb_build_stmt(p, is->init);
  4372. }
  4373. lbBlock *then = lb_create_block(p, "if.then");
  4374. lbBlock *done = lb_create_block(p, "if.done");
  4375. lbBlock *else_ = done;
  4376. if (is->else_stmt != nullptr) {
  4377. else_ = lb_create_block(p, "if.else");
  4378. }
  4379. lb_build_cond(p, is->cond, then, else_);
  4380. lb_start_block(p, then);
  4381. if (is->label != nullptr) {
  4382. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4383. tl->is_block = true;
  4384. }
  4385. lb_build_stmt(p, is->body);
  4386. lb_emit_jump(p, done);
  4387. if (is->else_stmt != nullptr) {
  4388. lb_start_block(p, else_);
  4389. lb_open_scope(p, is->else_stmt->scope);
  4390. lb_build_stmt(p, is->else_stmt);
  4391. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4392. lb_emit_jump(p, done);
  4393. }
  4394. lb_start_block(p, done);
  4395. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4396. case_end;
  4397. case_ast_node(fs, ForStmt, node);
  4398. lb_open_scope(p, node->scope); // Open Scope here
  4399. if (fs->init != nullptr) {
  4400. #if 1
  4401. lbBlock *init = lb_create_block(p, "for.init");
  4402. lb_emit_jump(p, init);
  4403. lb_start_block(p, init);
  4404. #endif
  4405. lb_build_stmt(p, fs->init);
  4406. }
  4407. lbBlock *body = lb_create_block(p, "for.body");
  4408. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4409. lbBlock *loop = body;
  4410. if (fs->cond != nullptr) {
  4411. loop = lb_create_block(p, "for.loop");
  4412. }
  4413. lbBlock *post = loop;
  4414. if (fs->post != nullptr) {
  4415. post = lb_create_block(p, "for.post");
  4416. }
  4417. lb_emit_jump(p, loop);
  4418. lb_start_block(p, loop);
  4419. if (loop != body) {
  4420. lb_build_cond(p, fs->cond, body, done);
  4421. lb_start_block(p, body);
  4422. }
  4423. lb_push_target_list(p, fs->label, done, post, nullptr);
  4424. lb_build_stmt(p, fs->body);
  4425. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4426. lb_pop_target_list(p);
  4427. lb_emit_jump(p, post);
  4428. if (fs->post != nullptr) {
  4429. lb_start_block(p, post);
  4430. lb_build_stmt(p, fs->post);
  4431. lb_emit_jump(p, loop);
  4432. }
  4433. lb_start_block(p, done);
  4434. case_end;
  4435. case_ast_node(rs, RangeStmt, node);
  4436. lb_build_range_stmt(p, rs, node->scope);
  4437. case_end;
  4438. case_ast_node(rs, UnrollRangeStmt, node);
  4439. lb_build_inline_range_stmt(p, rs, node->scope);
  4440. case_end;
  4441. case_ast_node(ss, SwitchStmt, node);
  4442. lb_build_switch_stmt(p, ss, node->scope);
  4443. case_end;
  4444. case_ast_node(ss, TypeSwitchStmt, node);
  4445. lb_build_type_switch_stmt(p, ss);
  4446. case_end;
  4447. case_ast_node(bs, BranchStmt, node);
  4448. lbBlock *block = nullptr;
  4449. if (bs->label != nullptr) {
  4450. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4451. switch (bs->token.kind) {
  4452. case Token_break: block = bb.break_; break;
  4453. case Token_continue: block = bb.continue_; break;
  4454. case Token_fallthrough:
  4455. GB_PANIC("fallthrough cannot have a label");
  4456. break;
  4457. }
  4458. } else {
  4459. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4460. if (t->is_block) {
  4461. continue;
  4462. }
  4463. switch (bs->token.kind) {
  4464. case Token_break: block = t->break_; break;
  4465. case Token_continue: block = t->continue_; break;
  4466. case Token_fallthrough: block = t->fallthrough_; break;
  4467. }
  4468. }
  4469. }
  4470. if (block != nullptr) {
  4471. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  4472. }
  4473. lb_emit_jump(p, block);
  4474. case_end;
  4475. }
  4476. }
  4477. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  4478. cond = lb_emit_conv(p, cond, t_llvm_bool);
  4479. lbValue res = {};
  4480. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  4481. res.type = x.type;
  4482. return res;
  4483. }
  4484. lbValue lb_const_nil(lbModule *m, Type *type) {
  4485. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  4486. return lbValue{v, type};
  4487. }
  4488. lbValue lb_const_undef(lbModule *m, Type *type) {
  4489. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  4490. return lbValue{v, type};
  4491. }
  4492. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4493. lbValue res = {};
  4494. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4495. res.type = type;
  4496. return res;
  4497. }
  4498. lbValue lb_const_string(lbModule *m, String const &value) {
  4499. return lb_const_value(m, t_string, exact_value_string(value));
  4500. }
  4501. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  4502. lbValue res = {};
  4503. res.value = LLVMConstInt(lb_type(m, type), value, false);
  4504. res.type = type;
  4505. return res;
  4506. }
  4507. LLVMValueRef lb_const_f16(lbModule *m, f32 f, Type *type=t_f16) {
  4508. GB_ASSERT(type_size_of(type) == 2);
  4509. u16 u = f32_to_f16(f);
  4510. if (is_type_different_to_arch_endianness(type)) {
  4511. u = gb_endian_swap16(u);
  4512. }
  4513. LLVMValueRef i = LLVMConstInt(LLVMInt16TypeInContext(m->ctx), u, false);
  4514. return LLVMConstBitCast(i, lb_type(m, type));
  4515. }
  4516. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4517. GB_ASSERT(type_size_of(type) == 4);
  4518. u32 u = bit_cast<u32>(f);
  4519. if (is_type_different_to_arch_endianness(type)) {
  4520. u = gb_endian_swap32(u);
  4521. }
  4522. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4523. return LLVMConstBitCast(i, lb_type(m, type));
  4524. }
  4525. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4526. x = lb_emit_conv(p, x, t);
  4527. y = lb_emit_conv(p, y, t);
  4528. if (is_type_float(t)) {
  4529. i64 sz = 8*type_size_of(t);
  4530. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4531. args[0] = x;
  4532. args[1] = y;
  4533. switch (sz) {
  4534. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  4535. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  4536. }
  4537. GB_PANIC("Unknown float type");
  4538. }
  4539. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4540. }
  4541. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4542. x = lb_emit_conv(p, x, t);
  4543. y = lb_emit_conv(p, y, t);
  4544. if (is_type_float(t)) {
  4545. i64 sz = 8*type_size_of(t);
  4546. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4547. args[0] = x;
  4548. args[1] = y;
  4549. switch (sz) {
  4550. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4551. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4552. }
  4553. GB_PANIC("Unknown float type");
  4554. }
  4555. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4556. }
  4557. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4558. lbValue z = {};
  4559. z = lb_emit_max(p, t, x, min);
  4560. z = lb_emit_min(p, t, z, max);
  4561. return z;
  4562. }
  4563. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4564. StringHashKey key = string_hash_string(str);
  4565. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4566. if (found != nullptr) {
  4567. return *found;
  4568. } else {
  4569. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4570. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4571. cast(char const *)str.text,
  4572. cast(unsigned)str.len,
  4573. false);
  4574. isize max_len = 7+8+1;
  4575. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4576. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4577. len -= 1;
  4578. m->global_array_index++;
  4579. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4580. LLVMSetInitializer(global_data, data);
  4581. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4582. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4583. string_map_set(&m->const_strings, key, ptr);
  4584. return ptr;
  4585. }
  4586. }
  4587. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4588. LLVMValueRef ptr = nullptr;
  4589. if (str.len != 0) {
  4590. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4591. } else {
  4592. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4593. }
  4594. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4595. LLVMValueRef values[2] = {ptr, str_len};
  4596. lbValue res = {};
  4597. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  4598. res.type = t_string;
  4599. return res;
  4600. }
  4601. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4602. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4603. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4604. cast(char const *)str.text,
  4605. cast(unsigned)str.len,
  4606. false);
  4607. char *name = nullptr;
  4608. {
  4609. isize max_len = 7+8+1;
  4610. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4611. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4612. len -= 1;
  4613. m->global_array_index++;
  4614. }
  4615. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4616. LLVMSetInitializer(global_data, data);
  4617. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4618. LLVMValueRef ptr = nullptr;
  4619. if (str.len != 0) {
  4620. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4621. } else {
  4622. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4623. }
  4624. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4625. LLVMValueRef values[2] = {ptr, len};
  4626. lbValue res = {};
  4627. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  4628. res.type = t_u8_slice;
  4629. return res;
  4630. }
  4631. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4632. isize index = type_info_index(info, type, false);
  4633. if (index >= 0) {
  4634. auto *set = &info->minimum_dependency_type_info_set;
  4635. for_array(i, set->entries) {
  4636. if (set->entries[i].ptr == index) {
  4637. return i+1;
  4638. }
  4639. }
  4640. }
  4641. if (err_on_not_found) {
  4642. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4643. }
  4644. return -1;
  4645. }
  4646. lbValue lb_typeid(lbModule *m, Type *type) {
  4647. type = default_type(type);
  4648. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4649. GB_ASSERT(id >= 0);
  4650. u64 kind = Typeid_Invalid;
  4651. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4652. u64 special = 0;
  4653. u64 reserved = 0;
  4654. Type *bt = base_type(type);
  4655. TypeKind tk = bt->kind;
  4656. switch (tk) {
  4657. case Type_Basic: {
  4658. u32 flags = bt->Basic.flags;
  4659. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4660. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4661. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4662. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4663. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4664. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4665. if (flags & BasicFlag_String) kind = Typeid_String;
  4666. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4667. } break;
  4668. case Type_Pointer: kind = Typeid_Pointer; break;
  4669. case Type_Array: kind = Typeid_Array; break;
  4670. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4671. case Type_Slice: kind = Typeid_Slice; break;
  4672. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4673. case Type_Map: kind = Typeid_Map; break;
  4674. case Type_Struct: kind = Typeid_Struct; break;
  4675. case Type_Enum: kind = Typeid_Enum; break;
  4676. case Type_Union: kind = Typeid_Union; break;
  4677. case Type_Tuple: kind = Typeid_Tuple; break;
  4678. case Type_Proc: kind = Typeid_Procedure; break;
  4679. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4680. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4681. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4682. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4683. }
  4684. if (is_type_cstring(type)) {
  4685. special = 1;
  4686. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4687. special = 1;
  4688. }
  4689. u64 data = 0;
  4690. if (build_context.word_size == 4) {
  4691. GB_ASSERT(id <= (1u<<24u));
  4692. data |= (id &~ (1u<<24)) << 0u; // index
  4693. data |= (kind &~ (1u<<5)) << 24u; // kind
  4694. data |= (named &~ (1u<<1)) << 29u; // kind
  4695. data |= (special &~ (1u<<1)) << 30u; // kind
  4696. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4697. } else {
  4698. GB_ASSERT(build_context.word_size == 8);
  4699. GB_ASSERT(id <= (1ull<<56u));
  4700. data |= (id &~ (1ull<<56)) << 0ul; // index
  4701. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4702. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4703. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4704. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4705. }
  4706. lbValue res = {};
  4707. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4708. res.type = t_typeid;
  4709. return res;
  4710. }
  4711. lbValue lb_type_info(lbModule *m, Type *type) {
  4712. type = default_type(type);
  4713. isize index = lb_type_info_index(m->info, type);
  4714. GB_ASSERT(index >= 0);
  4715. LLVMTypeRef it = lb_type(m, t_int);
  4716. LLVMValueRef indices[2] = {
  4717. LLVMConstInt(it, 0, false),
  4718. LLVMConstInt(it, index, true),
  4719. };
  4720. lbValue value = {};
  4721. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  4722. value.type = t_type_info_ptr;
  4723. return value;
  4724. }
  4725. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  4726. bool is_local = allow_local && m->curr_procedure != nullptr;
  4727. bool is_const = true;
  4728. if (is_local) {
  4729. for (isize i = 0; i < count; i++) {
  4730. GB_ASSERT(values[i] != nullptr);
  4731. if (!LLVMIsConstant(values[i])) {
  4732. is_const = false;
  4733. break;
  4734. }
  4735. }
  4736. }
  4737. if (!is_const) {
  4738. lbProcedure *p = m->curr_procedure;
  4739. GB_ASSERT(p != nullptr);
  4740. lbAddr v = lb_add_local_generated(p, type, false);
  4741. lbValue ptr = lb_addr_get_ptr(p, v);
  4742. for (isize i = 0; i < count; i++) {
  4743. lbValue elem = lb_emit_array_epi(p, ptr, i);
  4744. LLVMBuildStore(p->builder, values[i], elem.value);
  4745. }
  4746. return lb_addr_load(p, v).value;
  4747. }
  4748. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  4749. }
  4750. lbValue lb_find_procedure_value_from_entity(lbModule *m, Entity *e) {
  4751. e = strip_entity_wrapping(e);
  4752. GB_ASSERT(e != nullptr);
  4753. auto *found = map_get(&m->values, hash_entity(e));
  4754. if (found) {
  4755. return *found;
  4756. }
  4757. // TODO(bill): this is
  4758. lbProcedure *missing_proc = lb_create_procedure(m, e);
  4759. found = map_get(&m->values, hash_entity(e));
  4760. if (found) {
  4761. return *found;
  4762. }
  4763. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  4764. return {};
  4765. }
  4766. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4767. LLVMContextRef ctx = m->ctx;
  4768. type = default_type(type);
  4769. Type *original_type = type;
  4770. lbValue res = {};
  4771. res.type = original_type;
  4772. type = core_type(type);
  4773. value = convert_exact_value_for_type(value, type);
  4774. if (value.kind == ExactValue_Typeid) {
  4775. return lb_typeid(m, value.value_typeid);
  4776. }
  4777. if (value.kind == ExactValue_Invalid) {
  4778. return lb_const_nil(m, type);
  4779. }
  4780. if (value.kind == ExactValue_Procedure) {
  4781. Ast *expr = unparen_expr(value.value_procedure);
  4782. if (expr->kind == Ast_ProcLit) {
  4783. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4784. }
  4785. Entity *e = entity_from_expr(expr);
  4786. return lb_find_procedure_value_from_entity(m, e);
  4787. }
  4788. bool is_local = allow_local && m->curr_procedure != nullptr;
  4789. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4790. if (is_type_slice(type)) {
  4791. if (value.kind == ExactValue_String) {
  4792. GB_ASSERT(is_type_u8_slice(type));
  4793. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4794. return res;
  4795. } else {
  4796. ast_node(cl, CompoundLit, value.value_compound);
  4797. isize count = cl->elems.count;
  4798. if (count == 0) {
  4799. return lb_const_nil(m, type);
  4800. }
  4801. count = gb_max(cl->max_count, count);
  4802. Type *elem = base_type(type)->Slice.elem;
  4803. Type *t = alloc_type_array(elem, count);
  4804. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4805. LLVMValueRef array_data = nullptr;
  4806. if (is_local) {
  4807. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4808. // its backing data on the stack
  4809. lbProcedure *p = m->curr_procedure;
  4810. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4811. LLVMTypeRef llvm_type = lb_type(m, t);
  4812. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4813. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4814. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4815. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4816. {
  4817. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4818. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4819. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4820. lbAddr slice = lb_add_local_generated(p, type, false);
  4821. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4822. return lb_addr_load(p, slice);
  4823. }
  4824. } else {
  4825. isize max_len = 7+8+1;
  4826. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4827. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4828. m->global_array_index++;
  4829. String name = make_string(cast(u8 *)str, len-1);
  4830. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4831. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4832. LLVMSetInitializer(array_data, backing_array.value);
  4833. lbValue g = {};
  4834. g.value = array_data;
  4835. g.type = t;
  4836. lb_add_entity(m, e, g);
  4837. lb_add_member(m, name, g);
  4838. {
  4839. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4840. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4841. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4842. LLVMValueRef values[2] = {ptr, len};
  4843. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4844. return res;
  4845. }
  4846. }
  4847. }
  4848. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4849. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4850. i64 count = type->Array.count;
  4851. Type *elem = type->Array.elem;
  4852. LLVMTypeRef et = lb_type(m, elem);
  4853. Rune rune;
  4854. isize offset = 0;
  4855. isize width = 1;
  4856. String s = value.value_string;
  4857. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4858. for (i64 i = 0; i < count && offset < s.len; i++) {
  4859. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4860. offset += width;
  4861. elems[i] = LLVMConstInt(et, rune, true);
  4862. }
  4863. GB_ASSERT(offset == s.len);
  4864. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  4865. return res;
  4866. }
  4867. GB_PANIC("HERE!\n");
  4868. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4869. cast(char const *)value.value_string.text,
  4870. cast(unsigned)value.value_string.len,
  4871. false /*DontNullTerminate*/);
  4872. res.value = data;
  4873. return res;
  4874. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4875. GB_ASSERT(type->Array.count == value.value_string.len);
  4876. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4877. cast(char const *)value.value_string.text,
  4878. cast(unsigned)value.value_string.len,
  4879. true /*DontNullTerminate*/);
  4880. res.value = data;
  4881. return res;
  4882. } else if (is_type_array(type) &&
  4883. value.kind != ExactValue_Invalid &&
  4884. value.kind != ExactValue_String &&
  4885. value.kind != ExactValue_Compound) {
  4886. i64 count = type->Array.count;
  4887. Type *elem = type->Array.elem;
  4888. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4889. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4890. for (i64 i = 0; i < count; i++) {
  4891. elems[i] = single_elem.value;
  4892. }
  4893. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  4894. return res;
  4895. }
  4896. switch (value.kind) {
  4897. case ExactValue_Invalid:
  4898. res.value = LLVMConstNull(lb_type(m, original_type));
  4899. return res;
  4900. case ExactValue_Bool:
  4901. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4902. return res;
  4903. case ExactValue_String:
  4904. {
  4905. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4906. lbValue res = {};
  4907. res.type = default_type(original_type);
  4908. if (is_type_cstring(res.type)) {
  4909. res.value = ptr;
  4910. } else {
  4911. if (value.value_string.len == 0) {
  4912. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4913. }
  4914. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4915. LLVMValueRef values[2] = {ptr, str_len};
  4916. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4917. }
  4918. return res;
  4919. }
  4920. case ExactValue_Integer:
  4921. if (is_type_pointer(type)) {
  4922. unsigned len = cast(unsigned)value.value_integer.len;
  4923. LLVMTypeRef t = lb_type(m, original_type);
  4924. if (len == 0) {
  4925. res.value = LLVMConstNull(t);
  4926. } else {
  4927. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), len, big_int_ptr(&value.value_integer));
  4928. res.value = LLVMConstIntToPtr(i, t);
  4929. }
  4930. } else {
  4931. unsigned len = cast(unsigned)value.value_integer.len;
  4932. if (len == 0) {
  4933. res.value = LLVMConstNull(lb_type(m, original_type));
  4934. } else {
  4935. u64 *words = big_int_ptr(&value.value_integer);
  4936. if (is_type_different_to_arch_endianness(type)) {
  4937. // NOTE(bill): Swap byte order for different endianness
  4938. i64 sz = type_size_of(type);
  4939. isize byte_len = gb_size_of(u64)*len;
  4940. u8 *old_bytes = cast(u8 *)words;
  4941. // TODO(bill): Use a different allocator here for a temporary allocation
  4942. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4943. for (i64 i = 0; i < sz; i++) {
  4944. new_bytes[i] = old_bytes[sz-1-i];
  4945. }
  4946. words = cast(u64 *)new_bytes;
  4947. }
  4948. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4949. if (value.value_integer.neg) {
  4950. res.value = LLVMConstNeg(res.value);
  4951. }
  4952. }
  4953. }
  4954. return res;
  4955. case ExactValue_Float:
  4956. if (is_type_different_to_arch_endianness(type)) {
  4957. u64 u = bit_cast<u64>(value.value_float);
  4958. u = gb_endian_swap64(u);
  4959. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4960. } else {
  4961. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4962. }
  4963. return res;
  4964. case ExactValue_Complex:
  4965. {
  4966. LLVMValueRef values[2] = {};
  4967. switch (8*type_size_of(type)) {
  4968. case 32:
  4969. values[0] = lb_const_f16(m, cast(f32)value.value_complex->real);
  4970. values[1] = lb_const_f16(m, cast(f32)value.value_complex->imag);
  4971. break;
  4972. case 64:
  4973. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  4974. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  4975. break;
  4976. case 128:
  4977. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  4978. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  4979. break;
  4980. }
  4981. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4982. return res;
  4983. }
  4984. break;
  4985. case ExactValue_Quaternion:
  4986. {
  4987. LLVMValueRef values[4] = {};
  4988. switch (8*type_size_of(type)) {
  4989. case 64:
  4990. // @QuaternionLayout
  4991. values[3] = lb_const_f16(m, cast(f32)value.value_quaternion->real);
  4992. values[0] = lb_const_f16(m, cast(f32)value.value_quaternion->imag);
  4993. values[1] = lb_const_f16(m, cast(f32)value.value_quaternion->jmag);
  4994. values[2] = lb_const_f16(m, cast(f32)value.value_quaternion->kmag);
  4995. break;
  4996. case 128:
  4997. // @QuaternionLayout
  4998. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  4999. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  5000. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  5001. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  5002. break;
  5003. case 256:
  5004. // @QuaternionLayout
  5005. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  5006. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  5007. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  5008. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  5009. break;
  5010. }
  5011. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  5012. return res;
  5013. }
  5014. break;
  5015. case ExactValue_Pointer:
  5016. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  5017. return res;
  5018. case ExactValue_Compound:
  5019. if (is_type_slice(type)) {
  5020. return lb_const_value(m, type, value, allow_local);
  5021. } else if (is_type_array(type)) {
  5022. ast_node(cl, CompoundLit, value.value_compound);
  5023. Type *elem_type = type->Array.elem;
  5024. isize elem_count = cl->elems.count;
  5025. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5026. return lb_const_nil(m, original_type);
  5027. }
  5028. if (cl->elems[0]->kind == Ast_FieldValue) {
  5029. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5030. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  5031. isize value_index = 0;
  5032. for (i64 i = 0; i < type->Array.count; i++) {
  5033. bool found = false;
  5034. for (isize j = 0; j < elem_count; j++) {
  5035. Ast *elem = cl->elems[j];
  5036. ast_node(fv, FieldValue, elem);
  5037. if (is_ast_range(fv->field)) {
  5038. ast_node(ie, BinaryExpr, fv->field);
  5039. TypeAndValue lo_tav = ie->left->tav;
  5040. TypeAndValue hi_tav = ie->right->tav;
  5041. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5042. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5043. TokenKind op = ie->op.kind;
  5044. i64 lo = exact_value_to_i64(lo_tav.value);
  5045. i64 hi = exact_value_to_i64(hi_tav.value);
  5046. if (op == Token_Ellipsis) {
  5047. hi += 1;
  5048. }
  5049. if (lo == i) {
  5050. TypeAndValue tav = fv->value->tav;
  5051. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5052. for (i64 k = lo; k < hi; k++) {
  5053. values[value_index++] = val;
  5054. }
  5055. found = true;
  5056. i += (hi-lo-1);
  5057. break;
  5058. }
  5059. } else {
  5060. TypeAndValue index_tav = fv->field->tav;
  5061. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5062. i64 index = exact_value_to_i64(index_tav.value);
  5063. if (index == i) {
  5064. TypeAndValue tav = fv->value->tav;
  5065. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5066. values[value_index++] = val;
  5067. found = true;
  5068. break;
  5069. }
  5070. }
  5071. }
  5072. if (!found) {
  5073. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5074. }
  5075. }
  5076. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5077. return res;
  5078. } else {
  5079. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  5080. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  5081. for (isize i = 0; i < elem_count; i++) {
  5082. TypeAndValue tav = cl->elems[i]->tav;
  5083. GB_ASSERT(tav.mode != Addressing_Invalid);
  5084. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5085. }
  5086. for (isize i = elem_count; i < type->Array.count; i++) {
  5087. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5088. }
  5089. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5090. return res;
  5091. }
  5092. } else if (is_type_enumerated_array(type)) {
  5093. ast_node(cl, CompoundLit, value.value_compound);
  5094. Type *elem_type = type->EnumeratedArray.elem;
  5095. isize elem_count = cl->elems.count;
  5096. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5097. return lb_const_nil(m, original_type);
  5098. }
  5099. if (cl->elems[0]->kind == Ast_FieldValue) {
  5100. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5101. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5102. isize value_index = 0;
  5103. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  5104. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  5105. for (i64 i = total_lo; i <= total_hi; i++) {
  5106. bool found = false;
  5107. for (isize j = 0; j < elem_count; j++) {
  5108. Ast *elem = cl->elems[j];
  5109. ast_node(fv, FieldValue, elem);
  5110. if (is_ast_range(fv->field)) {
  5111. ast_node(ie, BinaryExpr, fv->field);
  5112. TypeAndValue lo_tav = ie->left->tav;
  5113. TypeAndValue hi_tav = ie->right->tav;
  5114. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5115. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5116. TokenKind op = ie->op.kind;
  5117. i64 lo = exact_value_to_i64(lo_tav.value);
  5118. i64 hi = exact_value_to_i64(hi_tav.value);
  5119. if (op == Token_Ellipsis) {
  5120. hi += 1;
  5121. }
  5122. if (lo == i) {
  5123. TypeAndValue tav = fv->value->tav;
  5124. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5125. for (i64 k = lo; k < hi; k++) {
  5126. values[value_index++] = val;
  5127. }
  5128. found = true;
  5129. i += (hi-lo-1);
  5130. break;
  5131. }
  5132. } else {
  5133. TypeAndValue index_tav = fv->field->tav;
  5134. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5135. i64 index = exact_value_to_i64(index_tav.value);
  5136. if (index == i) {
  5137. TypeAndValue tav = fv->value->tav;
  5138. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5139. values[value_index++] = val;
  5140. found = true;
  5141. break;
  5142. }
  5143. }
  5144. }
  5145. if (!found) {
  5146. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5147. }
  5148. }
  5149. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5150. return res;
  5151. } else {
  5152. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  5153. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5154. for (isize i = 0; i < elem_count; i++) {
  5155. TypeAndValue tav = cl->elems[i]->tav;
  5156. GB_ASSERT(tav.mode != Addressing_Invalid);
  5157. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5158. }
  5159. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  5160. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5161. }
  5162. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5163. return res;
  5164. }
  5165. } else if (is_type_simd_vector(type)) {
  5166. ast_node(cl, CompoundLit, value.value_compound);
  5167. Type *elem_type = type->SimdVector.elem;
  5168. isize elem_count = cl->elems.count;
  5169. if (elem_count == 0) {
  5170. return lb_const_nil(m, original_type);
  5171. }
  5172. GB_ASSERT(elem_type_can_be_constant(elem_type));
  5173. isize total_elem_count = type->SimdVector.count;
  5174. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  5175. for (isize i = 0; i < elem_count; i++) {
  5176. TypeAndValue tav = cl->elems[i]->tav;
  5177. GB_ASSERT(tav.mode != Addressing_Invalid);
  5178. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5179. }
  5180. LLVMTypeRef et = lb_type(m, elem_type);
  5181. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  5182. values[i] = LLVMConstNull(et);
  5183. }
  5184. for (isize i = 0; i< total_elem_count; i++) {
  5185. values[i] = llvm_const_cast(values[i], et);
  5186. }
  5187. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  5188. return res;
  5189. } else if (is_type_struct(type)) {
  5190. ast_node(cl, CompoundLit, value.value_compound);
  5191. if (cl->elems.count == 0) {
  5192. return lb_const_nil(m, original_type);
  5193. }
  5194. isize offset = 0;
  5195. if (type->Struct.custom_align > 0) {
  5196. offset = 1;
  5197. }
  5198. isize value_count = type->Struct.fields.count + offset;
  5199. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5200. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  5201. if (cl->elems.count > 0) {
  5202. if (cl->elems[0]->kind == Ast_FieldValue) {
  5203. isize elem_count = cl->elems.count;
  5204. for (isize i = 0; i < elem_count; i++) {
  5205. ast_node(fv, FieldValue, cl->elems[i]);
  5206. String name = fv->field->Ident.token.string;
  5207. TypeAndValue tav = fv->value->tav;
  5208. GB_ASSERT(tav.mode != Addressing_Invalid);
  5209. Selection sel = lookup_field(type, name, false);
  5210. Entity *f = type->Struct.fields[sel.index[0]];
  5211. if (elem_type_can_be_constant(f->type)) {
  5212. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  5213. visited[offset+f->Variable.field_index] = true;
  5214. }
  5215. }
  5216. } else {
  5217. for_array(i, cl->elems) {
  5218. Entity *f = type->Struct.fields[i];
  5219. TypeAndValue tav = cl->elems[i]->tav;
  5220. ExactValue val = {};
  5221. if (tav.mode != Addressing_Invalid) {
  5222. val = tav.value;
  5223. }
  5224. if (elem_type_can_be_constant(f->type)) {
  5225. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  5226. visited[offset+f->Variable.field_index] = true;
  5227. }
  5228. }
  5229. }
  5230. }
  5231. for (isize i = 0; i < type->Struct.fields.count; i++) {
  5232. if (!visited[offset+i]) {
  5233. GB_ASSERT(values[offset+i] == nullptr);
  5234. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  5235. }
  5236. }
  5237. if (type->Struct.custom_align > 0) {
  5238. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  5239. }
  5240. bool is_constant = true;
  5241. for (isize i = 0; i < value_count; i++) {
  5242. LLVMValueRef val = values[i];
  5243. if (!LLVMIsConstant(val)) {
  5244. GB_ASSERT(is_local);
  5245. GB_ASSERT(LLVMGetInstructionOpcode(val) == LLVMLoad);
  5246. is_constant = false;
  5247. }
  5248. }
  5249. if (is_constant) {
  5250. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  5251. return res;
  5252. } else {
  5253. // TODO(bill): THIS IS HACK BUT IT WORKS FOR WHAT I NEED
  5254. LLVMValueRef *old_values = values;
  5255. LLVMValueRef *new_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5256. for (isize i = 0; i < value_count; i++) {
  5257. LLVMValueRef old_value = old_values[i];
  5258. if (LLVMIsConstant(old_value)) {
  5259. new_values[i] = old_value;
  5260. } else {
  5261. new_values[i] = LLVMConstNull(LLVMTypeOf(old_value));
  5262. }
  5263. }
  5264. LLVMValueRef constant_value = llvm_const_named_struct(lb_type(m, original_type), new_values, cast(unsigned)value_count);
  5265. GB_ASSERT(is_local);
  5266. lbProcedure *p = m->curr_procedure;
  5267. lbAddr v = lb_add_local_generated(p, res.type, true);
  5268. LLVMBuildStore(p->builder, constant_value, v.addr.value);
  5269. for (isize i = 0; i < value_count; i++) {
  5270. LLVMValueRef val = old_values[i];
  5271. if (!LLVMIsConstant(val)) {
  5272. LLVMValueRef dst = LLVMBuildStructGEP(p->builder, v.addr.value, cast(unsigned)i, "");
  5273. LLVMBuildStore(p->builder, val, dst);
  5274. }
  5275. }
  5276. return lb_addr_load(p, v);
  5277. }
  5278. } else if (is_type_bit_set(type)) {
  5279. ast_node(cl, CompoundLit, value.value_compound);
  5280. if (cl->elems.count == 0) {
  5281. return lb_const_nil(m, original_type);
  5282. }
  5283. i64 sz = type_size_of(type);
  5284. if (sz == 0) {
  5285. return lb_const_nil(m, original_type);
  5286. }
  5287. u64 bits = 0;
  5288. for_array(i, cl->elems) {
  5289. Ast *e = cl->elems[i];
  5290. GB_ASSERT(e->kind != Ast_FieldValue);
  5291. TypeAndValue tav = e->tav;
  5292. if (tav.mode != Addressing_Constant) {
  5293. continue;
  5294. }
  5295. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  5296. i64 v = big_int_to_i64(&tav.value.value_integer);
  5297. i64 lower = type->BitSet.lower;
  5298. bits |= 1ull<<cast(u64)(v-lower);
  5299. }
  5300. if (is_type_different_to_arch_endianness(type)) {
  5301. i64 size = type_size_of(type);
  5302. switch (size) {
  5303. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  5304. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  5305. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  5306. }
  5307. }
  5308. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  5309. return res;
  5310. } else {
  5311. return lb_const_nil(m, original_type);
  5312. }
  5313. break;
  5314. case ExactValue_Procedure:
  5315. {
  5316. Ast *expr = value.value_procedure;
  5317. GB_ASSERT(expr != nullptr);
  5318. if (expr->kind == Ast_ProcLit) {
  5319. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5320. }
  5321. }
  5322. break;
  5323. case ExactValue_Typeid:
  5324. return lb_typeid(m, value.value_typeid);
  5325. }
  5326. return lb_const_nil(m, original_type);
  5327. }
  5328. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  5329. lbModule *m = p->module;
  5330. LLVMValueRef fields[4] = {};
  5331. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  5332. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  5333. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  5334. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  5335. lbValue res = {};
  5336. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  5337. res.type = t_source_code_location;
  5338. return res;
  5339. }
  5340. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  5341. String proc_name = {};
  5342. if (p->entity) {
  5343. proc_name = p->entity->token.string;
  5344. }
  5345. TokenPos pos = {};
  5346. if (node) {
  5347. pos = ast_token(node).pos;
  5348. }
  5349. return lb_emit_source_code_location(p, proc_name, pos);
  5350. }
  5351. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  5352. switch (op) {
  5353. case Token_Add:
  5354. return x;
  5355. case Token_Not: // Boolean not
  5356. case Token_Xor: // Bitwise not
  5357. case Token_Sub: // Number negation
  5358. break;
  5359. case Token_Pointer:
  5360. GB_PANIC("This should be handled elsewhere");
  5361. break;
  5362. }
  5363. if (is_type_array(x.type)) {
  5364. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5365. Type *tl = base_type(x.type);
  5366. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5367. GB_ASSERT(is_type_array(type));
  5368. Type *elem_type = base_array_type(type);
  5369. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5370. lbAddr res_addr = lb_add_local_generated(p, type, false);
  5371. lbValue res = lb_addr_get_ptr(p, res_addr);
  5372. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5373. i32 count = cast(i32)tl->Array.count;
  5374. if (inline_array_arith) {
  5375. // inline
  5376. for (i32 i = 0; i < count; i++) {
  5377. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5378. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5379. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  5380. }
  5381. } else {
  5382. auto loop_data = lb_loop_start(p, count, t_i32);
  5383. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  5384. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5385. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  5386. lb_loop_end(p, loop_data);
  5387. }
  5388. return lb_emit_load(p, res);
  5389. }
  5390. if (op == Token_Xor) {
  5391. lbValue cmp = {};
  5392. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  5393. cmp.type = x.type;
  5394. return lb_emit_conv(p, cmp, type);
  5395. }
  5396. if (op == Token_Not) {
  5397. lbValue cmp = {};
  5398. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  5399. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  5400. cmp.type = t_llvm_bool;
  5401. return lb_emit_conv(p, cmp, type);
  5402. }
  5403. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5404. Type *platform_type = integer_endian_type_to_platform_type(type);
  5405. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5406. lbValue res = {};
  5407. res.value = LLVMBuildNeg(p->builder, v.value, "");
  5408. res.type = platform_type;
  5409. return lb_emit_byte_swap(p, res, type);
  5410. }
  5411. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5412. Type *platform_type = integer_endian_type_to_platform_type(type);
  5413. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5414. lbValue res = {};
  5415. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  5416. res.type = platform_type;
  5417. return lb_emit_byte_swap(p, res, type);
  5418. }
  5419. lbValue res = {};
  5420. switch (op) {
  5421. case Token_Not: // Boolean not
  5422. case Token_Xor: // Bitwise not
  5423. res.value = LLVMBuildNot(p->builder, x.value, "");
  5424. res.type = x.type;
  5425. return res;
  5426. case Token_Sub: // Number negation
  5427. if (is_type_integer(x.type)) {
  5428. res.value = LLVMBuildNeg(p->builder, x.value, "");
  5429. } else if (is_type_float(x.type)) {
  5430. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  5431. } else if (is_type_complex(x.type)) {
  5432. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5433. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5434. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5435. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5436. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5437. return lb_addr_load(p, addr);
  5438. } else if (is_type_quaternion(x.type)) {
  5439. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5440. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5441. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  5442. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  5443. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5444. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5445. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5446. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  5447. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  5448. return lb_addr_load(p, addr);
  5449. } else {
  5450. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  5451. }
  5452. res.type = x.type;
  5453. return res;
  5454. }
  5455. return res;
  5456. }
  5457. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  5458. lbModule *m = p->module;
  5459. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  5460. lhs = lb_emit_conv(p, lhs, type);
  5461. rhs = lb_emit_conv(p, rhs, type);
  5462. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  5463. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  5464. GB_ASSERT(is_type_array(type));
  5465. Type *elem_type = base_array_type(type);
  5466. lbAddr res = lb_add_local_generated(p, type, false);
  5467. i64 count = base_type(type)->Array.count;
  5468. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5469. if (inline_array_arith) {
  5470. for (i64 i = 0; i < count; i++) {
  5471. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  5472. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  5473. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  5474. lbValue a = lb_emit_load(p, a_ptr);
  5475. lbValue b = lb_emit_load(p, b_ptr);
  5476. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5477. lb_emit_store(p, dst_ptr, c);
  5478. }
  5479. } else {
  5480. auto loop_data = lb_loop_start(p, count, t_i32);
  5481. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  5482. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  5483. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  5484. lbValue a = lb_emit_load(p, a_ptr);
  5485. lbValue b = lb_emit_load(p, b_ptr);
  5486. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5487. lb_emit_store(p, dst_ptr, c);
  5488. lb_loop_end(p, loop_data);
  5489. }
  5490. return lb_addr_load(p, res);
  5491. } else if (is_type_complex(type)) {
  5492. lhs = lb_emit_conv(p, lhs, type);
  5493. rhs = lb_emit_conv(p, rhs, type);
  5494. Type *ft = base_complex_elem_type(type);
  5495. if (op == Token_Quo) {
  5496. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5497. args[0] = lhs;
  5498. args[1] = rhs;
  5499. switch (type_size_of(ft)) {
  5500. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  5501. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  5502. default: GB_PANIC("Unknown float type"); break;
  5503. }
  5504. }
  5505. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5506. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  5507. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  5508. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  5509. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  5510. lbValue real = {};
  5511. lbValue imag = {};
  5512. switch (op) {
  5513. case Token_Add:
  5514. real = lb_emit_arith(p, Token_Add, a, c, ft);
  5515. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  5516. break;
  5517. case Token_Sub:
  5518. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  5519. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  5520. break;
  5521. case Token_Mul: {
  5522. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  5523. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  5524. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  5525. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  5526. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  5527. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  5528. break;
  5529. }
  5530. }
  5531. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  5532. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  5533. return lb_addr_load(p, res);
  5534. } else if (is_type_quaternion(type)) {
  5535. lhs = lb_emit_conv(p, lhs, type);
  5536. rhs = lb_emit_conv(p, rhs, type);
  5537. Type *ft = base_complex_elem_type(type);
  5538. if (op == Token_Add || op == Token_Sub) {
  5539. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5540. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  5541. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  5542. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  5543. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  5544. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  5545. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  5546. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  5547. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  5548. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  5549. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  5550. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  5551. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  5552. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  5553. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  5554. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  5555. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  5556. return lb_addr_load(p, res);
  5557. } else if (op == Token_Mul) {
  5558. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5559. args[0] = lhs;
  5560. args[1] = rhs;
  5561. switch (8*type_size_of(ft)) {
  5562. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  5563. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  5564. default: GB_PANIC("Unknown float type"); break;
  5565. }
  5566. } else if (op == Token_Quo) {
  5567. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5568. args[0] = lhs;
  5569. args[1] = rhs;
  5570. switch (8*type_size_of(ft)) {
  5571. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  5572. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  5573. default: GB_PANIC("Unknown float type"); break;
  5574. }
  5575. }
  5576. }
  5577. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5578. switch (op) {
  5579. case Token_AndNot:
  5580. case Token_And:
  5581. case Token_Or:
  5582. case Token_Xor:
  5583. goto handle_op;
  5584. }
  5585. Type *platform_type = integer_endian_type_to_platform_type(type);
  5586. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5587. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5588. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5589. return lb_emit_byte_swap(p, res, type);
  5590. }
  5591. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5592. Type *platform_type = integer_endian_type_to_platform_type(type);
  5593. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5594. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5595. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5596. return lb_emit_byte_swap(p, res, type);
  5597. }
  5598. handle_op:
  5599. lhs = lb_emit_conv(p, lhs, type);
  5600. rhs = lb_emit_conv(p, rhs, type);
  5601. lbValue res = {};
  5602. res.type = type;
  5603. // NOTE(bill): Bit Set Aliases for + and -
  5604. if (is_type_bit_set(type)) {
  5605. switch (op) {
  5606. case Token_Add: op = Token_Or; break;
  5607. case Token_Sub: op = Token_AndNot; break;
  5608. }
  5609. }
  5610. switch (op) {
  5611. case Token_Add:
  5612. if (is_type_float(type)) {
  5613. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  5614. return res;
  5615. }
  5616. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  5617. return res;
  5618. case Token_Sub:
  5619. if (is_type_float(type)) {
  5620. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  5621. return res;
  5622. }
  5623. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  5624. return res;
  5625. case Token_Mul:
  5626. if (is_type_float(type)) {
  5627. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  5628. return res;
  5629. }
  5630. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  5631. return res;
  5632. case Token_Quo:
  5633. if (is_type_float(type)) {
  5634. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  5635. return res;
  5636. } else if (is_type_unsigned(type)) {
  5637. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  5638. return res;
  5639. }
  5640. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  5641. return res;
  5642. case Token_Mod:
  5643. if (is_type_float(type)) {
  5644. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  5645. return res;
  5646. } else if (is_type_unsigned(type)) {
  5647. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5648. return res;
  5649. }
  5650. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5651. return res;
  5652. case Token_ModMod:
  5653. if (is_type_unsigned(type)) {
  5654. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5655. return res;
  5656. } else {
  5657. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5658. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5659. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5660. res.value = c;
  5661. return res;
  5662. }
  5663. case Token_And:
  5664. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5665. return res;
  5666. case Token_Or:
  5667. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5668. return res;
  5669. case Token_Xor:
  5670. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5671. return res;
  5672. case Token_Shl:
  5673. {
  5674. rhs = lb_emit_conv(p, rhs, lhs.type);
  5675. LLVMValueRef lhsval = lhs.value;
  5676. LLVMValueRef bits = rhs.value;
  5677. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5678. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  5679. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5680. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5681. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  5682. return res;
  5683. }
  5684. case Token_Shr:
  5685. {
  5686. rhs = lb_emit_conv(p, rhs, lhs.type);
  5687. LLVMValueRef lhsval = lhs.value;
  5688. LLVMValueRef bits = rhs.value;
  5689. bool is_unsigned = is_type_unsigned(type);
  5690. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5691. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  5692. if (is_unsigned) {
  5693. res.value = LLVMBuildLShr(p->builder, lhsval, bits, "");
  5694. } else {
  5695. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5696. }
  5697. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5698. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  5699. return res;
  5700. }
  5701. case Token_AndNot:
  5702. {
  5703. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5704. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5705. return res;
  5706. }
  5707. break;
  5708. }
  5709. GB_PANIC("unhandled operator of lb_emit_arith");
  5710. return {};
  5711. }
  5712. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5713. ast_node(be, BinaryExpr, expr);
  5714. TypeAndValue tv = type_and_value_of_expr(expr);
  5715. switch (be->op.kind) {
  5716. case Token_Add:
  5717. case Token_Sub:
  5718. case Token_Mul:
  5719. case Token_Quo:
  5720. case Token_Mod:
  5721. case Token_ModMod:
  5722. case Token_And:
  5723. case Token_Or:
  5724. case Token_Xor:
  5725. case Token_AndNot:
  5726. case Token_Shl:
  5727. case Token_Shr: {
  5728. Type *type = default_type(tv.type);
  5729. lbValue left = lb_build_expr(p, be->left);
  5730. lbValue right = lb_build_expr(p, be->right);
  5731. return lb_emit_arith(p, be->op.kind, left, right, type);
  5732. }
  5733. case Token_CmpEq:
  5734. case Token_NotEq:
  5735. case Token_Lt:
  5736. case Token_LtEq:
  5737. case Token_Gt:
  5738. case Token_GtEq:
  5739. {
  5740. lbValue left = {};
  5741. lbValue right = {};
  5742. if (be->left->tav.mode == Addressing_Type) {
  5743. left = lb_typeid(p->module, be->left->tav.type);
  5744. }
  5745. if (be->right->tav.mode == Addressing_Type) {
  5746. right = lb_typeid(p->module, be->right->tav.type);
  5747. }
  5748. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5749. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5750. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5751. Type *type = default_type(tv.type);
  5752. return lb_emit_conv(p, cmp, type);
  5753. }
  5754. case Token_CmpAnd:
  5755. case Token_CmpOr:
  5756. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5757. case Token_in:
  5758. case Token_not_in:
  5759. {
  5760. lbValue left = lb_build_expr(p, be->left);
  5761. Type *type = default_type(tv.type);
  5762. lbValue right = lb_build_expr(p, be->right);
  5763. Type *rt = base_type(right.type);
  5764. switch (rt->kind) {
  5765. case Type_Map:
  5766. {
  5767. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5768. lbValue h = lb_gen_map_header(p, addr, rt);
  5769. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  5770. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5771. args[0] = h;
  5772. args[1] = key;
  5773. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5774. if (be->op.kind == Token_in) {
  5775. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5776. } else {
  5777. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  5778. }
  5779. }
  5780. break;
  5781. case Type_BitSet:
  5782. {
  5783. Type *key_type = rt->BitSet.elem;
  5784. GB_ASSERT(are_types_identical(left.type, key_type));
  5785. Type *it = bit_set_to_int(rt);
  5786. left = lb_emit_conv(p, left, it);
  5787. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  5788. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  5789. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  5790. bit = lb_emit_conv(p, bit, it);
  5791. lbValue old_value = lb_emit_transmute(p, right, it);
  5792. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  5793. if (be->op.kind == Token_in) {
  5794. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5795. } else {
  5796. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5797. }
  5798. }
  5799. break;
  5800. default:
  5801. GB_PANIC("Invalid 'in' type");
  5802. }
  5803. break;
  5804. }
  5805. break;
  5806. default:
  5807. GB_PANIC("Invalid binary expression");
  5808. break;
  5809. }
  5810. return {};
  5811. }
  5812. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5813. Type *prev_src = src;
  5814. // Type *prev_dst = dst;
  5815. src = base_type(type_deref(src));
  5816. // dst = base_type(type_deref(dst));
  5817. bool src_is_ptr = src != prev_src;
  5818. // bool dst_is_ptr = dst != prev_dst;
  5819. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5820. for_array(i, src->Struct.fields) {
  5821. Entity *f = src->Struct.fields[i];
  5822. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5823. if (are_types_identical(dst, f->type)) {
  5824. return f->token.string;
  5825. }
  5826. if (src_is_ptr && is_type_pointer(dst)) {
  5827. if (are_types_identical(type_deref(dst), f->type)) {
  5828. return f->token.string;
  5829. }
  5830. }
  5831. if (is_type_struct(f->type)) {
  5832. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5833. if (name.len > 0) {
  5834. return name;
  5835. }
  5836. }
  5837. }
  5838. }
  5839. return str_lit("");
  5840. }
  5841. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5842. GB_ASSERT(is_type_pointer(value.type));
  5843. GB_ASSERT(is_type_pointer(t));
  5844. GB_ASSERT(lb_is_const(value));
  5845. lbValue res = {};
  5846. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5847. res.type = t;
  5848. return res;
  5849. }
  5850. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5851. lbModule *m = p->module;
  5852. t = reduce_tuple_to_single_type(t);
  5853. Type *src_type = value.type;
  5854. if (are_types_identical(t, src_type)) {
  5855. return value;
  5856. }
  5857. Type *src = core_type(src_type);
  5858. Type *dst = core_type(t);
  5859. GB_ASSERT(src != nullptr);
  5860. GB_ASSERT(dst != nullptr);
  5861. if (is_type_untyped_nil(src)) {
  5862. return lb_const_nil(m, t);
  5863. }
  5864. if (is_type_untyped_undef(src)) {
  5865. return lb_const_undef(m, t);
  5866. }
  5867. if (LLVMIsConstant(value.value)) {
  5868. if (is_type_any(dst)) {
  5869. Type *st = default_type(src_type);
  5870. lbAddr default_value = lb_add_local_generated(p, st, false);
  5871. lb_addr_store(p, default_value, value);
  5872. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5873. lbValue id = lb_typeid(m, st);
  5874. lbAddr res = lb_add_local_generated(p, t, false);
  5875. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5876. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5877. lb_emit_store(p, a0, data);
  5878. lb_emit_store(p, a1, id);
  5879. return lb_addr_load(p, res);
  5880. } else if (dst->kind == Type_Basic) {
  5881. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5882. String str = lb_get_const_string(m, value);
  5883. lbValue res = {};
  5884. res.type = t;
  5885. res.value = llvm_cstring(m, str);
  5886. return res;
  5887. }
  5888. // if (is_type_float(dst)) {
  5889. // return value;
  5890. // } else if (is_type_integer(dst)) {
  5891. // return value;
  5892. // }
  5893. // ExactValue ev = value->Constant.value;
  5894. // if (is_type_float(dst)) {
  5895. // ev = exact_value_to_float(ev);
  5896. // } else if (is_type_complex(dst)) {
  5897. // ev = exact_value_to_complex(ev);
  5898. // } else if (is_type_quaternion(dst)) {
  5899. // ev = exact_value_to_quaternion(ev);
  5900. // } else if (is_type_string(dst)) {
  5901. // // Handled elsewhere
  5902. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5903. // } else if (is_type_integer(dst)) {
  5904. // ev = exact_value_to_integer(ev);
  5905. // } else if (is_type_pointer(dst)) {
  5906. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5907. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5908. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5909. // }
  5910. // return lb_const_value(p->module, t, ev);
  5911. }
  5912. }
  5913. if (are_types_identical(src, dst)) {
  5914. if (!are_types_identical(src_type, t)) {
  5915. return lb_emit_transmute(p, value, t);
  5916. }
  5917. return value;
  5918. }
  5919. // bool <-> llvm bool
  5920. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5921. lbValue res = {};
  5922. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5923. res.type = dst;
  5924. return res;
  5925. }
  5926. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5927. lbValue res = {};
  5928. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5929. res.type = dst;
  5930. return res;
  5931. }
  5932. // integer -> integer
  5933. if (is_type_integer(src) && is_type_integer(dst)) {
  5934. GB_ASSERT(src->kind == Type_Basic &&
  5935. dst->kind == Type_Basic);
  5936. i64 sz = type_size_of(default_type(src));
  5937. i64 dz = type_size_of(default_type(dst));
  5938. if (sz == dz) {
  5939. if (dz > 1 && !types_have_same_internal_endian(src, dst)) {
  5940. return lb_emit_byte_swap(p, value, t);
  5941. }
  5942. lbValue res = {};
  5943. res.value = value.value;
  5944. res.type = t;
  5945. return res;
  5946. }
  5947. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5948. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5949. value = lb_emit_byte_swap(p, value, platform_src_type);
  5950. }
  5951. LLVMOpcode op = LLVMTrunc;
  5952. if (dz < sz) {
  5953. op = LLVMTrunc;
  5954. } else if (dz == sz) {
  5955. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5956. // NOTE(bill): Copy the value just for type correctness
  5957. op = LLVMBitCast;
  5958. } else if (dz > sz) {
  5959. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5960. }
  5961. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5962. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5963. lbValue res = {};
  5964. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5965. res.type = t;
  5966. return lb_emit_byte_swap(p, res, t);
  5967. } else {
  5968. lbValue res = {};
  5969. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5970. res.type = t;
  5971. return res;
  5972. }
  5973. }
  5974. // boolean -> boolean/integer
  5975. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5976. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5977. lbValue res = {};
  5978. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5979. res.type = t;
  5980. return res;
  5981. }
  5982. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5983. return lb_emit_transmute(p, value, dst);
  5984. }
  5985. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5986. return lb_emit_transmute(p, value, dst);
  5987. }
  5988. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5989. return lb_emit_transmute(p, value, dst);
  5990. }
  5991. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5992. return lb_emit_transmute(p, value, dst);
  5993. }
  5994. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5995. lbValue c = lb_emit_conv(p, value, t_cstring);
  5996. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5997. args[0] = c;
  5998. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5999. return lb_emit_conv(p, s, dst);
  6000. }
  6001. // integer -> boolean
  6002. if (is_type_integer(src) && is_type_boolean(dst)) {
  6003. lbValue res = {};
  6004. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  6005. res.type = t_llvm_bool;
  6006. return lb_emit_conv(p, res, t);
  6007. }
  6008. // float -> float
  6009. if (is_type_float(src) && is_type_float(dst)) {
  6010. i64 sz = type_size_of(src);
  6011. i64 dz = type_size_of(dst);
  6012. if (dz == sz) {
  6013. if (types_have_same_internal_endian(src, dst)) {
  6014. lbValue res = {};
  6015. res.type = t;
  6016. res.value = value.value;
  6017. return res;
  6018. } else {
  6019. return lb_emit_byte_swap(p, value, t);
  6020. }
  6021. }
  6022. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6023. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6024. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6025. lbValue res = {};
  6026. res = lb_emit_conv(p, value, platform_src_type);
  6027. res = lb_emit_conv(p, res, platform_dst_type);
  6028. if (is_type_different_to_arch_endianness(dst)) {
  6029. res = lb_emit_byte_swap(p, res, t);
  6030. }
  6031. return lb_emit_conv(p, res, t);
  6032. }
  6033. lbValue res = {};
  6034. res.type = t;
  6035. if (dz >= sz) {
  6036. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  6037. } else {
  6038. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  6039. }
  6040. return res;
  6041. }
  6042. if (is_type_complex(src) && is_type_complex(dst)) {
  6043. Type *ft = base_complex_elem_type(dst);
  6044. lbAddr gen = lb_add_local_generated(p, dst, false);
  6045. lbValue gp = lb_addr_get_ptr(p, gen);
  6046. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6047. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6048. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6049. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  6050. return lb_addr_load(p, gen);
  6051. }
  6052. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  6053. // @QuaternionLayout
  6054. Type *ft = base_complex_elem_type(dst);
  6055. lbAddr gen = lb_add_local_generated(p, dst, false);
  6056. lbValue gp = lb_addr_get_ptr(p, gen);
  6057. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6058. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6059. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  6060. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  6061. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  6062. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  6063. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  6064. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  6065. return lb_addr_load(p, gen);
  6066. }
  6067. if (is_type_float(src) && is_type_complex(dst)) {
  6068. Type *ft = base_complex_elem_type(dst);
  6069. lbAddr gen = lb_add_local_generated(p, dst, true);
  6070. lbValue gp = lb_addr_get_ptr(p, gen);
  6071. lbValue real = lb_emit_conv(p, value, ft);
  6072. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6073. return lb_addr_load(p, gen);
  6074. }
  6075. if (is_type_float(src) && is_type_quaternion(dst)) {
  6076. Type *ft = base_complex_elem_type(dst);
  6077. lbAddr gen = lb_add_local_generated(p, dst, true);
  6078. lbValue gp = lb_addr_get_ptr(p, gen);
  6079. lbValue real = lb_emit_conv(p, value, ft);
  6080. // @QuaternionLayout
  6081. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6082. return lb_addr_load(p, gen);
  6083. }
  6084. if (is_type_complex(src) && is_type_quaternion(dst)) {
  6085. Type *ft = base_complex_elem_type(dst);
  6086. lbAddr gen = lb_add_local_generated(p, dst, true);
  6087. lbValue gp = lb_addr_get_ptr(p, gen);
  6088. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6089. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6090. // @QuaternionLayout
  6091. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6092. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  6093. return lb_addr_load(p, gen);
  6094. }
  6095. // float <-> integer
  6096. if (is_type_float(src) && is_type_integer(dst)) {
  6097. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6098. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6099. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6100. lbValue res = {};
  6101. res = lb_emit_conv(p, value, platform_src_type);
  6102. res = lb_emit_conv(p, res, platform_dst_type);
  6103. if (is_type_different_to_arch_endianness(dst)) {
  6104. res = lb_emit_byte_swap(p, res, t);
  6105. }
  6106. return lb_emit_conv(p, res, t);
  6107. }
  6108. lbValue res = {};
  6109. res.type = t;
  6110. if (is_type_unsigned(dst)) {
  6111. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  6112. } else {
  6113. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  6114. }
  6115. return res;
  6116. }
  6117. if (is_type_integer(src) && is_type_float(dst)) {
  6118. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6119. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6120. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6121. lbValue res = {};
  6122. res = lb_emit_conv(p, value, platform_src_type);
  6123. res = lb_emit_conv(p, res, platform_dst_type);
  6124. if (is_type_different_to_arch_endianness(dst)) {
  6125. res = lb_emit_byte_swap(p, res, t);
  6126. }
  6127. return lb_emit_conv(p, res, t);
  6128. }
  6129. lbValue res = {};
  6130. res.type = t;
  6131. if (is_type_unsigned(src)) {
  6132. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  6133. } else {
  6134. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  6135. }
  6136. return res;
  6137. }
  6138. // Pointer <-> uintptr
  6139. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6140. lbValue res = {};
  6141. res.type = t;
  6142. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6143. return res;
  6144. }
  6145. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6146. lbValue res = {};
  6147. res.type = t;
  6148. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6149. return res;
  6150. }
  6151. #if 1
  6152. if (is_type_union(dst)) {
  6153. for_array(i, dst->Union.variants) {
  6154. Type *vt = dst->Union.variants[i];
  6155. if (are_types_identical(vt, src_type)) {
  6156. lbAddr parent = lb_add_local_generated(p, t, true);
  6157. lb_emit_store_union_variant(p, parent.addr, value, vt);
  6158. return lb_addr_load(p, parent);
  6159. }
  6160. }
  6161. }
  6162. #endif
  6163. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  6164. // subtype polymorphism casting
  6165. if (check_is_assignable_to_using_subtype(src_type, t)) {
  6166. Type *st = type_deref(src_type);
  6167. Type *pst = st;
  6168. st = type_deref(st);
  6169. bool st_is_ptr = is_type_pointer(src_type);
  6170. st = base_type(st);
  6171. Type *dt = t;
  6172. bool dt_is_ptr = type_deref(dt) != dt;
  6173. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  6174. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  6175. if (field_name.len > 0) {
  6176. // NOTE(bill): It can be casted
  6177. Selection sel = lookup_field(st, field_name, false, true);
  6178. if (sel.entity != nullptr) {
  6179. if (st_is_ptr) {
  6180. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  6181. Type *rt = res.type;
  6182. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6183. res = lb_emit_load(p, res);
  6184. }
  6185. return res;
  6186. } else {
  6187. if (is_type_pointer(value.type)) {
  6188. Type *rt = value.type;
  6189. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6190. value = lb_emit_load(p, value);
  6191. } else {
  6192. value = lb_emit_deep_field_gep(p, value, sel);
  6193. return lb_emit_load(p, value);
  6194. }
  6195. }
  6196. return lb_emit_deep_field_ev(p, value, sel);
  6197. }
  6198. } else {
  6199. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  6200. }
  6201. }
  6202. }
  6203. // Pointer <-> Pointer
  6204. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6205. lbValue res = {};
  6206. res.type = t;
  6207. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6208. return res;
  6209. }
  6210. // proc <-> proc
  6211. if (is_type_proc(src) && is_type_proc(dst)) {
  6212. lbValue res = {};
  6213. res.type = t;
  6214. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6215. return res;
  6216. }
  6217. // pointer -> proc
  6218. if (is_type_pointer(src) && is_type_proc(dst)) {
  6219. lbValue res = {};
  6220. res.type = t;
  6221. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6222. return res;
  6223. }
  6224. // proc -> pointer
  6225. if (is_type_proc(src) && is_type_pointer(dst)) {
  6226. lbValue res = {};
  6227. res.type = t;
  6228. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6229. return res;
  6230. }
  6231. // []byte/[]u8 <-> string
  6232. if (is_type_u8_slice(src) && is_type_string(dst)) {
  6233. return lb_emit_transmute(p, value, t);
  6234. }
  6235. if (is_type_string(src) && is_type_u8_slice(dst)) {
  6236. return lb_emit_transmute(p, value, t);
  6237. }
  6238. if (is_type_array(dst)) {
  6239. Type *elem = dst->Array.elem;
  6240. lbValue e = lb_emit_conv(p, value, elem);
  6241. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6242. lbAddr v = lb_add_local_generated(p, t, false);
  6243. isize index_count = cast(isize)dst->Array.count;
  6244. for (isize i = 0; i < index_count; i++) {
  6245. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  6246. lb_emit_store(p, elem, e);
  6247. }
  6248. return lb_addr_load(p, v);
  6249. }
  6250. if (is_type_any(dst)) {
  6251. if (is_type_untyped_nil(src)) {
  6252. return lb_const_nil(p->module, t);
  6253. }
  6254. if (is_type_untyped_undef(src)) {
  6255. return lb_const_undef(p->module, t);
  6256. }
  6257. lbAddr result = lb_add_local_generated(p, t, true);
  6258. Type *st = default_type(src_type);
  6259. lbValue data = lb_address_from_load_or_generate_local(p, value);
  6260. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  6261. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  6262. data = lb_emit_conv(p, data, t_rawptr);
  6263. lbValue id = lb_typeid(p->module, st);
  6264. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  6265. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  6266. lb_emit_store(p, any_data, data);
  6267. lb_emit_store(p, any_id, id);
  6268. return lb_addr_load(p, result);
  6269. }
  6270. i64 src_sz = type_size_of(src);
  6271. i64 dst_sz = type_size_of(dst);
  6272. if (src_sz == dst_sz) {
  6273. // bit_set <-> integer
  6274. if (is_type_integer(src) && is_type_bit_set(dst)) {
  6275. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  6276. res.type = dst;
  6277. return res;
  6278. }
  6279. if (is_type_bit_set(src) && is_type_integer(dst)) {
  6280. lbValue bs = value;
  6281. bs.type = bit_set_to_int(src);
  6282. return lb_emit_conv(p, bs, dst);
  6283. }
  6284. // typeid <-> integer
  6285. if (is_type_integer(src) && is_type_typeid(dst)) {
  6286. return lb_emit_transmute(p, value, dst);
  6287. }
  6288. if (is_type_typeid(src) && is_type_integer(dst)) {
  6289. return lb_emit_transmute(p, value, dst);
  6290. }
  6291. }
  6292. if (is_type_untyped(src)) {
  6293. if (is_type_string(src) && is_type_string(dst)) {
  6294. lbAddr result = lb_add_local_generated(p, t, false);
  6295. lb_addr_store(p, result, value);
  6296. return lb_addr_load(p, result);
  6297. }
  6298. }
  6299. gb_printf_err("%.*s\n", LIT(p->name));
  6300. gb_printf_err("lb_emit_conv: src -> dst\n");
  6301. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  6302. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  6303. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  6304. gb_printf_err("Not Identical %p != %p\n", src, dst);
  6305. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  6306. type_to_string(src_type), type_to_string(t),
  6307. LIT(p->name));
  6308. return {};
  6309. }
  6310. bool lb_is_type_aggregate(Type *t) {
  6311. t = base_type(t);
  6312. switch (t->kind) {
  6313. case Type_Basic:
  6314. switch (t->Basic.kind) {
  6315. case Basic_string:
  6316. case Basic_any:
  6317. return true;
  6318. case Basic_complex32:
  6319. case Basic_complex64:
  6320. case Basic_complex128:
  6321. case Basic_quaternion64:
  6322. case Basic_quaternion128:
  6323. case Basic_quaternion256:
  6324. return true;
  6325. }
  6326. break;
  6327. case Type_Pointer:
  6328. return false;
  6329. case Type_Array:
  6330. case Type_Slice:
  6331. case Type_Struct:
  6332. case Type_Union:
  6333. case Type_Tuple:
  6334. case Type_DynamicArray:
  6335. case Type_Map:
  6336. case Type_SimdVector:
  6337. return true;
  6338. case Type_Named:
  6339. return lb_is_type_aggregate(t->Named.base);
  6340. }
  6341. return false;
  6342. }
  6343. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  6344. Type *src_type = value.type;
  6345. if (are_types_identical(t, src_type)) {
  6346. return value;
  6347. }
  6348. lbValue res = {};
  6349. res.type = t;
  6350. Type *src = base_type(src_type);
  6351. Type *dst = base_type(t);
  6352. lbModule *m = p->module;
  6353. i64 sz = type_size_of(src);
  6354. i64 dz = type_size_of(dst);
  6355. if (sz != dz) {
  6356. LLVMTypeRef s = lb_type(m, src);
  6357. LLVMTypeRef d = lb_type(m, dst);
  6358. i64 llvm_sz = lb_sizeof(s);
  6359. i64 llvm_dz = lb_sizeof(d);
  6360. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  6361. }
  6362. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  6363. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  6364. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6365. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6366. return res;
  6367. }
  6368. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6369. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6370. return res;
  6371. }
  6372. if (is_type_uintptr(src) && is_type_proc(dst)) {
  6373. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6374. return res;
  6375. }
  6376. if (is_type_proc(src) && is_type_uintptr(dst)) {
  6377. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6378. return res;
  6379. }
  6380. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  6381. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6382. return res;
  6383. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  6384. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6385. return res;
  6386. }
  6387. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6388. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  6389. return res;
  6390. }
  6391. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  6392. lbValue s = lb_address_from_load_or_generate_local(p, value);
  6393. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  6394. return lb_emit_load(p, d);
  6395. }
  6396. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  6397. // GB_PANIC("lb_emit_transmute");
  6398. return res;
  6399. }
  6400. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  6401. GB_ASSERT(addr.kind == lbAddr_Context);
  6402. GB_ASSERT(addr.ctx.sel.index.count == 0);
  6403. lbModule *m = p->module;
  6404. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6405. args[0] = addr.addr;
  6406. lb_emit_runtime_call(p, "__init_context", args);
  6407. }
  6408. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  6409. Type *pt = base_type(p->type);
  6410. GB_ASSERT(pt->kind == Type_Proc);
  6411. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  6412. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  6413. e->flags |= EntityFlag_NoAlias;
  6414. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  6415. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  6416. lbValue param = {context_ptr, e->type};
  6417. lb_add_entity(p->module, e, param);
  6418. lbAddr ctx_addr = {};
  6419. ctx_addr.kind = lbAddr_Context;
  6420. ctx_addr.addr = param;
  6421. lbContextData *cd = array_add_and_get(&p->context_stack);
  6422. cd->ctx = ctx_addr;
  6423. cd->scope_index = -1;
  6424. cd->uses = +1; // make sure it has been used already
  6425. return cd;
  6426. }
  6427. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  6428. ctx.kind = lbAddr_Context;
  6429. lbContextData *cd = array_add_and_get(&p->context_stack);
  6430. cd->ctx = ctx;
  6431. cd->scope_index = p->scope_index;
  6432. return cd;
  6433. }
  6434. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  6435. if (p->context_stack.count > 0) {
  6436. return p->context_stack[p->context_stack.count-1].ctx;
  6437. }
  6438. Type *pt = base_type(p->type);
  6439. GB_ASSERT(pt->kind == Type_Proc);
  6440. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  6441. lbAddr c = lb_add_local_generated(p, t_context, true);
  6442. c.kind = lbAddr_Context;
  6443. lb_emit_init_context(p, c);
  6444. lb_push_context_onto_stack(p, c);
  6445. lb_add_debug_context_variable(p, c);
  6446. return c;
  6447. }
  6448. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  6449. if (LLVMIsALoadInst(value.value)) {
  6450. lbValue res = {};
  6451. res.value = LLVMGetOperand(value.value, 0);
  6452. res.type = alloc_type_pointer(value.type);
  6453. return res;
  6454. }
  6455. GB_ASSERT(is_type_typed(value.type));
  6456. lbAddr res = lb_add_local_generated(p, value.type, false);
  6457. lb_addr_store(p, res, value);
  6458. return res.addr;
  6459. }
  6460. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  6461. if (LLVMIsALoadInst(value.value)) {
  6462. lbValue res = {};
  6463. res.value = LLVMGetOperand(value.value, 0);
  6464. res.type = alloc_type_pointer(value.type);
  6465. return res;
  6466. }
  6467. GB_PANIC("lb_address_from_load");
  6468. return {};
  6469. }
  6470. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  6471. i64 type_alignment = type_align_of(new_type);
  6472. if (alignment < type_alignment) {
  6473. alignment = type_alignment;
  6474. }
  6475. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  6476. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  6477. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  6478. lb_addr_store(p, ptr, val);
  6479. // ptr.kind = lbAddr_Context;
  6480. return ptr.addr;
  6481. }
  6482. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  6483. GB_ASSERT(is_type_pointer(s.type));
  6484. Type *t = base_type(type_deref(s.type));
  6485. Type *result_type = nullptr;
  6486. if (is_type_relative_pointer(t)) {
  6487. s = lb_addr_get_ptr(p, lb_addr(s));
  6488. }
  6489. if (is_type_struct(t)) {
  6490. result_type = get_struct_field_type(t, index);
  6491. } else if (is_type_union(t)) {
  6492. GB_ASSERT(index == -1);
  6493. return lb_emit_union_tag_ptr(p, s);
  6494. } else if (is_type_tuple(t)) {
  6495. GB_ASSERT(t->Tuple.variables.count > 0);
  6496. result_type = t->Tuple.variables[index]->type;
  6497. } else if (is_type_complex(t)) {
  6498. Type *ft = base_complex_elem_type(t);
  6499. switch (index) {
  6500. case 0: result_type = ft; break;
  6501. case 1: result_type = ft; break;
  6502. }
  6503. } else if (is_type_quaternion(t)) {
  6504. Type *ft = base_complex_elem_type(t);
  6505. switch (index) {
  6506. case 0: result_type = ft; break;
  6507. case 1: result_type = ft; break;
  6508. case 2: result_type = ft; break;
  6509. case 3: result_type = ft; break;
  6510. }
  6511. } else if (is_type_slice(t)) {
  6512. switch (index) {
  6513. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6514. case 1: result_type = t_int; break;
  6515. }
  6516. } else if (is_type_string(t)) {
  6517. switch (index) {
  6518. case 0: result_type = t_u8_ptr; break;
  6519. case 1: result_type = t_int; break;
  6520. }
  6521. } else if (is_type_any(t)) {
  6522. switch (index) {
  6523. case 0: result_type = t_rawptr; break;
  6524. case 1: result_type = t_typeid; break;
  6525. }
  6526. } else if (is_type_dynamic_array(t)) {
  6527. switch (index) {
  6528. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6529. case 1: result_type = t_int; break;
  6530. case 2: result_type = t_int; break;
  6531. case 3: result_type = t_allocator; break;
  6532. }
  6533. } else if (is_type_map(t)) {
  6534. init_map_internal_types(t);
  6535. Type *itp = alloc_type_pointer(t->Map.internal_type);
  6536. s = lb_emit_transmute(p, s, itp);
  6537. Type *gst = t->Map.internal_type;
  6538. GB_ASSERT(gst->kind == Type_Struct);
  6539. switch (index) {
  6540. case 0: result_type = get_struct_field_type(gst, 0); break;
  6541. case 1: result_type = get_struct_field_type(gst, 1); break;
  6542. }
  6543. } else if (is_type_array(t)) {
  6544. return lb_emit_array_epi(p, s, index);
  6545. } else if (is_type_relative_slice(t)) {
  6546. switch (index) {
  6547. case 0: result_type = t->RelativeSlice.base_integer; break;
  6548. case 1: result_type = t->RelativeSlice.base_integer; break;
  6549. }
  6550. } else {
  6551. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  6552. }
  6553. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  6554. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6555. index += 1;
  6556. }
  6557. if (lb_is_const(s)) {
  6558. lbModule *m = p->module;
  6559. lbValue res = {};
  6560. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  6561. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6562. res.type = alloc_type_pointer(result_type);
  6563. return res;
  6564. } else {
  6565. lbValue res = {};
  6566. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  6567. res.type = alloc_type_pointer(result_type);
  6568. return res;
  6569. }
  6570. }
  6571. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  6572. if (LLVMIsALoadInst(s.value)) {
  6573. lbValue res = {};
  6574. res.value = LLVMGetOperand(s.value, 0);
  6575. res.type = alloc_type_pointer(s.type);
  6576. lbValue ptr = lb_emit_struct_ep(p, res, index);
  6577. return lb_emit_load(p, ptr);
  6578. }
  6579. Type *t = base_type(s.type);
  6580. Type *result_type = nullptr;
  6581. switch (t->kind) {
  6582. case Type_Basic:
  6583. switch (t->Basic.kind) {
  6584. case Basic_string:
  6585. switch (index) {
  6586. case 0: result_type = t_u8_ptr; break;
  6587. case 1: result_type = t_int; break;
  6588. }
  6589. break;
  6590. case Basic_any:
  6591. switch (index) {
  6592. case 0: result_type = t_rawptr; break;
  6593. case 1: result_type = t_typeid; break;
  6594. }
  6595. break;
  6596. case Basic_complex32:
  6597. case Basic_complex64:
  6598. case Basic_complex128:
  6599. {
  6600. Type *ft = base_complex_elem_type(t);
  6601. switch (index) {
  6602. case 0: result_type = ft; break;
  6603. case 1: result_type = ft; break;
  6604. }
  6605. break;
  6606. }
  6607. case Basic_quaternion64:
  6608. case Basic_quaternion128:
  6609. case Basic_quaternion256:
  6610. {
  6611. Type *ft = base_complex_elem_type(t);
  6612. switch (index) {
  6613. case 0: result_type = ft; break;
  6614. case 1: result_type = ft; break;
  6615. case 2: result_type = ft; break;
  6616. case 3: result_type = ft; break;
  6617. }
  6618. break;
  6619. }
  6620. }
  6621. break;
  6622. case Type_Struct:
  6623. result_type = get_struct_field_type(t, index);
  6624. break;
  6625. case Type_Union:
  6626. GB_ASSERT(index == -1);
  6627. // return lb_emit_union_tag_value(p, s);
  6628. GB_PANIC("lb_emit_union_tag_value");
  6629. case Type_Tuple:
  6630. GB_ASSERT(t->Tuple.variables.count > 0);
  6631. result_type = t->Tuple.variables[index]->type;
  6632. if (t->Tuple.variables.count == 1) {
  6633. return s;
  6634. }
  6635. break;
  6636. case Type_Slice:
  6637. switch (index) {
  6638. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6639. case 1: result_type = t_int; break;
  6640. }
  6641. break;
  6642. case Type_DynamicArray:
  6643. switch (index) {
  6644. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6645. case 1: result_type = t_int; break;
  6646. case 2: result_type = t_int; break;
  6647. case 3: result_type = t_allocator; break;
  6648. }
  6649. break;
  6650. case Type_Map:
  6651. {
  6652. init_map_internal_types(t);
  6653. Type *gst = t->Map.generated_struct_type;
  6654. switch (index) {
  6655. case 0: result_type = get_struct_field_type(gst, 0); break;
  6656. case 1: result_type = get_struct_field_type(gst, 1); break;
  6657. }
  6658. }
  6659. break;
  6660. case Type_Array:
  6661. result_type = t->Array.elem;
  6662. break;
  6663. default:
  6664. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  6665. break;
  6666. }
  6667. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  6668. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6669. index += 1;
  6670. }
  6671. lbValue res = {};
  6672. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  6673. res.type = result_type;
  6674. return res;
  6675. }
  6676. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  6677. GB_ASSERT(sel.index.count > 0);
  6678. Type *type = type_deref(e.type);
  6679. for_array(i, sel.index) {
  6680. i32 index = cast(i32)sel.index[i];
  6681. if (is_type_pointer(type)) {
  6682. type = type_deref(type);
  6683. e = lb_emit_load(p, e);
  6684. }
  6685. type = core_type(type);
  6686. if (is_type_quaternion(type)) {
  6687. e = lb_emit_struct_ep(p, e, index);
  6688. } else if (is_type_raw_union(type)) {
  6689. type = get_struct_field_type(type, index);
  6690. GB_ASSERT(is_type_pointer(e.type));
  6691. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  6692. } else if (is_type_struct(type)) {
  6693. type = get_struct_field_type(type, index);
  6694. e = lb_emit_struct_ep(p, e, index);
  6695. } else if (type->kind == Type_Union) {
  6696. GB_ASSERT(index == -1);
  6697. type = t_type_info_ptr;
  6698. e = lb_emit_struct_ep(p, e, index);
  6699. } else if (type->kind == Type_Tuple) {
  6700. type = type->Tuple.variables[index]->type;
  6701. e = lb_emit_struct_ep(p, e, index);
  6702. } else if (type->kind == Type_Basic) {
  6703. switch (type->Basic.kind) {
  6704. case Basic_any: {
  6705. if (index == 0) {
  6706. type = t_rawptr;
  6707. } else if (index == 1) {
  6708. type = t_type_info_ptr;
  6709. }
  6710. e = lb_emit_struct_ep(p, e, index);
  6711. break;
  6712. }
  6713. case Basic_string:
  6714. e = lb_emit_struct_ep(p, e, index);
  6715. break;
  6716. default:
  6717. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6718. break;
  6719. }
  6720. } else if (type->kind == Type_Slice) {
  6721. e = lb_emit_struct_ep(p, e, index);
  6722. } else if (type->kind == Type_DynamicArray) {
  6723. e = lb_emit_struct_ep(p, e, index);
  6724. } else if (type->kind == Type_Array) {
  6725. e = lb_emit_array_epi(p, e, index);
  6726. } else if (type->kind == Type_Map) {
  6727. e = lb_emit_struct_ep(p, e, index);
  6728. } else if (type->kind == Type_RelativePointer) {
  6729. e = lb_emit_struct_ep(p, e, index);
  6730. } else {
  6731. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6732. }
  6733. }
  6734. return e;
  6735. }
  6736. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6737. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6738. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6739. return lb_emit_load(p, res);
  6740. }
  6741. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  6742. // NOTE(bill): The prev block may defer injection before it's terminator
  6743. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6744. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6745. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6746. return;
  6747. }
  6748. isize prev_context_stack_count = p->context_stack.count;
  6749. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  6750. defer (p->context_stack.count = prev_context_stack_count);
  6751. p->context_stack.count = d.context_stack_count;
  6752. lbBlock *b = lb_create_block(p, "defer");
  6753. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6754. lb_emit_jump(p, b);
  6755. }
  6756. lb_start_block(p, b);
  6757. if (d.kind == lbDefer_Node) {
  6758. lb_build_stmt(p, d.stmt);
  6759. } else if (d.kind == lbDefer_Instr) {
  6760. // NOTE(bill): Need to make a new copy
  6761. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6762. LLVMInsertIntoBuilder(p->builder, instr);
  6763. } else if (d.kind == lbDefer_Proc) {
  6764. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6765. }
  6766. }
  6767. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6768. isize count = p->defer_stmts.count;
  6769. isize i = count;
  6770. while (i --> 0) {
  6771. lbDefer const &d = p->defer_stmts[i];
  6772. if (kind == lbDeferExit_Default) {
  6773. if (p->scope_index == d.scope_index &&
  6774. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6775. lb_build_defer_stmt(p, d);
  6776. array_pop(&p->defer_stmts);
  6777. continue;
  6778. } else {
  6779. break;
  6780. }
  6781. } else if (kind == lbDeferExit_Return) {
  6782. lb_build_defer_stmt(p, d);
  6783. } else if (kind == lbDeferExit_Branch) {
  6784. GB_ASSERT(block != nullptr);
  6785. isize lower_limit = block->scope_index;
  6786. if (lower_limit < d.scope_index) {
  6787. lb_build_defer_stmt(p, d);
  6788. }
  6789. }
  6790. }
  6791. }
  6792. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  6793. Type *pt = base_type(p->type);
  6794. GB_ASSERT(pt->kind == Type_Proc);
  6795. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6796. GB_ASSERT(p->context_stack.count != 0);
  6797. }
  6798. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6799. d->kind = lbDefer_Node;
  6800. d->scope_index = scope_index;
  6801. d->context_stack_count = p->context_stack.count;
  6802. d->block = p->curr_block;
  6803. d->stmt = stmt;
  6804. }
  6805. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  6806. Type *pt = base_type(p->type);
  6807. GB_ASSERT(pt->kind == Type_Proc);
  6808. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6809. GB_ASSERT(p->context_stack.count != 0);
  6810. }
  6811. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6812. d->kind = lbDefer_Proc;
  6813. d->scope_index = p->scope_index;
  6814. d->block = p->curr_block;
  6815. d->context_stack_count = p->context_stack.count;
  6816. d->proc.deferred = deferred;
  6817. d->proc.result_as_args = result_as_args;
  6818. }
  6819. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  6820. Array<lbValue> array = {};
  6821. Type *t = base_type(value.type);
  6822. if (t == nullptr) {
  6823. // Do nothing
  6824. } else if (is_type_tuple(t)) {
  6825. GB_ASSERT(t->kind == Type_Tuple);
  6826. auto *rt = &t->Tuple;
  6827. if (rt->variables.count > 0) {
  6828. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  6829. for_array(i, rt->variables) {
  6830. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  6831. array[i] = elem;
  6832. }
  6833. }
  6834. } else {
  6835. array = array_make<lbValue>(permanent_allocator(), 1);
  6836. array[0] = value;
  6837. }
  6838. return array;
  6839. }
  6840. 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) {
  6841. unsigned arg_count = cast(unsigned)processed_args.count;
  6842. if (return_ptr.value != nullptr) {
  6843. arg_count += 1;
  6844. }
  6845. if (context_ptr.addr.value != nullptr) {
  6846. arg_count += 1;
  6847. }
  6848. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  6849. isize arg_index = 0;
  6850. if (return_ptr.value != nullptr) {
  6851. args[arg_index++] = return_ptr.value;
  6852. }
  6853. for_array(i, processed_args) {
  6854. lbValue arg = processed_args[i];
  6855. args[arg_index++] = arg.value;
  6856. }
  6857. if (context_ptr.addr.value != nullptr) {
  6858. LLVMValueRef cp = context_ptr.addr.value;
  6859. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  6860. args[arg_index++] = cp;
  6861. }
  6862. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  6863. GB_ASSERT(curr_block != p->decl_block->block);
  6864. {
  6865. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6866. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6867. LLVMValueRef fn = value.value;
  6868. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6869. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6870. }
  6871. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6872. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6873. {
  6874. unsigned param_count = LLVMCountParamTypes(fnp);
  6875. GB_ASSERT(arg_count >= param_count);
  6876. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  6877. LLVMGetParamTypes(fnp, param_types);
  6878. for (unsigned i = 0; i < param_count; i++) {
  6879. LLVMTypeRef param_type = param_types[i];
  6880. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  6881. GB_ASSERT_MSG(
  6882. arg_type == param_type,
  6883. "Parameter types do not match: %s != %s, argument: %s",
  6884. LLVMPrintTypeToString(arg_type),
  6885. LLVMPrintTypeToString(param_type),
  6886. LLVMPrintValueToString(args[i])
  6887. );
  6888. }
  6889. }
  6890. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  6891. switch (inlining) {
  6892. case ProcInlining_none:
  6893. break;
  6894. case ProcInlining_inline:
  6895. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  6896. break;
  6897. case ProcInlining_no_inline:
  6898. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  6899. break;
  6900. }
  6901. lbValue res = {};
  6902. res.value = ret;
  6903. res.type = abi_rt;
  6904. return res;
  6905. }
  6906. }
  6907. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6908. // LLVMMetadataRef curr_loc = LLVMGetCurrentDebugLocation2(p->builder);
  6909. // LLVMSetCurrentDebugLocation2(p->builder, nullptr);
  6910. // defer (if (curr_loc) {
  6911. // LLVMSetCurrentDebugLocation2(p->builder, curr_loc);
  6912. // });
  6913. String name = make_string_c(c_name);
  6914. AstPackage *pkg = p->module->info->runtime_package;
  6915. Entity *e = scope_lookup_current(pkg->scope, name);
  6916. lbValue *found = nullptr;
  6917. if (p->module != e->code_gen_module) {
  6918. gb_mutex_lock(&p->module->mutex);
  6919. }
  6920. GB_ASSERT(e->code_gen_module != nullptr);
  6921. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6922. if (p->module != e->code_gen_module) {
  6923. gb_mutex_unlock(&p->module->mutex);
  6924. }
  6925. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6926. return lb_emit_call(p, *found, args);
  6927. }
  6928. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6929. lbModule *m = p->module;
  6930. Type *pt = base_type(value.type);
  6931. GB_ASSERT(pt->kind == Type_Proc);
  6932. Type *results = pt->Proc.results;
  6933. if (p->entity != nullptr) {
  6934. if (p->entity->flags & EntityFlag_Disabled) {
  6935. return {};
  6936. }
  6937. }
  6938. lbAddr context_ptr = {};
  6939. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6940. context_ptr = lb_find_or_generate_context_ptr(p);
  6941. }
  6942. defer (if (pt->Proc.diverging) {
  6943. LLVMBuildUnreachable(p->builder);
  6944. });
  6945. bool is_c_vararg = pt->Proc.c_vararg;
  6946. isize param_count = pt->Proc.param_count;
  6947. if (is_c_vararg) {
  6948. GB_ASSERT(param_count-1 <= args.count);
  6949. param_count -= 1;
  6950. } else {
  6951. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6952. }
  6953. lbValue result = {};
  6954. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6955. {
  6956. lbFunctionType **ft_found = nullptr;
  6957. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6958. if (!ft_found) {
  6959. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6960. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6961. }
  6962. GB_ASSERT(ft_found != nullptr);
  6963. lbFunctionType *ft = *ft_found;
  6964. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6965. unsigned param_index = 0;
  6966. for (isize i = 0; i < param_count; i++) {
  6967. Entity *e = pt->Proc.params->Tuple.variables[i];
  6968. if (e->kind != Entity_Variable) {
  6969. continue;
  6970. }
  6971. GB_ASSERT(e->flags & EntityFlag_Param);
  6972. Type *original_type = e->type;
  6973. lbArgType *arg = &ft->args[param_index];
  6974. if (arg->kind == lbArg_Ignore) {
  6975. continue;
  6976. }
  6977. lbValue x = lb_emit_conv(p, args[i], original_type);
  6978. LLVMTypeRef xt = lb_type(p->module, x.type);
  6979. if (arg->kind == lbArg_Direct) {
  6980. LLVMTypeRef abi_type = arg->cast_type;
  6981. if (!abi_type) {
  6982. abi_type = arg->type;
  6983. }
  6984. if (xt == abi_type) {
  6985. array_add(&processed_args, x);
  6986. } else {
  6987. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6988. array_add(&processed_args, x);
  6989. }
  6990. } else if (arg->kind == lbArg_Indirect) {
  6991. lbValue ptr = {};
  6992. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6993. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6994. // i.e. `T const &` in C++
  6995. ptr = lb_address_from_load_or_generate_local(p, x);
  6996. } else {
  6997. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6998. }
  6999. array_add(&processed_args, ptr);
  7000. }
  7001. param_index += 1;
  7002. }
  7003. if (inlining == ProcInlining_none) {
  7004. inlining = p->inlining;
  7005. }
  7006. Type *rt = reduce_tuple_to_single_type(results);
  7007. if (return_by_pointer) {
  7008. lbValue return_ptr = {};
  7009. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  7010. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  7011. return_ptr = p->return_ptr_hint_value;
  7012. p->return_ptr_hint_used = true;
  7013. }
  7014. }
  7015. if (return_ptr.value == nullptr) {
  7016. lbAddr r = lb_add_local_generated(p, rt, true);
  7017. return_ptr = r.addr;
  7018. }
  7019. GB_ASSERT(is_type_pointer(return_ptr.type));
  7020. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  7021. result = lb_emit_load(p, return_ptr);
  7022. } else if (rt != nullptr) {
  7023. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  7024. if (ft->ret.cast_type) {
  7025. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  7026. }
  7027. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  7028. result.type = rt;
  7029. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  7030. result.type = t_llvm_bool;
  7031. }
  7032. if (!is_type_tuple(rt)) {
  7033. result = lb_emit_conv(p, result, rt);
  7034. }
  7035. } else {
  7036. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  7037. }
  7038. }
  7039. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  7040. if (found != nullptr) {
  7041. Entity *e = *found;
  7042. if (e != nullptr && entity_has_deferred_procedure(e)) {
  7043. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  7044. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  7045. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  7046. GB_ASSERT(deferred_found != nullptr);
  7047. lbValue deferred = *deferred_found;
  7048. auto in_args = args;
  7049. Array<lbValue> result_as_args = {};
  7050. switch (kind) {
  7051. case DeferredProcedure_none:
  7052. break;
  7053. case DeferredProcedure_in:
  7054. result_as_args = in_args;
  7055. break;
  7056. case DeferredProcedure_out:
  7057. result_as_args = lb_value_to_array(p, result);
  7058. break;
  7059. case DeferredProcedure_in_out:
  7060. {
  7061. auto out_args = lb_value_to_array(p, result);
  7062. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  7063. array_copy(&result_as_args, in_args, 0);
  7064. array_copy(&result_as_args, out_args, in_args.count);
  7065. }
  7066. break;
  7067. }
  7068. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  7069. }
  7070. }
  7071. return result;
  7072. }
  7073. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  7074. Type *t = s.type;
  7075. GB_ASSERT(is_type_pointer(t));
  7076. Type *st = base_type(type_deref(t));
  7077. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7078. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  7079. LLVMValueRef indices[2] = {};
  7080. indices[0] = llvm_zero(p->module);
  7081. indices[1] = lb_emit_conv(p, index, t_int).value;
  7082. Type *ptr = base_array_type(st);
  7083. lbValue res = {};
  7084. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  7085. res.type = alloc_type_pointer(ptr);
  7086. return res;
  7087. }
  7088. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  7089. Type *t = s.type;
  7090. GB_ASSERT(is_type_pointer(t));
  7091. Type *st = base_type(type_deref(t));
  7092. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7093. GB_ASSERT(0 <= index);
  7094. Type *ptr = base_array_type(st);
  7095. LLVMValueRef indices[2] = {
  7096. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  7097. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  7098. };
  7099. lbValue res = {};
  7100. if (lb_is_const(s)) {
  7101. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  7102. } else {
  7103. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  7104. }
  7105. res.type = alloc_type_pointer(ptr);
  7106. return res;
  7107. }
  7108. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  7109. LLVMValueRef indices[1] = {index.value};
  7110. lbValue res = {};
  7111. res.type = ptr.type;
  7112. if (lb_is_const(ptr) && lb_is_const(index)) {
  7113. res.value = LLVMConstGEP(ptr.value, indices, 1);
  7114. } else {
  7115. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  7116. }
  7117. return res;
  7118. }
  7119. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  7120. GB_ASSERT(is_type_pointer(data.type));
  7121. GB_ASSERT(are_types_identical(len.type, t_int));
  7122. LLVMValueRef vals[2] = {
  7123. data.value,
  7124. len.value,
  7125. };
  7126. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  7127. }
  7128. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  7129. Type *t = lb_addr_type(slice);
  7130. GB_ASSERT(is_type_slice(t));
  7131. lbValue ptr = lb_addr_get_ptr(p, slice);
  7132. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7133. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7134. }
  7135. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  7136. Type *t = lb_addr_type(string);
  7137. GB_ASSERT(is_type_string(t));
  7138. lbValue ptr = lb_addr_get_ptr(p, string);
  7139. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7140. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7141. }
  7142. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  7143. Type *t = base_type(string.type);
  7144. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  7145. return lb_emit_struct_ev(p, string, 0);
  7146. }
  7147. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  7148. Type *t = base_type(string.type);
  7149. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  7150. return lb_emit_struct_ev(p, string, 1);
  7151. }
  7152. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  7153. GB_ASSERT(is_type_cstring(value.type));
  7154. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7155. args[0] = lb_emit_conv(p, value, t_cstring);
  7156. return lb_emit_runtime_call(p, "cstring_len", args);
  7157. }
  7158. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  7159. Type *t = type_deref(array_ptr.type);
  7160. GB_ASSERT(is_type_array(t));
  7161. return lb_emit_struct_ep(p, array_ptr, 0);
  7162. }
  7163. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  7164. GB_ASSERT(is_type_slice(slice.type));
  7165. return lb_emit_struct_ev(p, slice, 0);
  7166. }
  7167. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  7168. GB_ASSERT(is_type_slice(slice.type));
  7169. return lb_emit_struct_ev(p, slice, 1);
  7170. }
  7171. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  7172. GB_ASSERT(is_type_dynamic_array(da.type));
  7173. return lb_emit_struct_ev(p, da, 0);
  7174. }
  7175. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  7176. GB_ASSERT(is_type_dynamic_array(da.type));
  7177. return lb_emit_struct_ev(p, da, 1);
  7178. }
  7179. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  7180. GB_ASSERT(is_type_dynamic_array(da.type));
  7181. return lb_emit_struct_ev(p, da, 2);
  7182. }
  7183. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  7184. GB_ASSERT(is_type_dynamic_array(da.type));
  7185. return lb_emit_struct_ev(p, da, 3);
  7186. }
  7187. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  7188. Type *t = base_type(value.type);
  7189. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7190. init_map_internal_types(t);
  7191. Type *gst = t->Map.generated_struct_type;
  7192. i32 index = 1;
  7193. lbValue entries = lb_emit_struct_ev(p, value, index);
  7194. return entries;
  7195. }
  7196. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  7197. Type *t = base_type(type_deref(value.type));
  7198. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7199. init_map_internal_types(t);
  7200. Type *gst = t->Map.generated_struct_type;
  7201. i32 index = 1;
  7202. lbValue entries = lb_emit_struct_ep(p, value, index);
  7203. return entries;
  7204. }
  7205. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  7206. lbValue entries = lb_map_entries(p, value);
  7207. return lb_dynamic_array_len(p, entries);
  7208. }
  7209. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  7210. lbValue entries = lb_map_entries(p, value);
  7211. return lb_dynamic_array_cap(p, entries);
  7212. }
  7213. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  7214. Type *t = base_type(value.type);
  7215. bool is_ptr = false;
  7216. if (is_type_pointer(t)) {
  7217. is_ptr = true;
  7218. t = base_type(type_deref(t));
  7219. }
  7220. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7221. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7222. }
  7223. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  7224. t->Struct.soa_kind == StructSoa_Dynamic);
  7225. isize n = 0;
  7226. Type *elem = base_type(t->Struct.soa_elem);
  7227. if (elem->kind == Type_Struct) {
  7228. n = elem->Struct.fields.count;
  7229. } else if (elem->kind == Type_Array) {
  7230. n = elem->Array.count;
  7231. } else {
  7232. GB_PANIC("Unreachable");
  7233. }
  7234. if (is_ptr) {
  7235. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7236. return lb_emit_load(p, v);
  7237. }
  7238. return lb_emit_struct_ev(p, value, cast(i32)n);
  7239. }
  7240. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  7241. Type *t = base_type(value.type);
  7242. bool is_ptr = false;
  7243. if (is_type_pointer(t)) {
  7244. is_ptr = true;
  7245. t = base_type(type_deref(t));
  7246. }
  7247. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7248. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7249. }
  7250. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  7251. isize n = 0;
  7252. Type *elem = base_type(t->Struct.soa_elem);
  7253. if (elem->kind == Type_Struct) {
  7254. n = elem->Struct.fields.count+1;
  7255. } else if (elem->kind == Type_Array) {
  7256. n = elem->Array.count+1;
  7257. } else {
  7258. GB_PANIC("Unreachable");
  7259. }
  7260. if (is_ptr) {
  7261. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7262. return lb_emit_load(p, v);
  7263. }
  7264. return lb_emit_struct_ev(p, value, cast(i32)n);
  7265. }
  7266. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7267. GB_ASSERT(ce->args.count > 0);
  7268. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  7269. for_array(i, slices) {
  7270. Ast *arg = ce->args[i];
  7271. if (arg->kind == Ast_FieldValue) {
  7272. arg = arg->FieldValue.value;
  7273. }
  7274. slices[i] = lb_build_expr(p, arg);
  7275. }
  7276. lbValue len = lb_slice_len(p, slices[0]);
  7277. for (isize i = 1; i < slices.count; i++) {
  7278. lbValue other_len = lb_slice_len(p, slices[i]);
  7279. len = lb_emit_min(p, t_int, len, other_len);
  7280. }
  7281. GB_ASSERT(is_type_soa_struct(tv.type));
  7282. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7283. for_array(i, slices) {
  7284. lbValue src = lb_slice_elem(p, slices[i]);
  7285. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  7286. lb_emit_store(p, dst, src);
  7287. }
  7288. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  7289. lb_emit_store(p, len_dst, len);
  7290. return lb_addr_load(p, res);
  7291. }
  7292. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7293. GB_ASSERT(ce->args.count == 1);
  7294. lbValue arg = lb_build_expr(p, ce->args[0]);
  7295. Type *t = base_type(arg.type);
  7296. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  7297. lbValue len = lb_soa_struct_len(p, arg);
  7298. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7299. if (is_type_tuple(tv.type)) {
  7300. lbValue rp = lb_addr_get_ptr(p, res);
  7301. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  7302. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  7303. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  7304. lb_fill_slice(p, dst, ptr, len);
  7305. }
  7306. } else {
  7307. GB_ASSERT(is_type_slice(tv.type));
  7308. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  7309. lb_fill_slice(p, res, ptr, len);
  7310. }
  7311. return lb_addr_load(p, res);
  7312. }
  7313. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  7314. ast_node(ce, CallExpr, expr);
  7315. switch (id) {
  7316. case BuiltinProc_DIRECTIVE: {
  7317. ast_node(bd, BasicDirective, ce->proc);
  7318. String name = bd->name;
  7319. GB_ASSERT(name == "location");
  7320. String procedure = p->entity->token.string;
  7321. TokenPos pos = ast_token(ce->proc).pos;
  7322. if (ce->args.count > 0) {
  7323. Ast *ident = unselector_expr(ce->args[0]);
  7324. GB_ASSERT(ident->kind == Ast_Ident);
  7325. Entity *e = entity_of_node(ident);
  7326. GB_ASSERT(e != nullptr);
  7327. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  7328. procedure = e->parent_proc_decl->entity->token.string;
  7329. } else {
  7330. procedure = str_lit("");
  7331. }
  7332. pos = e->token.pos;
  7333. }
  7334. return lb_emit_source_code_location(p, procedure, pos);
  7335. }
  7336. case BuiltinProc_type_info_of: {
  7337. Ast *arg = ce->args[0];
  7338. TypeAndValue tav = type_and_value_of_expr(arg);
  7339. if (tav.mode == Addressing_Type) {
  7340. Type *t = default_type(type_of_expr(arg));
  7341. return lb_type_info(p->module, t);
  7342. }
  7343. GB_ASSERT(is_type_typeid(tav.type));
  7344. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7345. args[0] = lb_build_expr(p, arg);
  7346. return lb_emit_runtime_call(p, "__type_info_of", args);
  7347. }
  7348. case BuiltinProc_typeid_of: {
  7349. Ast *arg = ce->args[0];
  7350. TypeAndValue tav = type_and_value_of_expr(arg);
  7351. GB_ASSERT(tav.mode == Addressing_Type);
  7352. Type *t = default_type(type_of_expr(arg));
  7353. return lb_typeid(p->module, t);
  7354. }
  7355. case BuiltinProc_len: {
  7356. lbValue v = lb_build_expr(p, ce->args[0]);
  7357. Type *t = base_type(v.type);
  7358. if (is_type_pointer(t)) {
  7359. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7360. v = lb_emit_load(p, v);
  7361. t = type_deref(t);
  7362. }
  7363. if (is_type_cstring(t)) {
  7364. return lb_cstring_len(p, v);
  7365. } else if (is_type_string(t)) {
  7366. return lb_string_len(p, v);
  7367. } else if (is_type_array(t)) {
  7368. GB_PANIC("Array lengths are constant");
  7369. } else if (is_type_slice(t)) {
  7370. return lb_slice_len(p, v);
  7371. } else if (is_type_dynamic_array(t)) {
  7372. return lb_dynamic_array_len(p, v);
  7373. } else if (is_type_map(t)) {
  7374. return lb_map_len(p, v);
  7375. } else if (is_type_soa_struct(t)) {
  7376. return lb_soa_struct_len(p, v);
  7377. }
  7378. GB_PANIC("Unreachable");
  7379. break;
  7380. }
  7381. case BuiltinProc_cap: {
  7382. lbValue v = lb_build_expr(p, ce->args[0]);
  7383. Type *t = base_type(v.type);
  7384. if (is_type_pointer(t)) {
  7385. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7386. v = lb_emit_load(p, v);
  7387. t = type_deref(t);
  7388. }
  7389. if (is_type_string(t)) {
  7390. GB_PANIC("Unreachable");
  7391. } else if (is_type_array(t)) {
  7392. GB_PANIC("Array lengths are constant");
  7393. } else if (is_type_slice(t)) {
  7394. return lb_slice_len(p, v);
  7395. } else if (is_type_dynamic_array(t)) {
  7396. return lb_dynamic_array_cap(p, v);
  7397. } else if (is_type_map(t)) {
  7398. return lb_map_cap(p, v);
  7399. } else if (is_type_soa_struct(t)) {
  7400. return lb_soa_struct_cap(p, v);
  7401. }
  7402. GB_PANIC("Unreachable");
  7403. break;
  7404. }
  7405. case BuiltinProc_swizzle: {
  7406. isize index_count = ce->args.count-1;
  7407. if (is_type_simd_vector(tv.type)) {
  7408. lbValue vec = lb_build_expr(p, ce->args[0]);
  7409. if (index_count == 0) {
  7410. return vec;
  7411. }
  7412. unsigned mask_len = cast(unsigned)index_count;
  7413. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  7414. for (isize i = 1; i < ce->args.count; i++) {
  7415. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7416. GB_ASSERT(is_type_integer(tv.type));
  7417. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7418. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  7419. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  7420. }
  7421. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  7422. LLVMValueRef v1 = vec.value;
  7423. LLVMValueRef v2 = vec.value;
  7424. lbValue res = {};
  7425. res.type = tv.type;
  7426. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  7427. return res;
  7428. }
  7429. lbAddr addr = lb_build_addr(p, ce->args[0]);
  7430. if (index_count == 0) {
  7431. return lb_addr_load(p, addr);
  7432. }
  7433. lbValue src = lb_addr_get_ptr(p, addr);
  7434. // TODO(bill): Should this be zeroed or not?
  7435. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  7436. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  7437. for (i32 i = 1; i < ce->args.count; i++) {
  7438. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7439. GB_ASSERT(is_type_integer(tv.type));
  7440. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7441. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  7442. i32 dst_index = i-1;
  7443. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  7444. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  7445. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  7446. }
  7447. return lb_addr_load(p, dst);
  7448. }
  7449. case BuiltinProc_complex: {
  7450. lbValue real = lb_build_expr(p, ce->args[0]);
  7451. lbValue imag = lb_build_expr(p, ce->args[1]);
  7452. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7453. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7454. Type *ft = base_complex_elem_type(tv.type);
  7455. real = lb_emit_conv(p, real, ft);
  7456. imag = lb_emit_conv(p, imag, ft);
  7457. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  7458. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  7459. return lb_emit_load(p, dst);
  7460. }
  7461. case BuiltinProc_quaternion: {
  7462. lbValue real = lb_build_expr(p, ce->args[0]);
  7463. lbValue imag = lb_build_expr(p, ce->args[1]);
  7464. lbValue jmag = lb_build_expr(p, ce->args[2]);
  7465. lbValue kmag = lb_build_expr(p, ce->args[3]);
  7466. // @QuaternionLayout
  7467. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7468. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7469. Type *ft = base_complex_elem_type(tv.type);
  7470. real = lb_emit_conv(p, real, ft);
  7471. imag = lb_emit_conv(p, imag, ft);
  7472. jmag = lb_emit_conv(p, jmag, ft);
  7473. kmag = lb_emit_conv(p, kmag, ft);
  7474. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  7475. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  7476. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  7477. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  7478. return lb_emit_load(p, dst);
  7479. }
  7480. case BuiltinProc_real: {
  7481. lbValue val = lb_build_expr(p, ce->args[0]);
  7482. if (is_type_complex(val.type)) {
  7483. lbValue real = lb_emit_struct_ev(p, val, 0);
  7484. return lb_emit_conv(p, real, tv.type);
  7485. } else if (is_type_quaternion(val.type)) {
  7486. // @QuaternionLayout
  7487. lbValue real = lb_emit_struct_ev(p, val, 3);
  7488. return lb_emit_conv(p, real, tv.type);
  7489. }
  7490. GB_PANIC("invalid type for real");
  7491. return {};
  7492. }
  7493. case BuiltinProc_imag: {
  7494. lbValue val = lb_build_expr(p, ce->args[0]);
  7495. if (is_type_complex(val.type)) {
  7496. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7497. return lb_emit_conv(p, imag, tv.type);
  7498. } else if (is_type_quaternion(val.type)) {
  7499. // @QuaternionLayout
  7500. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7501. return lb_emit_conv(p, imag, tv.type);
  7502. }
  7503. GB_PANIC("invalid type for imag");
  7504. return {};
  7505. }
  7506. case BuiltinProc_jmag: {
  7507. lbValue val = lb_build_expr(p, ce->args[0]);
  7508. if (is_type_quaternion(val.type)) {
  7509. // @QuaternionLayout
  7510. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7511. return lb_emit_conv(p, imag, tv.type);
  7512. }
  7513. GB_PANIC("invalid type for jmag");
  7514. return {};
  7515. }
  7516. case BuiltinProc_kmag: {
  7517. lbValue val = lb_build_expr(p, ce->args[0]);
  7518. if (is_type_quaternion(val.type)) {
  7519. // @QuaternionLayout
  7520. lbValue imag = lb_emit_struct_ev(p, val, 2);
  7521. return lb_emit_conv(p, imag, tv.type);
  7522. }
  7523. GB_PANIC("invalid type for kmag");
  7524. return {};
  7525. }
  7526. case BuiltinProc_conj: {
  7527. lbValue val = lb_build_expr(p, ce->args[0]);
  7528. lbValue res = {};
  7529. Type *t = val.type;
  7530. if (is_type_complex(t)) {
  7531. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7532. lbValue real = lb_emit_struct_ev(p, val, 0);
  7533. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7534. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7535. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  7536. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  7537. } else if (is_type_quaternion(t)) {
  7538. // @QuaternionLayout
  7539. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7540. lbValue real = lb_emit_struct_ev(p, val, 3);
  7541. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7542. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  7543. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  7544. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7545. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  7546. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  7547. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  7548. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  7549. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  7550. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  7551. }
  7552. return lb_emit_load(p, res);
  7553. }
  7554. case BuiltinProc_expand_to_tuple: {
  7555. lbValue val = lb_build_expr(p, ce->args[0]);
  7556. Type *t = base_type(val.type);
  7557. if (!is_type_tuple(tv.type)) {
  7558. if (t->kind == Type_Struct) {
  7559. GB_ASSERT(t->Struct.fields.count == 1);
  7560. return lb_emit_struct_ev(p, val, 0);
  7561. } else if (t->kind == Type_Array) {
  7562. GB_ASSERT(t->Array.count == 1);
  7563. return lb_emit_array_epi(p, val, 0);
  7564. } else {
  7565. GB_PANIC("Unknown type of expand_to_tuple");
  7566. }
  7567. }
  7568. GB_ASSERT(is_type_tuple(tv.type));
  7569. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7570. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7571. if (t->kind == Type_Struct) {
  7572. for_array(src_index, t->Struct.fields) {
  7573. Entity *field = t->Struct.fields[src_index];
  7574. i32 field_index = field->Variable.field_index;
  7575. lbValue f = lb_emit_struct_ev(p, val, field_index);
  7576. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  7577. lb_emit_store(p, ep, f);
  7578. }
  7579. } else if (t->kind == Type_Array) {
  7580. // TODO(bill): Clean-up this code
  7581. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  7582. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  7583. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  7584. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  7585. lb_emit_store(p, ep, f);
  7586. }
  7587. } else {
  7588. GB_PANIC("Unknown type of expand_to_tuple");
  7589. }
  7590. return lb_emit_load(p, tuple);
  7591. }
  7592. case BuiltinProc_min: {
  7593. Type *t = type_of_expr(expr);
  7594. if (ce->args.count == 2) {
  7595. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7596. } else {
  7597. lbValue x = lb_build_expr(p, ce->args[0]);
  7598. for (isize i = 1; i < ce->args.count; i++) {
  7599. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  7600. }
  7601. return x;
  7602. }
  7603. }
  7604. case BuiltinProc_max: {
  7605. Type *t = type_of_expr(expr);
  7606. if (ce->args.count == 2) {
  7607. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7608. } else {
  7609. lbValue x = lb_build_expr(p, ce->args[0]);
  7610. for (isize i = 1; i < ce->args.count; i++) {
  7611. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  7612. }
  7613. return x;
  7614. }
  7615. }
  7616. case BuiltinProc_abs: {
  7617. lbValue x = lb_build_expr(p, ce->args[0]);
  7618. Type *t = x.type;
  7619. if (is_type_unsigned(t)) {
  7620. return x;
  7621. }
  7622. if (is_type_quaternion(t)) {
  7623. i64 sz = 8*type_size_of(t);
  7624. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7625. args[0] = x;
  7626. switch (sz) {
  7627. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  7628. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  7629. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  7630. }
  7631. GB_PANIC("Unknown complex type");
  7632. } else if (is_type_complex(t)) {
  7633. i64 sz = 8*type_size_of(t);
  7634. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7635. args[0] = x;
  7636. switch (sz) {
  7637. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  7638. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  7639. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  7640. }
  7641. GB_PANIC("Unknown complex type");
  7642. } else if (is_type_float(t)) {
  7643. i64 sz = 8*type_size_of(t);
  7644. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7645. args[0] = x;
  7646. switch (sz) {
  7647. case 16: return lb_emit_runtime_call(p, "abs_f16", args);
  7648. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  7649. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  7650. }
  7651. GB_PANIC("Unknown float type");
  7652. }
  7653. lbValue zero = lb_const_nil(p->module, t);
  7654. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  7655. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  7656. return lb_emit_select(p, cond, neg, x);
  7657. }
  7658. case BuiltinProc_clamp:
  7659. return lb_emit_clamp(p, type_of_expr(expr),
  7660. lb_build_expr(p, ce->args[0]),
  7661. lb_build_expr(p, ce->args[1]),
  7662. lb_build_expr(p, ce->args[2]));
  7663. case BuiltinProc_soa_zip:
  7664. return lb_soa_zip(p, ce, tv);
  7665. case BuiltinProc_soa_unzip:
  7666. return lb_soa_unzip(p, ce, tv);
  7667. // "Intrinsics"
  7668. case BuiltinProc_alloca:
  7669. {
  7670. lbValue sz = lb_build_expr(p, ce->args[0]);
  7671. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  7672. lbValue res = {};
  7673. res.type = t_u8_ptr;
  7674. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  7675. LLVMSetAlignment(res.value, cast(unsigned)al);
  7676. return res;
  7677. }
  7678. case BuiltinProc_cpu_relax:
  7679. if (build_context.metrics.arch == TargetArch_386 ||
  7680. build_context.metrics.arch == TargetArch_amd64) {
  7681. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7682. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7683. cast(char *)"pause", 5,
  7684. cast(char *)"", 0,
  7685. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7686. LLVMInlineAsmDialectATT
  7687. );
  7688. GB_ASSERT(the_asm != nullptr);
  7689. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7690. } else if (build_context.metrics.arch == TargetArch_arm64) {
  7691. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7692. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7693. cast(char *)"yield", 5,
  7694. cast(char *)"", 0,
  7695. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7696. LLVMInlineAsmDialectATT
  7697. );
  7698. GB_ASSERT(the_asm != nullptr);
  7699. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7700. }
  7701. return {};
  7702. case BuiltinProc_debug_trap:
  7703. case BuiltinProc_trap:
  7704. {
  7705. char const *name = nullptr;
  7706. switch (id) {
  7707. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  7708. case BuiltinProc_trap: name = "llvm.trap"; break;
  7709. }
  7710. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  7711. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  7712. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  7713. LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  7714. if (id == BuiltinProc_trap) {
  7715. LLVMBuildUnreachable(p->builder);
  7716. }
  7717. return {};
  7718. }
  7719. case BuiltinProc_read_cycle_counter:
  7720. {
  7721. char const *name = "llvm.readcyclecounter";
  7722. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  7723. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  7724. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  7725. lbValue res = {};
  7726. res.value = LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  7727. res.type = tv.type;
  7728. return res;
  7729. }
  7730. case BuiltinProc_count_trailing_zeros:
  7731. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  7732. case BuiltinProc_count_leading_zeros:
  7733. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  7734. case BuiltinProc_count_ones:
  7735. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  7736. case BuiltinProc_count_zeros:
  7737. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  7738. case BuiltinProc_reverse_bits:
  7739. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  7740. case BuiltinProc_byte_swap:
  7741. {
  7742. lbValue x = lb_build_expr(p, ce->args[0]);
  7743. x = lb_emit_conv(p, x, tv.type);
  7744. return lb_emit_byte_swap(p, x, tv.type);
  7745. }
  7746. case BuiltinProc_overflow_add:
  7747. case BuiltinProc_overflow_sub:
  7748. case BuiltinProc_overflow_mul:
  7749. {
  7750. Type *main_type = tv.type;
  7751. Type *type = main_type;
  7752. if (is_type_tuple(main_type)) {
  7753. type = main_type->Tuple.variables[0]->type;
  7754. }
  7755. lbValue x = lb_build_expr(p, ce->args[0]);
  7756. lbValue y = lb_build_expr(p, ce->args[1]);
  7757. x = lb_emit_conv(p, x, type);
  7758. y = lb_emit_conv(p, y, type);
  7759. char const *name = nullptr;
  7760. if (is_type_unsigned(type)) {
  7761. switch (id) {
  7762. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  7763. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  7764. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  7765. }
  7766. } else {
  7767. switch (id) {
  7768. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  7769. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  7770. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  7771. }
  7772. }
  7773. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  7774. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  7775. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  7776. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  7777. LLVMValueRef args[2] = {};
  7778. args[0] = x.value;
  7779. args[1] = y.value;
  7780. lbValue res = {};
  7781. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  7782. if (is_type_tuple(main_type)) {
  7783. Type *res_type = nullptr;
  7784. gbAllocator a = permanent_allocator();
  7785. res_type = alloc_type_tuple();
  7786. array_init(&res_type->Tuple.variables, a, 2);
  7787. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  7788. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7789. res.type = res_type;
  7790. } else {
  7791. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  7792. res.type = type;
  7793. }
  7794. return res;
  7795. }
  7796. case BuiltinProc_atomic_fence:
  7797. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  7798. return {};
  7799. case BuiltinProc_atomic_fence_acq:
  7800. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  7801. return {};
  7802. case BuiltinProc_atomic_fence_rel:
  7803. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  7804. return {};
  7805. case BuiltinProc_atomic_fence_acqrel:
  7806. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  7807. return {};
  7808. case BuiltinProc_volatile_store:
  7809. case BuiltinProc_atomic_store:
  7810. case BuiltinProc_atomic_store_rel:
  7811. case BuiltinProc_atomic_store_relaxed:
  7812. case BuiltinProc_atomic_store_unordered: {
  7813. lbValue dst = lb_build_expr(p, ce->args[0]);
  7814. lbValue val = lb_build_expr(p, ce->args[1]);
  7815. val = lb_emit_conv(p, val, type_deref(dst.type));
  7816. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  7817. switch (id) {
  7818. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  7819. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7820. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  7821. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7822. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7823. }
  7824. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7825. return {};
  7826. }
  7827. case BuiltinProc_volatile_load:
  7828. case BuiltinProc_atomic_load:
  7829. case BuiltinProc_atomic_load_acq:
  7830. case BuiltinProc_atomic_load_relaxed:
  7831. case BuiltinProc_atomic_load_unordered: {
  7832. lbValue dst = lb_build_expr(p, ce->args[0]);
  7833. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  7834. switch (id) {
  7835. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  7836. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7837. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  7838. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7839. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7840. }
  7841. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7842. lbValue res = {};
  7843. res.value = instr;
  7844. res.type = type_deref(dst.type);
  7845. return res;
  7846. }
  7847. case BuiltinProc_atomic_add:
  7848. case BuiltinProc_atomic_add_acq:
  7849. case BuiltinProc_atomic_add_rel:
  7850. case BuiltinProc_atomic_add_acqrel:
  7851. case BuiltinProc_atomic_add_relaxed:
  7852. case BuiltinProc_atomic_sub:
  7853. case BuiltinProc_atomic_sub_acq:
  7854. case BuiltinProc_atomic_sub_rel:
  7855. case BuiltinProc_atomic_sub_acqrel:
  7856. case BuiltinProc_atomic_sub_relaxed:
  7857. case BuiltinProc_atomic_and:
  7858. case BuiltinProc_atomic_and_acq:
  7859. case BuiltinProc_atomic_and_rel:
  7860. case BuiltinProc_atomic_and_acqrel:
  7861. case BuiltinProc_atomic_and_relaxed:
  7862. case BuiltinProc_atomic_nand:
  7863. case BuiltinProc_atomic_nand_acq:
  7864. case BuiltinProc_atomic_nand_rel:
  7865. case BuiltinProc_atomic_nand_acqrel:
  7866. case BuiltinProc_atomic_nand_relaxed:
  7867. case BuiltinProc_atomic_or:
  7868. case BuiltinProc_atomic_or_acq:
  7869. case BuiltinProc_atomic_or_rel:
  7870. case BuiltinProc_atomic_or_acqrel:
  7871. case BuiltinProc_atomic_or_relaxed:
  7872. case BuiltinProc_atomic_xor:
  7873. case BuiltinProc_atomic_xor_acq:
  7874. case BuiltinProc_atomic_xor_rel:
  7875. case BuiltinProc_atomic_xor_acqrel:
  7876. case BuiltinProc_atomic_xor_relaxed:
  7877. case BuiltinProc_atomic_xchg:
  7878. case BuiltinProc_atomic_xchg_acq:
  7879. case BuiltinProc_atomic_xchg_rel:
  7880. case BuiltinProc_atomic_xchg_acqrel:
  7881. case BuiltinProc_atomic_xchg_relaxed: {
  7882. lbValue dst = lb_build_expr(p, ce->args[0]);
  7883. lbValue val = lb_build_expr(p, ce->args[1]);
  7884. val = lb_emit_conv(p, val, type_deref(dst.type));
  7885. LLVMAtomicRMWBinOp op = {};
  7886. LLVMAtomicOrdering ordering = {};
  7887. switch (id) {
  7888. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7889. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  7890. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  7891. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7892. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  7893. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7894. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  7895. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  7896. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7897. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  7898. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7899. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  7900. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  7901. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7902. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  7903. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7904. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  7905. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  7906. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7907. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  7908. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7909. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  7910. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  7911. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7912. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  7913. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7914. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  7915. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  7916. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7917. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  7918. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7919. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  7920. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  7921. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7922. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  7923. }
  7924. lbValue res = {};
  7925. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  7926. res.type = tv.type;
  7927. return res;
  7928. }
  7929. case BuiltinProc_atomic_cxchg:
  7930. case BuiltinProc_atomic_cxchg_acq:
  7931. case BuiltinProc_atomic_cxchg_rel:
  7932. case BuiltinProc_atomic_cxchg_acqrel:
  7933. case BuiltinProc_atomic_cxchg_relaxed:
  7934. case BuiltinProc_atomic_cxchg_failrelaxed:
  7935. case BuiltinProc_atomic_cxchg_failacq:
  7936. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  7937. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  7938. case BuiltinProc_atomic_cxchgweak:
  7939. case BuiltinProc_atomic_cxchgweak_acq:
  7940. case BuiltinProc_atomic_cxchgweak_rel:
  7941. case BuiltinProc_atomic_cxchgweak_acqrel:
  7942. case BuiltinProc_atomic_cxchgweak_relaxed:
  7943. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  7944. case BuiltinProc_atomic_cxchgweak_failacq:
  7945. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  7946. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  7947. Type *type = expr->tav.type;
  7948. lbValue address = lb_build_expr(p, ce->args[0]);
  7949. Type *elem = type_deref(address.type);
  7950. lbValue old_value = lb_build_expr(p, ce->args[1]);
  7951. lbValue new_value = lb_build_expr(p, ce->args[2]);
  7952. old_value = lb_emit_conv(p, old_value, elem);
  7953. new_value = lb_emit_conv(p, new_value, elem);
  7954. LLVMAtomicOrdering success_ordering = {};
  7955. LLVMAtomicOrdering failure_ordering = {};
  7956. LLVMBool weak = false;
  7957. switch (id) {
  7958. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7959. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7960. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7961. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7962. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7963. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7964. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  7965. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7966. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7967. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7968. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7969. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7970. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7971. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7972. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7973. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  7974. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7975. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7976. }
  7977. // TODO(bill): Figure out how to make it weak
  7978. LLVMBool single_threaded = weak;
  7979. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  7980. p->builder, address.value,
  7981. old_value.value, new_value.value,
  7982. success_ordering,
  7983. failure_ordering,
  7984. single_threaded
  7985. );
  7986. if (tv.type->kind == Type_Tuple) {
  7987. Type *fix_typed = alloc_type_tuple();
  7988. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  7989. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  7990. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7991. lbValue res = {};
  7992. res.value = value;
  7993. res.type = fix_typed;
  7994. return res;
  7995. } else {
  7996. lbValue res = {};
  7997. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  7998. res.type = tv.type;
  7999. return res;
  8000. }
  8001. }
  8002. case BuiltinProc_type_equal_proc:
  8003. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  8004. case BuiltinProc_type_hasher_proc:
  8005. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  8006. case BuiltinProc_fixed_point_mul:
  8007. case BuiltinProc_fixed_point_div:
  8008. case BuiltinProc_fixed_point_mul_sat:
  8009. case BuiltinProc_fixed_point_div_sat:
  8010. {
  8011. bool do_bswap = is_type_different_to_arch_endianness(tv.type);
  8012. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  8013. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  8014. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  8015. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), platform_type);
  8016. char const *name = nullptr;
  8017. if (is_type_unsigned(tv.type)) {
  8018. switch (id) {
  8019. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  8020. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  8021. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  8022. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  8023. }
  8024. } else {
  8025. switch (id) {
  8026. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  8027. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  8028. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  8029. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  8030. }
  8031. }
  8032. GB_ASSERT(name != nullptr);
  8033. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  8034. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8035. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8036. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8037. lbValue res = {};
  8038. LLVMValueRef args[3] = {};
  8039. args[0] = x.value;
  8040. args[1] = y.value;
  8041. args[2] = scale.value;
  8042. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8043. res.type = platform_type;
  8044. return lb_emit_conv(p, res, tv.type);
  8045. }
  8046. case BuiltinProc_expect:
  8047. {
  8048. Type *t = default_type(tv.type);
  8049. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  8050. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  8051. char const *name = "llvm.expect";
  8052. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  8053. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8054. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8055. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8056. lbValue res = {};
  8057. LLVMValueRef args[2] = {};
  8058. args[0] = x.value;
  8059. args[1] = y.value;
  8060. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8061. res.type = t;
  8062. return lb_emit_conv(p, res, t);
  8063. }
  8064. }
  8065. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  8066. return {};
  8067. }
  8068. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  8069. switch (param_value.kind) {
  8070. case ParameterValue_Constant:
  8071. if (is_type_constant_type(parameter_type)) {
  8072. return lb_const_value(p->module, parameter_type, param_value.value);
  8073. } else {
  8074. ExactValue ev = param_value.value;
  8075. lbValue arg = {};
  8076. Type *type = type_of_expr(param_value.original_ast_expr);
  8077. if (type != nullptr) {
  8078. arg = lb_const_value(p->module, type, ev);
  8079. } else {
  8080. arg = lb_const_value(p->module, parameter_type, param_value.value);
  8081. }
  8082. return lb_emit_conv(p, arg, parameter_type);
  8083. }
  8084. case ParameterValue_Nil:
  8085. return lb_const_nil(p->module, parameter_type);
  8086. case ParameterValue_Location:
  8087. {
  8088. String proc_name = {};
  8089. if (p->entity != nullptr) {
  8090. proc_name = p->entity->token.string;
  8091. }
  8092. return lb_emit_source_code_location(p, proc_name, pos);
  8093. }
  8094. case ParameterValue_Value:
  8095. return lb_build_expr(p, param_value.ast_value);
  8096. }
  8097. return lb_const_nil(p->module, parameter_type);
  8098. }
  8099. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  8100. lbModule *m = p->module;
  8101. TypeAndValue tv = type_and_value_of_expr(expr);
  8102. ast_node(ce, CallExpr, expr);
  8103. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  8104. AddressingMode proc_mode = proc_tv.mode;
  8105. if (proc_mode == Addressing_Type) {
  8106. GB_ASSERT(ce->args.count == 1);
  8107. lbValue x = lb_build_expr(p, ce->args[0]);
  8108. lbValue y = lb_emit_conv(p, x, tv.type);
  8109. return y;
  8110. }
  8111. Ast *pexpr = unparen_expr(ce->proc);
  8112. if (proc_mode == Addressing_Builtin) {
  8113. Entity *e = entity_of_node(pexpr);
  8114. BuiltinProcId id = BuiltinProc_Invalid;
  8115. if (e != nullptr) {
  8116. id = cast(BuiltinProcId)e->Builtin.id;
  8117. } else {
  8118. id = BuiltinProc_DIRECTIVE;
  8119. }
  8120. return lb_build_builtin_proc(p, expr, tv, id);
  8121. }
  8122. // NOTE(bill): Regular call
  8123. lbValue value = {};
  8124. Ast *proc_expr = unparen_expr(ce->proc);
  8125. if (proc_expr->tav.mode == Addressing_Constant) {
  8126. ExactValue v = proc_expr->tav.value;
  8127. switch (v.kind) {
  8128. case ExactValue_Integer:
  8129. {
  8130. u64 u = big_int_to_u64(&v.value_integer);
  8131. lbValue x = {};
  8132. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  8133. x.type = t_uintptr;
  8134. x = lb_emit_conv(p, x, t_rawptr);
  8135. value = lb_emit_conv(p, x, proc_expr->tav.type);
  8136. break;
  8137. }
  8138. case ExactValue_Pointer:
  8139. {
  8140. u64 u = cast(u64)v.value_pointer;
  8141. lbValue x = {};
  8142. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  8143. x.type = t_uintptr;
  8144. x = lb_emit_conv(p, x, t_rawptr);
  8145. value = lb_emit_conv(p, x, proc_expr->tav.type);
  8146. break;
  8147. }
  8148. }
  8149. }
  8150. Entity *proc_entity = entity_of_node(proc_expr);
  8151. if (proc_entity != nullptr) {
  8152. if (proc_entity->flags & EntityFlag_Disabled) {
  8153. return {};
  8154. }
  8155. }
  8156. if (value.value == nullptr) {
  8157. value = lb_build_expr(p, proc_expr);
  8158. }
  8159. GB_ASSERT(value.value != nullptr);
  8160. Type *proc_type_ = base_type(value.type);
  8161. GB_ASSERT(proc_type_->kind == Type_Proc);
  8162. TypeProc *pt = &proc_type_->Proc;
  8163. if (is_call_expr_field_value(ce)) {
  8164. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  8165. for_array(arg_index, ce->args) {
  8166. Ast *arg = ce->args[arg_index];
  8167. ast_node(fv, FieldValue, arg);
  8168. GB_ASSERT(fv->field->kind == Ast_Ident);
  8169. String name = fv->field->Ident.token.string;
  8170. isize index = lookup_procedure_parameter(pt, name);
  8171. GB_ASSERT(index >= 0);
  8172. TypeAndValue tav = type_and_value_of_expr(fv->value);
  8173. if (tav.mode == Addressing_Type) {
  8174. args[index] = lb_const_nil(m, tav.type);
  8175. } else {
  8176. args[index] = lb_build_expr(p, fv->value);
  8177. }
  8178. }
  8179. TypeTuple *params = &pt->params->Tuple;
  8180. for (isize i = 0; i < args.count; i++) {
  8181. Entity *e = params->variables[i];
  8182. if (e->kind == Entity_TypeName) {
  8183. args[i] = lb_const_nil(m, e->type);
  8184. } else if (e->kind == Entity_Constant) {
  8185. continue;
  8186. } else {
  8187. GB_ASSERT(e->kind == Entity_Variable);
  8188. if (args[i].value == nullptr) {
  8189. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8190. } else {
  8191. args[i] = lb_emit_conv(p, args[i], e->type);
  8192. }
  8193. }
  8194. }
  8195. for (isize i = 0; i < args.count; i++) {
  8196. Entity *e = params->variables[i];
  8197. if (args[i].type == nullptr) {
  8198. continue;
  8199. } else if (is_type_untyped_nil(args[i].type)) {
  8200. args[i] = lb_const_nil(m, e->type);
  8201. } else if (is_type_untyped_undef(args[i].type)) {
  8202. args[i] = lb_const_undef(m, e->type);
  8203. }
  8204. }
  8205. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  8206. }
  8207. isize arg_index = 0;
  8208. isize arg_count = 0;
  8209. for_array(i, ce->args) {
  8210. Ast *arg = ce->args[i];
  8211. TypeAndValue tav = type_and_value_of_expr(arg);
  8212. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  8213. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  8214. Type *at = tav.type;
  8215. if (at->kind == Type_Tuple) {
  8216. arg_count += at->Tuple.variables.count;
  8217. } else {
  8218. arg_count++;
  8219. }
  8220. }
  8221. isize param_count = 0;
  8222. if (pt->params) {
  8223. GB_ASSERT(pt->params->kind == Type_Tuple);
  8224. param_count = pt->params->Tuple.variables.count;
  8225. }
  8226. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  8227. isize variadic_index = pt->variadic_index;
  8228. bool variadic = pt->variadic && variadic_index >= 0;
  8229. bool vari_expand = ce->ellipsis.pos.line != 0;
  8230. bool is_c_vararg = pt->c_vararg;
  8231. String proc_name = {};
  8232. if (p->entity != nullptr) {
  8233. proc_name = p->entity->token.string;
  8234. }
  8235. TokenPos pos = ast_token(ce->proc).pos;
  8236. TypeTuple *param_tuple = nullptr;
  8237. if (pt->params) {
  8238. GB_ASSERT(pt->params->kind == Type_Tuple);
  8239. param_tuple = &pt->params->Tuple;
  8240. }
  8241. for_array(i, ce->args) {
  8242. Ast *arg = ce->args[i];
  8243. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  8244. if (arg_tv.mode == Addressing_Type) {
  8245. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  8246. } else {
  8247. lbValue a = lb_build_expr(p, arg);
  8248. Type *at = a.type;
  8249. if (at->kind == Type_Tuple) {
  8250. for_array(i, at->Tuple.variables) {
  8251. Entity *e = at->Tuple.variables[i];
  8252. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  8253. args[arg_index++] = v;
  8254. }
  8255. } else {
  8256. args[arg_index++] = a;
  8257. }
  8258. }
  8259. }
  8260. if (param_count > 0) {
  8261. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  8262. GB_ASSERT(param_count < 1000000);
  8263. if (arg_count < param_count) {
  8264. isize end = cast(isize)param_count;
  8265. if (variadic) {
  8266. end = variadic_index;
  8267. }
  8268. while (arg_index < end) {
  8269. Entity *e = param_tuple->variables[arg_index];
  8270. GB_ASSERT(e->kind == Entity_Variable);
  8271. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8272. }
  8273. }
  8274. if (is_c_vararg) {
  8275. GB_ASSERT(variadic);
  8276. GB_ASSERT(!vari_expand);
  8277. isize i = 0;
  8278. for (; i < variadic_index; i++) {
  8279. Entity *e = param_tuple->variables[i];
  8280. if (e->kind == Entity_Variable) {
  8281. args[i] = lb_emit_conv(p, args[i], e->type);
  8282. }
  8283. }
  8284. Type *variadic_type = param_tuple->variables[i]->type;
  8285. GB_ASSERT(is_type_slice(variadic_type));
  8286. variadic_type = base_type(variadic_type)->Slice.elem;
  8287. if (!is_type_any(variadic_type)) {
  8288. for (; i < arg_count; i++) {
  8289. args[i] = lb_emit_conv(p, args[i], variadic_type);
  8290. }
  8291. } else {
  8292. for (; i < arg_count; i++) {
  8293. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  8294. }
  8295. }
  8296. } else if (variadic) {
  8297. isize i = 0;
  8298. for (; i < variadic_index; i++) {
  8299. Entity *e = param_tuple->variables[i];
  8300. if (e->kind == Entity_Variable) {
  8301. args[i] = lb_emit_conv(p, args[i], e->type);
  8302. }
  8303. }
  8304. if (!vari_expand) {
  8305. Type *variadic_type = param_tuple->variables[i]->type;
  8306. GB_ASSERT(is_type_slice(variadic_type));
  8307. variadic_type = base_type(variadic_type)->Slice.elem;
  8308. for (; i < arg_count; i++) {
  8309. args[i] = lb_emit_conv(p, args[i], variadic_type);
  8310. }
  8311. }
  8312. } else {
  8313. for (isize i = 0; i < param_count; i++) {
  8314. Entity *e = param_tuple->variables[i];
  8315. if (e->kind == Entity_Variable) {
  8316. if (args[i].value == nullptr) {
  8317. continue;
  8318. }
  8319. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  8320. args[i] = lb_emit_conv(p, args[i], e->type);
  8321. }
  8322. }
  8323. }
  8324. if (variadic && !vari_expand && !is_c_vararg) {
  8325. // variadic call argument generation
  8326. Type *slice_type = param_tuple->variables[variadic_index]->type;
  8327. Type *elem_type = base_type(slice_type)->Slice.elem;
  8328. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  8329. isize slice_len = arg_count+1 - (variadic_index+1);
  8330. if (slice_len > 0) {
  8331. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  8332. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  8333. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  8334. lb_emit_store(p, addr, args[i]);
  8335. }
  8336. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  8337. lbValue len = lb_const_int(m, t_int, slice_len);
  8338. lb_fill_slice(p, slice, base_elem, len);
  8339. }
  8340. arg_count = param_count;
  8341. args[variadic_index] = lb_addr_load(p, slice);
  8342. }
  8343. }
  8344. if (variadic && variadic_index+1 < param_count) {
  8345. for (isize i = variadic_index+1; i < param_count; i++) {
  8346. Entity *e = param_tuple->variables[i];
  8347. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8348. }
  8349. }
  8350. isize final_count = param_count;
  8351. if (is_c_vararg) {
  8352. final_count = arg_count;
  8353. }
  8354. if (param_tuple != nullptr) {
  8355. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  8356. Entity *e = param_tuple->variables[i];
  8357. if (args[i].type == nullptr) {
  8358. continue;
  8359. } else if (is_type_untyped_nil(args[i].type)) {
  8360. args[i] = lb_const_nil(m, e->type);
  8361. } else if (is_type_untyped_undef(args[i].type)) {
  8362. args[i] = lb_const_undef(m, e->type);
  8363. }
  8364. }
  8365. }
  8366. auto call_args = array_slice(args, 0, final_count);
  8367. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  8368. }
  8369. bool lb_is_const(lbValue value) {
  8370. LLVMValueRef v = value.value;
  8371. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  8372. // TODO(bill): Is this correct behaviour?
  8373. return true;
  8374. }
  8375. if (LLVMIsConstant(v)) {
  8376. return true;
  8377. }
  8378. return false;
  8379. }
  8380. bool lb_is_const_or_global(lbValue value) {
  8381. if (lb_is_const(value)) {
  8382. return true;
  8383. }
  8384. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  8385. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  8386. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  8387. return false;
  8388. }
  8389. LLVMTypeRef elem = LLVMGetElementType(t);
  8390. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  8391. }
  8392. return false;
  8393. }
  8394. bool lb_is_const_nil(lbValue value) {
  8395. LLVMValueRef v = value.value;
  8396. if (LLVMIsConstant(v)) {
  8397. if (LLVMIsAConstantAggregateZero(v)) {
  8398. return true;
  8399. } else if (LLVMIsAConstantPointerNull(v)) {
  8400. return true;
  8401. }
  8402. }
  8403. return false;
  8404. }
  8405. String lb_get_const_string(lbModule *m, lbValue value) {
  8406. GB_ASSERT(lb_is_const(value));
  8407. GB_ASSERT(LLVMIsConstant(value.value));
  8408. Type *t = base_type(value.type);
  8409. GB_ASSERT(are_types_identical(t, t_string));
  8410. unsigned ptr_indices[1] = {0};
  8411. unsigned len_indices[1] = {1};
  8412. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  8413. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  8414. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  8415. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  8416. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  8417. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  8418. size_t length = 0;
  8419. char const *text = LLVMGetAsString(underlying_ptr, &length);
  8420. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  8421. return make_string(cast(u8 const *)text, real_length);
  8422. }
  8423. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  8424. GB_ASSERT(is_type_pointer(addr.type));
  8425. Type *type = type_deref(addr.type);
  8426. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  8427. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  8428. }
  8429. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  8430. AstPackage *pkg = m->info->runtime_package;
  8431. Entity *e = scope_lookup_current(pkg->scope, name);
  8432. lbValue *found = nullptr;
  8433. if (m != e->code_gen_module) {
  8434. gb_mutex_lock(&m->mutex);
  8435. }
  8436. GB_ASSERT(e->code_gen_module != nullptr);
  8437. found = map_get(&e->code_gen_module->values, hash_entity(e));
  8438. if (m != e->code_gen_module) {
  8439. gb_mutex_unlock(&m->mutex);
  8440. }
  8441. GB_ASSERT(found != nullptr);
  8442. return found->value;
  8443. }
  8444. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type) {
  8445. GB_ASSERT(type_size_of(value.type) == type_size_of(end_type));
  8446. if (type_size_of(value.type) < 2) {
  8447. return value;
  8448. }
  8449. Type *original_type = value.type;
  8450. if (is_type_float(original_type)) {
  8451. i64 sz = type_size_of(original_type);
  8452. Type *integer_type = nullptr;
  8453. switch (sz) {
  8454. case 2: integer_type = t_u16; break;
  8455. case 4: integer_type = t_u32; break;
  8456. case 8: integer_type = t_u64; break;
  8457. }
  8458. GB_ASSERT(integer_type != nullptr);
  8459. value = lb_emit_transmute(p, value, integer_type);
  8460. }
  8461. char const *name = "llvm.bswap";
  8462. LLVMTypeRef types[1] = {lb_type(p->module, value.type)};
  8463. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8464. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8465. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8466. LLVMValueRef args[1] = {};
  8467. args[0] = value.value;
  8468. lbValue res = {};
  8469. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8470. res.type = value.type;
  8471. if (is_type_float(original_type)) {
  8472. res = lb_emit_transmute(p, res, original_type);
  8473. }
  8474. res.type = end_type;
  8475. return res;
  8476. }
  8477. lbValue lb_emit_count_ones(lbProcedure *p, lbValue x, Type *type) {
  8478. x = lb_emit_conv(p, x, type);
  8479. char const *name = "llvm.ctpop";
  8480. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8481. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8482. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8483. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8484. LLVMValueRef args[1] = {};
  8485. args[0] = x.value;
  8486. lbValue res = {};
  8487. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8488. res.type = type;
  8489. return res;
  8490. }
  8491. lbValue lb_emit_count_zeros(lbProcedure *p, lbValue x, Type *type) {
  8492. i64 sz = 8*type_size_of(type);
  8493. lbValue size = lb_const_int(p->module, type, cast(u64)sz);
  8494. lbValue count = lb_emit_count_ones(p, x, type);
  8495. return lb_emit_arith(p, Token_Sub, size, count, type);
  8496. }
  8497. lbValue lb_emit_count_trailing_zeros(lbProcedure *p, lbValue x, Type *type) {
  8498. x = lb_emit_conv(p, x, type);
  8499. char const *name = "llvm.cttz";
  8500. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8501. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8502. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8503. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8504. LLVMValueRef args[2] = {};
  8505. args[0] = x.value;
  8506. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  8507. lbValue res = {};
  8508. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8509. res.type = type;
  8510. return res;
  8511. }
  8512. lbValue lb_emit_count_leading_zeros(lbProcedure *p, lbValue x, Type *type) {
  8513. x = lb_emit_conv(p, x, type);
  8514. char const *name = "llvm.ctlz";
  8515. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8516. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8517. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8518. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8519. LLVMValueRef args[2] = {};
  8520. args[0] = x.value;
  8521. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  8522. lbValue res = {};
  8523. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8524. res.type = type;
  8525. return res;
  8526. }
  8527. lbValue lb_emit_reverse_bits(lbProcedure *p, lbValue x, Type *type) {
  8528. x = lb_emit_conv(p, x, type);
  8529. char const *name = "llvm.bitreverse";
  8530. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8531. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8532. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8533. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8534. LLVMValueRef args[1] = {};
  8535. args[0] = x.value;
  8536. lbValue res = {};
  8537. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8538. res.type = type;
  8539. return res;
  8540. }
  8541. lbValue lb_emit_bit_set_card(lbProcedure *p, lbValue x) {
  8542. GB_ASSERT(is_type_bit_set(x.type));
  8543. Type *underlying = bit_set_to_int(x.type);
  8544. lbValue card = lb_emit_count_ones(p, x, underlying);
  8545. return lb_emit_conv(p, card, t_int);
  8546. }
  8547. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  8548. lbLoopData data = {};
  8549. lbValue max = lb_const_int(p->module, t_int, count);
  8550. data.idx_addr = lb_add_local_generated(p, index_type, true);
  8551. data.body = lb_create_block(p, "loop.body");
  8552. data.done = lb_create_block(p, "loop.done");
  8553. data.loop = lb_create_block(p, "loop.loop");
  8554. lb_emit_jump(p, data.loop);
  8555. lb_start_block(p, data.loop);
  8556. data.idx = lb_addr_load(p, data.idx_addr);
  8557. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  8558. lb_emit_if(p, cond, data.body, data.done);
  8559. lb_start_block(p, data.body);
  8560. return data;
  8561. }
  8562. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  8563. if (data.idx_addr.addr.value != nullptr) {
  8564. lb_emit_increment(p, data.idx_addr.addr);
  8565. lb_emit_jump(p, data.loop);
  8566. lb_start_block(p, data.done);
  8567. }
  8568. }
  8569. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  8570. lbValue res = {};
  8571. res.type = t_llvm_bool;
  8572. Type *t = x.type;
  8573. if (is_type_pointer(t)) {
  8574. if (op_kind == Token_CmpEq) {
  8575. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8576. } else if (op_kind == Token_NotEq) {
  8577. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8578. }
  8579. return res;
  8580. } else if (is_type_cstring(t)) {
  8581. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  8582. if (op_kind == Token_CmpEq) {
  8583. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  8584. } else if (op_kind == Token_NotEq) {
  8585. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  8586. }
  8587. return res;
  8588. } else if (is_type_proc(t)) {
  8589. if (op_kind == Token_CmpEq) {
  8590. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8591. } else if (op_kind == Token_NotEq) {
  8592. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8593. }
  8594. return res;
  8595. } else if (is_type_any(t)) {
  8596. // TODO(bill): is this correct behaviour for nil comparison for any?
  8597. lbValue data = lb_emit_struct_ev(p, x, 0);
  8598. lbValue ti = lb_emit_struct_ev(p, x, 1);
  8599. if (op_kind == Token_CmpEq) {
  8600. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  8601. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  8602. res.value = LLVMBuildOr(p->builder, a, b, "");
  8603. return res;
  8604. } else if (op_kind == Token_NotEq) {
  8605. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  8606. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  8607. res.value = LLVMBuildAnd(p->builder, a, b, "");
  8608. return res;
  8609. }
  8610. } else if (is_type_slice(t)) {
  8611. lbValue len = lb_emit_struct_ev(p, x, 1);
  8612. if (op_kind == Token_CmpEq) {
  8613. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8614. return res;
  8615. } else if (op_kind == Token_NotEq) {
  8616. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8617. return res;
  8618. }
  8619. } else if (is_type_dynamic_array(t)) {
  8620. lbValue cap = lb_emit_struct_ev(p, x, 2);
  8621. if (op_kind == Token_CmpEq) {
  8622. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8623. return res;
  8624. } else if (op_kind == Token_NotEq) {
  8625. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8626. return res;
  8627. }
  8628. } else if (is_type_map(t)) {
  8629. lbValue cap = lb_map_cap(p, x);
  8630. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  8631. } else if (is_type_union(t)) {
  8632. if (type_size_of(t) == 0) {
  8633. if (op_kind == Token_CmpEq) {
  8634. return lb_const_bool(p->module, t_llvm_bool, true);
  8635. } else if (op_kind == Token_NotEq) {
  8636. return lb_const_bool(p->module, t_llvm_bool, false);
  8637. }
  8638. } else if (is_type_union_maybe_pointer(t)) {
  8639. lbValue tag = lb_emit_transmute(p, x, t_rawptr);
  8640. return lb_emit_comp_against_nil(p, op_kind, tag);
  8641. } else {
  8642. lbValue tag = lb_emit_union_tag_value(p, x);
  8643. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  8644. }
  8645. } else if (is_type_typeid(t)) {
  8646. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  8647. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  8648. } else if (is_type_soa_struct(t)) {
  8649. Type *bt = base_type(t);
  8650. if (bt->Struct.soa_kind == StructSoa_Slice) {
  8651. lbValue len = lb_soa_struct_len(p, x);
  8652. if (op_kind == Token_CmpEq) {
  8653. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8654. return res;
  8655. } else if (op_kind == Token_NotEq) {
  8656. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8657. return res;
  8658. }
  8659. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  8660. lbValue cap = lb_soa_struct_cap(p, x);
  8661. if (op_kind == Token_CmpEq) {
  8662. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8663. return res;
  8664. } else if (op_kind == Token_NotEq) {
  8665. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8666. return res;
  8667. }
  8668. }
  8669. } else if (is_type_struct(t) && type_has_nil(t)) {
  8670. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8671. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  8672. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8673. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  8674. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  8675. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  8676. return res;
  8677. }
  8678. return {};
  8679. }
  8680. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  8681. Type *original_type = type;
  8682. type = base_type(type);
  8683. GB_ASSERT(is_type_comparable(type));
  8684. Type *pt = alloc_type_pointer(type);
  8685. LLVMTypeRef ptr_type = lb_type(m, pt);
  8686. auto key = hash_type(type);
  8687. lbProcedure **found = map_get(&m->equal_procs, key);
  8688. lbProcedure *compare_proc = nullptr;
  8689. if (found) {
  8690. compare_proc = *found;
  8691. GB_ASSERT(compare_proc != nullptr);
  8692. return {compare_proc->value, compare_proc->type};
  8693. }
  8694. static u32 proc_index = 0;
  8695. char buf[16] = {};
  8696. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  8697. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8698. String proc_name = make_string_c(str);
  8699. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  8700. map_set(&m->equal_procs, key, p);
  8701. lb_begin_procedure_body(p);
  8702. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8703. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8704. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  8705. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  8706. lbValue lhs = {x, pt};
  8707. lbValue rhs = {y, pt};
  8708. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  8709. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  8710. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  8711. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  8712. lb_start_block(p, block_same_ptr);
  8713. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8714. lb_start_block(p, block_diff_ptr);
  8715. if (type->kind == Type_Struct) {
  8716. type_set_offsets(type);
  8717. lbBlock *block_false = lb_create_block(p, "bfalse");
  8718. lbValue res = lb_const_bool(m, t_bool, true);
  8719. for_array(i, type->Struct.fields) {
  8720. lbBlock *next_block = lb_create_block(p, "btrue");
  8721. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  8722. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  8723. lbValue left = lb_emit_load(p, pleft);
  8724. lbValue right = lb_emit_load(p, pright);
  8725. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8726. lb_emit_if(p, ok, next_block, block_false);
  8727. lb_emit_jump(p, next_block);
  8728. lb_start_block(p, next_block);
  8729. }
  8730. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8731. lb_start_block(p, block_false);
  8732. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  8733. } else if (type->kind == Type_Union) {
  8734. if (is_type_union_maybe_pointer(type)) {
  8735. Type *v = type->Union.variants[0];
  8736. Type *pv = alloc_type_pointer(v);
  8737. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  8738. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  8739. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8740. ok = lb_emit_conv(p, ok, t_bool);
  8741. LLVMBuildRet(p->builder, ok.value);
  8742. } else {
  8743. lbBlock *block_false = lb_create_block(p, "bfalse");
  8744. lbBlock *block_switch = lb_create_block(p, "bswitch");
  8745. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  8746. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  8747. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  8748. lb_emit_if(p, tag_eq, block_switch, block_false);
  8749. lb_start_block(p, block_switch);
  8750. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, cast(unsigned)type->Union.variants.count);
  8751. for_array(i, type->Union.variants) {
  8752. lbBlock *case_block = lb_create_block(p, "bcase");
  8753. lb_start_block(p, case_block);
  8754. Type *v = type->Union.variants[i];
  8755. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  8756. Type *vp = alloc_type_pointer(v);
  8757. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  8758. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  8759. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8760. ok = lb_emit_conv(p, ok, t_bool);
  8761. LLVMBuildRet(p->builder, ok.value);
  8762. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  8763. }
  8764. lb_start_block(p, block_false);
  8765. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  8766. }
  8767. } else {
  8768. lbValue left = lb_emit_load(p, lhs);
  8769. lbValue right = lb_emit_load(p, rhs);
  8770. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8771. ok = lb_emit_conv(p, ok, t_bool);
  8772. LLVMBuildRet(p->builder, ok.value);
  8773. }
  8774. lb_end_procedure_body(p);
  8775. compare_proc = p;
  8776. return {compare_proc->value, compare_proc->type};
  8777. }
  8778. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  8779. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  8780. i64 sz = type_size_of(type);
  8781. if (1 <= sz && sz <= 16) {
  8782. char name[20] = {};
  8783. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  8784. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8785. args[0] = data;
  8786. args[1] = seed;
  8787. return lb_emit_runtime_call(p, name, args);
  8788. }
  8789. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8790. args[0] = data;
  8791. args[1] = seed;
  8792. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  8793. return lb_emit_runtime_call(p, "default_hasher_n", args);
  8794. }
  8795. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  8796. Type *original_type = type;
  8797. type = core_type(type);
  8798. GB_ASSERT(is_type_valid_for_keys(type));
  8799. Type *pt = alloc_type_pointer(type);
  8800. LLVMTypeRef ptr_type = lb_type(m, pt);
  8801. auto key = hash_type(type);
  8802. lbProcedure **found = map_get(&m->hasher_procs, key);
  8803. if (found) {
  8804. GB_ASSERT(*found != nullptr);
  8805. return {(*found)->value, (*found)->type};
  8806. }
  8807. static u32 proc_index = 0;
  8808. char buf[16] = {};
  8809. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  8810. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8811. String proc_name = make_string_c(str);
  8812. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  8813. map_set(&m->hasher_procs, key, p);
  8814. lb_begin_procedure_body(p);
  8815. defer (lb_end_procedure_body(p));
  8816. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8817. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8818. lbValue data = {x, t_rawptr};
  8819. lbValue seed = {y, t_uintptr};
  8820. LLVMAttributeRef nonnull_attr = lb_create_enum_attribute(m->ctx, "nonnull");
  8821. LLVMAddAttributeAtIndex(p->value, 1+0, nonnull_attr);
  8822. if (is_type_simple_compare(type)) {
  8823. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  8824. LLVMBuildRet(p->builder, res.value);
  8825. return {p->value, p->type};
  8826. }
  8827. if (type->kind == Type_Struct) {
  8828. type_set_offsets(type);
  8829. data = lb_emit_conv(p, data, t_u8_ptr);
  8830. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8831. for_array(i, type->Struct.fields) {
  8832. i64 offset = type->Struct.offsets[i];
  8833. Entity *field = type->Struct.fields[i];
  8834. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  8835. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  8836. args[0] = ptr;
  8837. args[1] = seed;
  8838. seed = lb_emit_call(p, field_hasher, args);
  8839. }
  8840. LLVMBuildRet(p->builder, seed.value);
  8841. } else if (type->kind == Type_Union) {
  8842. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8843. if (is_type_union_maybe_pointer(type)) {
  8844. Type *v = type->Union.variants[0];
  8845. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  8846. args[0] = data;
  8847. args[1] = seed;
  8848. lbValue res = lb_emit_call(p, variant_hasher, args);
  8849. LLVMBuildRet(p->builder, res.value);
  8850. }
  8851. lbBlock *end_block = lb_create_block(p, "bend");
  8852. data = lb_emit_conv(p, data, pt);
  8853. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  8854. lbValue tag = lb_emit_load(p, tag_ptr);
  8855. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  8856. for_array(i, type->Union.variants) {
  8857. lbBlock *case_block = lb_create_block(p, "bcase");
  8858. lb_start_block(p, case_block);
  8859. Type *v = type->Union.variants[i];
  8860. Type *vp = alloc_type_pointer(v);
  8861. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  8862. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  8863. args[0] = data;
  8864. args[1] = seed;
  8865. lbValue res = lb_emit_call(p, variant_hasher, args);
  8866. LLVMBuildRet(p->builder, res.value);
  8867. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  8868. }
  8869. lb_start_block(p, end_block);
  8870. LLVMBuildRet(p->builder, seed.value);
  8871. } else if (type->kind == Type_Array) {
  8872. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  8873. lb_addr_store(p, pres, seed);
  8874. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8875. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  8876. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  8877. data = lb_emit_conv(p, data, pt);
  8878. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8879. args[0] = ptr;
  8880. args[1] = lb_addr_load(p, pres);
  8881. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8882. lb_addr_store(p, pres, new_seed);
  8883. lb_loop_end(p, loop_data);
  8884. lbValue res = lb_addr_load(p, pres);
  8885. LLVMBuildRet(p->builder, res.value);
  8886. } else if (type->kind == Type_EnumeratedArray) {
  8887. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  8888. lb_addr_store(p, res, seed);
  8889. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8890. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  8891. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  8892. data = lb_emit_conv(p, data, pt);
  8893. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8894. args[0] = ptr;
  8895. args[1] = lb_addr_load(p, res);
  8896. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8897. lb_addr_store(p, res, new_seed);
  8898. lb_loop_end(p, loop_data);
  8899. lbValue vres = lb_addr_load(p, res);
  8900. LLVMBuildRet(p->builder, vres.value);
  8901. } else if (is_type_cstring(type)) {
  8902. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8903. args[0] = data;
  8904. args[1] = seed;
  8905. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  8906. LLVMBuildRet(p->builder, res.value);
  8907. } else if (is_type_string(type)) {
  8908. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8909. args[0] = data;
  8910. args[1] = seed;
  8911. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  8912. LLVMBuildRet(p->builder, res.value);
  8913. } else {
  8914. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  8915. }
  8916. return {p->value, p->type};
  8917. }
  8918. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  8919. Type *a = core_type(left.type);
  8920. Type *b = core_type(right.type);
  8921. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  8922. lbValue nil_check = {};
  8923. if (is_type_untyped_nil(left.type)) {
  8924. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  8925. } else if (is_type_untyped_nil(right.type)) {
  8926. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  8927. }
  8928. if (nil_check.value != nullptr) {
  8929. return nil_check;
  8930. }
  8931. if (are_types_identical(a, b)) {
  8932. // NOTE(bill): No need for a conversion
  8933. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  8934. left = lb_emit_conv(p, left, right.type);
  8935. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  8936. right = lb_emit_conv(p, right, left.type);
  8937. } else {
  8938. Type *lt = left.type;
  8939. Type *rt = right.type;
  8940. // if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  8941. // Type *blt = base_type(lt);
  8942. // Type *brt = base_type(rt);
  8943. // i64 bits = gb_max(blt->BitSet.bits, brt->BitSet.bits);
  8944. // i64 bytes = bits / 8;
  8945. // switch (bytes) {
  8946. // case 1:
  8947. // left = lb_emit_conv(p, left, t_u8);
  8948. // right = lb_emit_conv(p, right, t_u8);
  8949. // break;
  8950. // case 2:
  8951. // left = lb_emit_conv(p, left, t_u16);
  8952. // right = lb_emit_conv(p, right, t_u16);
  8953. // break;
  8954. // case 4:
  8955. // left = lb_emit_conv(p, left, t_u32);
  8956. // right = lb_emit_conv(p, right, t_u32);
  8957. // break;
  8958. // case 8:
  8959. // left = lb_emit_conv(p, left, t_u64);
  8960. // right = lb_emit_conv(p, right, t_u64);
  8961. // break;
  8962. // default: GB_PANIC("Unknown integer size"); break;
  8963. // }
  8964. // }
  8965. lt = left.type;
  8966. rt = right.type;
  8967. i64 ls = type_size_of(lt);
  8968. i64 rs = type_size_of(rt);
  8969. if (ls < rs) {
  8970. left = lb_emit_conv(p, left, rt);
  8971. } else if (ls > rs) {
  8972. right = lb_emit_conv(p, right, lt);
  8973. } else {
  8974. right = lb_emit_conv(p, right, lt);
  8975. }
  8976. }
  8977. if (is_type_array(a)) {
  8978. Type *tl = base_type(a);
  8979. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  8980. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  8981. TokenKind cmp_op = Token_And;
  8982. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  8983. if (op_kind == Token_NotEq) {
  8984. res = lb_const_bool(p->module, t_llvm_bool, false);
  8985. cmp_op = Token_Or;
  8986. } else if (op_kind == Token_CmpEq) {
  8987. res = lb_const_bool(p->module, t_llvm_bool, true);
  8988. cmp_op = Token_And;
  8989. }
  8990. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  8991. i32 count = cast(i32)tl->Array.count;
  8992. if (inline_array_arith) {
  8993. // inline
  8994. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8995. lb_addr_store(p, val, res);
  8996. for (i32 i = 0; i < count; i++) {
  8997. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  8998. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  8999. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  9000. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  9001. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  9002. }
  9003. return lb_addr_load(p, val);
  9004. } else {
  9005. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  9006. // TODO(bill): Test to see if this is actually faster!!!!
  9007. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9008. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  9009. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  9010. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  9011. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  9012. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  9013. return lb_emit_conv(p, res, t_bool);
  9014. } else {
  9015. lbAddr val = lb_add_local_generated(p, t_bool, false);
  9016. lb_addr_store(p, val, res);
  9017. auto loop_data = lb_loop_start(p, count, t_i32);
  9018. {
  9019. lbValue i = loop_data.idx;
  9020. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  9021. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  9022. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  9023. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  9024. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  9025. }
  9026. lb_loop_end(p, loop_data);
  9027. return lb_addr_load(p, val);
  9028. }
  9029. }
  9030. }
  9031. if ((is_type_struct(a) || is_type_union(a)) && is_type_comparable(a)) {
  9032. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  9033. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  9034. lbValue res = {};
  9035. if (is_type_simple_compare(a)) {
  9036. // TODO(bill): Test to see if this is actually faster!!!!
  9037. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9038. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  9039. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  9040. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  9041. res = lb_emit_runtime_call(p, "memory_equal", args);
  9042. } else {
  9043. lbValue value = lb_get_equal_proc_for_type(p->module, a);
  9044. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9045. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  9046. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  9047. res = lb_emit_call(p, value, args);
  9048. }
  9049. if (op_kind == Token_NotEq) {
  9050. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  9051. }
  9052. return res;
  9053. }
  9054. if (is_type_string(a)) {
  9055. if (is_type_cstring(a)) {
  9056. left = lb_emit_conv(p, left, t_string);
  9057. right = lb_emit_conv(p, right, t_string);
  9058. }
  9059. char const *runtime_procedure = nullptr;
  9060. switch (op_kind) {
  9061. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  9062. case Token_NotEq: runtime_procedure = "string_ne"; break;
  9063. case Token_Lt: runtime_procedure = "string_lt"; break;
  9064. case Token_Gt: runtime_procedure = "string_gt"; break;
  9065. case Token_LtEq: runtime_procedure = "string_le"; break;
  9066. case Token_GtEq: runtime_procedure = "string_gt"; break;
  9067. }
  9068. GB_ASSERT(runtime_procedure != nullptr);
  9069. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9070. args[0] = left;
  9071. args[1] = right;
  9072. return lb_emit_runtime_call(p, runtime_procedure, args);
  9073. }
  9074. if (is_type_complex(a)) {
  9075. char const *runtime_procedure = "";
  9076. i64 sz = 8*type_size_of(a);
  9077. switch (sz) {
  9078. case 64:
  9079. switch (op_kind) {
  9080. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  9081. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  9082. }
  9083. break;
  9084. case 128:
  9085. switch (op_kind) {
  9086. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  9087. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  9088. }
  9089. break;
  9090. }
  9091. GB_ASSERT(runtime_procedure != nullptr);
  9092. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9093. args[0] = left;
  9094. args[1] = right;
  9095. return lb_emit_runtime_call(p, runtime_procedure, args);
  9096. }
  9097. if (is_type_quaternion(a)) {
  9098. char const *runtime_procedure = "";
  9099. i64 sz = 8*type_size_of(a);
  9100. switch (sz) {
  9101. case 128:
  9102. switch (op_kind) {
  9103. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  9104. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  9105. }
  9106. break;
  9107. case 256:
  9108. switch (op_kind) {
  9109. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  9110. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  9111. }
  9112. break;
  9113. }
  9114. GB_ASSERT(runtime_procedure != nullptr);
  9115. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9116. args[0] = left;
  9117. args[1] = right;
  9118. return lb_emit_runtime_call(p, runtime_procedure, args);
  9119. }
  9120. if (is_type_bit_set(a)) {
  9121. switch (op_kind) {
  9122. case Token_Lt:
  9123. case Token_LtEq:
  9124. case Token_Gt:
  9125. case Token_GtEq:
  9126. {
  9127. Type *it = bit_set_to_int(a);
  9128. lbValue lhs = lb_emit_transmute(p, left, it);
  9129. lbValue rhs = lb_emit_transmute(p, right, it);
  9130. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  9131. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  9132. // (lhs & rhs) == lhs
  9133. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  9134. res.type = t_llvm_bool;
  9135. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  9136. // (lhs & rhs) == rhs
  9137. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  9138. res.type = t_llvm_bool;
  9139. }
  9140. // NOTE(bill): Strict subsets
  9141. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  9142. // res &~ (lhs == rhs)
  9143. lbValue eq = {};
  9144. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  9145. eq.type = t_llvm_bool;
  9146. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  9147. }
  9148. return res;
  9149. }
  9150. case Token_CmpEq:
  9151. case Token_NotEq:
  9152. {
  9153. LLVMIntPredicate pred = {};
  9154. switch (op_kind) {
  9155. case Token_CmpEq: pred = LLVMIntEQ; break;
  9156. case Token_NotEq: pred = LLVMIntNE; break;
  9157. }
  9158. lbValue res = {};
  9159. res.type = t_llvm_bool;
  9160. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  9161. return res;
  9162. }
  9163. }
  9164. }
  9165. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  9166. Type *t = left.type;
  9167. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  9168. Type *platform_type = integer_endian_type_to_platform_type(t);
  9169. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  9170. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  9171. left = x;
  9172. right = y;
  9173. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  9174. Type *platform_type = integer_endian_type_to_platform_type(t);
  9175. lbValue x = lb_emit_conv(p, left, platform_type);
  9176. lbValue y = lb_emit_conv(p, right, platform_type);
  9177. left = x;
  9178. right = y;
  9179. }
  9180. }
  9181. a = core_type(left.type);
  9182. b = core_type(right.type);
  9183. lbValue res = {};
  9184. res.type = t_llvm_bool;
  9185. if (is_type_integer(a) ||
  9186. is_type_boolean(a) ||
  9187. is_type_pointer(a) ||
  9188. is_type_proc(a) ||
  9189. is_type_enum(a)) {
  9190. LLVMIntPredicate pred = {};
  9191. if (is_type_unsigned(left.type)) {
  9192. switch (op_kind) {
  9193. case Token_Gt: pred = LLVMIntUGT; break;
  9194. case Token_GtEq: pred = LLVMIntUGE; break;
  9195. case Token_Lt: pred = LLVMIntULT; break;
  9196. case Token_LtEq: pred = LLVMIntULE; break;
  9197. }
  9198. } else {
  9199. switch (op_kind) {
  9200. case Token_Gt: pred = LLVMIntSGT; break;
  9201. case Token_GtEq: pred = LLVMIntSGE; break;
  9202. case Token_Lt: pred = LLVMIntSLT; break;
  9203. case Token_LtEq: pred = LLVMIntSLE; break;
  9204. }
  9205. }
  9206. switch (op_kind) {
  9207. case Token_CmpEq: pred = LLVMIntEQ; break;
  9208. case Token_NotEq: pred = LLVMIntNE; break;
  9209. }
  9210. LLVMValueRef lhs = left.value;
  9211. LLVMValueRef rhs = right.value;
  9212. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  9213. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  9214. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  9215. }
  9216. }
  9217. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  9218. } else if (is_type_float(a)) {
  9219. LLVMRealPredicate pred = {};
  9220. switch (op_kind) {
  9221. case Token_CmpEq: pred = LLVMRealOEQ; break;
  9222. case Token_Gt: pred = LLVMRealOGT; break;
  9223. case Token_GtEq: pred = LLVMRealOGE; break;
  9224. case Token_Lt: pred = LLVMRealOLT; break;
  9225. case Token_LtEq: pred = LLVMRealOLE; break;
  9226. case Token_NotEq: pred = LLVMRealONE; break;
  9227. }
  9228. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  9229. } else if (is_type_typeid(a)) {
  9230. LLVMIntPredicate pred = {};
  9231. switch (op_kind) {
  9232. case Token_Gt: pred = LLVMIntUGT; break;
  9233. case Token_GtEq: pred = LLVMIntUGE; break;
  9234. case Token_Lt: pred = LLVMIntULT; break;
  9235. case Token_LtEq: pred = LLVMIntULE; break;
  9236. case Token_CmpEq: pred = LLVMIntEQ; break;
  9237. case Token_NotEq: pred = LLVMIntNE; break;
  9238. }
  9239. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  9240. } else {
  9241. 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)));
  9242. }
  9243. return res;
  9244. }
  9245. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  9246. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  9247. if (found != nullptr) {
  9248. lbValue value = {};
  9249. value.value = (*found)->value;
  9250. value.type = (*found)->type;
  9251. return value;
  9252. }
  9253. ast_node(pl, ProcLit, expr);
  9254. // NOTE(bill): Generate a new name
  9255. // parent$count
  9256. isize name_len = prefix_name.len + 1 + 8 + 1;
  9257. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  9258. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  9259. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  9260. String name = make_string((u8 *)name_text, name_len-1);
  9261. Type *type = type_of_expr(expr);
  9262. Token token = {};
  9263. token.pos = ast_token(expr).pos;
  9264. token.kind = Token_Ident;
  9265. token.string = name;
  9266. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  9267. e->file = expr->file;
  9268. e->decl_info = pl->decl;
  9269. lbProcedure *p = lb_create_procedure(m, e);
  9270. lbValue value = {};
  9271. value.value = p->value;
  9272. value.type = p->type;
  9273. array_add(&m->procedures_to_generate, p);
  9274. if (parent != nullptr) {
  9275. array_add(&parent->children, p);
  9276. } else {
  9277. string_map_set(&m->members, name, value);
  9278. }
  9279. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  9280. return value;
  9281. }
  9282. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  9283. lbModule *m = p->module;
  9284. Type *src_type = value.type;
  9285. bool is_ptr = is_type_pointer(src_type);
  9286. bool is_tuple = true;
  9287. Type *tuple = type;
  9288. if (type->kind != Type_Tuple) {
  9289. is_tuple = false;
  9290. tuple = make_optional_ok_type(type);
  9291. }
  9292. lbAddr v = lb_add_local_generated(p, tuple, true);
  9293. if (is_ptr) {
  9294. value = lb_emit_load(p, value);
  9295. }
  9296. Type *src = base_type(type_deref(src_type));
  9297. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  9298. Type *dst = tuple->Tuple.variables[0]->type;
  9299. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  9300. lbValue tag = {};
  9301. lbValue dst_tag = {};
  9302. lbValue cond = {};
  9303. lbValue data = {};
  9304. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  9305. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9306. if (is_type_union_maybe_pointer(src)) {
  9307. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  9308. } else {
  9309. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  9310. dst_tag = lb_const_union_tag(m, src, dst);
  9311. }
  9312. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  9313. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  9314. if (data.value != nullptr) {
  9315. GB_ASSERT(is_type_union_maybe_pointer(src));
  9316. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  9317. } else {
  9318. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  9319. }
  9320. lb_emit_if(p, cond, ok_block, end_block);
  9321. lb_start_block(p, ok_block);
  9322. if (data.value == nullptr) {
  9323. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  9324. }
  9325. lb_emit_store(p, gep0, data);
  9326. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  9327. lb_emit_jump(p, end_block);
  9328. lb_start_block(p, end_block);
  9329. if (!is_tuple) {
  9330. if (do_conversion_check) {
  9331. // NOTE(bill): Panic on invalid conversion
  9332. Type *dst_type = tuple->Tuple.variables[0]->type;
  9333. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  9334. auto args = array_make<lbValue>(permanent_allocator(), 7);
  9335. args[0] = ok;
  9336. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  9337. args[2] = lb_const_int(m, t_i32, pos.line);
  9338. args[3] = lb_const_int(m, t_i32, pos.column);
  9339. args[4] = lb_typeid(m, src_type);
  9340. args[5] = lb_typeid(m, dst_type);
  9341. args[6] = lb_emit_conv(p, value_, t_rawptr);
  9342. lb_emit_runtime_call(p, "type_assertion_check2", args);
  9343. }
  9344. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  9345. }
  9346. return lb_addr_load(p, v);
  9347. }
  9348. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9349. lbModule *m = p->module;
  9350. Type *src_type = value.type;
  9351. if (is_type_pointer(src_type)) {
  9352. value = lb_emit_load(p, value);
  9353. }
  9354. bool is_tuple = true;
  9355. Type *tuple = type;
  9356. if (type->kind != Type_Tuple) {
  9357. is_tuple = false;
  9358. tuple = make_optional_ok_type(type);
  9359. }
  9360. Type *dst_type = tuple->Tuple.variables[0]->type;
  9361. lbAddr v = lb_add_local_generated(p, tuple, true);
  9362. lbValue dst_typeid = lb_typeid(m, dst_type);
  9363. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  9364. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  9365. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  9366. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  9367. lb_emit_if(p, cond, ok_block, end_block);
  9368. lb_start_block(p, ok_block);
  9369. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  9370. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9371. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  9372. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  9373. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  9374. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  9375. lb_emit_jump(p, end_block);
  9376. lb_start_block(p, end_block);
  9377. if (!is_tuple) {
  9378. // NOTE(bill): Panic on invalid conversion
  9379. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  9380. auto args = array_make<lbValue>(permanent_allocator(), 7);
  9381. args[0] = ok;
  9382. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  9383. args[2] = lb_const_int(m, t_i32, pos.line);
  9384. args[3] = lb_const_int(m, t_i32, pos.column);
  9385. args[4] = any_typeid;
  9386. args[5] = dst_typeid;
  9387. args[6] = lb_emit_struct_ev(p, value, 0);;
  9388. lb_emit_runtime_call(p, "type_assertion_check2", args);
  9389. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  9390. }
  9391. return v;
  9392. }
  9393. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9394. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  9395. }
  9396. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  9397. lbModule *m = p->module;
  9398. u16 prev_state_flags = p->state_flags;
  9399. defer (p->state_flags = prev_state_flags);
  9400. if (expr->state_flags != 0) {
  9401. u16 in = expr->state_flags;
  9402. u16 out = p->state_flags;
  9403. if (in & StateFlag_bounds_check) {
  9404. out |= StateFlag_bounds_check;
  9405. out &= ~StateFlag_no_bounds_check;
  9406. } else if (in & StateFlag_no_bounds_check) {
  9407. out |= StateFlag_no_bounds_check;
  9408. out &= ~StateFlag_bounds_check;
  9409. }
  9410. p->state_flags = out;
  9411. }
  9412. expr = unparen_expr(expr);
  9413. TokenPos expr_pos = ast_token(expr).pos;
  9414. TypeAndValue tv = type_and_value_of_expr(expr);
  9415. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %s\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), token_pos_to_string(expr_pos), LIT(p->name), type_to_string(p->type));
  9416. if (tv.value.kind != ExactValue_Invalid) {
  9417. // NOTE(bill): Short on constant values
  9418. return lb_const_value(p->module, tv.type, tv.value);
  9419. }
  9420. #if 0
  9421. LLVMMetadataRef prev_debug_location = nullptr;
  9422. if (p->debug_info != nullptr) {
  9423. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  9424. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  9425. }
  9426. defer (if (prev_debug_location != nullptr) {
  9427. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  9428. });
  9429. #endif
  9430. switch (expr->kind) {
  9431. case_ast_node(bl, BasicLit, expr);
  9432. TokenPos pos = bl->token.pos;
  9433. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  9434. case_end;
  9435. case_ast_node(bd, BasicDirective, expr);
  9436. TokenPos pos = bd->token.pos;
  9437. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name));
  9438. case_end;
  9439. case_ast_node(i, Implicit, expr);
  9440. return lb_addr_load(p, lb_build_addr(p, expr));
  9441. case_end;
  9442. case_ast_node(u, Undef, expr)
  9443. lbValue res = {};
  9444. if (is_type_untyped(tv.type)) {
  9445. res.value = nullptr;
  9446. res.type = t_untyped_undef;
  9447. } else {
  9448. res.value = LLVMGetUndef(lb_type(m, tv.type));
  9449. res.type = tv.type;
  9450. }
  9451. return res;
  9452. case_end;
  9453. case_ast_node(i, Ident, expr);
  9454. Entity *e = entity_from_expr(expr);
  9455. e = strip_entity_wrapping(e);
  9456. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  9457. if (e->kind == Entity_Builtin) {
  9458. Token token = ast_token(expr);
  9459. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  9460. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  9461. token_pos_to_string(token.pos));
  9462. return {};
  9463. } else if (e->kind == Entity_Nil) {
  9464. lbValue res = {};
  9465. res.value = nullptr;
  9466. res.type = e->type;
  9467. return res;
  9468. }
  9469. GB_ASSERT(e->kind != Entity_ProcGroup);
  9470. auto *found = map_get(&p->module->values, hash_entity(e));
  9471. if (found) {
  9472. auto v = *found;
  9473. // NOTE(bill): This is because pointers are already pointers in LLVM
  9474. if (is_type_proc(v.type)) {
  9475. return v;
  9476. }
  9477. return lb_emit_load(p, v);
  9478. } else if (e != nullptr && e->kind == Entity_Variable) {
  9479. return lb_addr_load(p, lb_build_addr(p, expr));
  9480. }
  9481. gb_printf_err("Error in: %s\n", token_pos_to_string(i->token.pos));
  9482. String pkg = {};
  9483. if (e->pkg) {
  9484. pkg = e->pkg->name;
  9485. }
  9486. 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);
  9487. return {};
  9488. case_end;
  9489. case_ast_node(de, DerefExpr, expr);
  9490. return lb_addr_load(p, lb_build_addr(p, expr));
  9491. case_end;
  9492. case_ast_node(se, SelectorExpr, expr);
  9493. TypeAndValue tav = type_and_value_of_expr(expr);
  9494. GB_ASSERT(tav.mode != Addressing_Invalid);
  9495. return lb_addr_load(p, lb_build_addr(p, expr));
  9496. case_end;
  9497. case_ast_node(ise, ImplicitSelectorExpr, expr);
  9498. TypeAndValue tav = type_and_value_of_expr(expr);
  9499. GB_ASSERT(tav.mode == Addressing_Constant);
  9500. return lb_const_value(p->module, tv.type, tv.value);
  9501. case_end;
  9502. case_ast_node(se, SelectorCallExpr, expr);
  9503. GB_ASSERT(se->modified_call);
  9504. TypeAndValue tav = type_and_value_of_expr(expr);
  9505. GB_ASSERT(tav.mode != Addressing_Invalid);
  9506. return lb_build_expr(p, se->call);
  9507. case_end;
  9508. case_ast_node(te, TernaryExpr, expr);
  9509. LLVMValueRef incoming_values[2] = {};
  9510. LLVMBasicBlockRef incoming_blocks[2] = {};
  9511. GB_ASSERT(te->y != nullptr);
  9512. lbBlock *then = lb_create_block(p, "if.then");
  9513. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  9514. lbBlock *else_ = lb_create_block(p, "if.else");
  9515. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  9516. lb_start_block(p, then);
  9517. Type *type = default_type(type_of_expr(expr));
  9518. lb_open_scope(p, nullptr);
  9519. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  9520. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9521. lb_emit_jump(p, done);
  9522. lb_start_block(p, else_);
  9523. lb_open_scope(p, nullptr);
  9524. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  9525. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9526. lb_emit_jump(p, done);
  9527. lb_start_block(p, done);
  9528. lbValue res = {};
  9529. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  9530. res.type = type;
  9531. GB_ASSERT(p->curr_block->preds.count >= 2);
  9532. incoming_blocks[0] = p->curr_block->preds[0]->block;
  9533. incoming_blocks[1] = p->curr_block->preds[1]->block;
  9534. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  9535. return res;
  9536. case_end;
  9537. case_ast_node(te, TernaryIfExpr, expr);
  9538. LLVMValueRef incoming_values[2] = {};
  9539. LLVMBasicBlockRef incoming_blocks[2] = {};
  9540. GB_ASSERT(te->y != nullptr);
  9541. lbBlock *then = lb_create_block(p, "if.then");
  9542. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  9543. lbBlock *else_ = lb_create_block(p, "if.else");
  9544. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  9545. lb_start_block(p, then);
  9546. Type *type = default_type(type_of_expr(expr));
  9547. lb_open_scope(p, nullptr);
  9548. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  9549. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9550. lb_emit_jump(p, done);
  9551. lb_start_block(p, else_);
  9552. lb_open_scope(p, nullptr);
  9553. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  9554. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9555. lb_emit_jump(p, done);
  9556. lb_start_block(p, done);
  9557. lbValue res = {};
  9558. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  9559. res.type = type;
  9560. GB_ASSERT(p->curr_block->preds.count >= 2);
  9561. incoming_blocks[0] = p->curr_block->preds[0]->block;
  9562. incoming_blocks[1] = p->curr_block->preds[1]->block;
  9563. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  9564. return res;
  9565. case_end;
  9566. case_ast_node(te, TernaryWhenExpr, expr);
  9567. TypeAndValue tav = type_and_value_of_expr(te->cond);
  9568. GB_ASSERT(tav.mode == Addressing_Constant);
  9569. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  9570. if (tav.value.value_bool) {
  9571. return lb_build_expr(p, te->x);
  9572. } else {
  9573. return lb_build_expr(p, te->y);
  9574. }
  9575. case_end;
  9576. case_ast_node(ta, TypeAssertion, expr);
  9577. TokenPos pos = ast_token(expr).pos;
  9578. Type *type = tv.type;
  9579. lbValue e = lb_build_expr(p, ta->expr);
  9580. Type *t = type_deref(e.type);
  9581. if (is_type_union(t)) {
  9582. return lb_emit_union_cast(p, e, type, pos);
  9583. } else if (is_type_any(t)) {
  9584. return lb_emit_any_cast(p, e, type, pos);
  9585. } else {
  9586. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9587. }
  9588. case_end;
  9589. case_ast_node(tc, TypeCast, expr);
  9590. lbValue e = lb_build_expr(p, tc->expr);
  9591. switch (tc->token.kind) {
  9592. case Token_cast:
  9593. return lb_emit_conv(p, e, tv.type);
  9594. case Token_transmute:
  9595. return lb_emit_transmute(p, e, tv.type);
  9596. }
  9597. GB_PANIC("Invalid AST TypeCast");
  9598. case_end;
  9599. case_ast_node(ac, AutoCast, expr);
  9600. lbValue value = lb_build_expr(p, ac->expr);
  9601. return lb_emit_conv(p, value, tv.type);
  9602. case_end;
  9603. case_ast_node(ue, UnaryExpr, expr);
  9604. switch (ue->op.kind) {
  9605. case Token_And: {
  9606. Ast *ue_expr = unparen_expr(ue->expr);
  9607. if (ue_expr->kind == Ast_CompoundLit) {
  9608. lbValue v = lb_build_expr(p, ue->expr);
  9609. Type *type = v.type;
  9610. lbAddr addr = {};
  9611. if (p->is_startup) {
  9612. addr = lb_add_global_generated(p->module, type, v);
  9613. } else {
  9614. addr = lb_add_local_generated(p, type, false);
  9615. }
  9616. lb_addr_store(p, addr, v);
  9617. return addr.addr;
  9618. } else if (ue_expr->kind == Ast_TypeAssertion) {
  9619. GB_ASSERT(is_type_pointer(tv.type));
  9620. ast_node(ta, TypeAssertion, ue_expr);
  9621. TokenPos pos = ast_token(expr).pos;
  9622. Type *type = type_of_expr(ue_expr);
  9623. GB_ASSERT(!is_type_tuple(type));
  9624. lbValue e = lb_build_expr(p, ta->expr);
  9625. Type *t = type_deref(e.type);
  9626. if (is_type_union(t)) {
  9627. lbValue v = e;
  9628. if (!is_type_pointer(v.type)) {
  9629. v = lb_address_from_load_or_generate_local(p, v);
  9630. }
  9631. Type *src_type = type_deref(v.type);
  9632. Type *dst_type = type;
  9633. lbValue src_tag = {};
  9634. lbValue dst_tag = {};
  9635. if (is_type_union_maybe_pointer(src_type)) {
  9636. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  9637. dst_tag = lb_const_bool(p->module, t_bool, true);
  9638. } else {
  9639. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  9640. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  9641. }
  9642. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  9643. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9644. args[0] = ok;
  9645. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9646. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9647. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9648. args[4] = lb_typeid(p->module, src_type);
  9649. args[5] = lb_typeid(p->module, dst_type);
  9650. lb_emit_runtime_call(p, "type_assertion_check", args);
  9651. lbValue data_ptr = v;
  9652. return lb_emit_conv(p, data_ptr, tv.type);
  9653. } else if (is_type_any(t)) {
  9654. lbValue v = e;
  9655. if (is_type_pointer(v.type)) {
  9656. v = lb_emit_load(p, v);
  9657. }
  9658. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  9659. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  9660. lbValue id = lb_typeid(p->module, type);
  9661. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  9662. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9663. args[0] = ok;
  9664. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9665. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9666. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9667. args[4] = any_id;
  9668. args[5] = id;
  9669. lb_emit_runtime_call(p, "type_assertion_check", args);
  9670. return lb_emit_conv(p, data_ptr, tv.type);
  9671. } else {
  9672. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  9673. }
  9674. }
  9675. return lb_build_addr_ptr(p, ue->expr);
  9676. }
  9677. default:
  9678. {
  9679. lbValue v = lb_build_expr(p, ue->expr);
  9680. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  9681. }
  9682. }
  9683. case_end;
  9684. case_ast_node(be, BinaryExpr, expr);
  9685. return lb_build_binary_expr(p, expr);
  9686. case_end;
  9687. case_ast_node(pl, ProcLit, expr);
  9688. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  9689. case_end;
  9690. case_ast_node(cl, CompoundLit, expr);
  9691. return lb_addr_load(p, lb_build_addr(p, expr));
  9692. case_end;
  9693. case_ast_node(ce, CallExpr, expr);
  9694. lbValue res = lb_build_call_expr(p, expr);
  9695. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  9696. GB_ASSERT(is_type_tuple(res.type));
  9697. GB_ASSERT(res.type->Tuple.variables.count == 2);
  9698. return lb_emit_struct_ev(p, res, 0);
  9699. }
  9700. return res;
  9701. case_end;
  9702. case_ast_node(se, SliceExpr, expr);
  9703. return lb_addr_load(p, lb_build_addr(p, expr));
  9704. case_end;
  9705. case_ast_node(ie, IndexExpr, expr);
  9706. return lb_addr_load(p, lb_build_addr(p, expr));
  9707. case_end;
  9708. case_ast_node(ia, InlineAsmExpr, expr);
  9709. Type *t = type_of_expr(expr);
  9710. GB_ASSERT(is_type_asm_proc(t));
  9711. String asm_string = {};
  9712. String constraints_string = {};
  9713. TypeAndValue tav;
  9714. tav = type_and_value_of_expr(ia->asm_string);
  9715. GB_ASSERT(is_type_string(tav.type));
  9716. GB_ASSERT(tav.value.kind == ExactValue_String);
  9717. asm_string = tav.value.value_string;
  9718. tav = type_and_value_of_expr(ia->constraints_string);
  9719. GB_ASSERT(is_type_string(tav.type));
  9720. GB_ASSERT(tav.value.kind == ExactValue_String);
  9721. constraints_string = tav.value.value_string;
  9722. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  9723. switch (ia->dialect) {
  9724. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  9725. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  9726. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  9727. default: GB_PANIC("Unhandled inline asm dialect"); break;
  9728. }
  9729. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  9730. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  9731. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  9732. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  9733. ia->has_side_effects, ia->is_align_stack, dialect
  9734. );
  9735. GB_ASSERT(the_asm != nullptr);
  9736. return {the_asm, t};
  9737. case_end;
  9738. }
  9739. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  9740. return {};
  9741. }
  9742. lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  9743. lbAddr *found = map_get(&p->module->soa_values, hash_entity(e));
  9744. GB_ASSERT(found != nullptr);
  9745. return *found;
  9746. }
  9747. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  9748. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  9749. String name = e->token.string;
  9750. Entity *parent = e->using_parent;
  9751. Selection sel = lookup_field(parent->type, name, false);
  9752. GB_ASSERT(sel.entity != nullptr);
  9753. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  9754. lbValue v = {};
  9755. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  9756. // NOTE(bill): using SOA value (probably from for-in statement)
  9757. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  9758. v = lb_addr_get_ptr(p, parent_addr);
  9759. } else if (pv != nullptr) {
  9760. v = *pv;
  9761. } else {
  9762. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  9763. v = lb_build_addr_ptr(p, e->using_expr);
  9764. }
  9765. GB_ASSERT(v.value != nullptr);
  9766. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  9767. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  9768. if (parent->scope) {
  9769. if ((parent->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) {
  9770. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  9771. }
  9772. } else {
  9773. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  9774. }
  9775. return ptr;
  9776. }
  9777. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  9778. GB_ASSERT(e != nullptr);
  9779. if (e->kind == Entity_Constant) {
  9780. Type *t = default_type(type_of_expr(expr));
  9781. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  9782. lbAddr g = lb_add_global_generated(p->module, t, v);
  9783. return g;
  9784. }
  9785. lbValue v = {};
  9786. lbValue *found = map_get(&p->module->values, hash_entity(e));
  9787. if (found) {
  9788. v = *found;
  9789. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  9790. // NOTE(bill): Calculate the using variable every time
  9791. v = lb_get_using_variable(p, e);
  9792. } else if (e->flags & EntityFlag_SoaPtrField) {
  9793. return lb_get_soa_variable_addr(p, e);
  9794. }
  9795. if (v.value == nullptr) {
  9796. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  9797. LIT(p->name),
  9798. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  9799. GB_PANIC("Unknown value");
  9800. }
  9801. return lb_addr(v);
  9802. }
  9803. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  9804. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  9805. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  9806. map_type = base_type(map_type);
  9807. GB_ASSERT(map_type->kind == Type_Map);
  9808. Type *key_type = map_type->Map.key;
  9809. Type *val_type = map_type->Map.value;
  9810. // NOTE(bill): Removes unnecessary allocation if split gep
  9811. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  9812. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  9813. lb_emit_store(p, gep0, m);
  9814. i64 entry_size = type_size_of (map_type->Map.entry_type);
  9815. i64 entry_align = type_align_of (map_type->Map.entry_type);
  9816. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  9817. i64 key_size = type_size_of (map_type->Map.key);
  9818. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  9819. i64 value_size = type_size_of (map_type->Map.value);
  9820. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  9821. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  9822. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  9823. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  9824. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  9825. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  9826. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  9827. return lb_addr_load(p, h);
  9828. }
  9829. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  9830. if (true) {
  9831. return {};
  9832. }
  9833. lbValue hashed_key = {};
  9834. if (lb_is_const(key)) {
  9835. u64 hash = 0xcbf29ce484222325;
  9836. if (is_type_cstring(key_type)) {
  9837. size_t length = 0;
  9838. char const *text = LLVMGetAsString(key.value, &length);
  9839. hash = fnv64a(text, cast(isize)length);
  9840. } else if (is_type_string(key_type)) {
  9841. unsigned data_indices[] = {0};
  9842. unsigned len_indices[] = {1};
  9843. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  9844. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  9845. isize length = LLVMConstIntGetSExtValue(len);
  9846. char const *text = nullptr;
  9847. if (false && length != 0) {
  9848. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  9849. return {};
  9850. }
  9851. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  9852. size_t ulength = 0;
  9853. text = LLVMGetAsString(data, &ulength);
  9854. gb_printf_err("%td %td %s\n", length, ulength, text);
  9855. length = gb_min(length, cast(isize)ulength);
  9856. }
  9857. hash = fnv64a(text, cast(isize)length);
  9858. } else {
  9859. return {};
  9860. }
  9861. // TODO(bill): other const hash types
  9862. if (build_context.word_size == 4) {
  9863. hash &= 0xffffffffull;
  9864. }
  9865. hashed_key = lb_const_int(m, t_uintptr, hash);
  9866. }
  9867. return hashed_key;
  9868. }
  9869. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  9870. Type *hash_type = t_u64;
  9871. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  9872. lbValue vp = lb_addr_get_ptr(p, v);
  9873. Type *t = base_type(key.type);
  9874. key = lb_emit_conv(p, key, key_type);
  9875. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  9876. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  9877. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  9878. if (hashed_key.value == nullptr) {
  9879. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  9880. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9881. args[0] = key_ptr;
  9882. args[1] = lb_const_int(p->module, t_uintptr, 0);
  9883. hashed_key = lb_emit_call(p, hasher, args);
  9884. }
  9885. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  9886. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  9887. return lb_addr_load(p, v);
  9888. }
  9889. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  9890. lbValue map_key, lbValue map_value, Ast *node) {
  9891. map_type = base_type(map_type);
  9892. GB_ASSERT(map_type->kind == Type_Map);
  9893. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  9894. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  9895. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  9896. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  9897. lb_addr_store(p, value_addr, v);
  9898. auto args = array_make<lbValue>(permanent_allocator(), 4);
  9899. args[0] = h;
  9900. args[1] = key;
  9901. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  9902. args[3] = lb_emit_source_code_location(p, node);
  9903. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  9904. }
  9905. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  9906. expr = unparen_expr(expr);
  9907. switch (expr->kind) {
  9908. case_ast_node(i, Implicit, expr);
  9909. lbAddr v = {};
  9910. switch (i->kind) {
  9911. case Token_context:
  9912. v = lb_find_or_generate_context_ptr(p);
  9913. break;
  9914. }
  9915. GB_ASSERT(v.addr.value != nullptr);
  9916. return v;
  9917. case_end;
  9918. case_ast_node(i, Ident, expr);
  9919. if (is_blank_ident(expr)) {
  9920. lbAddr val = {};
  9921. return val;
  9922. }
  9923. String name = i->token.string;
  9924. Entity *e = entity_of_node(expr);
  9925. return lb_build_addr_from_entity(p, e, expr);
  9926. case_end;
  9927. case_ast_node(se, SelectorExpr, expr);
  9928. Ast *sel = unparen_expr(se->selector);
  9929. if (sel->kind == Ast_Ident) {
  9930. String selector = sel->Ident.token.string;
  9931. TypeAndValue tav = type_and_value_of_expr(se->expr);
  9932. if (tav.mode == Addressing_Invalid) {
  9933. // NOTE(bill): Imports
  9934. Entity *imp = entity_of_node(se->expr);
  9935. if (imp != nullptr) {
  9936. GB_ASSERT(imp->kind == Entity_ImportName);
  9937. }
  9938. return lb_build_addr(p, unparen_expr(se->selector));
  9939. }
  9940. Type *type = base_type(tav.type);
  9941. if (tav.mode == Addressing_Type) { // Addressing_Type
  9942. Selection sel = lookup_field(type, selector, true);
  9943. Entity *e = sel.entity;
  9944. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  9945. GB_ASSERT(e->flags & EntityFlag_TypeField);
  9946. String name = e->token.string;
  9947. /*if (name == "names") {
  9948. lbValue ti_ptr = lb_type_info(m, type);
  9949. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  9950. lbValue names_ptr = nullptr;
  9951. if (is_type_enum(type)) {
  9952. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  9953. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  9954. } else if (type->kind == Type_Struct) {
  9955. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  9956. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  9957. }
  9958. return ir_addr(names_ptr);
  9959. } else */{
  9960. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  9961. }
  9962. GB_PANIC("Unreachable");
  9963. }
  9964. Selection sel = lookup_field(type, selector, false);
  9965. GB_ASSERT(sel.entity != nullptr);
  9966. {
  9967. lbAddr addr = lb_build_addr(p, se->expr);
  9968. if (addr.kind == lbAddr_Map) {
  9969. lbValue v = lb_addr_load(p, addr);
  9970. lbValue a = lb_address_from_load_or_generate_local(p, v);
  9971. a = lb_emit_deep_field_gep(p, a, sel);
  9972. return lb_addr(a);
  9973. } else if (addr.kind == lbAddr_Context) {
  9974. GB_ASSERT(sel.index.count > 0);
  9975. if (addr.ctx.sel.index.count >= 0) {
  9976. sel = selection_combine(addr.ctx.sel, sel);
  9977. }
  9978. addr.ctx.sel = sel;
  9979. addr.kind = lbAddr_Context;
  9980. return addr;
  9981. } else if (addr.kind == lbAddr_SoaVariable) {
  9982. lbValue index = addr.soa.index;
  9983. i32 first_index = sel.index[0];
  9984. Selection sub_sel = sel;
  9985. sub_sel.index.data += 1;
  9986. sub_sel.index.count -= 1;
  9987. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  9988. Type *t = base_type(type_deref(addr.addr.type));
  9989. GB_ASSERT(is_type_soa_struct(t));
  9990. // TODO(bill): Bounds check
  9991. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  9992. lbValue len = lb_soa_struct_len(p, addr.addr);
  9993. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  9994. }
  9995. lbValue item = {};
  9996. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9997. item = lb_emit_array_ep(p, arr, index);
  9998. } else {
  9999. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  10000. }
  10001. if (sub_sel.index.count > 0) {
  10002. item = lb_emit_deep_field_gep(p, item, sub_sel);
  10003. }
  10004. return lb_addr(item);
  10005. }
  10006. lbValue a = lb_addr_get_ptr(p, addr);
  10007. a = lb_emit_deep_field_gep(p, a, sel);
  10008. return lb_addr(a);
  10009. }
  10010. } else {
  10011. GB_PANIC("Unsupported selector expression");
  10012. }
  10013. case_end;
  10014. case_ast_node(se, SelectorCallExpr, expr);
  10015. GB_ASSERT(se->modified_call);
  10016. TypeAndValue tav = type_and_value_of_expr(expr);
  10017. GB_ASSERT(tav.mode != Addressing_Invalid);
  10018. return lb_build_addr(p, se->call);
  10019. case_end;
  10020. case_ast_node(ta, TypeAssertion, expr);
  10021. TokenPos pos = ast_token(expr).pos;
  10022. lbValue e = lb_build_expr(p, ta->expr);
  10023. Type *t = type_deref(e.type);
  10024. if (is_type_union(t)) {
  10025. Type *type = type_of_expr(expr);
  10026. lbAddr v = lb_add_local_generated(p, type, false);
  10027. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  10028. return v;
  10029. } else if (is_type_any(t)) {
  10030. Type *type = type_of_expr(expr);
  10031. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  10032. } else {
  10033. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  10034. }
  10035. case_end;
  10036. case_ast_node(ue, UnaryExpr, expr);
  10037. switch (ue->op.kind) {
  10038. case Token_And: {
  10039. return lb_build_addr(p, ue->expr);
  10040. }
  10041. default:
  10042. GB_PANIC("Invalid unary expression for lb_build_addr");
  10043. }
  10044. case_end;
  10045. case_ast_node(be, BinaryExpr, expr);
  10046. lbValue v = lb_build_expr(p, expr);
  10047. Type *t = v.type;
  10048. if (is_type_pointer(t)) {
  10049. return lb_addr(v);
  10050. }
  10051. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  10052. case_end;
  10053. case_ast_node(ie, IndexExpr, expr);
  10054. Type *t = base_type(type_of_expr(ie->expr));
  10055. bool deref = is_type_pointer(t);
  10056. t = base_type(type_deref(t));
  10057. if (is_type_soa_struct(t)) {
  10058. // SOA STRUCTURES!!!!
  10059. lbValue val = lb_build_addr_ptr(p, ie->expr);
  10060. if (deref) {
  10061. val = lb_emit_load(p, val);
  10062. }
  10063. lbValue index = lb_build_expr(p, ie->index);
  10064. return lb_addr_soa_variable(val, index, ie->index);
  10065. }
  10066. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  10067. // SOA Structures for slices/dynamic arrays
  10068. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  10069. lbValue field = lb_build_expr(p, ie->expr);
  10070. lbValue index = lb_build_expr(p, ie->index);
  10071. if (!build_context.no_bounds_check) {
  10072. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  10073. // GB_ASSERT(LLVMIsALoadInst(field.value));
  10074. // lbValue a = {};
  10075. // a.value = LLVMGetOperand(field.value, 0);
  10076. // a.type = alloc_type_pointer(field.type);
  10077. // irInstr *b = &a->Instr;
  10078. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  10079. // lbValue base_struct = b->StructElementPtr.address;
  10080. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  10081. // lbValue len = ir_soa_struct_len(p, base_struct);
  10082. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10083. }
  10084. lbValue val = lb_emit_ptr_offset(p, field, index);
  10085. return lb_addr(val);
  10086. }
  10087. if (!is_type_indexable(t)) {
  10088. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  10089. if (found != nullptr) {
  10090. if (found->kind == TypeAtomOp_index_get) {
  10091. return lb_build_addr(p, found->node);
  10092. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  10093. return lb_addr(lb_build_expr(p, found->node));
  10094. } else if (found->kind == TypeAtomOp_index_set) {
  10095. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  10096. if (deref) {
  10097. ptr = lb_emit_load(p, ptr);
  10098. }
  10099. lbAddr addr = {lbAddr_AtomOp_index_set};
  10100. addr.addr = ptr;
  10101. addr.index_set.index = lb_build_expr(p, ie->index);
  10102. addr.index_set.node = found->node;
  10103. return addr;
  10104. }
  10105. }
  10106. }
  10107. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  10108. if (is_type_map(t)) {
  10109. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  10110. if (deref) {
  10111. map_val = lb_emit_load(p, map_val);
  10112. }
  10113. lbValue key = lb_build_expr(p, ie->index);
  10114. key = lb_emit_conv(p, key, t->Map.key);
  10115. Type *result_type = type_of_expr(expr);
  10116. return lb_addr_map(map_val, key, t, result_type);
  10117. }
  10118. switch (t->kind) {
  10119. case Type_Array: {
  10120. lbValue array = {};
  10121. array = lb_build_addr_ptr(p, ie->expr);
  10122. if (deref) {
  10123. array = lb_emit_load(p, array);
  10124. }
  10125. lbValue index = lb_build_expr(p, ie->index);
  10126. index = lb_emit_conv(p, index, t_int);
  10127. lbValue elem = lb_emit_array_ep(p, array, index);
  10128. auto index_tv = type_and_value_of_expr(ie->index);
  10129. if (index_tv.mode != Addressing_Constant) {
  10130. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  10131. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10132. }
  10133. return lb_addr(elem);
  10134. }
  10135. case Type_EnumeratedArray: {
  10136. lbValue array = {};
  10137. array = lb_build_addr_ptr(p, ie->expr);
  10138. if (deref) {
  10139. array = lb_emit_load(p, array);
  10140. }
  10141. Type *index_type = t->EnumeratedArray.index;
  10142. auto index_tv = type_and_value_of_expr(ie->index);
  10143. lbValue index = {};
  10144. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  10145. if (index_tv.mode == Addressing_Constant) {
  10146. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  10147. index = lb_const_value(p->module, index_type, idx);
  10148. } else {
  10149. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10150. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  10151. }
  10152. } else {
  10153. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10154. }
  10155. lbValue elem = lb_emit_array_ep(p, array, index);
  10156. if (index_tv.mode != Addressing_Constant) {
  10157. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  10158. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10159. }
  10160. return lb_addr(elem);
  10161. }
  10162. case Type_Slice: {
  10163. lbValue slice = {};
  10164. slice = lb_build_expr(p, ie->expr);
  10165. if (deref) {
  10166. slice = lb_emit_load(p, slice);
  10167. }
  10168. lbValue elem = lb_slice_elem(p, slice);
  10169. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10170. lbValue len = lb_slice_len(p, slice);
  10171. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10172. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10173. return lb_addr(v);
  10174. }
  10175. case Type_RelativeSlice: {
  10176. lbAddr slice_addr = {};
  10177. if (deref) {
  10178. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  10179. } else {
  10180. slice_addr = lb_build_addr(p, ie->expr);
  10181. }
  10182. lbValue slice = lb_addr_load(p, slice_addr);
  10183. lbValue elem = lb_slice_elem(p, slice);
  10184. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10185. lbValue len = lb_slice_len(p, slice);
  10186. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10187. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10188. return lb_addr(v);
  10189. }
  10190. case Type_DynamicArray: {
  10191. lbValue dynamic_array = {};
  10192. dynamic_array = lb_build_expr(p, ie->expr);
  10193. if (deref) {
  10194. dynamic_array = lb_emit_load(p, dynamic_array);
  10195. }
  10196. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  10197. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  10198. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10199. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10200. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10201. return lb_addr(v);
  10202. }
  10203. case Type_Basic: { // Basic_string
  10204. lbValue str;
  10205. lbValue elem;
  10206. lbValue len;
  10207. lbValue index;
  10208. str = lb_build_expr(p, ie->expr);
  10209. if (deref) {
  10210. str = lb_emit_load(p, str);
  10211. }
  10212. elem = lb_string_elem(p, str);
  10213. len = lb_string_len(p, str);
  10214. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10215. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10216. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  10217. }
  10218. }
  10219. case_end;
  10220. case_ast_node(se, SliceExpr, expr);
  10221. lbValue low = lb_const_int(p->module, t_int, 0);
  10222. lbValue high = {};
  10223. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  10224. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  10225. bool no_indices = se->low == nullptr && se->high == nullptr;
  10226. {
  10227. Type *type = base_type(type_of_expr(se->expr));
  10228. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  10229. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  10230. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  10231. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  10232. if (found) {
  10233. lbValue base = lb_build_expr(p, found->node);
  10234. Type *slice_type = base.type;
  10235. lbValue len = lb_slice_len(p, base);
  10236. if (high.value == nullptr) high = len;
  10237. if (!no_indices) {
  10238. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10239. }
  10240. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  10241. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10242. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10243. lb_fill_slice(p, slice, elem, new_len);
  10244. return slice;
  10245. }
  10246. }
  10247. }
  10248. }
  10249. lbAddr addr = lb_build_addr(p, se->expr);
  10250. lbValue base = lb_addr_load(p, addr);
  10251. Type *type = base_type(base.type);
  10252. if (is_type_pointer(type)) {
  10253. type = base_type(type_deref(type));
  10254. addr = lb_addr(base);
  10255. base = lb_addr_load(p, addr);
  10256. }
  10257. switch (type->kind) {
  10258. case Type_Slice: {
  10259. Type *slice_type = type;
  10260. lbValue len = lb_slice_len(p, base);
  10261. if (high.value == nullptr) high = len;
  10262. if (!no_indices) {
  10263. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10264. }
  10265. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  10266. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10267. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10268. lb_fill_slice(p, slice, elem, new_len);
  10269. return slice;
  10270. }
  10271. case Type_RelativeSlice:
  10272. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  10273. break;
  10274. case Type_DynamicArray: {
  10275. Type *elem_type = type->DynamicArray.elem;
  10276. Type *slice_type = alloc_type_slice(elem_type);
  10277. lbValue len = lb_dynamic_array_len(p, base);
  10278. if (high.value == nullptr) high = len;
  10279. if (!no_indices) {
  10280. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10281. }
  10282. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  10283. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10284. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10285. lb_fill_slice(p, slice, elem, new_len);
  10286. return slice;
  10287. }
  10288. case Type_Array: {
  10289. Type *slice_type = alloc_type_slice(type->Array.elem);
  10290. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  10291. if (high.value == nullptr) high = len;
  10292. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  10293. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  10294. if (!low_const || !high_const) {
  10295. if (!no_indices) {
  10296. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10297. }
  10298. }
  10299. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  10300. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10301. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10302. lb_fill_slice(p, slice, elem, new_len);
  10303. return slice;
  10304. }
  10305. case Type_Basic: {
  10306. GB_ASSERT(type == t_string);
  10307. lbValue len = lb_string_len(p, base);
  10308. if (high.value == nullptr) high = len;
  10309. if (!no_indices) {
  10310. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10311. }
  10312. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  10313. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10314. lbAddr str = lb_add_local_generated(p, t_string, false);
  10315. lb_fill_string(p, str, elem, new_len);
  10316. return str;
  10317. }
  10318. case Type_Struct:
  10319. if (is_type_soa_struct(type)) {
  10320. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  10321. if (high.value == nullptr) high = len;
  10322. if (!no_indices) {
  10323. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10324. }
  10325. #if 1
  10326. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  10327. if (type->Struct.soa_kind == StructSoa_Fixed) {
  10328. i32 field_count = cast(i32)type->Struct.fields.count;
  10329. for (i32 i = 0; i < field_count; i++) {
  10330. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10331. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  10332. field_src = lb_emit_array_ep(p, field_src, low);
  10333. lb_emit_store(p, field_dst, field_src);
  10334. }
  10335. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10336. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10337. lb_emit_store(p, len_dst, new_len);
  10338. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  10339. if (no_indices) {
  10340. lb_addr_store(p, dst, base);
  10341. } else {
  10342. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  10343. for (i32 i = 0; i < field_count; i++) {
  10344. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10345. lbValue field_src = lb_emit_struct_ev(p, base, i);
  10346. field_src = lb_emit_ptr_offset(p, field_src, low);
  10347. lb_emit_store(p, field_dst, field_src);
  10348. }
  10349. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10350. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10351. lb_emit_store(p, len_dst, new_len);
  10352. }
  10353. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  10354. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  10355. for (i32 i = 0; i < field_count; i++) {
  10356. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10357. lbValue field_src = lb_emit_struct_ev(p, base, i);
  10358. field_src = lb_emit_ptr_offset(p, field_src, low);
  10359. lb_emit_store(p, field_dst, field_src);
  10360. }
  10361. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10362. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10363. lb_emit_store(p, len_dst, new_len);
  10364. }
  10365. return dst;
  10366. #endif
  10367. }
  10368. break;
  10369. }
  10370. GB_PANIC("Unknown slicable type");
  10371. case_end;
  10372. case_ast_node(de, DerefExpr, expr);
  10373. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  10374. lbAddr addr = lb_build_addr(p, de->expr);
  10375. addr.relative.deref = true;
  10376. return addr;
  10377. }
  10378. lbValue addr = lb_build_expr(p, de->expr);
  10379. return lb_addr(addr);
  10380. case_end;
  10381. case_ast_node(ce, CallExpr, expr);
  10382. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  10383. lbValue e = lb_build_expr(p, expr);
  10384. lbAddr v = lb_add_local_generated(p, e.type, false);
  10385. lb_addr_store(p, v, e);
  10386. return v;
  10387. case_end;
  10388. case_ast_node(cl, CompoundLit, expr);
  10389. Type *type = type_of_expr(expr);
  10390. Type *bt = base_type(type);
  10391. lbAddr v = lb_add_local_generated(p, type, true);
  10392. Type *et = nullptr;
  10393. switch (bt->kind) {
  10394. case Type_Array: et = bt->Array.elem; break;
  10395. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  10396. case Type_Slice: et = bt->Slice.elem; break;
  10397. case Type_BitSet: et = bt->BitSet.elem; break;
  10398. case Type_SimdVector: et = bt->SimdVector.elem; break;
  10399. }
  10400. String proc_name = {};
  10401. if (p->entity) {
  10402. proc_name = p->entity->token.string;
  10403. }
  10404. TokenPos pos = ast_token(expr).pos;
  10405. switch (bt->kind) {
  10406. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  10407. case Type_Struct: {
  10408. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  10409. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  10410. bool is_raw_union = is_type_raw_union(bt);
  10411. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  10412. TypeStruct *st = &bt->Struct;
  10413. if (cl->elems.count > 0) {
  10414. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10415. for_array(field_index, cl->elems) {
  10416. Ast *elem = cl->elems[field_index];
  10417. lbValue field_expr = {};
  10418. Entity *field = nullptr;
  10419. isize index = field_index;
  10420. if (elem->kind == Ast_FieldValue) {
  10421. ast_node(fv, FieldValue, elem);
  10422. String name = fv->field->Ident.token.string;
  10423. Selection sel = lookup_field(bt, name, false);
  10424. index = sel.index[0];
  10425. elem = fv->value;
  10426. TypeAndValue tav = type_and_value_of_expr(elem);
  10427. } else {
  10428. TypeAndValue tav = type_and_value_of_expr(elem);
  10429. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  10430. index = sel.index[0];
  10431. }
  10432. field = st->fields[index];
  10433. Type *ft = field->type;
  10434. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  10435. continue;
  10436. }
  10437. field_expr = lb_build_expr(p, elem);
  10438. Type *fet = field_expr.type;
  10439. GB_ASSERT(fet->kind != Type_Tuple);
  10440. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  10441. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  10442. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  10443. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10444. lb_emit_store_union_variant(p, gep, field_expr, fet);
  10445. } else {
  10446. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10447. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10448. lb_emit_store(p, gep, fv);
  10449. }
  10450. }
  10451. }
  10452. break;
  10453. }
  10454. case Type_Map: {
  10455. if (cl->elems.count == 0) {
  10456. break;
  10457. }
  10458. {
  10459. auto args = array_make<lbValue>(permanent_allocator(), 3);
  10460. args[0] = lb_gen_map_header(p, v.addr, type);
  10461. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  10462. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  10463. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  10464. }
  10465. for_array(field_index, cl->elems) {
  10466. Ast *elem = cl->elems[field_index];
  10467. ast_node(fv, FieldValue, elem);
  10468. lbValue key = lb_build_expr(p, fv->field);
  10469. lbValue value = lb_build_expr(p, fv->value);
  10470. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  10471. }
  10472. break;
  10473. }
  10474. case Type_Array: {
  10475. if (cl->elems.count > 0) {
  10476. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10477. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10478. // NOTE(bill): Separate value, gep, store into their own chunks
  10479. for_array(i, cl->elems) {
  10480. Ast *elem = cl->elems[i];
  10481. if (elem->kind == Ast_FieldValue) {
  10482. ast_node(fv, FieldValue, elem);
  10483. if (lb_is_elem_const(fv->value, et)) {
  10484. continue;
  10485. }
  10486. if (is_ast_range(fv->field)) {
  10487. ast_node(ie, BinaryExpr, fv->field);
  10488. TypeAndValue lo_tav = ie->left->tav;
  10489. TypeAndValue hi_tav = ie->right->tav;
  10490. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10491. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10492. TokenKind op = ie->op.kind;
  10493. i64 lo = exact_value_to_i64(lo_tav.value);
  10494. i64 hi = exact_value_to_i64(hi_tav.value);
  10495. if (op == Token_Ellipsis) {
  10496. hi += 1;
  10497. }
  10498. lbValue value = lb_build_expr(p, fv->value);
  10499. for (i64 k = lo; k < hi; k++) {
  10500. lbCompoundLitElemTempData data = {};
  10501. data.value = value;
  10502. data.elem_index = cast(i32)k;
  10503. array_add(&temp_data, data);
  10504. }
  10505. } else {
  10506. auto tav = fv->field->tav;
  10507. GB_ASSERT(tav.mode == Addressing_Constant);
  10508. i64 index = exact_value_to_i64(tav.value);
  10509. lbValue value = lb_build_expr(p, fv->value);
  10510. lbCompoundLitElemTempData data = {};
  10511. data.value = lb_emit_conv(p, value, et);
  10512. data.expr = fv->value;
  10513. data.elem_index = cast(i32)index;
  10514. array_add(&temp_data, data);
  10515. }
  10516. } else {
  10517. if (lb_is_elem_const(elem, et)) {
  10518. continue;
  10519. }
  10520. lbCompoundLitElemTempData data = {};
  10521. data.expr = elem;
  10522. data.elem_index = cast(i32)i;
  10523. array_add(&temp_data, data);
  10524. }
  10525. }
  10526. for_array(i, temp_data) {
  10527. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  10528. }
  10529. for_array(i, temp_data) {
  10530. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  10531. auto return_ptr_hint_value = p->return_ptr_hint_value;
  10532. auto return_ptr_hint_used = p->return_ptr_hint_used;
  10533. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  10534. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  10535. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  10536. lbValue field_expr = temp_data[i].value;
  10537. Ast *expr = temp_data[i].expr;
  10538. p->return_ptr_hint_value = temp_data[i].gep;
  10539. p->return_ptr_hint_ast = unparen_expr(expr);
  10540. if (field_expr.value == nullptr) {
  10541. field_expr = lb_build_expr(p, expr);
  10542. }
  10543. Type *t = field_expr.type;
  10544. GB_ASSERT(t->kind != Type_Tuple);
  10545. lbValue ev = lb_emit_conv(p, field_expr, et);
  10546. if (!p->return_ptr_hint_used) {
  10547. temp_data[i].value = ev;
  10548. }
  10549. }
  10550. for_array(i, temp_data) {
  10551. if (temp_data[i].value.value != nullptr) {
  10552. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10553. }
  10554. }
  10555. }
  10556. break;
  10557. }
  10558. case Type_EnumeratedArray: {
  10559. if (cl->elems.count > 0) {
  10560. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10561. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10562. // NOTE(bill): Separate value, gep, store into their own chunks
  10563. for_array(i, cl->elems) {
  10564. Ast *elem = cl->elems[i];
  10565. if (elem->kind == Ast_FieldValue) {
  10566. ast_node(fv, FieldValue, elem);
  10567. if (lb_is_elem_const(fv->value, et)) {
  10568. continue;
  10569. }
  10570. if (is_ast_range(fv->field)) {
  10571. ast_node(ie, BinaryExpr, fv->field);
  10572. TypeAndValue lo_tav = ie->left->tav;
  10573. TypeAndValue hi_tav = ie->right->tav;
  10574. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10575. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10576. TokenKind op = ie->op.kind;
  10577. i64 lo = exact_value_to_i64(lo_tav.value);
  10578. i64 hi = exact_value_to_i64(hi_tav.value);
  10579. if (op == Token_Ellipsis) {
  10580. hi += 1;
  10581. }
  10582. lbValue value = lb_build_expr(p, fv->value);
  10583. for (i64 k = lo; k < hi; k++) {
  10584. lbCompoundLitElemTempData data = {};
  10585. data.value = value;
  10586. data.elem_index = cast(i32)k;
  10587. array_add(&temp_data, data);
  10588. }
  10589. } else {
  10590. auto tav = fv->field->tav;
  10591. GB_ASSERT(tav.mode == Addressing_Constant);
  10592. i64 index = exact_value_to_i64(tav.value);
  10593. lbValue value = lb_build_expr(p, fv->value);
  10594. lbCompoundLitElemTempData data = {};
  10595. data.value = lb_emit_conv(p, value, et);
  10596. data.expr = fv->value;
  10597. data.elem_index = cast(i32)index;
  10598. array_add(&temp_data, data);
  10599. }
  10600. } else {
  10601. if (lb_is_elem_const(elem, et)) {
  10602. continue;
  10603. }
  10604. lbCompoundLitElemTempData data = {};
  10605. data.expr = elem;
  10606. data.elem_index = cast(i32)i;
  10607. array_add(&temp_data, data);
  10608. }
  10609. }
  10610. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  10611. for_array(i, temp_data) {
  10612. i32 index = temp_data[i].elem_index - index_offset;
  10613. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  10614. }
  10615. for_array(i, temp_data) {
  10616. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  10617. auto return_ptr_hint_value = p->return_ptr_hint_value;
  10618. auto return_ptr_hint_used = p->return_ptr_hint_used;
  10619. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  10620. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  10621. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  10622. lbValue field_expr = temp_data[i].value;
  10623. Ast *expr = temp_data[i].expr;
  10624. p->return_ptr_hint_value = temp_data[i].gep;
  10625. p->return_ptr_hint_ast = unparen_expr(expr);
  10626. if (field_expr.value == nullptr) {
  10627. field_expr = lb_build_expr(p, expr);
  10628. }
  10629. Type *t = field_expr.type;
  10630. GB_ASSERT(t->kind != Type_Tuple);
  10631. lbValue ev = lb_emit_conv(p, field_expr, et);
  10632. if (!p->return_ptr_hint_used) {
  10633. temp_data[i].value = ev;
  10634. }
  10635. }
  10636. for_array(i, temp_data) {
  10637. if (temp_data[i].value.value != nullptr) {
  10638. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10639. }
  10640. }
  10641. }
  10642. break;
  10643. }
  10644. case Type_Slice: {
  10645. if (cl->elems.count > 0) {
  10646. Type *elem_type = bt->Slice.elem;
  10647. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  10648. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  10649. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  10650. lbValue data = lb_slice_elem(p, slice);
  10651. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10652. for_array(i, cl->elems) {
  10653. Ast *elem = cl->elems[i];
  10654. if (elem->kind == Ast_FieldValue) {
  10655. ast_node(fv, FieldValue, elem);
  10656. if (lb_is_elem_const(fv->value, et)) {
  10657. continue;
  10658. }
  10659. if (is_ast_range(fv->field)) {
  10660. ast_node(ie, BinaryExpr, fv->field);
  10661. TypeAndValue lo_tav = ie->left->tav;
  10662. TypeAndValue hi_tav = ie->right->tav;
  10663. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10664. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10665. TokenKind op = ie->op.kind;
  10666. i64 lo = exact_value_to_i64(lo_tav.value);
  10667. i64 hi = exact_value_to_i64(hi_tav.value);
  10668. if (op == Token_Ellipsis) {
  10669. hi += 1;
  10670. }
  10671. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10672. for (i64 k = lo; k < hi; k++) {
  10673. lbCompoundLitElemTempData data = {};
  10674. data.value = value;
  10675. data.elem_index = cast(i32)k;
  10676. array_add(&temp_data, data);
  10677. }
  10678. } else {
  10679. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10680. i64 index = exact_value_to_i64(fv->field->tav.value);
  10681. lbValue field_expr = lb_build_expr(p, fv->value);
  10682. GB_ASSERT(!is_type_tuple(field_expr.type));
  10683. lbValue ev = lb_emit_conv(p, field_expr, et);
  10684. lbCompoundLitElemTempData data = {};
  10685. data.value = ev;
  10686. data.elem_index = cast(i32)index;
  10687. array_add(&temp_data, data);
  10688. }
  10689. } else {
  10690. if (lb_is_elem_const(elem, et)) {
  10691. continue;
  10692. }
  10693. lbValue field_expr = lb_build_expr(p, elem);
  10694. GB_ASSERT(!is_type_tuple(field_expr.type));
  10695. lbValue ev = lb_emit_conv(p, field_expr, et);
  10696. lbCompoundLitElemTempData data = {};
  10697. data.value = ev;
  10698. data.elem_index = cast(i32)i;
  10699. array_add(&temp_data, data);
  10700. }
  10701. }
  10702. for_array(i, temp_data) {
  10703. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  10704. }
  10705. for_array(i, temp_data) {
  10706. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10707. }
  10708. {
  10709. lbValue count = {};
  10710. count.type = t_int;
  10711. if (lb_is_const(slice)) {
  10712. unsigned indices[1] = {1};
  10713. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  10714. } else {
  10715. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  10716. }
  10717. lb_fill_slice(p, v, data, count);
  10718. }
  10719. }
  10720. break;
  10721. }
  10722. case Type_DynamicArray: {
  10723. if (cl->elems.count == 0) {
  10724. break;
  10725. }
  10726. Type *et = bt->DynamicArray.elem;
  10727. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  10728. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  10729. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  10730. {
  10731. auto args = array_make<lbValue>(permanent_allocator(), 5);
  10732. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  10733. args[1] = size;
  10734. args[2] = align;
  10735. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  10736. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  10737. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  10738. }
  10739. lbValue items = lb_generate_local_array(p, et, item_count);
  10740. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  10741. for_array(i, cl->elems) {
  10742. Ast *elem = cl->elems[i];
  10743. if (elem->kind == Ast_FieldValue) {
  10744. ast_node(fv, FieldValue, elem);
  10745. if (is_ast_range(fv->field)) {
  10746. ast_node(ie, BinaryExpr, fv->field);
  10747. TypeAndValue lo_tav = ie->left->tav;
  10748. TypeAndValue hi_tav = ie->right->tav;
  10749. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10750. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10751. TokenKind op = ie->op.kind;
  10752. i64 lo = exact_value_to_i64(lo_tav.value);
  10753. i64 hi = exact_value_to_i64(hi_tav.value);
  10754. if (op == Token_Ellipsis) {
  10755. hi += 1;
  10756. }
  10757. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10758. for (i64 k = lo; k < hi; k++) {
  10759. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  10760. lb_emit_store(p, ep, value);
  10761. }
  10762. } else {
  10763. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10764. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  10765. lbValue ev = lb_build_expr(p, fv->value);
  10766. lbValue value = lb_emit_conv(p, ev, et);
  10767. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  10768. lb_emit_store(p, ep, value);
  10769. }
  10770. } else {
  10771. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  10772. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  10773. lb_emit_store(p, ep, value);
  10774. }
  10775. }
  10776. {
  10777. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10778. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  10779. args[1] = size;
  10780. args[2] = align;
  10781. args[3] = lb_emit_conv(p, items, t_rawptr);
  10782. args[4] = lb_const_int(p->module, t_int, item_count);
  10783. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  10784. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  10785. }
  10786. break;
  10787. }
  10788. case Type_Basic: {
  10789. GB_ASSERT(is_type_any(bt));
  10790. if (cl->elems.count > 0) {
  10791. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10792. String field_names[2] = {
  10793. str_lit("data"),
  10794. str_lit("id"),
  10795. };
  10796. Type *field_types[2] = {
  10797. t_rawptr,
  10798. t_typeid,
  10799. };
  10800. for_array(field_index, cl->elems) {
  10801. Ast *elem = cl->elems[field_index];
  10802. lbValue field_expr = {};
  10803. isize index = field_index;
  10804. if (elem->kind == Ast_FieldValue) {
  10805. ast_node(fv, FieldValue, elem);
  10806. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  10807. index = sel.index[0];
  10808. elem = fv->value;
  10809. } else {
  10810. TypeAndValue tav = type_and_value_of_expr(elem);
  10811. Selection sel = lookup_field(bt, field_names[field_index], false);
  10812. index = sel.index[0];
  10813. }
  10814. field_expr = lb_build_expr(p, elem);
  10815. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  10816. Type *ft = field_types[index];
  10817. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10818. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10819. lb_emit_store(p, gep, fv);
  10820. }
  10821. }
  10822. break;
  10823. }
  10824. case Type_BitSet: {
  10825. i64 sz = type_size_of(type);
  10826. if (cl->elems.count > 0 && sz > 0) {
  10827. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10828. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  10829. for_array(i, cl->elems) {
  10830. Ast *elem = cl->elems[i];
  10831. GB_ASSERT(elem->kind != Ast_FieldValue);
  10832. if (lb_is_elem_const(elem, et)) {
  10833. continue;
  10834. }
  10835. lbValue expr = lb_build_expr(p, elem);
  10836. GB_ASSERT(expr.type->kind != Type_Tuple);
  10837. Type *it = bit_set_to_int(bt);
  10838. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  10839. lbValue e = lb_emit_conv(p, expr, it);
  10840. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  10841. e = lb_emit_arith(p, Token_Shl, one, e, it);
  10842. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  10843. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  10844. new_value = lb_emit_transmute(p, new_value, type);
  10845. lb_addr_store(p, v, new_value);
  10846. }
  10847. }
  10848. break;
  10849. }
  10850. }
  10851. return v;
  10852. case_end;
  10853. case_ast_node(tc, TypeCast, expr);
  10854. Type *type = type_of_expr(expr);
  10855. lbValue x = lb_build_expr(p, tc->expr);
  10856. lbValue e = {};
  10857. switch (tc->token.kind) {
  10858. case Token_cast:
  10859. e = lb_emit_conv(p, x, type);
  10860. break;
  10861. case Token_transmute:
  10862. e = lb_emit_transmute(p, x, type);
  10863. break;
  10864. default:
  10865. GB_PANIC("Invalid AST TypeCast");
  10866. }
  10867. lbAddr v = lb_add_local_generated(p, type, false);
  10868. lb_addr_store(p, v, e);
  10869. return v;
  10870. case_end;
  10871. case_ast_node(ac, AutoCast, expr);
  10872. return lb_build_addr(p, ac->expr);
  10873. case_end;
  10874. }
  10875. TokenPos token_pos = ast_token(expr).pos;
  10876. GB_PANIC("Unexpected address expression\n"
  10877. "\tAst: %.*s @ "
  10878. "%s\n",
  10879. LIT(ast_strings[expr->kind]),
  10880. token_pos_to_string(token_pos));
  10881. return {};
  10882. }
  10883. void lb_init_module(lbModule *m, Checker *c) {
  10884. m->info = &c->info;
  10885. gbString module_name = nullptr;
  10886. if (m->pkg) {
  10887. module_name = gb_string_make(heap_allocator(), "odin_package-");
  10888. module_name = gb_string_append_length(module_name, m->pkg->name.text, m->pkg->name.len);
  10889. }
  10890. m->ctx = LLVMContextCreate();
  10891. m->mod = LLVMModuleCreateWithNameInContext(module_name ? module_name : "odin_package", m->ctx);
  10892. // m->debug_builder = nullptr;
  10893. if (build_context.ODIN_DEBUG) {
  10894. enum {DEBUG_METADATA_VERSION = 3};
  10895. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  10896. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  10897. switch (build_context.metrics.os) {
  10898. case TargetOs_windows:
  10899. LLVMAddModuleFlag(m->mod,
  10900. LLVMModuleFlagBehaviorWarning,
  10901. "CodeView", 8,
  10902. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  10903. break;
  10904. case TargetOs_darwin:
  10905. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  10906. LLVMAddModuleFlag(m->mod,
  10907. LLVMModuleFlagBehaviorWarning,
  10908. "Dwarf Version", 13,
  10909. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  10910. break;
  10911. }
  10912. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  10913. }
  10914. gb_mutex_init(&m->mutex);
  10915. gbAllocator a = heap_allocator();
  10916. map_init(&m->types, a);
  10917. map_init(&m->llvm_types, a);
  10918. map_init(&m->values, a);
  10919. map_init(&m->soa_values, a);
  10920. string_map_init(&m->members, a);
  10921. map_init(&m->procedure_values, a);
  10922. string_map_init(&m->procedures, a);
  10923. string_map_init(&m->const_strings, a);
  10924. map_init(&m->anonymous_proc_lits, a);
  10925. map_init(&m->function_type_map, a);
  10926. map_init(&m->equal_procs, a);
  10927. map_init(&m->hasher_procs, a);
  10928. array_init(&m->procedures_to_generate, a, 0, 1024);
  10929. array_init(&m->foreign_library_paths, a, 0, 1024);
  10930. map_init(&m->debug_values, a);
  10931. array_init(&m->debug_incomplete_types, a, 0, 1024);
  10932. }
  10933. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  10934. if (global_error_collector.count != 0) {
  10935. return false;
  10936. }
  10937. isize tc = c->parser->total_token_count;
  10938. if (tc < 2) {
  10939. return false;
  10940. }
  10941. String init_fullpath = c->parser->init_fullpath;
  10942. if (build_context.out_filepath.len == 0) {
  10943. gen->output_name = remove_directory_from_path(init_fullpath);
  10944. gen->output_name = remove_extension_from_path(gen->output_name);
  10945. gen->output_name = string_trim_whitespace(gen->output_name);
  10946. if (gen->output_name.len == 0) {
  10947. gen->output_name = c->info.init_scope->pkg->name;
  10948. }
  10949. gen->output_base = gen->output_name;
  10950. } else {
  10951. gen->output_name = build_context.out_filepath;
  10952. gen->output_name = string_trim_whitespace(gen->output_name);
  10953. if (gen->output_name.len == 0) {
  10954. gen->output_name = c->info.init_scope->pkg->name;
  10955. }
  10956. isize pos = string_extension_position(gen->output_name);
  10957. if (pos < 0) {
  10958. gen->output_base = gen->output_name;
  10959. } else {
  10960. gen->output_base = substring(gen->output_name, 0, pos);
  10961. }
  10962. }
  10963. gbAllocator ha = heap_allocator();
  10964. array_init(&gen->output_object_paths, ha);
  10965. gen->output_base = path_to_full_path(ha, gen->output_base);
  10966. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  10967. output_file_path = gb_string_appendc(output_file_path, ".obj");
  10968. defer (gb_string_free(output_file_path));
  10969. gen->info = &c->info;
  10970. map_init(&gen->modules, permanent_allocator(), gen->info->packages.entries.count*2);
  10971. for_array(i, gen->info->packages.entries) {
  10972. AstPackage *pkg = gen->info->packages.entries[i].value;
  10973. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  10974. m->pkg = pkg;
  10975. map_set(&gen->modules, hash_pointer(pkg), m);
  10976. lb_init_module(m, c);
  10977. }
  10978. map_set(&gen->modules, hash_pointer(nullptr), &gen->default_module);
  10979. lb_init_module(&gen->default_module, c);
  10980. return true;
  10981. }
  10982. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  10983. GB_ASSERT(type != nullptr);
  10984. type = default_type(type);
  10985. isize max_len = 7+8+1;
  10986. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  10987. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  10988. m->global_generated_index++;
  10989. String name = make_string(str, len-1);
  10990. Scope *scope = nullptr;
  10991. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  10992. lbValue g = {};
  10993. g.type = alloc_type_pointer(type);
  10994. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  10995. if (value.value != nullptr) {
  10996. GB_ASSERT(LLVMIsConstant(value.value));
  10997. LLVMSetInitializer(g.value, value.value);
  10998. } else {
  10999. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  11000. }
  11001. lb_add_entity(m, e, g);
  11002. lb_add_member(m, name, g);
  11003. return lb_addr(g);
  11004. }
  11005. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  11006. AstPackage *p = m->info->runtime_package;
  11007. Entity *e = scope_lookup_current(p->scope, name);
  11008. lbValue *found = map_get(&m->values, hash_entity(e));
  11009. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  11010. lbValue value = *found;
  11011. return value;
  11012. }
  11013. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  11014. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  11015. lbValue *found = map_get(&m->values, hash_entity(e));
  11016. GB_ASSERT_MSG(found != nullptr, "Unable to find value '%.*s.%.*s'", LIT(pkg), LIT(name));
  11017. lbValue value = *found;
  11018. return value;
  11019. }
  11020. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  11021. i32 index = cast(i32)lb_type_info_index(m->info, type);
  11022. GB_ASSERT(index >= 0);
  11023. // gb_printf_err("%d %s\n", index, type_to_string(type));
  11024. LLVMValueRef indices[2] = {
  11025. LLVMConstInt(lb_type(m, t_int), 0, false),
  11026. LLVMConstInt(lb_type(m, t_int), index, false),
  11027. };
  11028. lbValue res = {};
  11029. res.type = t_type_info_ptr;
  11030. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  11031. return res;
  11032. }
  11033. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  11034. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  11035. lb_global_type_info_member_types_index += cast(i32)count;
  11036. return offset;
  11037. }
  11038. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  11039. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  11040. lb_global_type_info_member_names_index += cast(i32)count;
  11041. return offset;
  11042. }
  11043. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  11044. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  11045. lb_global_type_info_member_offsets_index += cast(i32)count;
  11046. return offset;
  11047. }
  11048. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  11049. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  11050. lb_global_type_info_member_usings_index += cast(i32)count;
  11051. return offset;
  11052. }
  11053. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  11054. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  11055. lb_global_type_info_member_tags_index += cast(i32)count;
  11056. return offset;
  11057. }
  11058. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  11059. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  11060. return lb_addr_get_ptr(p, addr);
  11061. }
  11062. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  11063. Token token = {Token_Ident};
  11064. isize name_len = prefix.len + 1 + 20;
  11065. auto suffix_id = cast(unsigned long long)id;
  11066. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  11067. gb_snprintf(text, name_len,
  11068. "%.*s-%llu", LIT(prefix), suffix_id);
  11069. text[name_len] = 0;
  11070. String s = make_string_c(text);
  11071. Type *t = alloc_type_array(elem_type, count);
  11072. lbValue g = {};
  11073. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  11074. g.type = alloc_type_pointer(t);
  11075. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  11076. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  11077. string_map_set(&m->members, s, g);
  11078. return g;
  11079. }
  11080. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  11081. lbModule *m = p->module;
  11082. LLVMContextRef ctx = m->ctx;
  11083. CheckerInfo *info = m->info;
  11084. {
  11085. // NOTE(bill): Set the type_table slice with the global backing array
  11086. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  11087. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  11088. GB_ASSERT(is_type_array(type));
  11089. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  11090. LLVMValueRef values[2] = {
  11091. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  11092. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  11093. };
  11094. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  11095. LLVMSetInitializer(global_type_table.value, slice);
  11096. }
  11097. // Useful types
  11098. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  11099. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  11100. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  11101. Type *t_type_info_flags = type_info_flags_entity->type;
  11102. i32 type_info_member_types_index = 0;
  11103. i32 type_info_member_names_index = 0;
  11104. i32 type_info_member_offsets_index = 0;
  11105. for_array(type_info_type_index, info->type_info_types) {
  11106. Type *t = info->type_info_types[type_info_type_index];
  11107. if (t == nullptr || t == t_invalid) {
  11108. continue;
  11109. }
  11110. isize entry_index = lb_type_info_index(info, t, false);
  11111. if (entry_index <= 0) {
  11112. continue;
  11113. }
  11114. lbValue tag = {};
  11115. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  11116. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  11117. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  11118. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  11119. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  11120. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  11121. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  11122. switch (t->kind) {
  11123. case Type_Named: {
  11124. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  11125. LLVMValueRef pkg_name = nullptr;
  11126. if (t->Named.type_name->pkg) {
  11127. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  11128. } else {
  11129. pkg_name = LLVMConstNull(lb_type(m, t_string));
  11130. }
  11131. String proc_name = {};
  11132. if (t->Named.type_name->parent_proc_decl) {
  11133. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  11134. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  11135. proc_name = decl->entity->token.string;
  11136. }
  11137. }
  11138. TokenPos pos = t->Named.type_name->token.pos;
  11139. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  11140. LLVMValueRef vals[4] = {
  11141. lb_const_string(p->module, t->Named.type_name->token.string).value,
  11142. lb_get_type_info_ptr(m, t->Named.base).value,
  11143. pkg_name,
  11144. loc.value
  11145. };
  11146. lbValue res = {};
  11147. res.type = type_deref(tag.type);
  11148. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11149. lb_emit_store(p, tag, res);
  11150. break;
  11151. }
  11152. case Type_Basic:
  11153. switch (t->Basic.kind) {
  11154. case Basic_bool:
  11155. case Basic_b8:
  11156. case Basic_b16:
  11157. case Basic_b32:
  11158. case Basic_b64:
  11159. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  11160. break;
  11161. case Basic_i8:
  11162. case Basic_u8:
  11163. case Basic_i16:
  11164. case Basic_u16:
  11165. case Basic_i32:
  11166. case Basic_u32:
  11167. case Basic_i64:
  11168. case Basic_u64:
  11169. case Basic_i128:
  11170. case Basic_u128:
  11171. case Basic_i16le:
  11172. case Basic_u16le:
  11173. case Basic_i32le:
  11174. case Basic_u32le:
  11175. case Basic_i64le:
  11176. case Basic_u64le:
  11177. case Basic_i128le:
  11178. case Basic_u128le:
  11179. case Basic_i16be:
  11180. case Basic_u16be:
  11181. case Basic_i32be:
  11182. case Basic_u32be:
  11183. case Basic_i64be:
  11184. case Basic_u64be:
  11185. case Basic_i128be:
  11186. case Basic_u128be:
  11187. case Basic_int:
  11188. case Basic_uint:
  11189. case Basic_uintptr: {
  11190. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  11191. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  11192. // NOTE(bill): This is matches the runtime layout
  11193. u8 endianness_value = 0;
  11194. if (t->Basic.flags & BasicFlag_EndianLittle) {
  11195. endianness_value = 1;
  11196. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  11197. endianness_value = 2;
  11198. }
  11199. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  11200. LLVMValueRef vals[2] = {
  11201. is_signed.value,
  11202. endianness.value,
  11203. };
  11204. lbValue res = {};
  11205. res.type = type_deref(tag.type);
  11206. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11207. lb_emit_store(p, tag, res);
  11208. break;
  11209. }
  11210. case Basic_rune:
  11211. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  11212. break;
  11213. case Basic_f16:
  11214. case Basic_f32:
  11215. case Basic_f64:
  11216. case Basic_f16le:
  11217. case Basic_f32le:
  11218. case Basic_f64le:
  11219. case Basic_f16be:
  11220. case Basic_f32be:
  11221. case Basic_f64be:
  11222. {
  11223. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  11224. // NOTE(bill): This is matches the runtime layout
  11225. u8 endianness_value = 0;
  11226. if (t->Basic.flags & BasicFlag_EndianLittle) {
  11227. endianness_value = 1;
  11228. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  11229. endianness_value = 2;
  11230. }
  11231. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  11232. LLVMValueRef vals[1] = {
  11233. endianness.value,
  11234. };
  11235. lbValue res = {};
  11236. res.type = type_deref(tag.type);
  11237. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11238. lb_emit_store(p, tag, res);
  11239. }
  11240. break;
  11241. case Basic_complex32:
  11242. case Basic_complex64:
  11243. case Basic_complex128:
  11244. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  11245. break;
  11246. case Basic_quaternion64:
  11247. case Basic_quaternion128:
  11248. case Basic_quaternion256:
  11249. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  11250. break;
  11251. case Basic_rawptr:
  11252. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  11253. break;
  11254. case Basic_string:
  11255. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  11256. break;
  11257. case Basic_cstring:
  11258. {
  11259. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  11260. LLVMValueRef vals[1] = {
  11261. lb_const_bool(m, t_bool, true).value,
  11262. };
  11263. lbValue res = {};
  11264. res.type = type_deref(tag.type);
  11265. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11266. lb_emit_store(p, tag, res);
  11267. }
  11268. break;
  11269. case Basic_any:
  11270. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  11271. break;
  11272. case Basic_typeid:
  11273. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  11274. break;
  11275. }
  11276. break;
  11277. case Type_Pointer: {
  11278. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  11279. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  11280. LLVMValueRef vals[1] = {
  11281. gep.value,
  11282. };
  11283. lbValue res = {};
  11284. res.type = type_deref(tag.type);
  11285. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11286. lb_emit_store(p, tag, res);
  11287. break;
  11288. }
  11289. case Type_Array: {
  11290. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  11291. i64 ez = type_size_of(t->Array.elem);
  11292. LLVMValueRef vals[3] = {
  11293. lb_get_type_info_ptr(m, t->Array.elem).value,
  11294. lb_const_int(m, t_int, ez).value,
  11295. lb_const_int(m, t_int, t->Array.count).value,
  11296. };
  11297. lbValue res = {};
  11298. res.type = type_deref(tag.type);
  11299. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11300. lb_emit_store(p, tag, res);
  11301. break;
  11302. }
  11303. case Type_EnumeratedArray: {
  11304. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  11305. LLVMValueRef vals[6] = {
  11306. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  11307. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  11308. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  11309. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  11310. // Unions
  11311. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  11312. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  11313. };
  11314. lbValue res = {};
  11315. res.type = type_deref(tag.type);
  11316. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11317. lb_emit_store(p, tag, res);
  11318. // NOTE(bill): Union assignment
  11319. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  11320. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  11321. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  11322. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  11323. lb_emit_store(p, min_value, min_v);
  11324. lb_emit_store(p, max_value, max_v);
  11325. break;
  11326. }
  11327. case Type_DynamicArray: {
  11328. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  11329. LLVMValueRef vals[2] = {
  11330. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  11331. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  11332. };
  11333. lbValue res = {};
  11334. res.type = type_deref(tag.type);
  11335. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11336. lb_emit_store(p, tag, res);
  11337. break;
  11338. }
  11339. case Type_Slice: {
  11340. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  11341. LLVMValueRef vals[2] = {
  11342. lb_get_type_info_ptr(m, t->Slice.elem).value,
  11343. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  11344. };
  11345. lbValue res = {};
  11346. res.type = type_deref(tag.type);
  11347. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11348. lb_emit_store(p, tag, res);
  11349. break;
  11350. }
  11351. case Type_Proc: {
  11352. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  11353. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11354. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11355. if (t->Proc.params != nullptr) {
  11356. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  11357. }
  11358. if (t->Proc.results != nullptr) {
  11359. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  11360. }
  11361. LLVMValueRef vals[4] = {
  11362. params,
  11363. results,
  11364. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  11365. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  11366. };
  11367. lbValue res = {};
  11368. res.type = type_deref(tag.type);
  11369. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11370. lb_emit_store(p, tag, res);
  11371. break;
  11372. }
  11373. case Type_Tuple: {
  11374. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  11375. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  11376. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  11377. for_array(i, t->Tuple.variables) {
  11378. // NOTE(bill): offset is not used for tuples
  11379. Entity *f = t->Tuple.variables[i];
  11380. lbValue index = lb_const_int(m, t_int, i);
  11381. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11382. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  11383. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  11384. if (f->token.string.len > 0) {
  11385. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  11386. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  11387. }
  11388. }
  11389. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  11390. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  11391. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  11392. LLVMValueRef vals[2] = {
  11393. types_slice,
  11394. names_slice,
  11395. };
  11396. lbValue res = {};
  11397. res.type = type_deref(tag.type);
  11398. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11399. lb_emit_store(p, tag, res);
  11400. break;
  11401. }
  11402. case Type_Enum:
  11403. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  11404. {
  11405. GB_ASSERT(t->Enum.base_type != nullptr);
  11406. // 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));
  11407. LLVMValueRef vals[3] = {};
  11408. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  11409. if (t->Enum.fields.count > 0) {
  11410. auto fields = t->Enum.fields;
  11411. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  11412. str_lit("$enum_names"), cast(i64)entry_index);
  11413. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  11414. str_lit("$enum_values"), cast(i64)entry_index);
  11415. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  11416. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  11417. GB_ASSERT(is_type_integer(t->Enum.base_type));
  11418. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  11419. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  11420. for_array(i, fields) {
  11421. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  11422. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  11423. }
  11424. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  11425. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  11426. LLVMSetInitializer(name_array.value, name_init);
  11427. LLVMSetInitializer(value_array.value, value_init);
  11428. lbValue v_count = lb_const_int(m, t_int, fields.count);
  11429. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  11430. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  11431. } else {
  11432. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  11433. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  11434. }
  11435. lbValue res = {};
  11436. res.type = type_deref(tag.type);
  11437. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11438. lb_emit_store(p, tag, res);
  11439. }
  11440. break;
  11441. case Type_Union: {
  11442. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  11443. {
  11444. LLVMValueRef vals[7] = {};
  11445. isize variant_count = gb_max(0, t->Union.variants.count);
  11446. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  11447. // NOTE(bill): Zeroth is nil so ignore it
  11448. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  11449. Type *vt = t->Union.variants[variant_index];
  11450. lbValue tip = lb_get_type_info_ptr(m, vt);
  11451. lbValue index = lb_const_int(m, t_int, variant_index);
  11452. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11453. lb_emit_store(p, type_info, lb_type_info(m, vt));
  11454. }
  11455. lbValue count = lb_const_int(m, t_int, variant_count);
  11456. vals[0] = llvm_const_slice(m, memory_types, count);
  11457. i64 tag_size = union_tag_size(t);
  11458. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  11459. if (tag_size > 0) {
  11460. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  11461. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  11462. } else {
  11463. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  11464. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11465. }
  11466. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  11467. vals[3] = lb_get_equal_proc_for_type(m, t).value;
  11468. }
  11469. vals[4] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  11470. vals[5] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  11471. vals[6] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  11472. for (isize i = 0; i < gb_count_of(vals); i++) {
  11473. if (vals[i] == nullptr) {
  11474. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  11475. }
  11476. }
  11477. lbValue res = {};
  11478. res.type = type_deref(tag.type);
  11479. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11480. lb_emit_store(p, tag, res);
  11481. }
  11482. break;
  11483. }
  11484. case Type_Struct: {
  11485. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  11486. LLVMValueRef vals[12] = {};
  11487. {
  11488. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  11489. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  11490. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  11491. vals[5] = is_packed.value;
  11492. vals[6] = is_raw_union.value;
  11493. vals[7] = is_custom_align.value;
  11494. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  11495. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  11496. }
  11497. if (t->Struct.soa_kind != StructSoa_None) {
  11498. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  11499. Type *kind_type = type_deref(kind.type);
  11500. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  11501. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  11502. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  11503. vals[9] = soa_kind.value;
  11504. vals[10] = soa_type.value;
  11505. vals[11] = soa_len.value;
  11506. }
  11507. }
  11508. isize count = t->Struct.fields.count;
  11509. if (count > 0) {
  11510. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  11511. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  11512. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  11513. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  11514. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  11515. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  11516. for (isize source_index = 0; source_index < count; source_index++) {
  11517. // TODO(bill): Order fields in source order not layout order
  11518. Entity *f = t->Struct.fields[source_index];
  11519. lbValue tip = lb_get_type_info_ptr(m, f->type);
  11520. i64 foffset = 0;
  11521. if (!t->Struct.is_raw_union) {
  11522. foffset = t->Struct.offsets[f->Variable.field_index];
  11523. }
  11524. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  11525. lbValue index = lb_const_int(m, t_int, source_index);
  11526. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11527. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  11528. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  11529. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  11530. if (f->token.string.len > 0) {
  11531. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  11532. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  11533. }
  11534. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  11535. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  11536. if (t->Struct.tags.count > 0) {
  11537. String tag_string = t->Struct.tags[source_index];
  11538. if (tag_string.len > 0) {
  11539. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  11540. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  11541. }
  11542. }
  11543. }
  11544. lbValue cv = lb_const_int(m, t_int, count);
  11545. vals[0] = llvm_const_slice(m, memory_types, cv);
  11546. vals[1] = llvm_const_slice(m, memory_names, cv);
  11547. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  11548. vals[3] = llvm_const_slice(m, memory_usings, cv);
  11549. vals[4] = llvm_const_slice(m, memory_tags, cv);
  11550. }
  11551. for (isize i = 0; i < gb_count_of(vals); i++) {
  11552. if (vals[i] == nullptr) {
  11553. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  11554. }
  11555. }
  11556. lbValue res = {};
  11557. res.type = type_deref(tag.type);
  11558. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11559. lb_emit_store(p, tag, res);
  11560. break;
  11561. }
  11562. case Type_Map: {
  11563. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  11564. init_map_internal_types(t);
  11565. LLVMValueRef vals[5] = {
  11566. lb_get_type_info_ptr(m, t->Map.key).value,
  11567. lb_get_type_info_ptr(m, t->Map.value).value,
  11568. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  11569. lb_get_equal_proc_for_type(m, t->Map.key).value,
  11570. lb_get_hasher_proc_for_type(m, t->Map.key).value
  11571. };
  11572. lbValue res = {};
  11573. res.type = type_deref(tag.type);
  11574. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11575. lb_emit_store(p, tag, res);
  11576. break;
  11577. }
  11578. case Type_BitSet:
  11579. {
  11580. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  11581. GB_ASSERT(is_type_typed(t->BitSet.elem));
  11582. LLVMValueRef vals[4] = {
  11583. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  11584. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  11585. lb_const_int(m, t_i64, t->BitSet.lower).value,
  11586. lb_const_int(m, t_i64, t->BitSet.upper).value,
  11587. };
  11588. if (t->BitSet.underlying != nullptr) {
  11589. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  11590. }
  11591. lbValue res = {};
  11592. res.type = type_deref(tag.type);
  11593. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11594. lb_emit_store(p, tag, res);
  11595. }
  11596. break;
  11597. case Type_SimdVector:
  11598. {
  11599. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  11600. LLVMValueRef vals[3] = {};
  11601. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  11602. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  11603. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  11604. lbValue res = {};
  11605. res.type = type_deref(tag.type);
  11606. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11607. lb_emit_store(p, tag, res);
  11608. }
  11609. break;
  11610. case Type_RelativePointer:
  11611. {
  11612. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  11613. LLVMValueRef vals[2] = {
  11614. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  11615. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  11616. };
  11617. lbValue res = {};
  11618. res.type = type_deref(tag.type);
  11619. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11620. lb_emit_store(p, tag, res);
  11621. }
  11622. break;
  11623. case Type_RelativeSlice:
  11624. {
  11625. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  11626. LLVMValueRef vals[2] = {
  11627. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  11628. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  11629. };
  11630. lbValue res = {};
  11631. res.type = type_deref(tag.type);
  11632. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11633. lb_emit_store(p, tag, res);
  11634. }
  11635. break;
  11636. }
  11637. if (tag.value != nullptr) {
  11638. Type *tag_type = type_deref(tag.type);
  11639. GB_ASSERT(is_type_named(tag_type));
  11640. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  11641. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  11642. } else {
  11643. if (t != t_llvm_bool) {
  11644. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  11645. }
  11646. }
  11647. }
  11648. }
  11649. struct lbGlobalVariable {
  11650. lbValue var;
  11651. lbValue init;
  11652. DeclInfo *decl;
  11653. bool is_initialized;
  11654. };
  11655. lbProcedure *lb_create_startup_type_info(lbModule *m) {
  11656. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  11657. defer (LLVMDisposePassManager(default_function_pass_manager));
  11658. lb_populate_function_pass_manager(default_function_pass_manager, false, build_context.optimization_level);
  11659. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11660. Type *params = alloc_type_tuple();
  11661. Type *results = alloc_type_tuple();
  11662. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11663. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  11664. p->is_startup = true;
  11665. lb_begin_procedure_body(p);
  11666. lb_setup_type_info_data(p);
  11667. lb_end_procedure_body(p);
  11668. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11669. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11670. LLVMDumpValue(p->value);
  11671. gb_printf_err("\n\n\n\n");
  11672. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11673. }
  11674. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11675. return p;
  11676. }
  11677. lbProcedure *lb_create_startup_runtime(lbModule *m, lbProcedure *startup_type_info, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  11678. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  11679. defer (LLVMDisposePassManager(default_function_pass_manager));
  11680. lb_populate_function_pass_manager(default_function_pass_manager, false, build_context.optimization_level);
  11681. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11682. Type *params = alloc_type_tuple();
  11683. Type *results = alloc_type_tuple();
  11684. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11685. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  11686. p->is_startup = true;
  11687. lb_begin_procedure_body(p);
  11688. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  11689. for_array(i, global_variables) {
  11690. auto *var = &global_variables[i];
  11691. if (var->is_initialized) {
  11692. continue;
  11693. }
  11694. Entity *e = var->decl->entity;
  11695. GB_ASSERT(e->kind == Entity_Variable);
  11696. if (var->decl->init_expr != nullptr) {
  11697. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  11698. lbValue init = lb_build_expr(p, var->decl->init_expr);
  11699. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  11700. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  11701. if (lb_is_const_or_global(init)) {
  11702. if (!var->is_initialized) {
  11703. LLVMSetInitializer(var->var.value, init.value);
  11704. var->is_initialized = true;
  11705. continue;
  11706. }
  11707. } else {
  11708. var->init = init;
  11709. }
  11710. }
  11711. if (var->init.value != nullptr) {
  11712. GB_ASSERT(!var->is_initialized);
  11713. Type *t = type_deref(var->var.type);
  11714. if (is_type_any(t)) {
  11715. // NOTE(bill): Edge case for 'any' type
  11716. Type *var_type = default_type(var->init.type);
  11717. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  11718. lb_addr_store(p, g, var->init);
  11719. lbValue gp = lb_addr_get_ptr(p, g);
  11720. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  11721. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  11722. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  11723. lb_emit_store(p, ti, lb_type_info(m, var_type));
  11724. } else {
  11725. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  11726. LLVMTypeRef vt = LLVMGetElementType(pvt);
  11727. lbValue src0 = lb_emit_conv(p, var->init, t);
  11728. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  11729. LLVMValueRef dst = var->var.value;
  11730. LLVMBuildStore(p->builder, src, dst);
  11731. }
  11732. var->is_initialized = true;
  11733. }
  11734. }
  11735. lb_end_procedure_body(p);
  11736. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11737. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11738. LLVMDumpValue(p->value);
  11739. gb_printf_err("\n\n\n\n");
  11740. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11741. }
  11742. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11743. return p;
  11744. }
  11745. lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime) {
  11746. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  11747. defer (LLVMDisposePassManager(default_function_pass_manager));
  11748. lb_populate_function_pass_manager(default_function_pass_manager, false, build_context.optimization_level);
  11749. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11750. Type *params = alloc_type_tuple();
  11751. Type *results = alloc_type_tuple();
  11752. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  11753. String name = str_lit("main");
  11754. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  11755. name = str_lit("mainCRTStartup");
  11756. } else {
  11757. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  11758. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  11759. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  11760. }
  11761. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  11762. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  11763. Type *proc_type = alloc_type_proc(nullptr,
  11764. params, params->Tuple.variables.count,
  11765. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  11766. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  11767. p->is_startup = true;
  11768. lb_begin_procedure_body(p);
  11769. { // initialize `runtime.args__`
  11770. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  11771. argc = lb_emit_conv(p, argc, t_int);
  11772. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  11773. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  11774. lb_fill_slice(p, args, argv, argc);
  11775. }
  11776. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  11777. if (build_context.command_kind == Command_test) {
  11778. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  11779. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  11780. Type *slice_type = alloc_type_slice(t_Internal_Test);
  11781. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  11782. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  11783. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  11784. LLVMValueRef indices[2] = {};
  11785. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  11786. for_array(i, m->info->testing_procedures) {
  11787. Entity *testing_proc = m->info->testing_procedures[i];
  11788. String name = testing_proc->token.string;
  11789. lbValue *found = map_get(&m->values, hash_entity(testing_proc));
  11790. GB_ASSERT(found != nullptr);
  11791. String pkg_name = {};
  11792. if (testing_proc->pkg != nullptr) {
  11793. pkg_name = testing_proc->pkg->name;
  11794. }
  11795. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  11796. lbValue v_name = lb_find_or_add_entity_string(m, name);
  11797. lbValue v_proc = *found;
  11798. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  11799. LLVMValueRef vals[3] = {};
  11800. vals[0] = v_pkg.value;
  11801. vals[1] = v_name.value;
  11802. vals[2] = v_proc.value;
  11803. GB_ASSERT(LLVMIsConstant(vals[0]));
  11804. GB_ASSERT(LLVMIsConstant(vals[1]));
  11805. GB_ASSERT(LLVMIsConstant(vals[2]));
  11806. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  11807. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  11808. LLVMBuildStore(p->builder, src, dst);
  11809. }
  11810. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  11811. lb_fill_slice(p, all_tests_slice,
  11812. lb_array_elem(p, all_tests_array),
  11813. lb_const_int(m, t_int, m->info->testing_procedures.count));
  11814. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  11815. auto args = array_make<lbValue>(heap_allocator(), 1);
  11816. args[0] = lb_addr_load(p, all_tests_slice);
  11817. lb_emit_call(p, runner, args);
  11818. } else {
  11819. lbValue *found = map_get(&m->values, hash_entity(m->info->entry_point));
  11820. GB_ASSERT(found != nullptr);
  11821. lb_emit_call(p, *found, {});
  11822. }
  11823. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  11824. lb_end_procedure_body(p);
  11825. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11826. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11827. LLVMDumpValue(p->value);
  11828. gb_printf_err("\n\n\n\n");
  11829. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11830. }
  11831. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11832. return p;
  11833. }
  11834. void lb_generate_code(lbGenerator *gen) {
  11835. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  11836. TIME_SECTION("LLVM Initializtion");
  11837. lbModule *m = &gen->default_module;
  11838. CheckerInfo *info = gen->info;
  11839. auto *min_dep_set = &info->minimum_dependency_set;
  11840. LLVMInitializeAllTargetInfos();
  11841. LLVMInitializeAllTargets();
  11842. LLVMInitializeAllTargetMCs();
  11843. LLVMInitializeAllAsmPrinters();
  11844. LLVMInitializeAllAsmParsers();
  11845. LLVMInitializeAllDisassemblers();
  11846. LLVMInitializeNativeTarget();
  11847. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  11848. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  11849. for_array(i, gen->modules.entries) {
  11850. LLVMSetTarget(gen->modules.entries[i].value->mod, target_triple);
  11851. }
  11852. LLVMTargetRef target = {};
  11853. char *llvm_error = nullptr;
  11854. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  11855. GB_ASSERT(target != nullptr);
  11856. TIME_SECTION("LLVM Create Target Machine");
  11857. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  11858. if (build_context.metrics.arch == TargetArch_wasm32) {
  11859. code_mode = LLVMCodeModelJITDefault;
  11860. }
  11861. char const *host_cpu_name = LLVMGetHostCPUName();
  11862. char const *llvm_cpu = "generic";
  11863. char const *llvm_features = "";
  11864. if (build_context.microarch.len != 0) {
  11865. if (build_context.microarch == "native") {
  11866. llvm_cpu = host_cpu_name;
  11867. } else {
  11868. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  11869. }
  11870. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  11871. llvm_features = LLVMGetHostCPUFeatures();
  11872. }
  11873. }
  11874. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  11875. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  11876. switch (build_context.optimization_level) {
  11877. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  11878. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  11879. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  11880. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  11881. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  11882. }
  11883. // NOTE(bill): Target Machine Creation
  11884. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(
  11885. target, target_triple, llvm_cpu,
  11886. llvm_features,
  11887. code_gen_level,
  11888. LLVMRelocDefault,
  11889. code_mode);
  11890. defer (LLVMDisposeTargetMachine(target_machine));
  11891. for_array(i, gen->modules.entries) {
  11892. LLVMSetModuleDataLayout(gen->modules.entries[i].value->mod, LLVMCreateTargetDataLayout(target_machine));
  11893. }
  11894. if (m->debug_builder) { // Debug Info
  11895. for_array(i, info->files.entries) {
  11896. AstFile *f = info->files.entries[i].value;
  11897. String fullpath = f->fullpath;
  11898. String filename = remove_directory_from_path(fullpath);
  11899. String directory = directory_from_path(fullpath);
  11900. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  11901. cast(char const *)filename.text, filename.len,
  11902. cast(char const *)directory.text, directory.len);
  11903. lb_set_llvm_metadata(m, f, res);
  11904. }
  11905. gbString producer = gb_string_make(heap_allocator(), "odin");
  11906. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  11907. // #ifdef NIGHTLY
  11908. // producer = gb_string_appendc(producer, "-nightly");
  11909. // #endif
  11910. // #ifdef GIT_SHA
  11911. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  11912. // #endif
  11913. gbString split_name = gb_string_make(heap_allocator(), "");
  11914. LLVMBool is_optimized = build_context.optimization_level > 0;
  11915. AstFile *init_file = m->info->init_package->files[0];
  11916. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  11917. init_file = m->info->entry_point->identifier->file;
  11918. }
  11919. LLVMBool split_debug_inlining = false;
  11920. LLVMBool debug_info_for_profiling = false;
  11921. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  11922. lb_get_llvm_metadata(m, init_file),
  11923. producer, gb_string_length(producer),
  11924. is_optimized, "", 0,
  11925. 1, split_name, gb_string_length(split_name),
  11926. LLVMDWARFEmissionFull,
  11927. 0, split_debug_inlining,
  11928. debug_info_for_profiling,
  11929. "", 0, // sys_root
  11930. "", 0 // SDK
  11931. );
  11932. GB_ASSERT(m->debug_compile_unit != nullptr);
  11933. }
  11934. TIME_SECTION("LLVM Global Variables");
  11935. {
  11936. { // Add type info data
  11937. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  11938. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  11939. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  11940. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  11941. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11942. LLVMSetLinkage(g, LLVMInternalLinkage);
  11943. lbValue value = {};
  11944. value.value = g;
  11945. value.type = alloc_type_pointer(t);
  11946. lb_global_type_info_data = lb_addr(value);
  11947. }
  11948. { // Type info member buffer
  11949. // NOTE(bill): Removes need for heap allocation by making it global memory
  11950. isize count = 0;
  11951. for_array(entry_index, m->info->type_info_types) {
  11952. Type *t = m->info->type_info_types[entry_index];
  11953. isize index = lb_type_info_index(m->info, t, false);
  11954. if (index < 0) {
  11955. continue;
  11956. }
  11957. switch (t->kind) {
  11958. case Type_Union:
  11959. count += t->Union.variants.count;
  11960. break;
  11961. case Type_Struct:
  11962. count += t->Struct.fields.count;
  11963. break;
  11964. case Type_Tuple:
  11965. count += t->Tuple.variables.count;
  11966. break;
  11967. }
  11968. }
  11969. if (count > 0) {
  11970. {
  11971. char const *name = LB_TYPE_INFO_TYPES_NAME;
  11972. Type *t = alloc_type_array(t_type_info_ptr, count);
  11973. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  11974. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11975. LLVMSetLinkage(g, LLVMInternalLinkage);
  11976. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  11977. }
  11978. {
  11979. char const *name = LB_TYPE_INFO_NAMES_NAME;
  11980. Type *t = alloc_type_array(t_string, count);
  11981. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  11982. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11983. LLVMSetLinkage(g, LLVMInternalLinkage);
  11984. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  11985. }
  11986. {
  11987. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  11988. Type *t = alloc_type_array(t_uintptr, count);
  11989. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  11990. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11991. LLVMSetLinkage(g, LLVMInternalLinkage);
  11992. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  11993. }
  11994. {
  11995. char const *name = LB_TYPE_INFO_USINGS_NAME;
  11996. Type *t = alloc_type_array(t_bool, count);
  11997. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  11998. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11999. LLVMSetLinkage(g, LLVMInternalLinkage);
  12000. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  12001. }
  12002. {
  12003. char const *name = LB_TYPE_INFO_TAGS_NAME;
  12004. Type *t = alloc_type_array(t_string, count);
  12005. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  12006. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  12007. LLVMSetLinkage(g, LLVMInternalLinkage);
  12008. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  12009. }
  12010. }
  12011. }
  12012. }
  12013. isize global_variable_max_count = 0;
  12014. Entity *entry_point = info->entry_point;
  12015. bool has_dll_main = false;
  12016. bool has_win_main = false;
  12017. for_array(i, info->entities) {
  12018. Entity *e = info->entities[i];
  12019. String name = e->token.string;
  12020. bool is_global = e->pkg != nullptr;
  12021. if (e->kind == Entity_Variable) {
  12022. global_variable_max_count++;
  12023. } else if (e->kind == Entity_Procedure && !is_global) {
  12024. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  12025. GB_ASSERT(e == entry_point);
  12026. // entry_point = e;
  12027. }
  12028. if (e->Procedure.is_export ||
  12029. (e->Procedure.link_name.len > 0) ||
  12030. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  12031. if (!has_dll_main && name == "DllMain") {
  12032. has_dll_main = true;
  12033. } else if (!has_win_main && name == "WinMain") {
  12034. has_win_main = true;
  12035. }
  12036. }
  12037. }
  12038. }
  12039. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  12040. for_array(i, info->variable_init_order) {
  12041. DeclInfo *d = info->variable_init_order[i];
  12042. Entity *e = d->entity;
  12043. if ((e->scope->flags & ScopeFlag_File) == 0) {
  12044. continue;
  12045. }
  12046. if (!ptr_set_exists(min_dep_set, e)) {
  12047. continue;
  12048. }
  12049. DeclInfo *decl = decl_info_of_entity(e);
  12050. if (decl == nullptr) {
  12051. continue;
  12052. }
  12053. GB_ASSERT(e->kind == Entity_Variable);
  12054. bool is_foreign = e->Variable.is_foreign;
  12055. bool is_export = e->Variable.is_export;
  12056. String name = lb_get_entity_name(m, e);
  12057. lbValue g = {};
  12058. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  12059. g.type = alloc_type_pointer(e->type);
  12060. if (e->Variable.thread_local_model != "") {
  12061. LLVMSetThreadLocal(g.value, true);
  12062. String m = e->Variable.thread_local_model;
  12063. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  12064. if (m == "default") {
  12065. mode = LLVMGeneralDynamicTLSModel;
  12066. } else if (m == "localdynamic") {
  12067. mode = LLVMLocalDynamicTLSModel;
  12068. } else if (m == "initialexec") {
  12069. mode = LLVMInitialExecTLSModel;
  12070. } else if (m == "localexec") {
  12071. mode = LLVMLocalExecTLSModel;
  12072. } else {
  12073. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  12074. }
  12075. LLVMSetThreadLocalMode(g.value, mode);
  12076. }
  12077. if (is_foreign) {
  12078. LLVMSetExternallyInitialized(g.value, true);
  12079. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  12080. } else {
  12081. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  12082. }
  12083. if (is_export) {
  12084. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  12085. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  12086. }
  12087. if (e->flags & EntityFlag_Static) {
  12088. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  12089. }
  12090. lbGlobalVariable var = {};
  12091. var.var = g;
  12092. var.decl = decl;
  12093. if (decl->init_expr != nullptr) {
  12094. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  12095. if (!is_type_any(e->type)) {
  12096. if (tav.mode != Addressing_Invalid) {
  12097. if (tav.value.kind != ExactValue_Invalid) {
  12098. ExactValue v = tav.value;
  12099. lbValue init = lb_const_value(m, tav.type, v);
  12100. LLVMSetInitializer(g.value, init.value);
  12101. var.is_initialized = true;
  12102. }
  12103. }
  12104. }
  12105. if (!var.is_initialized &&
  12106. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  12107. var.is_initialized = true;
  12108. }
  12109. }
  12110. array_add(&global_variables, var);
  12111. lb_add_entity(m, e, g);
  12112. lb_add_member(m, name, g);
  12113. if (m->debug_builder) {
  12114. String global_name = e->token.string;
  12115. if (global_name.len != 0 && global_name != "_") {
  12116. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  12117. LLVMMetadataRef llvm_scope = llvm_file;
  12118. LLVMBool local_to_unit = e->flags & EntityFlag_Static;
  12119. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  12120. LLVMMetadataRef llvm_decl = nullptr;
  12121. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  12122. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  12123. m->debug_builder, llvm_scope,
  12124. cast(char const *)global_name.text, global_name.len,
  12125. "", 0, // linkage
  12126. llvm_file, e->token.pos.line,
  12127. lb_debug_type(m, e->type),
  12128. local_to_unit,
  12129. llvm_expr,
  12130. llvm_decl,
  12131. align_in_bits
  12132. );
  12133. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  12134. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  12135. }
  12136. }
  12137. }
  12138. TIME_SECTION("LLVM Global Procedures and Types");
  12139. for_array(i, info->entities) {
  12140. Entity *e = info->entities[i];
  12141. String name = e->token.string;
  12142. DeclInfo *decl = e->decl_info;
  12143. Scope * scope = e->scope;
  12144. if ((scope->flags & ScopeFlag_File) == 0) {
  12145. continue;
  12146. }
  12147. Scope *package_scope = scope->parent;
  12148. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  12149. switch (e->kind) {
  12150. case Entity_Variable:
  12151. // NOTE(bill): Handled above as it requires a specific load order
  12152. continue;
  12153. case Entity_ProcGroup:
  12154. continue;
  12155. case Entity_TypeName:
  12156. case Entity_Procedure:
  12157. break;
  12158. }
  12159. bool polymorphic_struct = false;
  12160. if (e->type != nullptr && e->kind == Entity_TypeName) {
  12161. Type *bt = base_type(e->type);
  12162. if (bt->kind == Type_Struct) {
  12163. polymorphic_struct = is_type_polymorphic(bt);
  12164. }
  12165. }
  12166. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  12167. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  12168. continue;
  12169. }
  12170. String mangled_name = lb_get_entity_name(m, e);
  12171. switch (e->kind) {
  12172. case Entity_TypeName:
  12173. lb_type(m, e->type);
  12174. break;
  12175. case Entity_Procedure:
  12176. {
  12177. lbProcedure *p = lb_create_procedure(m, e);
  12178. array_add(&m->procedures_to_generate, p);
  12179. }
  12180. break;
  12181. }
  12182. }
  12183. TIME_SECTION("LLVM Registry Initializtion");
  12184. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  12185. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  12186. LLVMPassManagerRef function_pass_manager_minimal = LLVMCreateFunctionPassManagerForModule(m->mod);
  12187. LLVMPassManagerRef function_pass_manager_size = LLVMCreateFunctionPassManagerForModule(m->mod);
  12188. LLVMPassManagerRef function_pass_manager_speed = LLVMCreateFunctionPassManagerForModule(m->mod);
  12189. defer (LLVMDisposePassManager(default_function_pass_manager));
  12190. defer (LLVMDisposePassManager(function_pass_manager_minimal));
  12191. defer (LLVMDisposePassManager(function_pass_manager_size));
  12192. defer (LLVMDisposePassManager(function_pass_manager_speed));
  12193. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  12194. LLVMInitializeFunctionPassManager(function_pass_manager_minimal);
  12195. LLVMInitializeFunctionPassManager(function_pass_manager_size);
  12196. LLVMInitializeFunctionPassManager(function_pass_manager_speed);
  12197. lb_populate_function_pass_manager(default_function_pass_manager, false, build_context.optimization_level);
  12198. lb_populate_function_pass_manager_specific(function_pass_manager_minimal, 0);
  12199. lb_populate_function_pass_manager_specific(function_pass_manager_size, 1);
  12200. lb_populate_function_pass_manager_specific(function_pass_manager_speed, 2);
  12201. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12202. LLVMFinalizeFunctionPassManager(function_pass_manager_minimal);
  12203. LLVMFinalizeFunctionPassManager(function_pass_manager_size);
  12204. LLVMFinalizeFunctionPassManager(function_pass_manager_speed);
  12205. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(m->mod);
  12206. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  12207. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  12208. lb_populate_function_pass_manager(default_function_pass_manager_without_memcpy, true, build_context.optimization_level);
  12209. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  12210. TIME_SECTION("LLVM Runtime Type Information Creation");
  12211. lbProcedure *startup_type_info = lb_create_startup_type_info(m);
  12212. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  12213. lbProcedure *startup_runtime = lb_create_startup_runtime(m, startup_type_info, global_variables);
  12214. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  12215. TIME_SECTION("LLVM Procedure Generation");
  12216. for_array(i, m->procedures_to_generate) {
  12217. lbProcedure *p = m->procedures_to_generate[i];
  12218. if (p->is_done) {
  12219. continue;
  12220. }
  12221. if (p->body != nullptr) { // Build Procedure
  12222. m->curr_procedure = p;
  12223. lb_begin_procedure_body(p);
  12224. lb_build_stmt(p, p->body);
  12225. lb_end_procedure_body(p);
  12226. p->is_done = true;
  12227. m->curr_procedure = nullptr;
  12228. }
  12229. lb_end_procedure(p);
  12230. // Add Flags
  12231. if (p->body != nullptr) {
  12232. if (p->name == "memcpy" || p->name == "memmove" ||
  12233. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  12234. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  12235. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  12236. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  12237. }
  12238. }
  12239. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12240. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  12241. LLVMDumpValue(p->value);
  12242. gb_printf_err("\n\n\n\n");
  12243. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12244. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12245. }
  12246. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  12247. gb_exit(1);
  12248. }
  12249. }
  12250. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  12251. TIME_SECTION("LLVM main");
  12252. lb_create_main_procedure(m, startup_runtime);
  12253. }
  12254. if (m->debug_builder != nullptr) {
  12255. TIME_SECTION("LLVM Debug Info Complete Types");
  12256. lb_debug_complete_types(m);
  12257. TIME_SECTION("LLVM Print Module to File");
  12258. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12259. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12260. gb_exit(1);
  12261. return;
  12262. }
  12263. TIME_SECTION("LLVM Debug Info Builder Finalize");
  12264. LLVMDIBuilderFinalize(m->debug_builder);
  12265. }
  12266. TIME_SECTION("LLVM Function Pass");
  12267. for_array(i, gen->modules.entries) {
  12268. lbModule *m = gen->modules.entries[i].value;
  12269. for_array(i, m->procedures_to_generate) {
  12270. lbProcedure *p = m->procedures_to_generate[i];
  12271. if (p->body != nullptr) { // Build Procedure
  12272. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  12273. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  12274. } else {
  12275. if (p->entity && p->entity->kind == Entity_Procedure) {
  12276. switch (p->entity->Procedure.optimization_mode) {
  12277. case ProcedureOptimizationMode_None:
  12278. case ProcedureOptimizationMode_Minimal:
  12279. LLVMRunFunctionPassManager(function_pass_manager_minimal, p->value);
  12280. break;
  12281. case ProcedureOptimizationMode_Size:
  12282. LLVMRunFunctionPassManager(function_pass_manager_size, p->value);
  12283. break;
  12284. case ProcedureOptimizationMode_Speed:
  12285. LLVMRunFunctionPassManager(function_pass_manager_speed, p->value);
  12286. break;
  12287. default:
  12288. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  12289. break;
  12290. }
  12291. } else {
  12292. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  12293. }
  12294. }
  12295. }
  12296. }
  12297. for_array(i, m->equal_procs.entries) {
  12298. lbProcedure *p = m->equal_procs.entries[i].value;
  12299. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  12300. }
  12301. for_array(i, m->hasher_procs.entries) {
  12302. lbProcedure *p = m->hasher_procs.entries[i].value;
  12303. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  12304. }
  12305. }
  12306. TIME_SECTION("LLVM Module Pass");
  12307. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  12308. defer (LLVMDisposePassManager(module_pass_manager));
  12309. lb_populate_module_pass_manager(target_machine, module_pass_manager, build_context.optimization_level);
  12310. for_array(i, gen->modules.entries) {
  12311. lbModule *m = gen->modules.entries[i].value;
  12312. LLVMRunPassManager(module_pass_manager, m->mod);
  12313. }
  12314. llvm_error = nullptr;
  12315. defer (LLVMDisposeMessage(llvm_error));
  12316. String filepath_obj = {};
  12317. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  12318. if (build_context.build_mode == BuildMode_Assembly) {
  12319. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  12320. code_gen_file_type = LLVMAssemblyFile;
  12321. } else {
  12322. switch (build_context.metrics.os) {
  12323. case TargetOs_windows:
  12324. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  12325. break;
  12326. case TargetOs_darwin:
  12327. case TargetOs_linux:
  12328. case TargetOs_essence:
  12329. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  12330. break;
  12331. case TargetOs_js:
  12332. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  12333. break;
  12334. }
  12335. }
  12336. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  12337. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  12338. if (build_context.keep_temp_files) {
  12339. TIME_SECTION("LLVM Print Module to File");
  12340. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12341. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12342. gb_exit(1);
  12343. return;
  12344. }
  12345. }
  12346. gb_exit(1);
  12347. return;
  12348. }
  12349. llvm_error = nullptr;
  12350. if (build_context.keep_temp_files ||
  12351. build_context.build_mode == BuildMode_LLVM_IR) {
  12352. TIME_SECTION("LLVM Print Module to File");
  12353. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12354. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12355. gb_exit(1);
  12356. return;
  12357. }
  12358. if (build_context.build_mode == BuildMode_LLVM_IR) {
  12359. gb_exit(0);
  12360. return;
  12361. }
  12362. }
  12363. TIME_SECTION("LLVM Object Generation");
  12364. if (LLVMTargetMachineEmitToFile(target_machine, m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  12365. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12366. gb_exit(1);
  12367. return;
  12368. }
  12369. array_add(&gen->output_object_paths, filepath_obj);
  12370. for_array(i, m->info->required_foreign_imports_through_force) {
  12371. Entity *e = m->info->required_foreign_imports_through_force[i];
  12372. lb_add_foreign_library_path(m, e);
  12373. }
  12374. #undef TIME_SECTION
  12375. }