llvm_backend.cpp 365 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845
  1. #include "llvm_backend.hpp"
  2. gb_global lbAddr lb_global_type_info_data = {};
  3. gb_global lbAddr lb_global_type_info_member_types = {};
  4. gb_global lbAddr lb_global_type_info_member_names = {};
  5. gb_global lbAddr lb_global_type_info_member_offsets = {};
  6. gb_global lbAddr lb_global_type_info_member_usings = {};
  7. gb_global lbAddr lb_global_type_info_member_tags = {};
  8. gb_global isize lb_global_type_info_data_index = 0;
  9. gb_global isize lb_global_type_info_member_types_index = 0;
  10. gb_global isize lb_global_type_info_member_names_index = 0;
  11. gb_global isize lb_global_type_info_member_offsets_index = 0;
  12. gb_global isize lb_global_type_info_member_usings_index = 0;
  13. gb_global isize lb_global_type_info_member_tags_index = 0;
  14. struct lbLoopData {
  15. lbAddr idx_addr;
  16. lbValue idx;
  17. lbBlock *body;
  18. lbBlock *done;
  19. lbBlock *loop;
  20. };
  21. struct lbCompoundLitElemTempData {
  22. Ast * expr;
  23. lbValue value;
  24. i32 elem_index;
  25. lbValue gep;
  26. };
  27. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  28. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  29. LLVMValueRef llvm_zero32(lbModule *m) {
  30. return LLVMConstInt(lb_type(m, t_i32), 0, false);
  31. }
  32. LLVMValueRef llvm_one32(lbModule *m) {
  33. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  34. }
  35. lbValue lb_zero(lbModule *m, Type *t) {
  36. lbValue v = {};
  37. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  38. v.type = t;
  39. return v;
  40. }
  41. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  42. lbValue v = lb_find_or_add_entity_string(m, str);
  43. unsigned indices[1] = {0};
  44. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  45. }
  46. lbAddr lb_addr(lbValue addr) {
  47. lbAddr v = {lbAddr_Default, addr};
  48. return v;
  49. }
  50. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  51. lbAddr v = {lbAddr_Map, addr};
  52. v.map.key = map_key;
  53. v.map.type = map_type;
  54. v.map.result = map_result;
  55. return v;
  56. }
  57. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  58. lbAddr v = {lbAddr_SoaVariable, addr};
  59. v.soa.index = index;
  60. v.soa.index_expr = index_expr;
  61. return v;
  62. }
  63. lbAddr lb_addr_bit_field(lbValue value, i32 index) {
  64. lbAddr addr = {};
  65. addr.kind = lbAddr_BitField;
  66. addr.addr = value;
  67. addr.bit_field.value_index = index;
  68. return addr;
  69. }
  70. Type *lb_addr_type(lbAddr const &addr) {
  71. if (addr.addr.value == nullptr) {
  72. return nullptr;
  73. }
  74. if (addr.kind == lbAddr_Map) {
  75. Type *t = base_type(addr.map.type);
  76. GB_ASSERT(is_type_map(t));
  77. return t->Map.value;
  78. }
  79. return type_deref(addr.addr.type);
  80. }
  81. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  82. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  83. }
  84. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  85. if (addr.addr.value == nullptr) {
  86. GB_PANIC("Illegal addr -> nullptr");
  87. return {};
  88. }
  89. switch (addr.kind) {
  90. case lbAddr_Map: {
  91. Type *map_type = base_type(addr.map.type);
  92. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  93. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  94. auto args = array_make<lbValue>(heap_allocator(), 2);
  95. args[0] = h;
  96. args[1] = key;
  97. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  98. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  99. }
  100. case lbAddr_BitField: {
  101. lbValue v = lb_addr_load(p, addr);
  102. return lb_address_from_load_or_generate_local(p, v);
  103. }
  104. case lbAddr_Context:
  105. GB_PANIC("lbAddr_Context should be handled elsewhere");
  106. }
  107. return addr.addr;
  108. }
  109. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  110. lbAddr addr = lb_build_addr(p, expr);
  111. return lb_addr_get_ptr(p, addr);
  112. }
  113. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  114. }
  115. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  116. }
  117. void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value) {
  118. if (addr.addr.value == nullptr) {
  119. return;
  120. }
  121. GB_ASSERT(value.type != nullptr);
  122. if (is_type_untyped_undef(value.type)) {
  123. Type *t = lb_addr_type(addr);
  124. value.type = t;
  125. value.value = LLVMGetUndef(lb_type(p->module, t));
  126. } else if (is_type_untyped_nil(value.type)) {
  127. Type *t = lb_addr_type(addr);
  128. value.type = t;
  129. value.value = LLVMConstNull(lb_type(p->module, t));
  130. }
  131. if (addr.kind == lbAddr_AtomOp_index_set) {
  132. lbValue ptr = addr.addr;
  133. lbValue index = addr.index_set.index;
  134. Ast *node = addr.index_set.node;
  135. ast_node(ce, CallExpr, node);
  136. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  137. proc_type = base_type(proc_type);
  138. GB_ASSERT(is_type_proc(proc_type));
  139. TypeProc *pt = &proc_type->Proc;
  140. isize arg_count = 3;
  141. isize param_count = 0;
  142. if (pt->params) {
  143. GB_ASSERT(pt->params->kind == Type_Tuple);
  144. param_count = pt->params->Tuple.variables.count;
  145. }
  146. auto args = array_make<lbValue>(heap_allocator(), gb_max(arg_count, param_count));
  147. args[0] = ptr;
  148. args[1] = index;
  149. args[2] = value;
  150. isize arg_index = arg_count;
  151. if (arg_count < param_count) {
  152. lbModule *m = p->module;
  153. String proc_name = {};
  154. if (p->entity != nullptr) {
  155. proc_name = p->entity->token.string;
  156. }
  157. TokenPos pos = ast_token(ce->proc).pos;
  158. TypeTuple *param_tuple = &pt->params->Tuple;
  159. isize end = cast(isize)param_count;
  160. while (arg_index < end) {
  161. Entity *e = param_tuple->variables[arg_index];
  162. GB_ASSERT(e->kind == Entity_Variable);
  163. switch (e->Variable.param_value.kind) {
  164. case ParameterValue_Constant:
  165. args[arg_index++] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  166. break;
  167. case ParameterValue_Nil:
  168. args[arg_index++] = lb_const_nil(m, e->type);
  169. break;
  170. case ParameterValue_Location:
  171. args[arg_index++] = lb_emit_source_code_location(p, proc_name, pos);
  172. break;
  173. case ParameterValue_Value:
  174. args[arg_index++] = lb_build_expr(p, e->Variable.param_value.ast_value);
  175. break;
  176. }
  177. }
  178. }
  179. Entity *e = entity_from_expr(ce->proc);
  180. GB_ASSERT(e != nullptr);
  181. GB_ASSERT(is_type_polymorphic(e->type));
  182. {
  183. lbValue *found = nullptr;
  184. if (p->module != e->code_gen_module) {
  185. gb_mutex_lock(&p->module->mutex);
  186. }
  187. found = map_get(&e->code_gen_module->values, hash_entity(e));
  188. if (p->module != e->code_gen_module) {
  189. gb_mutex_unlock(&p->module->mutex);
  190. }
  191. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  192. lb_emit_call(p, *found, args);
  193. }
  194. return;
  195. } else if (addr.kind == lbAddr_Map) {
  196. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value);
  197. return;
  198. } else if (addr.kind == lbAddr_BitField) {
  199. Type *bft = base_type(type_deref(addr.addr.type));
  200. GB_ASSERT(is_type_bit_field(bft));
  201. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  202. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  203. if (size_in_bits == 0) {
  204. return;
  205. }
  206. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  207. LLVMTypeRef dst_type = LLVMIntTypeInContext(p->module->ctx, size_in_bits);
  208. LLVMValueRef src = LLVMBuildIntCast2(p->builder, value.value, dst_type, false, "");
  209. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  210. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  211. LLVMBuildStore(p->builder, src, field_ptr);
  212. return;
  213. } else if (addr.kind == lbAddr_Context) {
  214. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  215. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  216. lb_addr_store(p, next_addr, old);
  217. lb_push_context_onto_stack(p, next_addr);
  218. lbValue next = lb_addr_get_ptr(p, next_addr);
  219. if (addr.ctx.sel.index.count > 0) {
  220. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  221. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  222. lb_emit_store(p, lhs, rhs);
  223. } else {
  224. lbValue lhs = next;
  225. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  226. lb_emit_store(p, lhs, rhs);
  227. }
  228. return;
  229. } else if (addr.kind == lbAddr_SoaVariable) {
  230. Type *t = type_deref(addr.addr.type);
  231. t = base_type(t);
  232. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  233. value = lb_emit_conv(p, value, t->Struct.soa_elem);
  234. lbValue index = addr.soa.index;
  235. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  236. Type *t = base_type(type_deref(addr.addr.type));
  237. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  238. i64 count = t->Struct.soa_count;
  239. lbValue len = lb_const_int(p->module, t_int, count);
  240. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  241. }
  242. for_array(i, t->Struct.fields) {
  243. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  244. dst = lb_emit_array_ep(p, dst, index);
  245. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  246. lb_emit_store(p, dst, src);
  247. }
  248. return;
  249. }
  250. GB_ASSERT(value.value != nullptr);
  251. value = lb_emit_conv(p, value, lb_addr_type(addr));
  252. LLVMBuildStore(p->builder, value.value, addr.addr.value);
  253. }
  254. void lb_const_store(lbValue ptr, lbValue value) {
  255. GB_ASSERT(lb_is_const(ptr));
  256. GB_ASSERT(lb_is_const(value));
  257. GB_ASSERT(is_type_pointer(ptr.type));
  258. LLVMSetInitializer(ptr.value, value.value);
  259. }
  260. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  261. GB_ASSERT(value.value != nullptr);
  262. Type *a = type_deref(ptr.type);
  263. if (is_type_boolean(a)) {
  264. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  265. value = lb_emit_conv(p, value, a);
  266. }
  267. Type *ca = core_type(a);
  268. if (ca->kind == Type_Basic) {
  269. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  270. } else {
  271. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  272. }
  273. LLVMBuildStore(p->builder, value.value, ptr.value);
  274. }
  275. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  276. lbModule *m = p->module;
  277. GB_ASSERT(value.value != nullptr);
  278. Type *t = type_deref(value.type);
  279. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  280. return lbValue{v, t};
  281. }
  282. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  283. GB_ASSERT(addr.addr.value != nullptr);
  284. if (addr.kind == lbAddr_Map) {
  285. Type *map_type = base_type(addr.map.type);
  286. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  287. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  288. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  289. auto args = array_make<lbValue>(heap_allocator(), 2);
  290. args[0] = h;
  291. args[1] = key;
  292. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  293. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  294. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  295. lbBlock *then = lb_create_block(p, "map.get.then");
  296. lbBlock *done = lb_create_block(p, "map.get.done");
  297. lb_emit_if(p, ok, then, done);
  298. lb_start_block(p, then);
  299. {
  300. // TODO(bill): mem copy it instead?
  301. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  302. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  303. lb_emit_store(p, gep0, lb_emit_load(p, value));
  304. }
  305. lb_emit_jump(p, done);
  306. lb_start_block(p, done);
  307. if (is_type_tuple(addr.map.result)) {
  308. return lb_addr_load(p, v);
  309. } else {
  310. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  311. return lb_emit_load(p, single);
  312. }
  313. } else if (addr.kind == lbAddr_BitField) {
  314. Type *bft = base_type(type_deref(addr.addr.type));
  315. GB_ASSERT(is_type_bit_field(bft));
  316. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  317. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  318. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  319. if (size_in_bytes == 0) {
  320. GB_ASSERT(size_in_bits == 0);
  321. lbValue res = {};
  322. res.type = t_i32;
  323. res.value = LLVMConstInt(lb_type(p->module, res.type), 0, false);
  324. return res;
  325. }
  326. Type *int_type = nullptr;
  327. switch (size_in_bytes) {
  328. case 1: int_type = t_u8; break;
  329. case 2: int_type = t_u16; break;
  330. case 4: int_type = t_u32; break;
  331. case 8: int_type = t_u64; break;
  332. case 16: int_type = t_u128; break;
  333. }
  334. GB_ASSERT(int_type != nullptr);
  335. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  336. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  337. LLVMValueRef field = LLVMBuildLoad(p->builder, field_ptr, "");
  338. lbValue res = {};
  339. res.type = int_type;
  340. res.value = LLVMBuildZExtOrBitCast(p->builder, field, lb_type(p->module, int_type), "");
  341. return res;
  342. } else if (addr.kind == lbAddr_Context) {
  343. if (addr.ctx.sel.index.count > 0) {
  344. lbValue a = addr.addr;
  345. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  346. return lb_emit_load(p, b);
  347. } else {
  348. return lb_emit_load(p, addr.addr);
  349. }
  350. } else if (addr.kind == lbAddr_SoaVariable) {
  351. Type *t = type_deref(addr.addr.type);
  352. t = base_type(t);
  353. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  354. Type *elem = t->Struct.soa_elem;
  355. lbValue len = {};
  356. if (t->Struct.soa_kind == StructSoa_Fixed) {
  357. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  358. } else {
  359. lbValue v = lb_emit_load(p, addr.addr);
  360. len = lb_soa_struct_len(p, v);
  361. }
  362. lbAddr res = lb_add_local_generated(p, elem, true);
  363. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  364. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  365. }
  366. if (t->Struct.soa_kind == StructSoa_Fixed) {
  367. for_array(i, t->Struct.fields) {
  368. Entity *field = t->Struct.fields[i];
  369. Type *base_type = field->type;
  370. GB_ASSERT(base_type->kind == Type_Array);
  371. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  372. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  373. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  374. lbValue src = lb_emit_load(p, src_ptr);
  375. lb_emit_store(p, dst, src);
  376. }
  377. } else {
  378. isize field_count = t->Struct.fields.count;
  379. if (t->Struct.soa_kind == StructSoa_Slice) {
  380. field_count -= 1;
  381. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  382. field_count -= 3;
  383. }
  384. for (isize i = 0; i < field_count; i++) {
  385. Entity *field = t->Struct.fields[i];
  386. Type *base_type = field->type;
  387. GB_ASSERT(base_type->kind == Type_Pointer);
  388. Type *elem = base_type->Pointer.elem;
  389. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  390. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  391. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  392. lbValue src = lb_emit_load(p, src_ptr);
  393. src = lb_emit_load(p, src);
  394. lb_emit_store(p, dst, src);
  395. }
  396. }
  397. return lb_addr_load(p, res);
  398. }
  399. if (is_type_proc(addr.addr.type)) {
  400. return addr.addr;
  401. }
  402. return lb_emit_load(p, addr.addr);
  403. }
  404. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  405. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  406. }
  407. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  408. Type *t = u.type;
  409. GB_ASSERT_MSG(is_type_pointer(t) &&
  410. is_type_union(type_deref(t)), "%s", type_to_string(t));
  411. Type *ut = type_deref(t);
  412. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  413. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  414. GB_ASSERT(type_size_of(ut) > 0);
  415. Type *tag_type = union_tag_type(ut);
  416. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  417. unsigned element_count = LLVMCountStructElementTypes(uvt);
  418. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  419. lbValue tag_ptr = {};
  420. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  421. tag_ptr.type = alloc_type_pointer(tag_type);
  422. return tag_ptr;
  423. }
  424. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  425. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  426. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  427. return lb_emit_load(p, tag_ptr);
  428. }
  429. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  430. Type *t = type_deref(parent.type);
  431. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  432. // No tag needed!
  433. } else {
  434. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  435. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  436. }
  437. }
  438. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  439. gbAllocator a = heap_allocator();
  440. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  441. lb_emit_store(p, underlying, variant);
  442. lb_emit_store_union_variant_tag(p, parent, variant_type);
  443. }
  444. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  445. unsigned field_count = LLVMCountStructElementTypes(src);
  446. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  447. LLVMGetStructElementTypes(src, fields);
  448. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  449. gb_free(heap_allocator(), fields);
  450. }
  451. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  452. switch (alignment) {
  453. case 1:
  454. return LLVMArrayType(lb_type(m, t_u8), 0);
  455. case 2:
  456. return LLVMArrayType(lb_type(m, t_u16), 0);
  457. case 4:
  458. return LLVMArrayType(lb_type(m, t_u32), 0);
  459. case 8:
  460. return LLVMArrayType(lb_type(m, t_u64), 0);
  461. case 16:
  462. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  463. default:
  464. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  465. break;
  466. }
  467. return nullptr;
  468. }
  469. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  470. if (!elem_type_can_be_constant(elem_type)) {
  471. return false;
  472. }
  473. if (elem->kind == Ast_FieldValue) {
  474. elem = elem->FieldValue.value;
  475. }
  476. TypeAndValue tav = type_and_value_of_expr(elem);
  477. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  478. return tav.value.kind != ExactValue_Invalid;
  479. }
  480. String lb_mangle_name(lbModule *m, Entity *e) {
  481. gbAllocator a = heap_allocator();
  482. String name = e->token.string;
  483. AstPackage *pkg = e->pkg;
  484. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  485. String pkgn = pkg->name;
  486. GB_ASSERT(!rune_is_digit(pkgn[0]));
  487. isize max_len = pkgn.len + 1 + name.len + 1;
  488. bool require_suffix_id = is_type_polymorphic(e->type, true);
  489. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  490. require_suffix_id = true;
  491. } else if (is_blank_ident(e->token)) {
  492. require_suffix_id = true;
  493. }if (e->flags & EntityFlag_NotExported) {
  494. require_suffix_id = true;
  495. }
  496. if (require_suffix_id) {
  497. max_len += 21;
  498. }
  499. char *new_name = gb_alloc_array(a, char, max_len);
  500. isize new_name_len = gb_snprintf(
  501. new_name, max_len,
  502. "%.*s.%.*s", LIT(pkgn), LIT(name)
  503. );
  504. if (require_suffix_id) {
  505. char *str = new_name + new_name_len-1;
  506. isize len = max_len-new_name_len;
  507. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  508. new_name_len += extra-1;
  509. }
  510. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  511. return mangled_name;
  512. }
  513. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  514. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  515. // and as a result, the declaration does not have time to determine what it should be
  516. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  517. if (e->TypeName.ir_mangled_name.len != 0) {
  518. return e->TypeName.ir_mangled_name;
  519. }
  520. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  521. if (p == nullptr) {
  522. Entity *proc = nullptr;
  523. if (e->parent_proc_decl != nullptr) {
  524. proc = e->parent_proc_decl->entity;
  525. } else {
  526. Scope *scope = e->scope;
  527. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  528. scope = scope->parent;
  529. }
  530. GB_ASSERT(scope != nullptr);
  531. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  532. proc = scope->procedure_entity;
  533. }
  534. GB_ASSERT(proc->kind == Entity_Procedure);
  535. if (proc->code_gen_procedure != nullptr) {
  536. p = proc->code_gen_procedure;
  537. }
  538. }
  539. // NOTE(bill): Generate a new name
  540. // parent_proc.name-guid
  541. String ts_name = e->token.string;
  542. if (p != nullptr) {
  543. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  544. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  545. u32 guid = ++p->module->nested_type_name_guid;
  546. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  547. String name = make_string(cast(u8 *)name_text, name_len-1);
  548. e->TypeName.ir_mangled_name = name;
  549. return name;
  550. } else {
  551. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  552. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  553. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  554. static u32 guid = 0;
  555. guid += 1;
  556. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  557. String name = make_string(cast(u8 *)name_text, name_len-1);
  558. e->TypeName.ir_mangled_name = name;
  559. return name;
  560. }
  561. }
  562. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  563. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  564. return e->TypeName.ir_mangled_name;
  565. }
  566. GB_ASSERT(e != nullptr);
  567. if (e->pkg == nullptr) {
  568. return e->token.string;
  569. }
  570. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  571. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  572. }
  573. String name = {};
  574. bool no_name_mangle = false;
  575. if (e->kind == Entity_Variable) {
  576. bool is_foreign = e->Variable.is_foreign;
  577. bool is_export = e->Variable.is_export;
  578. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  579. if (e->Variable.link_name.len > 0) {
  580. return e->Variable.link_name;
  581. }
  582. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  583. return e->Procedure.link_name;
  584. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  585. no_name_mangle = true;
  586. }
  587. if (!no_name_mangle) {
  588. name = lb_mangle_name(m, e);
  589. }
  590. if (name.len == 0) {
  591. name = e->token.string;
  592. }
  593. if (e->kind == Entity_TypeName) {
  594. if ((e->scope->flags & ScopeFlag_File) == 0) {
  595. gb_printf_err("<<< %.*s %.*s %p\n", LIT(e->token.string), LIT(name), e);
  596. }
  597. e->TypeName.ir_mangled_name = name;
  598. } else if (e->kind == Entity_Procedure) {
  599. e->Procedure.link_name = name;
  600. }
  601. return name;
  602. }
  603. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  604. Type *original_type = type;
  605. LLVMContextRef ctx = m->ctx;
  606. i64 size = type_size_of(type); // Check size
  607. GB_ASSERT(type != t_invalid);
  608. switch (type->kind) {
  609. case Type_Basic:
  610. switch (type->Basic.kind) {
  611. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  612. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  613. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  614. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  615. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  616. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  617. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  618. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  619. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  620. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  621. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  622. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  623. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  624. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  625. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  626. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  627. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  628. // Basic_f16,
  629. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  630. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  631. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  632. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  633. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  634. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  635. // Basic_complex32,
  636. case Basic_complex64:
  637. {
  638. char const *name = "..complex64";
  639. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  640. if (type != nullptr) {
  641. return type;
  642. }
  643. type = LLVMStructCreateNamed(ctx, name);
  644. LLVMTypeRef fields[2] = {
  645. lb_type(m, t_f32),
  646. lb_type(m, t_f32),
  647. };
  648. LLVMStructSetBody(type, fields, 2, false);
  649. return type;
  650. }
  651. case Basic_complex128:
  652. {
  653. char const *name = "..complex128";
  654. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  655. if (type != nullptr) {
  656. return type;
  657. }
  658. type = LLVMStructCreateNamed(ctx, name);
  659. LLVMTypeRef fields[2] = {
  660. lb_type(m, t_f64),
  661. lb_type(m, t_f64),
  662. };
  663. LLVMStructSetBody(type, fields, 2, false);
  664. return type;
  665. }
  666. case Basic_quaternion128:
  667. {
  668. char const *name = "..quaternion128";
  669. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  670. if (type != nullptr) {
  671. return type;
  672. }
  673. type = LLVMStructCreateNamed(ctx, name);
  674. LLVMTypeRef fields[4] = {
  675. lb_type(m, t_f32),
  676. lb_type(m, t_f32),
  677. lb_type(m, t_f32),
  678. lb_type(m, t_f32),
  679. };
  680. LLVMStructSetBody(type, fields, 4, false);
  681. return type;
  682. }
  683. case Basic_quaternion256:
  684. {
  685. char const *name = "..quaternion256";
  686. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  687. if (type != nullptr) {
  688. return type;
  689. }
  690. type = LLVMStructCreateNamed(ctx, name);
  691. LLVMTypeRef fields[4] = {
  692. lb_type(m, t_f64),
  693. lb_type(m, t_f64),
  694. lb_type(m, t_f64),
  695. lb_type(m, t_f64),
  696. };
  697. LLVMStructSetBody(type, fields, 4, false);
  698. return type;
  699. }
  700. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  701. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  702. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  703. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  704. case Basic_string:
  705. {
  706. char const *name = "..string";
  707. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  708. if (type != nullptr) {
  709. return type;
  710. }
  711. type = LLVMStructCreateNamed(ctx, name);
  712. LLVMTypeRef fields[2] = {
  713. LLVMPointerType(lb_type(m, t_u8), 0),
  714. lb_type(m, t_int),
  715. };
  716. LLVMStructSetBody(type, fields, 2, false);
  717. return type;
  718. }
  719. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  720. case Basic_any:
  721. {
  722. char const *name = "..any";
  723. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  724. if (type != nullptr) {
  725. return type;
  726. }
  727. type = LLVMStructCreateNamed(ctx, name);
  728. LLVMTypeRef fields[2] = {
  729. lb_type(m, t_rawptr),
  730. lb_type(m, t_typeid),
  731. };
  732. LLVMStructSetBody(type, fields, 2, false);
  733. return type;
  734. }
  735. case Basic_typeid: return LLVMIntType(8*cast(unsigned)build_context.word_size);
  736. // Endian Specific Types
  737. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  738. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  739. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  740. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  741. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  742. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  743. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  744. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  745. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  746. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  747. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  748. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  749. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  750. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  751. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  752. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  753. // Untyped types
  754. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  755. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  756. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  757. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  758. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  759. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  760. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  761. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  762. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  763. }
  764. break;
  765. case Type_Named:
  766. {
  767. Type *base = base_type(type->Named.base);
  768. switch (base->kind) {
  769. case Type_Basic:
  770. return lb_type(m, base);
  771. case Type_Named:
  772. case Type_Generic:
  773. case Type_BitFieldValue:
  774. GB_PANIC("INVALID TYPE");
  775. break;
  776. case Type_Opaque:
  777. return lb_type(m, base->Opaque.elem);
  778. case Type_Pointer:
  779. case Type_Array:
  780. case Type_EnumeratedArray:
  781. case Type_Slice:
  782. case Type_DynamicArray:
  783. case Type_Map:
  784. case Type_Enum:
  785. case Type_BitSet:
  786. case Type_SimdVector:
  787. return lb_type(m, base);
  788. // TODO(bill): Deal with this correctly. Can this be named?
  789. case Type_Proc:
  790. return lb_type(m, base);
  791. case Type_Tuple:
  792. return lb_type(m, base);
  793. }
  794. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  795. if (found) {
  796. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  797. if (kind == LLVMStructTypeKind) {
  798. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  799. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  800. if (llvm_type != nullptr) {
  801. return llvm_type;
  802. }
  803. llvm_type = LLVMStructCreateNamed(ctx, name);
  804. map_set(&m->types, hash_type(type), llvm_type);
  805. lb_clone_struct_type(llvm_type, *found);
  806. return llvm_type;
  807. }
  808. }
  809. switch (base->kind) {
  810. case Type_Struct:
  811. case Type_Union:
  812. case Type_BitField:
  813. {
  814. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  815. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  816. if (llvm_type != nullptr) {
  817. return llvm_type;
  818. }
  819. llvm_type = LLVMStructCreateNamed(ctx, name);
  820. map_set(&m->types, hash_type(type), llvm_type);
  821. lb_clone_struct_type(llvm_type, lb_type(m, base));
  822. return llvm_type;
  823. }
  824. }
  825. return lb_type(m, base);
  826. }
  827. case Type_Pointer:
  828. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  829. case Type_Opaque:
  830. return lb_type(m, base_type(type));
  831. case Type_Array:
  832. return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  833. case Type_EnumeratedArray:
  834. return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  835. case Type_Slice:
  836. {
  837. LLVMTypeRef fields[2] = {
  838. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  839. lb_type(m, t_int), // len
  840. };
  841. return LLVMStructTypeInContext(ctx, fields, 2, false);
  842. }
  843. break;
  844. case Type_DynamicArray:
  845. {
  846. LLVMTypeRef fields[4] = {
  847. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  848. lb_type(m, t_int), // len
  849. lb_type(m, t_int), // cap
  850. lb_type(m, t_allocator), // allocator
  851. };
  852. return LLVMStructTypeInContext(ctx, fields, 4, false);
  853. }
  854. break;
  855. case Type_Map:
  856. return lb_type(m, type->Map.internal_type);
  857. case Type_Struct:
  858. {
  859. if (type->Struct.is_raw_union) {
  860. unsigned field_count = 2;
  861. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  862. i64 alignment = type_align_of(type);
  863. unsigned size_of_union = cast(unsigned)type_size_of(type);
  864. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  865. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  866. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  867. }
  868. isize offset = 0;
  869. if (type->Struct.custom_align > 0) {
  870. offset = 1;
  871. }
  872. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  873. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  874. GB_ASSERT(fields != nullptr);
  875. defer (gb_free(heap_allocator(), fields));
  876. for_array(i, type->Struct.fields) {
  877. Entity *field = type->Struct.fields[i];
  878. fields[i+offset] = lb_type(m, field->type);
  879. }
  880. if (type->Struct.custom_align > 0) {
  881. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  882. }
  883. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  884. }
  885. break;
  886. case Type_Union:
  887. if (type->Union.variants.count == 0) {
  888. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  889. } else {
  890. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  891. // LLVM takes the first element's alignment as the entire alignment (like C)
  892. i64 align = type_align_of(type);
  893. i64 size = type_size_of(type);
  894. if (is_type_union_maybe_pointer_original_alignment(type)) {
  895. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  896. return LLVMStructTypeInContext(ctx, fields, 1, false);
  897. }
  898. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  899. LLVMTypeRef fields[3] = {};
  900. unsigned field_count = 1;
  901. fields[0] = lb_alignment_prefix_type_hack(m, align);
  902. if (is_type_union_maybe_pointer(type)) {
  903. field_count += 1;
  904. fields[1] = lb_type(m, type->Union.variants[0]);
  905. } else {
  906. field_count += 2;
  907. if (block_size == align) {
  908. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  909. } else {
  910. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  911. }
  912. fields[2] = lb_type(m, union_tag_type(type));
  913. }
  914. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  915. }
  916. break;
  917. case Type_Enum:
  918. return lb_type(m, base_enum_type(type));
  919. case Type_Tuple:
  920. if (type->Tuple.variables.count == 1) {
  921. return lb_type(m, type->Tuple.variables[0]->type);
  922. } else {
  923. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  924. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  925. defer (gb_free(heap_allocator(), fields));
  926. for_array(i, type->Tuple.variables) {
  927. Entity *field = type->Tuple.variables[i];
  928. fields[i] = lb_type(m, field->type);
  929. }
  930. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  931. }
  932. case Type_Proc:
  933. {
  934. set_procedure_abi_types(heap_allocator(), type);
  935. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  936. isize offset = 0;
  937. if (type->Proc.return_by_pointer) {
  938. offset = 1;
  939. } else if (type->Proc.abi_compat_result_type != nullptr) {
  940. return_type = lb_type(m, type->Proc.abi_compat_result_type);
  941. }
  942. isize extra_param_count = offset;
  943. if (type->Proc.calling_convention == ProcCC_Odin) {
  944. extra_param_count += 1;
  945. }
  946. isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  947. LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  948. defer (gb_free(heap_allocator(), param_types));
  949. isize param_index = offset;
  950. for_array(i, type->Proc.abi_compat_params) {
  951. Type *param = type->Proc.abi_compat_params[i];
  952. if (param == nullptr) {
  953. continue;
  954. }
  955. param_types[param_index++] = lb_type(m, param);
  956. }
  957. if (type->Proc.return_by_pointer) {
  958. param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  959. }
  960. if (type->Proc.calling_convention == ProcCC_Odin) {
  961. param_types[param_index++] = lb_type(m, t_context_ptr);
  962. }
  963. LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  964. return LLVMPointerType(t, 0);
  965. }
  966. break;
  967. case Type_BitFieldValue:
  968. return LLVMIntType(type->BitFieldValue.bits);
  969. case Type_BitField:
  970. {
  971. LLVMTypeRef internal_type = nullptr;
  972. {
  973. GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  974. unsigned field_count = cast(unsigned)type->BitField.fields.count;
  975. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  976. defer (gb_free(heap_allocator(), fields));
  977. for_array(i, type->BitField.sizes) {
  978. u32 size = type->BitField.sizes[i];
  979. fields[i] = LLVMIntType(size);
  980. }
  981. internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  982. }
  983. unsigned field_count = 2;
  984. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  985. i64 alignment = 1;
  986. if (type->BitField.custom_align > 0) {
  987. alignment = type->BitField.custom_align;
  988. }
  989. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  990. fields[1] = internal_type;
  991. return LLVMStructTypeInContext(ctx, fields, field_count, true);
  992. }
  993. break;
  994. case Type_BitSet:
  995. return LLVMIntType(8*cast(unsigned)type_size_of(type));
  996. case Type_SimdVector:
  997. if (type->SimdVector.is_x86_mmx) {
  998. return LLVMX86MMXTypeInContext(ctx);
  999. }
  1000. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1001. }
  1002. GB_PANIC("Invalid type %s", type_to_string(type));
  1003. return LLVMInt32TypeInContext(ctx);
  1004. }
  1005. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1006. type = default_type(type);
  1007. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1008. if (found) {
  1009. return *found;
  1010. }
  1011. LLVMTypeRef llvm_type = lb_type_internal(m, type);
  1012. map_set(&m->types, hash_type(type), llvm_type);
  1013. return llvm_type;
  1014. }
  1015. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1016. Type *original_type = type;
  1017. LLVMContextRef ctx = m->ctx;
  1018. i64 size = type_size_of(type); // Check size
  1019. GB_ASSERT(type != t_invalid);
  1020. switch (type->kind) {
  1021. case Type_Basic:
  1022. switch (type->Basic.kind) {
  1023. case Basic_llvm_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "llvm bool", 9, 1, 0, LLVMDIFlagZero);
  1024. case Basic_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "bool", 4, 8, 0, LLVMDIFlagZero);
  1025. case Basic_b8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b8", 2, 8, 0, LLVMDIFlagZero);
  1026. case Basic_b16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b16", 3, 16, 0, LLVMDIFlagZero);
  1027. case Basic_b32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b32", 3, 32, 0, LLVMDIFlagZero);
  1028. case Basic_b64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b64", 3, 64, 0, LLVMDIFlagZero);
  1029. case Basic_i8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i8", 2, 8, 0, LLVMDIFlagZero);
  1030. case Basic_u8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u8", 2, 8, 0, LLVMDIFlagZero);
  1031. case Basic_i16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16", 3, 16, 0, LLVMDIFlagZero);
  1032. case Basic_u16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16", 3, 16, 0, LLVMDIFlagZero);
  1033. case Basic_i32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32", 3, 32, 0, LLVMDIFlagZero);
  1034. case Basic_u32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32", 3, 32, 0, LLVMDIFlagZero);
  1035. case Basic_i64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64", 3, 64, 0, LLVMDIFlagZero);
  1036. case Basic_u64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64", 3, 64, 0, LLVMDIFlagZero);
  1037. case Basic_i128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128", 4, 128, 0, LLVMDIFlagZero);
  1038. case Basic_u128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128", 4, 128, 0, LLVMDIFlagZero);
  1039. case Basic_rune: return LLVMDIBuilderCreateBasicType(m->debug_builder, "rune", 4, 32, 0, LLVMDIFlagZero);
  1040. // Basic_f16,
  1041. case Basic_f32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32", 3, 32, 0, LLVMDIFlagZero);
  1042. case Basic_f64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64", 3, 64, 0, LLVMDIFlagZero);
  1043. // Basic_complex32,
  1044. case Basic_complex64:
  1045. {
  1046. return nullptr;
  1047. // char const *name = "..complex64";
  1048. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1049. // if (type != nullptr) {
  1050. // return type;
  1051. // }
  1052. // type = LLVMStructCreateNamed(ctx, name);
  1053. // LLVMTypeRef fields[2] = {
  1054. // lb_type(m, t_f32),
  1055. // lb_type(m, t_f32),
  1056. // };
  1057. // LLVMStructSetBody(type, fields, 2, false);
  1058. // return type;
  1059. }
  1060. case Basic_complex128:
  1061. {
  1062. return nullptr;
  1063. // char const *name = "..complex128";
  1064. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1065. // if (type != nullptr) {
  1066. // return type;
  1067. // }
  1068. // type = LLVMStructCreateNamed(ctx, name);
  1069. // LLVMTypeRef fields[2] = {
  1070. // lb_type(m, t_f64),
  1071. // lb_type(m, t_f64),
  1072. // };
  1073. // LLVMStructSetBody(type, fields, 2, false);
  1074. // return type;
  1075. }
  1076. case Basic_quaternion128:
  1077. {
  1078. return nullptr;
  1079. // char const *name = "..quaternion128";
  1080. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1081. // if (type != nullptr) {
  1082. // return type;
  1083. // }
  1084. // type = LLVMStructCreateNamed(ctx, name);
  1085. // LLVMTypeRef fields[4] = {
  1086. // lb_type(m, t_f32),
  1087. // lb_type(m, t_f32),
  1088. // lb_type(m, t_f32),
  1089. // lb_type(m, t_f32),
  1090. // };
  1091. // LLVMStructSetBody(type, fields, 4, false);
  1092. // return type;
  1093. }
  1094. case Basic_quaternion256:
  1095. {
  1096. return nullptr;
  1097. // char const *name = "..quaternion256";
  1098. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1099. // if (type != nullptr) {
  1100. // return type;
  1101. // }
  1102. // type = LLVMStructCreateNamed(ctx, name);
  1103. // LLVMTypeRef fields[4] = {
  1104. // lb_type(m, t_f64),
  1105. // lb_type(m, t_f64),
  1106. // lb_type(m, t_f64),
  1107. // lb_type(m, t_f64),
  1108. // };
  1109. // LLVMStructSetBody(type, fields, 4, false);
  1110. // return type;
  1111. }
  1112. case Basic_int: return LLVMDIBuilderCreateBasicType(m->debug_builder, "int", 3, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1113. case Basic_uint: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uint", 4, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1114. case Basic_uintptr: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uintptr", 7, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1115. case Basic_rawptr:
  1116. return nullptr;
  1117. // return LLVMPointerType(LLVMInt8Type(), 0);
  1118. case Basic_string:
  1119. {
  1120. return nullptr;
  1121. // char const *name = "..string";
  1122. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1123. // if (type != nullptr) {
  1124. // return type;
  1125. // }
  1126. // type = LLVMStructCreateNamed(ctx, name);
  1127. // LLVMTypeRef fields[2] = {
  1128. // LLVMPointerType(lb_type(m, t_u8), 0),
  1129. // lb_type(m, t_int),
  1130. // };
  1131. // LLVMStructSetBody(type, fields, 2, false);
  1132. // return type;
  1133. }
  1134. case Basic_cstring:
  1135. return nullptr;
  1136. // return LLVMPointerType(LLVMInt8Type(), 0);
  1137. case Basic_any:
  1138. {
  1139. return nullptr;
  1140. // char const *name = "..any";
  1141. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1142. // if (type != nullptr) {
  1143. // return type;
  1144. // }
  1145. // type = LLVMStructCreateNamed(ctx, name);
  1146. // LLVMTypeRef fields[2] = {
  1147. // lb_type(m, t_rawptr),
  1148. // lb_type(m, t_typeid),
  1149. // };
  1150. // LLVMStructSetBody(type, fields, 2, false);
  1151. // return type;
  1152. }
  1153. case Basic_typeid: return LLVMDIBuilderCreateBasicType(m->debug_builder, "typeid", 6, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1154. // Endian Specific Types
  1155. case Basic_i16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1156. case Basic_u16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1157. case Basic_i32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1158. case Basic_u32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1159. case Basic_i64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1160. case Basic_u64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1161. case Basic_i128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1162. case Basic_u128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1163. case Basic_i16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1164. case Basic_u16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1165. case Basic_i32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1166. case Basic_u32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1167. case Basic_i64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1168. case Basic_u64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1169. case Basic_i128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1170. case Basic_u128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1171. // Untyped types
  1172. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1173. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1174. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1175. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1176. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1177. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1178. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1179. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1180. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1181. }
  1182. break;
  1183. case Type_Named:
  1184. {
  1185. return nullptr;
  1186. // Type *base = base_type(type->Named.base);
  1187. // switch (base->kind) {
  1188. // case Type_Basic:
  1189. // return lb_type(m, base);
  1190. // case Type_Named:
  1191. // case Type_Generic:
  1192. // case Type_BitFieldValue:
  1193. // GB_PANIC("INVALID TYPE");
  1194. // break;
  1195. // case Type_Opaque:
  1196. // return lb_type(m, base->Opaque.elem);
  1197. // case Type_Pointer:
  1198. // case Type_Array:
  1199. // case Type_EnumeratedArray:
  1200. // case Type_Slice:
  1201. // case Type_DynamicArray:
  1202. // case Type_Map:
  1203. // case Type_Enum:
  1204. // case Type_BitSet:
  1205. // case Type_SimdVector:
  1206. // return lb_type(m, base);
  1207. // // TODO(bill): Deal with this correctly. Can this be named?
  1208. // case Type_Proc:
  1209. // return lb_type(m, base);
  1210. // case Type_Tuple:
  1211. // return lb_type(m, base);
  1212. // }
  1213. // LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1214. // if (found) {
  1215. // LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1216. // if (kind == LLVMStructTypeKind) {
  1217. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1218. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1219. // if (llvm_type != nullptr) {
  1220. // return llvm_type;
  1221. // }
  1222. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1223. // map_set(&m->types, hash_type(type), llvm_type);
  1224. // lb_clone_struct_type(llvm_type, *found);
  1225. // return llvm_type;
  1226. // }
  1227. // }
  1228. // switch (base->kind) {
  1229. // case Type_Struct:
  1230. // case Type_Union:
  1231. // case Type_BitField:
  1232. // {
  1233. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1234. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1235. // if (llvm_type != nullptr) {
  1236. // return llvm_type;
  1237. // }
  1238. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1239. // map_set(&m->types, hash_type(type), llvm_type);
  1240. // lb_clone_struct_type(llvm_type, lb_type(m, base));
  1241. // return llvm_type;
  1242. // }
  1243. // }
  1244. // return lb_type(m, base);
  1245. }
  1246. case Type_Pointer:
  1247. return nullptr;
  1248. // return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1249. case Type_Opaque:
  1250. return nullptr;
  1251. // return lb_type(m, base_type(type));
  1252. case Type_Array:
  1253. return nullptr;
  1254. // return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1255. case Type_EnumeratedArray:
  1256. return nullptr;
  1257. // return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1258. case Type_Slice:
  1259. {
  1260. return nullptr;
  1261. // LLVMTypeRef fields[2] = {
  1262. // LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1263. // lb_type(m, t_int), // len
  1264. // };
  1265. // return LLVMStructTypeInContext(ctx, fields, 2, false);
  1266. }
  1267. break;
  1268. case Type_DynamicArray:
  1269. {
  1270. return nullptr;
  1271. // LLVMTypeRef fields[4] = {
  1272. // LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1273. // lb_type(m, t_int), // len
  1274. // lb_type(m, t_int), // cap
  1275. // lb_type(m, t_allocator), // allocator
  1276. // };
  1277. // return LLVMStructTypeInContext(ctx, fields, 4, false);
  1278. }
  1279. break;
  1280. case Type_Map:
  1281. return nullptr;
  1282. // return lb_type(m, type->Map.internal_type);
  1283. case Type_Struct:
  1284. {
  1285. return nullptr;
  1286. // if (type->Struct.is_raw_union) {
  1287. // unsigned field_count = 2;
  1288. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1289. // i64 alignment = type_align_of(type);
  1290. // unsigned size_of_union = cast(unsigned)type_size_of(type);
  1291. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1292. // fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1293. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1294. // }
  1295. // isize offset = 0;
  1296. // if (type->Struct.custom_align > 0) {
  1297. // offset = 1;
  1298. // }
  1299. // unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1300. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1301. // GB_ASSERT(fields != nullptr);
  1302. // defer (gb_free(heap_allocator(), fields));
  1303. // for_array(i, type->Struct.fields) {
  1304. // Entity *field = type->Struct.fields[i];
  1305. // fields[i+offset] = lb_type(m, field->type);
  1306. // }
  1307. // if (type->Struct.custom_align > 0) {
  1308. // fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1309. // }
  1310. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1311. }
  1312. break;
  1313. case Type_Union:
  1314. return nullptr;
  1315. // if (type->Union.variants.count == 0) {
  1316. // return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1317. // } else {
  1318. // // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1319. // // LLVM takes the first element's alignment as the entire alignment (like C)
  1320. // i64 align = type_align_of(type);
  1321. // i64 size = type_size_of(type);
  1322. // if (is_type_union_maybe_pointer_original_alignment(type)) {
  1323. // LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1324. // return LLVMStructTypeInContext(ctx, fields, 1, false);
  1325. // }
  1326. // unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1327. // LLVMTypeRef fields[3] = {};
  1328. // unsigned field_count = 1;
  1329. // fields[0] = lb_alignment_prefix_type_hack(m, align);
  1330. // if (is_type_union_maybe_pointer(type)) {
  1331. // field_count += 1;
  1332. // fields[1] = lb_type(m, type->Union.variants[0]);
  1333. // } else {
  1334. // field_count += 2;
  1335. // if (block_size == align) {
  1336. // fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1337. // } else {
  1338. // fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1339. // }
  1340. // fields[2] = lb_type(m, union_tag_type(type));
  1341. // }
  1342. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1343. // }
  1344. // break;
  1345. case Type_Enum:
  1346. return nullptr;
  1347. // return lb_type(m, base_enum_type(type));
  1348. case Type_Tuple:
  1349. return nullptr;
  1350. // if (type->Tuple.variables.count == 1) {
  1351. // return lb_type(m, type->Tuple.variables[0]->type);
  1352. // } else {
  1353. // unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1354. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1355. // defer (gb_free(heap_allocator(), fields));
  1356. // for_array(i, type->Tuple.variables) {
  1357. // Entity *field = type->Tuple.variables[i];
  1358. // fields[i] = lb_type(m, field->type);
  1359. // }
  1360. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1361. // }
  1362. case Type_Proc:
  1363. {
  1364. return nullptr;
  1365. // set_procedure_abi_types(heap_allocator(), type);
  1366. // LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1367. // isize offset = 0;
  1368. // if (type->Proc.return_by_pointer) {
  1369. // offset = 1;
  1370. // } else if (type->Proc.abi_compat_result_type != nullptr) {
  1371. // return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1372. // }
  1373. // isize extra_param_count = offset;
  1374. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1375. // extra_param_count += 1;
  1376. // }
  1377. // isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1378. // LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1379. // defer (gb_free(heap_allocator(), param_types));
  1380. // isize param_index = offset;
  1381. // for_array(i, type->Proc.abi_compat_params) {
  1382. // Type *param = type->Proc.abi_compat_params[i];
  1383. // if (param == nullptr) {
  1384. // continue;
  1385. // }
  1386. // param_types[param_index++] = lb_type(m, param);
  1387. // }
  1388. // if (type->Proc.return_by_pointer) {
  1389. // param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  1390. // }
  1391. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1392. // param_types[param_index++] = lb_type(m, t_context_ptr);
  1393. // }
  1394. // LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  1395. // return LLVMPointerType(t, 0);
  1396. }
  1397. break;
  1398. case Type_BitFieldValue:
  1399. return nullptr;
  1400. // return LLVMIntType(type->BitFieldValue.bits);
  1401. case Type_BitField:
  1402. {
  1403. return nullptr;
  1404. // LLVMTypeRef internal_type = nullptr;
  1405. // {
  1406. // GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1407. // unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1408. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1409. // defer (gb_free(heap_allocator(), fields));
  1410. // for_array(i, type->BitField.sizes) {
  1411. // u32 size = type->BitField.sizes[i];
  1412. // fields[i] = LLVMIntType(size);
  1413. // }
  1414. // internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1415. // }
  1416. // unsigned field_count = 2;
  1417. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1418. // i64 alignment = 1;
  1419. // if (type->BitField.custom_align > 0) {
  1420. // alignment = type->BitField.custom_align;
  1421. // }
  1422. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1423. // fields[1] = internal_type;
  1424. // return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1425. }
  1426. break;
  1427. case Type_BitSet:
  1428. return nullptr;
  1429. // return LLVMIntType(8*cast(unsigned)type_size_of(type));
  1430. case Type_SimdVector:
  1431. return nullptr;
  1432. // if (type->SimdVector.is_x86_mmx) {
  1433. // return LLVMX86MMXTypeInContext(ctx);
  1434. // }
  1435. // return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1436. }
  1437. GB_PANIC("Invalid type %s", type_to_string(type));
  1438. return nullptr;
  1439. }
  1440. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1441. LLVMTypeRef t = lb_type(m, type);
  1442. LLVMMetadataRef *found = map_get(&m->debug_values, hash_pointer(t));
  1443. if (found != nullptr) {
  1444. return *found;
  1445. }
  1446. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1447. map_set(&m->debug_values, hash_pointer(t), dt);
  1448. return dt;
  1449. }
  1450. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1451. if (e != nullptr) {
  1452. map_set(&m->values, hash_entity(e), val);
  1453. }
  1454. }
  1455. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1456. if (name.len > 0) {
  1457. string_map_set(&m->members, name, val);
  1458. }
  1459. }
  1460. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1461. string_map_set(&m->members, key, val);
  1462. }
  1463. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1464. if (p->entity != nullptr) {
  1465. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1466. }
  1467. string_map_set(&m->procedures, p->name, p);
  1468. }
  1469. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  1470. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  1471. LLVMValueRef values[2] = {
  1472. str_elem.value,
  1473. str_len.value,
  1474. };
  1475. lbValue res = {};
  1476. res.type = t_string;
  1477. res.value = LLVMConstNamedStruct(lb_type(p->module, t_string), values, gb_count_of(values));
  1478. return res;
  1479. } else {
  1480. lbAddr res = lb_add_local_generated(p, t_string, false);
  1481. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  1482. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  1483. return lb_addr_load(p, res);
  1484. }
  1485. }
  1486. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1487. unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name));
  1488. GB_ASSERT(kind != 0);
  1489. return LLVMCreateEnumAttribute(ctx, kind, value);
  1490. }
  1491. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1492. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1493. GB_ASSERT(attr != nullptr);
  1494. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1495. }
  1496. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1497. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  1498. }
  1499. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  1500. GB_ASSERT(entity != nullptr);
  1501. String link_name = lb_get_entity_name(m, entity);
  1502. {
  1503. StringHashKey key = string_hash_string(link_name);
  1504. lbValue *found = string_map_get(&m->members, key);
  1505. if (found) {
  1506. lb_add_entity(m, entity, *found);
  1507. lbProcedure **p_found = string_map_get(&m->procedures, key);
  1508. GB_ASSERT(p_found != nullptr);
  1509. return *p_found;
  1510. }
  1511. }
  1512. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  1513. p->module = m;
  1514. entity->code_gen_module = m;
  1515. entity->code_gen_procedure = p;
  1516. p->entity = entity;
  1517. p->name = link_name;
  1518. DeclInfo *decl = entity->decl_info;
  1519. ast_node(pl, ProcLit, decl->proc_lit);
  1520. Type *pt = base_type(entity->type);
  1521. GB_ASSERT(pt->kind == Type_Proc);
  1522. set_procedure_abi_types(heap_allocator(), entity->type);
  1523. p->type = entity->type;
  1524. p->type_expr = decl->type_expr;
  1525. p->body = pl->body;
  1526. p->tags = pt->Proc.tags;
  1527. p->inlining = ProcInlining_none;
  1528. p->is_foreign = entity->Procedure.is_foreign;
  1529. p->is_export = entity->Procedure.is_export;
  1530. p->is_entry_point = false;
  1531. gbAllocator a = heap_allocator();
  1532. p->children.allocator = a;
  1533. p->params.allocator = a;
  1534. p->defer_stmts.allocator = a;
  1535. p->blocks.allocator = a;
  1536. p->branch_blocks.allocator = a;
  1537. p->context_stack.allocator = a;
  1538. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  1539. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1540. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1541. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1542. LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]);
  1543. lbValue proc_value = {p->value, p->type};
  1544. lb_add_entity(m, entity, proc_value);
  1545. lb_add_member(m, p->name, proc_value);
  1546. lb_add_procedure_value(m, p);
  1547. // NOTE(bill): offset==0 is the return value
  1548. isize offset = 1;
  1549. if (pt->Proc.return_by_pointer) {
  1550. lb_add_proc_attribute_at_index(p, 1, "sret");
  1551. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1552. offset = 2;
  1553. }
  1554. isize parameter_index = 0;
  1555. if (pt->Proc.param_count) {
  1556. TypeTuple *params = &pt->Proc.params->Tuple;
  1557. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1558. Entity *e = params->variables[i];
  1559. Type *original_type = e->type;
  1560. Type *abi_type = pt->Proc.abi_compat_params[i];
  1561. if (e->kind != Entity_Variable) continue;
  1562. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1563. continue;
  1564. }
  1565. if (is_type_tuple(abi_type)) {
  1566. for_array(j, abi_type->Tuple.variables) {
  1567. Type *tft = abi_type->Tuple.variables[j]->type;
  1568. if (e->flags&EntityFlag_NoAlias) {
  1569. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1570. }
  1571. }
  1572. parameter_index += abi_type->Tuple.variables.count;
  1573. } else {
  1574. if (e->flags&EntityFlag_NoAlias) {
  1575. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1576. }
  1577. parameter_index += 1;
  1578. }
  1579. }
  1580. }
  1581. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1582. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1583. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1584. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1585. }
  1586. if (entity->Procedure.is_foreign) {
  1587. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  1588. }
  1589. { // Debug Information
  1590. unsigned line = cast(unsigned)entity->token.pos.line;
  1591. LLVMMetadataRef file = nullptr;
  1592. if (entity->file != nullptr) {
  1593. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1594. }
  1595. LLVMMetadataRef scope = nullptr;
  1596. LLVMMetadataRef type = nullptr;
  1597. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1598. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1599. cast(char const *)entity->token.string.text, entity->token.string.len,
  1600. cast(char const *)p->name.text, p->name.len,
  1601. file, line, type,
  1602. true, p->body == nullptr,
  1603. line, LLVMDIFlagZero, false
  1604. );
  1605. GB_ASSERT(res != nullptr);
  1606. map_set(&m->debug_values, hash_pointer(p), res);
  1607. }
  1608. return p;
  1609. }
  1610. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1611. {
  1612. lbValue *found = string_map_get(&m->members, link_name);
  1613. GB_ASSERT(found == nullptr);
  1614. }
  1615. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  1616. p->module = m;
  1617. p->name = link_name;
  1618. p->type = type;
  1619. p->type_expr = nullptr;
  1620. p->body = nullptr;
  1621. p->tags = 0;
  1622. p->inlining = ProcInlining_none;
  1623. p->is_foreign = false;
  1624. p->is_export = false;
  1625. p->is_entry_point = false;
  1626. gbAllocator a = heap_allocator();
  1627. p->children.allocator = a;
  1628. p->params.allocator = a;
  1629. p->defer_stmts.allocator = a;
  1630. p->blocks.allocator = a;
  1631. p->branch_blocks.allocator = a;
  1632. p->context_stack.allocator = a;
  1633. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  1634. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1635. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1636. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1637. Type *pt = p->type;
  1638. LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]);
  1639. lbValue proc_value = {p->value, p->type};
  1640. lb_add_member(m, p->name, proc_value);
  1641. lb_add_procedure_value(m, p);
  1642. // NOTE(bill): offset==0 is the return value
  1643. isize offset = 1;
  1644. if (pt->Proc.return_by_pointer) {
  1645. lb_add_proc_attribute_at_index(p, 1, "sret");
  1646. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1647. offset = 2;
  1648. }
  1649. isize parameter_index = 0;
  1650. if (pt->Proc.param_count) {
  1651. TypeTuple *params = &pt->Proc.params->Tuple;
  1652. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1653. Entity *e = params->variables[i];
  1654. Type *original_type = e->type;
  1655. Type *abi_type = pt->Proc.abi_compat_params[i];
  1656. if (e->kind != Entity_Variable) continue;
  1657. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1658. continue;
  1659. }
  1660. if (is_type_tuple(abi_type)) {
  1661. for_array(j, abi_type->Tuple.variables) {
  1662. Type *tft = abi_type->Tuple.variables[j]->type;
  1663. if (e->flags&EntityFlag_NoAlias) {
  1664. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1665. }
  1666. }
  1667. parameter_index += abi_type->Tuple.variables.count;
  1668. } else {
  1669. if (e->flags&EntityFlag_NoAlias) {
  1670. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1671. }
  1672. parameter_index += 1;
  1673. }
  1674. }
  1675. }
  1676. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1677. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1678. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1679. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1680. }
  1681. return p;
  1682. }
  1683. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  1684. lbParamPasskind kind = lbParamPass_Value;
  1685. if (e != nullptr && abi_type != e->type) {
  1686. if (is_type_pointer(abi_type)) {
  1687. GB_ASSERT(e->kind == Entity_Variable);
  1688. kind = lbParamPass_Pointer;
  1689. if (e->flags&EntityFlag_Value) {
  1690. kind = lbParamPass_ConstRef;
  1691. }
  1692. } else if (is_type_integer(abi_type)) {
  1693. kind = lbParamPass_Integer;
  1694. } else if (abi_type == t_llvm_bool) {
  1695. kind = lbParamPass_Value;
  1696. } else if (is_type_simd_vector(abi_type)) {
  1697. kind = lbParamPass_BitCast;
  1698. } else if (is_type_float(abi_type)) {
  1699. kind = lbParamPass_BitCast;
  1700. } else if (is_type_tuple(abi_type)) {
  1701. kind = lbParamPass_Tuple;
  1702. } else {
  1703. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  1704. }
  1705. }
  1706. if (kind_) *kind_ = kind;
  1707. lbValue res = {};
  1708. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  1709. res.type = abi_type;
  1710. return res;
  1711. }
  1712. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1713. lbParamPasskind kind = lbParamPass_Value;
  1714. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  1715. array_add(&p->params, v);
  1716. lbValue res = {};
  1717. switch (kind) {
  1718. case lbParamPass_Value: {
  1719. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1720. lbValue x = v;
  1721. if (abi_type == t_llvm_bool) {
  1722. x = lb_emit_conv(p, x, t_bool);
  1723. }
  1724. lb_addr_store(p, l, x);
  1725. return x;
  1726. }
  1727. case lbParamPass_Pointer:
  1728. lb_add_entity(p->module, e, v);
  1729. return lb_emit_load(p, v);
  1730. case lbParamPass_Integer: {
  1731. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1732. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  1733. lb_emit_store(p, iptr, v);
  1734. return lb_addr_load(p, l);
  1735. }
  1736. case lbParamPass_ConstRef:
  1737. lb_add_entity(p->module, e, v);
  1738. return lb_emit_load(p, v);
  1739. case lbParamPass_BitCast: {
  1740. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1741. lbValue x = lb_emit_transmute(p, v, e->type);
  1742. lb_addr_store(p, l, x);
  1743. return x;
  1744. }
  1745. case lbParamPass_Tuple: {
  1746. lbAddr l = lb_add_local(p, e->type, e, true, index);
  1747. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  1748. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  1749. if (abi_type->Tuple.variables.count > 0) {
  1750. array_pop(&p->params);
  1751. }
  1752. for_array(i, abi_type->Tuple.variables) {
  1753. Type *t = abi_type->Tuple.variables[i]->type;
  1754. lbParamPasskind elem_kind = lbParamPass_Value;
  1755. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  1756. array_add(&p->params, elem);
  1757. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  1758. lb_emit_store(p, dst, elem);
  1759. }
  1760. return lb_addr_load(p, l);
  1761. }
  1762. }
  1763. GB_PANIC("Unreachable");
  1764. return {};
  1765. }
  1766. void lb_start_block(lbProcedure *p, lbBlock *b) {
  1767. GB_ASSERT(b != nullptr);
  1768. if (!b->appended) {
  1769. b->appended = true;
  1770. LLVMAppendExistingBasicBlock(p->value, b->block);
  1771. }
  1772. LLVMPositionBuilderAtEnd(p->builder, b->block);
  1773. p->curr_block = b;
  1774. }
  1775. void lb_begin_procedure_body(lbProcedure *p) {
  1776. DeclInfo *decl = decl_info_of_entity(p->entity);
  1777. if (decl != nullptr) {
  1778. for_array(i, decl->labels) {
  1779. BlockLabel bl = decl->labels[i];
  1780. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  1781. array_add(&p->branch_blocks, bb);
  1782. }
  1783. }
  1784. p->builder = LLVMCreateBuilder();
  1785. p->decl_block = lb_create_block(p, "decls", true);
  1786. p->entry_block = lb_create_block(p, "entry", true);
  1787. lb_start_block(p, p->entry_block);
  1788. GB_ASSERT(p->type != nullptr);
  1789. i32 parameter_index = 0;
  1790. if (p->type->Proc.return_by_pointer) {
  1791. // NOTE(bill): this must be parameter 0
  1792. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  1793. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  1794. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  1795. lbValue return_ptr_value = {};
  1796. return_ptr_value.value = LLVMGetParam(p->value, 0);
  1797. return_ptr_value.type = alloc_type_pointer(p->type->Proc.abi_compat_result_type);
  1798. p->return_ptr = lb_addr(return_ptr_value);
  1799. lb_add_entity(p->module, e, return_ptr_value);
  1800. parameter_index += 1;
  1801. }
  1802. if (p->type->Proc.params != nullptr) {
  1803. TypeTuple *params = &p->type->Proc.params->Tuple;
  1804. if (p->type_expr != nullptr) {
  1805. ast_node(pt, ProcType, p->type_expr);
  1806. isize param_index = 0;
  1807. isize q_index = 0;
  1808. for_array(i, params->variables) {
  1809. ast_node(fl, FieldList, pt->params);
  1810. GB_ASSERT(fl->list.count > 0);
  1811. GB_ASSERT(fl->list[0]->kind == Ast_Field);
  1812. if (q_index == fl->list[param_index]->Field.names.count) {
  1813. q_index = 0;
  1814. param_index++;
  1815. }
  1816. ast_node(field, Field, fl->list[param_index]);
  1817. Ast *name = field->names[q_index++];
  1818. Entity *e = params->variables[i];
  1819. if (e->kind != Entity_Variable) {
  1820. continue;
  1821. }
  1822. Type *abi_type = p->type->Proc.abi_compat_params[i];
  1823. if (e->token.string != "") {
  1824. lb_add_param(p, e, name, abi_type, parameter_index);
  1825. }
  1826. if (is_type_tuple(abi_type)) {
  1827. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  1828. } else {
  1829. parameter_index += 1;
  1830. }
  1831. }
  1832. } else {
  1833. auto abi_types = p->type->Proc.abi_compat_params;
  1834. for_array(i, params->variables) {
  1835. Entity *e = params->variables[i];
  1836. if (e->kind != Entity_Variable) {
  1837. continue;
  1838. }
  1839. Type *abi_type = e->type;
  1840. if (abi_types.count > 0) {
  1841. abi_type = abi_types[i];
  1842. }
  1843. if (e->token.string != "") {
  1844. lb_add_param(p, e, nullptr, abi_type, parameter_index);
  1845. }
  1846. if (is_type_tuple(abi_type)) {
  1847. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  1848. } else {
  1849. parameter_index += 1;
  1850. }
  1851. }
  1852. }
  1853. }
  1854. if (p->type->Proc.has_named_results) {
  1855. GB_ASSERT(p->type->Proc.result_count > 0);
  1856. TypeTuple *results = &p->type->Proc.results->Tuple;
  1857. LLVMValueRef return_ptr = LLVMGetParam(p->value, 0);
  1858. isize result_index = 0;
  1859. for_array(i, results->variables) {
  1860. Entity *e = results->variables[i];
  1861. if (e->kind != Entity_Variable) {
  1862. continue;
  1863. }
  1864. if (e->token.string != "") {
  1865. GB_ASSERT(!is_blank_ident(e->token));
  1866. lbAddr res = lb_add_local(p, e->type, e);
  1867. lbValue c = {};
  1868. switch (e->Variable.param_value.kind) {
  1869. case ParameterValue_Constant:
  1870. c = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  1871. break;
  1872. case ParameterValue_Nil:
  1873. c = lb_const_nil(p->module, e->type);
  1874. break;
  1875. case ParameterValue_Location:
  1876. GB_PANIC("ParameterValue_Location");
  1877. break;
  1878. }
  1879. if (c.value != nullptr) {
  1880. lb_addr_store(p, res, c);
  1881. }
  1882. }
  1883. result_index += 1;
  1884. }
  1885. }
  1886. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  1887. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  1888. e->flags |= EntityFlag_NoAlias;
  1889. lbValue param = {};
  1890. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  1891. param.type = e->type;
  1892. lb_add_entity(p->module, e, param);
  1893. lbAddr ctx_addr = {};
  1894. ctx_addr.kind = lbAddr_Context;
  1895. ctx_addr.addr = param;
  1896. lbContextData ctx = {ctx_addr, p->scope_index};
  1897. array_add(&p->context_stack, ctx);
  1898. }
  1899. lb_start_block(p, p->entry_block);
  1900. }
  1901. void lb_end_procedure_body(lbProcedure *p) {
  1902. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  1903. LLVMBuildBr(p->builder, p->entry_block->block);
  1904. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  1905. if (p->type->Proc.result_count == 0) {
  1906. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  1907. if (!LLVMIsAReturnInst(instr)) {
  1908. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1909. LLVMBuildRetVoid(p->builder);
  1910. }
  1911. } else {
  1912. if (p->curr_block->preds.count == 0) {
  1913. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  1914. if (instr == nullptr) {
  1915. // NOTE(bill): Remove dead trailing block
  1916. LLVMDeleteBasicBlock(p->curr_block->block);
  1917. }
  1918. }
  1919. }
  1920. p->curr_block = nullptr;
  1921. }
  1922. void lb_end_procedure(lbProcedure *p) {
  1923. LLVMDisposeBuilder(p->builder);
  1924. }
  1925. void lb_add_edge(lbBlock *from, lbBlock *to) {
  1926. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  1927. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  1928. array_add(&from->succs, to);
  1929. array_add(&to->preds, from);
  1930. }
  1931. }
  1932. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  1933. lbBlock *b = gb_alloc_item(heap_allocator(), lbBlock);
  1934. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  1935. b->appended = false;
  1936. if (append) {
  1937. b->appended = true;
  1938. LLVMAppendExistingBasicBlock(p->value, b->block);
  1939. }
  1940. b->scope = p->curr_scope;
  1941. b->scope_index = p->scope_index;
  1942. b->preds.allocator = heap_allocator();
  1943. b->succs.allocator = heap_allocator();
  1944. array_add(&p->blocks, b);
  1945. return b;
  1946. }
  1947. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  1948. if (p->curr_block == nullptr) {
  1949. return;
  1950. }
  1951. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1952. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1953. return;
  1954. }
  1955. lb_add_edge(p->curr_block, target_block);
  1956. LLVMBuildBr(p->builder, target_block->block);
  1957. p->curr_block = nullptr;
  1958. }
  1959. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  1960. lbBlock *b = p->curr_block;
  1961. if (b == nullptr) {
  1962. return;
  1963. }
  1964. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1965. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1966. return;
  1967. }
  1968. lb_add_edge(b, true_block);
  1969. lb_add_edge(b, false_block);
  1970. LLVMValueRef cv = cond.value;
  1971. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  1972. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  1973. }
  1974. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  1975. GB_ASSERT(cond != nullptr);
  1976. GB_ASSERT(true_block != nullptr);
  1977. GB_ASSERT(false_block != nullptr);
  1978. switch (cond->kind) {
  1979. case_ast_node(pe, ParenExpr, cond);
  1980. return lb_build_cond(p, pe->expr, true_block, false_block);
  1981. case_end;
  1982. case_ast_node(ue, UnaryExpr, cond);
  1983. if (ue->op.kind == Token_Not) {
  1984. return lb_build_cond(p, ue->expr, false_block, true_block);
  1985. }
  1986. case_end;
  1987. case_ast_node(be, BinaryExpr, cond);
  1988. if (be->op.kind == Token_CmpAnd) {
  1989. lbBlock *block = lb_create_block(p, "cmp.and");
  1990. lb_build_cond(p, be->left, block, false_block);
  1991. lb_start_block(p, block);
  1992. return lb_build_cond(p, be->right, true_block, false_block);
  1993. } else if (be->op.kind == Token_CmpOr) {
  1994. lbBlock *block = lb_create_block(p, "cmp.or");
  1995. lb_build_cond(p, be->left, true_block, block);
  1996. lb_start_block(p, block);
  1997. return lb_build_cond(p, be->right, true_block, false_block);
  1998. }
  1999. case_end;
  2000. }
  2001. lbValue v = lb_build_expr(p, cond);
  2002. // v = lb_emit_conv(p, v, t_bool);
  2003. v = lb_emit_conv(p, v, t_llvm_bool);
  2004. lb_emit_if(p, v, true_block, false_block);
  2005. return v;
  2006. }
  2007. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2008. GB_ASSERT(p->decl_block != p->curr_block);
  2009. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2010. char const *name = "";
  2011. if (e != nullptr) {
  2012. // name = alloc_cstring(heap_allocator(), e->token.string);
  2013. }
  2014. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2015. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2016. LLVMSetAlignment(ptr, 16); // TODO(bill): Make this configurable
  2017. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2018. if (zero_init) {
  2019. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2020. }
  2021. lbValue val = {};
  2022. val.value = ptr;
  2023. val.type = alloc_type_pointer(type);
  2024. if (e != nullptr) {
  2025. lb_add_entity(p->module, e, val);
  2026. }
  2027. return lb_addr(val);
  2028. }
  2029. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2030. return lb_add_local(p, type, nullptr, zero_init);
  2031. }
  2032. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2033. GB_ASSERT(pd->body != nullptr);
  2034. lbModule *m = p->module;
  2035. auto *min_dep_set = &m->info->minimum_dependency_set;
  2036. if (ptr_set_exists(min_dep_set, e) == false) {
  2037. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2038. return;
  2039. }
  2040. // NOTE(bill): Generate a new name
  2041. // parent.name-guid
  2042. String original_name = e->token.string;
  2043. String pd_name = original_name;
  2044. if (e->Procedure.link_name.len > 0) {
  2045. pd_name = e->Procedure.link_name;
  2046. }
  2047. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2048. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  2049. i32 guid = cast(i32)p->children.count;
  2050. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2051. String name = make_string(cast(u8 *)name_text, name_len-1);
  2052. set_procedure_abi_types(heap_allocator(), e->type);
  2053. e->Procedure.link_name = name;
  2054. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2055. e->code_gen_procedure = nested_proc;
  2056. lbValue value = {};
  2057. value.value = nested_proc->value;
  2058. value.type = nested_proc->type;
  2059. lb_add_entity(m, e, value);
  2060. array_add(&p->children, nested_proc);
  2061. array_add(&m->procedures_to_generate, nested_proc);
  2062. }
  2063. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2064. if (e == nullptr) {
  2065. return;
  2066. }
  2067. GB_ASSERT(e->kind == Entity_LibraryName);
  2068. GB_ASSERT(e->flags & EntityFlag_Used);
  2069. for_array(i, e->LibraryName.paths) {
  2070. String library_path = e->LibraryName.paths[i];
  2071. if (library_path.len == 0) {
  2072. continue;
  2073. }
  2074. bool ok = true;
  2075. for_array(path_index, m->foreign_library_paths) {
  2076. String path = m->foreign_library_paths[path_index];
  2077. #if defined(GB_SYSTEM_WINDOWS)
  2078. if (str_eq_ignore_case(path, library_path)) {
  2079. #else
  2080. if (str_eq(path, library_path)) {
  2081. #endif
  2082. ok = false;
  2083. break;
  2084. }
  2085. }
  2086. if (ok) {
  2087. array_add(&m->foreign_library_paths, library_path);
  2088. }
  2089. }
  2090. }
  2091. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2092. if (vd == nullptr || vd->is_mutable) {
  2093. return;
  2094. }
  2095. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2096. static i32 global_guid = 0;
  2097. for_array(i, vd->names) {
  2098. Ast *ident = vd->names[i];
  2099. GB_ASSERT(ident->kind == Ast_Ident);
  2100. Entity *e = entity_of_ident(ident);
  2101. GB_ASSERT(e != nullptr);
  2102. if (e->kind != Entity_TypeName) {
  2103. continue;
  2104. }
  2105. bool polymorphic_struct = false;
  2106. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2107. Type *bt = base_type(e->type);
  2108. if (bt->kind == Type_Struct) {
  2109. polymorphic_struct = bt->Struct.is_polymorphic;
  2110. }
  2111. }
  2112. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2113. continue;
  2114. }
  2115. if (e->TypeName.ir_mangled_name.len != 0) {
  2116. // NOTE(bill): Already set
  2117. continue;
  2118. }
  2119. lb_set_nested_type_name_ir_mangled_name(e, p);
  2120. }
  2121. for_array(i, vd->names) {
  2122. Ast *ident = vd->names[i];
  2123. GB_ASSERT(ident->kind == Ast_Ident);
  2124. Entity *e = entity_of_ident(ident);
  2125. GB_ASSERT(e != nullptr);
  2126. if (e->kind != Entity_Procedure) {
  2127. continue;
  2128. }
  2129. CheckerInfo *info = p->module->info;
  2130. DeclInfo *decl = decl_info_of_entity(e);
  2131. ast_node(pl, ProcLit, decl->proc_lit);
  2132. if (pl->body != nullptr) {
  2133. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2134. if (found) {
  2135. auto procs = *found;
  2136. for_array(i, procs) {
  2137. Entity *e = procs[i];
  2138. if (!ptr_set_exists(min_dep_set, e)) {
  2139. continue;
  2140. }
  2141. DeclInfo *d = decl_info_of_entity(e);
  2142. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2143. }
  2144. } else {
  2145. lb_build_nested_proc(p, pl, e);
  2146. }
  2147. } else {
  2148. // FFI - Foreign function interace
  2149. String original_name = e->token.string;
  2150. String name = original_name;
  2151. if (e->Procedure.is_foreign) {
  2152. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2153. }
  2154. if (e->Procedure.link_name.len > 0) {
  2155. name = e->Procedure.link_name;
  2156. }
  2157. lbValue *prev_value = string_map_get(&p->module->members, name);
  2158. if (prev_value != nullptr) {
  2159. // NOTE(bill): Don't do mutliple declarations in the IR
  2160. return;
  2161. }
  2162. set_procedure_abi_types(heap_allocator(), e->type);
  2163. e->Procedure.link_name = name;
  2164. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2165. lbValue value = {};
  2166. value.value = nested_proc->value;
  2167. value.type = nested_proc->type;
  2168. array_add(&p->module->procedures_to_generate, nested_proc);
  2169. if (p != nullptr) {
  2170. array_add(&p->children, nested_proc);
  2171. } else {
  2172. string_map_set(&p->module->members, name, value);
  2173. }
  2174. }
  2175. }
  2176. }
  2177. void lb_build_stmt_list(lbProcedure *p, Array<Ast *> const &stmts) {
  2178. for_array(i, stmts) {
  2179. Ast *stmt = stmts[i];
  2180. switch (stmt->kind) {
  2181. case_ast_node(vd, ValueDecl, stmt);
  2182. lb_build_constant_value_decl(p, vd);
  2183. case_end;
  2184. case_ast_node(fb, ForeignBlockDecl, stmt);
  2185. ast_node(block, BlockStmt, fb->body);
  2186. lb_build_stmt_list(p, block->stmts);
  2187. case_end;
  2188. }
  2189. }
  2190. for_array(i, stmts) {
  2191. lb_build_stmt(p, stmts[i]);
  2192. }
  2193. }
  2194. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2195. GB_ASSERT(ident->kind == Ast_Ident);
  2196. Entity *e = entity_of_ident(ident);
  2197. GB_ASSERT(e->kind == Entity_Label);
  2198. for_array(i, p->branch_blocks) {
  2199. lbBranchBlocks *b = &p->branch_blocks[i];
  2200. if (b->label == e->Label.node) {
  2201. return *b;
  2202. }
  2203. }
  2204. GB_PANIC("Unreachable");
  2205. lbBranchBlocks empty = {};
  2206. return empty;
  2207. }
  2208. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2209. lbTargetList *tl = gb_alloc_item(heap_allocator(), lbTargetList);
  2210. tl->prev = p->target_list;
  2211. tl->break_ = break_;
  2212. tl->continue_ = continue_;
  2213. tl->fallthrough_ = fallthrough_;
  2214. p->target_list = tl;
  2215. if (label != nullptr) { // Set label blocks
  2216. GB_ASSERT(label->kind == Ast_Label);
  2217. for_array(i, p->branch_blocks) {
  2218. lbBranchBlocks *b = &p->branch_blocks[i];
  2219. GB_ASSERT(b->label != nullptr && label != nullptr);
  2220. GB_ASSERT(b->label->kind == Ast_Label);
  2221. if (b->label == label) {
  2222. b->break_ = break_;
  2223. b->continue_ = continue_;
  2224. return tl;
  2225. }
  2226. }
  2227. GB_PANIC("Unreachable");
  2228. }
  2229. return tl;
  2230. }
  2231. void lb_pop_target_list(lbProcedure *p) {
  2232. p->target_list = p->target_list->prev;
  2233. }
  2234. void lb_open_scope(lbProcedure *p) {
  2235. p->scope_index += 1;
  2236. }
  2237. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  2238. lb_emit_defer_stmts(p, kind, block);
  2239. GB_ASSERT(p->scope_index > 0);
  2240. // NOTE(bill): Remove `context`s made in that scope
  2241. while (p->context_stack.count > 0) {
  2242. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  2243. if (ctx->scope_index >= p->scope_index) {
  2244. array_pop(&p->context_stack);
  2245. } else {
  2246. break;
  2247. }
  2248. }
  2249. p->scope_index -= 1;
  2250. }
  2251. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  2252. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  2253. GB_ASSERT(is_type_boolean(tv.type));
  2254. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  2255. if (tv.value.value_bool) {
  2256. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  2257. } else if (ws->else_stmt) {
  2258. switch (ws->else_stmt->kind) {
  2259. case Ast_BlockStmt:
  2260. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  2261. break;
  2262. case Ast_WhenStmt:
  2263. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  2264. break;
  2265. default:
  2266. GB_PANIC("Invalid 'else' statement in 'when' statement");
  2267. break;
  2268. }
  2269. }
  2270. }
  2271. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  2272. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2273. lbModule *m = p->module;
  2274. lbValue count = {};
  2275. Type *expr_type = base_type(type_deref(expr.type));
  2276. switch (expr_type->kind) {
  2277. case Type_Array:
  2278. count = lb_const_int(m, t_int, expr_type->Array.count);
  2279. break;
  2280. }
  2281. lbValue val = {};
  2282. lbValue idx = {};
  2283. lbBlock *loop = nullptr;
  2284. lbBlock *done = nullptr;
  2285. lbBlock *body = nullptr;
  2286. lbAddr index = lb_add_local_generated(p, t_int, false);
  2287. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  2288. loop = lb_create_block(p, "for.index.loop");
  2289. lb_emit_jump(p, loop);
  2290. lb_start_block(p, loop);
  2291. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  2292. lb_addr_store(p, index, incr);
  2293. body = lb_create_block(p, "for.index.body");
  2294. done = lb_create_block(p, "for.index.done");
  2295. if (count.value == nullptr) {
  2296. GB_ASSERT(count_ptr.value != nullptr);
  2297. count = lb_emit_load(p, count_ptr);
  2298. }
  2299. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  2300. lb_emit_if(p, cond, body, done);
  2301. lb_start_block(p, body);
  2302. idx = lb_addr_load(p, index);
  2303. switch (expr_type->kind) {
  2304. case Type_Array: {
  2305. if (val_type != nullptr) {
  2306. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2307. }
  2308. break;
  2309. }
  2310. case Type_EnumeratedArray: {
  2311. if (val_type != nullptr) {
  2312. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2313. // NOTE(bill): Override the idx value for the enumeration
  2314. Type *index_type = expr_type->EnumeratedArray.index;
  2315. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  2316. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  2317. }
  2318. }
  2319. break;
  2320. }
  2321. case Type_Slice: {
  2322. if (val_type != nullptr) {
  2323. lbValue elem = lb_slice_elem(p, expr);
  2324. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2325. }
  2326. break;
  2327. }
  2328. case Type_DynamicArray: {
  2329. if (val_type != nullptr) {
  2330. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  2331. elem = lb_emit_load(p, elem);
  2332. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2333. }
  2334. break;
  2335. }
  2336. case Type_Map: {
  2337. lbAddr key = lb_add_local_generated(p, expr_type->Map.key, true);
  2338. lbValue entries = lb_map_entries_ptr(p, expr);
  2339. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  2340. elem = lb_emit_load(p, elem);
  2341. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  2342. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  2343. lbValue hash = lb_emit_struct_ep(p, entry, 0);
  2344. if (is_type_string(expr_type->Map.key)) {
  2345. lbValue str = lb_emit_struct_ep(p, hash, 1);
  2346. lb_addr_store(p, key, lb_emit_load(p, str));
  2347. } else {
  2348. lbValue hash_ptr = lb_emit_struct_ep(p, hash, 0);
  2349. hash_ptr = lb_emit_conv(p, hash_ptr, key.addr.type);
  2350. lb_addr_store(p, key, lb_emit_load(p, hash_ptr));
  2351. }
  2352. idx = lb_addr_load(p, key);
  2353. break;
  2354. }
  2355. default:
  2356. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  2357. break;
  2358. }
  2359. if (val_) *val_ = val;
  2360. if (idx_) *idx_ = idx;
  2361. if (loop_) *loop_ = loop;
  2362. if (done_) *done_ = done;
  2363. }
  2364. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  2365. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2366. lbModule *m = p->module;
  2367. lbValue count = lb_const_int(m, t_int, 0);
  2368. Type *expr_type = base_type(expr.type);
  2369. switch (expr_type->kind) {
  2370. case Type_Basic:
  2371. count = lb_string_len(p, expr);
  2372. break;
  2373. default:
  2374. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  2375. break;
  2376. }
  2377. lbValue val = {};
  2378. lbValue idx = {};
  2379. lbBlock *loop = nullptr;
  2380. lbBlock *done = nullptr;
  2381. lbBlock *body = nullptr;
  2382. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2383. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2384. loop = lb_create_block(p, "for.string.loop");
  2385. lb_emit_jump(p, loop);
  2386. lb_start_block(p, loop);
  2387. body = lb_create_block(p, "for.string.body");
  2388. done = lb_create_block(p, "for.string.done");
  2389. lbValue offset = lb_addr_load(p, offset_);
  2390. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  2391. lb_emit_if(p, cond, body, done);
  2392. lb_start_block(p, body);
  2393. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  2394. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  2395. auto args = array_make<lbValue>(heap_allocator(), 1);
  2396. args[0] = lb_emit_string(p, str_elem, str_len);
  2397. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  2398. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  2399. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  2400. idx = offset;
  2401. if (val_type != nullptr) {
  2402. val = lb_emit_struct_ev(p, rune_and_len, 0);
  2403. }
  2404. if (val_) *val_ = val;
  2405. if (idx_) *idx_ = idx;
  2406. if (loop_) *loop_ = loop;
  2407. if (done_) *done_ = done;
  2408. }
  2409. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  2410. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2411. lbModule *m = p->module;
  2412. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  2413. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  2414. lbValue lower = lb_build_expr(p, node->left);
  2415. lbValue upper = {};
  2416. lbValue val = {};
  2417. lbValue idx = {};
  2418. lbBlock *loop = nullptr;
  2419. lbBlock *done = nullptr;
  2420. lbBlock *body = nullptr;
  2421. if (val_type == nullptr) {
  2422. val_type = lower.type;
  2423. }
  2424. lbAddr value = lb_add_local_generated(p, val_type, false);
  2425. lb_addr_store(p, value, lower);
  2426. lbAddr index = lb_add_local_generated(p, t_int, false);
  2427. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  2428. loop = lb_create_block(p, "for.interval.loop");
  2429. lb_emit_jump(p, loop);
  2430. lb_start_block(p, loop);
  2431. body = lb_create_block(p, "for.interval.body");
  2432. done = lb_create_block(p, "for.interval.done");
  2433. TokenKind op = Token_Lt;
  2434. switch (node->op.kind) {
  2435. case Token_Ellipsis: op = Token_LtEq; break;
  2436. case Token_RangeHalf: op = Token_Lt; break;
  2437. default: GB_PANIC("Invalid interval operator"); break;
  2438. }
  2439. upper = lb_build_expr(p, node->right);
  2440. lbValue curr_value = lb_addr_load(p, value);
  2441. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  2442. lb_emit_if(p, cond, body, done);
  2443. lb_start_block(p, body);
  2444. val = lb_addr_load(p, value);
  2445. idx = lb_addr_load(p, index);
  2446. lb_emit_increment(p, value.addr);
  2447. lb_emit_increment(p, index.addr);
  2448. if (val_) *val_ = val;
  2449. if (idx_) *idx_ = idx;
  2450. if (loop_) *loop_ = loop;
  2451. if (done_) *done_ = done;
  2452. }
  2453. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2454. lbModule *m = p->module;
  2455. Type *t = enum_type;
  2456. GB_ASSERT(is_type_enum(t));
  2457. Type *enum_ptr = alloc_type_pointer(t);
  2458. t = base_type(t);
  2459. Type *core_elem = core_type(t);
  2460. GB_ASSERT(t->kind == Type_Enum);
  2461. i64 enum_count = t->Enum.fields.count;
  2462. lbValue max_count = lb_const_int(m, t_int, enum_count);
  2463. lbValue ti = lb_type_info(m, t);
  2464. lbValue variant = lb_emit_struct_ep(p, ti, 3);
  2465. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  2466. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  2467. lbValue values_data = lb_slice_elem(p, values);
  2468. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2469. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2470. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  2471. lb_emit_jump(p, loop);
  2472. lb_start_block(p, loop);
  2473. lbBlock *body = lb_create_block(p, "for.enum.body");
  2474. lbBlock *done = lb_create_block(p, "for.enum.done");
  2475. lbValue offset = lb_addr_load(p, offset_);
  2476. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  2477. lb_emit_if(p, cond, body, done);
  2478. lb_start_block(p, body);
  2479. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  2480. lb_emit_increment(p, offset_.addr);
  2481. lbValue val = {};
  2482. if (val_type != nullptr) {
  2483. GB_ASSERT(are_types_identical(enum_type, val_type));
  2484. if (is_type_integer(core_elem)) {
  2485. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  2486. val = lb_emit_conv(p, i, t);
  2487. } else {
  2488. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  2489. }
  2490. }
  2491. if (val_) *val_ = val;
  2492. if (idx_) *idx_ = offset;
  2493. if (loop_) *loop_ = loop;
  2494. if (done_) *done_ = done;
  2495. }
  2496. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  2497. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  2498. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  2499. lb_emit_jump(p, loop);
  2500. lb_start_block(p, loop);
  2501. lbBlock *body = lb_create_block(p, "for.tuple.body");
  2502. lbBlock *done = lb_create_block(p, "for.tuple.done");
  2503. lbValue tuple_value = lb_build_expr(p, expr);
  2504. Type *tuple = tuple_value.type;
  2505. GB_ASSERT(tuple->kind == Type_Tuple);
  2506. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  2507. i32 cond_index = tuple_count-1;
  2508. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  2509. lb_emit_if(p, cond, body, done);
  2510. lb_start_block(p, body);
  2511. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  2512. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  2513. if (loop_) *loop_ = loop;
  2514. if (done_) *done_ = done;
  2515. }
  2516. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  2517. lb_open_scope(p);
  2518. Type *val0_type = nullptr;
  2519. Type *val1_type = nullptr;
  2520. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2521. val0_type = type_of_expr(rs->val0);
  2522. }
  2523. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2524. val1_type = type_of_expr(rs->val1);
  2525. }
  2526. if (val0_type != nullptr) {
  2527. Entity *e = entity_of_ident(rs->val0);
  2528. lb_add_local(p, e->type, e, true);
  2529. }
  2530. if (val1_type != nullptr) {
  2531. Entity *e = entity_of_ident(rs->val1);
  2532. lb_add_local(p, e->type, e, true);
  2533. }
  2534. lbValue val = {};
  2535. lbValue key = {};
  2536. lbBlock *loop = nullptr;
  2537. lbBlock *done = nullptr;
  2538. Ast *expr = unparen_expr(rs->expr);
  2539. bool is_map = false;
  2540. TypeAndValue tav = type_and_value_of_expr(expr);
  2541. if (is_ast_range(expr)) {
  2542. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  2543. } else if (tav.mode == Addressing_Type) {
  2544. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  2545. } else {
  2546. Type *expr_type = type_of_expr(expr);
  2547. Type *et = base_type(type_deref(expr_type));
  2548. switch (et->kind) {
  2549. case Type_Map: {
  2550. is_map = true;
  2551. lbValue map = lb_build_addr_ptr(p, expr);
  2552. if (is_type_pointer(type_deref(map.type))) {
  2553. map = lb_emit_load(p, map);
  2554. }
  2555. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  2556. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  2557. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  2558. break;
  2559. }
  2560. case Type_Array: {
  2561. lbValue array = lb_build_addr_ptr(p, expr);
  2562. if (is_type_pointer(type_deref(array.type))) {
  2563. array = lb_emit_load(p, array);
  2564. }
  2565. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2566. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  2567. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2568. break;
  2569. }
  2570. case Type_EnumeratedArray: {
  2571. lbValue array = lb_build_addr_ptr(p, expr);
  2572. if (is_type_pointer(type_deref(array.type))) {
  2573. array = lb_emit_load(p, array);
  2574. }
  2575. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2576. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  2577. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2578. break;
  2579. }
  2580. case Type_DynamicArray: {
  2581. lbValue count_ptr = {};
  2582. lbValue array = lb_build_addr_ptr(p, expr);
  2583. if (is_type_pointer(type_deref(array.type))) {
  2584. array = lb_emit_load(p, array);
  2585. }
  2586. count_ptr = lb_emit_struct_ep(p, array, 1);
  2587. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  2588. break;
  2589. }
  2590. case Type_Slice: {
  2591. lbValue count_ptr = {};
  2592. lbValue slice = lb_build_expr(p, expr);
  2593. if (is_type_pointer(slice.type)) {
  2594. count_ptr = lb_emit_struct_ep(p, slice, 1);
  2595. slice = lb_emit_load(p, slice);
  2596. } else {
  2597. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  2598. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  2599. }
  2600. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  2601. break;
  2602. }
  2603. case Type_Basic: {
  2604. lbValue string = lb_build_expr(p, expr);
  2605. if (is_type_pointer(string.type)) {
  2606. string = lb_emit_load(p, string);
  2607. }
  2608. if (is_type_untyped(expr_type)) {
  2609. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  2610. lb_addr_store(p, s, string);
  2611. string = lb_addr_load(p, s);
  2612. }
  2613. Type *t = base_type(string.type);
  2614. GB_ASSERT(!is_type_cstring(t));
  2615. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  2616. break;
  2617. }
  2618. case Type_Tuple:
  2619. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  2620. break;
  2621. default:
  2622. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  2623. break;
  2624. }
  2625. }
  2626. if (is_map) {
  2627. if (val0_type) lb_store_range_stmt_val(p, rs->val0, key);
  2628. if (val1_type) lb_store_range_stmt_val(p, rs->val1, val);
  2629. } else {
  2630. if (val0_type) lb_store_range_stmt_val(p, rs->val0, val);
  2631. if (val1_type) lb_store_range_stmt_val(p, rs->val1, key);
  2632. }
  2633. lb_push_target_list(p, rs->label, done, loop, nullptr);
  2634. lb_build_stmt(p, rs->body);
  2635. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2636. lb_pop_target_list(p);
  2637. lb_emit_jump(p, loop);
  2638. lb_start_block(p, done);
  2639. }
  2640. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  2641. lbModule *m = p->module;
  2642. lb_open_scope(p); // Open scope here
  2643. Type *val0_type = nullptr;
  2644. Type *val1_type = nullptr;
  2645. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2646. val0_type = type_of_expr(rs->val0);
  2647. }
  2648. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2649. val1_type = type_of_expr(rs->val1);
  2650. }
  2651. if (val0_type != nullptr) {
  2652. Entity *e = entity_of_ident(rs->val0);
  2653. lb_add_local(p, e->type, e, true);
  2654. }
  2655. if (val1_type != nullptr) {
  2656. Entity *e = entity_of_ident(rs->val1);
  2657. lb_add_local(p, e->type, e, true);
  2658. }
  2659. lbValue val = {};
  2660. lbValue key = {};
  2661. lbBlock *loop = nullptr;
  2662. lbBlock *done = nullptr;
  2663. Ast *expr = unparen_expr(rs->expr);
  2664. TypeAndValue tav = type_and_value_of_expr(expr);
  2665. if (is_ast_range(expr)) {
  2666. lbAddr val0_addr = {};
  2667. lbAddr val1_addr = {};
  2668. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2669. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2670. TokenKind op = expr->BinaryExpr.op.kind;
  2671. Ast *start_expr = expr->BinaryExpr.left;
  2672. Ast *end_expr = expr->BinaryExpr.right;
  2673. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  2674. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  2675. ExactValue start = start_expr->tav.value;
  2676. ExactValue end = end_expr->tav.value;
  2677. if (op == Token_Ellipsis) { // .. [start, end]
  2678. ExactValue index = exact_value_i64(0);
  2679. for (ExactValue val = start;
  2680. compare_exact_values(Token_LtEq, val, end);
  2681. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2682. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2683. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2684. lb_build_stmt(p, rs->body);
  2685. }
  2686. } else if (op == Token_RangeHalf) { // ..< [start, end)
  2687. ExactValue index = exact_value_i64(0);
  2688. for (ExactValue val = start;
  2689. compare_exact_values(Token_Lt, val, end);
  2690. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2691. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2692. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2693. lb_build_stmt(p, rs->body);
  2694. }
  2695. }
  2696. } else if (tav.mode == Addressing_Type) {
  2697. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  2698. Type *et = type_deref(tav.type);
  2699. Type *bet = base_type(et);
  2700. lbAddr val0_addr = {};
  2701. lbAddr val1_addr = {};
  2702. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2703. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2704. for_array(i, bet->Enum.fields) {
  2705. Entity *field = bet->Enum.fields[i];
  2706. GB_ASSERT(field->kind == Entity_Constant);
  2707. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  2708. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2709. lb_build_stmt(p, rs->body);
  2710. }
  2711. } else {
  2712. lbAddr val0_addr = {};
  2713. lbAddr val1_addr = {};
  2714. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2715. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2716. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  2717. Type *t = base_type(expr->tav.type);
  2718. switch (t->kind) {
  2719. case Type_Basic:
  2720. GB_ASSERT(is_type_string(t));
  2721. {
  2722. ExactValue value = expr->tav.value;
  2723. GB_ASSERT(value.kind == ExactValue_String);
  2724. String str = value.value_string;
  2725. Rune codepoint = 0;
  2726. isize offset = 0;
  2727. do {
  2728. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  2729. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  2730. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  2731. lb_build_stmt(p, rs->body);
  2732. offset += width;
  2733. } while (offset < str.len);
  2734. }
  2735. break;
  2736. case Type_Array:
  2737. if (t->Array.count > 0) {
  2738. lbValue val = lb_build_expr(p, expr);
  2739. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2740. for (i64 i = 0; i < t->Array.count; i++) {
  2741. if (val0_type) {
  2742. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2743. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2744. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2745. }
  2746. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2747. lb_build_stmt(p, rs->body);
  2748. }
  2749. }
  2750. break;
  2751. case Type_EnumeratedArray:
  2752. if (t->EnumeratedArray.count > 0) {
  2753. lbValue val = lb_build_expr(p, expr);
  2754. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2755. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  2756. if (val0_type) {
  2757. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2758. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2759. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2760. }
  2761. if (val1_type) {
  2762. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  2763. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  2764. }
  2765. lb_build_stmt(p, rs->body);
  2766. }
  2767. }
  2768. break;
  2769. default:
  2770. GB_PANIC("Invalid inline for type");
  2771. break;
  2772. }
  2773. }
  2774. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2775. }
  2776. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  2777. if (ss->init != nullptr) {
  2778. lb_build_stmt(p, ss->init);
  2779. }
  2780. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  2781. if (ss->tag != nullptr) {
  2782. tag = lb_build_expr(p, ss->tag);
  2783. }
  2784. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  2785. ast_node(body, BlockStmt, ss->body);
  2786. Array<Ast *> default_stmts = {};
  2787. lbBlock *default_fall = nullptr;
  2788. lbBlock *default_block = nullptr;
  2789. lbBlock *fall = nullptr;
  2790. isize case_count = body->stmts.count;
  2791. for_array(i, body->stmts) {
  2792. Ast *clause = body->stmts[i];
  2793. ast_node(cc, CaseClause, clause);
  2794. lbBlock *body = fall;
  2795. if (body == nullptr) {
  2796. body = lb_create_block(p, "switch.case.body");
  2797. }
  2798. fall = done;
  2799. if (i+1 < case_count) {
  2800. fall = lb_create_block(p, "switch.fall.body");
  2801. }
  2802. if (cc->list.count == 0) {
  2803. // default case
  2804. default_stmts = cc->stmts;
  2805. default_fall = fall;
  2806. default_block = body;
  2807. continue;
  2808. }
  2809. lbBlock *next_cond = nullptr;
  2810. for_array(j, cc->list) {
  2811. Ast *expr = unparen_expr(cc->list[j]);
  2812. next_cond = lb_create_block(p, "switch.case.next");
  2813. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  2814. if (is_ast_range(expr)) {
  2815. ast_node(ie, BinaryExpr, expr);
  2816. TokenKind op = Token_Invalid;
  2817. switch (ie->op.kind) {
  2818. case Token_Ellipsis: op = Token_LtEq; break;
  2819. case Token_RangeHalf: op = Token_Lt; break;
  2820. default: GB_PANIC("Invalid interval operator"); break;
  2821. }
  2822. lbValue lhs = lb_build_expr(p, ie->left);
  2823. lbValue rhs = lb_build_expr(p, ie->right);
  2824. // TODO(bill): do short circuit here
  2825. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  2826. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  2827. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  2828. } else {
  2829. if (expr->tav.mode == Addressing_Type) {
  2830. GB_ASSERT(is_type_typeid(tag.type));
  2831. lbValue e = lb_typeid(p->module, expr->tav.type);
  2832. e = lb_emit_conv(p, e, tag.type);
  2833. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  2834. } else {
  2835. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  2836. }
  2837. }
  2838. lb_emit_if(p, cond, body, next_cond);
  2839. lb_start_block(p, next_cond);
  2840. }
  2841. lb_start_block(p, body);
  2842. lb_push_target_list(p, ss->label, done, nullptr, fall);
  2843. lb_open_scope(p);
  2844. lb_build_stmt_list(p, cc->stmts);
  2845. lb_close_scope(p, lbDeferExit_Default, body);
  2846. lb_pop_target_list(p);
  2847. lb_emit_jump(p, done);
  2848. lb_start_block(p, next_cond);
  2849. }
  2850. if (default_block != nullptr) {
  2851. lb_emit_jump(p, default_block);
  2852. lb_start_block(p, default_block);
  2853. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  2854. lb_open_scope(p);
  2855. lb_build_stmt_list(p, default_stmts);
  2856. lb_close_scope(p, lbDeferExit_Default, default_block);
  2857. lb_pop_target_list(p);
  2858. }
  2859. lb_emit_jump(p, done);
  2860. lb_start_block(p, done);
  2861. }
  2862. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  2863. Entity *e = implicit_entity_of_node(clause);
  2864. GB_ASSERT(e != nullptr);
  2865. if (e->flags & EntityFlag_Value) {
  2866. // by value
  2867. GB_ASSERT(are_types_identical(e->type, value.type));
  2868. lbAddr x = lb_add_local(p, e->type, e, false);
  2869. lb_addr_store(p, x, value);
  2870. } else {
  2871. // by reference
  2872. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  2873. lb_add_entity(p->module, e, value);
  2874. }
  2875. }
  2876. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  2877. Entity *e = entity_of_node(stmt_val);
  2878. if (e == nullptr) {
  2879. return {};
  2880. }
  2881. if ((e->flags & EntityFlag_Value) == 0) {
  2882. if (LLVMIsALoadInst(value.value)) {
  2883. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  2884. lb_add_entity(p->module, e, ptr);
  2885. return lb_addr(ptr);
  2886. }
  2887. }
  2888. // by value
  2889. lbAddr addr = lb_add_local(p, e->type, e, false);
  2890. lb_addr_store(p, addr, value);
  2891. return addr;
  2892. }
  2893. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  2894. ast_node(cc, CaseClause, clause);
  2895. lb_push_target_list(p, label, done, nullptr, nullptr);
  2896. lb_open_scope(p);
  2897. lb_build_stmt_list(p, cc->stmts);
  2898. lb_close_scope(p, lbDeferExit_Default, body);
  2899. lb_pop_target_list(p);
  2900. lb_emit_jump(p, done);
  2901. }
  2902. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  2903. lbModule *m = p->module;
  2904. ast_node(as, AssignStmt, ss->tag);
  2905. GB_ASSERT(as->lhs.count == 1);
  2906. GB_ASSERT(as->rhs.count == 1);
  2907. lbValue parent = lb_build_expr(p, as->rhs[0]);
  2908. bool is_parent_ptr = is_type_pointer(parent.type);
  2909. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  2910. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  2911. lbValue parent_value = parent;
  2912. lbValue parent_ptr = parent;
  2913. if (!is_parent_ptr) {
  2914. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  2915. }
  2916. lbValue tag_index = {};
  2917. lbValue union_data = {};
  2918. if (switch_kind == TypeSwitch_Union) {
  2919. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  2920. tag_index = lb_emit_load(p, tag_ptr);
  2921. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  2922. }
  2923. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  2924. lb_emit_jump(p, start_block);
  2925. lb_start_block(p, start_block);
  2926. // NOTE(bill): Append this later
  2927. lbBlock *done = lb_create_block(p, "typeswitch.done");
  2928. Ast *default_ = nullptr;
  2929. ast_node(body, BlockStmt, ss->body);
  2930. gb_local_persist i32 weird_count = 0;
  2931. for_array(i, body->stmts) {
  2932. Ast *clause = body->stmts[i];
  2933. ast_node(cc, CaseClause, clause);
  2934. if (cc->list.count == 0) {
  2935. default_ = clause;
  2936. continue;
  2937. }
  2938. lbBlock *body = lb_create_block(p, "typeswitch.body");
  2939. lbBlock *next = nullptr;
  2940. Type *case_type = nullptr;
  2941. for_array(type_index, cc->list) {
  2942. next = lb_create_block(p, "typeswitch.next");
  2943. case_type = type_of_expr(cc->list[type_index]);
  2944. lbValue cond = {};
  2945. if (switch_kind == TypeSwitch_Union) {
  2946. Type *ut = base_type(type_deref(parent.type));
  2947. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  2948. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  2949. } else if (switch_kind == TypeSwitch_Any) {
  2950. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  2951. lbValue case_typeid = lb_typeid(m, case_type);
  2952. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  2953. }
  2954. GB_ASSERT(cond.value != nullptr);
  2955. lb_emit_if(p, cond, body, next);
  2956. lb_start_block(p, next);
  2957. }
  2958. Entity *case_entity = implicit_entity_of_node(clause);
  2959. lbValue value = parent_value;
  2960. lb_start_block(p, body);
  2961. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  2962. if (cc->list.count == 1) {
  2963. lbValue data = {};
  2964. if (switch_kind == TypeSwitch_Union) {
  2965. data = union_data;
  2966. } else if (switch_kind == TypeSwitch_Any) {
  2967. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  2968. data = any_data;
  2969. }
  2970. Type *ct = case_entity->type;
  2971. Type *ct_ptr = alloc_type_pointer(ct);
  2972. value = lb_emit_conv(p, data, ct_ptr);
  2973. if (!by_reference) {
  2974. value = lb_emit_load(p, value);
  2975. }
  2976. }
  2977. lb_store_type_case_implicit(p, clause, value);
  2978. lb_type_case_body(p, ss->label, clause, body, done);
  2979. lb_start_block(p, next);
  2980. }
  2981. if (default_ != nullptr) {
  2982. lb_store_type_case_implicit(p, default_, parent_value);
  2983. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  2984. } else {
  2985. lb_emit_jump(p, done);
  2986. }
  2987. lb_start_block(p, done);
  2988. }
  2989. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  2990. lbModule *m = p->module;
  2991. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  2992. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  2993. type = default_type(type);
  2994. lbValue short_circuit = {};
  2995. if (op == Token_CmpAnd) {
  2996. lb_build_cond(p, left, rhs, done);
  2997. short_circuit = lb_const_bool(m, type, false);
  2998. } else if (op == Token_CmpOr) {
  2999. lb_build_cond(p, left, done, rhs);
  3000. short_circuit = lb_const_bool(m, type, true);
  3001. }
  3002. if (rhs->preds.count == 0) {
  3003. lb_start_block(p, done);
  3004. return short_circuit;
  3005. }
  3006. if (done->preds.count == 0) {
  3007. lb_start_block(p, rhs);
  3008. return lb_build_expr(p, right);
  3009. }
  3010. Array<LLVMValueRef> incoming_values = {};
  3011. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3012. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3013. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3014. for_array(i, done->preds) {
  3015. incoming_values[i] = short_circuit.value;
  3016. incoming_blocks[i] = done->preds[i]->block;
  3017. }
  3018. lb_start_block(p, rhs);
  3019. lbValue edge = lb_build_expr(p, right);
  3020. incoming_values[done->preds.count] = edge.value;
  3021. incoming_blocks[done->preds.count] = p->curr_block->block;
  3022. lb_emit_jump(p, done);
  3023. lb_start_block(p, done);
  3024. lbValue res = {};
  3025. res.type = type;
  3026. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3027. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3028. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3029. return res;
  3030. }
  3031. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3032. switch (node->kind) {
  3033. case_ast_node(bs, EmptyStmt, node);
  3034. case_end;
  3035. case_ast_node(us, UsingStmt, node);
  3036. case_end;
  3037. case_ast_node(ws, WhenStmt, node);
  3038. lb_build_when_stmt(p, ws);
  3039. case_end;
  3040. case_ast_node(bs, BlockStmt, node);
  3041. if (bs->label != nullptr) {
  3042. lbBlock *done = lb_create_block(p, "block.done");
  3043. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3044. tl->is_block = true;
  3045. lb_open_scope(p);
  3046. lb_build_stmt_list(p, bs->stmts);
  3047. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3048. lb_emit_jump(p, done);
  3049. lb_start_block(p, done);
  3050. } else {
  3051. lb_open_scope(p);
  3052. lb_build_stmt_list(p, bs->stmts);
  3053. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3054. }
  3055. case_end;
  3056. case_ast_node(vd, ValueDecl, node);
  3057. if (!vd->is_mutable) {
  3058. return;
  3059. }
  3060. bool is_static = false;
  3061. if (vd->names.count > 0) {
  3062. Entity *e = entity_of_ident(vd->names[0]);
  3063. if (e->flags & EntityFlag_Static) {
  3064. // NOTE(bill): If one of the entities is static, they all are
  3065. is_static = true;
  3066. }
  3067. }
  3068. if (is_static) {
  3069. for_array(i, vd->names) {
  3070. lbValue value = {};
  3071. if (vd->values.count > 0) {
  3072. GB_ASSERT(vd->names.count == vd->values.count);
  3073. Ast *ast_value = vd->values[i];
  3074. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3075. ast_value->tav.mode == Addressing_Invalid);
  3076. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value);
  3077. }
  3078. Ast *ident = vd->names[i];
  3079. GB_ASSERT(!is_blank_ident(ident));
  3080. Entity *e = entity_of_ident(ident);
  3081. GB_ASSERT(e->flags & EntityFlag_Static);
  3082. String name = e->token.string;
  3083. String mangled_name = {};
  3084. {
  3085. gbString str = gb_string_make_length(heap_allocator(), p->name.text, p->name.len);
  3086. str = gb_string_appendc(str, "-");
  3087. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3088. mangled_name.text = cast(u8 *)str;
  3089. mangled_name.len = gb_string_length(str);
  3090. }
  3091. char *c_name = alloc_cstring(heap_allocator(), mangled_name);
  3092. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3093. if (value.value != nullptr) {
  3094. LLVMSetInitializer(global, value.value);
  3095. } else {
  3096. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3097. }
  3098. if (e->Variable.thread_local_model != "") {
  3099. LLVMSetThreadLocal(global, true);
  3100. String m = e->Variable.thread_local_model;
  3101. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3102. if (m == "default") {
  3103. mode = LLVMGeneralDynamicTLSModel;
  3104. } else if (m == "localdynamic") {
  3105. mode = LLVMLocalDynamicTLSModel;
  3106. } else if (m == "initialexec") {
  3107. mode = LLVMInitialExecTLSModel;
  3108. } else if (m == "localexec") {
  3109. mode = LLVMLocalExecTLSModel;
  3110. } else {
  3111. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3112. }
  3113. LLVMSetThreadLocalMode(global, mode);
  3114. } else {
  3115. LLVMSetLinkage(global, LLVMInternalLinkage);
  3116. }
  3117. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3118. lb_add_entity(p->module, e, global_val);
  3119. lb_add_member(p->module, mangled_name, global_val);
  3120. }
  3121. return;
  3122. }
  3123. if (vd->values.count == 0) { // declared and zero-initialized
  3124. for_array(i, vd->names) {
  3125. Ast *name = vd->names[i];
  3126. if (!is_blank_ident(name)) {
  3127. Entity *e = entity_of_ident(name);
  3128. lb_add_local(p, e->type, e, true);
  3129. }
  3130. }
  3131. } else { // Tuple(s)
  3132. auto lvals = array_make<lbAddr>(heap_allocator(), 0, vd->names.count);
  3133. auto inits = array_make<lbValue>(heap_allocator(), 0, vd->names.count);
  3134. for_array(i, vd->names) {
  3135. Ast *name = vd->names[i];
  3136. lbAddr lval = {};
  3137. if (!is_blank_ident(name)) {
  3138. Entity *e = entity_of_ident(name);
  3139. lval = lb_add_local(p, e->type, e, false);
  3140. }
  3141. array_add(&lvals, lval);
  3142. }
  3143. for_array(i, vd->values) {
  3144. lbValue init = lb_build_expr(p, vd->values[i]);
  3145. Type *t = init.type;
  3146. if (t->kind == Type_Tuple) {
  3147. for_array(i, t->Tuple.variables) {
  3148. Entity *e = t->Tuple.variables[i];
  3149. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3150. array_add(&inits, v);
  3151. }
  3152. } else {
  3153. array_add(&inits, init);
  3154. }
  3155. }
  3156. for_array(i, inits) {
  3157. lbAddr lval = lvals[i];
  3158. lbValue init = inits[i];
  3159. lb_addr_store(p, lval, init);
  3160. }
  3161. }
  3162. case_end;
  3163. case_ast_node(as, AssignStmt, node);
  3164. if (as->op.kind == Token_Eq) {
  3165. auto lvals = array_make<lbAddr>(heap_allocator(), 0, as->lhs.count);
  3166. for_array(i, as->lhs) {
  3167. Ast *lhs = as->lhs[i];
  3168. lbAddr lval = {};
  3169. if (!is_blank_ident(lhs)) {
  3170. lval = lb_build_addr(p, lhs);
  3171. }
  3172. array_add(&lvals, lval);
  3173. }
  3174. if (as->lhs.count == as->rhs.count) {
  3175. if (as->lhs.count == 1) {
  3176. lbAddr lval = lvals[0];
  3177. Ast *rhs = as->rhs[0];
  3178. lbValue init = lb_build_expr(p, rhs);
  3179. lb_addr_store(p, lvals[0], init);
  3180. } else {
  3181. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  3182. for_array(i, as->rhs) {
  3183. lbValue init = lb_build_expr(p, as->rhs[i]);
  3184. array_add(&inits, init);
  3185. }
  3186. for_array(i, inits) {
  3187. lbAddr lval = lvals[i];
  3188. lbValue init = inits[i];
  3189. lb_addr_store(p, lval, init);
  3190. }
  3191. }
  3192. } else {
  3193. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  3194. for_array(i, as->rhs) {
  3195. lbValue init = lb_build_expr(p, as->rhs[i]);
  3196. Type *t = init.type;
  3197. // TODO(bill): refactor for code reuse as this is repeated a bit
  3198. if (t->kind == Type_Tuple) {
  3199. for_array(i, t->Tuple.variables) {
  3200. Entity *e = t->Tuple.variables[i];
  3201. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3202. array_add(&inits, v);
  3203. }
  3204. } else {
  3205. array_add(&inits, init);
  3206. }
  3207. }
  3208. for_array(i, inits) {
  3209. lbAddr lval = lvals[i];
  3210. lbValue init = inits[i];
  3211. lb_addr_store(p, lval, init);
  3212. }
  3213. }
  3214. } else {
  3215. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  3216. // +=, -=, etc
  3217. i32 op = cast(i32)as->op.kind;
  3218. op += Token_Add - Token_AddEq; // Convert += to +
  3219. if (op == Token_CmpAnd || op == Token_CmpOr) {
  3220. Type *type = as->lhs[0]->tav.type;
  3221. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  3222. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3223. lb_addr_store(p, lhs, new_value);
  3224. } else {
  3225. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3226. lbValue value = lb_build_expr(p, as->rhs[0]);
  3227. lbValue old_value = lb_addr_load(p, lhs);
  3228. Type *type = old_value.type;
  3229. lbValue change = lb_emit_conv(p, value, type);
  3230. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  3231. lb_addr_store(p, lhs, new_value);
  3232. }
  3233. return;
  3234. }
  3235. case_end;
  3236. case_ast_node(es, ExprStmt, node);
  3237. lb_build_expr(p, es->expr);
  3238. case_end;
  3239. case_ast_node(ds, DeferStmt, node);
  3240. isize scope_index = p->scope_index;
  3241. lb_add_defer_node(p, scope_index, ds->stmt);
  3242. case_end;
  3243. case_ast_node(rs, ReturnStmt, node);
  3244. lbValue res = {};
  3245. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  3246. isize return_count = p->type->Proc.result_count;
  3247. isize res_count = rs->results.count;
  3248. if (return_count == 0) {
  3249. // No return values
  3250. LLVMBuildRetVoid(p->builder);
  3251. return;
  3252. } else if (return_count == 1) {
  3253. Entity *e = tuple->variables[0];
  3254. if (res_count == 0) {
  3255. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3256. GB_ASSERT(found);
  3257. res = lb_emit_load(p, *found);
  3258. } else {
  3259. res = lb_build_expr(p, rs->results[0]);
  3260. res = lb_emit_conv(p, res, e->type);
  3261. }
  3262. } else {
  3263. auto results = array_make<lbValue>(heap_allocator(), 0, return_count);
  3264. if (res_count != 0) {
  3265. for (isize res_index = 0; res_index < res_count; res_index++) {
  3266. lbValue res = lb_build_expr(p, rs->results[res_index]);
  3267. Type *t = res.type;
  3268. if (t->kind == Type_Tuple) {
  3269. for_array(i, t->Tuple.variables) {
  3270. Entity *e = t->Tuple.variables[i];
  3271. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  3272. array_add(&results, v);
  3273. }
  3274. } else {
  3275. array_add(&results, res);
  3276. }
  3277. }
  3278. } else {
  3279. for (isize res_index = 0; res_index < return_count; res_index++) {
  3280. Entity *e = tuple->variables[res_index];
  3281. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3282. GB_ASSERT(found);
  3283. lbValue res = lb_emit_load(p, *found);
  3284. array_add(&results, res);
  3285. }
  3286. }
  3287. GB_ASSERT(results.count == return_count);
  3288. Type *ret_type = p->type->Proc.results;
  3289. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3290. res = lb_add_local_generated(p, ret_type, false).addr;
  3291. for_array(i, results) {
  3292. Entity *e = tuple->variables[i];
  3293. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  3294. lbValue val = lb_emit_conv(p, results[i], e->type);
  3295. lb_emit_store(p, field, val);
  3296. }
  3297. res = lb_emit_load(p, res);
  3298. }
  3299. if (p->type->Proc.return_by_pointer) {
  3300. if (res.value != nullptr) {
  3301. lb_addr_store(p, p->return_ptr, res);
  3302. } else {
  3303. lb_addr_store(p, p->return_ptr, lb_const_nil(p->module, p->type->Proc.abi_compat_result_type));
  3304. }
  3305. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3306. LLVMBuildRetVoid(p->builder);
  3307. } else {
  3308. GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name));
  3309. Type *abi_rt = p->type->Proc.abi_compat_result_type;
  3310. if (!are_types_identical(res.type, abi_rt)) {
  3311. res = lb_emit_transmute(p, res, abi_rt);
  3312. }
  3313. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3314. LLVMBuildRet(p->builder, res.value);
  3315. }
  3316. case_end;
  3317. case_ast_node(is, IfStmt, node);
  3318. lb_open_scope(p); // Scope #1
  3319. if (is->init != nullptr) {
  3320. // TODO(bill): Should this have a separate block to begin with?
  3321. #if 1
  3322. lbBlock *init = lb_create_block(p, "if.init");
  3323. lb_emit_jump(p, init);
  3324. lb_start_block(p, init);
  3325. #endif
  3326. lb_build_stmt(p, is->init);
  3327. }
  3328. lbBlock *then = lb_create_block(p, "if.then");
  3329. lbBlock *done = lb_create_block(p, "if.done");
  3330. lbBlock *else_ = done;
  3331. if (is->else_stmt != nullptr) {
  3332. else_ = lb_create_block(p, "if.else");
  3333. }
  3334. lb_build_cond(p, is->cond, then, else_);
  3335. lb_start_block(p, then);
  3336. if (is->label != nullptr) {
  3337. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  3338. tl->is_block = true;
  3339. }
  3340. lb_build_stmt(p, is->body);
  3341. lb_emit_jump(p, done);
  3342. if (is->else_stmt != nullptr) {
  3343. lb_start_block(p, else_);
  3344. lb_open_scope(p);
  3345. lb_build_stmt(p, is->else_stmt);
  3346. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3347. lb_emit_jump(p, done);
  3348. }
  3349. lb_start_block(p, done);
  3350. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3351. case_end;
  3352. case_ast_node(fs, ForStmt, node);
  3353. lb_open_scope(p); // Open Scope here
  3354. if (fs->init != nullptr) {
  3355. #if 1
  3356. lbBlock *init = lb_create_block(p, "for.init");
  3357. lb_emit_jump(p, init);
  3358. lb_start_block(p, init);
  3359. #endif
  3360. lb_build_stmt(p, fs->init);
  3361. }
  3362. lbBlock *body = lb_create_block(p, "for.body");
  3363. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  3364. lbBlock *loop = body;
  3365. if (fs->cond != nullptr) {
  3366. loop = lb_create_block(p, "for.loop");
  3367. }
  3368. lbBlock *post = loop;
  3369. if (fs->post != nullptr) {
  3370. post = lb_create_block(p, "for.post");
  3371. }
  3372. lb_emit_jump(p, loop);
  3373. lb_start_block(p, loop);
  3374. if (loop != body) {
  3375. lb_build_cond(p, fs->cond, body, done);
  3376. lb_start_block(p, body);
  3377. }
  3378. lb_push_target_list(p, fs->label, done, post, nullptr);
  3379. lb_build_stmt(p, fs->body);
  3380. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3381. lb_pop_target_list(p);
  3382. lb_emit_jump(p, post);
  3383. if (fs->post != nullptr) {
  3384. lb_start_block(p, post);
  3385. lb_build_stmt(p, fs->post);
  3386. lb_emit_jump(p, loop);
  3387. }
  3388. lb_start_block(p, done);
  3389. case_end;
  3390. case_ast_node(rs, RangeStmt, node);
  3391. lb_build_range_stmt(p, rs);
  3392. case_end;
  3393. case_ast_node(rs, InlineRangeStmt, node);
  3394. lb_build_inline_range_stmt(p, rs);
  3395. case_end;
  3396. case_ast_node(ss, SwitchStmt, node);
  3397. lb_build_switch_stmt(p, ss);
  3398. case_end;
  3399. case_ast_node(ss, TypeSwitchStmt, node);
  3400. lb_build_type_switch_stmt(p, ss);
  3401. case_end;
  3402. case_ast_node(bs, BranchStmt, node);
  3403. lbBlock *block = nullptr;
  3404. if (bs->label != nullptr) {
  3405. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  3406. switch (bs->token.kind) {
  3407. case Token_break: block = bb.break_; break;
  3408. case Token_continue: block = bb.continue_; break;
  3409. case Token_fallthrough:
  3410. GB_PANIC("fallthrough cannot have a label");
  3411. break;
  3412. }
  3413. } else {
  3414. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  3415. if (t->is_block) {
  3416. continue;
  3417. }
  3418. switch (bs->token.kind) {
  3419. case Token_break: block = t->break_; break;
  3420. case Token_continue: block = t->continue_; break;
  3421. case Token_fallthrough: block = t->fallthrough_; break;
  3422. }
  3423. }
  3424. }
  3425. if (block != nullptr) {
  3426. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  3427. }
  3428. lb_emit_jump(p, block);
  3429. case_end;
  3430. }
  3431. }
  3432. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  3433. cond = lb_emit_conv(p, cond, t_llvm_bool);
  3434. lbValue res = {};
  3435. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  3436. res.type = x.type;
  3437. return res;
  3438. }
  3439. lbValue lb_const_nil(lbModule *m, Type *type) {
  3440. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  3441. return lbValue{v, type};
  3442. }
  3443. lbValue lb_const_undef(lbModule *m, Type *type) {
  3444. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  3445. return lbValue{v, type};
  3446. }
  3447. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  3448. lbValue res = {};
  3449. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  3450. res.type = type;
  3451. return res;
  3452. }
  3453. lbValue lb_const_string(lbModule *m, String const &value) {
  3454. return lb_const_value(m, t_string, exact_value_string(value));
  3455. }
  3456. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  3457. lbValue res = {};
  3458. res.value = LLVMConstInt(lb_type(m, type), value, false);
  3459. res.type = type;
  3460. return res;
  3461. }
  3462. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  3463. GB_ASSERT(type_size_of(type) == 4);
  3464. u32 u = bit_cast<u32>(f);
  3465. if (is_type_different_to_arch_endianness(type)) {
  3466. u = gb_endian_swap32(u);
  3467. }
  3468. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  3469. return LLVMConstBitCast(i, lb_type(m, type));
  3470. }
  3471. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3472. x = lb_emit_conv(p, x, t);
  3473. y = lb_emit_conv(p, y, t);
  3474. if (is_type_float(t)) {
  3475. gbAllocator a = heap_allocator();
  3476. i64 sz = 8*type_size_of(t);
  3477. auto args = array_make<lbValue>(heap_allocator(), 2);
  3478. args[0] = x;
  3479. args[1] = y;
  3480. switch (sz) {
  3481. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  3482. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  3483. }
  3484. GB_PANIC("Unknown float type");
  3485. }
  3486. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  3487. }
  3488. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3489. x = lb_emit_conv(p, x, t);
  3490. y = lb_emit_conv(p, y, t);
  3491. if (is_type_float(t)) {
  3492. gbAllocator a = heap_allocator();
  3493. i64 sz = 8*type_size_of(t);
  3494. auto args = array_make<lbValue>(heap_allocator(), 2);
  3495. args[0] = x;
  3496. args[1] = y;
  3497. switch (sz) {
  3498. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  3499. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  3500. }
  3501. GB_PANIC("Unknown float type");
  3502. }
  3503. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  3504. }
  3505. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  3506. lbValue z = {};
  3507. z = lb_emit_max(p, t, x, min);
  3508. z = lb_emit_min(p, t, z, max);
  3509. return z;
  3510. }
  3511. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  3512. StringHashKey key = string_hash_string(str);
  3513. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  3514. if (found != nullptr) {
  3515. return *found;
  3516. } else {
  3517. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  3518. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3519. cast(char const *)str.text,
  3520. cast(unsigned)str.len,
  3521. false);
  3522. isize max_len = 7+8+1;
  3523. char *name = gb_alloc_array(heap_allocator(), char, max_len);
  3524. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3525. len -= 1;
  3526. m->global_array_index++;
  3527. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3528. LLVMSetInitializer(global_data, data);
  3529. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3530. string_map_set(&m->const_strings, key, ptr);
  3531. return ptr;
  3532. }
  3533. }
  3534. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  3535. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, str);
  3536. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3537. LLVMValueRef values[2] = {ptr, str_len};
  3538. lbValue res = {};
  3539. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  3540. res.type = t_string;
  3541. return res;
  3542. }
  3543. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  3544. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  3545. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3546. cast(char const *)str.text,
  3547. cast(unsigned)str.len,
  3548. false);
  3549. char *name = nullptr;
  3550. {
  3551. isize max_len = 7+8+1;
  3552. name = gb_alloc_array(heap_allocator(), char, max_len);
  3553. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3554. len -= 1;
  3555. m->global_array_index++;
  3556. }
  3557. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3558. LLVMSetInitializer(global_data, data);
  3559. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3560. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3561. LLVMValueRef values[2] = {ptr, len};
  3562. lbValue res = {};
  3563. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  3564. res.type = t_u8_slice;
  3565. return res;
  3566. }
  3567. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  3568. isize index = type_info_index(info, type, false);
  3569. if (index >= 0) {
  3570. auto *set = &info->minimum_dependency_type_info_set;
  3571. for_array(i, set->entries) {
  3572. if (set->entries[i].ptr == index) {
  3573. return i+1;
  3574. }
  3575. }
  3576. }
  3577. if (err_on_not_found) {
  3578. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  3579. }
  3580. return -1;
  3581. }
  3582. lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type) {
  3583. type = default_type(type);
  3584. u64 id = cast(u64)lb_type_info_index(m->info, type);
  3585. GB_ASSERT(id >= 0);
  3586. u64 kind = Typeid_Invalid;
  3587. u64 named = is_type_named(type) && type->kind != Type_Basic;
  3588. u64 special = 0;
  3589. u64 reserved = 0;
  3590. Type *bt = base_type(type);
  3591. TypeKind tk = bt->kind;
  3592. switch (tk) {
  3593. case Type_Basic: {
  3594. u32 flags = bt->Basic.flags;
  3595. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  3596. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  3597. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  3598. if (flags & BasicFlag_Float) kind = Typeid_Float;
  3599. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  3600. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  3601. if (flags & BasicFlag_String) kind = Typeid_String;
  3602. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  3603. } break;
  3604. case Type_Pointer: kind = Typeid_Pointer; break;
  3605. case Type_Array: kind = Typeid_Array; break;
  3606. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  3607. case Type_Slice: kind = Typeid_Slice; break;
  3608. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  3609. case Type_Map: kind = Typeid_Map; break;
  3610. case Type_Struct: kind = Typeid_Struct; break;
  3611. case Type_Enum: kind = Typeid_Enum; break;
  3612. case Type_Union: kind = Typeid_Union; break;
  3613. case Type_Tuple: kind = Typeid_Tuple; break;
  3614. case Type_Proc: kind = Typeid_Procedure; break;
  3615. case Type_BitField: kind = Typeid_Bit_Field; break;
  3616. case Type_BitSet: kind = Typeid_Bit_Set; break;
  3617. }
  3618. if (is_type_cstring(type)) {
  3619. special = 1;
  3620. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  3621. special = 1;
  3622. }
  3623. u64 data = 0;
  3624. if (build_context.word_size == 4) {
  3625. data |= (id &~ (1u<<24)) << 0u; // index
  3626. data |= (kind &~ (1u<<5)) << 24u; // kind
  3627. data |= (named &~ (1u<<1)) << 29u; // kind
  3628. data |= (special &~ (1u<<1)) << 30u; // kind
  3629. data |= (reserved &~ (1u<<1)) << 31u; // kind
  3630. } else {
  3631. GB_ASSERT(build_context.word_size == 8);
  3632. data |= (id &~ (1ull<<56)) << 0ul; // index
  3633. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  3634. data |= (named &~ (1ull<<1)) << 61ull; // kind
  3635. data |= (special &~ (1ull<<1)) << 62ull; // kind
  3636. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  3637. }
  3638. lbValue res = {};
  3639. res.value = LLVMConstInt(lb_type(m, typeid_type), data, false);
  3640. res.type = typeid_type;
  3641. return res;
  3642. }
  3643. lbValue lb_type_info(lbModule *m, Type *type) {
  3644. type = default_type(type);
  3645. isize index = lb_type_info_index(m->info, type);
  3646. GB_ASSERT(index >= 0);
  3647. LLVMTypeRef it = lb_type(m, t_int);
  3648. LLVMValueRef indices[2] = {
  3649. LLVMConstInt(it, 0, false),
  3650. LLVMConstInt(it, index, true),
  3651. };
  3652. lbValue value = {};
  3653. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  3654. value.type = t_type_info_ptr;
  3655. return value;
  3656. }
  3657. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) {
  3658. LLVMContextRef ctx = m->ctx;
  3659. type = default_type(type);
  3660. Type *original_type = type;
  3661. lbValue res = {};
  3662. res.type = original_type;
  3663. type = core_type(type);
  3664. value = convert_exact_value_for_type(value, type);
  3665. if (value.kind == ExactValue_Typeid) {
  3666. return lb_typeid(m, value.value_typeid, original_type);
  3667. }
  3668. if (value.kind == ExactValue_Invalid) {
  3669. return lb_const_nil(m, type);
  3670. }
  3671. if (value.kind == ExactValue_Procedure) {
  3672. Ast *expr = value.value_procedure;
  3673. if (expr->kind == Ast_ProcLit) {
  3674. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  3675. }
  3676. Entity *e = entity_from_expr(expr);
  3677. e = strip_entity_wrapping(e);
  3678. GB_ASSERT(e != nullptr);
  3679. auto *found = map_get(&m->values, hash_entity(e));
  3680. if (found) {
  3681. return *found;
  3682. }
  3683. GB_PANIC("Error in: %.*s(%td:%td), missing procedure %.*s\n", LIT(e->token.pos.file), e->token.pos.line, e->token.pos.column, LIT(e->token.string));
  3684. }
  3685. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  3686. if (is_type_slice(type)) {
  3687. if (value.kind == ExactValue_String) {
  3688. GB_ASSERT(is_type_u8_slice(type));
  3689. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  3690. return res;
  3691. } else {
  3692. ast_node(cl, CompoundLit, value.value_compound);
  3693. isize count = cl->elems.count;
  3694. if (count == 0) {
  3695. return lb_const_nil(m, type);
  3696. }
  3697. count = gb_max(cl->max_count, count);
  3698. Type *elem = base_type(type)->Slice.elem;
  3699. Type *t = alloc_type_array(elem, count);
  3700. lbValue backing_array = lb_const_value(m, t, value);
  3701. isize max_len = 7+8+1;
  3702. char *str = gb_alloc_array(heap_allocator(), char, max_len);
  3703. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  3704. m->global_array_index++;
  3705. String name = make_string(cast(u8 *)str, len-1);
  3706. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  3707. LLVMValueRef global_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  3708. LLVMSetInitializer(global_data, backing_array.value);
  3709. lbValue g = {};
  3710. g.value = global_data;
  3711. g.type = t;
  3712. lb_add_entity(m, e, g);
  3713. lb_add_member(m, name, g);
  3714. {
  3715. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  3716. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3717. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  3718. LLVMValueRef values[2] = {ptr, len};
  3719. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3720. return res;
  3721. }
  3722. }
  3723. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  3724. LLVMValueRef data = LLVMConstStringInContext(ctx,
  3725. cast(char const *)value.value_string.text,
  3726. cast(unsigned)value.value_string.len,
  3727. false);
  3728. res.value = data;
  3729. return res;
  3730. } else if (is_type_array(type) &&
  3731. value.kind != ExactValue_Invalid &&
  3732. value.kind != ExactValue_String &&
  3733. value.kind != ExactValue_Compound) {
  3734. i64 count = type->Array.count;
  3735. Type *elem = type->Array.elem;
  3736. lbValue single_elem = lb_const_value(m, elem, value);
  3737. LLVMValueRef *elems = gb_alloc_array(heap_allocator(), LLVMValueRef, count);
  3738. for (i64 i = 0; i < count; i++) {
  3739. elems[i] = single_elem.value;
  3740. }
  3741. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  3742. return res;
  3743. }
  3744. switch (value.kind) {
  3745. case ExactValue_Invalid:
  3746. res.value = LLVMConstNull(lb_type(m, original_type));
  3747. return res;
  3748. case ExactValue_Bool:
  3749. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  3750. return res;
  3751. case ExactValue_String:
  3752. {
  3753. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  3754. lbValue res = {};
  3755. res.type = default_type(original_type);
  3756. if (is_type_cstring(res.type)) {
  3757. res.value = ptr;
  3758. } else {
  3759. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  3760. LLVMValueRef values[2] = {ptr, str_len};
  3761. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3762. }
  3763. return res;
  3764. }
  3765. case ExactValue_Integer:
  3766. if (is_type_pointer(type)) {
  3767. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  3768. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  3769. } else {
  3770. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  3771. if (value.value_integer.neg) {
  3772. res.value = LLVMConstNeg(res.value);
  3773. }
  3774. }
  3775. return res;
  3776. case ExactValue_Float:
  3777. if (type_size_of(type) == 4) {
  3778. f32 f = cast(f32)value.value_float;
  3779. res.value = lb_const_f32(m, f, type);
  3780. return res;
  3781. }
  3782. if (is_type_different_to_arch_endianness(type)) {
  3783. u64 u = bit_cast<u64>(value.value_float);
  3784. u = gb_endian_swap64(u);
  3785. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  3786. } else {
  3787. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  3788. }
  3789. return res;
  3790. case ExactValue_Complex:
  3791. {
  3792. LLVMValueRef values[2] = {};
  3793. switch (8*type_size_of(type)) {
  3794. case 64:
  3795. values[0] = lb_const_f32(m, cast(f32)value.value_complex.real);
  3796. values[1] = lb_const_f32(m, cast(f32)value.value_complex.imag);
  3797. break;
  3798. case 128:
  3799. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real);
  3800. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.imag);
  3801. break;
  3802. }
  3803. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3804. return res;
  3805. }
  3806. break;
  3807. case ExactValue_Quaternion:
  3808. {
  3809. LLVMValueRef values[4] = {};
  3810. switch (8*type_size_of(type)) {
  3811. case 128:
  3812. // @QuaternionLayout
  3813. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion.real);
  3814. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion.imag);
  3815. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion.jmag);
  3816. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion.kmag);
  3817. break;
  3818. case 256:
  3819. // @QuaternionLayout
  3820. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.real);
  3821. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.imag);
  3822. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.jmag);
  3823. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.kmag);
  3824. break;
  3825. }
  3826. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  3827. return res;
  3828. }
  3829. break;
  3830. case ExactValue_Pointer:
  3831. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  3832. return res;
  3833. case ExactValue_Compound:
  3834. if (is_type_slice(type)) {
  3835. return lb_const_value(m, type, value);
  3836. } else if (is_type_array(type)) {
  3837. ast_node(cl, CompoundLit, value.value_compound);
  3838. Type *elem_type = type->Array.elem;
  3839. isize elem_count = cl->elems.count;
  3840. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  3841. return lb_const_nil(m, original_type);
  3842. }
  3843. if (cl->elems[0]->kind == Ast_FieldValue) {
  3844. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  3845. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  3846. defer (gb_free(heap_allocator(), values));
  3847. isize value_index = 0;
  3848. for (i64 i = 0; i < type->Array.count; i++) {
  3849. bool found = false;
  3850. for (isize j = 0; j < elem_count; j++) {
  3851. Ast *elem = cl->elems[j];
  3852. ast_node(fv, FieldValue, elem);
  3853. if (is_ast_range(fv->field)) {
  3854. ast_node(ie, BinaryExpr, fv->field);
  3855. TypeAndValue lo_tav = ie->left->tav;
  3856. TypeAndValue hi_tav = ie->right->tav;
  3857. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3858. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3859. TokenKind op = ie->op.kind;
  3860. i64 lo = exact_value_to_i64(lo_tav.value);
  3861. i64 hi = exact_value_to_i64(hi_tav.value);
  3862. if (op == Token_Ellipsis) {
  3863. hi += 1;
  3864. }
  3865. if (lo == i) {
  3866. TypeAndValue tav = fv->value->tav;
  3867. if (tav.mode != Addressing_Constant) {
  3868. break;
  3869. }
  3870. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3871. for (i64 k = lo; k < hi; k++) {
  3872. values[value_index++] = val;
  3873. }
  3874. found = true;
  3875. i += (hi-lo-1);
  3876. break;
  3877. }
  3878. } else {
  3879. TypeAndValue index_tav = fv->field->tav;
  3880. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3881. i64 index = exact_value_to_i64(index_tav.value);
  3882. if (index == i) {
  3883. TypeAndValue tav = fv->value->tav;
  3884. if (tav.mode != Addressing_Constant) {
  3885. break;
  3886. }
  3887. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3888. values[value_index++] = val;
  3889. found = true;
  3890. break;
  3891. }
  3892. }
  3893. }
  3894. if (!found) {
  3895. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  3896. }
  3897. }
  3898. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  3899. return res;
  3900. } else {
  3901. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  3902. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  3903. defer (gb_free(heap_allocator(), values));
  3904. for (isize i = 0; i < elem_count; i++) {
  3905. TypeAndValue tav = cl->elems[i]->tav;
  3906. GB_ASSERT(tav.mode != Addressing_Invalid);
  3907. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3908. }
  3909. for (isize i = elem_count; i < type->Array.count; i++) {
  3910. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3911. }
  3912. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  3913. return res;
  3914. }
  3915. } else if (is_type_enumerated_array(type)) {
  3916. ast_node(cl, CompoundLit, value.value_compound);
  3917. Type *elem_type = type->EnumeratedArray.elem;
  3918. isize elem_count = cl->elems.count;
  3919. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  3920. return lb_const_nil(m, original_type);
  3921. }
  3922. if (cl->elems[0]->kind == Ast_FieldValue) {
  3923. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  3924. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  3925. defer (gb_free(heap_allocator(), values));
  3926. isize value_index = 0;
  3927. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  3928. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  3929. for (i64 i = total_lo; i <= total_hi; i++) {
  3930. bool found = false;
  3931. for (isize j = 0; j < elem_count; j++) {
  3932. Ast *elem = cl->elems[j];
  3933. ast_node(fv, FieldValue, elem);
  3934. if (is_ast_range(fv->field)) {
  3935. ast_node(ie, BinaryExpr, fv->field);
  3936. TypeAndValue lo_tav = ie->left->tav;
  3937. TypeAndValue hi_tav = ie->right->tav;
  3938. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3939. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3940. TokenKind op = ie->op.kind;
  3941. i64 lo = exact_value_to_i64(lo_tav.value);
  3942. i64 hi = exact_value_to_i64(hi_tav.value);
  3943. if (op == Token_Ellipsis) {
  3944. hi += 1;
  3945. }
  3946. if (lo == i) {
  3947. TypeAndValue tav = fv->value->tav;
  3948. if (tav.mode != Addressing_Constant) {
  3949. break;
  3950. }
  3951. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3952. for (i64 k = lo; k < hi; k++) {
  3953. values[value_index++] = val;
  3954. }
  3955. found = true;
  3956. i += (hi-lo-1);
  3957. break;
  3958. }
  3959. } else {
  3960. TypeAndValue index_tav = fv->field->tav;
  3961. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3962. i64 index = exact_value_to_i64(index_tav.value);
  3963. if (index == i) {
  3964. TypeAndValue tav = fv->value->tav;
  3965. if (tav.mode != Addressing_Constant) {
  3966. break;
  3967. }
  3968. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3969. values[value_index++] = val;
  3970. found = true;
  3971. break;
  3972. }
  3973. }
  3974. }
  3975. if (!found) {
  3976. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  3977. }
  3978. }
  3979. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  3980. return res;
  3981. } else {
  3982. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  3983. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  3984. defer (gb_free(heap_allocator(), values));
  3985. for (isize i = 0; i < elem_count; i++) {
  3986. TypeAndValue tav = cl->elems[i]->tav;
  3987. GB_ASSERT(tav.mode != Addressing_Invalid);
  3988. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3989. }
  3990. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  3991. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3992. }
  3993. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  3994. return res;
  3995. }
  3996. } else if (is_type_simd_vector(type)) {
  3997. ast_node(cl, CompoundLit, value.value_compound);
  3998. Type *elem_type = type->SimdVector.elem;
  3999. isize elem_count = cl->elems.count;
  4000. if (elem_count == 0) {
  4001. return lb_const_nil(m, original_type);
  4002. }
  4003. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4004. isize total_elem_count = type->SimdVector.count;
  4005. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, total_elem_count);
  4006. defer (gb_free(heap_allocator(), values));
  4007. for (isize i = 0; i < elem_count; i++) {
  4008. TypeAndValue tav = cl->elems[i]->tav;
  4009. GB_ASSERT(tav.mode != Addressing_Invalid);
  4010. values[i] = lb_const_value(m, elem_type, tav.value).value;
  4011. }
  4012. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  4013. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4014. }
  4015. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  4016. return res;
  4017. } else if (is_type_struct(type)) {
  4018. ast_node(cl, CompoundLit, value.value_compound);
  4019. if (cl->elems.count == 0) {
  4020. return lb_const_nil(m, original_type);
  4021. }
  4022. isize offset = 0;
  4023. if (type->Struct.custom_align > 0) {
  4024. offset = 1;
  4025. }
  4026. isize value_count = type->Struct.fields.count + offset;
  4027. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, value_count);
  4028. bool *visited = gb_alloc_array(heap_allocator(), bool, value_count);
  4029. defer (gb_free(heap_allocator(), values));
  4030. defer (gb_free(heap_allocator(), visited));
  4031. if (cl->elems.count > 0) {
  4032. if (cl->elems[0]->kind == Ast_FieldValue) {
  4033. isize elem_count = cl->elems.count;
  4034. for (isize i = 0; i < elem_count; i++) {
  4035. ast_node(fv, FieldValue, cl->elems[i]);
  4036. String name = fv->field->Ident.token.string;
  4037. TypeAndValue tav = fv->value->tav;
  4038. GB_ASSERT(tav.mode != Addressing_Invalid);
  4039. Selection sel = lookup_field(type, name, false);
  4040. Entity *f = type->Struct.fields[sel.index[0]];
  4041. if (elem_type_can_be_constant(f->type)) {
  4042. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value).value;
  4043. visited[offset+f->Variable.field_index] = true;
  4044. }
  4045. }
  4046. } else {
  4047. for_array(i, cl->elems) {
  4048. Entity *f = type->Struct.fields[i];
  4049. TypeAndValue tav = cl->elems[i]->tav;
  4050. ExactValue val = {};
  4051. if (tav.mode != Addressing_Invalid) {
  4052. val = tav.value;
  4053. }
  4054. if (elem_type_can_be_constant(f->type)) {
  4055. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val).value;
  4056. visited[offset+f->Variable.field_index] = true;
  4057. }
  4058. }
  4059. }
  4060. }
  4061. for (isize i = 0; i < type->Struct.fields.count; i++) {
  4062. if (!visited[offset+i]) {
  4063. GB_ASSERT(values[offset+i] == nullptr);
  4064. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  4065. }
  4066. }
  4067. if (type->Struct.custom_align > 0) {
  4068. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  4069. }
  4070. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  4071. return res;
  4072. } else if (is_type_bit_set(type)) {
  4073. ast_node(cl, CompoundLit, value.value_compound);
  4074. if (cl->elems.count == 0) {
  4075. return lb_const_nil(m, original_type);
  4076. }
  4077. i64 sz = type_size_of(type);
  4078. if (sz == 0) {
  4079. return lb_const_nil(m, original_type);
  4080. }
  4081. u64 bits = 0;
  4082. for_array(i, cl->elems) {
  4083. Ast *e = cl->elems[i];
  4084. GB_ASSERT(e->kind != Ast_FieldValue);
  4085. TypeAndValue tav = e->tav;
  4086. if (tav.mode != Addressing_Constant) {
  4087. continue;
  4088. }
  4089. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  4090. i64 v = big_int_to_i64(&tav.value.value_integer);
  4091. i64 lower = type->BitSet.lower;
  4092. bits |= 1ull<<cast(u64)(v-lower);
  4093. }
  4094. if (is_type_different_to_arch_endianness(type)) {
  4095. i64 size = type_size_of(type);
  4096. switch (size) {
  4097. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  4098. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  4099. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  4100. }
  4101. }
  4102. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  4103. return res;
  4104. } else {
  4105. return lb_const_nil(m, original_type);
  4106. }
  4107. break;
  4108. case ExactValue_Procedure:
  4109. {
  4110. Ast *expr = value.value_procedure;
  4111. GB_ASSERT(expr != nullptr);
  4112. if (expr->kind == Ast_ProcLit) {
  4113. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4114. }
  4115. }
  4116. break;
  4117. case ExactValue_Typeid:
  4118. return lb_typeid(m, value.value_typeid, original_type);
  4119. }
  4120. return lb_const_nil(m, original_type);
  4121. }
  4122. u64 lb_generate_source_code_location_hash(TokenPos const &pos) {
  4123. u64 h = 0xcbf29ce484222325;
  4124. for (isize i = 0; i < pos.file.len; i++) {
  4125. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  4126. }
  4127. h = h ^ (u64(pos.line) * 0x100000001b3);
  4128. h = h ^ (u64(pos.column) * 0x100000001b3);
  4129. return h;
  4130. }
  4131. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  4132. lbModule *m = p->module;
  4133. LLVMValueRef fields[5] = {};
  4134. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  4135. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  4136. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  4137. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  4138. fields[4]/*hash*/ = lb_const_int(m, t_u64, lb_generate_source_code_location_hash(pos)).value;
  4139. lbValue res = {};
  4140. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, 5);
  4141. res.type = t_source_code_location;
  4142. return res;
  4143. }
  4144. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  4145. String proc_name = {};
  4146. if (p->entity) {
  4147. proc_name = p->entity->token.string;
  4148. }
  4149. TokenPos pos = {};
  4150. if (node) {
  4151. pos = ast_token(node).pos;
  4152. }
  4153. return lb_emit_source_code_location(p, proc_name, pos);
  4154. }
  4155. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  4156. switch (op) {
  4157. case Token_Add:
  4158. return x;
  4159. case Token_Not: // Boolean not
  4160. case Token_Xor: // Bitwise not
  4161. case Token_Sub: // Number negation
  4162. break;
  4163. case Token_Pointer:
  4164. GB_PANIC("This should be handled elsewhere");
  4165. break;
  4166. }
  4167. if (is_type_array(x.type)) {
  4168. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  4169. Type *tl = base_type(x.type);
  4170. lbValue val = lb_address_from_load_or_generate_local(p, x);
  4171. GB_ASSERT(is_type_array(type));
  4172. Type *elem_type = base_array_type(type);
  4173. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4174. lbAddr res_addr = lb_add_local_generated(p, type, false);
  4175. lbValue res = lb_addr_get_ptr(p, res_addr);
  4176. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4177. i32 count = cast(i32)tl->Array.count;
  4178. if (inline_array_arith) {
  4179. // inline
  4180. for (i32 i = 0; i < count; i++) {
  4181. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  4182. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4183. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  4184. }
  4185. } else {
  4186. auto loop_data = lb_loop_start(p, count, t_i32);
  4187. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  4188. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4189. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  4190. lb_loop_end(p, loop_data);
  4191. }
  4192. return lb_emit_load(p, res);
  4193. }
  4194. if (op == Token_Xor) {
  4195. lbValue cmp = {};
  4196. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  4197. cmp.type = x.type;
  4198. return lb_emit_conv(p, cmp, type);
  4199. }
  4200. if (op == Token_Not) {
  4201. lbValue cmp = {};
  4202. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  4203. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  4204. cmp.type = t_llvm_bool;
  4205. return lb_emit_conv(p, cmp, type);
  4206. }
  4207. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4208. Type *platform_type = integer_endian_type_to_platform_type(type);
  4209. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4210. lbValue res = {};
  4211. res.value = LLVMBuildNeg(p->builder, v.value, "");
  4212. res.type = platform_type;
  4213. return lb_emit_byte_swap(p, res, type);
  4214. }
  4215. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4216. Type *platform_type = integer_endian_type_to_platform_type(type);
  4217. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4218. lbValue res = {};
  4219. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  4220. res.type = platform_type;
  4221. return lb_emit_byte_swap(p, res, type);
  4222. }
  4223. lbValue res = {};
  4224. switch (op) {
  4225. case Token_Not: // Boolean not
  4226. case Token_Xor: // Bitwise not
  4227. res.value = LLVMBuildNot(p->builder, x.value, "");
  4228. res.type = x.type;
  4229. return res;
  4230. case Token_Sub: // Number negation
  4231. if (is_type_integer(x.type)) {
  4232. res.value = LLVMBuildNeg(p->builder, x.value, "");
  4233. } else if (is_type_float(x.type)) {
  4234. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  4235. } else if (is_type_complex(x.type)) {
  4236. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4237. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4238. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4239. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4240. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4241. return lb_addr_load(p, addr);
  4242. } else if (is_type_quaternion(x.type)) {
  4243. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4244. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4245. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  4246. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  4247. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4248. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4249. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4250. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  4251. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  4252. return lb_addr_load(p, addr);
  4253. } else {
  4254. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  4255. }
  4256. res.type = x.type;
  4257. return res;
  4258. }
  4259. return res;
  4260. }
  4261. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  4262. lbModule *m = p->module;
  4263. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  4264. lhs = lb_emit_conv(p, lhs, type);
  4265. rhs = lb_emit_conv(p, rhs, type);
  4266. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  4267. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4268. GB_ASSERT(is_type_array(type));
  4269. Type *elem_type = base_array_type(type);
  4270. lbAddr res = lb_add_local_generated(p, type, false);
  4271. i64 count = base_type(type)->Array.count;
  4272. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4273. if (inline_array_arith) {
  4274. for (i64 i = 0; i < count; i++) {
  4275. lbValue a = lb_emit_load(p, lb_emit_array_epi(p, x, i));
  4276. lbValue b = lb_emit_load(p, lb_emit_array_epi(p, y, i));
  4277. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4278. lb_emit_store(p, lb_emit_array_epi(p, res.addr, i), c);
  4279. }
  4280. } else {
  4281. auto loop_data = lb_loop_start(p, count);
  4282. lbValue a = lb_emit_load(p, lb_emit_array_ep(p, x, loop_data.idx));
  4283. lbValue b = lb_emit_load(p, lb_emit_array_ep(p, y, loop_data.idx));
  4284. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4285. lb_emit_store(p, lb_emit_array_ep(p, res.addr, loop_data.idx), c);
  4286. lb_loop_end(p, loop_data);
  4287. }
  4288. return lb_addr_load(p, res);
  4289. } else if (is_type_complex(type)) {
  4290. lhs = lb_emit_conv(p, lhs, type);
  4291. rhs = lb_emit_conv(p, rhs, type);
  4292. Type *ft = base_complex_elem_type(type);
  4293. if (op == Token_Quo) {
  4294. auto args = array_make<lbValue>(heap_allocator(), 2);
  4295. args[0] = lhs;
  4296. args[1] = rhs;
  4297. switch (type_size_of(ft)) {
  4298. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  4299. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  4300. default: GB_PANIC("Unknown float type"); break;
  4301. }
  4302. }
  4303. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4304. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  4305. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  4306. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  4307. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  4308. lbValue real = {};
  4309. lbValue imag = {};
  4310. switch (op) {
  4311. case Token_Add:
  4312. real = lb_emit_arith(p, Token_Add, a, c, ft);
  4313. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  4314. break;
  4315. case Token_Sub:
  4316. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  4317. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  4318. break;
  4319. case Token_Mul: {
  4320. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  4321. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  4322. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  4323. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  4324. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  4325. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  4326. break;
  4327. }
  4328. }
  4329. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  4330. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  4331. return lb_addr_load(p, res);
  4332. } else if (is_type_quaternion(type)) {
  4333. lhs = lb_emit_conv(p, lhs, type);
  4334. rhs = lb_emit_conv(p, rhs, type);
  4335. Type *ft = base_complex_elem_type(type);
  4336. if (op == Token_Add || op == Token_Sub) {
  4337. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4338. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  4339. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  4340. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  4341. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  4342. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  4343. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  4344. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  4345. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  4346. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  4347. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  4348. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  4349. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  4350. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  4351. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  4352. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  4353. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  4354. return lb_addr_load(p, res);
  4355. } else if (op == Token_Mul) {
  4356. auto args = array_make<lbValue>(heap_allocator(), 2);
  4357. args[0] = lhs;
  4358. args[1] = rhs;
  4359. switch (8*type_size_of(ft)) {
  4360. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  4361. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  4362. default: GB_PANIC("Unknown float type"); break;
  4363. }
  4364. } else if (op == Token_Quo) {
  4365. auto args = array_make<lbValue>(heap_allocator(), 2);
  4366. args[0] = lhs;
  4367. args[1] = rhs;
  4368. switch (8*type_size_of(ft)) {
  4369. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  4370. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  4371. default: GB_PANIC("Unknown float type"); break;
  4372. }
  4373. }
  4374. }
  4375. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4376. switch (op) {
  4377. case Token_AndNot:
  4378. case Token_And:
  4379. case Token_Or:
  4380. case Token_Xor:
  4381. goto handle_op;
  4382. }
  4383. Type *platform_type = integer_endian_type_to_platform_type(type);
  4384. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4385. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4386. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4387. return lb_emit_byte_swap(p, res, type);
  4388. }
  4389. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4390. Type *platform_type = integer_endian_type_to_platform_type(type);
  4391. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4392. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4393. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4394. return lb_emit_byte_swap(p, res, type);
  4395. }
  4396. handle_op:
  4397. lhs = lb_emit_conv(p, lhs, type);
  4398. rhs = lb_emit_conv(p, rhs, type);
  4399. lbValue res = {};
  4400. res.type = type;
  4401. switch (op) {
  4402. case Token_Add:
  4403. if (is_type_float(type)) {
  4404. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  4405. return res;
  4406. }
  4407. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  4408. return res;
  4409. case Token_Sub:
  4410. if (is_type_float(type)) {
  4411. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  4412. return res;
  4413. }
  4414. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  4415. return res;
  4416. case Token_Mul:
  4417. if (is_type_float(type)) {
  4418. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  4419. return res;
  4420. }
  4421. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  4422. return res;
  4423. case Token_Quo:
  4424. if (is_type_float(type)) {
  4425. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  4426. return res;
  4427. } else if (is_type_unsigned(type)) {
  4428. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  4429. return res;
  4430. }
  4431. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  4432. return res;
  4433. case Token_Mod:
  4434. if (is_type_float(type)) {
  4435. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  4436. return res;
  4437. } else if (is_type_unsigned(type)) {
  4438. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  4439. return res;
  4440. }
  4441. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  4442. return res;
  4443. case Token_ModMod:
  4444. if (is_type_unsigned(type)) {
  4445. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  4446. return res;
  4447. } else {
  4448. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  4449. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  4450. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  4451. res.value = c;
  4452. return res;
  4453. }
  4454. case Token_And:
  4455. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  4456. return res;
  4457. case Token_Or:
  4458. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  4459. return res;
  4460. case Token_Xor:
  4461. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  4462. return res;
  4463. case Token_Shl:
  4464. rhs = lb_emit_conv(p, rhs, lhs.type);
  4465. res.value = LLVMBuildShl(p->builder, lhs.value, rhs.value, "");
  4466. return res;
  4467. case Token_Shr:
  4468. if (is_type_unsigned(type)) {
  4469. res.value = LLVMBuildLShr(p->builder, lhs.value, rhs.value, "");
  4470. return res;
  4471. }
  4472. rhs = lb_emit_conv(p, rhs, lhs.type);
  4473. res.value = LLVMBuildAShr(p->builder, lhs.value, rhs.value, "");
  4474. return res;
  4475. case Token_AndNot:
  4476. {
  4477. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  4478. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  4479. return res;
  4480. }
  4481. break;
  4482. }
  4483. GB_PANIC("unhandled operator of lb_emit_arith");
  4484. return {};
  4485. }
  4486. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  4487. ast_node(be, BinaryExpr, expr);
  4488. TypeAndValue tv = type_and_value_of_expr(expr);
  4489. switch (be->op.kind) {
  4490. case Token_Add:
  4491. case Token_Sub:
  4492. case Token_Mul:
  4493. case Token_Quo:
  4494. case Token_Mod:
  4495. case Token_ModMod:
  4496. case Token_And:
  4497. case Token_Or:
  4498. case Token_Xor:
  4499. case Token_AndNot:
  4500. case Token_Shl:
  4501. case Token_Shr: {
  4502. Type *type = default_type(tv.type);
  4503. lbValue left = lb_build_expr(p, be->left);
  4504. lbValue right = lb_build_expr(p, be->right);
  4505. return lb_emit_arith(p, be->op.kind, left, right, type);
  4506. }
  4507. case Token_CmpEq:
  4508. case Token_NotEq:
  4509. case Token_Lt:
  4510. case Token_LtEq:
  4511. case Token_Gt:
  4512. case Token_GtEq:
  4513. {
  4514. lbValue left = {};
  4515. lbValue right = {};
  4516. if (be->left->tav.mode == Addressing_Type) {
  4517. left = lb_typeid(p->module, be->left->tav.type, t_typeid);
  4518. }
  4519. if (be->right->tav.mode == Addressing_Type) {
  4520. right = lb_typeid(p->module, be->right->tav.type, t_typeid);
  4521. }
  4522. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  4523. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  4524. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  4525. Type *type = default_type(tv.type);
  4526. return lb_emit_conv(p, cmp, type);
  4527. }
  4528. case Token_CmpAnd:
  4529. case Token_CmpOr:
  4530. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  4531. case Token_in:
  4532. case Token_not_in:
  4533. {
  4534. lbValue left = lb_build_expr(p, be->left);
  4535. Type *type = default_type(tv.type);
  4536. lbValue right = lb_build_expr(p, be->right);
  4537. Type *rt = base_type(right.type);
  4538. switch (rt->kind) {
  4539. case Type_Map:
  4540. {
  4541. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  4542. lbValue h = lb_gen_map_header(p, addr, rt);
  4543. lbValue key = lb_gen_map_key(p, left, rt->Map.key);
  4544. auto args = array_make<lbValue>(heap_allocator(), 2);
  4545. args[0] = h;
  4546. args[1] = key;
  4547. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  4548. if (be->op.kind == Token_in) {
  4549. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  4550. } else {
  4551. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  4552. }
  4553. }
  4554. break;
  4555. case Type_BitSet:
  4556. {
  4557. Type *key_type = rt->BitSet.elem;
  4558. GB_ASSERT(are_types_identical(left.type, key_type));
  4559. Type *it = bit_set_to_int(rt);
  4560. left = lb_emit_conv(p, left, it);
  4561. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  4562. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  4563. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  4564. bit = lb_emit_conv(p, bit, it);
  4565. lbValue old_value = lb_emit_transmute(p, right, it);
  4566. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  4567. if (be->op.kind == Token_in) {
  4568. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  4569. } else {
  4570. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  4571. }
  4572. }
  4573. break;
  4574. default:
  4575. GB_PANIC("Invalid 'in' type");
  4576. }
  4577. break;
  4578. }
  4579. break;
  4580. default:
  4581. GB_PANIC("Invalid binary expression");
  4582. break;
  4583. }
  4584. return {};
  4585. }
  4586. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  4587. Type *prev_src = src;
  4588. // Type *prev_dst = dst;
  4589. src = base_type(type_deref(src));
  4590. // dst = base_type(type_deref(dst));
  4591. bool src_is_ptr = src != prev_src;
  4592. // bool dst_is_ptr = dst != prev_dst;
  4593. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  4594. for_array(i, src->Struct.fields) {
  4595. Entity *f = src->Struct.fields[i];
  4596. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  4597. if (are_types_identical(dst, f->type)) {
  4598. return f->token.string;
  4599. }
  4600. if (src_is_ptr && is_type_pointer(dst)) {
  4601. if (are_types_identical(type_deref(dst), f->type)) {
  4602. return f->token.string;
  4603. }
  4604. }
  4605. if (is_type_struct(f->type)) {
  4606. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  4607. if (name.len > 0) {
  4608. return name;
  4609. }
  4610. }
  4611. }
  4612. }
  4613. return str_lit("");
  4614. }
  4615. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  4616. GB_ASSERT(is_type_pointer(value.type));
  4617. GB_ASSERT(is_type_pointer(t));
  4618. GB_ASSERT(lb_is_const(value));
  4619. lbValue res = {};
  4620. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  4621. res.type = t;
  4622. return res;
  4623. }
  4624. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  4625. lbModule *m = p->module;
  4626. t = reduce_tuple_to_single_type(t);
  4627. Type *src_type = value.type;
  4628. if (are_types_identical(t, src_type)) {
  4629. return value;
  4630. }
  4631. Type *src = core_type(src_type);
  4632. Type *dst = core_type(t);
  4633. if (is_type_untyped_nil(src)) {
  4634. return lb_const_nil(m, t);
  4635. }
  4636. if (is_type_untyped_undef(src)) {
  4637. return lb_const_undef(m, t);
  4638. }
  4639. if (LLVMIsConstant(value.value)) {
  4640. if (is_type_any(dst)) {
  4641. Type *st = default_type(src_type);
  4642. lbAddr default_value = lb_add_local_generated(p, st, false);
  4643. lb_addr_store(p, default_value, value);
  4644. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  4645. lbValue id = lb_typeid(m, st);
  4646. lbAddr res = lb_add_local_generated(p, t, false);
  4647. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  4648. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  4649. lb_emit_store(p, a0, data);
  4650. lb_emit_store(p, a1, id);
  4651. return lb_addr_load(p, res);
  4652. } else if (dst->kind == Type_Basic) {
  4653. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  4654. String str = lb_get_const_string(m, value);
  4655. lbValue res = {};
  4656. res.type = t;
  4657. res.value = llvm_cstring(m, str);
  4658. return res;
  4659. }
  4660. // if (is_type_float(dst)) {
  4661. // return value;
  4662. // } else if (is_type_integer(dst)) {
  4663. // return value;
  4664. // }
  4665. // ExactValue ev = value->Constant.value;
  4666. // if (is_type_float(dst)) {
  4667. // ev = exact_value_to_float(ev);
  4668. // } else if (is_type_complex(dst)) {
  4669. // ev = exact_value_to_complex(ev);
  4670. // } else if (is_type_quaternion(dst)) {
  4671. // ev = exact_value_to_quaternion(ev);
  4672. // } else if (is_type_string(dst)) {
  4673. // // Handled elsewhere
  4674. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  4675. // } else if (is_type_integer(dst)) {
  4676. // ev = exact_value_to_integer(ev);
  4677. // } else if (is_type_pointer(dst)) {
  4678. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  4679. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  4680. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  4681. // }
  4682. // return lb_const_value(p->module, t, ev);
  4683. }
  4684. }
  4685. if (are_types_identical(src, dst)) {
  4686. if (!are_types_identical(src_type, t)) {
  4687. return lb_emit_transmute(p, value, t);
  4688. }
  4689. return value;
  4690. }
  4691. // bool <-> llvm bool
  4692. if (is_type_boolean(src) && dst == t_llvm_bool) {
  4693. lbValue res = {};
  4694. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  4695. res.type = dst;
  4696. return res;
  4697. }
  4698. if (src == t_llvm_bool && is_type_boolean(dst)) {
  4699. lbValue res = {};
  4700. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  4701. res.type = dst;
  4702. return res;
  4703. }
  4704. // integer -> integer
  4705. if (is_type_integer(src) && is_type_integer(dst)) {
  4706. GB_ASSERT(src->kind == Type_Basic &&
  4707. dst->kind == Type_Basic);
  4708. i64 sz = type_size_of(default_type(src));
  4709. i64 dz = type_size_of(default_type(dst));
  4710. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  4711. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  4712. value = lb_emit_byte_swap(p, value, platform_src_type);
  4713. }
  4714. LLVMOpcode op = LLVMTrunc;
  4715. if (dz < sz) {
  4716. op = LLVMTrunc;
  4717. } else if (dz == sz) {
  4718. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  4719. // NOTE(bill): Copy the value just for type correctness
  4720. op = LLVMBitCast;
  4721. } else if (dz > sz) {
  4722. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  4723. }
  4724. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  4725. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  4726. lbValue res = {};
  4727. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  4728. res.type = t;
  4729. return lb_emit_byte_swap(p, res, t);
  4730. } else {
  4731. lbValue res = {};
  4732. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  4733. res.type = t;
  4734. return res;
  4735. }
  4736. }
  4737. // boolean -> boolean/integer
  4738. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  4739. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  4740. lbValue res = {};
  4741. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  4742. res.type = t;
  4743. return res;
  4744. }
  4745. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  4746. return lb_emit_transmute(p, value, dst);
  4747. }
  4748. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  4749. return lb_emit_transmute(p, value, dst);
  4750. }
  4751. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  4752. return lb_emit_transmute(p, value, dst);
  4753. }
  4754. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  4755. return lb_emit_transmute(p, value, dst);
  4756. }
  4757. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  4758. lbValue c = lb_emit_conv(p, value, t_cstring);
  4759. auto args = array_make<lbValue>(heap_allocator(), 1);
  4760. args[0] = c;
  4761. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  4762. return lb_emit_conv(p, s, dst);
  4763. }
  4764. // integer -> boolean
  4765. if (is_type_integer(src) && is_type_boolean(dst)) {
  4766. lbValue res = {};
  4767. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  4768. res.type = t_llvm_bool;
  4769. return lb_emit_conv(p, res, t);
  4770. }
  4771. // float -> float
  4772. if (is_type_float(src) && is_type_float(dst)) {
  4773. gbAllocator a = heap_allocator();
  4774. i64 sz = type_size_of(src);
  4775. i64 dz = type_size_of(dst);
  4776. if (dz == sz) {
  4777. if (types_have_same_internal_endian(src, dst)) {
  4778. lbValue res = {};
  4779. res.type = t;
  4780. res.value = value.value;
  4781. return res;
  4782. } else {
  4783. return lb_emit_byte_swap(p, value, t);
  4784. }
  4785. }
  4786. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  4787. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  4788. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  4789. lbValue res = {};
  4790. res = lb_emit_conv(p, value, platform_src_type);
  4791. res = lb_emit_conv(p, res, platform_dst_type);
  4792. if (is_type_different_to_arch_endianness(dst)) {
  4793. res = lb_emit_byte_swap(p, res, t);
  4794. }
  4795. return lb_emit_conv(p, res, t);
  4796. }
  4797. lbValue res = {};
  4798. res.type = t;
  4799. if (dz >= sz) {
  4800. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  4801. } else {
  4802. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  4803. }
  4804. return res;
  4805. }
  4806. if (is_type_complex(src) && is_type_complex(dst)) {
  4807. Type *ft = base_complex_elem_type(dst);
  4808. lbAddr gen = lb_add_local_generated(p, dst, false);
  4809. lbValue gp = lb_addr_get_ptr(p, gen);
  4810. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4811. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4812. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  4813. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  4814. return lb_addr_load(p, gen);
  4815. }
  4816. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  4817. // @QuaternionLayout
  4818. Type *ft = base_complex_elem_type(dst);
  4819. lbAddr gen = lb_add_local_generated(p, dst, false);
  4820. lbValue gp = lb_addr_get_ptr(p, gen);
  4821. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4822. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4823. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  4824. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  4825. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  4826. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  4827. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  4828. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  4829. return lb_addr_load(p, gen);
  4830. }
  4831. if (is_type_float(src) && is_type_complex(dst)) {
  4832. Type *ft = base_complex_elem_type(dst);
  4833. lbAddr gen = lb_add_local_generated(p, dst, true);
  4834. lbValue gp = lb_addr_get_ptr(p, gen);
  4835. lbValue real = lb_emit_conv(p, value, ft);
  4836. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  4837. return lb_addr_load(p, gen);
  4838. }
  4839. if (is_type_float(src) && is_type_quaternion(dst)) {
  4840. Type *ft = base_complex_elem_type(dst);
  4841. lbAddr gen = lb_add_local_generated(p, dst, true);
  4842. lbValue gp = lb_addr_get_ptr(p, gen);
  4843. lbValue real = lb_emit_conv(p, value, ft);
  4844. // @QuaternionLayout
  4845. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  4846. return lb_addr_load(p, gen);
  4847. }
  4848. if (is_type_complex(src) && is_type_quaternion(dst)) {
  4849. Type *ft = base_complex_elem_type(dst);
  4850. lbAddr gen = lb_add_local_generated(p, dst, true);
  4851. lbValue gp = lb_addr_get_ptr(p, gen);
  4852. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4853. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4854. // @QuaternionLayout
  4855. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  4856. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  4857. return lb_addr_load(p, gen);
  4858. }
  4859. // float <-> integer
  4860. if (is_type_float(src) && is_type_integer(dst)) {
  4861. lbValue res = {};
  4862. res.type = t;
  4863. if (is_type_unsigned(dst)) {
  4864. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  4865. } else {
  4866. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  4867. }
  4868. return res;
  4869. }
  4870. if (is_type_integer(src) && is_type_float(dst)) {
  4871. lbValue res = {};
  4872. res.type = t;
  4873. if (is_type_unsigned(src)) {
  4874. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  4875. } else {
  4876. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  4877. }
  4878. return res;
  4879. }
  4880. // Pointer <-> uintptr
  4881. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4882. lbValue res = {};
  4883. res.type = t;
  4884. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4885. return res;
  4886. }
  4887. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4888. lbValue res = {};
  4889. res.type = t;
  4890. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4891. return res;
  4892. }
  4893. #if 1
  4894. if (is_type_union(dst)) {
  4895. for_array(i, dst->Union.variants) {
  4896. Type *vt = dst->Union.variants[i];
  4897. if (are_types_identical(vt, src_type)) {
  4898. lbAddr parent = lb_add_local_generated(p, t, true);
  4899. lb_emit_store_union_variant(p, parent.addr, value, vt);
  4900. return lb_addr_load(p, parent);
  4901. }
  4902. }
  4903. }
  4904. #endif
  4905. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  4906. // subtype polymorphism casting
  4907. if (check_is_assignable_to_using_subtype(src_type, t)) {
  4908. Type *st = type_deref(src_type);
  4909. Type *pst = st;
  4910. st = type_deref(st);
  4911. bool st_is_ptr = is_type_pointer(src_type);
  4912. st = base_type(st);
  4913. Type *dt = t;
  4914. bool dt_is_ptr = type_deref(dt) != dt;
  4915. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  4916. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  4917. if (field_name.len > 0) {
  4918. // NOTE(bill): It can be casted
  4919. Selection sel = lookup_field(st, field_name, false, true);
  4920. if (sel.entity != nullptr) {
  4921. if (st_is_ptr) {
  4922. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  4923. Type *rt = res.type;
  4924. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4925. res = lb_emit_load(p, res);
  4926. }
  4927. return res;
  4928. } else {
  4929. if (is_type_pointer(value.type)) {
  4930. Type *rt = value.type;
  4931. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4932. value = lb_emit_load(p, value);
  4933. } else {
  4934. value = lb_emit_deep_field_gep(p, value, sel);
  4935. return lb_emit_load(p, value);
  4936. }
  4937. }
  4938. return lb_emit_deep_field_ev(p, value, sel);
  4939. }
  4940. } else {
  4941. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  4942. }
  4943. }
  4944. }
  4945. // Pointer <-> Pointer
  4946. if (is_type_pointer(src) && is_type_pointer(dst)) {
  4947. lbValue res = {};
  4948. res.type = t;
  4949. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4950. return res;
  4951. }
  4952. // proc <-> proc
  4953. if (is_type_proc(src) && is_type_proc(dst)) {
  4954. lbValue res = {};
  4955. res.type = t;
  4956. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4957. return res;
  4958. }
  4959. // pointer -> proc
  4960. if (is_type_pointer(src) && is_type_proc(dst)) {
  4961. lbValue res = {};
  4962. res.type = t;
  4963. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4964. return res;
  4965. }
  4966. // proc -> pointer
  4967. if (is_type_proc(src) && is_type_pointer(dst)) {
  4968. lbValue res = {};
  4969. res.type = t;
  4970. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4971. return res;
  4972. }
  4973. // []byte/[]u8 <-> string
  4974. if (is_type_u8_slice(src) && is_type_string(dst)) {
  4975. return lb_emit_transmute(p, value, t);
  4976. }
  4977. if (is_type_string(src) && is_type_u8_slice(dst)) {
  4978. return lb_emit_transmute(p, value, t);
  4979. }
  4980. if (is_type_array(dst)) {
  4981. Type *elem = dst->Array.elem;
  4982. lbValue e = lb_emit_conv(p, value, elem);
  4983. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4984. lbAddr v = lb_add_local_generated(p, t, false);
  4985. isize index_count = cast(isize)dst->Array.count;
  4986. for (isize i = 0; i < index_count; i++) {
  4987. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  4988. lb_emit_store(p, elem, e);
  4989. }
  4990. return lb_addr_load(p, v);
  4991. }
  4992. if (is_type_any(dst)) {
  4993. if (is_type_untyped_nil(src)) {
  4994. return lb_const_nil(p->module, t);
  4995. }
  4996. if (is_type_untyped_undef(src)) {
  4997. return lb_const_undef(p->module, t);
  4998. }
  4999. lbAddr result = lb_add_local_generated(p, t, true);
  5000. Type *st = default_type(src_type);
  5001. lbValue data = lb_address_from_load_or_generate_local(p, value);
  5002. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  5003. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5004. data = lb_emit_conv(p, data, t_rawptr);
  5005. lbValue id = lb_typeid(p->module, st);
  5006. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  5007. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  5008. lb_emit_store(p, any_data, data);
  5009. lb_emit_store(p, any_id, id);
  5010. return lb_addr_load(p, result);
  5011. }
  5012. if (is_type_untyped(src)) {
  5013. if (is_type_string(src) && is_type_string(dst)) {
  5014. lbAddr result = lb_add_local_generated(p, t, false);
  5015. lb_addr_store(p, result, value);
  5016. return lb_addr_load(p, result);
  5017. }
  5018. }
  5019. gb_printf_err("%.*s\n", LIT(p->name));
  5020. gb_printf_err("lb_emit_conv: src -> dst\n");
  5021. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5022. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5023. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  5024. gb_printf_err("Not Identical %p != %p\n", src, dst);
  5025. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5026. type_to_string(src_type), type_to_string(t),
  5027. LIT(p->name));
  5028. return {};
  5029. }
  5030. bool lb_is_type_aggregate(Type *t) {
  5031. t = base_type(t);
  5032. switch (t->kind) {
  5033. case Type_Basic:
  5034. switch (t->Basic.kind) {
  5035. case Basic_string:
  5036. case Basic_any:
  5037. return true;
  5038. // case Basic_complex32:
  5039. case Basic_complex64:
  5040. case Basic_complex128:
  5041. case Basic_quaternion128:
  5042. case Basic_quaternion256:
  5043. return true;
  5044. }
  5045. break;
  5046. case Type_Pointer:
  5047. return false;
  5048. case Type_Array:
  5049. case Type_Slice:
  5050. case Type_Struct:
  5051. case Type_Union:
  5052. case Type_Tuple:
  5053. case Type_DynamicArray:
  5054. case Type_Map:
  5055. case Type_BitField:
  5056. case Type_SimdVector:
  5057. return true;
  5058. case Type_Named:
  5059. return lb_is_type_aggregate(t->Named.base);
  5060. }
  5061. return false;
  5062. }
  5063. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  5064. Type *src_type = value.type;
  5065. if (are_types_identical(t, src_type)) {
  5066. return value;
  5067. }
  5068. lbValue res = {};
  5069. res.type = t;
  5070. Type *src = base_type(src_type);
  5071. Type *dst = base_type(t);
  5072. lbModule *m = p->module;
  5073. i64 sz = type_size_of(src);
  5074. i64 dz = type_size_of(dst);
  5075. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5076. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5077. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5078. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5079. return res;
  5080. }
  5081. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5082. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5083. return res;
  5084. }
  5085. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5086. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5087. return res;
  5088. }
  5089. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5090. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5091. return res;
  5092. }
  5093. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5094. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5095. return res;
  5096. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5097. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5098. return res;
  5099. }
  5100. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5101. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  5102. return res;
  5103. }
  5104. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  5105. lbValue s = lb_address_from_load_or_generate_local(p, value);
  5106. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  5107. return lb_emit_load(p, d);
  5108. }
  5109. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  5110. // GB_PANIC("lb_emit_transmute");
  5111. return res;
  5112. }
  5113. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  5114. GB_ASSERT(addr.kind == lbAddr_Context);
  5115. GB_ASSERT(addr.ctx.sel.index.count == 0);
  5116. lbModule *m = p->module;
  5117. gbAllocator a = heap_allocator();
  5118. auto args = array_make<lbValue>(a, 1);
  5119. args[0] = addr.addr;
  5120. lb_emit_runtime_call(p, "__init_context", args);
  5121. }
  5122. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  5123. ctx.kind = lbAddr_Context;
  5124. lbContextData cd = {ctx, p->scope_index};
  5125. array_add(&p->context_stack, cd);
  5126. }
  5127. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  5128. if (p->context_stack.count > 0) {
  5129. return p->context_stack[p->context_stack.count-1].ctx;
  5130. }
  5131. Type *pt = base_type(p->type);
  5132. GB_ASSERT(pt->kind == Type_Proc);
  5133. {
  5134. lbAddr c = lb_add_local_generated(p, t_context, false);
  5135. c.kind = lbAddr_Context;
  5136. lb_emit_init_context(p, c);
  5137. lb_push_context_onto_stack(p, c);
  5138. return c;
  5139. }
  5140. }
  5141. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  5142. if (LLVMIsALoadInst(value.value)) {
  5143. lbValue res = {};
  5144. res.value = LLVMGetOperand(value.value, 0);
  5145. res.type = alloc_type_pointer(value.type);
  5146. return res;
  5147. }
  5148. GB_ASSERT(is_type_typed(value.type));
  5149. lbAddr res = lb_add_local_generated(p, value.type, false);
  5150. lb_addr_store(p, res, value);
  5151. return res.addr;
  5152. }
  5153. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  5154. i64 type_alignment = type_align_of(new_type);
  5155. if (alignment < type_alignment) {
  5156. alignment = type_alignment;
  5157. }
  5158. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  5159. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  5160. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  5161. lb_addr_store(p, ptr, val);
  5162. ptr.kind = lbAddr_Context;
  5163. return ptr.addr;
  5164. }
  5165. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  5166. gbAllocator a = heap_allocator();
  5167. GB_ASSERT(is_type_pointer(s.type));
  5168. Type *t = base_type(type_deref(s.type));
  5169. Type *result_type = nullptr;
  5170. if (t->kind == Type_Opaque) {
  5171. t = t->Opaque.elem;
  5172. }
  5173. if (is_type_struct(t)) {
  5174. result_type = get_struct_field_type(t, index);
  5175. } else if (is_type_union(t)) {
  5176. GB_ASSERT(index == -1);
  5177. return lb_emit_union_tag_ptr(p, s);
  5178. } else if (is_type_tuple(t)) {
  5179. GB_ASSERT(t->Tuple.variables.count > 0);
  5180. result_type = t->Tuple.variables[index]->type;
  5181. } else if (is_type_complex(t)) {
  5182. Type *ft = base_complex_elem_type(t);
  5183. switch (index) {
  5184. case 0: result_type = ft; break;
  5185. case 1: result_type = ft; break;
  5186. }
  5187. } else if (is_type_quaternion(t)) {
  5188. Type *ft = base_complex_elem_type(t);
  5189. switch (index) {
  5190. case 0: result_type = ft; break;
  5191. case 1: result_type = ft; break;
  5192. case 2: result_type = ft; break;
  5193. case 3: result_type = ft; break;
  5194. }
  5195. } else if (is_type_slice(t)) {
  5196. switch (index) {
  5197. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5198. case 1: result_type = t_int; break;
  5199. }
  5200. } else if (is_type_string(t)) {
  5201. switch (index) {
  5202. case 0: result_type = t_u8_ptr; break;
  5203. case 1: result_type = t_int; break;
  5204. }
  5205. } else if (is_type_any(t)) {
  5206. switch (index) {
  5207. case 0: result_type = t_rawptr; break;
  5208. case 1: result_type = t_typeid; break;
  5209. }
  5210. } else if (is_type_dynamic_array(t)) {
  5211. switch (index) {
  5212. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5213. case 1: result_type = t_int; break;
  5214. case 2: result_type = t_int; break;
  5215. case 3: result_type = t_allocator; break;
  5216. }
  5217. } else if (is_type_map(t)) {
  5218. init_map_internal_types(t);
  5219. Type *itp = alloc_type_pointer(t->Map.internal_type);
  5220. s = lb_emit_transmute(p, s, itp);
  5221. Type *gst = t->Map.internal_type;
  5222. GB_ASSERT(gst->kind == Type_Struct);
  5223. switch (index) {
  5224. case 0: result_type = get_struct_field_type(gst, 0); break;
  5225. case 1: result_type = get_struct_field_type(gst, 1); break;
  5226. }
  5227. } else if (is_type_array(t)) {
  5228. return lb_emit_array_epi(p, s, index);
  5229. } else {
  5230. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  5231. }
  5232. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  5233. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5234. index += 1;
  5235. }
  5236. if (lb_is_const(s)) {
  5237. lbModule *m = p->module;
  5238. lbValue res = {};
  5239. LLVMValueRef indices[2] = {llvm_zero32(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  5240. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  5241. res.type = alloc_type_pointer(result_type);
  5242. return res;
  5243. } else {
  5244. lbValue res = {};
  5245. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  5246. res.type = alloc_type_pointer(result_type);
  5247. return res;
  5248. }
  5249. }
  5250. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  5251. if (LLVMIsALoadInst(s.value)) {
  5252. lbValue res = {};
  5253. res.value = LLVMGetOperand(s.value, 0);
  5254. res.type = alloc_type_pointer(s.type);
  5255. lbValue ptr = lb_emit_struct_ep(p, res, index);
  5256. return lb_emit_load(p, ptr);
  5257. }
  5258. gbAllocator a = heap_allocator();
  5259. Type *t = base_type(s.type);
  5260. Type *result_type = nullptr;
  5261. switch (t->kind) {
  5262. case Type_Basic:
  5263. switch (t->Basic.kind) {
  5264. case Basic_string:
  5265. switch (index) {
  5266. case 0: result_type = t_u8_ptr; break;
  5267. case 1: result_type = t_int; break;
  5268. }
  5269. break;
  5270. case Basic_any:
  5271. switch (index) {
  5272. case 0: result_type = t_rawptr; break;
  5273. case 1: result_type = t_typeid; break;
  5274. }
  5275. break;
  5276. case Basic_complex64: case Basic_complex128:
  5277. {
  5278. Type *ft = base_complex_elem_type(t);
  5279. switch (index) {
  5280. case 0: result_type = ft; break;
  5281. case 1: result_type = ft; break;
  5282. }
  5283. break;
  5284. }
  5285. case Basic_quaternion128: case Basic_quaternion256:
  5286. {
  5287. Type *ft = base_complex_elem_type(t);
  5288. switch (index) {
  5289. case 0: result_type = ft; break;
  5290. case 1: result_type = ft; break;
  5291. case 2: result_type = ft; break;
  5292. case 3: result_type = ft; break;
  5293. }
  5294. break;
  5295. }
  5296. }
  5297. break;
  5298. case Type_Struct:
  5299. result_type = get_struct_field_type(t, index);
  5300. break;
  5301. case Type_Union:
  5302. GB_ASSERT(index == -1);
  5303. // return lb_emit_union_tag_value(p, s);
  5304. GB_PANIC("lb_emit_union_tag_value");
  5305. case Type_Tuple:
  5306. GB_ASSERT(t->Tuple.variables.count > 0);
  5307. result_type = t->Tuple.variables[index]->type;
  5308. if (t->Tuple.variables.count == 1) {
  5309. return s;
  5310. }
  5311. break;
  5312. case Type_Slice:
  5313. switch (index) {
  5314. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5315. case 1: result_type = t_int; break;
  5316. }
  5317. break;
  5318. case Type_DynamicArray:
  5319. switch (index) {
  5320. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5321. case 1: result_type = t_int; break;
  5322. case 2: result_type = t_int; break;
  5323. case 3: result_type = t_allocator; break;
  5324. }
  5325. break;
  5326. case Type_Map:
  5327. {
  5328. init_map_internal_types(t);
  5329. Type *gst = t->Map.generated_struct_type;
  5330. switch (index) {
  5331. case 0: result_type = get_struct_field_type(gst, 0); break;
  5332. case 1: result_type = get_struct_field_type(gst, 1); break;
  5333. }
  5334. }
  5335. break;
  5336. case Type_Array:
  5337. result_type = t->Array.elem;
  5338. break;
  5339. default:
  5340. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  5341. break;
  5342. }
  5343. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  5344. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5345. index += 1;
  5346. }
  5347. lbValue res = {};
  5348. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  5349. res.type = result_type;
  5350. return res;
  5351. }
  5352. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  5353. GB_ASSERT(sel.index.count > 0);
  5354. Type *type = type_deref(e.type);
  5355. gbAllocator a = heap_allocator();
  5356. for_array(i, sel.index) {
  5357. i32 index = cast(i32)sel.index[i];
  5358. if (is_type_pointer(type)) {
  5359. type = type_deref(type);
  5360. e = lb_emit_load(p, e);
  5361. }
  5362. type = core_type(type);
  5363. if (type->kind == Type_Opaque) {
  5364. type = type->Opaque.elem;
  5365. }
  5366. if (is_type_quaternion(type)) {
  5367. e = lb_emit_struct_ep(p, e, index);
  5368. } else if (is_type_raw_union(type)) {
  5369. type = get_struct_field_type(type, index);
  5370. GB_ASSERT(is_type_pointer(e.type));
  5371. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  5372. } else if (is_type_struct(type)) {
  5373. type = get_struct_field_type(type, index);
  5374. e = lb_emit_struct_ep(p, e, index);
  5375. } else if (type->kind == Type_Union) {
  5376. GB_ASSERT(index == -1);
  5377. type = t_type_info_ptr;
  5378. e = lb_emit_struct_ep(p, e, index);
  5379. } else if (type->kind == Type_Tuple) {
  5380. type = type->Tuple.variables[index]->type;
  5381. e = lb_emit_struct_ep(p, e, index);
  5382. } else if (type->kind == Type_Basic) {
  5383. switch (type->Basic.kind) {
  5384. case Basic_any: {
  5385. if (index == 0) {
  5386. type = t_rawptr;
  5387. } else if (index == 1) {
  5388. type = t_type_info_ptr;
  5389. }
  5390. e = lb_emit_struct_ep(p, e, index);
  5391. break;
  5392. }
  5393. case Basic_string:
  5394. e = lb_emit_struct_ep(p, e, index);
  5395. break;
  5396. default:
  5397. GB_PANIC("un-gep-able type");
  5398. break;
  5399. }
  5400. } else if (type->kind == Type_Slice) {
  5401. e = lb_emit_struct_ep(p, e, index);
  5402. } else if (type->kind == Type_DynamicArray) {
  5403. e = lb_emit_struct_ep(p, e, index);
  5404. } else if (type->kind == Type_Array) {
  5405. e = lb_emit_array_epi(p, e, index);
  5406. } else if (type->kind == Type_Map) {
  5407. e = lb_emit_struct_ep(p, e, index);
  5408. } else {
  5409. GB_PANIC("un-gep-able type %s", type_to_string(type));
  5410. }
  5411. }
  5412. return e;
  5413. }
  5414. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  5415. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  5416. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  5417. return lb_emit_load(p, res);
  5418. }
  5419. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  5420. // NOTE(bill): The prev block may defer injection before it's terminator
  5421. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  5422. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  5423. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  5424. return;
  5425. }
  5426. lbBlock *b = lb_create_block(p, "defer");
  5427. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  5428. lb_emit_jump(p, b);
  5429. }
  5430. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  5431. lb_emit_jump(p, b);
  5432. }
  5433. lb_start_block(p, b);
  5434. if (d.kind == lbDefer_Node) {
  5435. lb_build_stmt(p, d.stmt);
  5436. } else if (d.kind == lbDefer_Instr) {
  5437. // NOTE(bill): Need to make a new copy
  5438. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  5439. LLVMInsertIntoBuilder(p->builder, instr);
  5440. } else if (d.kind == lbDefer_Proc) {
  5441. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  5442. }
  5443. }
  5444. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  5445. isize count = p->defer_stmts.count;
  5446. isize i = count;
  5447. while (i --> 0) {
  5448. lbDefer d = p->defer_stmts[i];
  5449. if (kind == lbDeferExit_Default) {
  5450. if (p->scope_index == d.scope_index &&
  5451. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  5452. lb_build_defer_stmt(p, d);
  5453. array_pop(&p->defer_stmts);
  5454. continue;
  5455. } else {
  5456. break;
  5457. }
  5458. } else if (kind == lbDeferExit_Return) {
  5459. lb_build_defer_stmt(p, d);
  5460. } else if (kind == lbDeferExit_Branch) {
  5461. GB_ASSERT(block != nullptr);
  5462. isize lower_limit = block->scope_index;
  5463. if (lower_limit < d.scope_index) {
  5464. lb_build_defer_stmt(p, d);
  5465. }
  5466. }
  5467. }
  5468. }
  5469. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  5470. lbDefer d = {lbDefer_Node};
  5471. d.scope_index = scope_index;
  5472. d.context_stack_count = p->context_stack.count;
  5473. d.block = p->curr_block;
  5474. d.stmt = stmt;
  5475. array_add(&p->defer_stmts, d);
  5476. return d;
  5477. }
  5478. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  5479. lbDefer d = {lbDefer_Proc};
  5480. d.scope_index = p->scope_index;
  5481. d.block = p->curr_block;
  5482. d.proc.deferred = deferred;
  5483. d.proc.result_as_args = result_as_args;
  5484. array_add(&p->defer_stmts, d);
  5485. return d;
  5486. }
  5487. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  5488. Array<lbValue> array = {};
  5489. Type *t = base_type(value.type);
  5490. if (t == nullptr) {
  5491. // Do nothing
  5492. } else if (is_type_tuple(t)) {
  5493. GB_ASSERT(t->kind == Type_Tuple);
  5494. auto *rt = &t->Tuple;
  5495. if (rt->variables.count > 0) {
  5496. array = array_make<lbValue>(heap_allocator(), rt->variables.count);
  5497. for_array(i, rt->variables) {
  5498. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  5499. array[i] = elem;
  5500. }
  5501. }
  5502. } else {
  5503. array = array_make<lbValue>(heap_allocator(), 1);
  5504. array[0] = value;
  5505. }
  5506. return array;
  5507. }
  5508. 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) {
  5509. unsigned arg_count = cast(unsigned)processed_args.count;
  5510. if (return_ptr.value != nullptr) {
  5511. arg_count += 1;
  5512. }
  5513. if (context_ptr.addr.value != nullptr) {
  5514. arg_count += 1;
  5515. }
  5516. LLVMValueRef *args = gb_alloc_array(heap_allocator(), LLVMValueRef, arg_count);
  5517. isize arg_index = 0;
  5518. if (return_ptr.value != nullptr) {
  5519. args[arg_index++] = return_ptr.value;
  5520. }
  5521. for_array(i, processed_args) {
  5522. lbValue arg = processed_args[i];
  5523. args[arg_index++] = arg.value;
  5524. }
  5525. if (context_ptr.addr.value != nullptr) {
  5526. args[arg_index++] = context_ptr.addr.value;
  5527. }
  5528. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  5529. GB_ASSERT(curr_block != p->decl_block->block);
  5530. LLVMValueRef ret = LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(p->module, value.type)), value.value, args, arg_count, "");;
  5531. lbValue res = {};
  5532. res.value = ret;
  5533. res.type = abi_rt;
  5534. return res;
  5535. }
  5536. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  5537. String name = make_string_c(c_name);
  5538. AstPackage *pkg = p->module->info->runtime_package;
  5539. Entity *e = scope_lookup_current(pkg->scope, name);
  5540. lbValue *found = nullptr;
  5541. if (p->module != e->code_gen_module) {
  5542. gb_mutex_lock(&p->module->mutex);
  5543. }
  5544. found = map_get(&e->code_gen_module->values, hash_entity(e));
  5545. if (p->module != e->code_gen_module) {
  5546. gb_mutex_unlock(&p->module->mutex);
  5547. }
  5548. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  5549. return lb_emit_call(p, *found, args);
  5550. }
  5551. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  5552. lbModule *m = p->module;
  5553. Type *pt = base_type(value.type);
  5554. GB_ASSERT(pt->kind == Type_Proc);
  5555. Type *results = pt->Proc.results;
  5556. if (p->entity != nullptr) {
  5557. if (p->entity->flags & EntityFlag_Disabled) {
  5558. return {};
  5559. }
  5560. }
  5561. lbAddr context_ptr = {};
  5562. if (pt->Proc.calling_convention == ProcCC_Odin) {
  5563. context_ptr = lb_find_or_generate_context_ptr(p);
  5564. }
  5565. set_procedure_abi_types(heap_allocator(), pt);
  5566. bool is_c_vararg = pt->Proc.c_vararg;
  5567. isize param_count = pt->Proc.param_count;
  5568. if (is_c_vararg) {
  5569. GB_ASSERT(param_count-1 <= args.count);
  5570. param_count -= 1;
  5571. } else {
  5572. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  5573. }
  5574. auto processed_args = array_make<lbValue>(heap_allocator(), 0, args.count);
  5575. for (isize i = 0; i < param_count; i++) {
  5576. Entity *e = pt->Proc.params->Tuple.variables[i];
  5577. if (e->kind != Entity_Variable) {
  5578. // array_add(&processed_args, args[i]);
  5579. continue;
  5580. }
  5581. GB_ASSERT(e->flags & EntityFlag_Param);
  5582. Type *original_type = e->type;
  5583. Type *new_type = pt->Proc.abi_compat_params[i];
  5584. Type *arg_type = args[i].type;
  5585. if (are_types_identical(arg_type, new_type)) {
  5586. // NOTE(bill): Done
  5587. array_add(&processed_args, args[i]);
  5588. } else if (!are_types_identical(original_type, new_type)) {
  5589. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  5590. if (e->flags&EntityFlag_ImplicitReference) {
  5591. array_add(&processed_args, lb_address_from_load_or_generate_local(p, args[i]));
  5592. } else if (!is_type_pointer(arg_type)) {
  5593. array_add(&processed_args, lb_copy_value_to_ptr(p, args[i], original_type, 16));
  5594. }
  5595. } else if (is_type_integer(new_type) || is_type_float(new_type)) {
  5596. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  5597. } else if (new_type == t_llvm_bool) {
  5598. array_add(&processed_args, lb_emit_conv(p, args[i], new_type));
  5599. } else if (is_type_simd_vector(new_type)) {
  5600. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  5601. } else if (is_type_tuple(new_type)) {
  5602. Type *abi_type = pt->Proc.abi_compat_params[i];
  5603. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  5604. lbValue x = lb_emit_transmute(p, args[i], st);
  5605. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  5606. lbValue xx = lb_emit_struct_ev(p, x, cast(i32)j);
  5607. array_add(&processed_args, xx);
  5608. }
  5609. }
  5610. } else {
  5611. lbValue x = lb_emit_conv(p, args[i], new_type);
  5612. array_add(&processed_args, x);
  5613. }
  5614. }
  5615. if (inlining == ProcInlining_none) {
  5616. inlining = p->inlining;
  5617. }
  5618. lbValue result = {};
  5619. Type *abi_rt = reduce_tuple_to_single_type(pt->Proc.abi_compat_result_type);
  5620. Type *rt = reduce_tuple_to_single_type(results);
  5621. if (pt->Proc.return_by_pointer) {
  5622. lbValue return_ptr = {};
  5623. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  5624. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  5625. return_ptr = p->return_ptr_hint_value;
  5626. p->return_ptr_hint_used = true;
  5627. }
  5628. }
  5629. if (return_ptr.value == nullptr) {
  5630. lbAddr r = lb_add_local_generated(p, rt, true);
  5631. return_ptr = r.addr;
  5632. }
  5633. GB_ASSERT(is_type_pointer(return_ptr.type));
  5634. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  5635. result = lb_emit_load(p, return_ptr);
  5636. } else {
  5637. result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining);
  5638. if (abi_rt != rt) {
  5639. result = lb_emit_transmute(p, result, rt);
  5640. }
  5641. }
  5642. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  5643. if (found != nullptr) {
  5644. Entity *e = *found;
  5645. if (e != nullptr && entity_has_deferred_procedure(e)) {
  5646. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  5647. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  5648. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  5649. GB_ASSERT(deferred_found != nullptr);
  5650. lbValue deferred = *deferred_found;
  5651. auto in_args = args;
  5652. Array<lbValue> result_as_args = {};
  5653. switch (kind) {
  5654. case DeferredProcedure_none:
  5655. break;
  5656. case DeferredProcedure_in:
  5657. result_as_args = in_args;
  5658. break;
  5659. case DeferredProcedure_out:
  5660. result_as_args = lb_value_to_array(p, result);
  5661. break;
  5662. }
  5663. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  5664. }
  5665. }
  5666. return result;
  5667. }
  5668. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  5669. Type *t = s.type;
  5670. GB_ASSERT(is_type_pointer(t));
  5671. Type *st = base_type(type_deref(t));
  5672. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  5673. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  5674. LLVMValueRef indices[2] = {};
  5675. indices[0] = llvm_zero32(p->module);
  5676. indices[1] = lb_emit_conv(p, index, t_int).value;
  5677. Type *ptr = base_array_type(st);
  5678. lbValue res = {};
  5679. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  5680. res.type = alloc_type_pointer(ptr);
  5681. return res;
  5682. }
  5683. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  5684. Type *t = s.type;
  5685. GB_ASSERT(is_type_pointer(t));
  5686. Type *st = base_type(type_deref(t));
  5687. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  5688. GB_ASSERT(0 <= index);
  5689. Type *ptr = base_array_type(st);
  5690. LLVMValueRef indices[2] = {
  5691. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  5692. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  5693. };
  5694. lbValue res = {};
  5695. if (lb_is_const(s)) {
  5696. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  5697. } else {
  5698. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  5699. }
  5700. res.type = alloc_type_pointer(ptr);
  5701. return res;
  5702. }
  5703. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  5704. LLVMValueRef indices[1] = {index.value};
  5705. lbValue res = {};
  5706. res.type = ptr.type;
  5707. if (lb_is_const(ptr) && lb_is_const(index)) {
  5708. res.value = LLVMConstGEP(ptr.value, indices, 1);
  5709. } else {
  5710. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  5711. }
  5712. return res;
  5713. }
  5714. LLVMValueRef llvm_const_slice(lbValue data, lbValue len) {
  5715. GB_ASSERT(is_type_pointer(data.type));
  5716. GB_ASSERT(are_types_identical(len.type, t_int));
  5717. LLVMValueRef vals[2] = {
  5718. data.value,
  5719. len.value,
  5720. };
  5721. return LLVMConstStruct(vals, gb_count_of(vals), false);
  5722. }
  5723. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  5724. Type *t = lb_addr_type(slice);
  5725. GB_ASSERT(is_type_slice(t));
  5726. lbValue ptr = lb_addr_get_ptr(p, slice);
  5727. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  5728. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  5729. }
  5730. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  5731. Type *t = lb_addr_type(string);
  5732. GB_ASSERT(is_type_string(t));
  5733. lbValue ptr = lb_addr_get_ptr(p, string);
  5734. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  5735. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  5736. }
  5737. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  5738. Type *t = base_type(string.type);
  5739. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  5740. return lb_emit_struct_ev(p, string, 0);
  5741. }
  5742. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  5743. Type *t = base_type(string.type);
  5744. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  5745. return lb_emit_struct_ev(p, string, 1);
  5746. }
  5747. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  5748. GB_ASSERT(is_type_cstring(value.type));
  5749. auto args = array_make<lbValue>(heap_allocator(), 1);
  5750. args[0] = lb_emit_conv(p, value, t_cstring);
  5751. return lb_emit_runtime_call(p, "cstring_len", args);
  5752. }
  5753. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  5754. Type *t = type_deref(array_ptr.type);
  5755. GB_ASSERT(is_type_array(t));
  5756. return lb_emit_struct_ep(p, array_ptr, 0);
  5757. }
  5758. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  5759. GB_ASSERT(is_type_slice(slice.type));
  5760. return lb_emit_struct_ev(p, slice, 0);
  5761. }
  5762. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  5763. GB_ASSERT(is_type_slice(slice.type));
  5764. return lb_emit_struct_ev(p, slice, 1);
  5765. }
  5766. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  5767. GB_ASSERT(is_type_dynamic_array(da.type));
  5768. return lb_emit_struct_ev(p, da, 0);
  5769. }
  5770. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  5771. GB_ASSERT(is_type_dynamic_array(da.type));
  5772. return lb_emit_struct_ev(p, da, 1);
  5773. }
  5774. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  5775. GB_ASSERT(is_type_dynamic_array(da.type));
  5776. return lb_emit_struct_ev(p, da, 2);
  5777. }
  5778. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  5779. GB_ASSERT(is_type_dynamic_array(da.type));
  5780. return lb_emit_struct_ev(p, da, 3);
  5781. }
  5782. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  5783. gbAllocator a = heap_allocator();
  5784. Type *t = base_type(value.type);
  5785. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  5786. init_map_internal_types(t);
  5787. Type *gst = t->Map.generated_struct_type;
  5788. i32 index = 1;
  5789. lbValue entries = lb_emit_struct_ev(p, value, index);
  5790. return entries;
  5791. }
  5792. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  5793. gbAllocator a = heap_allocator();
  5794. Type *t = base_type(type_deref(value.type));
  5795. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  5796. init_map_internal_types(t);
  5797. Type *gst = t->Map.generated_struct_type;
  5798. i32 index = 1;
  5799. lbValue entries = lb_emit_struct_ep(p, value, index);
  5800. return entries;
  5801. }
  5802. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  5803. lbValue entries = lb_map_entries(p, value);
  5804. return lb_dynamic_array_len(p, entries);
  5805. }
  5806. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  5807. lbValue entries = lb_map_entries(p, value);
  5808. return lb_dynamic_array_cap(p, entries);
  5809. }
  5810. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  5811. Type *t = base_type(value.type);
  5812. bool is_ptr = false;
  5813. if (is_type_pointer(t)) {
  5814. is_ptr = true;
  5815. t = base_type(type_deref(t));
  5816. }
  5817. if (t->Struct.soa_kind == StructSoa_Fixed) {
  5818. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  5819. }
  5820. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  5821. t->Struct.soa_kind == StructSoa_Dynamic);
  5822. isize n = 0;
  5823. Type *elem = base_type(t->Struct.soa_elem);
  5824. if (elem->kind == Type_Struct) {
  5825. n = elem->Struct.fields.count;
  5826. } else if (elem->kind == Type_Array) {
  5827. n = elem->Array.count;
  5828. } else {
  5829. GB_PANIC("Unreachable");
  5830. }
  5831. if (is_ptr) {
  5832. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  5833. return lb_emit_load(p, v);
  5834. }
  5835. return lb_emit_struct_ev(p, value, cast(i32)n);
  5836. }
  5837. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  5838. Type *t = base_type(value.type);
  5839. bool is_ptr = false;
  5840. if (is_type_pointer(t)) {
  5841. is_ptr = true;
  5842. t = base_type(type_deref(t));
  5843. }
  5844. if (t->Struct.soa_kind == StructSoa_Fixed) {
  5845. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  5846. }
  5847. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  5848. isize n = 0;
  5849. Type *elem = base_type(t->Struct.soa_elem);
  5850. if (elem->kind == Type_Struct) {
  5851. n = elem->Struct.fields.count+1;
  5852. } else if (elem->kind == Type_Array) {
  5853. n = elem->Array.count+1;
  5854. } else {
  5855. GB_PANIC("Unreachable");
  5856. }
  5857. if (is_ptr) {
  5858. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  5859. return lb_emit_load(p, v);
  5860. }
  5861. return lb_emit_struct_ev(p, value, cast(i32)n);
  5862. }
  5863. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  5864. ast_node(ce, CallExpr, expr);
  5865. switch (id) {
  5866. case BuiltinProc_DIRECTIVE: {
  5867. ast_node(bd, BasicDirective, ce->proc);
  5868. String name = bd->name;
  5869. GB_ASSERT(name == "location");
  5870. String procedure = p->entity->token.string;
  5871. TokenPos pos = ast_token(ce->proc).pos;
  5872. if (ce->args.count > 0) {
  5873. Ast *ident = unselector_expr(ce->args[0]);
  5874. GB_ASSERT(ident->kind == Ast_Ident);
  5875. Entity *e = entity_of_ident(ident);
  5876. GB_ASSERT(e != nullptr);
  5877. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  5878. procedure = e->parent_proc_decl->entity->token.string;
  5879. } else {
  5880. procedure = str_lit("");
  5881. }
  5882. pos = e->token.pos;
  5883. }
  5884. return lb_emit_source_code_location(p, procedure, pos);
  5885. }
  5886. case BuiltinProc_type_info_of: {
  5887. Ast *arg = ce->args[0];
  5888. TypeAndValue tav = type_and_value_of_expr(arg);
  5889. if (tav.mode == Addressing_Type) {
  5890. Type *t = default_type(type_of_expr(arg));
  5891. return lb_type_info(p->module, t);
  5892. }
  5893. GB_ASSERT(is_type_typeid(tav.type));
  5894. auto args = array_make<lbValue>(heap_allocator(), 1);
  5895. args[0] = lb_build_expr(p, arg);
  5896. return lb_emit_runtime_call(p, "__type_info_of", args);
  5897. }
  5898. case BuiltinProc_typeid_of: {
  5899. Ast *arg = ce->args[0];
  5900. TypeAndValue tav = type_and_value_of_expr(arg);
  5901. if (tav.mode == Addressing_Type) {
  5902. Type *t = default_type(type_of_expr(arg));
  5903. return lb_typeid(p->module, t);
  5904. }
  5905. Type *t = base_type(tav.type);
  5906. GB_ASSERT(are_types_identical(t, t_type_info_ptr));
  5907. auto args = array_make<lbValue>(heap_allocator(), 1);
  5908. args[0] = lb_emit_conv(p, lb_build_expr(p, arg), t_type_info_ptr);
  5909. return lb_emit_runtime_call(p, "__typeid_of", args);
  5910. }
  5911. case BuiltinProc_len: {
  5912. lbValue v = lb_build_expr(p, ce->args[0]);
  5913. Type *t = base_type(v.type);
  5914. if (is_type_pointer(t)) {
  5915. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5916. v = lb_emit_load(p, v);
  5917. t = type_deref(t);
  5918. }
  5919. if (is_type_cstring(t)) {
  5920. return lb_cstring_len(p, v);
  5921. } else if (is_type_string(t)) {
  5922. return lb_string_len(p, v);
  5923. } else if (is_type_array(t)) {
  5924. GB_PANIC("Array lengths are constant");
  5925. } else if (is_type_slice(t)) {
  5926. return lb_slice_len(p, v);
  5927. } else if (is_type_dynamic_array(t)) {
  5928. return lb_dynamic_array_len(p, v);
  5929. } else if (is_type_map(t)) {
  5930. return lb_map_len(p, v);
  5931. } else if (is_type_soa_struct(t)) {
  5932. return lb_soa_struct_len(p, v);
  5933. }
  5934. GB_PANIC("Unreachable");
  5935. break;
  5936. }
  5937. case BuiltinProc_cap: {
  5938. lbValue v = lb_build_expr(p, ce->args[0]);
  5939. Type *t = base_type(v.type);
  5940. if (is_type_pointer(t)) {
  5941. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5942. v = lb_emit_load(p, v);
  5943. t = type_deref(t);
  5944. }
  5945. if (is_type_string(t)) {
  5946. GB_PANIC("Unreachable");
  5947. } else if (is_type_array(t)) {
  5948. GB_PANIC("Array lengths are constant");
  5949. } else if (is_type_slice(t)) {
  5950. return lb_slice_len(p, v);
  5951. } else if (is_type_dynamic_array(t)) {
  5952. return lb_dynamic_array_cap(p, v);
  5953. } else if (is_type_map(t)) {
  5954. return lb_map_cap(p, v);
  5955. } else if (is_type_soa_struct(t)) {
  5956. return lb_soa_struct_cap(p, v);
  5957. }
  5958. GB_PANIC("Unreachable");
  5959. break;
  5960. }
  5961. case BuiltinProc_swizzle: {
  5962. lbAddr addr = lb_build_addr(p, ce->args[0]);
  5963. isize index_count = ce->args.count-1;
  5964. if (index_count == 0) {
  5965. return lb_addr_load(p, addr);
  5966. }
  5967. lbValue src = lb_addr_get_ptr(p, addr);
  5968. // TODO(bill): Should this be zeroed or not?
  5969. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  5970. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  5971. for (i32 i = 1; i < ce->args.count; i++) {
  5972. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  5973. GB_ASSERT(is_type_integer(tv.type));
  5974. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  5975. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  5976. i32 dst_index = i-1;
  5977. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  5978. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  5979. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  5980. }
  5981. return lb_addr_load(p, dst);
  5982. }
  5983. case BuiltinProc_complex: {
  5984. lbValue real = lb_build_expr(p, ce->args[0]);
  5985. lbValue imag = lb_build_expr(p, ce->args[1]);
  5986. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  5987. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  5988. Type *ft = base_complex_elem_type(tv.type);
  5989. real = lb_emit_conv(p, real, ft);
  5990. imag = lb_emit_conv(p, imag, ft);
  5991. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  5992. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  5993. return lb_emit_load(p, dst);
  5994. }
  5995. case BuiltinProc_quaternion: {
  5996. lbValue real = lb_build_expr(p, ce->args[0]);
  5997. lbValue imag = lb_build_expr(p, ce->args[1]);
  5998. lbValue jmag = lb_build_expr(p, ce->args[2]);
  5999. lbValue kmag = lb_build_expr(p, ce->args[3]);
  6000. // @QuaternionLayout
  6001. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6002. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6003. Type *ft = base_complex_elem_type(tv.type);
  6004. real = lb_emit_conv(p, real, ft);
  6005. imag = lb_emit_conv(p, imag, ft);
  6006. jmag = lb_emit_conv(p, jmag, ft);
  6007. kmag = lb_emit_conv(p, kmag, ft);
  6008. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  6009. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  6010. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  6011. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  6012. return lb_emit_load(p, dst);
  6013. }
  6014. case BuiltinProc_real: {
  6015. lbValue val = lb_build_expr(p, ce->args[0]);
  6016. if (is_type_complex(val.type)) {
  6017. lbValue real = lb_emit_struct_ev(p, val, 0);
  6018. return lb_emit_conv(p, real, tv.type);
  6019. } else if (is_type_quaternion(val.type)) {
  6020. // @QuaternionLayout
  6021. lbValue real = lb_emit_struct_ev(p, val, 3);
  6022. return lb_emit_conv(p, real, tv.type);
  6023. }
  6024. GB_PANIC("invalid type for real");
  6025. return {};
  6026. }
  6027. case BuiltinProc_imag: {
  6028. lbValue val = lb_build_expr(p, ce->args[0]);
  6029. if (is_type_complex(val.type)) {
  6030. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6031. return lb_emit_conv(p, imag, tv.type);
  6032. } else if (is_type_quaternion(val.type)) {
  6033. // @QuaternionLayout
  6034. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6035. return lb_emit_conv(p, imag, tv.type);
  6036. }
  6037. GB_PANIC("invalid type for imag");
  6038. return {};
  6039. }
  6040. case BuiltinProc_jmag: {
  6041. lbValue val = lb_build_expr(p, ce->args[0]);
  6042. if (is_type_quaternion(val.type)) {
  6043. // @QuaternionLayout
  6044. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6045. return lb_emit_conv(p, imag, tv.type);
  6046. }
  6047. GB_PANIC("invalid type for jmag");
  6048. return {};
  6049. }
  6050. case BuiltinProc_kmag: {
  6051. lbValue val = lb_build_expr(p, ce->args[0]);
  6052. if (is_type_quaternion(val.type)) {
  6053. // @QuaternionLayout
  6054. lbValue imag = lb_emit_struct_ev(p, val, 2);
  6055. return lb_emit_conv(p, imag, tv.type);
  6056. }
  6057. GB_PANIC("invalid type for kmag");
  6058. return {};
  6059. }
  6060. case BuiltinProc_conj: {
  6061. lbValue val = lb_build_expr(p, ce->args[0]);
  6062. lbValue res = {};
  6063. Type *t = val.type;
  6064. if (is_type_complex(t)) {
  6065. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6066. lbValue real = lb_emit_struct_ev(p, val, 0);
  6067. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6068. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6069. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  6070. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  6071. } else if (is_type_quaternion(t)) {
  6072. // @QuaternionLayout
  6073. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6074. lbValue real = lb_emit_struct_ev(p, val, 3);
  6075. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6076. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  6077. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  6078. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6079. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  6080. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  6081. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  6082. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  6083. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  6084. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  6085. }
  6086. return lb_emit_load(p, res);
  6087. }
  6088. case BuiltinProc_expand_to_tuple: {
  6089. lbValue val = lb_build_expr(p, ce->args[0]);
  6090. Type *t = base_type(val.type);
  6091. if (!is_type_tuple(tv.type)) {
  6092. if (t->kind == Type_Struct) {
  6093. GB_ASSERT(t->Struct.fields.count == 1);
  6094. return lb_emit_struct_ev(p, val, 0);
  6095. } else if (t->kind == Type_Array) {
  6096. GB_ASSERT(t->Array.count == 1);
  6097. return lb_emit_array_epi(p, val, 0);
  6098. } else {
  6099. GB_PANIC("Unknown type of expand_to_tuple");
  6100. }
  6101. }
  6102. GB_ASSERT(is_type_tuple(tv.type));
  6103. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6104. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6105. if (t->kind == Type_Struct) {
  6106. for_array(src_index, t->Struct.fields) {
  6107. Entity *field = t->Struct.fields[src_index];
  6108. i32 field_index = field->Variable.field_index;
  6109. lbValue f = lb_emit_struct_ev(p, val, field_index);
  6110. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  6111. lb_emit_store(p, ep, f);
  6112. }
  6113. } else if (t->kind == Type_Array) {
  6114. // TODO(bill): Clean-up this code
  6115. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  6116. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  6117. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  6118. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  6119. lb_emit_store(p, ep, f);
  6120. }
  6121. } else {
  6122. GB_PANIC("Unknown type of expand_to_tuple");
  6123. }
  6124. return lb_emit_load(p, tuple);
  6125. }
  6126. case BuiltinProc_min: {
  6127. Type *t = type_of_expr(expr);
  6128. if (ce->args.count == 2) {
  6129. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6130. } else {
  6131. lbValue x = lb_build_expr(p, ce->args[0]);
  6132. for (isize i = 1; i < ce->args.count; i++) {
  6133. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  6134. }
  6135. return x;
  6136. }
  6137. }
  6138. case BuiltinProc_max: {
  6139. Type *t = type_of_expr(expr);
  6140. if (ce->args.count == 2) {
  6141. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6142. } else {
  6143. lbValue x = lb_build_expr(p, ce->args[0]);
  6144. for (isize i = 1; i < ce->args.count; i++) {
  6145. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  6146. }
  6147. return x;
  6148. }
  6149. }
  6150. case BuiltinProc_abs: {
  6151. gbAllocator a = heap_allocator();
  6152. lbValue x = lb_build_expr(p, ce->args[0]);
  6153. Type *t = x.type;
  6154. if (is_type_unsigned(t)) {
  6155. return x;
  6156. }
  6157. if (is_type_quaternion(t)) {
  6158. i64 sz = 8*type_size_of(t);
  6159. auto args = array_make<lbValue>(heap_allocator(), 1);
  6160. args[0] = x;
  6161. switch (sz) {
  6162. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  6163. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  6164. }
  6165. GB_PANIC("Unknown complex type");
  6166. } else if (is_type_complex(t)) {
  6167. i64 sz = 8*type_size_of(t);
  6168. auto args = array_make<lbValue>(heap_allocator(), 1);
  6169. args[0] = x;
  6170. switch (sz) {
  6171. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  6172. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  6173. }
  6174. GB_PANIC("Unknown complex type");
  6175. } else if (is_type_float(t)) {
  6176. i64 sz = 8*type_size_of(t);
  6177. auto args = array_make<lbValue>(heap_allocator(), 1);
  6178. args[0] = x;
  6179. switch (sz) {
  6180. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  6181. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  6182. }
  6183. GB_PANIC("Unknown float type");
  6184. }
  6185. lbValue zero = lb_const_nil(p->module, t);
  6186. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  6187. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  6188. return lb_emit_select(p, cond, neg, x);
  6189. }
  6190. case BuiltinProc_clamp:
  6191. return lb_emit_clamp(p, type_of_expr(expr),
  6192. lb_build_expr(p, ce->args[0]),
  6193. lb_build_expr(p, ce->args[1]),
  6194. lb_build_expr(p, ce->args[2]));
  6195. // "Intrinsics"
  6196. case BuiltinProc_cpu_relax:
  6197. // TODO(bill): BuiltinProc_cpu_relax
  6198. // ir_write_str_lit(f, "call void asm sideeffect \"pause\", \"\"()");
  6199. return {};
  6200. case BuiltinProc_atomic_fence:
  6201. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  6202. return {};
  6203. case BuiltinProc_atomic_fence_acq:
  6204. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  6205. return {};
  6206. case BuiltinProc_atomic_fence_rel:
  6207. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  6208. return {};
  6209. case BuiltinProc_atomic_fence_acqrel:
  6210. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  6211. return {};
  6212. case BuiltinProc_atomic_store:
  6213. case BuiltinProc_atomic_store_rel:
  6214. case BuiltinProc_atomic_store_relaxed:
  6215. case BuiltinProc_atomic_store_unordered: {
  6216. lbValue dst = lb_build_expr(p, ce->args[0]);
  6217. lbValue val = lb_build_expr(p, ce->args[1]);
  6218. val = lb_emit_conv(p, val, type_deref(dst.type));
  6219. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  6220. switch (id) {
  6221. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  6222. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  6223. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  6224. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  6225. }
  6226. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  6227. return {};
  6228. }
  6229. case BuiltinProc_atomic_load:
  6230. case BuiltinProc_atomic_load_acq:
  6231. case BuiltinProc_atomic_load_relaxed:
  6232. case BuiltinProc_atomic_load_unordered: {
  6233. lbValue dst = lb_build_expr(p, ce->args[0]);
  6234. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  6235. switch (id) {
  6236. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  6237. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  6238. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  6239. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  6240. }
  6241. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  6242. lbValue res = {};
  6243. res.value = instr;
  6244. res.type = type_deref(dst.type);
  6245. return res;
  6246. }
  6247. case BuiltinProc_atomic_add:
  6248. case BuiltinProc_atomic_add_acq:
  6249. case BuiltinProc_atomic_add_rel:
  6250. case BuiltinProc_atomic_add_acqrel:
  6251. case BuiltinProc_atomic_add_relaxed:
  6252. case BuiltinProc_atomic_sub:
  6253. case BuiltinProc_atomic_sub_acq:
  6254. case BuiltinProc_atomic_sub_rel:
  6255. case BuiltinProc_atomic_sub_acqrel:
  6256. case BuiltinProc_atomic_sub_relaxed:
  6257. case BuiltinProc_atomic_and:
  6258. case BuiltinProc_atomic_and_acq:
  6259. case BuiltinProc_atomic_and_rel:
  6260. case BuiltinProc_atomic_and_acqrel:
  6261. case BuiltinProc_atomic_and_relaxed:
  6262. case BuiltinProc_atomic_nand:
  6263. case BuiltinProc_atomic_nand_acq:
  6264. case BuiltinProc_atomic_nand_rel:
  6265. case BuiltinProc_atomic_nand_acqrel:
  6266. case BuiltinProc_atomic_nand_relaxed:
  6267. case BuiltinProc_atomic_or:
  6268. case BuiltinProc_atomic_or_acq:
  6269. case BuiltinProc_atomic_or_rel:
  6270. case BuiltinProc_atomic_or_acqrel:
  6271. case BuiltinProc_atomic_or_relaxed:
  6272. case BuiltinProc_atomic_xor:
  6273. case BuiltinProc_atomic_xor_acq:
  6274. case BuiltinProc_atomic_xor_rel:
  6275. case BuiltinProc_atomic_xor_acqrel:
  6276. case BuiltinProc_atomic_xor_relaxed:
  6277. case BuiltinProc_atomic_xchg:
  6278. case BuiltinProc_atomic_xchg_acq:
  6279. case BuiltinProc_atomic_xchg_rel:
  6280. case BuiltinProc_atomic_xchg_acqrel:
  6281. case BuiltinProc_atomic_xchg_relaxed: {
  6282. lbValue dst = lb_build_expr(p, ce->args[0]);
  6283. lbValue val = lb_build_expr(p, ce->args[1]);
  6284. val = lb_emit_conv(p, val, type_deref(dst.type));
  6285. LLVMAtomicRMWBinOp op = {};
  6286. LLVMAtomicOrdering ordering = {};
  6287. switch (id) {
  6288. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6289. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  6290. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  6291. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6292. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  6293. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6294. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  6295. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  6296. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6297. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  6298. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6299. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  6300. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  6301. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6302. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  6303. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6304. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  6305. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  6306. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6307. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  6308. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6309. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  6310. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  6311. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6312. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  6313. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6314. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  6315. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  6316. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6317. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  6318. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6319. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  6320. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  6321. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6322. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  6323. }
  6324. LLVMValueRef instr = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  6325. return {};
  6326. }
  6327. case BuiltinProc_atomic_cxchg:
  6328. case BuiltinProc_atomic_cxchg_acq:
  6329. case BuiltinProc_atomic_cxchg_rel:
  6330. case BuiltinProc_atomic_cxchg_acqrel:
  6331. case BuiltinProc_atomic_cxchg_relaxed:
  6332. case BuiltinProc_atomic_cxchg_failrelaxed:
  6333. case BuiltinProc_atomic_cxchg_failacq:
  6334. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  6335. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  6336. case BuiltinProc_atomic_cxchgweak:
  6337. case BuiltinProc_atomic_cxchgweak_acq:
  6338. case BuiltinProc_atomic_cxchgweak_rel:
  6339. case BuiltinProc_atomic_cxchgweak_acqrel:
  6340. case BuiltinProc_atomic_cxchgweak_relaxed:
  6341. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  6342. case BuiltinProc_atomic_cxchgweak_failacq:
  6343. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  6344. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  6345. Type *type = expr->tav.type;
  6346. lbValue address = lb_build_expr(p, ce->args[0]);
  6347. Type *elem = type_deref(address.type);
  6348. lbValue old_value = lb_build_expr(p, ce->args[1]);
  6349. lbValue new_value = lb_build_expr(p, ce->args[2]);
  6350. old_value = lb_emit_conv(p, old_value, elem);
  6351. new_value = lb_emit_conv(p, new_value, elem);
  6352. LLVMAtomicOrdering success_ordering = {};
  6353. LLVMAtomicOrdering failure_ordering = {};
  6354. LLVMBool weak = false;
  6355. switch (id) {
  6356. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6357. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6358. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6359. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6360. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6361. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6362. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  6363. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6364. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6365. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6366. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6367. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6368. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6369. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6370. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6371. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  6372. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6373. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6374. }
  6375. // TODO(bill): Figure out how to make it weak
  6376. LLVMBool single_threaded = !weak;
  6377. LLVMValueRef instr = LLVMBuildAtomicCmpXchg(p->builder, address.value,
  6378. old_value.value, new_value.value,
  6379. success_ordering,
  6380. failure_ordering,
  6381. single_threaded);
  6382. return {};
  6383. }
  6384. }
  6385. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  6386. return {};
  6387. }
  6388. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  6389. lbModule *m = p->module;
  6390. TypeAndValue tv = type_and_value_of_expr(expr);
  6391. ast_node(ce, CallExpr, expr);
  6392. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  6393. AddressingMode proc_mode = proc_tv.mode;
  6394. if (proc_mode == Addressing_Type) {
  6395. GB_ASSERT(ce->args.count == 1);
  6396. lbValue x = lb_build_expr(p, ce->args[0]);
  6397. lbValue y = lb_emit_conv(p, x, tv.type);
  6398. return y;
  6399. }
  6400. Ast *pexpr = unparen_expr(ce->proc);
  6401. if (proc_mode == Addressing_Builtin) {
  6402. Entity *e = entity_of_node(pexpr);
  6403. BuiltinProcId id = BuiltinProc_Invalid;
  6404. if (e != nullptr) {
  6405. id = cast(BuiltinProcId)e->Builtin.id;
  6406. } else {
  6407. id = BuiltinProc_DIRECTIVE;
  6408. }
  6409. return lb_build_builtin_proc(p, expr, tv, id);
  6410. }
  6411. // NOTE(bill): Regular call
  6412. lbValue value = {};
  6413. Ast *proc_expr = unparen_expr(ce->proc);
  6414. if (proc_expr->tav.mode == Addressing_Constant) {
  6415. ExactValue v = proc_expr->tav.value;
  6416. switch (v.kind) {
  6417. case ExactValue_Integer:
  6418. {
  6419. u64 u = big_int_to_u64(&v.value_integer);
  6420. lbValue x = {};
  6421. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  6422. x.type = t_uintptr;
  6423. x = lb_emit_conv(p, x, t_rawptr);
  6424. value = lb_emit_conv(p, x, proc_expr->tav.type);
  6425. break;
  6426. }
  6427. case ExactValue_Pointer:
  6428. {
  6429. u64 u = cast(u64)v.value_pointer;
  6430. lbValue x = {};
  6431. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  6432. x.type = t_uintptr;
  6433. x = lb_emit_conv(p, x, t_rawptr);
  6434. value = lb_emit_conv(p, x, proc_expr->tav.type);
  6435. break;
  6436. }
  6437. }
  6438. }
  6439. if (value.value == nullptr) {
  6440. value = lb_build_expr(p, proc_expr);
  6441. }
  6442. GB_ASSERT(value.value != nullptr);
  6443. Type *proc_type_ = base_type(value.type);
  6444. GB_ASSERT(proc_type_->kind == Type_Proc);
  6445. TypeProc *pt = &proc_type_->Proc;
  6446. set_procedure_abi_types(heap_allocator(), proc_type_);
  6447. if (is_call_expr_field_value(ce)) {
  6448. auto args = array_make<lbValue>(heap_allocator(), pt->param_count);
  6449. for_array(arg_index, ce->args) {
  6450. Ast *arg = ce->args[arg_index];
  6451. ast_node(fv, FieldValue, arg);
  6452. GB_ASSERT(fv->field->kind == Ast_Ident);
  6453. String name = fv->field->Ident.token.string;
  6454. isize index = lookup_procedure_parameter(pt, name);
  6455. GB_ASSERT(index >= 0);
  6456. TypeAndValue tav = type_and_value_of_expr(fv->value);
  6457. if (tav.mode == Addressing_Type) {
  6458. args[index] = lb_const_nil(m, tav.type);
  6459. } else {
  6460. args[index] = lb_build_expr(p, fv->value);
  6461. }
  6462. }
  6463. TypeTuple *params = &pt->params->Tuple;
  6464. for (isize i = 0; i < args.count; i++) {
  6465. Entity *e = params->variables[i];
  6466. if (e->kind == Entity_TypeName) {
  6467. args[i] = lb_const_nil(m, e->type);
  6468. } else if (e->kind == Entity_Constant) {
  6469. continue;
  6470. } else {
  6471. GB_ASSERT(e->kind == Entity_Variable);
  6472. if (args[i].value == nullptr) {
  6473. switch (e->Variable.param_value.kind) {
  6474. case ParameterValue_Constant:
  6475. args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  6476. break;
  6477. case ParameterValue_Nil:
  6478. args[i] = lb_const_nil(m, e->type);
  6479. break;
  6480. case ParameterValue_Location:
  6481. args[i] = lb_emit_source_code_location(p, p->entity->token.string, ast_token(expr).pos);
  6482. break;
  6483. case ParameterValue_Value:
  6484. args[i] = lb_build_expr(p, e->Variable.param_value.ast_value);
  6485. break;
  6486. }
  6487. } else {
  6488. args[i] = lb_emit_conv(p, args[i], e->type);
  6489. }
  6490. }
  6491. }
  6492. for (isize i = 0; i < args.count; i++) {
  6493. Entity *e = params->variables[i];
  6494. if (args[i].type == nullptr) {
  6495. continue;
  6496. } else if (is_type_untyped_nil(args[i].type)) {
  6497. args[i] = lb_const_nil(m, e->type);
  6498. } else if (is_type_untyped_undef(args[i].type)) {
  6499. args[i] = lb_const_undef(m, e->type);
  6500. }
  6501. }
  6502. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  6503. }
  6504. isize arg_index = 0;
  6505. isize arg_count = 0;
  6506. for_array(i, ce->args) {
  6507. Ast *arg = ce->args[i];
  6508. TypeAndValue tav = type_and_value_of_expr(arg);
  6509. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  6510. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  6511. Type *at = tav.type;
  6512. if (at->kind == Type_Tuple) {
  6513. arg_count += at->Tuple.variables.count;
  6514. } else {
  6515. arg_count++;
  6516. }
  6517. }
  6518. isize param_count = 0;
  6519. if (pt->params) {
  6520. GB_ASSERT(pt->params->kind == Type_Tuple);
  6521. param_count = pt->params->Tuple.variables.count;
  6522. }
  6523. auto args = array_make<lbValue>(heap_allocator(), cast(isize)gb_max(param_count, arg_count));
  6524. isize variadic_index = pt->variadic_index;
  6525. bool variadic = pt->variadic && variadic_index >= 0;
  6526. bool vari_expand = ce->ellipsis.pos.line != 0;
  6527. bool is_c_vararg = pt->c_vararg;
  6528. String proc_name = {};
  6529. if (p->entity != nullptr) {
  6530. proc_name = p->entity->token.string;
  6531. }
  6532. TokenPos pos = ast_token(ce->proc).pos;
  6533. TypeTuple *param_tuple = nullptr;
  6534. if (pt->params) {
  6535. GB_ASSERT(pt->params->kind == Type_Tuple);
  6536. param_tuple = &pt->params->Tuple;
  6537. }
  6538. for_array(i, ce->args) {
  6539. Ast *arg = ce->args[i];
  6540. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  6541. if (arg_tv.mode == Addressing_Type) {
  6542. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  6543. } else {
  6544. lbValue a = lb_build_expr(p, arg);
  6545. Type *at = a.type;
  6546. if (at->kind == Type_Tuple) {
  6547. for_array(i, at->Tuple.variables) {
  6548. Entity *e = at->Tuple.variables[i];
  6549. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  6550. args[arg_index++] = v;
  6551. }
  6552. } else {
  6553. args[arg_index++] = a;
  6554. }
  6555. }
  6556. }
  6557. if (param_count > 0) {
  6558. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  6559. GB_ASSERT(param_count < 1000000);
  6560. if (arg_count < param_count) {
  6561. isize end = cast(isize)param_count;
  6562. if (variadic) {
  6563. end = variadic_index;
  6564. }
  6565. while (arg_index < end) {
  6566. Entity *e = param_tuple->variables[arg_index];
  6567. GB_ASSERT(e->kind == Entity_Variable);
  6568. switch (e->Variable.param_value.kind) {
  6569. case ParameterValue_Constant:
  6570. args[arg_index++] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  6571. break;
  6572. case ParameterValue_Nil:
  6573. args[arg_index++] = lb_const_nil(m, e->type);
  6574. break;
  6575. case ParameterValue_Location:
  6576. args[arg_index++] = lb_emit_source_code_location(p, proc_name, pos);
  6577. break;
  6578. case ParameterValue_Value:
  6579. args[arg_index++] = lb_build_expr(p, e->Variable.param_value.ast_value);
  6580. break;
  6581. }
  6582. }
  6583. }
  6584. if (is_c_vararg) {
  6585. GB_ASSERT(variadic);
  6586. GB_ASSERT(!vari_expand);
  6587. isize i = 0;
  6588. for (; i < variadic_index; i++) {
  6589. Entity *e = param_tuple->variables[i];
  6590. if (e->kind == Entity_Variable) {
  6591. args[i] = lb_emit_conv(p, args[i], e->type);
  6592. }
  6593. }
  6594. Type *variadic_type = param_tuple->variables[i]->type;
  6595. GB_ASSERT(is_type_slice(variadic_type));
  6596. variadic_type = base_type(variadic_type)->Slice.elem;
  6597. if (!is_type_any(variadic_type)) {
  6598. for (; i < arg_count; i++) {
  6599. args[i] = lb_emit_conv(p, args[i], variadic_type);
  6600. }
  6601. } else {
  6602. for (; i < arg_count; i++) {
  6603. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  6604. }
  6605. }
  6606. } else if (variadic) {
  6607. isize i = 0;
  6608. for (; i < variadic_index; i++) {
  6609. Entity *e = param_tuple->variables[i];
  6610. if (e->kind == Entity_Variable) {
  6611. args[i] = lb_emit_conv(p, args[i], e->type);
  6612. }
  6613. }
  6614. if (!vari_expand) {
  6615. Type *variadic_type = param_tuple->variables[i]->type;
  6616. GB_ASSERT(is_type_slice(variadic_type));
  6617. variadic_type = base_type(variadic_type)->Slice.elem;
  6618. for (; i < arg_count; i++) {
  6619. args[i] = lb_emit_conv(p, args[i], variadic_type);
  6620. }
  6621. }
  6622. } else {
  6623. for (isize i = 0; i < param_count; i++) {
  6624. Entity *e = param_tuple->variables[i];
  6625. if (e->kind == Entity_Variable) {
  6626. if (args[i].value == nullptr) {
  6627. continue;
  6628. }
  6629. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  6630. args[i] = lb_emit_conv(p, args[i], e->type);
  6631. }
  6632. }
  6633. }
  6634. if (variadic && !vari_expand && !is_c_vararg) {
  6635. // variadic call argument generation
  6636. gbAllocator allocator = heap_allocator();
  6637. Type *slice_type = param_tuple->variables[variadic_index]->type;
  6638. Type *elem_type = base_type(slice_type)->Slice.elem;
  6639. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  6640. isize slice_len = arg_count+1 - (variadic_index+1);
  6641. if (slice_len > 0) {
  6642. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  6643. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  6644. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  6645. lb_emit_store(p, addr, args[i]);
  6646. }
  6647. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  6648. lbValue len = lb_const_int(m, t_int, slice_len);
  6649. lb_fill_slice(p, slice, base_elem, len);
  6650. }
  6651. arg_count = param_count;
  6652. args[variadic_index] = lb_addr_load(p, slice);
  6653. }
  6654. }
  6655. if (variadic && variadic_index+1 < param_count) {
  6656. for (isize i = variadic_index+1; i < param_count; i++) {
  6657. Entity *e = param_tuple->variables[i];
  6658. switch (e->Variable.param_value.kind) {
  6659. case ParameterValue_Constant:
  6660. args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  6661. break;
  6662. case ParameterValue_Nil:
  6663. args[i] = lb_const_nil(m, e->type);
  6664. break;
  6665. case ParameterValue_Location:
  6666. args[i] = lb_emit_source_code_location(p, proc_name, pos);
  6667. break;
  6668. case ParameterValue_Value:
  6669. args[i] = lb_build_expr(p, e->Variable.param_value.ast_value);
  6670. break;
  6671. }
  6672. }
  6673. }
  6674. isize final_count = param_count;
  6675. if (is_c_vararg) {
  6676. final_count = arg_count;
  6677. }
  6678. if (param_tuple != nullptr) {
  6679. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  6680. Entity *e = param_tuple->variables[i];
  6681. if (args[i].type == nullptr) {
  6682. continue;
  6683. } else if (is_type_untyped_nil(args[i].type)) {
  6684. args[i] = lb_const_nil(m, e->type);
  6685. } else if (is_type_untyped_undef(args[i].type)) {
  6686. args[i] = lb_const_undef(m, e->type);
  6687. }
  6688. }
  6689. }
  6690. auto call_args = array_slice(args, 0, final_count);
  6691. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  6692. }
  6693. bool lb_is_const(lbValue value) {
  6694. LLVMValueRef v = value.value;
  6695. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  6696. // TODO(bill): Is this correct behaviour?
  6697. return true;
  6698. }
  6699. if (LLVMIsConstant(v)) {
  6700. return true;
  6701. }
  6702. return false;
  6703. }
  6704. bool lb_is_const_nil(lbValue value) {
  6705. LLVMValueRef v = value.value;
  6706. if (LLVMIsConstant(v)) {
  6707. if (LLVMIsAConstantAggregateZero(v)) {
  6708. return true;
  6709. } else if (LLVMIsAConstantPointerNull(v)) {
  6710. return true;
  6711. }
  6712. }
  6713. return false;
  6714. }
  6715. String lb_get_const_string(lbModule *m, lbValue value) {
  6716. GB_ASSERT(lb_is_const(value));
  6717. Type *t = base_type(value.type);
  6718. GB_ASSERT(are_types_identical(t, t_string));
  6719. unsigned ptr_indices[1] = {0};
  6720. unsigned len_indices[1] = {1};
  6721. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  6722. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  6723. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  6724. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  6725. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  6726. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  6727. size_t length = 0;
  6728. char const *text = LLVMGetAsString(underlying_ptr, &length);
  6729. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  6730. return make_string(cast(u8 const *)text, real_length);
  6731. }
  6732. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  6733. GB_ASSERT(is_type_pointer(addr.type));
  6734. Type *type = type_deref(addr.type);
  6735. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  6736. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  6737. }
  6738. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  6739. AstPackage *pkg = m->info->runtime_package;
  6740. Entity *e = scope_lookup_current(pkg->scope, name);
  6741. lbValue *found = nullptr;
  6742. if (m != e->code_gen_module) {
  6743. gb_mutex_lock(&m->mutex);
  6744. }
  6745. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6746. if (m != e->code_gen_module) {
  6747. gb_mutex_unlock(&m->mutex);
  6748. }
  6749. GB_ASSERT(found != nullptr);
  6750. return found->value;
  6751. }
  6752. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  6753. Type *vt = core_type(value.type);
  6754. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  6755. // TODO(bill): lb_emit_byte_swap
  6756. lbValue res = {};
  6757. res.type = platform_type;
  6758. res.value = value.value;
  6759. int sz = cast(int)type_size_of(vt);
  6760. if (sz > 1) {
  6761. if (is_type_float(platform_type)) {
  6762. String name = {};
  6763. switch (sz) {
  6764. case 4: name = str_lit("bswap_f32"); break;
  6765. case 8: name = str_lit("bswap_f64"); break;
  6766. default: GB_PANIC("unhandled byteswap size"); break;
  6767. }
  6768. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  6769. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  6770. } else {
  6771. GB_ASSERT(is_type_integer(platform_type));
  6772. String name = {};
  6773. switch (sz) {
  6774. case 2: name = str_lit("bswap_16"); break;
  6775. case 4: name = str_lit("bswap_32"); break;
  6776. case 8: name = str_lit("bswap_64"); break;
  6777. case 16: name = str_lit("bswap_128"); break;
  6778. default: GB_PANIC("unhandled byteswap size"); break;
  6779. }
  6780. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  6781. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  6782. }
  6783. }
  6784. return res;
  6785. }
  6786. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  6787. lbLoopData data = {};
  6788. lbValue max = lb_const_int(p->module, t_int, count);
  6789. data.idx_addr = lb_add_local_generated(p, index_type, true);
  6790. data.body = lb_create_block(p, "loop.body");
  6791. data.done = lb_create_block(p, "loop.done");
  6792. data.loop = lb_create_block(p, "loop.loop");
  6793. lb_emit_jump(p, data.loop);
  6794. lb_start_block(p, data.loop);
  6795. data.idx = lb_addr_load(p, data.idx_addr);
  6796. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  6797. lb_emit_if(p, cond, data.body, data.done);
  6798. lb_start_block(p, data.body);
  6799. return data;
  6800. }
  6801. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  6802. if (data.idx_addr.addr.value != nullptr) {
  6803. lb_emit_increment(p, data.idx_addr.addr);
  6804. lb_emit_jump(p, data.loop);
  6805. lb_start_block(p, data.done);
  6806. }
  6807. }
  6808. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  6809. lbValue res = {};
  6810. res.type = t_llvm_bool;
  6811. Type *t = x.type;
  6812. if (is_type_pointer(t)) {
  6813. if (op_kind == Token_CmpEq) {
  6814. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  6815. } else if (op_kind == Token_NotEq) {
  6816. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  6817. }
  6818. return res;
  6819. } else if (is_type_cstring(t)) {
  6820. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  6821. if (op_kind == Token_CmpEq) {
  6822. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  6823. } else if (op_kind == Token_NotEq) {
  6824. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  6825. }
  6826. return res;
  6827. } else if (is_type_proc(t)) {
  6828. if (op_kind == Token_CmpEq) {
  6829. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  6830. } else if (op_kind == Token_NotEq) {
  6831. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  6832. }
  6833. return res;
  6834. } else if (is_type_any(t)) {
  6835. // TODO(bill): is this correct behaviour for nil comparison for any?
  6836. lbValue data = lb_emit_struct_ev(p, x, 0);
  6837. lbValue ti = lb_emit_struct_ev(p, x, 1);
  6838. if (op_kind == Token_CmpEq) {
  6839. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  6840. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  6841. res.value = LLVMBuildOr(p->builder, a, b, "");
  6842. return res;
  6843. } else if (op_kind == Token_NotEq) {
  6844. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  6845. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  6846. res.value = LLVMBuildAnd(p->builder, a, b, "");
  6847. return res;
  6848. }
  6849. } else if (is_type_slice(t)) {
  6850. lbValue len = lb_emit_struct_ev(p, x, 1);
  6851. if (op_kind == Token_CmpEq) {
  6852. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  6853. return res;
  6854. } else if (op_kind == Token_NotEq) {
  6855. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  6856. return res;
  6857. }
  6858. } else if (is_type_dynamic_array(t)) {
  6859. lbValue cap = lb_emit_struct_ev(p, x, 2);
  6860. if (op_kind == Token_CmpEq) {
  6861. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  6862. return res;
  6863. } else if (op_kind == Token_NotEq) {
  6864. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  6865. return res;
  6866. }
  6867. } else if (is_type_map(t)) {
  6868. lbValue cap = lb_map_cap(p, x);
  6869. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  6870. } else if (is_type_union(t)) {
  6871. if (type_size_of(t) == 0) {
  6872. if (op_kind == Token_CmpEq) {
  6873. return lb_const_bool(p->module, t_llvm_bool, true);
  6874. } else if (op_kind == Token_NotEq) {
  6875. return lb_const_bool(p->module, t_llvm_bool, false);
  6876. }
  6877. } else {
  6878. lbValue tag = lb_emit_union_tag_value(p, x);
  6879. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  6880. }
  6881. } else if (is_type_typeid(t)) {
  6882. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  6883. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  6884. } else if (is_type_bit_field(t)) {
  6885. auto args = array_make<lbValue>(heap_allocator(), 2);
  6886. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  6887. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  6888. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  6889. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  6890. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  6891. return res;
  6892. } else if (is_type_soa_struct(t)) {
  6893. Type *bt = base_type(t);
  6894. if (bt->Struct.soa_kind == StructSoa_Slice) {
  6895. lbValue len = lb_soa_struct_len(p, x);
  6896. if (op_kind == Token_CmpEq) {
  6897. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  6898. return res;
  6899. } else if (op_kind == Token_NotEq) {
  6900. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  6901. return res;
  6902. }
  6903. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  6904. lbValue cap = lb_soa_struct_cap(p, x);
  6905. if (op_kind == Token_CmpEq) {
  6906. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  6907. return res;
  6908. } else if (op_kind == Token_NotEq) {
  6909. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  6910. return res;
  6911. }
  6912. }
  6913. }
  6914. return {};
  6915. }
  6916. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  6917. Type *a = core_type(left.type);
  6918. Type *b = core_type(right.type);
  6919. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  6920. lbValue nil_check = {};
  6921. if (is_type_untyped_nil(left.type)) {
  6922. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  6923. } else if (is_type_untyped_nil(right.type)) {
  6924. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  6925. }
  6926. if (nil_check.value != nullptr) {
  6927. return nil_check;
  6928. }
  6929. if (are_types_identical(a, b)) {
  6930. // NOTE(bill): No need for a conversion
  6931. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  6932. left = lb_emit_conv(p, left, right.type);
  6933. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  6934. right = lb_emit_conv(p, right, left.type);
  6935. } else {
  6936. gbAllocator a = heap_allocator();
  6937. Type *lt = left.type;
  6938. Type *rt = right.type;
  6939. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  6940. Type *blt = base_type(lt);
  6941. Type *brt = base_type(rt);
  6942. GB_ASSERT(is_type_bit_field_value(blt));
  6943. GB_ASSERT(is_type_bit_field_value(brt));
  6944. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  6945. i64 bytes = bits / 8;
  6946. switch (bytes) {
  6947. case 1:
  6948. left = lb_emit_conv(p, left, t_u8);
  6949. right = lb_emit_conv(p, right, t_u8);
  6950. break;
  6951. case 2:
  6952. left = lb_emit_conv(p, left, t_u16);
  6953. right = lb_emit_conv(p, right, t_u16);
  6954. break;
  6955. case 4:
  6956. left = lb_emit_conv(p, left, t_u32);
  6957. right = lb_emit_conv(p, right, t_u32);
  6958. break;
  6959. case 8:
  6960. left = lb_emit_conv(p, left, t_u64);
  6961. right = lb_emit_conv(p, right, t_u64);
  6962. break;
  6963. default: GB_PANIC("Unknown integer size"); break;
  6964. }
  6965. }
  6966. lt = left.type;
  6967. rt = right.type;
  6968. i64 ls = type_size_of(lt);
  6969. i64 rs = type_size_of(rt);
  6970. if (ls < rs) {
  6971. left = lb_emit_conv(p, left, rt);
  6972. } else if (ls > rs) {
  6973. right = lb_emit_conv(p, right, lt);
  6974. } else {
  6975. right = lb_emit_conv(p, right, lt);
  6976. }
  6977. }
  6978. if (is_type_array(a)) {
  6979. Type *tl = base_type(a);
  6980. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  6981. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  6982. TokenKind cmp_op = Token_And;
  6983. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  6984. if (op_kind == Token_NotEq) {
  6985. res = lb_const_bool(p->module, t_llvm_bool, false);
  6986. cmp_op = Token_Or;
  6987. } else if (op_kind == Token_CmpEq) {
  6988. res = lb_const_bool(p->module, t_llvm_bool, true);
  6989. cmp_op = Token_And;
  6990. }
  6991. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  6992. i32 count = cast(i32)tl->Array.count;
  6993. if (inline_array_arith) {
  6994. // inline
  6995. lbAddr val = lb_add_local_generated(p, t_bool, false);
  6996. lb_addr_store(p, val, res);
  6997. for (i32 i = 0; i < count; i++) {
  6998. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  6999. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  7000. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7001. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7002. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7003. }
  7004. return lb_addr_load(p, val);
  7005. } else {
  7006. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  7007. // TODO(bill): Test to see if this is actually faster!!!!
  7008. auto args = array_make<lbValue>(heap_allocator(), 3);
  7009. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7010. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  7011. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  7012. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  7013. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  7014. return lb_emit_conv(p, res, t_bool);
  7015. } else {
  7016. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7017. lb_addr_store(p, val, res);
  7018. auto loop_data = lb_loop_start(p, count, t_i32);
  7019. {
  7020. lbValue i = loop_data.idx;
  7021. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  7022. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  7023. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7024. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7025. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7026. }
  7027. lb_loop_end(p, loop_data);
  7028. return lb_addr_load(p, val);
  7029. }
  7030. }
  7031. }
  7032. if (is_type_string(a)) {
  7033. if (is_type_cstring(a)) {
  7034. left = lb_emit_conv(p, left, t_string);
  7035. right = lb_emit_conv(p, right, t_string);
  7036. }
  7037. char const *runtime_procedure = nullptr;
  7038. switch (op_kind) {
  7039. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  7040. case Token_NotEq: runtime_procedure = "string_ne"; break;
  7041. case Token_Lt: runtime_procedure = "string_lt"; break;
  7042. case Token_Gt: runtime_procedure = "string_gt"; break;
  7043. case Token_LtEq: runtime_procedure = "string_le"; break;
  7044. case Token_GtEq: runtime_procedure = "string_gt"; break;
  7045. }
  7046. GB_ASSERT(runtime_procedure != nullptr);
  7047. auto args = array_make<lbValue>(heap_allocator(), 2);
  7048. args[0] = left;
  7049. args[1] = right;
  7050. return lb_emit_runtime_call(p, runtime_procedure, args);
  7051. }
  7052. if (is_type_complex(a)) {
  7053. char const *runtime_procedure = "";
  7054. i64 sz = 8*type_size_of(a);
  7055. switch (sz) {
  7056. case 64:
  7057. switch (op_kind) {
  7058. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  7059. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  7060. }
  7061. break;
  7062. case 128:
  7063. switch (op_kind) {
  7064. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  7065. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  7066. }
  7067. break;
  7068. }
  7069. GB_ASSERT(runtime_procedure != nullptr);
  7070. auto args = array_make<lbValue>(heap_allocator(), 2);
  7071. args[0] = left;
  7072. args[1] = right;
  7073. return lb_emit_runtime_call(p, runtime_procedure, args);
  7074. }
  7075. if (is_type_quaternion(a)) {
  7076. char const *runtime_procedure = "";
  7077. i64 sz = 8*type_size_of(a);
  7078. switch (sz) {
  7079. case 128:
  7080. switch (op_kind) {
  7081. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  7082. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  7083. }
  7084. break;
  7085. case 256:
  7086. switch (op_kind) {
  7087. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  7088. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  7089. }
  7090. break;
  7091. }
  7092. GB_ASSERT(runtime_procedure != nullptr);
  7093. auto args = array_make<lbValue>(heap_allocator(), 2);
  7094. args[0] = left;
  7095. args[1] = right;
  7096. return lb_emit_runtime_call(p, runtime_procedure, args);
  7097. }
  7098. if (is_type_bit_set(a)) {
  7099. switch (op_kind) {
  7100. case Token_Lt:
  7101. case Token_LtEq:
  7102. case Token_Gt:
  7103. case Token_GtEq:
  7104. {
  7105. Type *it = bit_set_to_int(a);
  7106. lbValue lhs = lb_emit_transmute(p, left, it);
  7107. lbValue rhs = lb_emit_transmute(p, right, it);
  7108. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  7109. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  7110. // (lhs & rhs) == lhs
  7111. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  7112. res.type = t_llvm_bool;
  7113. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  7114. // (lhs & rhs) == rhs
  7115. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  7116. res.type = t_llvm_bool;
  7117. }
  7118. // NOTE(bill): Strict subsets
  7119. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  7120. // res &~ (lhs == rhs)
  7121. lbValue eq = {};
  7122. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  7123. eq.type = t_llvm_bool;
  7124. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  7125. }
  7126. return res;
  7127. }
  7128. case Token_CmpEq:
  7129. case Token_NotEq:
  7130. {
  7131. LLVMIntPredicate pred = {};
  7132. switch (op_kind) {
  7133. case Token_CmpEq: pred = LLVMIntEQ; break;
  7134. case Token_NotEq: pred = LLVMIntNE; break;
  7135. }
  7136. lbValue res = {};
  7137. res.type = t_llvm_bool;
  7138. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7139. return res;
  7140. }
  7141. }
  7142. }
  7143. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  7144. Type *t = left.type;
  7145. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  7146. Type *platform_type = integer_endian_type_to_platform_type(t);
  7147. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  7148. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  7149. left = x;
  7150. right = y;
  7151. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  7152. Type *platform_type = integer_endian_type_to_platform_type(t);
  7153. lbValue x = lb_emit_conv(p, left, platform_type);
  7154. lbValue y = lb_emit_conv(p, right, platform_type);
  7155. left = x;
  7156. right = y;
  7157. }
  7158. }
  7159. a = core_type(left.type);
  7160. b = core_type(right.type);
  7161. lbValue res = {};
  7162. res.type = t_llvm_bool;
  7163. if (is_type_integer(a) ||
  7164. is_type_boolean(a) ||
  7165. is_type_pointer(a) ||
  7166. is_type_proc(a) ||
  7167. is_type_enum(a)) {
  7168. LLVMIntPredicate pred = {};
  7169. if (is_type_unsigned(left.type)) {
  7170. switch (op_kind) {
  7171. case Token_Gt: pred = LLVMIntUGT; break;
  7172. case Token_GtEq: pred = LLVMIntUGE; break;
  7173. case Token_Lt: pred = LLVMIntULT; break;
  7174. case Token_LtEq: pred = LLVMIntULE; break;
  7175. }
  7176. } else {
  7177. switch (op_kind) {
  7178. case Token_Gt: pred = LLVMIntSGT; break;
  7179. case Token_GtEq: pred = LLVMIntSGE; break;
  7180. case Token_Lt: pred = LLVMIntSLT; break;
  7181. case Token_LtEq: pred = LLVMIntSLE; break;
  7182. }
  7183. }
  7184. switch (op_kind) {
  7185. case Token_CmpEq: pred = LLVMIntEQ; break;
  7186. case Token_NotEq: pred = LLVMIntNE; break;
  7187. }
  7188. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7189. } else if (is_type_float(a)) {
  7190. LLVMRealPredicate pred = {};
  7191. switch (op_kind) {
  7192. case Token_CmpEq: pred = LLVMRealOEQ; break;
  7193. case Token_Gt: pred = LLVMRealOGT; break;
  7194. case Token_GtEq: pred = LLVMRealOGE; break;
  7195. case Token_Lt: pred = LLVMRealOLT; break;
  7196. case Token_LtEq: pred = LLVMRealOLE; break;
  7197. case Token_NotEq: pred = LLVMRealONE; break;
  7198. }
  7199. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  7200. } else if (is_type_typeid(a)) {
  7201. LLVMIntPredicate pred = {};
  7202. switch (op_kind) {
  7203. case Token_Gt: pred = LLVMIntUGT; break;
  7204. case Token_GtEq: pred = LLVMIntUGE; break;
  7205. case Token_Lt: pred = LLVMIntULT; break;
  7206. case Token_LtEq: pred = LLVMIntULE; break;
  7207. case Token_CmpEq: pred = LLVMIntEQ; break;
  7208. case Token_NotEq: pred = LLVMIntNE; break;
  7209. }
  7210. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7211. } else {
  7212. 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)));
  7213. }
  7214. return res;
  7215. }
  7216. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  7217. ast_node(pl, ProcLit, expr);
  7218. // NOTE(bill): Generate a new name
  7219. // parent$count
  7220. isize name_len = prefix_name.len + 1 + 8 + 1;
  7221. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  7222. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  7223. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  7224. String name = make_string((u8 *)name_text, name_len-1);
  7225. Type *type = type_of_expr(expr);
  7226. set_procedure_abi_types(heap_allocator(), type);
  7227. Token token = {};
  7228. token.pos = ast_token(expr).pos;
  7229. token.kind = Token_Ident;
  7230. token.string = name;
  7231. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  7232. e->decl_info = pl->decl;
  7233. lbProcedure *p = lb_create_procedure(m, e);
  7234. lbValue value = {};
  7235. value.value = p->value;
  7236. value.type = p->type;
  7237. array_add(&m->procedures_to_generate, p);
  7238. if (parent != nullptr) {
  7239. array_add(&parent->children, p);
  7240. } else {
  7241. string_map_set(&m->members, name, value);
  7242. }
  7243. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  7244. return value;
  7245. }
  7246. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  7247. lbModule *m = p->module;
  7248. Type *src_type = value.type;
  7249. bool is_ptr = is_type_pointer(src_type);
  7250. bool is_tuple = true;
  7251. Type *tuple = type;
  7252. if (type->kind != Type_Tuple) {
  7253. is_tuple = false;
  7254. tuple = make_optional_ok_type(type);
  7255. }
  7256. lbAddr v = lb_add_local_generated(p, tuple, true);
  7257. if (is_ptr) {
  7258. value = lb_emit_load(p, value);
  7259. }
  7260. Type *src = base_type(type_deref(src_type));
  7261. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  7262. Type *dst = tuple->Tuple.variables[0]->type;
  7263. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  7264. lbValue tag = {};
  7265. lbValue dst_tag = {};
  7266. lbValue cond = {};
  7267. lbValue data = {};
  7268. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  7269. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  7270. if (is_type_union_maybe_pointer(src)) {
  7271. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  7272. } else {
  7273. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  7274. dst_tag = lb_const_union_tag(m, src, dst);
  7275. }
  7276. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  7277. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  7278. if (data.value != nullptr) {
  7279. GB_ASSERT(is_type_union_maybe_pointer(src));
  7280. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  7281. } else {
  7282. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  7283. }
  7284. lb_emit_if(p, cond, ok_block, end_block);
  7285. lb_start_block(p, ok_block);
  7286. if (data.value == nullptr) {
  7287. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  7288. }
  7289. lb_emit_store(p, gep0, data);
  7290. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  7291. lb_emit_jump(p, end_block);
  7292. lb_start_block(p, end_block);
  7293. if (!is_tuple) {
  7294. if (do_conversion_check) {
  7295. // NOTE(bill): Panic on invalid conversion
  7296. Type *dst_type = tuple->Tuple.variables[0]->type;
  7297. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  7298. auto args = array_make<lbValue>(heap_allocator(), 6);
  7299. args[0] = ok;
  7300. args[1] = lb_const_string(m, pos.file);
  7301. args[2] = lb_const_int(m, t_int, pos.line);
  7302. args[3] = lb_const_int(m, t_int, pos.column);
  7303. args[4] = lb_typeid(m, src_type);
  7304. args[5] = lb_typeid(m, dst_type);
  7305. lb_emit_runtime_call(p, "type_assertion_check", args);
  7306. }
  7307. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  7308. }
  7309. return lb_addr_load(p, v);
  7310. }
  7311. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  7312. lbModule *m = p->module;
  7313. Type *src_type = value.type;
  7314. if (is_type_pointer(src_type)) {
  7315. value = lb_emit_load(p, value);
  7316. }
  7317. bool is_tuple = true;
  7318. Type *tuple = type;
  7319. if (type->kind != Type_Tuple) {
  7320. is_tuple = false;
  7321. tuple = make_optional_ok_type(type);
  7322. }
  7323. Type *dst_type = tuple->Tuple.variables[0]->type;
  7324. lbAddr v = lb_add_local_generated(p, tuple, true);
  7325. lbValue dst_typeid = lb_typeid(m, dst_type);
  7326. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  7327. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  7328. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  7329. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  7330. lb_emit_if(p, cond, ok_block, end_block);
  7331. lb_start_block(p, ok_block);
  7332. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  7333. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  7334. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  7335. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  7336. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  7337. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  7338. lb_emit_jump(p, end_block);
  7339. lb_start_block(p, end_block);
  7340. if (!is_tuple) {
  7341. // NOTE(bill): Panic on invalid conversion
  7342. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  7343. auto args = array_make<lbValue>(heap_allocator(), 6);
  7344. args[0] = ok;
  7345. args[1] = lb_const_string(m, pos.file);
  7346. args[2] = lb_const_int(m, t_int, pos.line);
  7347. args[3] = lb_const_int(m, t_int, pos.column);
  7348. args[4] = any_typeid;
  7349. args[5] = dst_typeid;
  7350. lb_emit_runtime_call(p, "type_assertion_check", args);
  7351. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  7352. }
  7353. return v;
  7354. }
  7355. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  7356. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  7357. }
  7358. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  7359. lbModule *m = p->module;
  7360. expr = unparen_expr(expr);
  7361. TypeAndValue tv = type_and_value_of_expr(expr);
  7362. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "%s", expr_to_string(expr));
  7363. GB_ASSERT(tv.mode != Addressing_Type);
  7364. if (tv.value.kind != ExactValue_Invalid) {
  7365. // NOTE(bill): Short on constant values
  7366. return lb_const_value(p->module, tv.type, tv.value);
  7367. }
  7368. switch (expr->kind) {
  7369. case_ast_node(bl, BasicLit, expr);
  7370. TokenPos pos = bl->token.pos;
  7371. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  7372. case_end;
  7373. case_ast_node(bd, BasicDirective, expr);
  7374. TokenPos pos = bd->token.pos;
  7375. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  7376. case_end;
  7377. case_ast_node(i, Implicit, expr);
  7378. return lb_addr_load(p, lb_build_addr(p, expr));
  7379. case_end;
  7380. case_ast_node(u, Undef, expr)
  7381. lbValue res = {};
  7382. if (is_type_untyped(tv.type)) {
  7383. res.value = nullptr;
  7384. res.type = t_untyped_undef;
  7385. } else {
  7386. res.value = LLVMGetUndef(lb_type(m, tv.type));
  7387. res.type = tv.type;
  7388. }
  7389. return res;
  7390. case_end;
  7391. case_ast_node(i, Ident, expr);
  7392. Entity *e = entity_from_expr(expr);
  7393. e = strip_entity_wrapping(e);
  7394. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  7395. if (e->kind == Entity_Builtin) {
  7396. Token token = ast_token(expr);
  7397. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  7398. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  7399. LIT(token.pos.file), token.pos.line, token.pos.column);
  7400. return {};
  7401. } else if (e->kind == Entity_Nil) {
  7402. lbValue res = {};
  7403. res.value = nullptr;
  7404. res.type = e->type;
  7405. return res;
  7406. }
  7407. GB_ASSERT(e->kind != Entity_ProcGroup);
  7408. auto *found = map_get(&p->module->values, hash_entity(e));
  7409. if (found) {
  7410. auto v = *found;
  7411. // NOTE(bill): This is because pointers are already pointers in LLVM
  7412. if (is_type_proc(v.type)) {
  7413. return v;
  7414. }
  7415. return lb_emit_load(p, v);
  7416. } else if (e != nullptr && e->kind == Entity_Variable) {
  7417. return lb_addr_load(p, lb_build_addr(p, expr));
  7418. }
  7419. gb_printf_err("Error in: %.*s(%td:%td) %s\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  7420. String pkg = {};
  7421. if (e->pkg) {
  7422. pkg = e->pkg->name;
  7423. }
  7424. 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);
  7425. return {};
  7426. case_end;
  7427. case_ast_node(de, DerefExpr, expr);
  7428. return lb_addr_load(p, lb_build_addr(p, expr));
  7429. case_end;
  7430. case_ast_node(se, SelectorExpr, expr);
  7431. TypeAndValue tav = type_and_value_of_expr(expr);
  7432. GB_ASSERT(tav.mode != Addressing_Invalid);
  7433. return lb_addr_load(p, lb_build_addr(p, expr));
  7434. case_end;
  7435. case_ast_node(ise, ImplicitSelectorExpr, expr);
  7436. TypeAndValue tav = type_and_value_of_expr(expr);
  7437. GB_ASSERT(tav.mode == Addressing_Constant);
  7438. return lb_const_value(p->module, tv.type, tv.value);
  7439. case_end;
  7440. case_ast_node(te, TernaryExpr, expr);
  7441. LLVMValueRef incoming_values[2] = {};
  7442. LLVMBasicBlockRef incoming_blocks[2] = {};
  7443. GB_ASSERT(te->y != nullptr);
  7444. lbBlock *then = lb_create_block(p, "if.then");
  7445. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  7446. lbBlock *else_ = lb_create_block(p, "if.else");
  7447. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  7448. lb_start_block(p, then);
  7449. Type *type = default_type(type_of_expr(expr));
  7450. lb_open_scope(p);
  7451. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  7452. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7453. lb_emit_jump(p, done);
  7454. lb_start_block(p, else_);
  7455. lb_open_scope(p);
  7456. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  7457. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7458. lb_emit_jump(p, done);
  7459. lb_start_block(p, done);
  7460. lbValue res = {};
  7461. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  7462. res.type = type;
  7463. GB_ASSERT(p->curr_block->preds.count >= 2);
  7464. incoming_blocks[0] = p->curr_block->preds[0]->block;
  7465. incoming_blocks[1] = p->curr_block->preds[1]->block;
  7466. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  7467. return res;
  7468. case_end;
  7469. case_ast_node(te, TernaryIfExpr, expr);
  7470. LLVMValueRef incoming_values[2] = {};
  7471. LLVMBasicBlockRef incoming_blocks[2] = {};
  7472. GB_ASSERT(te->y != nullptr);
  7473. lbBlock *then = lb_create_block(p, "if.then");
  7474. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  7475. lbBlock *else_ = lb_create_block(p, "if.else");
  7476. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  7477. lb_start_block(p, then);
  7478. Type *type = default_type(type_of_expr(expr));
  7479. lb_open_scope(p);
  7480. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  7481. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7482. lb_emit_jump(p, done);
  7483. lb_start_block(p, else_);
  7484. lb_open_scope(p);
  7485. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  7486. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7487. lb_emit_jump(p, done);
  7488. lb_start_block(p, done);
  7489. lbValue res = {};
  7490. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  7491. res.type = type;
  7492. GB_ASSERT(p->curr_block->preds.count >= 2);
  7493. incoming_blocks[0] = p->curr_block->preds[0]->block;
  7494. incoming_blocks[1] = p->curr_block->preds[1]->block;
  7495. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  7496. return res;
  7497. case_end;
  7498. case_ast_node(te, TernaryWhenExpr, expr);
  7499. TypeAndValue tav = type_and_value_of_expr(te->cond);
  7500. GB_ASSERT(tav.mode == Addressing_Constant);
  7501. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  7502. if (tav.value.value_bool) {
  7503. return lb_build_expr(p, te->x);
  7504. } else {
  7505. return lb_build_expr(p, te->y);
  7506. }
  7507. case_end;
  7508. case_ast_node(ta, TypeAssertion, expr);
  7509. TokenPos pos = ast_token(expr).pos;
  7510. Type *type = tv.type;
  7511. lbValue e = lb_build_expr(p, ta->expr);
  7512. Type *t = type_deref(e.type);
  7513. if (is_type_union(t)) {
  7514. return lb_emit_union_cast(p, e, type, pos);
  7515. } else if (is_type_any(t)) {
  7516. return lb_emit_any_cast(p, e, type, pos);
  7517. } else {
  7518. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  7519. }
  7520. case_end;
  7521. case_ast_node(tc, TypeCast, expr);
  7522. lbValue e = lb_build_expr(p, tc->expr);
  7523. switch (tc->token.kind) {
  7524. case Token_cast:
  7525. return lb_emit_conv(p, e, tv.type);
  7526. case Token_transmute:
  7527. return lb_emit_transmute(p, e, tv.type);
  7528. }
  7529. GB_PANIC("Invalid AST TypeCast");
  7530. case_end;
  7531. case_ast_node(ac, AutoCast, expr);
  7532. return lb_build_expr(p, ac->expr);
  7533. case_end;
  7534. case_ast_node(ue, UnaryExpr, expr);
  7535. switch (ue->op.kind) {
  7536. case Token_And: {
  7537. Ast *ue_expr = unparen_expr(ue->expr);
  7538. if (ue_expr->kind == Ast_CompoundLit) {
  7539. lbValue v = lb_build_expr(p, ue->expr);
  7540. Type *type = v.type;
  7541. lbAddr addr = {};
  7542. if (p->is_startup) {
  7543. addr = lb_add_global_generated(p->module, type, v);
  7544. } else {
  7545. addr = lb_add_local_generated(p, type, false);
  7546. }
  7547. lb_addr_store(p, addr, v);
  7548. return addr.addr;
  7549. } else if (ue_expr->kind == Ast_TypeAssertion) {
  7550. gbAllocator a = heap_allocator();
  7551. GB_ASSERT(is_type_pointer(tv.type));
  7552. ast_node(ta, TypeAssertion, ue_expr);
  7553. TokenPos pos = ast_token(expr).pos;
  7554. Type *type = type_of_expr(ue_expr);
  7555. GB_ASSERT(!is_type_tuple(type));
  7556. lbValue e = lb_build_expr(p, ta->expr);
  7557. Type *t = type_deref(e.type);
  7558. if (is_type_union(t)) {
  7559. lbValue v = e;
  7560. if (!is_type_pointer(v.type)) {
  7561. v = lb_address_from_load_or_generate_local(p, v);
  7562. }
  7563. Type *src_type = type_deref(v.type);
  7564. Type *dst_type = type;
  7565. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  7566. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  7567. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  7568. auto args = array_make<lbValue>(heap_allocator(), 6);
  7569. args[0] = ok;
  7570. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  7571. args[2] = lb_const_int(p->module, t_int, pos.line);
  7572. args[3] = lb_const_int(p->module, t_int, pos.column);
  7573. args[4] = lb_typeid(p->module, src_type);
  7574. args[5] = lb_typeid(p->module, dst_type);
  7575. lb_emit_runtime_call(p, "type_assertion_check", args);
  7576. lbValue data_ptr = v;
  7577. return lb_emit_conv(p, data_ptr, tv.type);
  7578. } else if (is_type_any(t)) {
  7579. lbValue v = e;
  7580. if (is_type_pointer(v.type)) {
  7581. v = lb_emit_load(p, v);
  7582. }
  7583. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  7584. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  7585. lbValue id = lb_typeid(p->module, type);
  7586. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  7587. auto args = array_make<lbValue>(heap_allocator(), 6);
  7588. args[0] = ok;
  7589. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  7590. args[2] = lb_const_int(p->module, t_int, pos.line);
  7591. args[3] = lb_const_int(p->module, t_int, pos.column);
  7592. args[4] = any_id;
  7593. args[5] = id;
  7594. lb_emit_runtime_call(p, "type_assertion_check", args);
  7595. return lb_emit_conv(p, data_ptr, tv.type);
  7596. } else {
  7597. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  7598. }
  7599. }
  7600. return lb_build_addr_ptr(p, ue->expr);
  7601. }
  7602. default:
  7603. {
  7604. lbValue v = lb_build_expr(p, ue->expr);
  7605. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  7606. }
  7607. }
  7608. case_end;
  7609. case_ast_node(be, BinaryExpr, expr);
  7610. return lb_build_binary_expr(p, expr);
  7611. case_end;
  7612. case_ast_node(pl, ProcLit, expr);
  7613. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  7614. case_end;
  7615. case_ast_node(cl, CompoundLit, expr);
  7616. return lb_addr_load(p, lb_build_addr(p, expr));
  7617. case_end;
  7618. case_ast_node(ce, CallExpr, expr);
  7619. lbValue res = lb_build_call_expr(p, expr);
  7620. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  7621. GB_ASSERT(is_type_tuple(res.type));
  7622. GB_ASSERT(res.type->Tuple.variables.count == 2);
  7623. return lb_emit_struct_ev(p, res, 0);
  7624. }
  7625. return res;
  7626. case_end;
  7627. case_ast_node(se, SliceExpr, expr);
  7628. return lb_addr_load(p, lb_build_addr(p, expr));
  7629. case_end;
  7630. case_ast_node(ie, IndexExpr, expr);
  7631. return lb_addr_load(p, lb_build_addr(p, expr));
  7632. case_end;
  7633. }
  7634. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  7635. return {};
  7636. }
  7637. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  7638. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  7639. String name = e->token.string;
  7640. Entity *parent = e->using_parent;
  7641. Selection sel = lookup_field(parent->type, name, false);
  7642. GB_ASSERT(sel.entity != nullptr);
  7643. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  7644. lbValue v = {};
  7645. if (pv != nullptr) {
  7646. v = *pv;
  7647. } else {
  7648. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  7649. v = lb_build_addr_ptr(p, e->using_expr);
  7650. }
  7651. GB_ASSERT(v.value != nullptr);
  7652. GB_ASSERT(parent->type == type_deref(v.type));
  7653. return lb_emit_deep_field_gep(p, v, sel);
  7654. }
  7655. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  7656. GB_ASSERT(e != nullptr);
  7657. if (e->kind == Entity_Constant) {
  7658. Type *t = default_type(type_of_expr(expr));
  7659. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  7660. lbAddr g = lb_add_global_generated(p->module, t, v);
  7661. return g;
  7662. }
  7663. lbValue v = {};
  7664. lbValue *found = map_get(&p->module->values, hash_entity(e));
  7665. if (found) {
  7666. v = *found;
  7667. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  7668. // NOTE(bill): Calculate the using variable every time
  7669. v = lb_get_using_variable(p, e);
  7670. }
  7671. if (v.value == nullptr) {
  7672. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  7673. LIT(p->name),
  7674. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  7675. GB_PANIC("Unknown value");
  7676. }
  7677. return lb_addr(v);
  7678. }
  7679. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  7680. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  7681. gbAllocator a = heap_allocator();
  7682. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  7683. map_type = base_type(map_type);
  7684. GB_ASSERT(map_type->kind == Type_Map);
  7685. Type *key_type = map_type->Map.key;
  7686. Type *val_type = map_type->Map.value;
  7687. // NOTE(bill): Removes unnecessary allocation if split gep
  7688. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  7689. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  7690. lb_emit_store(p, gep0, m);
  7691. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_const_bool(p->module, t_bool, is_type_string(key_type)));
  7692. i64 entry_size = type_size_of (map_type->Map.entry_type);
  7693. i64 entry_align = type_align_of (map_type->Map.entry_type);
  7694. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  7695. i64 value_size = type_size_of (map_type->Map.value);
  7696. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  7697. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  7698. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, value_offset));
  7699. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, value_size));
  7700. return lb_addr_load(p, h);
  7701. }
  7702. lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) {
  7703. Type *hash_type = t_u64;
  7704. lbAddr v = lb_add_local_generated(p, t_map_key, true);
  7705. Type *t = base_type(key.type);
  7706. key = lb_emit_conv(p, key, key_type);
  7707. if (is_type_integer(t)) {
  7708. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, key, hash_type));
  7709. } else if (is_type_enum(t)) {
  7710. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, key, hash_type));
  7711. } else if (is_type_typeid(t)) {
  7712. lbValue i = lb_emit_transmute(p, key, t_uint);
  7713. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, i, hash_type));
  7714. } else if (is_type_pointer(t)) {
  7715. lbValue ptr = lb_emit_conv(p, key, t_uintptr);
  7716. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, ptr, hash_type));
  7717. } else if (is_type_float(t)) {
  7718. lbValue bits = {};
  7719. i64 size = type_size_of(t);
  7720. switch (8*size) {
  7721. case 32: bits = lb_emit_transmute(p, key, t_u32); break;
  7722. case 64: bits = lb_emit_transmute(p, key, t_u64); break;
  7723. default: GB_PANIC("Unhandled float size: %lld bits", size); break;
  7724. }
  7725. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, bits, hash_type));
  7726. } else if (is_type_string(t)) {
  7727. lbValue str = lb_emit_conv(p, key, t_string);
  7728. lbValue hashed_str = {};
  7729. if (false && lb_is_const(str)) {
  7730. String value = lb_get_const_string(p->module, str);
  7731. u64 hs = fnv64a(value.text, value.len);
  7732. hashed_str = lb_const_value(p->module, t_u64, exact_value_u64(hs));
  7733. } else {
  7734. auto args = array_make<lbValue>(heap_allocator(), 1);
  7735. args[0] = str;
  7736. hashed_str = lb_emit_runtime_call(p, "default_hash_string", args);
  7737. }
  7738. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), hashed_str);
  7739. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), str);
  7740. } else {
  7741. GB_PANIC("Unhandled map key type");
  7742. }
  7743. return lb_addr_load(p, v);
  7744. }
  7745. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  7746. lbValue map_key, lbValue map_value) {
  7747. map_type = base_type(map_type);
  7748. GB_ASSERT(map_type->kind == Type_Map);
  7749. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  7750. lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key);
  7751. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  7752. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  7753. lb_addr_store(p, value_addr, v);
  7754. auto args = array_make<lbValue>(heap_allocator(), 4);
  7755. args[0] = h;
  7756. args[1] = key;
  7757. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  7758. args[3] = lb_emit_source_code_location(p, nullptr);
  7759. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  7760. }
  7761. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  7762. expr = unparen_expr(expr);
  7763. switch (expr->kind) {
  7764. case_ast_node(i, Implicit, expr);
  7765. lbAddr v = {};
  7766. switch (i->kind) {
  7767. case Token_context:
  7768. v = lb_find_or_generate_context_ptr(p);
  7769. break;
  7770. }
  7771. GB_ASSERT(v.addr.value != nullptr);
  7772. return v;
  7773. case_end;
  7774. case_ast_node(i, Ident, expr);
  7775. if (is_blank_ident(expr)) {
  7776. lbAddr val = {};
  7777. return val;
  7778. }
  7779. String name = i->token.string;
  7780. Entity *e = entity_of_ident(expr);
  7781. return lb_build_addr_from_entity(p, e, expr);
  7782. case_end;
  7783. case_ast_node(se, SelectorExpr, expr);
  7784. Ast *sel = unparen_expr(se->selector);
  7785. if (sel->kind == Ast_Ident) {
  7786. String selector = sel->Ident.token.string;
  7787. TypeAndValue tav = type_and_value_of_expr(se->expr);
  7788. if (tav.mode == Addressing_Invalid) {
  7789. // NOTE(bill): Imports
  7790. Entity *imp = entity_of_ident(se->expr);
  7791. if (imp != nullptr) {
  7792. GB_ASSERT(imp->kind == Entity_ImportName);
  7793. }
  7794. return lb_build_addr(p, unparen_expr(se->selector));
  7795. }
  7796. Type *type = base_type(tav.type);
  7797. if (tav.mode == Addressing_Type) { // Addressing_Type
  7798. Selection sel = lookup_field(type, selector, true);
  7799. Entity *e = sel.entity;
  7800. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  7801. GB_ASSERT(e->flags & EntityFlag_TypeField);
  7802. String name = e->token.string;
  7803. /*if (name == "names") {
  7804. lbValue ti_ptr = lb_type_info(m, type);
  7805. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  7806. lbValue names_ptr = nullptr;
  7807. if (is_type_enum(type)) {
  7808. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  7809. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  7810. } else if (type->kind == Type_Struct) {
  7811. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  7812. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  7813. }
  7814. return ir_addr(names_ptr);
  7815. } else */{
  7816. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  7817. }
  7818. GB_PANIC("Unreachable");
  7819. }
  7820. Selection sel = lookup_field(type, selector, false);
  7821. GB_ASSERT(sel.entity != nullptr);
  7822. if (sel.entity->type->kind == Type_BitFieldValue) {
  7823. lbAddr addr = lb_build_addr(p, se->expr);
  7824. Type *bft = type_deref(lb_addr_type(addr));
  7825. if (sel.index.count == 1) {
  7826. GB_ASSERT(is_type_bit_field(bft));
  7827. i32 index = sel.index[0];
  7828. return lb_addr_bit_field(lb_addr_get_ptr(p, addr), index);
  7829. } else {
  7830. Selection s = sel;
  7831. s.index.count--;
  7832. i32 index = s.index[s.index.count-1];
  7833. lbValue a = lb_addr_get_ptr(p, addr);
  7834. a = lb_emit_deep_field_gep(p, a, s);
  7835. return lb_addr_bit_field(a, index);
  7836. }
  7837. } else {
  7838. lbAddr addr = lb_build_addr(p, se->expr);
  7839. if (addr.kind == lbAddr_Map) {
  7840. lbValue v = lb_addr_load(p, addr);
  7841. lbValue a = lb_address_from_load_or_generate_local(p, v);
  7842. a = lb_emit_deep_field_gep(p, a, sel);
  7843. return lb_addr(a);
  7844. } else if (addr.kind == lbAddr_Context) {
  7845. GB_ASSERT(sel.index.count > 0);
  7846. if (addr.ctx.sel.index.count >= 0) {
  7847. sel = selection_combine(addr.ctx.sel, sel);
  7848. }
  7849. addr.ctx.sel = sel;
  7850. addr.kind = lbAddr_Context;
  7851. return addr;
  7852. } else if (addr.kind == lbAddr_SoaVariable) {
  7853. lbValue index = addr.soa.index;
  7854. i32 first_index = sel.index[0];
  7855. Selection sub_sel = sel;
  7856. sub_sel.index.data += 1;
  7857. sub_sel.index.count -= 1;
  7858. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  7859. Type *t = base_type(type_deref(addr.addr.type));
  7860. GB_ASSERT(is_type_soa_struct(t));
  7861. // TODO(bill): Bounds check
  7862. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  7863. lbValue len = lb_soa_struct_len(p, addr.addr);
  7864. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  7865. }
  7866. lbValue item = {};
  7867. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7868. item = lb_emit_array_ep(p, arr, index);
  7869. } else {
  7870. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  7871. }
  7872. if (sub_sel.index.count > 0) {
  7873. item = lb_emit_deep_field_gep(p, item, sub_sel);
  7874. }
  7875. return lb_addr(item);
  7876. }
  7877. lbValue a = lb_addr_get_ptr(p, addr);
  7878. a = lb_emit_deep_field_gep(p, a, sel);
  7879. return lb_addr(a);
  7880. }
  7881. } else {
  7882. GB_PANIC("Unsupported selector expression");
  7883. }
  7884. case_end;
  7885. case_ast_node(ta, TypeAssertion, expr);
  7886. gbAllocator a = heap_allocator();
  7887. TokenPos pos = ast_token(expr).pos;
  7888. lbValue e = lb_build_expr(p, ta->expr);
  7889. Type *t = type_deref(e.type);
  7890. if (is_type_union(t)) {
  7891. Type *type = type_of_expr(expr);
  7892. lbAddr v = lb_add_local_generated(p, type, false);
  7893. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  7894. return v;
  7895. } else if (is_type_any(t)) {
  7896. Type *type = type_of_expr(expr);
  7897. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  7898. } else {
  7899. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  7900. }
  7901. case_end;
  7902. case_ast_node(ue, UnaryExpr, expr);
  7903. switch (ue->op.kind) {
  7904. case Token_And: {
  7905. return lb_build_addr(p, ue->expr);
  7906. }
  7907. default:
  7908. GB_PANIC("Invalid unary expression for lb_build_addr");
  7909. }
  7910. case_end;
  7911. case_ast_node(be, BinaryExpr, expr);
  7912. lbValue v = lb_build_expr(p, expr);
  7913. Type *t = v.type;
  7914. if (is_type_pointer(t)) {
  7915. return lb_addr(v);
  7916. }
  7917. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  7918. case_end;
  7919. case_ast_node(ie, IndexExpr, expr);
  7920. Type *t = base_type(type_of_expr(ie->expr));
  7921. gbAllocator a = heap_allocator();
  7922. bool deref = is_type_pointer(t);
  7923. t = base_type(type_deref(t));
  7924. if (is_type_soa_struct(t)) {
  7925. // SOA STRUCTURES!!!!
  7926. lbValue val = lb_build_addr_ptr(p, ie->expr);
  7927. if (deref) {
  7928. val = lb_emit_load(p, val);
  7929. }
  7930. lbValue index = lb_build_expr(p, ie->index);
  7931. return lb_addr_soa_variable(val, index, ie->index);
  7932. }
  7933. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  7934. // SOA Structures for slices/dynamic arrays
  7935. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  7936. lbValue field = lb_build_expr(p, ie->expr);
  7937. lbValue index = lb_build_expr(p, ie->index);
  7938. if (!build_context.no_bounds_check) {
  7939. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  7940. // GB_ASSERT(LLVMIsALoadInst(field.value));
  7941. // lbValue a = {};
  7942. // a.value = LLVMGetOperand(field.value, 0);
  7943. // a.type = alloc_type_pointer(field.type);
  7944. // irInstr *b = &a->Instr;
  7945. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  7946. // lbValue base_struct = b->StructElementPtr.address;
  7947. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  7948. // lbValue len = ir_soa_struct_len(p, base_struct);
  7949. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7950. }
  7951. lbValue val = lb_emit_ptr_offset(p, field, index);
  7952. return lb_addr(val);
  7953. }
  7954. if (!is_type_indexable(t)) {
  7955. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  7956. if (found != nullptr) {
  7957. if (found->kind == TypeAtomOp_index_get) {
  7958. return lb_build_addr(p, found->node);
  7959. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  7960. return lb_addr(lb_build_expr(p, found->node));
  7961. } else if (found->kind == TypeAtomOp_index_set) {
  7962. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  7963. if (deref) {
  7964. ptr = lb_emit_load(p, ptr);
  7965. }
  7966. lbAddr addr = {lbAddr_AtomOp_index_set};
  7967. addr.addr = ptr;
  7968. addr.index_set.index = lb_build_expr(p, ie->index);
  7969. addr.index_set.node = found->node;
  7970. return addr;
  7971. }
  7972. }
  7973. }
  7974. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  7975. if (is_type_map(t)) {
  7976. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  7977. if (deref) {
  7978. map_val = lb_emit_load(p, map_val);
  7979. }
  7980. lbValue key = lb_build_expr(p, ie->index);
  7981. key = lb_emit_conv(p, key, t->Map.key);
  7982. Type *result_type = type_of_expr(expr);
  7983. return lb_addr_map(map_val, key, t, result_type);
  7984. }
  7985. lbValue using_addr = {};
  7986. switch (t->kind) {
  7987. case Type_Array: {
  7988. lbValue array = {};
  7989. if (using_addr.value != nullptr) {
  7990. array = using_addr;
  7991. } else {
  7992. array = lb_build_addr_ptr(p, ie->expr);
  7993. if (deref) {
  7994. array = lb_emit_load(p, array);
  7995. }
  7996. }
  7997. lbValue index = lb_build_expr(p, ie->index);
  7998. index = lb_emit_conv(p, index, t_int);
  7999. lbValue elem = lb_emit_array_ep(p, array, index);
  8000. auto index_tv = type_and_value_of_expr(ie->index);
  8001. if (index_tv.mode != Addressing_Constant) {
  8002. // lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  8003. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  8004. }
  8005. return lb_addr(elem);
  8006. }
  8007. case Type_EnumeratedArray: {
  8008. lbValue array = {};
  8009. if (using_addr.value != nullptr) {
  8010. array = using_addr;
  8011. } else {
  8012. array = lb_build_addr_ptr(p, ie->expr);
  8013. if (deref) {
  8014. array = lb_emit_load(p, array);
  8015. }
  8016. }
  8017. Type *index_type = t->EnumeratedArray.index;
  8018. auto index_tv = type_and_value_of_expr(ie->index);
  8019. lbValue index = {};
  8020. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  8021. if (index_tv.mode == Addressing_Constant) {
  8022. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  8023. index = lb_const_value(p->module, index_type, idx);
  8024. } else {
  8025. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8026. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  8027. }
  8028. } else {
  8029. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8030. }
  8031. lbValue elem = lb_emit_array_ep(p, array, index);
  8032. if (index_tv.mode != Addressing_Constant) {
  8033. // lbValue len = ir_const_int(t->EnumeratedArray.count);
  8034. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  8035. }
  8036. return lb_addr(elem);
  8037. }
  8038. case Type_Slice: {
  8039. lbValue slice = {};
  8040. if (using_addr.value != nullptr) {
  8041. slice = lb_emit_load(p, using_addr);
  8042. } else {
  8043. slice = lb_build_expr(p, ie->expr);
  8044. if (deref) {
  8045. slice = lb_emit_load(p, slice);
  8046. }
  8047. }
  8048. lbValue elem = lb_slice_elem(p, slice);
  8049. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8050. lbValue len = lb_slice_len(p, slice);
  8051. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  8052. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8053. return lb_addr(v);
  8054. }
  8055. case Type_DynamicArray: {
  8056. lbValue dynamic_array = {};
  8057. if (using_addr.value != nullptr) {
  8058. dynamic_array = lb_emit_load(p, using_addr);
  8059. } else {
  8060. dynamic_array = lb_build_expr(p, ie->expr);
  8061. if (deref) {
  8062. dynamic_array = lb_emit_load(p, dynamic_array);
  8063. }
  8064. }
  8065. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  8066. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  8067. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8068. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8069. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8070. return lb_addr(v);
  8071. }
  8072. case Type_Basic: { // Basic_string
  8073. lbValue str;
  8074. lbValue elem;
  8075. lbValue len;
  8076. lbValue index;
  8077. if (using_addr.value != nullptr) {
  8078. str = lb_emit_load(p, using_addr);
  8079. } else {
  8080. str = lb_build_expr(p, ie->expr);
  8081. if (deref) {
  8082. str = lb_emit_load(p, str);
  8083. }
  8084. }
  8085. elem = lb_string_elem(p, str);
  8086. len = lb_string_len(p, str);
  8087. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8088. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8089. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  8090. }
  8091. }
  8092. case_end;
  8093. case_ast_node(se, SliceExpr, expr);
  8094. gbAllocator a = heap_allocator();
  8095. lbValue low = lb_const_int(p->module, t_int, 0);
  8096. lbValue high = {};
  8097. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  8098. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  8099. bool no_indices = se->low == nullptr && se->high == nullptr;
  8100. {
  8101. Type *type = base_type(type_of_expr(se->expr));
  8102. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  8103. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  8104. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  8105. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8106. if (found) {
  8107. lbValue base = lb_build_expr(p, found->node);
  8108. Type *slice_type = base.type;
  8109. lbValue len = lb_slice_len(p, base);
  8110. if (high.value == nullptr) high = len;
  8111. if (!no_indices) {
  8112. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8113. }
  8114. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8115. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8116. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8117. lb_fill_slice(p, slice, elem, new_len);
  8118. return slice;
  8119. }
  8120. }
  8121. }
  8122. }
  8123. lbValue addr = lb_build_addr_ptr(p, se->expr);
  8124. lbValue base = lb_emit_load(p, addr);
  8125. Type *type = base_type(base.type);
  8126. if (is_type_pointer(type)) {
  8127. type = base_type(type_deref(type));
  8128. addr = base;
  8129. base = lb_emit_load(p, base);
  8130. }
  8131. switch (type->kind) {
  8132. case Type_Slice: {
  8133. Type *slice_type = type;
  8134. lbValue len = lb_slice_len(p, base);
  8135. if (high.value == nullptr) high = len;
  8136. if (!no_indices) {
  8137. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8138. }
  8139. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8140. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8141. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8142. lb_fill_slice(p, slice, elem, new_len);
  8143. return slice;
  8144. }
  8145. case Type_DynamicArray: {
  8146. Type *elem_type = type->DynamicArray.elem;
  8147. Type *slice_type = alloc_type_slice(elem_type);
  8148. lbValue len = lb_dynamic_array_len(p, base);
  8149. if (high.value == nullptr) high = len;
  8150. if (!no_indices) {
  8151. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8152. }
  8153. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  8154. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8155. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8156. lb_fill_slice(p, slice, elem, new_len);
  8157. return slice;
  8158. }
  8159. case Type_Array: {
  8160. Type *slice_type = alloc_type_slice(type->Array.elem);
  8161. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  8162. if (high.value == nullptr) high = len;
  8163. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  8164. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  8165. if (!low_const || !high_const) {
  8166. if (!no_indices) {
  8167. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8168. }
  8169. }
  8170. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, addr), low);
  8171. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8172. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8173. lb_fill_slice(p, slice, elem, new_len);
  8174. return slice;
  8175. }
  8176. case Type_Basic: {
  8177. GB_ASSERT(type == t_string);
  8178. lbValue len = lb_string_len(p, base);
  8179. if (high.value == nullptr) high = len;
  8180. if (!no_indices) {
  8181. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8182. }
  8183. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  8184. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8185. lbAddr str = lb_add_local_generated(p, t_string, false);
  8186. lb_fill_string(p, str, elem, new_len);
  8187. return str;
  8188. }
  8189. case Type_Struct:
  8190. if (is_type_soa_struct(type)) {
  8191. lbValue len = lb_soa_struct_len(p, addr);
  8192. if (high.value == nullptr) high = len;
  8193. if (!no_indices) {
  8194. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8195. }
  8196. #if 1
  8197. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  8198. if (type->Struct.soa_kind == StructSoa_Fixed) {
  8199. i32 field_count = cast(i32)type->Struct.fields.count;
  8200. for (i32 i = 0; i < field_count; i++) {
  8201. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8202. lbValue field_src = lb_emit_struct_ep(p, addr, i);
  8203. field_src = lb_emit_array_ep(p, field_src, low);
  8204. lb_emit_store(p, field_dst, field_src);
  8205. }
  8206. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  8207. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8208. lb_emit_store(p, len_dst, new_len);
  8209. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  8210. if (no_indices) {
  8211. lb_addr_store(p, dst, base);
  8212. } else {
  8213. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  8214. for (i32 i = 0; i < field_count; i++) {
  8215. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8216. lbValue field_src = lb_emit_struct_ev(p, base, i);
  8217. field_src = lb_emit_ptr_offset(p, field_src, low);
  8218. lb_emit_store(p, field_dst, field_src);
  8219. }
  8220. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  8221. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8222. lb_emit_store(p, len_dst, new_len);
  8223. }
  8224. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  8225. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  8226. for (i32 i = 0; i < field_count; i++) {
  8227. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8228. lbValue field_src = lb_emit_struct_ev(p, base, i);
  8229. field_src = lb_emit_ptr_offset(p, field_src, low);
  8230. lb_emit_store(p, field_dst, field_src);
  8231. }
  8232. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  8233. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8234. lb_emit_store(p, len_dst, new_len);
  8235. }
  8236. return dst;
  8237. #endif
  8238. }
  8239. break;
  8240. }
  8241. GB_PANIC("Unknown slicable type");
  8242. case_end;
  8243. case_ast_node(de, DerefExpr, expr);
  8244. lbValue addr = lb_build_expr(p, de->expr);
  8245. return lb_addr(addr);
  8246. case_end;
  8247. case_ast_node(ce, CallExpr, expr);
  8248. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  8249. lbValue e = lb_build_expr(p, expr);
  8250. lbAddr v = lb_add_local_generated(p, e.type, false);
  8251. lb_addr_store(p, v, e);
  8252. return v;
  8253. case_end;
  8254. case_ast_node(cl, CompoundLit, expr);
  8255. Type *type = type_of_expr(expr);
  8256. Type *bt = base_type(type);
  8257. lbAddr v = lb_add_local_generated(p, type, true);
  8258. Type *et = nullptr;
  8259. switch (bt->kind) {
  8260. case Type_Array: et = bt->Array.elem; break;
  8261. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  8262. case Type_Slice: et = bt->Slice.elem; break;
  8263. case Type_BitSet: et = bt->BitSet.elem; break;
  8264. case Type_SimdVector: et = bt->SimdVector.elem; break;
  8265. }
  8266. String proc_name = {};
  8267. if (p->entity) {
  8268. proc_name = p->entity->token.string;
  8269. }
  8270. TokenPos pos = ast_token(expr).pos;
  8271. switch (bt->kind) {
  8272. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  8273. case Type_Struct: {
  8274. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  8275. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  8276. bool is_raw_union = is_type_raw_union(bt);
  8277. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  8278. TypeStruct *st = &bt->Struct;
  8279. if (cl->elems.count > 0) {
  8280. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8281. for_array(field_index, cl->elems) {
  8282. Ast *elem = cl->elems[field_index];
  8283. lbValue field_expr = {};
  8284. Entity *field = nullptr;
  8285. isize index = field_index;
  8286. if (elem->kind == Ast_FieldValue) {
  8287. ast_node(fv, FieldValue, elem);
  8288. String name = fv->field->Ident.token.string;
  8289. Selection sel = lookup_field(bt, name, false);
  8290. index = sel.index[0];
  8291. elem = fv->value;
  8292. TypeAndValue tav = type_and_value_of_expr(elem);
  8293. } else {
  8294. TypeAndValue tav = type_and_value_of_expr(elem);
  8295. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  8296. index = sel.index[0];
  8297. }
  8298. field = st->fields[index];
  8299. Type *ft = field->type;
  8300. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  8301. continue;
  8302. }
  8303. field_expr = lb_build_expr(p, elem);
  8304. Type *fet = field_expr.type;
  8305. GB_ASSERT(fet->kind != Type_Tuple);
  8306. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  8307. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  8308. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  8309. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  8310. lb_emit_store_union_variant(p, gep, field_expr, fet);
  8311. } else {
  8312. lbValue fv = lb_emit_conv(p, field_expr, ft);
  8313. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  8314. lb_emit_store(p, gep, fv);
  8315. }
  8316. }
  8317. }
  8318. break;
  8319. }
  8320. case Type_Map: {
  8321. if (cl->elems.count == 0) {
  8322. break;
  8323. }
  8324. gbAllocator a = heap_allocator();
  8325. {
  8326. auto args = array_make<lbValue>(a, 3);
  8327. args[0] = lb_gen_map_header(p, v.addr, type);
  8328. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  8329. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  8330. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  8331. }
  8332. for_array(field_index, cl->elems) {
  8333. Ast *elem = cl->elems[field_index];
  8334. ast_node(fv, FieldValue, elem);
  8335. lbValue key = lb_build_expr(p, fv->field);
  8336. lbValue value = lb_build_expr(p, fv->value);
  8337. lb_insert_dynamic_map_key_and_value(p, v, type, key, value);
  8338. }
  8339. break;
  8340. }
  8341. case Type_Array: {
  8342. if (cl->elems.count > 0) {
  8343. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8344. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  8345. defer (array_free(&temp_data));
  8346. // NOTE(bill): Separate value, gep, store into their own chunks
  8347. for_array(i, cl->elems) {
  8348. Ast *elem = cl->elems[i];
  8349. if (elem->kind == Ast_FieldValue) {
  8350. ast_node(fv, FieldValue, elem);
  8351. if (lb_is_elem_const(fv->value, et)) {
  8352. continue;
  8353. }
  8354. if (is_ast_range(fv->field)) {
  8355. ast_node(ie, BinaryExpr, fv->field);
  8356. TypeAndValue lo_tav = ie->left->tav;
  8357. TypeAndValue hi_tav = ie->right->tav;
  8358. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  8359. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  8360. TokenKind op = ie->op.kind;
  8361. i64 lo = exact_value_to_i64(lo_tav.value);
  8362. i64 hi = exact_value_to_i64(hi_tav.value);
  8363. if (op == Token_Ellipsis) {
  8364. hi += 1;
  8365. }
  8366. lbValue value = lb_build_expr(p, fv->value);
  8367. for (i64 k = lo; k < hi; k++) {
  8368. lbCompoundLitElemTempData data = {};
  8369. data.value = value;
  8370. data.elem_index = cast(i32)k;
  8371. array_add(&temp_data, data);
  8372. }
  8373. } else {
  8374. auto tav = fv->field->tav;
  8375. GB_ASSERT(tav.mode == Addressing_Constant);
  8376. i64 index = exact_value_to_i64(tav.value);
  8377. lbValue value = lb_build_expr(p, fv->value);
  8378. lbCompoundLitElemTempData data = {};
  8379. data.value = lb_emit_conv(p, value, et);
  8380. data.expr = fv->value;
  8381. data.elem_index = cast(i32)index;
  8382. array_add(&temp_data, data);
  8383. }
  8384. } else {
  8385. if (lb_is_elem_const(elem, et)) {
  8386. continue;
  8387. }
  8388. lbCompoundLitElemTempData data = {};
  8389. data.expr = elem;
  8390. data.elem_index = cast(i32)i;
  8391. array_add(&temp_data, data);
  8392. }
  8393. }
  8394. for_array(i, temp_data) {
  8395. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  8396. }
  8397. for_array(i, temp_data) {
  8398. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  8399. auto return_ptr_hint_value = p->return_ptr_hint_value;
  8400. auto return_ptr_hint_used = p->return_ptr_hint_used;
  8401. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  8402. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  8403. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  8404. lbValue field_expr = temp_data[i].value;
  8405. Ast *expr = temp_data[i].expr;
  8406. p->return_ptr_hint_value = temp_data[i].gep;
  8407. p->return_ptr_hint_ast = unparen_expr(expr);
  8408. if (field_expr.value == nullptr) {
  8409. field_expr = lb_build_expr(p, expr);
  8410. }
  8411. Type *t = field_expr.type;
  8412. GB_ASSERT(t->kind != Type_Tuple);
  8413. lbValue ev = lb_emit_conv(p, field_expr, et);
  8414. if (!p->return_ptr_hint_used) {
  8415. temp_data[i].value = ev;
  8416. }
  8417. }
  8418. for_array(i, temp_data) {
  8419. if (temp_data[i].value.value != nullptr) {
  8420. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  8421. }
  8422. }
  8423. }
  8424. break;
  8425. }
  8426. case Type_EnumeratedArray: {
  8427. if (cl->elems.count > 0) {
  8428. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8429. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  8430. defer (array_free(&temp_data));
  8431. // NOTE(bill): Separate value, gep, store into their own chunks
  8432. for_array(i, cl->elems) {
  8433. Ast *elem = cl->elems[i];
  8434. if (elem->kind == Ast_FieldValue) {
  8435. ast_node(fv, FieldValue, elem);
  8436. if (lb_is_elem_const(fv->value, et)) {
  8437. continue;
  8438. }
  8439. if (is_ast_range(fv->field)) {
  8440. ast_node(ie, BinaryExpr, fv->field);
  8441. TypeAndValue lo_tav = ie->left->tav;
  8442. TypeAndValue hi_tav = ie->right->tav;
  8443. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  8444. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  8445. TokenKind op = ie->op.kind;
  8446. i64 lo = exact_value_to_i64(lo_tav.value);
  8447. i64 hi = exact_value_to_i64(hi_tav.value);
  8448. if (op == Token_Ellipsis) {
  8449. hi += 1;
  8450. }
  8451. lbValue value = lb_build_expr(p, fv->value);
  8452. for (i64 k = lo; k < hi; k++) {
  8453. lbCompoundLitElemTempData data = {};
  8454. data.value = value;
  8455. data.elem_index = cast(i32)k;
  8456. array_add(&temp_data, data);
  8457. }
  8458. } else {
  8459. auto tav = fv->field->tav;
  8460. GB_ASSERT(tav.mode == Addressing_Constant);
  8461. i64 index = exact_value_to_i64(tav.value);
  8462. lbValue value = lb_build_expr(p, fv->value);
  8463. lbCompoundLitElemTempData data = {};
  8464. data.value = lb_emit_conv(p, value, et);
  8465. data.expr = fv->value;
  8466. data.elem_index = cast(i32)index;
  8467. array_add(&temp_data, data);
  8468. }
  8469. } else {
  8470. if (lb_is_elem_const(elem, et)) {
  8471. continue;
  8472. }
  8473. lbCompoundLitElemTempData data = {};
  8474. data.expr = elem;
  8475. data.elem_index = cast(i32)i;
  8476. array_add(&temp_data, data);
  8477. }
  8478. }
  8479. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  8480. for_array(i, temp_data) {
  8481. i32 index = temp_data[i].elem_index - index_offset;
  8482. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  8483. }
  8484. for_array(i, temp_data) {
  8485. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  8486. auto return_ptr_hint_value = p->return_ptr_hint_value;
  8487. auto return_ptr_hint_used = p->return_ptr_hint_used;
  8488. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  8489. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  8490. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  8491. lbValue field_expr = temp_data[i].value;
  8492. Ast *expr = temp_data[i].expr;
  8493. p->return_ptr_hint_value = temp_data[i].gep;
  8494. p->return_ptr_hint_ast = unparen_expr(expr);
  8495. if (field_expr.value == nullptr) {
  8496. field_expr = lb_build_expr(p, expr);
  8497. }
  8498. Type *t = field_expr.type;
  8499. GB_ASSERT(t->kind != Type_Tuple);
  8500. lbValue ev = lb_emit_conv(p, field_expr, et);
  8501. if (!p->return_ptr_hint_used) {
  8502. temp_data[i].value = ev;
  8503. }
  8504. }
  8505. for_array(i, temp_data) {
  8506. if (temp_data[i].value.value != nullptr) {
  8507. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  8508. }
  8509. }
  8510. }
  8511. break;
  8512. }
  8513. case Type_Slice: {
  8514. if (cl->elems.count > 0) {
  8515. Type *elem_type = bt->Slice.elem;
  8516. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  8517. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  8518. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  8519. lbValue data = lb_slice_elem(p, slice);
  8520. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  8521. defer (array_free(&temp_data));
  8522. for_array(i, cl->elems) {
  8523. Ast *elem = cl->elems[i];
  8524. if (elem->kind == Ast_FieldValue) {
  8525. ast_node(fv, FieldValue, elem);
  8526. if (lb_is_elem_const(fv->value, et)) {
  8527. continue;
  8528. }
  8529. if (is_ast_range(fv->field)) {
  8530. ast_node(ie, BinaryExpr, fv->field);
  8531. TypeAndValue lo_tav = ie->left->tav;
  8532. TypeAndValue hi_tav = ie->right->tav;
  8533. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  8534. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  8535. TokenKind op = ie->op.kind;
  8536. i64 lo = exact_value_to_i64(lo_tav.value);
  8537. i64 hi = exact_value_to_i64(hi_tav.value);
  8538. if (op == Token_Ellipsis) {
  8539. hi += 1;
  8540. }
  8541. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  8542. for (i64 k = lo; k < hi; k++) {
  8543. lbCompoundLitElemTempData data = {};
  8544. data.value = value;
  8545. data.elem_index = cast(i32)k;
  8546. array_add(&temp_data, data);
  8547. }
  8548. } else {
  8549. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  8550. i64 index = exact_value_to_i64(fv->field->tav.value);
  8551. lbValue field_expr = lb_build_expr(p, fv->value);
  8552. GB_ASSERT(!is_type_tuple(field_expr.type));
  8553. lbValue ev = lb_emit_conv(p, field_expr, et);
  8554. lbCompoundLitElemTempData data = {};
  8555. data.value = ev;
  8556. data.elem_index = cast(i32)index;
  8557. array_add(&temp_data, data);
  8558. }
  8559. } else {
  8560. if (lb_is_elem_const(elem, et)) {
  8561. continue;
  8562. }
  8563. lbValue field_expr = lb_build_expr(p, elem);
  8564. GB_ASSERT(!is_type_tuple(field_expr.type));
  8565. lbValue ev = lb_emit_conv(p, field_expr, et);
  8566. lbCompoundLitElemTempData data = {};
  8567. data.value = ev;
  8568. data.elem_index = cast(i32)i;
  8569. array_add(&temp_data, data);
  8570. }
  8571. }
  8572. for_array(i, temp_data) {
  8573. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  8574. }
  8575. for_array(i, temp_data) {
  8576. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  8577. }
  8578. {
  8579. GB_ASSERT(lb_is_const(slice));
  8580. unsigned indices[1] = {1};
  8581. lbValue count = {};
  8582. count.type = t_int;
  8583. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  8584. lb_fill_slice(p, v, data, count);
  8585. }
  8586. }
  8587. break;
  8588. }
  8589. case Type_DynamicArray: {
  8590. if (cl->elems.count == 0) {
  8591. break;
  8592. }
  8593. Type *et = bt->DynamicArray.elem;
  8594. gbAllocator a = heap_allocator();
  8595. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  8596. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  8597. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  8598. {
  8599. auto args = array_make<lbValue>(a, 5);
  8600. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  8601. args[1] = size;
  8602. args[2] = align;
  8603. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  8604. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  8605. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  8606. }
  8607. lbValue items = lb_generate_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  8608. for_array(i, cl->elems) {
  8609. Ast *elem = cl->elems[i];
  8610. if (elem->kind == Ast_FieldValue) {
  8611. ast_node(fv, FieldValue, elem);
  8612. if (is_ast_range(fv->field)) {
  8613. ast_node(ie, BinaryExpr, fv->field);
  8614. TypeAndValue lo_tav = ie->left->tav;
  8615. TypeAndValue hi_tav = ie->right->tav;
  8616. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  8617. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  8618. TokenKind op = ie->op.kind;
  8619. i64 lo = exact_value_to_i64(lo_tav.value);
  8620. i64 hi = exact_value_to_i64(hi_tav.value);
  8621. if (op == Token_Ellipsis) {
  8622. hi += 1;
  8623. }
  8624. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  8625. for (i64 k = lo; k < hi; k++) {
  8626. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  8627. lb_emit_store(p, ep, value);
  8628. }
  8629. } else {
  8630. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  8631. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  8632. lbValue ev = lb_build_expr(p, fv->value);
  8633. lbValue value = lb_emit_conv(p, ev, et);
  8634. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  8635. lb_emit_store(p, ep, value);
  8636. }
  8637. } else {
  8638. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  8639. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  8640. lb_emit_store(p, ep, value);
  8641. }
  8642. }
  8643. {
  8644. auto args = array_make<lbValue>(a, 6);
  8645. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  8646. args[1] = size;
  8647. args[2] = align;
  8648. args[3] = lb_emit_conv(p, items, t_rawptr);
  8649. args[4] = lb_const_int(p->module, t_int, item_count);
  8650. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  8651. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  8652. }
  8653. break;
  8654. }
  8655. case Type_Basic: {
  8656. GB_ASSERT(is_type_any(bt));
  8657. if (cl->elems.count > 0) {
  8658. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8659. String field_names[2] = {
  8660. str_lit("data"),
  8661. str_lit("id"),
  8662. };
  8663. Type *field_types[2] = {
  8664. t_rawptr,
  8665. t_typeid,
  8666. };
  8667. for_array(field_index, cl->elems) {
  8668. Ast *elem = cl->elems[field_index];
  8669. lbValue field_expr = {};
  8670. isize index = field_index;
  8671. if (elem->kind == Ast_FieldValue) {
  8672. ast_node(fv, FieldValue, elem);
  8673. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  8674. index = sel.index[0];
  8675. elem = fv->value;
  8676. } else {
  8677. TypeAndValue tav = type_and_value_of_expr(elem);
  8678. Selection sel = lookup_field(bt, field_names[field_index], false);
  8679. index = sel.index[0];
  8680. }
  8681. field_expr = lb_build_expr(p, elem);
  8682. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  8683. Type *ft = field_types[index];
  8684. lbValue fv = lb_emit_conv(p, field_expr, ft);
  8685. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  8686. lb_emit_store(p, gep, fv);
  8687. }
  8688. }
  8689. break;
  8690. }
  8691. case Type_BitSet: {
  8692. i64 sz = type_size_of(type);
  8693. if (cl->elems.count > 0 && sz > 0) {
  8694. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8695. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  8696. for_array(i, cl->elems) {
  8697. Ast *elem = cl->elems[i];
  8698. GB_ASSERT(elem->kind != Ast_FieldValue);
  8699. if (lb_is_elem_const(elem, et)) {
  8700. continue;
  8701. }
  8702. lbValue expr = lb_build_expr(p, elem);
  8703. GB_ASSERT(expr.type->kind != Type_Tuple);
  8704. Type *it = bit_set_to_int(bt);
  8705. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  8706. lbValue e = lb_emit_conv(p, expr, it);
  8707. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  8708. e = lb_emit_arith(p, Token_Shl, one, e, it);
  8709. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  8710. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  8711. new_value = lb_emit_transmute(p, new_value, type);
  8712. lb_addr_store(p, v, new_value);
  8713. }
  8714. }
  8715. break;
  8716. }
  8717. }
  8718. return v;
  8719. case_end;
  8720. case_ast_node(tc, TypeCast, expr);
  8721. Type *type = type_of_expr(expr);
  8722. lbValue x = lb_build_expr(p, tc->expr);
  8723. lbValue e = {};
  8724. switch (tc->token.kind) {
  8725. case Token_cast:
  8726. e = lb_emit_conv(p, x, type);
  8727. break;
  8728. case Token_transmute:
  8729. e = lb_emit_transmute(p, x, type);
  8730. break;
  8731. default:
  8732. GB_PANIC("Invalid AST TypeCast");
  8733. }
  8734. lbAddr v = lb_add_local_generated(p, type, false);
  8735. lb_addr_store(p, v, e);
  8736. return v;
  8737. case_end;
  8738. case_ast_node(ac, AutoCast, expr);
  8739. return lb_build_addr(p, ac->expr);
  8740. case_end;
  8741. }
  8742. TokenPos token_pos = ast_token(expr).pos;
  8743. GB_PANIC("Unexpected address expression\n"
  8744. "\tAst: %.*s @ "
  8745. "%.*s(%td:%td)\n",
  8746. LIT(ast_strings[expr->kind]),
  8747. LIT(token_pos.file), token_pos.line, token_pos.column);
  8748. return {};
  8749. }
  8750. void lb_init_module(lbModule *m, Checker *c) {
  8751. m->info = &c->info;
  8752. m->ctx = LLVMGetGlobalContext();
  8753. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  8754. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  8755. gb_mutex_init(&m->mutex);
  8756. gbAllocator a = heap_allocator();
  8757. map_init(&m->types, a);
  8758. map_init(&m->values, a);
  8759. string_map_init(&m->members, a);
  8760. map_init(&m->procedure_values, a);
  8761. string_map_init(&m->procedures, a);
  8762. string_map_init(&m->const_strings, a);
  8763. map_init(&m->anonymous_proc_lits, a);
  8764. array_init(&m->procedures_to_generate, a);
  8765. array_init(&m->foreign_library_paths, a);
  8766. map_init(&m->debug_values, a);
  8767. }
  8768. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  8769. if (global_error_collector.count != 0) {
  8770. return false;
  8771. }
  8772. isize tc = c->parser->total_token_count;
  8773. if (tc < 2) {
  8774. return false;
  8775. }
  8776. String init_fullpath = c->parser->init_fullpath;
  8777. if (build_context.out_filepath.len == 0) {
  8778. gen->output_name = remove_directory_from_path(init_fullpath);
  8779. gen->output_name = remove_extension_from_path(gen->output_name);
  8780. gen->output_base = gen->output_name;
  8781. } else {
  8782. gen->output_name = build_context.out_filepath;
  8783. isize pos = string_extension_position(gen->output_name);
  8784. if (pos < 0) {
  8785. gen->output_base = gen->output_name;
  8786. } else {
  8787. gen->output_base = substring(gen->output_name, 0, pos);
  8788. }
  8789. }
  8790. gbAllocator ha = heap_allocator();
  8791. array_init(&gen->output_object_paths, ha);
  8792. gen->output_base = path_to_full_path(ha, gen->output_base);
  8793. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  8794. output_file_path = gb_string_appendc(output_file_path, ".obj");
  8795. defer (gb_string_free(output_file_path));
  8796. gen->info = &c->info;
  8797. lb_init_module(&gen->module, c);
  8798. return true;
  8799. }
  8800. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  8801. GB_ASSERT(type != nullptr);
  8802. type = default_type(type);
  8803. isize max_len = 7+8+1;
  8804. u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len);
  8805. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  8806. m->global_generated_index++;
  8807. String name = make_string(str, len-1);
  8808. Scope *scope = nullptr;
  8809. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  8810. lbValue g = {};
  8811. g.type = alloc_type_pointer(type);
  8812. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  8813. if (value.value != nullptr) {
  8814. GB_ASSERT(LLVMIsConstant(value.value));
  8815. LLVMSetInitializer(g.value, value.value);
  8816. } else {
  8817. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  8818. }
  8819. lb_add_entity(m, e, g);
  8820. lb_add_member(m, name, g);
  8821. return lb_addr(g);
  8822. }
  8823. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  8824. AstPackage *p = m->info->runtime_package;
  8825. Entity *e = scope_lookup_current(p->scope, name);
  8826. lbValue *found = map_get(&m->values, hash_entity(e));
  8827. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  8828. lbValue value = *found;
  8829. return value;
  8830. }
  8831. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  8832. i32 index = cast(i32)lb_type_info_index(m->info, type);
  8833. GB_ASSERT(index >= 0);
  8834. // gb_printf_err("%d %s\n", index, type_to_string(type));
  8835. LLVMValueRef indices[2] = {
  8836. LLVMConstInt(lb_type(m, t_int), 0, false),
  8837. LLVMConstInt(lb_type(m, t_int), index, false),
  8838. };
  8839. lbValue res = {};
  8840. res.type = t_type_info_ptr;
  8841. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  8842. return res;
  8843. }
  8844. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  8845. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  8846. lb_global_type_info_member_types_index += cast(i32)count;
  8847. return offset;
  8848. }
  8849. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  8850. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  8851. lb_global_type_info_member_names_index += cast(i32)count;
  8852. return offset;
  8853. }
  8854. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  8855. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  8856. lb_global_type_info_member_offsets_index += cast(i32)count;
  8857. return offset;
  8858. }
  8859. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  8860. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  8861. lb_global_type_info_member_usings_index += cast(i32)count;
  8862. return offset;
  8863. }
  8864. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  8865. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  8866. lb_global_type_info_member_tags_index += cast(i32)count;
  8867. return offset;
  8868. }
  8869. lbValue lb_generate_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  8870. gbAllocator a = heap_allocator();
  8871. Token token = {Token_Ident};
  8872. isize name_len = prefix.len + 1 + 20;
  8873. auto suffix_id = cast(unsigned long long)id;
  8874. char *text = gb_alloc_array(a, char, name_len+1);
  8875. gb_snprintf(text, name_len,
  8876. "%.*s-%llu", LIT(prefix), suffix_id);
  8877. text[name_len] = 0;
  8878. String s = make_string_c(text);
  8879. Type *t = alloc_type_array(elem_type, count);
  8880. lbValue g = {};
  8881. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  8882. g.type = alloc_type_pointer(t);
  8883. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  8884. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  8885. string_map_set(&m->members, s, g);
  8886. return g;
  8887. }
  8888. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  8889. lbModule *m = p->module;
  8890. LLVMContextRef ctx = m->ctx;
  8891. gbAllocator a = heap_allocator();
  8892. CheckerInfo *info = m->info;
  8893. {
  8894. // NOTE(bill): Set the type_table slice with the global backing array
  8895. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  8896. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  8897. GB_ASSERT(is_type_array(type));
  8898. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  8899. LLVMValueRef values[2] = {
  8900. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  8901. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  8902. };
  8903. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  8904. LLVMSetInitializer(global_type_table.value, slice);
  8905. }
  8906. // Useful types
  8907. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  8908. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  8909. i32 type_info_member_types_index = 0;
  8910. i32 type_info_member_names_index = 0;
  8911. i32 type_info_member_offsets_index = 0;
  8912. for_array(type_info_type_index, info->type_info_types) {
  8913. Type *t = info->type_info_types[type_info_type_index];
  8914. t = default_type(t);
  8915. if (t == t_invalid) {
  8916. continue;
  8917. }
  8918. isize entry_index = lb_type_info_index(info, t, false);
  8919. if (entry_index <= 0) {
  8920. continue;
  8921. }
  8922. lbValue tag = {};
  8923. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  8924. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 3);
  8925. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  8926. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  8927. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), lb_typeid(m, t));
  8928. switch (t->kind) {
  8929. case Type_Named: {
  8930. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  8931. LLVMValueRef vals[2] = {
  8932. lb_const_string(p->module, t->Named.type_name->token.string).value,
  8933. lb_get_type_info_ptr(m, t->Named.base).value,
  8934. };
  8935. lbValue res = {};
  8936. res.type = type_deref(tag.type);
  8937. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8938. lb_emit_store(p, tag, res);
  8939. break;
  8940. }
  8941. case Type_Basic:
  8942. switch (t->Basic.kind) {
  8943. case Basic_bool:
  8944. case Basic_b8:
  8945. case Basic_b16:
  8946. case Basic_b32:
  8947. case Basic_b64:
  8948. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  8949. break;
  8950. case Basic_i8:
  8951. case Basic_u8:
  8952. case Basic_i16:
  8953. case Basic_u16:
  8954. case Basic_i32:
  8955. case Basic_u32:
  8956. case Basic_i64:
  8957. case Basic_u64:
  8958. case Basic_i128:
  8959. case Basic_u128:
  8960. case Basic_i16le:
  8961. case Basic_u16le:
  8962. case Basic_i32le:
  8963. case Basic_u32le:
  8964. case Basic_i64le:
  8965. case Basic_u64le:
  8966. case Basic_i128le:
  8967. case Basic_u128le:
  8968. case Basic_i16be:
  8969. case Basic_u16be:
  8970. case Basic_i32be:
  8971. case Basic_u32be:
  8972. case Basic_i64be:
  8973. case Basic_u64be:
  8974. case Basic_i128be:
  8975. case Basic_u128be:
  8976. case Basic_int:
  8977. case Basic_uint:
  8978. case Basic_uintptr: {
  8979. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  8980. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  8981. // NOTE(bill): This is matches the runtime layout
  8982. u8 endianness_value = 0;
  8983. if (t->Basic.flags & BasicFlag_EndianLittle) {
  8984. endianness_value = 1;
  8985. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  8986. endianness_value = 2;
  8987. }
  8988. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  8989. LLVMValueRef vals[2] = {
  8990. is_signed.value,
  8991. endianness.value,
  8992. };
  8993. lbValue res = {};
  8994. res.type = type_deref(tag.type);
  8995. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8996. lb_emit_store(p, tag, res);
  8997. break;
  8998. }
  8999. case Basic_rune:
  9000. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  9001. break;
  9002. // case Basic_f16:
  9003. case Basic_f32:
  9004. case Basic_f64:
  9005. case Basic_f32le:
  9006. case Basic_f64le:
  9007. case Basic_f32be:
  9008. case Basic_f64be:
  9009. {
  9010. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  9011. // NOTE(bill): This is matches the runtime layout
  9012. u8 endianness_value = 0;
  9013. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9014. endianness_value = 1;
  9015. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9016. endianness_value = 2;
  9017. }
  9018. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9019. LLVMValueRef vals[1] = {
  9020. endianness.value,
  9021. };
  9022. lbValue res = {};
  9023. res.type = type_deref(tag.type);
  9024. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9025. lb_emit_store(p, tag, res);
  9026. }
  9027. break;
  9028. // case Basic_complex32:
  9029. case Basic_complex64:
  9030. case Basic_complex128:
  9031. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  9032. break;
  9033. case Basic_quaternion128:
  9034. case Basic_quaternion256:
  9035. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  9036. break;
  9037. case Basic_rawptr:
  9038. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9039. break;
  9040. case Basic_string:
  9041. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9042. break;
  9043. case Basic_cstring:
  9044. {
  9045. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9046. LLVMValueRef vals[1] = {
  9047. lb_const_bool(m, t_bool, true).value,
  9048. };
  9049. lbValue res = {};
  9050. res.type = type_deref(tag.type);
  9051. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9052. lb_emit_store(p, tag, res);
  9053. }
  9054. break;
  9055. case Basic_any:
  9056. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  9057. break;
  9058. case Basic_typeid:
  9059. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  9060. break;
  9061. }
  9062. break;
  9063. case Type_Pointer: {
  9064. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9065. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  9066. LLVMValueRef vals[1] = {
  9067. gep.value,
  9068. };
  9069. lbValue res = {};
  9070. res.type = type_deref(tag.type);
  9071. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9072. lb_emit_store(p, tag, res);
  9073. break;
  9074. }
  9075. case Type_Array: {
  9076. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  9077. i64 ez = type_size_of(t->Array.elem);
  9078. LLVMValueRef vals[3] = {
  9079. lb_get_type_info_ptr(m, t->Array.elem).value,
  9080. lb_const_int(m, t_int, ez).value,
  9081. lb_const_int(m, t_int, t->Array.count).value,
  9082. };
  9083. lbValue res = {};
  9084. res.type = type_deref(tag.type);
  9085. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9086. lb_emit_store(p, tag, res);
  9087. break;
  9088. }
  9089. case Type_EnumeratedArray: {
  9090. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  9091. LLVMValueRef vals[6] = {
  9092. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  9093. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  9094. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  9095. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  9096. // Unions
  9097. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9098. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9099. };
  9100. lbValue res = {};
  9101. res.type = type_deref(tag.type);
  9102. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9103. lb_emit_store(p, tag, res);
  9104. // NOTE(bill): Union assignment
  9105. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  9106. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  9107. lbValue min_v = lb_const_value(m, core_type(t->EnumeratedArray.index), t->EnumeratedArray.min_value);
  9108. lbValue max_v = lb_const_value(m, core_type(t->EnumeratedArray.index), t->EnumeratedArray.max_value);
  9109. lb_emit_store_union_variant(p, min_value, min_v, min_v.type);
  9110. lb_emit_store_union_variant(p, max_value, max_v, max_v.type);
  9111. break;
  9112. }
  9113. case Type_DynamicArray: {
  9114. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  9115. LLVMValueRef vals[2] = {
  9116. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  9117. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  9118. };
  9119. lbValue res = {};
  9120. res.type = type_deref(tag.type);
  9121. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9122. lb_emit_store(p, tag, res);
  9123. break;
  9124. }
  9125. case Type_Slice: {
  9126. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  9127. LLVMValueRef vals[2] = {
  9128. lb_get_type_info_ptr(m, t->Slice.elem).value,
  9129. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  9130. };
  9131. lbValue res = {};
  9132. res.type = type_deref(tag.type);
  9133. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9134. lb_emit_store(p, tag, res);
  9135. break;
  9136. }
  9137. case Type_Proc: {
  9138. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  9139. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9140. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9141. if (t->Proc.params != nullptr) {
  9142. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  9143. }
  9144. if (t->Proc.results != nullptr) {
  9145. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  9146. }
  9147. LLVMValueRef vals[4] = {
  9148. params,
  9149. results,
  9150. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  9151. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  9152. };
  9153. lbValue res = {};
  9154. res.type = type_deref(tag.type);
  9155. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9156. lb_emit_store(p, tag, res);
  9157. break;
  9158. }
  9159. case Type_Tuple: {
  9160. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  9161. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  9162. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  9163. for_array(i, t->Tuple.variables) {
  9164. // NOTE(bill): offset is not used for tuples
  9165. Entity *f = t->Tuple.variables[i];
  9166. lbValue index = lb_const_int(m, t_int, i);
  9167. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  9168. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  9169. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  9170. if (f->token.string.len > 0) {
  9171. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  9172. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  9173. }
  9174. }
  9175. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  9176. LLVMValueRef types_slice = llvm_const_slice(memory_types, count);
  9177. LLVMValueRef names_slice = llvm_const_slice(memory_names, count);
  9178. LLVMValueRef vals[2] = {
  9179. types_slice,
  9180. names_slice,
  9181. };
  9182. lbValue res = {};
  9183. res.type = type_deref(tag.type);
  9184. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9185. lb_emit_store(p, tag, res);
  9186. break;
  9187. }
  9188. case Type_Enum:
  9189. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  9190. {
  9191. GB_ASSERT(t->Enum.base_type != nullptr);
  9192. GB_ASSERT(type_size_of(t_type_info_enum_value) == 16);
  9193. LLVMValueRef vals[3] = {};
  9194. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  9195. if (t->Enum.fields.count > 0) {
  9196. auto fields = t->Enum.fields;
  9197. lbValue name_array = lb_generate_array(m, t_string, fields.count,
  9198. str_lit("$enum_names"), cast(i64)entry_index);
  9199. lbValue value_array = lb_generate_array(m, t_type_info_enum_value, fields.count,
  9200. str_lit("$enum_values"), cast(i64)entry_index);
  9201. LLVMValueRef *name_values = gb_alloc_array(heap_allocator(), LLVMValueRef, fields.count);
  9202. LLVMValueRef *value_values = gb_alloc_array(heap_allocator(), LLVMValueRef, fields.count);
  9203. defer (gb_free(heap_allocator(), name_values));
  9204. defer (gb_free(heap_allocator(), value_values));
  9205. GB_ASSERT(is_type_integer(t->Enum.base_type));
  9206. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  9207. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  9208. LLVMTypeRef u64_type = lb_type(m, t_u64);
  9209. for_array(i, fields) {
  9210. ExactValue value = fields[i]->Constant.value;
  9211. lbValue v = lb_const_value(m, t->Enum.base_type, value);
  9212. LLVMValueRef zv = LLVMConstZExt(v.value, u64_type);
  9213. lbValue tag = lb_const_union_tag(m, t_type_info_enum_value, v.type);
  9214. LLVMValueRef vals[3] = {
  9215. LLVMConstNull(align_type),
  9216. zv,
  9217. tag.value,
  9218. };
  9219. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  9220. value_values[i] = LLVMConstStruct(vals, gb_count_of(vals), false);
  9221. }
  9222. LLVMValueRef name_init = LLVMConstArray(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  9223. LLVMValueRef value_init = LLVMConstArray(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  9224. LLVMSetInitializer(name_array.value, name_init);
  9225. LLVMSetInitializer(value_array.value, value_init);
  9226. lbValue v_count = lb_const_int(m, t_int, fields.count);
  9227. vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count);
  9228. vals[2] = llvm_const_slice(lb_array_elem(p, value_array), v_count);
  9229. } else {
  9230. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  9231. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  9232. }
  9233. lbValue res = {};
  9234. res.type = type_deref(tag.type);
  9235. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9236. lb_emit_store(p, tag, res);
  9237. }
  9238. break;
  9239. case Type_Union: {
  9240. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  9241. {
  9242. LLVMValueRef vals[6] = {};
  9243. isize variant_count = gb_max(0, t->Union.variants.count);
  9244. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  9245. // NOTE(bill): Zeroth is nil so ignore it
  9246. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  9247. Type *vt = t->Union.variants[variant_index];
  9248. lbValue tip = lb_get_type_info_ptr(m, vt);
  9249. lbValue index = lb_const_int(m, t_int, variant_index);
  9250. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  9251. lb_emit_store(p, type_info, lb_type_info(m, vt));
  9252. }
  9253. lbValue count = lb_const_int(m, t_int, variant_count);
  9254. vals[0] = llvm_const_slice(memory_types, count);
  9255. i64 tag_size = union_tag_size(t);
  9256. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  9257. if (tag_size > 0) {
  9258. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  9259. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  9260. } else {
  9261. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  9262. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9263. }
  9264. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  9265. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  9266. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  9267. lbValue res = {};
  9268. res.type = type_deref(tag.type);
  9269. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9270. lb_emit_store(p, tag, res);
  9271. }
  9272. break;
  9273. }
  9274. case Type_Struct: {
  9275. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  9276. LLVMValueRef vals[11] = {};
  9277. {
  9278. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  9279. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  9280. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  9281. vals[5] = is_packed.value;
  9282. vals[6] = is_raw_union.value;
  9283. vals[7] = is_custom_align.value;
  9284. if (t->Struct.soa_kind != StructSoa_None) {
  9285. lbValue kind = lb_emit_struct_ep(p, tag, 8);
  9286. Type *kind_type = type_deref(kind.type);
  9287. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  9288. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  9289. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  9290. vals[8] = soa_kind.value;
  9291. vals[9] = soa_type.value;
  9292. vals[10] = soa_len.value;
  9293. }
  9294. }
  9295. isize count = t->Struct.fields.count;
  9296. if (count > 0) {
  9297. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  9298. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  9299. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  9300. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  9301. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  9302. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  9303. for (isize source_index = 0; source_index < count; source_index++) {
  9304. // TODO(bill): Order fields in source order not layout order
  9305. Entity *f = t->Struct.fields[source_index];
  9306. lbValue tip = lb_get_type_info_ptr(m, f->type);
  9307. i64 foffset = 0;
  9308. if (!t->Struct.is_raw_union) {
  9309. foffset = t->Struct.offsets[f->Variable.field_index];
  9310. }
  9311. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  9312. lbValue index = lb_const_int(m, t_int, source_index);
  9313. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  9314. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  9315. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  9316. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  9317. if (f->token.string.len > 0) {
  9318. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  9319. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  9320. }
  9321. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  9322. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  9323. if (t->Struct.tags.count > 0) {
  9324. String tag_string = t->Struct.tags[source_index];
  9325. if (tag_string.len > 0) {
  9326. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  9327. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  9328. }
  9329. }
  9330. }
  9331. lbValue cv = lb_const_int(m, t_int, count);
  9332. vals[0] = llvm_const_slice(memory_types, cv);
  9333. vals[1] = llvm_const_slice(memory_names, cv);
  9334. vals[2] = llvm_const_slice(memory_offsets, cv);
  9335. vals[3] = llvm_const_slice(memory_usings, cv);
  9336. vals[4] = llvm_const_slice(memory_tags, cv);
  9337. }
  9338. for (isize i = 0; i < gb_count_of(vals); i++) {
  9339. if (vals[i] == nullptr) {
  9340. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  9341. }
  9342. }
  9343. lbValue res = {};
  9344. res.type = type_deref(tag.type);
  9345. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9346. lb_emit_store(p, tag, res);
  9347. break;
  9348. }
  9349. case Type_Map: {
  9350. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  9351. init_map_internal_types(t);
  9352. LLVMValueRef vals[3] = {
  9353. lb_get_type_info_ptr(m, t->Map.key).value,
  9354. lb_get_type_info_ptr(m, t->Map.value).value,
  9355. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  9356. };
  9357. lbValue res = {};
  9358. res.type = type_deref(tag.type);
  9359. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9360. lb_emit_store(p, tag, res);
  9361. break;
  9362. }
  9363. case Type_BitField: {
  9364. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_field_ptr);
  9365. // names: []string;
  9366. // bits: []u32;
  9367. // offsets: []u32;
  9368. isize count = t->BitField.fields.count;
  9369. if (count > 0) {
  9370. auto fields = t->BitField.fields;
  9371. lbValue name_array = lb_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  9372. lbValue bit_array = lb_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  9373. lbValue offset_array = lb_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  9374. for (isize i = 0; i < count; i++) {
  9375. Entity *f = fields[i];
  9376. GB_ASSERT(f->type != nullptr);
  9377. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  9378. lbValue name_ep = lb_emit_array_epi(p, name_array, cast(i32)i);
  9379. lbValue bit_ep = lb_emit_array_epi(p, bit_array, cast(i32)i);
  9380. lbValue offset_ep = lb_emit_array_epi(p, offset_array, cast(i32)i);
  9381. lb_emit_store(p, name_ep, lb_const_string(m, f->token.string));
  9382. lb_emit_store(p, bit_ep, lb_const_int(m, t_i32, f->type->BitFieldValue.bits));
  9383. lb_emit_store(p, offset_ep, lb_const_int(m, t_i32, t->BitField.offsets[i]));
  9384. }
  9385. lbValue v_count = lb_const_int(m, t_int, count);
  9386. lbValue name_array_elem = lb_array_elem(p, name_array);
  9387. lbValue bit_array_elem = lb_array_elem(p, bit_array);
  9388. lbValue offset_array_elem = lb_array_elem(p, offset_array);
  9389. LLVMValueRef vals[3] = {
  9390. llvm_const_slice(name_array_elem, v_count),
  9391. llvm_const_slice(bit_array_elem, v_count),
  9392. llvm_const_slice(offset_array_elem, v_count),
  9393. };
  9394. lbValue res = {};
  9395. res.type = type_deref(tag.type);
  9396. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9397. lb_emit_store(p, tag, res);
  9398. }
  9399. break;
  9400. }
  9401. case Type_BitSet:
  9402. {
  9403. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  9404. GB_ASSERT(is_type_typed(t->BitSet.elem));
  9405. LLVMValueRef vals[4] = {
  9406. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  9407. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  9408. lb_const_int(m, t_i64, t->BitSet.lower).value,
  9409. lb_const_int(m, t_i64, t->BitSet.upper).value,
  9410. };
  9411. if (t->BitSet.underlying != nullptr) {
  9412. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  9413. }
  9414. lbValue res = {};
  9415. res.type = type_deref(tag.type);
  9416. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9417. lb_emit_store(p, tag, res);
  9418. }
  9419. break;
  9420. case Type_Opaque:
  9421. {
  9422. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_opaque_ptr);
  9423. LLVMValueRef vals[1] = {
  9424. lb_get_type_info_ptr(m, t->Opaque.elem).value,
  9425. };
  9426. lbValue res = {};
  9427. res.type = type_deref(tag.type);
  9428. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9429. lb_emit_store(p, tag, res);
  9430. }
  9431. break;
  9432. case Type_SimdVector:
  9433. {
  9434. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  9435. LLVMValueRef vals[4] = {};
  9436. if (t->SimdVector.is_x86_mmx) {
  9437. vals[3] = lb_const_bool(m, t_bool, true).value;
  9438. } else {
  9439. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  9440. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  9441. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  9442. }
  9443. lbValue res = {};
  9444. res.type = type_deref(tag.type);
  9445. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9446. lb_emit_store(p, tag, res);
  9447. }
  9448. break;
  9449. }
  9450. if (tag.value != nullptr) {
  9451. Type *tag_type = type_deref(tag.type);
  9452. GB_ASSERT(is_type_named(tag_type));
  9453. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  9454. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  9455. } else {
  9456. if (t != t_llvm_bool) {
  9457. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  9458. }
  9459. }
  9460. }
  9461. }
  9462. void lb_generate_code(lbGenerator *gen) {
  9463. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  9464. TIME_SECTION("LLVM Initializtion");
  9465. lbModule *m = &gen->module;
  9466. LLVMModuleRef mod = gen->module.mod;
  9467. CheckerInfo *info = gen->info;
  9468. Arena temp_arena = {};
  9469. arena_init(&temp_arena, heap_allocator());
  9470. gbAllocator temp_allocator = arena_allocator(&temp_arena);
  9471. gen->module.global_default_context = lb_add_global_generated(m, t_context, {});
  9472. gen->module.global_default_context.kind = lbAddr_Context;
  9473. auto *min_dep_set = &info->minimum_dependency_set;
  9474. LLVMInitializeAllTargetInfos();
  9475. LLVMInitializeAllTargets();
  9476. LLVMInitializeAllTargetMCs();
  9477. LLVMInitializeAllAsmPrinters();
  9478. LLVMInitializeAllAsmParsers();
  9479. LLVMInitializeAllDisassemblers();
  9480. LLVMInitializeNativeTarget();
  9481. char const *target_triple = alloc_cstring(heap_allocator(), build_context.metrics.target_triplet);
  9482. char const *target_data_layout = alloc_cstring(heap_allocator(), build_context.metrics.target_data_layout);
  9483. LLVMSetTarget(mod, target_triple);
  9484. LLVMTargetRef target = {};
  9485. char *llvm_error = nullptr;
  9486. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  9487. GB_ASSERT(target != nullptr);
  9488. TIME_SECTION("LLVM Create Target Machine");
  9489. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault);
  9490. defer (LLVMDisposeTargetMachine(target_machine));
  9491. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  9492. { // Debug Info
  9493. for_array(i, info->files.entries) {
  9494. AstFile *f = info->files.entries[i].value;
  9495. String fullpath = f->fullpath;
  9496. String filename = filename_from_path(fullpath);
  9497. String directory = directory_from_path(fullpath);
  9498. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  9499. cast(char const *)filename.text, filename.len,
  9500. cast(char const *)directory.text, directory.len);
  9501. map_set(&m->debug_values, hash_pointer(f), res);
  9502. f->llvm_metadata = res;
  9503. }
  9504. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  9505. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  9506. "odin", 4,
  9507. false, "", 0,
  9508. 1, "", 0,
  9509. LLVMDWARFEmissionFull, 0, true,
  9510. true
  9511. );
  9512. }
  9513. TIME_SECTION("LLVM Global Variables");
  9514. {
  9515. { // Add type info data
  9516. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  9517. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  9518. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  9519. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  9520. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  9521. LLVMSetLinkage(g, LLVMInternalLinkage);
  9522. lbValue value = {};
  9523. value.value = g;
  9524. value.type = alloc_type_pointer(t);
  9525. lb_global_type_info_data = lb_addr(value);
  9526. }
  9527. { // Type info member buffer
  9528. // NOTE(bill): Removes need for heap allocation by making it global memory
  9529. isize count = 0;
  9530. for_array(entry_index, m->info->type_info_types) {
  9531. Type *t = m->info->type_info_types[entry_index];
  9532. isize index = lb_type_info_index(m->info, t, false);
  9533. if (index < 0) {
  9534. continue;
  9535. }
  9536. switch (t->kind) {
  9537. case Type_Union:
  9538. count += t->Union.variants.count;
  9539. break;
  9540. case Type_Struct:
  9541. count += t->Struct.fields.count;
  9542. break;
  9543. case Type_Tuple:
  9544. count += t->Tuple.variables.count;
  9545. break;
  9546. }
  9547. }
  9548. if (count > 0) {
  9549. {
  9550. char const *name = LB_TYPE_INFO_TYPES_NAME;
  9551. Type *t = alloc_type_array(t_type_info_ptr, count);
  9552. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  9553. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  9554. LLVMSetLinkage(g, LLVMInternalLinkage);
  9555. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  9556. }
  9557. {
  9558. char const *name = LB_TYPE_INFO_NAMES_NAME;
  9559. Type *t = alloc_type_array(t_string, count);
  9560. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  9561. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  9562. LLVMSetLinkage(g, LLVMInternalLinkage);
  9563. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  9564. }
  9565. {
  9566. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  9567. Type *t = alloc_type_array(t_uintptr, count);
  9568. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  9569. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  9570. LLVMSetLinkage(g, LLVMInternalLinkage);
  9571. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  9572. }
  9573. {
  9574. char const *name = LB_TYPE_INFO_USINGS_NAME;
  9575. Type *t = alloc_type_array(t_bool, count);
  9576. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  9577. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  9578. LLVMSetLinkage(g, LLVMInternalLinkage);
  9579. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  9580. }
  9581. {
  9582. char const *name = LB_TYPE_INFO_TAGS_NAME;
  9583. Type *t = alloc_type_array(t_string, count);
  9584. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  9585. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  9586. LLVMSetLinkage(g, LLVMInternalLinkage);
  9587. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  9588. }
  9589. }
  9590. }
  9591. }
  9592. isize global_variable_max_count = 0;
  9593. Entity *entry_point = info->entry_point;
  9594. bool has_dll_main = false;
  9595. bool has_win_main = false;
  9596. for_array(i, info->entities) {
  9597. Entity *e = info->entities[i];
  9598. String name = e->token.string;
  9599. bool is_global = e->pkg != nullptr;
  9600. if (e->kind == Entity_Variable) {
  9601. global_variable_max_count++;
  9602. } else if (e->kind == Entity_Procedure && !is_global) {
  9603. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  9604. GB_ASSERT(e == entry_point);
  9605. // entry_point = e;
  9606. }
  9607. if (e->Procedure.is_export ||
  9608. (e->Procedure.link_name.len > 0) ||
  9609. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  9610. if (!has_dll_main && name == "DllMain") {
  9611. has_dll_main = true;
  9612. } else if (!has_win_main && name == "WinMain") {
  9613. has_win_main = true;
  9614. }
  9615. }
  9616. }
  9617. }
  9618. struct GlobalVariable {
  9619. lbValue var;
  9620. lbValue init;
  9621. DeclInfo *decl;
  9622. };
  9623. auto global_variables = array_make<GlobalVariable>(heap_allocator(), 0, global_variable_max_count);
  9624. for_array(i, info->variable_init_order) {
  9625. DeclInfo *d = info->variable_init_order[i];
  9626. Entity *e = d->entity;
  9627. if ((e->scope->flags & ScopeFlag_File) == 0) {
  9628. continue;
  9629. }
  9630. if (!ptr_set_exists(min_dep_set, e)) {
  9631. continue;
  9632. }
  9633. DeclInfo *decl = decl_info_of_entity(e);
  9634. if (decl == nullptr) {
  9635. continue;
  9636. }
  9637. GB_ASSERT(e->kind == Entity_Variable);
  9638. bool is_foreign = e->Variable.is_foreign;
  9639. bool is_export = e->Variable.is_export;
  9640. String name = lb_get_entity_name(m, e);
  9641. lbValue g = {};
  9642. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(heap_allocator(), name));
  9643. g.type = alloc_type_pointer(e->type);
  9644. if (e->Variable.thread_local_model != "") {
  9645. LLVMSetThreadLocal(g.value, true);
  9646. String m = e->Variable.thread_local_model;
  9647. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  9648. if (m == "default") {
  9649. mode = LLVMGeneralDynamicTLSModel;
  9650. } else if (m == "localdynamic") {
  9651. mode = LLVMLocalDynamicTLSModel;
  9652. } else if (m == "initialexec") {
  9653. mode = LLVMInitialExecTLSModel;
  9654. } else if (m == "localexec") {
  9655. mode = LLVMLocalExecTLSModel;
  9656. } else {
  9657. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  9658. }
  9659. LLVMSetThreadLocalMode(g.value, mode);
  9660. }
  9661. if (is_foreign) {
  9662. LLVMSetExternallyInitialized(g.value, true);
  9663. } else {
  9664. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  9665. }
  9666. if (is_export) {
  9667. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  9668. }
  9669. GlobalVariable var = {};
  9670. var.var = g;
  9671. var.decl = decl;
  9672. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  9673. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  9674. if (tav.mode != Addressing_Invalid) {
  9675. if (tav.value.kind != ExactValue_Invalid) {
  9676. ExactValue v = tav.value;
  9677. lbValue init = lb_const_value(m, tav.type, v);
  9678. LLVMSetInitializer(g.value, init.value);
  9679. }
  9680. }
  9681. }
  9682. array_add(&global_variables, var);
  9683. lb_add_entity(m, e, g);
  9684. lb_add_member(m, name, g);
  9685. }
  9686. TIME_SECTION("LLVM Global Procedures and Types");
  9687. for_array(i, info->entities) {
  9688. // arena_free_all(&temp_arena);
  9689. // gbAllocator a = temp_allocator;
  9690. Entity *e = info->entities[i];
  9691. String name = e->token.string;
  9692. DeclInfo *decl = e->decl_info;
  9693. Scope * scope = e->scope;
  9694. if ((scope->flags & ScopeFlag_File) == 0) {
  9695. continue;
  9696. }
  9697. Scope *package_scope = scope->parent;
  9698. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  9699. switch (e->kind) {
  9700. case Entity_Variable:
  9701. // NOTE(bill): Handled above as it requires a specific load order
  9702. continue;
  9703. case Entity_ProcGroup:
  9704. continue;
  9705. case Entity_TypeName:
  9706. case Entity_Procedure:
  9707. break;
  9708. }
  9709. bool polymorphic_struct = false;
  9710. if (e->type != nullptr && e->kind == Entity_TypeName) {
  9711. Type *bt = base_type(e->type);
  9712. if (bt->kind == Type_Struct) {
  9713. polymorphic_struct = is_type_polymorphic(bt);
  9714. }
  9715. }
  9716. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  9717. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  9718. continue;
  9719. }
  9720. String mangled_name = lb_get_entity_name(m, e);
  9721. switch (e->kind) {
  9722. case Entity_TypeName:
  9723. lb_type(m, e->type);
  9724. break;
  9725. case Entity_Procedure:
  9726. {
  9727. lbProcedure *p = lb_create_procedure(m, e);
  9728. array_add(&m->procedures_to_generate, p);
  9729. }
  9730. break;
  9731. }
  9732. }
  9733. TIME_SECTION("LLVM Procedure Generation");
  9734. for_array(i, m->procedures_to_generate) {
  9735. lbProcedure *p = m->procedures_to_generate[i];
  9736. if (p->is_done) {
  9737. continue;
  9738. }
  9739. if (p->body != nullptr) { // Build Procedure
  9740. lb_begin_procedure_body(p);
  9741. lb_build_stmt(p, p->body);
  9742. lb_end_procedure_body(p);
  9743. p->is_done = true;
  9744. }
  9745. lb_end_procedure(p);
  9746. // Add Flags
  9747. if (p->body != nullptr) {
  9748. if (p->name == "memcpy" || p->name == "memmove" ||
  9749. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  9750. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  9751. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  9752. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  9753. }
  9754. }
  9755. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  9756. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  9757. LLVMDumpValue(p->value);
  9758. gb_printf_err("\n\n\n\n");
  9759. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  9760. }
  9761. }
  9762. TIME_SECTION("LLVM Function Pass");
  9763. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  9764. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  9765. defer (LLVMDisposePassManager(default_function_pass_manager));
  9766. {
  9767. LLVMAddMemCpyOptPass(default_function_pass_manager);
  9768. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  9769. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  9770. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  9771. LLVMAddConstantPropagationPass(default_function_pass_manager);
  9772. LLVMAddAggressiveDCEPass(default_function_pass_manager);
  9773. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  9774. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  9775. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager);
  9776. }
  9777. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  9778. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  9779. {
  9780. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  9781. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  9782. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager_without_memcpy);
  9783. LLVMAddConstantPropagationPass(default_function_pass_manager_without_memcpy);
  9784. LLVMAddAggressiveDCEPass(default_function_pass_manager_without_memcpy);
  9785. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  9786. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  9787. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager_without_memcpy);
  9788. }
  9789. for_array(i, m->procedures_to_generate) {
  9790. lbProcedure *p = m->procedures_to_generate[i];
  9791. if (p->body != nullptr) { // Build Procedure
  9792. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  9793. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  9794. } else {
  9795. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  9796. }
  9797. }
  9798. }
  9799. TIME_SECTION("LLVM Runtime Creation");
  9800. lbProcedure *startup_type_info = nullptr;
  9801. lbProcedure *startup_context = nullptr;
  9802. lbProcedure *startup_runtime = nullptr;
  9803. { // Startup Type Info
  9804. Type *params = alloc_type_tuple();
  9805. Type *results = alloc_type_tuple();
  9806. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  9807. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  9808. p->is_startup = true;
  9809. startup_type_info = p;
  9810. lb_begin_procedure_body(p);
  9811. lb_setup_type_info_data(p);
  9812. lb_end_procedure_body(p);
  9813. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  9814. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  9815. LLVMDumpValue(p->value);
  9816. gb_printf_err("\n\n\n\n");
  9817. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  9818. }
  9819. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  9820. }
  9821. { // Startup Context
  9822. Type *params = alloc_type_tuple();
  9823. Type *results = alloc_type_tuple();
  9824. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  9825. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_CONTEXT_PROC_NAME), proc_type);
  9826. p->is_startup = true;
  9827. startup_context = p;
  9828. lb_begin_procedure_body(p);
  9829. lb_emit_init_context(p, p->module->global_default_context);
  9830. lb_end_procedure_body(p);
  9831. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  9832. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  9833. LLVMDumpValue(p->value);
  9834. gb_printf_err("\n\n\n\n");
  9835. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  9836. }
  9837. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  9838. }
  9839. { // Startup Runtime
  9840. Type *params = alloc_type_tuple();
  9841. Type *results = alloc_type_tuple();
  9842. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  9843. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  9844. p->is_startup = true;
  9845. startup_runtime = p;
  9846. lb_begin_procedure_body(p);
  9847. for_array(i, global_variables) {
  9848. auto *var = &global_variables[i];
  9849. if (var->decl->init_expr != nullptr) {
  9850. var->init = lb_build_expr(p, var->decl->init_expr);
  9851. }
  9852. Entity *e = var->decl->entity;
  9853. GB_ASSERT(e->kind == Entity_Variable);
  9854. if (e->Variable.is_foreign) {
  9855. Entity *fl = e->Procedure.foreign_library;
  9856. lb_add_foreign_library_path(m, fl);
  9857. }
  9858. if (e->flags & EntityFlag_Static) {
  9859. LLVMSetLinkage(var->var.value, LLVMInternalLinkage);
  9860. }
  9861. if (var->init.value != nullptr) {
  9862. Type *t = type_deref(var->var.type);
  9863. if (is_type_any(t)) {
  9864. // NOTE(bill): Edge case for 'any' type
  9865. Type *var_type = default_type(var->init.type);
  9866. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  9867. lb_addr_store(p, g, var->init);
  9868. lbValue gp = lb_addr_get_ptr(p, g);
  9869. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  9870. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  9871. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  9872. lb_emit_store(p, ti, lb_type_info(m, var_type));
  9873. } else {
  9874. lb_emit_store(p, var->var, lb_emit_conv(p, var->init, t));
  9875. }
  9876. }
  9877. }
  9878. lb_end_procedure_body(p);
  9879. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  9880. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  9881. LLVMDumpValue(p->value);
  9882. gb_printf_err("\n\n\n\n");
  9883. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  9884. }
  9885. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  9886. /*{
  9887. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  9888. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  9889. instr != last_instr;
  9890. instr = LLVMGetNextInstruction(instr)) {
  9891. if (LLVMIsAAllocaInst(instr)) {
  9892. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  9893. LLVMValueRef sz_val = LLVMSizeOf(type);
  9894. GB_ASSERT(LLVMIsConstant(sz_val));
  9895. gb_printf_err(">> 0x%p\n", sz_val);
  9896. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  9897. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  9898. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  9899. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  9900. gb_printf_err(">> %ll\n", sz);
  9901. }
  9902. }
  9903. }*/
  9904. }
  9905. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  9906. Type *params = alloc_type_tuple();
  9907. Type *results = alloc_type_tuple();
  9908. array_init(&params->Tuple.variables, heap_allocator(), 2);
  9909. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  9910. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  9911. array_init(&results->Tuple.variables, heap_allocator(), 1);
  9912. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  9913. Type *proc_type = alloc_type_proc(nullptr, params, 2, results, 1, false, ProcCC_CDecl);
  9914. lbProcedure *p = lb_create_dummy_procedure(m, str_lit("main"), proc_type);
  9915. p->is_startup = true;
  9916. lb_begin_procedure_body(p);
  9917. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  9918. GB_ASSERT(found != nullptr);
  9919. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  9920. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_context->type)), startup_context->value, nullptr, 0, "");
  9921. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  9922. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  9923. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  9924. lb_end_procedure_body(p);
  9925. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  9926. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  9927. LLVMDumpValue(p->value);
  9928. gb_printf_err("\n\n\n\n");
  9929. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  9930. }
  9931. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  9932. }
  9933. TIME_SECTION("LLVM Module Pass");
  9934. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  9935. defer (LLVMDisposePassManager(module_pass_manager));
  9936. LLVMAddAlwaysInlinerPass(module_pass_manager);
  9937. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  9938. // LLVMAddConstantMergePass(module_pass_manager);
  9939. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  9940. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  9941. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level);
  9942. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level);
  9943. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  9944. LLVMRunPassManager(module_pass_manager, mod);
  9945. llvm_error = nullptr;
  9946. defer (LLVMDisposeMessage(llvm_error));
  9947. String filepath_ll = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".ll"));
  9948. defer (gb_free(heap_allocator(), filepath_ll.text));
  9949. String filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".obj"));
  9950. if (build_context.keep_temp_files) {
  9951. TIME_SECTION("LLVM Print Module to File");
  9952. LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error);
  9953. // exit(1);
  9954. }
  9955. LLVMDIBuilderFinalize(m->debug_builder);
  9956. LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error);
  9957. llvm_error = nullptr;
  9958. TIME_SECTION("LLVM Object Generation");
  9959. LLVMBool was_an_error = LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, LLVMObjectFile, &llvm_error);
  9960. if (was_an_error) {
  9961. gb_printf_err("LLVM Error: %s\n", llvm_error);
  9962. gb_exit(1);
  9963. return;
  9964. }
  9965. array_add(&gen->output_object_paths, filepath_obj);
  9966. #undef TIME_SECTION
  9967. }