llvm_backend.cpp 388 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541
  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_zero(lbModule *m) {
  30. return LLVMConstInt(lb_type(m, t_int), 0, false);
  31. }
  32. LLVMValueRef llvm_one(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. bool lb_is_instr_terminating(LLVMValueRef instr) {
  47. if (instr != nullptr) {
  48. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  49. switch (op) {
  50. case LLVMRet:
  51. case LLVMBr:
  52. case LLVMSwitch:
  53. case LLVMIndirectBr:
  54. case LLVMInvoke:
  55. case LLVMUnreachable:
  56. case LLVMCallBr:
  57. return true;
  58. }
  59. }
  60. return false;
  61. }
  62. lbAddr lb_addr(lbValue addr) {
  63. lbAddr v = {lbAddr_Default, addr};
  64. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  65. GB_ASSERT(is_type_pointer(addr.type));
  66. v.kind = lbAddr_RelativePointer;
  67. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  68. GB_ASSERT(is_type_pointer(addr.type));
  69. v.kind = lbAddr_RelativeSlice;
  70. }
  71. return v;
  72. }
  73. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  74. lbAddr v = {lbAddr_Map, addr};
  75. v.map.key = map_key;
  76. v.map.type = map_type;
  77. v.map.result = map_result;
  78. return v;
  79. }
  80. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  81. lbAddr v = {lbAddr_SoaVariable, addr};
  82. v.soa.index = index;
  83. v.soa.index_expr = index_expr;
  84. return v;
  85. }
  86. lbAddr lb_addr_bit_field(lbValue value, i32 index) {
  87. lbAddr addr = {};
  88. addr.kind = lbAddr_BitField;
  89. addr.addr = value;
  90. addr.bit_field.value_index = index;
  91. return addr;
  92. }
  93. Type *lb_addr_type(lbAddr const &addr) {
  94. if (addr.addr.value == nullptr) {
  95. return nullptr;
  96. }
  97. if (addr.kind == lbAddr_Map) {
  98. Type *t = base_type(addr.map.type);
  99. GB_ASSERT(is_type_map(t));
  100. return t->Map.value;
  101. }
  102. return type_deref(addr.addr.type);
  103. }
  104. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  105. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  106. }
  107. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  108. if (addr.addr.value == nullptr) {
  109. GB_PANIC("Illegal addr -> nullptr");
  110. return {};
  111. }
  112. switch (addr.kind) {
  113. case lbAddr_Map: {
  114. Type *map_type = base_type(addr.map.type);
  115. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  116. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  117. auto args = array_make<lbValue>(heap_allocator(), 2);
  118. args[0] = h;
  119. args[1] = key;
  120. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  121. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  122. }
  123. case lbAddr_RelativePointer: {
  124. Type *rel_ptr = base_type(lb_addr_type(addr));
  125. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  126. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  127. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  128. offset = lb_emit_load(p, offset);
  129. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  130. offset = lb_emit_conv(p, offset, t_i64);
  131. }
  132. offset = lb_emit_conv(p, offset, t_uintptr);
  133. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  134. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  135. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  136. // NOTE(bill): nil check
  137. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  138. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  139. return final_ptr;
  140. }
  141. case lbAddr_BitField: {
  142. lbValue v = lb_addr_load(p, addr);
  143. return lb_address_from_load_or_generate_local(p, v);
  144. }
  145. case lbAddr_Context:
  146. GB_PANIC("lbAddr_Context should be handled elsewhere");
  147. }
  148. return addr.addr;
  149. }
  150. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  151. lbAddr addr = lb_build_addr(p, expr);
  152. return lb_addr_get_ptr(p, addr);
  153. }
  154. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  155. if (build_context.no_bounds_check) {
  156. return;
  157. }
  158. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  159. return;
  160. }
  161. index = lb_emit_conv(p, index, t_int);
  162. len = lb_emit_conv(p, len, t_int);
  163. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  164. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  165. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  166. auto args = array_make<lbValue>(heap_allocator(), 5);
  167. args[0] = file;
  168. args[1] = line;
  169. args[2] = column;
  170. args[3] = index;
  171. args[4] = len;
  172. lb_emit_runtime_call(p, "bounds_check_error", args);
  173. }
  174. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  175. if (build_context.no_bounds_check) {
  176. return;
  177. }
  178. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  179. return;
  180. }
  181. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  182. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  183. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  184. high = lb_emit_conv(p, high, t_int);
  185. if (!lower_value_used) {
  186. auto args = array_make<lbValue>(heap_allocator(), 5);
  187. args[0] = file;
  188. args[1] = line;
  189. args[2] = column;
  190. args[3] = high;
  191. args[4] = len;
  192. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  193. } else {
  194. // No need to convert unless used
  195. low = lb_emit_conv(p, low, t_int);
  196. auto args = array_make<lbValue>(heap_allocator(), 6);
  197. args[0] = file;
  198. args[1] = line;
  199. args[2] = column;
  200. args[3] = low;
  201. args[4] = high;
  202. args[5] = len;
  203. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  204. }
  205. }
  206. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  207. if (addr.addr.value == nullptr) {
  208. return;
  209. }
  210. GB_ASSERT(value.type != nullptr);
  211. if (is_type_untyped_undef(value.type)) {
  212. Type *t = lb_addr_type(addr);
  213. value.type = t;
  214. value.value = LLVMGetUndef(lb_type(p->module, t));
  215. } else if (is_type_untyped_nil(value.type)) {
  216. Type *t = lb_addr_type(addr);
  217. value.type = t;
  218. value.value = LLVMConstNull(lb_type(p->module, t));
  219. }
  220. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  221. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  222. }
  223. if (addr.kind == lbAddr_RelativePointer) {
  224. Type *rel_ptr = base_type(lb_addr_type(addr));
  225. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  226. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  227. GB_ASSERT(is_type_pointer(addr.addr.type));
  228. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  229. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  230. lbValue offset = {};
  231. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  232. offset.type = t_uintptr;
  233. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  234. offset = lb_emit_conv(p, offset, t_i64);
  235. }
  236. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  237. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  238. offset = lb_emit_select(p,
  239. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  240. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  241. offset
  242. );
  243. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  244. return;
  245. } else if (addr.kind == lbAddr_RelativeSlice) {
  246. Type *rel_ptr = base_type(lb_addr_type(addr));
  247. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  248. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  249. GB_ASSERT(is_type_pointer(addr.addr.type));
  250. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  251. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  252. lbValue offset = {};
  253. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  254. offset.type = t_uintptr;
  255. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  256. offset = lb_emit_conv(p, offset, t_i64);
  257. }
  258. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  259. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  260. offset = lb_emit_select(p,
  261. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  262. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  263. offset
  264. );
  265. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  266. lbValue len = lb_slice_len(p, value);
  267. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  268. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  269. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  270. return;
  271. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  272. lbValue ptr = addr.addr;
  273. lbValue index = addr.index_set.index;
  274. Ast *node = addr.index_set.node;
  275. ast_node(ce, CallExpr, node);
  276. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  277. proc_type = base_type(proc_type);
  278. GB_ASSERT(is_type_proc(proc_type));
  279. TypeProc *pt = &proc_type->Proc;
  280. isize arg_count = 3;
  281. isize param_count = 0;
  282. if (pt->params) {
  283. GB_ASSERT(pt->params->kind == Type_Tuple);
  284. param_count = pt->params->Tuple.variables.count;
  285. }
  286. auto args = array_make<lbValue>(heap_allocator(), gb_max(arg_count, param_count));
  287. args[0] = ptr;
  288. args[1] = index;
  289. args[2] = value;
  290. isize arg_index = arg_count;
  291. if (arg_count < param_count) {
  292. lbModule *m = p->module;
  293. String proc_name = {};
  294. if (p->entity != nullptr) {
  295. proc_name = p->entity->token.string;
  296. }
  297. TokenPos pos = ast_token(ce->proc).pos;
  298. TypeTuple *param_tuple = &pt->params->Tuple;
  299. isize end = cast(isize)param_count;
  300. while (arg_index < end) {
  301. Entity *e = param_tuple->variables[arg_index];
  302. GB_ASSERT(e->kind == Entity_Variable);
  303. switch (e->Variable.param_value.kind) {
  304. case ParameterValue_Constant:
  305. args[arg_index++] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  306. break;
  307. case ParameterValue_Nil:
  308. args[arg_index++] = lb_const_nil(m, e->type);
  309. break;
  310. case ParameterValue_Location:
  311. args[arg_index++] = lb_emit_source_code_location(p, proc_name, pos);
  312. break;
  313. case ParameterValue_Value:
  314. args[arg_index++] = lb_build_expr(p, e->Variable.param_value.ast_value);
  315. break;
  316. }
  317. }
  318. }
  319. Entity *e = entity_from_expr(ce->proc);
  320. GB_ASSERT(e != nullptr);
  321. GB_ASSERT(is_type_polymorphic(e->type));
  322. {
  323. lbValue *found = nullptr;
  324. if (p->module != e->code_gen_module) {
  325. gb_mutex_lock(&p->module->mutex);
  326. }
  327. found = map_get(&e->code_gen_module->values, hash_entity(e));
  328. if (p->module != e->code_gen_module) {
  329. gb_mutex_unlock(&p->module->mutex);
  330. }
  331. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  332. lb_emit_call(p, *found, args);
  333. }
  334. return;
  335. } else if (addr.kind == lbAddr_Map) {
  336. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  337. return;
  338. } else if (addr.kind == lbAddr_BitField) {
  339. Type *bft = base_type(type_deref(addr.addr.type));
  340. GB_ASSERT(is_type_bit_field(bft));
  341. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  342. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  343. if (size_in_bits == 0) {
  344. return;
  345. }
  346. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  347. LLVMTypeRef dst_type = LLVMIntTypeInContext(p->module->ctx, size_in_bits);
  348. LLVMValueRef src = LLVMBuildIntCast2(p->builder, value.value, dst_type, false, "");
  349. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  350. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  351. LLVMBuildStore(p->builder, src, field_ptr);
  352. return;
  353. } else if (addr.kind == lbAddr_Context) {
  354. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  355. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  356. lb_addr_store(p, next_addr, old);
  357. lb_push_context_onto_stack(p, next_addr);
  358. lbValue next = lb_addr_get_ptr(p, next_addr);
  359. if (addr.ctx.sel.index.count > 0) {
  360. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  361. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  362. lb_emit_store(p, lhs, rhs);
  363. } else {
  364. lbValue lhs = next;
  365. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  366. lb_emit_store(p, lhs, rhs);
  367. }
  368. return;
  369. } else if (addr.kind == lbAddr_SoaVariable) {
  370. Type *t = type_deref(addr.addr.type);
  371. t = base_type(t);
  372. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  373. value = lb_emit_conv(p, value, t->Struct.soa_elem);
  374. lbValue index = addr.soa.index;
  375. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  376. Type *t = base_type(type_deref(addr.addr.type));
  377. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  378. i64 count = t->Struct.soa_count;
  379. lbValue len = lb_const_int(p->module, t_int, count);
  380. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  381. }
  382. for_array(i, t->Struct.fields) {
  383. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  384. dst = lb_emit_array_ep(p, dst, index);
  385. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  386. lb_emit_store(p, dst, src);
  387. }
  388. return;
  389. }
  390. GB_ASSERT(value.value != nullptr);
  391. value = lb_emit_conv(p, value, lb_addr_type(addr));
  392. LLVMBuildStore(p->builder, value.value, addr.addr.value);
  393. }
  394. void lb_const_store(lbValue ptr, lbValue value) {
  395. GB_ASSERT(lb_is_const(ptr));
  396. GB_ASSERT(lb_is_const(value));
  397. GB_ASSERT(is_type_pointer(ptr.type));
  398. LLVMSetInitializer(ptr.value, value.value);
  399. }
  400. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  401. GB_ASSERT(value.value != nullptr);
  402. Type *a = type_deref(ptr.type);
  403. if (is_type_boolean(a)) {
  404. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  405. value = lb_emit_conv(p, value, a);
  406. }
  407. Type *ca = core_type(a);
  408. if (ca->kind == Type_Basic) {
  409. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  410. } else {
  411. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  412. }
  413. LLVMBuildStore(p->builder, value.value, ptr.value);
  414. }
  415. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  416. lbModule *m = p->module;
  417. GB_ASSERT(value.value != nullptr);
  418. Type *t = type_deref(value.type);
  419. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  420. return lbValue{v, t};
  421. }
  422. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  423. GB_ASSERT(addr.addr.value != nullptr);
  424. if (addr.kind == lbAddr_RelativePointer) {
  425. Type *rel_ptr = base_type(lb_addr_type(addr));
  426. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  427. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  428. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  429. offset = lb_emit_load(p, offset);
  430. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  431. offset = lb_emit_conv(p, offset, t_i64);
  432. }
  433. offset = lb_emit_conv(p, offset, t_uintptr);
  434. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  435. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  436. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  437. // NOTE(bill): nil check
  438. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  439. lbValue final_ptr = {};
  440. final_ptr.type = absolute_ptr.type;
  441. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  442. return lb_emit_load(p, final_ptr);
  443. } else if (addr.kind == lbAddr_RelativeSlice) {
  444. Type *rel_ptr = base_type(lb_addr_type(addr));
  445. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  446. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  447. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  448. lbValue offset = lb_emit_load(p, offset_ptr);
  449. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  450. offset = lb_emit_conv(p, offset, t_i64);
  451. }
  452. offset = lb_emit_conv(p, offset, t_uintptr);
  453. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  454. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  455. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  456. Type *slice_elem = slice_type->Slice.elem;
  457. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  458. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  459. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  460. // NOTE(bill): nil check
  461. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  462. lbValue data = {};
  463. data.type = absolute_ptr.type;
  464. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  465. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  466. len = lb_emit_conv(p, len, t_int);
  467. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  468. lb_fill_slice(p, slice, data, len);
  469. return lb_addr_load(p, slice);
  470. } else if (addr.kind == lbAddr_Map) {
  471. Type *map_type = base_type(addr.map.type);
  472. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  473. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  474. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  475. auto args = array_make<lbValue>(heap_allocator(), 2);
  476. args[0] = h;
  477. args[1] = key;
  478. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  479. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  480. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  481. lbBlock *then = lb_create_block(p, "map.get.then");
  482. lbBlock *done = lb_create_block(p, "map.get.done");
  483. lb_emit_if(p, ok, then, done);
  484. lb_start_block(p, then);
  485. {
  486. // TODO(bill): mem copy it instead?
  487. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  488. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  489. lb_emit_store(p, gep0, lb_emit_load(p, value));
  490. }
  491. lb_emit_jump(p, done);
  492. lb_start_block(p, done);
  493. if (is_type_tuple(addr.map.result)) {
  494. return lb_addr_load(p, v);
  495. } else {
  496. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  497. return lb_emit_load(p, single);
  498. }
  499. } else if (addr.kind == lbAddr_BitField) {
  500. Type *bft = base_type(type_deref(addr.addr.type));
  501. GB_ASSERT(is_type_bit_field(bft));
  502. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  503. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  504. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  505. if (size_in_bytes == 0) {
  506. GB_ASSERT(size_in_bits == 0);
  507. lbValue res = {};
  508. res.type = t_i32;
  509. res.value = LLVMConstInt(lb_type(p->module, res.type), 0, false);
  510. return res;
  511. }
  512. Type *int_type = nullptr;
  513. switch (size_in_bytes) {
  514. case 1: int_type = t_u8; break;
  515. case 2: int_type = t_u16; break;
  516. case 4: int_type = t_u32; break;
  517. case 8: int_type = t_u64; break;
  518. case 16: int_type = t_u128; break;
  519. }
  520. GB_ASSERT(int_type != nullptr);
  521. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  522. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  523. LLVMValueRef field = LLVMBuildLoad(p->builder, field_ptr, "");
  524. lbValue res = {};
  525. res.type = int_type;
  526. res.value = LLVMBuildZExtOrBitCast(p->builder, field, lb_type(p->module, int_type), "");
  527. return res;
  528. } else if (addr.kind == lbAddr_Context) {
  529. if (addr.ctx.sel.index.count > 0) {
  530. lbValue a = addr.addr;
  531. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  532. return lb_emit_load(p, b);
  533. } else {
  534. return lb_emit_load(p, addr.addr);
  535. }
  536. } else if (addr.kind == lbAddr_SoaVariable) {
  537. Type *t = type_deref(addr.addr.type);
  538. t = base_type(t);
  539. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  540. Type *elem = t->Struct.soa_elem;
  541. lbValue len = {};
  542. if (t->Struct.soa_kind == StructSoa_Fixed) {
  543. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  544. } else {
  545. lbValue v = lb_emit_load(p, addr.addr);
  546. len = lb_soa_struct_len(p, v);
  547. }
  548. lbAddr res = lb_add_local_generated(p, elem, true);
  549. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  550. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  551. }
  552. if (t->Struct.soa_kind == StructSoa_Fixed) {
  553. for_array(i, t->Struct.fields) {
  554. Entity *field = t->Struct.fields[i];
  555. Type *base_type = field->type;
  556. GB_ASSERT(base_type->kind == Type_Array);
  557. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  558. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  559. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  560. lbValue src = lb_emit_load(p, src_ptr);
  561. lb_emit_store(p, dst, src);
  562. }
  563. } else {
  564. isize field_count = t->Struct.fields.count;
  565. if (t->Struct.soa_kind == StructSoa_Slice) {
  566. field_count -= 1;
  567. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  568. field_count -= 3;
  569. }
  570. for (isize i = 0; i < field_count; i++) {
  571. Entity *field = t->Struct.fields[i];
  572. Type *base_type = field->type;
  573. GB_ASSERT(base_type->kind == Type_Pointer);
  574. Type *elem = base_type->Pointer.elem;
  575. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  576. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  577. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  578. lbValue src = lb_emit_load(p, src_ptr);
  579. src = lb_emit_load(p, src);
  580. lb_emit_store(p, dst, src);
  581. }
  582. }
  583. return lb_addr_load(p, res);
  584. }
  585. if (is_type_proc(addr.addr.type)) {
  586. return addr.addr;
  587. }
  588. return lb_emit_load(p, addr.addr);
  589. }
  590. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  591. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  592. }
  593. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  594. Type *t = u.type;
  595. GB_ASSERT_MSG(is_type_pointer(t) &&
  596. is_type_union(type_deref(t)), "%s", type_to_string(t));
  597. Type *ut = type_deref(t);
  598. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  599. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  600. GB_ASSERT(type_size_of(ut) > 0);
  601. Type *tag_type = union_tag_type(ut);
  602. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  603. unsigned element_count = LLVMCountStructElementTypes(uvt);
  604. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  605. lbValue tag_ptr = {};
  606. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  607. tag_ptr.type = alloc_type_pointer(tag_type);
  608. return tag_ptr;
  609. }
  610. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  611. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  612. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  613. return lb_emit_load(p, tag_ptr);
  614. }
  615. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  616. Type *t = type_deref(parent.type);
  617. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  618. // No tag needed!
  619. } else {
  620. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  621. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  622. }
  623. }
  624. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  625. gbAllocator a = heap_allocator();
  626. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  627. lb_emit_store(p, underlying, variant);
  628. lb_emit_store_union_variant_tag(p, parent, variant_type);
  629. }
  630. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  631. unsigned field_count = LLVMCountStructElementTypes(src);
  632. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  633. LLVMGetStructElementTypes(src, fields);
  634. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  635. gb_free(heap_allocator(), fields);
  636. }
  637. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  638. switch (alignment) {
  639. case 1:
  640. return LLVMArrayType(lb_type(m, t_u8), 0);
  641. case 2:
  642. return LLVMArrayType(lb_type(m, t_u16), 0);
  643. case 4:
  644. return LLVMArrayType(lb_type(m, t_u32), 0);
  645. case 8:
  646. return LLVMArrayType(lb_type(m, t_u64), 0);
  647. case 16:
  648. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  649. default:
  650. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  651. break;
  652. }
  653. return nullptr;
  654. }
  655. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  656. if (!elem_type_can_be_constant(elem_type)) {
  657. return false;
  658. }
  659. if (elem->kind == Ast_FieldValue) {
  660. elem = elem->FieldValue.value;
  661. }
  662. TypeAndValue tav = type_and_value_of_expr(elem);
  663. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  664. return tav.value.kind != ExactValue_Invalid;
  665. }
  666. String lb_mangle_name(lbModule *m, Entity *e) {
  667. gbAllocator a = heap_allocator();
  668. String name = e->token.string;
  669. AstPackage *pkg = e->pkg;
  670. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  671. String pkgn = pkg->name;
  672. GB_ASSERT(!rune_is_digit(pkgn[0]));
  673. if (pkgn == "llvm") {
  674. pkgn = str_lit("llvm$");
  675. }
  676. isize max_len = pkgn.len + 1 + name.len + 1;
  677. bool require_suffix_id = is_type_polymorphic(e->type, true);
  678. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  679. require_suffix_id = true;
  680. } else if (is_blank_ident(e->token)) {
  681. require_suffix_id = true;
  682. }if (e->flags & EntityFlag_NotExported) {
  683. require_suffix_id = true;
  684. }
  685. if (require_suffix_id) {
  686. max_len += 21;
  687. }
  688. char *new_name = gb_alloc_array(a, char, max_len);
  689. isize new_name_len = gb_snprintf(
  690. new_name, max_len,
  691. "%.*s.%.*s", LIT(pkgn), LIT(name)
  692. );
  693. if (require_suffix_id) {
  694. char *str = new_name + new_name_len-1;
  695. isize len = max_len-new_name_len;
  696. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  697. new_name_len += extra-1;
  698. }
  699. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  700. return mangled_name;
  701. }
  702. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  703. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  704. // and as a result, the declaration does not have time to determine what it should be
  705. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  706. if (e->TypeName.ir_mangled_name.len != 0) {
  707. return e->TypeName.ir_mangled_name;
  708. }
  709. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  710. if (p == nullptr) {
  711. Entity *proc = nullptr;
  712. if (e->parent_proc_decl != nullptr) {
  713. proc = e->parent_proc_decl->entity;
  714. } else {
  715. Scope *scope = e->scope;
  716. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  717. scope = scope->parent;
  718. }
  719. GB_ASSERT(scope != nullptr);
  720. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  721. proc = scope->procedure_entity;
  722. }
  723. GB_ASSERT(proc->kind == Entity_Procedure);
  724. if (proc->code_gen_procedure != nullptr) {
  725. p = proc->code_gen_procedure;
  726. }
  727. }
  728. // NOTE(bill): Generate a new name
  729. // parent_proc.name-guid
  730. String ts_name = e->token.string;
  731. if (p != nullptr) {
  732. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  733. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  734. u32 guid = ++p->module->nested_type_name_guid;
  735. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  736. String name = make_string(cast(u8 *)name_text, name_len-1);
  737. e->TypeName.ir_mangled_name = name;
  738. return name;
  739. } else {
  740. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  741. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  742. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  743. static u32 guid = 0;
  744. guid += 1;
  745. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  746. String name = make_string(cast(u8 *)name_text, name_len-1);
  747. e->TypeName.ir_mangled_name = name;
  748. return name;
  749. }
  750. }
  751. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  752. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  753. return e->TypeName.ir_mangled_name;
  754. }
  755. GB_ASSERT(e != nullptr);
  756. if (e->pkg == nullptr) {
  757. return e->token.string;
  758. }
  759. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  760. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  761. }
  762. String name = {};
  763. bool no_name_mangle = false;
  764. if (e->kind == Entity_Variable) {
  765. bool is_foreign = e->Variable.is_foreign;
  766. bool is_export = e->Variable.is_export;
  767. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  768. if (e->Variable.link_name.len > 0) {
  769. return e->Variable.link_name;
  770. }
  771. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  772. return e->Procedure.link_name;
  773. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  774. no_name_mangle = true;
  775. }
  776. if (!no_name_mangle) {
  777. name = lb_mangle_name(m, e);
  778. }
  779. if (name.len == 0) {
  780. name = e->token.string;
  781. }
  782. if (e->kind == Entity_TypeName) {
  783. if ((e->scope->flags & ScopeFlag_File) == 0) {
  784. gb_printf_err("<<< %.*s %.*s %p\n", LIT(e->token.string), LIT(name), e);
  785. }
  786. e->TypeName.ir_mangled_name = name;
  787. } else if (e->kind == Entity_Procedure) {
  788. e->Procedure.link_name = name;
  789. }
  790. return name;
  791. }
  792. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  793. Type *original_type = type;
  794. LLVMContextRef ctx = m->ctx;
  795. i64 size = type_size_of(type); // Check size
  796. GB_ASSERT(type != t_invalid);
  797. switch (type->kind) {
  798. case Type_Basic:
  799. switch (type->Basic.kind) {
  800. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  801. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  802. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  803. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  804. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  805. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  806. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  807. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  808. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  809. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  810. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  811. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  812. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  813. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  814. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  815. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  816. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  817. // Basic_f16,
  818. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  819. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  820. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  821. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  822. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  823. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  824. // Basic_complex32,
  825. case Basic_complex64:
  826. {
  827. char const *name = "..complex64";
  828. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  829. if (type != nullptr) {
  830. return type;
  831. }
  832. type = LLVMStructCreateNamed(ctx, name);
  833. LLVMTypeRef fields[2] = {
  834. lb_type(m, t_f32),
  835. lb_type(m, t_f32),
  836. };
  837. LLVMStructSetBody(type, fields, 2, false);
  838. return type;
  839. }
  840. case Basic_complex128:
  841. {
  842. char const *name = "..complex128";
  843. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  844. if (type != nullptr) {
  845. return type;
  846. }
  847. type = LLVMStructCreateNamed(ctx, name);
  848. LLVMTypeRef fields[2] = {
  849. lb_type(m, t_f64),
  850. lb_type(m, t_f64),
  851. };
  852. LLVMStructSetBody(type, fields, 2, false);
  853. return type;
  854. }
  855. case Basic_quaternion128:
  856. {
  857. char const *name = "..quaternion128";
  858. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  859. if (type != nullptr) {
  860. return type;
  861. }
  862. type = LLVMStructCreateNamed(ctx, name);
  863. LLVMTypeRef fields[4] = {
  864. lb_type(m, t_f32),
  865. lb_type(m, t_f32),
  866. lb_type(m, t_f32),
  867. lb_type(m, t_f32),
  868. };
  869. LLVMStructSetBody(type, fields, 4, false);
  870. return type;
  871. }
  872. case Basic_quaternion256:
  873. {
  874. char const *name = "..quaternion256";
  875. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  876. if (type != nullptr) {
  877. return type;
  878. }
  879. type = LLVMStructCreateNamed(ctx, name);
  880. LLVMTypeRef fields[4] = {
  881. lb_type(m, t_f64),
  882. lb_type(m, t_f64),
  883. lb_type(m, t_f64),
  884. lb_type(m, t_f64),
  885. };
  886. LLVMStructSetBody(type, fields, 4, false);
  887. return type;
  888. }
  889. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  890. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  891. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  892. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  893. case Basic_string:
  894. {
  895. char const *name = "..string";
  896. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  897. if (type != nullptr) {
  898. return type;
  899. }
  900. type = LLVMStructCreateNamed(ctx, name);
  901. LLVMTypeRef fields[2] = {
  902. LLVMPointerType(lb_type(m, t_u8), 0),
  903. lb_type(m, t_int),
  904. };
  905. LLVMStructSetBody(type, fields, 2, false);
  906. return type;
  907. }
  908. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  909. case Basic_any:
  910. {
  911. char const *name = "..any";
  912. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  913. if (type != nullptr) {
  914. return type;
  915. }
  916. type = LLVMStructCreateNamed(ctx, name);
  917. LLVMTypeRef fields[2] = {
  918. lb_type(m, t_rawptr),
  919. lb_type(m, t_typeid),
  920. };
  921. LLVMStructSetBody(type, fields, 2, false);
  922. return type;
  923. }
  924. case Basic_typeid: return LLVMIntType(8*cast(unsigned)build_context.word_size);
  925. // Endian Specific Types
  926. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  927. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  928. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  929. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  930. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  931. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  932. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  933. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  934. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  935. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  936. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  937. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  938. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  939. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  940. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  941. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  942. // Untyped types
  943. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  944. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  945. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  946. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  947. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  948. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  949. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  950. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  951. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  952. }
  953. break;
  954. case Type_Named:
  955. {
  956. Type *base = base_type(type->Named.base);
  957. switch (base->kind) {
  958. case Type_Basic:
  959. return lb_type(m, base);
  960. case Type_Named:
  961. case Type_Generic:
  962. case Type_BitFieldValue:
  963. GB_PANIC("INVALID TYPE");
  964. break;
  965. case Type_Opaque:
  966. return lb_type(m, base->Opaque.elem);
  967. case Type_Pointer:
  968. case Type_Array:
  969. case Type_EnumeratedArray:
  970. case Type_Slice:
  971. case Type_DynamicArray:
  972. case Type_Map:
  973. case Type_Enum:
  974. case Type_BitSet:
  975. case Type_SimdVector:
  976. return lb_type(m, base);
  977. // TODO(bill): Deal with this correctly. Can this be named?
  978. case Type_Proc:
  979. return lb_type(m, base);
  980. case Type_Tuple:
  981. return lb_type(m, base);
  982. }
  983. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  984. if (found) {
  985. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  986. if (kind == LLVMStructTypeKind) {
  987. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  988. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  989. if (llvm_type != nullptr) {
  990. return llvm_type;
  991. }
  992. llvm_type = LLVMStructCreateNamed(ctx, name);
  993. map_set(&m->types, hash_type(type), llvm_type);
  994. lb_clone_struct_type(llvm_type, *found);
  995. return llvm_type;
  996. }
  997. }
  998. switch (base->kind) {
  999. case Type_Struct:
  1000. case Type_Union:
  1001. case Type_BitField:
  1002. {
  1003. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1004. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1005. if (llvm_type != nullptr) {
  1006. return llvm_type;
  1007. }
  1008. llvm_type = LLVMStructCreateNamed(ctx, name);
  1009. map_set(&m->types, hash_type(type), llvm_type);
  1010. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1011. return llvm_type;
  1012. }
  1013. }
  1014. return lb_type(m, base);
  1015. }
  1016. case Type_Pointer:
  1017. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1018. case Type_Opaque:
  1019. return lb_type(m, base_type(type));
  1020. case Type_Array:
  1021. return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1022. case Type_EnumeratedArray:
  1023. return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1024. case Type_Slice:
  1025. {
  1026. LLVMTypeRef fields[2] = {
  1027. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1028. lb_type(m, t_int), // len
  1029. };
  1030. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1031. }
  1032. break;
  1033. case Type_DynamicArray:
  1034. {
  1035. LLVMTypeRef fields[4] = {
  1036. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1037. lb_type(m, t_int), // len
  1038. lb_type(m, t_int), // cap
  1039. lb_type(m, t_allocator), // allocator
  1040. };
  1041. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1042. }
  1043. break;
  1044. case Type_Map:
  1045. return lb_type(m, type->Map.internal_type);
  1046. case Type_Struct:
  1047. {
  1048. if (type->Struct.is_raw_union) {
  1049. unsigned field_count = 2;
  1050. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1051. i64 alignment = type_align_of(type);
  1052. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1053. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1054. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1055. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1056. }
  1057. isize offset = 0;
  1058. if (type->Struct.custom_align > 0) {
  1059. offset = 1;
  1060. }
  1061. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1062. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1063. GB_ASSERT(fields != nullptr);
  1064. defer (gb_free(heap_allocator(), fields));
  1065. for_array(i, type->Struct.fields) {
  1066. Entity *field = type->Struct.fields[i];
  1067. fields[i+offset] = lb_type(m, field->type);
  1068. }
  1069. if (type->Struct.custom_align > 0) {
  1070. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1071. }
  1072. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1073. }
  1074. break;
  1075. case Type_Union:
  1076. if (type->Union.variants.count == 0) {
  1077. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1078. } else {
  1079. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1080. // LLVM takes the first element's alignment as the entire alignment (like C)
  1081. i64 align = type_align_of(type);
  1082. i64 size = type_size_of(type);
  1083. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1084. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1085. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1086. }
  1087. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1088. LLVMTypeRef fields[3] = {};
  1089. unsigned field_count = 1;
  1090. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1091. if (is_type_union_maybe_pointer(type)) {
  1092. field_count += 1;
  1093. fields[1] = lb_type(m, type->Union.variants[0]);
  1094. } else {
  1095. field_count += 2;
  1096. if (block_size == align) {
  1097. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1098. } else {
  1099. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1100. }
  1101. fields[2] = lb_type(m, union_tag_type(type));
  1102. }
  1103. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1104. }
  1105. break;
  1106. case Type_Enum:
  1107. return lb_type(m, base_enum_type(type));
  1108. case Type_Tuple:
  1109. if (type->Tuple.variables.count == 1) {
  1110. return lb_type(m, type->Tuple.variables[0]->type);
  1111. } else {
  1112. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1113. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1114. defer (gb_free(heap_allocator(), fields));
  1115. for_array(i, type->Tuple.variables) {
  1116. Entity *field = type->Tuple.variables[i];
  1117. fields[i] = lb_type(m, field->type);
  1118. }
  1119. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1120. }
  1121. case Type_Proc:
  1122. {
  1123. set_procedure_abi_types(heap_allocator(), type);
  1124. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1125. if (type->Proc.return_by_pointer) {
  1126. // Void
  1127. } else if (type->Proc.abi_compat_result_type != nullptr) {
  1128. return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1129. }
  1130. isize extra_param_count = 0;
  1131. if (type->Proc.return_by_pointer) {
  1132. extra_param_count += 1;
  1133. }
  1134. if (type->Proc.calling_convention == ProcCC_Odin) {
  1135. extra_param_count += 1;
  1136. }
  1137. isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1138. auto param_types = array_make<LLVMTypeRef>(heap_allocator(), 0, param_count);
  1139. defer (array_free(&param_types));
  1140. if (type->Proc.return_by_pointer) {
  1141. array_add(&param_types, LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0));
  1142. }
  1143. for_array(i, type->Proc.abi_compat_params) {
  1144. Type *param = type->Proc.abi_compat_params[i];
  1145. if (param == nullptr) {
  1146. continue;
  1147. }
  1148. if (type->Proc.params->Tuple.variables[i]->flags & EntityFlag_CVarArg) {
  1149. GB_ASSERT(i+1 == type->Proc.abi_compat_params.count);
  1150. break;
  1151. }
  1152. if (is_type_tuple(param)) {
  1153. param = base_type(param);
  1154. for_array(j, param->Tuple.variables) {
  1155. Entity *v = param->Tuple.variables[j];
  1156. if (v->kind != Entity_Variable) {
  1157. // Sanity check
  1158. continue;
  1159. }
  1160. array_add(&param_types, lb_type(m, v->type));
  1161. }
  1162. } else {
  1163. array_add(&param_types, lb_type(m, param));
  1164. }
  1165. }
  1166. if (type->Proc.calling_convention == ProcCC_Odin) {
  1167. array_add(&param_types, lb_type(m, t_context_ptr));
  1168. }
  1169. LLVMTypeRef t = LLVMFunctionType(return_type, param_types.data, cast(unsigned)param_types.count, type->Proc.c_vararg);
  1170. return LLVMPointerType(t, 0);
  1171. }
  1172. break;
  1173. case Type_BitFieldValue:
  1174. return LLVMIntType(type->BitFieldValue.bits);
  1175. case Type_BitField:
  1176. {
  1177. LLVMTypeRef internal_type = nullptr;
  1178. {
  1179. GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1180. unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1181. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1182. defer (gb_free(heap_allocator(), fields));
  1183. for_array(i, type->BitField.sizes) {
  1184. u32 size = type->BitField.sizes[i];
  1185. fields[i] = LLVMIntType(size);
  1186. }
  1187. internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1188. }
  1189. unsigned field_count = 2;
  1190. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1191. i64 alignment = 1;
  1192. if (type->BitField.custom_align > 0) {
  1193. alignment = type->BitField.custom_align;
  1194. }
  1195. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1196. fields[1] = internal_type;
  1197. return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1198. }
  1199. break;
  1200. case Type_BitSet:
  1201. return LLVMIntType(8*cast(unsigned)type_size_of(type));
  1202. case Type_SimdVector:
  1203. if (type->SimdVector.is_x86_mmx) {
  1204. return LLVMX86MMXTypeInContext(ctx);
  1205. }
  1206. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1207. case Type_RelativePointer:
  1208. return lb_type_internal(m, type->RelativePointer.base_integer);
  1209. case Type_RelativeSlice:
  1210. {
  1211. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1212. unsigned field_count = 2;
  1213. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1214. fields[0] = base_integer;
  1215. fields[1] = base_integer;
  1216. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1217. }
  1218. }
  1219. GB_PANIC("Invalid type %s", type_to_string(type));
  1220. return LLVMInt32TypeInContext(ctx);
  1221. }
  1222. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1223. type = default_type(type);
  1224. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1225. if (found) {
  1226. return *found;
  1227. }
  1228. LLVMTypeRef llvm_type = lb_type_internal(m, type);
  1229. map_set(&m->types, hash_type(type), llvm_type);
  1230. return llvm_type;
  1231. }
  1232. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1233. Type *original_type = type;
  1234. LLVMContextRef ctx = m->ctx;
  1235. i64 size = type_size_of(type); // Check size
  1236. GB_ASSERT(type != t_invalid);
  1237. switch (type->kind) {
  1238. case Type_Basic:
  1239. switch (type->Basic.kind) {
  1240. case Basic_llvm_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "llvm bool", 9, 1, 0, LLVMDIFlagZero);
  1241. case Basic_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "bool", 4, 8, 0, LLVMDIFlagZero);
  1242. case Basic_b8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b8", 2, 8, 0, LLVMDIFlagZero);
  1243. case Basic_b16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b16", 3, 16, 0, LLVMDIFlagZero);
  1244. case Basic_b32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b32", 3, 32, 0, LLVMDIFlagZero);
  1245. case Basic_b64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b64", 3, 64, 0, LLVMDIFlagZero);
  1246. case Basic_i8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i8", 2, 8, 0, LLVMDIFlagZero);
  1247. case Basic_u8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u8", 2, 8, 0, LLVMDIFlagZero);
  1248. case Basic_i16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16", 3, 16, 0, LLVMDIFlagZero);
  1249. case Basic_u16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16", 3, 16, 0, LLVMDIFlagZero);
  1250. case Basic_i32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32", 3, 32, 0, LLVMDIFlagZero);
  1251. case Basic_u32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32", 3, 32, 0, LLVMDIFlagZero);
  1252. case Basic_i64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64", 3, 64, 0, LLVMDIFlagZero);
  1253. case Basic_u64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64", 3, 64, 0, LLVMDIFlagZero);
  1254. case Basic_i128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128", 4, 128, 0, LLVMDIFlagZero);
  1255. case Basic_u128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128", 4, 128, 0, LLVMDIFlagZero);
  1256. case Basic_rune: return LLVMDIBuilderCreateBasicType(m->debug_builder, "rune", 4, 32, 0, LLVMDIFlagZero);
  1257. // Basic_f16,
  1258. case Basic_f32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32", 3, 32, 0, LLVMDIFlagZero);
  1259. case Basic_f64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64", 3, 64, 0, LLVMDIFlagZero);
  1260. // Basic_complex32,
  1261. case Basic_complex64:
  1262. {
  1263. return nullptr;
  1264. // char const *name = "..complex64";
  1265. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1266. // if (type != nullptr) {
  1267. // return type;
  1268. // }
  1269. // type = LLVMStructCreateNamed(ctx, name);
  1270. // LLVMTypeRef fields[2] = {
  1271. // lb_type(m, t_f32),
  1272. // lb_type(m, t_f32),
  1273. // };
  1274. // LLVMStructSetBody(type, fields, 2, false);
  1275. // return type;
  1276. }
  1277. case Basic_complex128:
  1278. {
  1279. return nullptr;
  1280. // char const *name = "..complex128";
  1281. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1282. // if (type != nullptr) {
  1283. // return type;
  1284. // }
  1285. // type = LLVMStructCreateNamed(ctx, name);
  1286. // LLVMTypeRef fields[2] = {
  1287. // lb_type(m, t_f64),
  1288. // lb_type(m, t_f64),
  1289. // };
  1290. // LLVMStructSetBody(type, fields, 2, false);
  1291. // return type;
  1292. }
  1293. case Basic_quaternion128:
  1294. {
  1295. return nullptr;
  1296. // char const *name = "..quaternion128";
  1297. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1298. // if (type != nullptr) {
  1299. // return type;
  1300. // }
  1301. // type = LLVMStructCreateNamed(ctx, name);
  1302. // LLVMTypeRef fields[4] = {
  1303. // lb_type(m, t_f32),
  1304. // lb_type(m, t_f32),
  1305. // lb_type(m, t_f32),
  1306. // lb_type(m, t_f32),
  1307. // };
  1308. // LLVMStructSetBody(type, fields, 4, false);
  1309. // return type;
  1310. }
  1311. case Basic_quaternion256:
  1312. {
  1313. return nullptr;
  1314. // char const *name = "..quaternion256";
  1315. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1316. // if (type != nullptr) {
  1317. // return type;
  1318. // }
  1319. // type = LLVMStructCreateNamed(ctx, name);
  1320. // LLVMTypeRef fields[4] = {
  1321. // lb_type(m, t_f64),
  1322. // lb_type(m, t_f64),
  1323. // lb_type(m, t_f64),
  1324. // lb_type(m, t_f64),
  1325. // };
  1326. // LLVMStructSetBody(type, fields, 4, false);
  1327. // return type;
  1328. }
  1329. case Basic_int: return LLVMDIBuilderCreateBasicType(m->debug_builder, "int", 3, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1330. case Basic_uint: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uint", 4, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1331. case Basic_uintptr: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uintptr", 7, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1332. case Basic_rawptr:
  1333. return nullptr;
  1334. // return LLVMPointerType(LLVMInt8Type(), 0);
  1335. case Basic_string:
  1336. {
  1337. return nullptr;
  1338. // char const *name = "..string";
  1339. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1340. // if (type != nullptr) {
  1341. // return type;
  1342. // }
  1343. // type = LLVMStructCreateNamed(ctx, name);
  1344. // LLVMTypeRef fields[2] = {
  1345. // LLVMPointerType(lb_type(m, t_u8), 0),
  1346. // lb_type(m, t_int),
  1347. // };
  1348. // LLVMStructSetBody(type, fields, 2, false);
  1349. // return type;
  1350. }
  1351. case Basic_cstring:
  1352. return nullptr;
  1353. // return LLVMPointerType(LLVMInt8Type(), 0);
  1354. case Basic_any:
  1355. {
  1356. return nullptr;
  1357. // char const *name = "..any";
  1358. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1359. // if (type != nullptr) {
  1360. // return type;
  1361. // }
  1362. // type = LLVMStructCreateNamed(ctx, name);
  1363. // LLVMTypeRef fields[2] = {
  1364. // lb_type(m, t_rawptr),
  1365. // lb_type(m, t_typeid),
  1366. // };
  1367. // LLVMStructSetBody(type, fields, 2, false);
  1368. // return type;
  1369. }
  1370. case Basic_typeid: return LLVMDIBuilderCreateBasicType(m->debug_builder, "typeid", 6, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1371. // Endian Specific Types
  1372. case Basic_i16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1373. case Basic_u16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1374. case Basic_i32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1375. case Basic_u32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1376. case Basic_i64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1377. case Basic_u64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1378. case Basic_i128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1379. case Basic_u128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1380. case Basic_i16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1381. case Basic_u16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1382. case Basic_i32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1383. case Basic_u32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1384. case Basic_i64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1385. case Basic_u64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1386. case Basic_i128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1387. case Basic_u128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1388. // Untyped types
  1389. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1390. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1391. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1392. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1393. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1394. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1395. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1396. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1397. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1398. }
  1399. break;
  1400. case Type_Named:
  1401. {
  1402. return nullptr;
  1403. // Type *base = base_type(type->Named.base);
  1404. // switch (base->kind) {
  1405. // case Type_Basic:
  1406. // return lb_type(m, base);
  1407. // case Type_Named:
  1408. // case Type_Generic:
  1409. // case Type_BitFieldValue:
  1410. // GB_PANIC("INVALID TYPE");
  1411. // break;
  1412. // case Type_Opaque:
  1413. // return lb_type(m, base->Opaque.elem);
  1414. // case Type_Pointer:
  1415. // case Type_Array:
  1416. // case Type_EnumeratedArray:
  1417. // case Type_Slice:
  1418. // case Type_DynamicArray:
  1419. // case Type_Map:
  1420. // case Type_Enum:
  1421. // case Type_BitSet:
  1422. // case Type_SimdVector:
  1423. // return lb_type(m, base);
  1424. // // TODO(bill): Deal with this correctly. Can this be named?
  1425. // case Type_Proc:
  1426. // return lb_type(m, base);
  1427. // case Type_Tuple:
  1428. // return lb_type(m, base);
  1429. // }
  1430. // LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1431. // if (found) {
  1432. // LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1433. // if (kind == LLVMStructTypeKind) {
  1434. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1435. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1436. // if (llvm_type != nullptr) {
  1437. // return llvm_type;
  1438. // }
  1439. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1440. // map_set(&m->types, hash_type(type), llvm_type);
  1441. // lb_clone_struct_type(llvm_type, *found);
  1442. // return llvm_type;
  1443. // }
  1444. // }
  1445. // switch (base->kind) {
  1446. // case Type_Struct:
  1447. // case Type_Union:
  1448. // case Type_BitField:
  1449. // {
  1450. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1451. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1452. // if (llvm_type != nullptr) {
  1453. // return llvm_type;
  1454. // }
  1455. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1456. // map_set(&m->types, hash_type(type), llvm_type);
  1457. // lb_clone_struct_type(llvm_type, lb_type(m, base));
  1458. // return llvm_type;
  1459. // }
  1460. // }
  1461. // return lb_type(m, base);
  1462. }
  1463. case Type_Pointer:
  1464. return nullptr;
  1465. // return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1466. case Type_Opaque:
  1467. return nullptr;
  1468. // return lb_type(m, base_type(type));
  1469. case Type_Array:
  1470. return nullptr;
  1471. // return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1472. case Type_EnumeratedArray:
  1473. return nullptr;
  1474. // return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1475. case Type_Slice:
  1476. {
  1477. return nullptr;
  1478. // LLVMTypeRef fields[2] = {
  1479. // LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1480. // lb_type(m, t_int), // len
  1481. // };
  1482. // return LLVMStructTypeInContext(ctx, fields, 2, false);
  1483. }
  1484. break;
  1485. case Type_DynamicArray:
  1486. {
  1487. return nullptr;
  1488. // LLVMTypeRef fields[4] = {
  1489. // LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1490. // lb_type(m, t_int), // len
  1491. // lb_type(m, t_int), // cap
  1492. // lb_type(m, t_allocator), // allocator
  1493. // };
  1494. // return LLVMStructTypeInContext(ctx, fields, 4, false);
  1495. }
  1496. break;
  1497. case Type_Map:
  1498. return nullptr;
  1499. // return lb_type(m, type->Map.internal_type);
  1500. case Type_Struct:
  1501. {
  1502. return nullptr;
  1503. // if (type->Struct.is_raw_union) {
  1504. // unsigned field_count = 2;
  1505. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1506. // i64 alignment = type_align_of(type);
  1507. // unsigned size_of_union = cast(unsigned)type_size_of(type);
  1508. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1509. // fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1510. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1511. // }
  1512. // isize offset = 0;
  1513. // if (type->Struct.custom_align > 0) {
  1514. // offset = 1;
  1515. // }
  1516. // unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1517. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1518. // GB_ASSERT(fields != nullptr);
  1519. // defer (gb_free(heap_allocator(), fields));
  1520. // for_array(i, type->Struct.fields) {
  1521. // Entity *field = type->Struct.fields[i];
  1522. // fields[i+offset] = lb_type(m, field->type);
  1523. // }
  1524. // if (type->Struct.custom_align > 0) {
  1525. // fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1526. // }
  1527. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1528. }
  1529. break;
  1530. case Type_Union:
  1531. return nullptr;
  1532. // if (type->Union.variants.count == 0) {
  1533. // return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1534. // } else {
  1535. // // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1536. // // LLVM takes the first element's alignment as the entire alignment (like C)
  1537. // i64 align = type_align_of(type);
  1538. // i64 size = type_size_of(type);
  1539. // if (is_type_union_maybe_pointer_original_alignment(type)) {
  1540. // LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1541. // return LLVMStructTypeInContext(ctx, fields, 1, false);
  1542. // }
  1543. // unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1544. // LLVMTypeRef fields[3] = {};
  1545. // unsigned field_count = 1;
  1546. // fields[0] = lb_alignment_prefix_type_hack(m, align);
  1547. // if (is_type_union_maybe_pointer(type)) {
  1548. // field_count += 1;
  1549. // fields[1] = lb_type(m, type->Union.variants[0]);
  1550. // } else {
  1551. // field_count += 2;
  1552. // if (block_size == align) {
  1553. // fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1554. // } else {
  1555. // fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1556. // }
  1557. // fields[2] = lb_type(m, union_tag_type(type));
  1558. // }
  1559. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1560. // }
  1561. // break;
  1562. case Type_Enum:
  1563. return nullptr;
  1564. // return lb_type(m, base_enum_type(type));
  1565. case Type_Tuple:
  1566. return nullptr;
  1567. // if (type->Tuple.variables.count == 1) {
  1568. // return lb_type(m, type->Tuple.variables[0]->type);
  1569. // } else {
  1570. // unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1571. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1572. // defer (gb_free(heap_allocator(), fields));
  1573. // for_array(i, type->Tuple.variables) {
  1574. // Entity *field = type->Tuple.variables[i];
  1575. // fields[i] = lb_type(m, field->type);
  1576. // }
  1577. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1578. // }
  1579. case Type_Proc:
  1580. {
  1581. return nullptr;
  1582. // set_procedure_abi_types(heap_allocator(), type);
  1583. // LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1584. // isize offset = 0;
  1585. // if (type->Proc.return_by_pointer) {
  1586. // offset = 1;
  1587. // } else if (type->Proc.abi_compat_result_type != nullptr) {
  1588. // return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1589. // }
  1590. // isize extra_param_count = offset;
  1591. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1592. // extra_param_count += 1;
  1593. // }
  1594. // isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1595. // LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1596. // defer (gb_free(heap_allocator(), param_types));
  1597. // isize param_index = offset;
  1598. // for_array(i, type->Proc.abi_compat_params) {
  1599. // Type *param = type->Proc.abi_compat_params[i];
  1600. // if (param == nullptr) {
  1601. // continue;
  1602. // }
  1603. // param_types[param_index++] = lb_type(m, param);
  1604. // }
  1605. // if (type->Proc.return_by_pointer) {
  1606. // param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  1607. // }
  1608. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1609. // param_types[param_index++] = lb_type(m, t_context_ptr);
  1610. // }
  1611. // LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  1612. // return LLVMPointerType(t, 0);
  1613. }
  1614. break;
  1615. case Type_BitFieldValue:
  1616. return nullptr;
  1617. // return LLVMIntType(type->BitFieldValue.bits);
  1618. case Type_BitField:
  1619. {
  1620. return nullptr;
  1621. // LLVMTypeRef internal_type = nullptr;
  1622. // {
  1623. // GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1624. // unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1625. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1626. // defer (gb_free(heap_allocator(), fields));
  1627. // for_array(i, type->BitField.sizes) {
  1628. // u32 size = type->BitField.sizes[i];
  1629. // fields[i] = LLVMIntType(size);
  1630. // }
  1631. // internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1632. // }
  1633. // unsigned field_count = 2;
  1634. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1635. // i64 alignment = 1;
  1636. // if (type->BitField.custom_align > 0) {
  1637. // alignment = type->BitField.custom_align;
  1638. // }
  1639. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1640. // fields[1] = internal_type;
  1641. // return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1642. }
  1643. break;
  1644. case Type_BitSet:
  1645. return nullptr;
  1646. // return LLVMIntType(8*cast(unsigned)type_size_of(type));
  1647. case Type_SimdVector:
  1648. return nullptr;
  1649. // if (type->SimdVector.is_x86_mmx) {
  1650. // return LLVMX86MMXTypeInContext(ctx);
  1651. // }
  1652. // return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1653. }
  1654. GB_PANIC("Invalid type %s", type_to_string(type));
  1655. return nullptr;
  1656. }
  1657. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1658. LLVMTypeRef t = lb_type(m, type);
  1659. LLVMMetadataRef *found = map_get(&m->debug_values, hash_pointer(t));
  1660. if (found != nullptr) {
  1661. return *found;
  1662. }
  1663. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1664. map_set(&m->debug_values, hash_pointer(t), dt);
  1665. return dt;
  1666. }
  1667. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1668. if (e != nullptr) {
  1669. map_set(&m->values, hash_entity(e), val);
  1670. }
  1671. }
  1672. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1673. if (name.len > 0) {
  1674. string_map_set(&m->members, name, val);
  1675. }
  1676. }
  1677. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1678. string_map_set(&m->members, key, val);
  1679. }
  1680. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1681. if (p->entity != nullptr) {
  1682. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1683. }
  1684. string_map_set(&m->procedures, p->name, p);
  1685. }
  1686. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  1687. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  1688. LLVMValueRef values[2] = {
  1689. str_elem.value,
  1690. str_len.value,
  1691. };
  1692. lbValue res = {};
  1693. res.type = t_string;
  1694. res.value = LLVMConstNamedStruct(lb_type(p->module, t_string), values, gb_count_of(values));
  1695. return res;
  1696. } else {
  1697. lbAddr res = lb_add_local_generated(p, t_string, false);
  1698. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  1699. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  1700. return lb_addr_load(p, res);
  1701. }
  1702. }
  1703. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1704. unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name));
  1705. GB_ASSERT(kind != 0);
  1706. return LLVMCreateEnumAttribute(ctx, kind, value);
  1707. }
  1708. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1709. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1710. GB_ASSERT(attr != nullptr);
  1711. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1712. }
  1713. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1714. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  1715. }
  1716. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  1717. GB_ASSERT(entity != nullptr);
  1718. String link_name = lb_get_entity_name(m, entity);
  1719. {
  1720. StringHashKey key = string_hash_string(link_name);
  1721. lbValue *found = string_map_get(&m->members, key);
  1722. if (found) {
  1723. lb_add_entity(m, entity, *found);
  1724. lbProcedure **p_found = string_map_get(&m->procedures, key);
  1725. GB_ASSERT(p_found != nullptr);
  1726. return *p_found;
  1727. }
  1728. }
  1729. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  1730. p->module = m;
  1731. entity->code_gen_module = m;
  1732. entity->code_gen_procedure = p;
  1733. p->entity = entity;
  1734. p->name = link_name;
  1735. DeclInfo *decl = entity->decl_info;
  1736. ast_node(pl, ProcLit, decl->proc_lit);
  1737. Type *pt = base_type(entity->type);
  1738. GB_ASSERT(pt->kind == Type_Proc);
  1739. set_procedure_abi_types(heap_allocator(), entity->type);
  1740. p->type = entity->type;
  1741. p->type_expr = decl->type_expr;
  1742. p->body = pl->body;
  1743. p->tags = pt->Proc.tags;
  1744. p->inlining = ProcInlining_none;
  1745. p->is_foreign = entity->Procedure.is_foreign;
  1746. p->is_export = entity->Procedure.is_export;
  1747. p->is_entry_point = false;
  1748. gbAllocator a = heap_allocator();
  1749. p->children.allocator = a;
  1750. p->params.allocator = a;
  1751. p->defer_stmts.allocator = a;
  1752. p->blocks.allocator = a;
  1753. p->branch_blocks.allocator = a;
  1754. p->context_stack.allocator = a;
  1755. if (p->is_foreign) {
  1756. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  1757. }
  1758. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  1759. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1760. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1761. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1762. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1763. // TODO(bill): Clean up this logic
  1764. if (build_context.metrics.os != TargetOs_js) {
  1765. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1766. }
  1767. LLVMSetFunctionCallConv(p->value, cc_kind);
  1768. lbValue proc_value = {p->value, p->type};
  1769. lb_add_entity(m, entity, proc_value);
  1770. lb_add_member(m, p->name, proc_value);
  1771. lb_add_procedure_value(m, p);
  1772. if (p->is_export) {
  1773. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  1774. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  1775. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  1776. if (build_context.metrics.os == TargetOs_js) {
  1777. char const *export_name = alloc_cstring(heap_allocator(), p->name);
  1778. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  1779. }
  1780. }
  1781. if (p->is_foreign) {
  1782. if (build_context.metrics.os == TargetOs_js) {
  1783. char const *import_name = alloc_cstring(heap_allocator(), p->name);
  1784. char const *module_name = "env";
  1785. if (entity->Procedure.foreign_library != nullptr) {
  1786. Entity *foreign_library = entity->Procedure.foreign_library;
  1787. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1788. if (foreign_library->LibraryName.paths.count > 0) {
  1789. module_name = alloc_cstring(heap_allocator(), foreign_library->LibraryName.paths[0]);
  1790. }
  1791. }
  1792. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  1793. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  1794. }
  1795. }
  1796. // NOTE(bill): offset==0 is the return value
  1797. isize offset = 1;
  1798. if (pt->Proc.return_by_pointer) {
  1799. lb_add_proc_attribute_at_index(p, 1, "sret");
  1800. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1801. offset = 2;
  1802. }
  1803. isize parameter_index = 0;
  1804. if (pt->Proc.param_count) {
  1805. TypeTuple *params = &pt->Proc.params->Tuple;
  1806. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1807. Entity *e = params->variables[i];
  1808. Type *original_type = e->type;
  1809. Type *abi_type = pt->Proc.abi_compat_params[i];
  1810. if (e->kind != Entity_Variable) continue;
  1811. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1812. continue;
  1813. }
  1814. if (is_type_tuple(abi_type)) {
  1815. for_array(j, abi_type->Tuple.variables) {
  1816. Type *tft = abi_type->Tuple.variables[j]->type;
  1817. if (e->flags&EntityFlag_NoAlias) {
  1818. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1819. }
  1820. }
  1821. parameter_index += abi_type->Tuple.variables.count;
  1822. } else {
  1823. if (e->flags&EntityFlag_NoAlias) {
  1824. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1825. }
  1826. parameter_index += 1;
  1827. }
  1828. }
  1829. }
  1830. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1831. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1832. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1833. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1834. }
  1835. { // Debug Information
  1836. unsigned line = cast(unsigned)entity->token.pos.line;
  1837. LLVMMetadataRef file = nullptr;
  1838. if (entity->file != nullptr) {
  1839. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1840. }
  1841. LLVMMetadataRef scope = nullptr;
  1842. LLVMMetadataRef type = nullptr;
  1843. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1844. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1845. cast(char const *)entity->token.string.text, entity->token.string.len,
  1846. cast(char const *)p->name.text, p->name.len,
  1847. file, line, type,
  1848. true, p->body == nullptr,
  1849. line, LLVMDIFlagZero, false
  1850. );
  1851. GB_ASSERT(res != nullptr);
  1852. map_set(&m->debug_values, hash_pointer(p), res);
  1853. }
  1854. return p;
  1855. }
  1856. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1857. {
  1858. lbValue *found = string_map_get(&m->members, link_name);
  1859. GB_ASSERT(found == nullptr);
  1860. }
  1861. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  1862. p->module = m;
  1863. p->name = link_name;
  1864. p->type = type;
  1865. p->type_expr = nullptr;
  1866. p->body = nullptr;
  1867. p->tags = 0;
  1868. p->inlining = ProcInlining_none;
  1869. p->is_foreign = false;
  1870. p->is_export = false;
  1871. p->is_entry_point = false;
  1872. gbAllocator a = heap_allocator();
  1873. p->children.allocator = a;
  1874. p->params.allocator = a;
  1875. p->defer_stmts.allocator = a;
  1876. p->blocks.allocator = a;
  1877. p->branch_blocks.allocator = a;
  1878. p->context_stack.allocator = a;
  1879. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  1880. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1881. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1882. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1883. Type *pt = p->type;
  1884. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1885. // TODO(bill): Clean up this logic
  1886. if (build_context.metrics.os != TargetOs_js) {
  1887. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1888. }
  1889. LLVMSetFunctionCallConv(p->value, cc_kind);
  1890. lbValue proc_value = {p->value, p->type};
  1891. lb_add_member(m, p->name, proc_value);
  1892. lb_add_procedure_value(m, p);
  1893. // NOTE(bill): offset==0 is the return value
  1894. isize offset = 1;
  1895. if (pt->Proc.return_by_pointer) {
  1896. lb_add_proc_attribute_at_index(p, 1, "sret");
  1897. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1898. offset = 2;
  1899. }
  1900. isize parameter_index = 0;
  1901. if (pt->Proc.param_count) {
  1902. TypeTuple *params = &pt->Proc.params->Tuple;
  1903. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1904. Entity *e = params->variables[i];
  1905. Type *original_type = e->type;
  1906. Type *abi_type = pt->Proc.abi_compat_params[i];
  1907. if (e->kind != Entity_Variable) continue;
  1908. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1909. continue;
  1910. }
  1911. if (is_type_tuple(abi_type)) {
  1912. for_array(j, abi_type->Tuple.variables) {
  1913. Type *tft = abi_type->Tuple.variables[j]->type;
  1914. if (e->flags&EntityFlag_NoAlias) {
  1915. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1916. }
  1917. }
  1918. parameter_index += abi_type->Tuple.variables.count;
  1919. } else {
  1920. if (e->flags&EntityFlag_NoAlias) {
  1921. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1922. }
  1923. parameter_index += 1;
  1924. }
  1925. }
  1926. }
  1927. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1928. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1929. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1930. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1931. }
  1932. return p;
  1933. }
  1934. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  1935. lbParamPasskind kind = lbParamPass_Value;
  1936. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  1937. if (is_type_pointer(abi_type)) {
  1938. GB_ASSERT(e->kind == Entity_Variable);
  1939. Type *av = core_type(type_deref(abi_type));
  1940. if (are_types_identical(av, core_type(e->type))) {
  1941. kind = lbParamPass_Pointer;
  1942. if (e->flags&EntityFlag_Value) {
  1943. kind = lbParamPass_ConstRef;
  1944. }
  1945. } else {
  1946. kind = lbParamPass_BitCast;
  1947. }
  1948. } else if (is_type_integer(abi_type)) {
  1949. kind = lbParamPass_Integer;
  1950. } else if (abi_type == t_llvm_bool) {
  1951. kind = lbParamPass_Value;
  1952. } else if (is_type_boolean(abi_type)) {
  1953. kind = lbParamPass_Integer;
  1954. } else if (is_type_simd_vector(abi_type)) {
  1955. kind = lbParamPass_BitCast;
  1956. } else if (is_type_float(abi_type)) {
  1957. kind = lbParamPass_BitCast;
  1958. } else if (is_type_tuple(abi_type)) {
  1959. kind = lbParamPass_Tuple;
  1960. } else if (is_type_proc(abi_type)) {
  1961. kind = lbParamPass_Value;
  1962. } else {
  1963. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  1964. }
  1965. }
  1966. if (kind_) *kind_ = kind;
  1967. lbValue res = {};
  1968. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  1969. res.type = abi_type;
  1970. return res;
  1971. }
  1972. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1973. lbParamPasskind kind = lbParamPass_Value;
  1974. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  1975. array_add(&p->params, v);
  1976. lbValue res = {};
  1977. switch (kind) {
  1978. case lbParamPass_Value: {
  1979. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1980. lbValue x = v;
  1981. if (abi_type == t_llvm_bool) {
  1982. x = lb_emit_conv(p, x, t_bool);
  1983. }
  1984. lb_addr_store(p, l, x);
  1985. return x;
  1986. }
  1987. case lbParamPass_Pointer:
  1988. lb_add_entity(p->module, e, v);
  1989. return lb_emit_load(p, v);
  1990. case lbParamPass_Integer: {
  1991. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1992. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  1993. lb_emit_store(p, iptr, v);
  1994. return lb_addr_load(p, l);
  1995. }
  1996. case lbParamPass_ConstRef:
  1997. lb_add_entity(p->module, e, v);
  1998. return lb_emit_load(p, v);
  1999. case lbParamPass_BitCast: {
  2000. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2001. lbValue x = lb_emit_transmute(p, v, e->type);
  2002. lb_addr_store(p, l, x);
  2003. return x;
  2004. }
  2005. case lbParamPass_Tuple: {
  2006. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2007. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2008. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2009. if (abi_type->Tuple.variables.count > 0) {
  2010. array_pop(&p->params);
  2011. }
  2012. for_array(i, abi_type->Tuple.variables) {
  2013. Type *t = abi_type->Tuple.variables[i]->type;
  2014. GB_ASSERT(!is_type_tuple(t));
  2015. lbParamPasskind elem_kind = lbParamPass_Value;
  2016. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2017. array_add(&p->params, elem);
  2018. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2019. lb_emit_store(p, dst, elem);
  2020. }
  2021. return lb_addr_load(p, l);
  2022. }
  2023. }
  2024. GB_PANIC("Unreachable");
  2025. return {};
  2026. }
  2027. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2028. GB_ASSERT(b != nullptr);
  2029. if (!b->appended) {
  2030. b->appended = true;
  2031. LLVMAppendExistingBasicBlock(p->value, b->block);
  2032. }
  2033. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2034. p->curr_block = b;
  2035. }
  2036. void lb_begin_procedure_body(lbProcedure *p) {
  2037. DeclInfo *decl = decl_info_of_entity(p->entity);
  2038. if (decl != nullptr) {
  2039. for_array(i, decl->labels) {
  2040. BlockLabel bl = decl->labels[i];
  2041. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2042. array_add(&p->branch_blocks, bb);
  2043. }
  2044. }
  2045. if (p->tags != 0) {
  2046. u64 in = p->tags;
  2047. u64 out = p->module->state_flags;
  2048. if (in & ProcTag_bounds_check) {
  2049. out |= StateFlag_bounds_check;
  2050. out &= ~StateFlag_no_bounds_check;
  2051. } else if (in & ProcTag_no_bounds_check) {
  2052. out |= StateFlag_no_bounds_check;
  2053. out &= ~StateFlag_bounds_check;
  2054. }
  2055. p->module->state_flags = out;
  2056. }
  2057. p->builder = LLVMCreateBuilder();
  2058. p->decl_block = lb_create_block(p, "decls", true);
  2059. p->entry_block = lb_create_block(p, "entry", true);
  2060. lb_start_block(p, p->entry_block);
  2061. GB_ASSERT(p->type != nullptr);
  2062. i32 parameter_index = 0;
  2063. if (p->type->Proc.return_by_pointer) {
  2064. // NOTE(bill): this must be parameter 0
  2065. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2066. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2067. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2068. lbValue return_ptr_value = {};
  2069. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2070. return_ptr_value.type = alloc_type_pointer(p->type->Proc.abi_compat_result_type);
  2071. p->return_ptr = lb_addr(return_ptr_value);
  2072. lb_add_entity(p->module, e, return_ptr_value);
  2073. parameter_index += 1;
  2074. }
  2075. if (p->type->Proc.params != nullptr) {
  2076. TypeTuple *params = &p->type->Proc.params->Tuple;
  2077. auto abi_types = p->type->Proc.abi_compat_params;
  2078. for_array(i, params->variables) {
  2079. Entity *e = params->variables[i];
  2080. if (e->kind != Entity_Variable) {
  2081. continue;
  2082. }
  2083. Type *abi_type = e->type;
  2084. if (abi_types.count > 0) {
  2085. abi_type = abi_types[i];
  2086. }
  2087. if (e->token.string != "") {
  2088. lb_add_param(p, e, nullptr, abi_type, parameter_index);
  2089. }
  2090. if (is_type_tuple(abi_type)) {
  2091. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  2092. } else {
  2093. parameter_index += 1;
  2094. }
  2095. }
  2096. }
  2097. if (p->type->Proc.has_named_results) {
  2098. GB_ASSERT(p->type->Proc.result_count > 0);
  2099. TypeTuple *results = &p->type->Proc.results->Tuple;
  2100. isize result_index = 0;
  2101. for_array(i, results->variables) {
  2102. Entity *e = results->variables[i];
  2103. if (e->kind != Entity_Variable) {
  2104. continue;
  2105. }
  2106. if (e->token.string != "") {
  2107. GB_ASSERT(!is_blank_ident(e->token));
  2108. lbAddr res = lb_add_local(p, e->type, e);
  2109. lbValue c = {};
  2110. switch (e->Variable.param_value.kind) {
  2111. case ParameterValue_Constant:
  2112. c = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  2113. break;
  2114. case ParameterValue_Nil:
  2115. c = lb_const_nil(p->module, e->type);
  2116. break;
  2117. case ParameterValue_Location:
  2118. GB_PANIC("ParameterValue_Location");
  2119. break;
  2120. }
  2121. if (c.value != nullptr) {
  2122. lb_addr_store(p, res, c);
  2123. }
  2124. }
  2125. result_index += 1;
  2126. }
  2127. }
  2128. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2129. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  2130. e->flags |= EntityFlag_NoAlias;
  2131. lbValue param = {};
  2132. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  2133. param.type = e->type;
  2134. lb_add_entity(p->module, e, param);
  2135. lbAddr ctx_addr = {};
  2136. ctx_addr.kind = lbAddr_Context;
  2137. ctx_addr.addr = param;
  2138. lbContextData ctx = {ctx_addr, p->scope_index};
  2139. array_add(&p->context_stack, ctx);
  2140. }
  2141. lb_start_block(p, p->entry_block);
  2142. }
  2143. void lb_end_procedure_body(lbProcedure *p) {
  2144. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2145. LLVMBuildBr(p->builder, p->entry_block->block);
  2146. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2147. if (p->type->Proc.result_count == 0) {
  2148. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2149. if (!lb_is_instr_terminating(instr)) {
  2150. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2151. LLVMBuildRetVoid(p->builder);
  2152. }
  2153. } else {
  2154. if (p->curr_block->preds.count == 0) {
  2155. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2156. if (instr == nullptr) {
  2157. // NOTE(bill): Remove dead trailing block
  2158. LLVMDeleteBasicBlock(p->curr_block->block);
  2159. }
  2160. }
  2161. }
  2162. p->curr_block = nullptr;
  2163. p->module->state_flags = 0;
  2164. }
  2165. void lb_end_procedure(lbProcedure *p) {
  2166. LLVMDisposeBuilder(p->builder);
  2167. }
  2168. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2169. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2170. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2171. array_add(&from->succs, to);
  2172. array_add(&to->preds, from);
  2173. }
  2174. }
  2175. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2176. lbBlock *b = gb_alloc_item(heap_allocator(), lbBlock);
  2177. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2178. b->appended = false;
  2179. if (append) {
  2180. b->appended = true;
  2181. LLVMAppendExistingBasicBlock(p->value, b->block);
  2182. }
  2183. b->scope = p->curr_scope;
  2184. b->scope_index = p->scope_index;
  2185. b->preds.allocator = heap_allocator();
  2186. b->succs.allocator = heap_allocator();
  2187. array_add(&p->blocks, b);
  2188. return b;
  2189. }
  2190. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2191. if (p->curr_block == nullptr) {
  2192. return;
  2193. }
  2194. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2195. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2196. return;
  2197. }
  2198. lb_add_edge(p->curr_block, target_block);
  2199. LLVMBuildBr(p->builder, target_block->block);
  2200. p->curr_block = nullptr;
  2201. }
  2202. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2203. lbBlock *b = p->curr_block;
  2204. if (b == nullptr) {
  2205. return;
  2206. }
  2207. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2208. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2209. return;
  2210. }
  2211. lb_add_edge(b, true_block);
  2212. lb_add_edge(b, false_block);
  2213. LLVMValueRef cv = cond.value;
  2214. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2215. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2216. }
  2217. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2218. GB_ASSERT(cond != nullptr);
  2219. GB_ASSERT(true_block != nullptr);
  2220. GB_ASSERT(false_block != nullptr);
  2221. switch (cond->kind) {
  2222. case_ast_node(pe, ParenExpr, cond);
  2223. return lb_build_cond(p, pe->expr, true_block, false_block);
  2224. case_end;
  2225. case_ast_node(ue, UnaryExpr, cond);
  2226. if (ue->op.kind == Token_Not) {
  2227. return lb_build_cond(p, ue->expr, false_block, true_block);
  2228. }
  2229. case_end;
  2230. case_ast_node(be, BinaryExpr, cond);
  2231. if (be->op.kind == Token_CmpAnd) {
  2232. lbBlock *block = lb_create_block(p, "cmp.and");
  2233. lb_build_cond(p, be->left, block, false_block);
  2234. lb_start_block(p, block);
  2235. return lb_build_cond(p, be->right, true_block, false_block);
  2236. } else if (be->op.kind == Token_CmpOr) {
  2237. lbBlock *block = lb_create_block(p, "cmp.or");
  2238. lb_build_cond(p, be->left, true_block, block);
  2239. lb_start_block(p, block);
  2240. return lb_build_cond(p, be->right, true_block, false_block);
  2241. }
  2242. case_end;
  2243. }
  2244. lbValue v = lb_build_expr(p, cond);
  2245. // v = lb_emit_conv(p, v, t_bool);
  2246. v = lb_emit_conv(p, v, t_llvm_bool);
  2247. lb_emit_if(p, v, true_block, false_block);
  2248. return v;
  2249. }
  2250. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2251. GB_ASSERT(p->decl_block != p->curr_block);
  2252. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2253. char const *name = "";
  2254. if (e != nullptr) {
  2255. // name = alloc_cstring(heap_allocator(), e->token.string);
  2256. }
  2257. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2258. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2259. LLVMSetAlignment(ptr, 16); // TODO(bill): Make this configurable
  2260. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2261. if (zero_init) {
  2262. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2263. }
  2264. lbValue val = {};
  2265. val.value = ptr;
  2266. val.type = alloc_type_pointer(type);
  2267. if (e != nullptr) {
  2268. lb_add_entity(p->module, e, val);
  2269. }
  2270. return lb_addr(val);
  2271. }
  2272. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2273. return lb_add_local(p, type, nullptr, zero_init);
  2274. }
  2275. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2276. GB_ASSERT(pd->body != nullptr);
  2277. lbModule *m = p->module;
  2278. auto *min_dep_set = &m->info->minimum_dependency_set;
  2279. if (ptr_set_exists(min_dep_set, e) == false) {
  2280. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2281. return;
  2282. }
  2283. // NOTE(bill): Generate a new name
  2284. // parent.name-guid
  2285. String original_name = e->token.string;
  2286. String pd_name = original_name;
  2287. if (e->Procedure.link_name.len > 0) {
  2288. pd_name = e->Procedure.link_name;
  2289. }
  2290. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2291. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  2292. i32 guid = cast(i32)p->children.count;
  2293. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2294. String name = make_string(cast(u8 *)name_text, name_len-1);
  2295. set_procedure_abi_types(heap_allocator(), e->type);
  2296. e->Procedure.link_name = name;
  2297. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2298. e->code_gen_procedure = nested_proc;
  2299. lbValue value = {};
  2300. value.value = nested_proc->value;
  2301. value.type = nested_proc->type;
  2302. lb_add_entity(m, e, value);
  2303. array_add(&p->children, nested_proc);
  2304. array_add(&m->procedures_to_generate, nested_proc);
  2305. }
  2306. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2307. if (e == nullptr) {
  2308. return;
  2309. }
  2310. GB_ASSERT(e->kind == Entity_LibraryName);
  2311. GB_ASSERT(e->flags & EntityFlag_Used);
  2312. for_array(i, e->LibraryName.paths) {
  2313. String library_path = e->LibraryName.paths[i];
  2314. if (library_path.len == 0) {
  2315. continue;
  2316. }
  2317. bool ok = true;
  2318. for_array(path_index, m->foreign_library_paths) {
  2319. String path = m->foreign_library_paths[path_index];
  2320. #if defined(GB_SYSTEM_WINDOWS)
  2321. if (str_eq_ignore_case(path, library_path)) {
  2322. #else
  2323. if (str_eq(path, library_path)) {
  2324. #endif
  2325. ok = false;
  2326. break;
  2327. }
  2328. }
  2329. if (ok) {
  2330. array_add(&m->foreign_library_paths, library_path);
  2331. }
  2332. }
  2333. }
  2334. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2335. if (vd == nullptr || vd->is_mutable) {
  2336. return;
  2337. }
  2338. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2339. static i32 global_guid = 0;
  2340. for_array(i, vd->names) {
  2341. Ast *ident = vd->names[i];
  2342. GB_ASSERT(ident->kind == Ast_Ident);
  2343. Entity *e = entity_of_node(ident);
  2344. GB_ASSERT(e != nullptr);
  2345. if (e->kind != Entity_TypeName) {
  2346. continue;
  2347. }
  2348. bool polymorphic_struct = false;
  2349. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2350. Type *bt = base_type(e->type);
  2351. if (bt->kind == Type_Struct) {
  2352. polymorphic_struct = bt->Struct.is_polymorphic;
  2353. }
  2354. }
  2355. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2356. continue;
  2357. }
  2358. if (e->TypeName.ir_mangled_name.len != 0) {
  2359. // NOTE(bill): Already set
  2360. continue;
  2361. }
  2362. lb_set_nested_type_name_ir_mangled_name(e, p);
  2363. }
  2364. for_array(i, vd->names) {
  2365. Ast *ident = vd->names[i];
  2366. GB_ASSERT(ident->kind == Ast_Ident);
  2367. Entity *e = entity_of_node(ident);
  2368. GB_ASSERT(e != nullptr);
  2369. if (e->kind != Entity_Procedure) {
  2370. continue;
  2371. }
  2372. CheckerInfo *info = p->module->info;
  2373. DeclInfo *decl = decl_info_of_entity(e);
  2374. ast_node(pl, ProcLit, decl->proc_lit);
  2375. if (pl->body != nullptr) {
  2376. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2377. if (found) {
  2378. auto procs = *found;
  2379. for_array(i, procs) {
  2380. Entity *e = procs[i];
  2381. if (!ptr_set_exists(min_dep_set, e)) {
  2382. continue;
  2383. }
  2384. DeclInfo *d = decl_info_of_entity(e);
  2385. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2386. }
  2387. } else {
  2388. lb_build_nested_proc(p, pl, e);
  2389. }
  2390. } else {
  2391. // FFI - Foreign function interace
  2392. String original_name = e->token.string;
  2393. String name = original_name;
  2394. if (e->Procedure.is_foreign) {
  2395. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2396. }
  2397. if (e->Procedure.link_name.len > 0) {
  2398. name = e->Procedure.link_name;
  2399. }
  2400. lbValue *prev_value = string_map_get(&p->module->members, name);
  2401. if (prev_value != nullptr) {
  2402. // NOTE(bill): Don't do mutliple declarations in the IR
  2403. return;
  2404. }
  2405. set_procedure_abi_types(heap_allocator(), e->type);
  2406. e->Procedure.link_name = name;
  2407. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2408. lbValue value = {};
  2409. value.value = nested_proc->value;
  2410. value.type = nested_proc->type;
  2411. array_add(&p->module->procedures_to_generate, nested_proc);
  2412. if (p != nullptr) {
  2413. array_add(&p->children, nested_proc);
  2414. } else {
  2415. string_map_set(&p->module->members, name, value);
  2416. }
  2417. }
  2418. }
  2419. }
  2420. void lb_build_stmt_list(lbProcedure *p, Array<Ast *> const &stmts) {
  2421. for_array(i, stmts) {
  2422. Ast *stmt = stmts[i];
  2423. switch (stmt->kind) {
  2424. case_ast_node(vd, ValueDecl, stmt);
  2425. lb_build_constant_value_decl(p, vd);
  2426. case_end;
  2427. case_ast_node(fb, ForeignBlockDecl, stmt);
  2428. ast_node(block, BlockStmt, fb->body);
  2429. lb_build_stmt_list(p, block->stmts);
  2430. case_end;
  2431. }
  2432. }
  2433. for_array(i, stmts) {
  2434. lb_build_stmt(p, stmts[i]);
  2435. }
  2436. }
  2437. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2438. GB_ASSERT(ident->kind == Ast_Ident);
  2439. Entity *e = entity_of_node(ident);
  2440. GB_ASSERT(e->kind == Entity_Label);
  2441. for_array(i, p->branch_blocks) {
  2442. lbBranchBlocks *b = &p->branch_blocks[i];
  2443. if (b->label == e->Label.node) {
  2444. return *b;
  2445. }
  2446. }
  2447. GB_PANIC("Unreachable");
  2448. lbBranchBlocks empty = {};
  2449. return empty;
  2450. }
  2451. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2452. lbTargetList *tl = gb_alloc_item(heap_allocator(), lbTargetList);
  2453. tl->prev = p->target_list;
  2454. tl->break_ = break_;
  2455. tl->continue_ = continue_;
  2456. tl->fallthrough_ = fallthrough_;
  2457. p->target_list = tl;
  2458. if (label != nullptr) { // Set label blocks
  2459. GB_ASSERT(label->kind == Ast_Label);
  2460. for_array(i, p->branch_blocks) {
  2461. lbBranchBlocks *b = &p->branch_blocks[i];
  2462. GB_ASSERT(b->label != nullptr && label != nullptr);
  2463. GB_ASSERT(b->label->kind == Ast_Label);
  2464. if (b->label == label) {
  2465. b->break_ = break_;
  2466. b->continue_ = continue_;
  2467. return tl;
  2468. }
  2469. }
  2470. GB_PANIC("Unreachable");
  2471. }
  2472. return tl;
  2473. }
  2474. void lb_pop_target_list(lbProcedure *p) {
  2475. p->target_list = p->target_list->prev;
  2476. }
  2477. void lb_open_scope(lbProcedure *p) {
  2478. p->scope_index += 1;
  2479. }
  2480. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  2481. lb_emit_defer_stmts(p, kind, block);
  2482. GB_ASSERT(p->scope_index > 0);
  2483. // NOTE(bill): Remove `context`s made in that scope
  2484. while (p->context_stack.count > 0) {
  2485. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  2486. if (ctx->scope_index >= p->scope_index) {
  2487. array_pop(&p->context_stack);
  2488. } else {
  2489. break;
  2490. }
  2491. }
  2492. p->scope_index -= 1;
  2493. }
  2494. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  2495. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  2496. GB_ASSERT(is_type_boolean(tv.type));
  2497. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  2498. if (tv.value.value_bool) {
  2499. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  2500. } else if (ws->else_stmt) {
  2501. switch (ws->else_stmt->kind) {
  2502. case Ast_BlockStmt:
  2503. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  2504. break;
  2505. case Ast_WhenStmt:
  2506. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  2507. break;
  2508. default:
  2509. GB_PANIC("Invalid 'else' statement in 'when' statement");
  2510. break;
  2511. }
  2512. }
  2513. }
  2514. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  2515. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2516. lbModule *m = p->module;
  2517. lbValue count = {};
  2518. Type *expr_type = base_type(type_deref(expr.type));
  2519. switch (expr_type->kind) {
  2520. case Type_Array:
  2521. count = lb_const_int(m, t_int, expr_type->Array.count);
  2522. break;
  2523. }
  2524. lbValue val = {};
  2525. lbValue idx = {};
  2526. lbBlock *loop = nullptr;
  2527. lbBlock *done = nullptr;
  2528. lbBlock *body = nullptr;
  2529. lbAddr index = lb_add_local_generated(p, t_int, false);
  2530. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  2531. loop = lb_create_block(p, "for.index.loop");
  2532. lb_emit_jump(p, loop);
  2533. lb_start_block(p, loop);
  2534. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  2535. lb_addr_store(p, index, incr);
  2536. body = lb_create_block(p, "for.index.body");
  2537. done = lb_create_block(p, "for.index.done");
  2538. if (count.value == nullptr) {
  2539. GB_ASSERT(count_ptr.value != nullptr);
  2540. count = lb_emit_load(p, count_ptr);
  2541. }
  2542. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  2543. lb_emit_if(p, cond, body, done);
  2544. lb_start_block(p, body);
  2545. idx = lb_addr_load(p, index);
  2546. switch (expr_type->kind) {
  2547. case Type_Array: {
  2548. if (val_type != nullptr) {
  2549. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2550. }
  2551. break;
  2552. }
  2553. case Type_EnumeratedArray: {
  2554. if (val_type != nullptr) {
  2555. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2556. // NOTE(bill): Override the idx value for the enumeration
  2557. Type *index_type = expr_type->EnumeratedArray.index;
  2558. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  2559. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  2560. }
  2561. }
  2562. break;
  2563. }
  2564. case Type_Slice: {
  2565. if (val_type != nullptr) {
  2566. lbValue elem = lb_slice_elem(p, expr);
  2567. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2568. }
  2569. break;
  2570. }
  2571. case Type_DynamicArray: {
  2572. if (val_type != nullptr) {
  2573. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  2574. elem = lb_emit_load(p, elem);
  2575. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2576. }
  2577. break;
  2578. }
  2579. case Type_Map: {
  2580. lbValue entries = lb_map_entries_ptr(p, expr);
  2581. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  2582. elem = lb_emit_load(p, elem);
  2583. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  2584. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  2585. lbValue key_raw = lb_emit_struct_ep(p, entry, 0);
  2586. key_raw = lb_emit_struct_ep(p, key_raw, 1);
  2587. lbValue key = lb_emit_conv(p, key_raw, alloc_type_pointer(expr_type->Map.key));
  2588. idx = lb_emit_load(p, key);
  2589. break;
  2590. }
  2591. default:
  2592. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  2593. break;
  2594. }
  2595. if (val_) *val_ = val;
  2596. if (idx_) *idx_ = idx;
  2597. if (loop_) *loop_ = loop;
  2598. if (done_) *done_ = done;
  2599. }
  2600. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  2601. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2602. lbModule *m = p->module;
  2603. lbValue count = lb_const_int(m, t_int, 0);
  2604. Type *expr_type = base_type(expr.type);
  2605. switch (expr_type->kind) {
  2606. case Type_Basic:
  2607. count = lb_string_len(p, expr);
  2608. break;
  2609. default:
  2610. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  2611. break;
  2612. }
  2613. lbValue val = {};
  2614. lbValue idx = {};
  2615. lbBlock *loop = nullptr;
  2616. lbBlock *done = nullptr;
  2617. lbBlock *body = nullptr;
  2618. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2619. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2620. loop = lb_create_block(p, "for.string.loop");
  2621. lb_emit_jump(p, loop);
  2622. lb_start_block(p, loop);
  2623. body = lb_create_block(p, "for.string.body");
  2624. done = lb_create_block(p, "for.string.done");
  2625. lbValue offset = lb_addr_load(p, offset_);
  2626. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  2627. lb_emit_if(p, cond, body, done);
  2628. lb_start_block(p, body);
  2629. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  2630. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  2631. auto args = array_make<lbValue>(heap_allocator(), 1);
  2632. args[0] = lb_emit_string(p, str_elem, str_len);
  2633. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  2634. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  2635. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  2636. idx = offset;
  2637. if (val_type != nullptr) {
  2638. val = lb_emit_struct_ev(p, rune_and_len, 0);
  2639. }
  2640. if (val_) *val_ = val;
  2641. if (idx_) *idx_ = idx;
  2642. if (loop_) *loop_ = loop;
  2643. if (done_) *done_ = done;
  2644. }
  2645. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  2646. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2647. lbModule *m = p->module;
  2648. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  2649. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  2650. lbValue lower = lb_build_expr(p, node->left);
  2651. lbValue upper = {};
  2652. lbValue val = {};
  2653. lbValue idx = {};
  2654. lbBlock *loop = nullptr;
  2655. lbBlock *done = nullptr;
  2656. lbBlock *body = nullptr;
  2657. if (val_type == nullptr) {
  2658. val_type = lower.type;
  2659. }
  2660. lbAddr value = lb_add_local_generated(p, val_type, false);
  2661. lb_addr_store(p, value, lower);
  2662. lbAddr index = lb_add_local_generated(p, t_int, false);
  2663. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  2664. loop = lb_create_block(p, "for.interval.loop");
  2665. lb_emit_jump(p, loop);
  2666. lb_start_block(p, loop);
  2667. body = lb_create_block(p, "for.interval.body");
  2668. done = lb_create_block(p, "for.interval.done");
  2669. TokenKind op = Token_Lt;
  2670. switch (node->op.kind) {
  2671. case Token_Ellipsis: op = Token_LtEq; break;
  2672. case Token_RangeHalf: op = Token_Lt; break;
  2673. default: GB_PANIC("Invalid interval operator"); break;
  2674. }
  2675. upper = lb_build_expr(p, node->right);
  2676. lbValue curr_value = lb_addr_load(p, value);
  2677. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  2678. lb_emit_if(p, cond, body, done);
  2679. lb_start_block(p, body);
  2680. val = lb_addr_load(p, value);
  2681. idx = lb_addr_load(p, index);
  2682. lb_emit_increment(p, value.addr);
  2683. lb_emit_increment(p, index.addr);
  2684. if (val_) *val_ = val;
  2685. if (idx_) *idx_ = idx;
  2686. if (loop_) *loop_ = loop;
  2687. if (done_) *done_ = done;
  2688. }
  2689. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2690. lbModule *m = p->module;
  2691. Type *t = enum_type;
  2692. GB_ASSERT(is_type_enum(t));
  2693. Type *enum_ptr = alloc_type_pointer(t);
  2694. t = base_type(t);
  2695. Type *core_elem = core_type(t);
  2696. GB_ASSERT(t->kind == Type_Enum);
  2697. i64 enum_count = t->Enum.fields.count;
  2698. lbValue max_count = lb_const_int(m, t_int, enum_count);
  2699. lbValue ti = lb_type_info(m, t);
  2700. lbValue variant = lb_emit_struct_ep(p, ti, 3);
  2701. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  2702. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  2703. lbValue values_data = lb_slice_elem(p, values);
  2704. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2705. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2706. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  2707. lb_emit_jump(p, loop);
  2708. lb_start_block(p, loop);
  2709. lbBlock *body = lb_create_block(p, "for.enum.body");
  2710. lbBlock *done = lb_create_block(p, "for.enum.done");
  2711. lbValue offset = lb_addr_load(p, offset_);
  2712. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  2713. lb_emit_if(p, cond, body, done);
  2714. lb_start_block(p, body);
  2715. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  2716. lb_emit_increment(p, offset_.addr);
  2717. lbValue val = {};
  2718. if (val_type != nullptr) {
  2719. GB_ASSERT(are_types_identical(enum_type, val_type));
  2720. if (is_type_integer(core_elem)) {
  2721. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  2722. val = lb_emit_conv(p, i, t);
  2723. } else {
  2724. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  2725. }
  2726. }
  2727. if (val_) *val_ = val;
  2728. if (idx_) *idx_ = offset;
  2729. if (loop_) *loop_ = loop;
  2730. if (done_) *done_ = done;
  2731. }
  2732. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  2733. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  2734. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  2735. lb_emit_jump(p, loop);
  2736. lb_start_block(p, loop);
  2737. lbBlock *body = lb_create_block(p, "for.tuple.body");
  2738. lbBlock *done = lb_create_block(p, "for.tuple.done");
  2739. lbValue tuple_value = lb_build_expr(p, expr);
  2740. Type *tuple = tuple_value.type;
  2741. GB_ASSERT(tuple->kind == Type_Tuple);
  2742. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  2743. i32 cond_index = tuple_count-1;
  2744. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  2745. lb_emit_if(p, cond, body, done);
  2746. lb_start_block(p, body);
  2747. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  2748. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  2749. if (loop_) *loop_ = loop;
  2750. if (done_) *done_ = done;
  2751. }
  2752. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  2753. lb_open_scope(p);
  2754. Type *val0_type = nullptr;
  2755. Type *val1_type = nullptr;
  2756. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2757. val0_type = type_of_expr(rs->val0);
  2758. }
  2759. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2760. val1_type = type_of_expr(rs->val1);
  2761. }
  2762. if (val0_type != nullptr) {
  2763. Entity *e = entity_of_node(rs->val0);
  2764. lb_add_local(p, e->type, e, true);
  2765. }
  2766. if (val1_type != nullptr) {
  2767. Entity *e = entity_of_node(rs->val1);
  2768. lb_add_local(p, e->type, e, true);
  2769. }
  2770. lbValue val = {};
  2771. lbValue key = {};
  2772. lbBlock *loop = nullptr;
  2773. lbBlock *done = nullptr;
  2774. Ast *expr = unparen_expr(rs->expr);
  2775. bool is_map = false;
  2776. TypeAndValue tav = type_and_value_of_expr(expr);
  2777. if (is_ast_range(expr)) {
  2778. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  2779. } else if (tav.mode == Addressing_Type) {
  2780. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  2781. } else {
  2782. Type *expr_type = type_of_expr(expr);
  2783. Type *et = base_type(type_deref(expr_type));
  2784. switch (et->kind) {
  2785. case Type_Map: {
  2786. is_map = true;
  2787. lbValue map = lb_build_addr_ptr(p, expr);
  2788. if (is_type_pointer(type_deref(map.type))) {
  2789. map = lb_emit_load(p, map);
  2790. }
  2791. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  2792. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  2793. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  2794. break;
  2795. }
  2796. case Type_Array: {
  2797. lbValue array = lb_build_addr_ptr(p, expr);
  2798. if (is_type_pointer(type_deref(array.type))) {
  2799. array = lb_emit_load(p, array);
  2800. }
  2801. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2802. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  2803. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2804. break;
  2805. }
  2806. case Type_EnumeratedArray: {
  2807. lbValue array = lb_build_addr_ptr(p, expr);
  2808. if (is_type_pointer(type_deref(array.type))) {
  2809. array = lb_emit_load(p, array);
  2810. }
  2811. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2812. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  2813. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2814. break;
  2815. }
  2816. case Type_DynamicArray: {
  2817. lbValue count_ptr = {};
  2818. lbValue array = lb_build_addr_ptr(p, expr);
  2819. if (is_type_pointer(type_deref(array.type))) {
  2820. array = lb_emit_load(p, array);
  2821. }
  2822. count_ptr = lb_emit_struct_ep(p, array, 1);
  2823. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  2824. break;
  2825. }
  2826. case Type_Slice: {
  2827. lbValue count_ptr = {};
  2828. lbValue slice = lb_build_expr(p, expr);
  2829. if (is_type_pointer(slice.type)) {
  2830. count_ptr = lb_emit_struct_ep(p, slice, 1);
  2831. slice = lb_emit_load(p, slice);
  2832. } else {
  2833. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  2834. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  2835. }
  2836. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  2837. break;
  2838. }
  2839. case Type_Basic: {
  2840. lbValue string = lb_build_expr(p, expr);
  2841. if (is_type_pointer(string.type)) {
  2842. string = lb_emit_load(p, string);
  2843. }
  2844. if (is_type_untyped(expr_type)) {
  2845. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  2846. lb_addr_store(p, s, string);
  2847. string = lb_addr_load(p, s);
  2848. }
  2849. Type *t = base_type(string.type);
  2850. GB_ASSERT(!is_type_cstring(t));
  2851. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  2852. break;
  2853. }
  2854. case Type_Tuple:
  2855. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  2856. break;
  2857. default:
  2858. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  2859. break;
  2860. }
  2861. }
  2862. if (is_map) {
  2863. if (val0_type) lb_store_range_stmt_val(p, rs->val0, key);
  2864. if (val1_type) lb_store_range_stmt_val(p, rs->val1, val);
  2865. } else {
  2866. if (val0_type) lb_store_range_stmt_val(p, rs->val0, val);
  2867. if (val1_type) lb_store_range_stmt_val(p, rs->val1, key);
  2868. }
  2869. lb_push_target_list(p, rs->label, done, loop, nullptr);
  2870. lb_build_stmt(p, rs->body);
  2871. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2872. lb_pop_target_list(p);
  2873. lb_emit_jump(p, loop);
  2874. lb_start_block(p, done);
  2875. }
  2876. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  2877. lbModule *m = p->module;
  2878. lb_open_scope(p); // Open scope here
  2879. Type *val0_type = nullptr;
  2880. Type *val1_type = nullptr;
  2881. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2882. val0_type = type_of_expr(rs->val0);
  2883. }
  2884. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2885. val1_type = type_of_expr(rs->val1);
  2886. }
  2887. if (val0_type != nullptr) {
  2888. Entity *e = entity_of_node(rs->val0);
  2889. lb_add_local(p, e->type, e, true);
  2890. }
  2891. if (val1_type != nullptr) {
  2892. Entity *e = entity_of_node(rs->val1);
  2893. lb_add_local(p, e->type, e, true);
  2894. }
  2895. lbValue val = {};
  2896. lbValue key = {};
  2897. lbBlock *loop = nullptr;
  2898. lbBlock *done = nullptr;
  2899. Ast *expr = unparen_expr(rs->expr);
  2900. TypeAndValue tav = type_and_value_of_expr(expr);
  2901. if (is_ast_range(expr)) {
  2902. lbAddr val0_addr = {};
  2903. lbAddr val1_addr = {};
  2904. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2905. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2906. TokenKind op = expr->BinaryExpr.op.kind;
  2907. Ast *start_expr = expr->BinaryExpr.left;
  2908. Ast *end_expr = expr->BinaryExpr.right;
  2909. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  2910. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  2911. ExactValue start = start_expr->tav.value;
  2912. ExactValue end = end_expr->tav.value;
  2913. if (op == Token_Ellipsis) { // .. [start, end]
  2914. ExactValue index = exact_value_i64(0);
  2915. for (ExactValue val = start;
  2916. compare_exact_values(Token_LtEq, val, end);
  2917. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2918. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2919. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2920. lb_build_stmt(p, rs->body);
  2921. }
  2922. } else if (op == Token_RangeHalf) { // ..< [start, end)
  2923. ExactValue index = exact_value_i64(0);
  2924. for (ExactValue val = start;
  2925. compare_exact_values(Token_Lt, val, end);
  2926. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2927. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2928. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2929. lb_build_stmt(p, rs->body);
  2930. }
  2931. }
  2932. } else if (tav.mode == Addressing_Type) {
  2933. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  2934. Type *et = type_deref(tav.type);
  2935. Type *bet = base_type(et);
  2936. lbAddr val0_addr = {};
  2937. lbAddr val1_addr = {};
  2938. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2939. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2940. for_array(i, bet->Enum.fields) {
  2941. Entity *field = bet->Enum.fields[i];
  2942. GB_ASSERT(field->kind == Entity_Constant);
  2943. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  2944. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2945. lb_build_stmt(p, rs->body);
  2946. }
  2947. } else {
  2948. lbAddr val0_addr = {};
  2949. lbAddr val1_addr = {};
  2950. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2951. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2952. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  2953. Type *t = base_type(expr->tav.type);
  2954. switch (t->kind) {
  2955. case Type_Basic:
  2956. GB_ASSERT(is_type_string(t));
  2957. {
  2958. ExactValue value = expr->tav.value;
  2959. GB_ASSERT(value.kind == ExactValue_String);
  2960. String str = value.value_string;
  2961. Rune codepoint = 0;
  2962. isize offset = 0;
  2963. do {
  2964. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  2965. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  2966. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  2967. lb_build_stmt(p, rs->body);
  2968. offset += width;
  2969. } while (offset < str.len);
  2970. }
  2971. break;
  2972. case Type_Array:
  2973. if (t->Array.count > 0) {
  2974. lbValue val = lb_build_expr(p, expr);
  2975. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2976. for (i64 i = 0; i < t->Array.count; i++) {
  2977. if (val0_type) {
  2978. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2979. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2980. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2981. }
  2982. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2983. lb_build_stmt(p, rs->body);
  2984. }
  2985. }
  2986. break;
  2987. case Type_EnumeratedArray:
  2988. if (t->EnumeratedArray.count > 0) {
  2989. lbValue val = lb_build_expr(p, expr);
  2990. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2991. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  2992. if (val0_type) {
  2993. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2994. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2995. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2996. }
  2997. if (val1_type) {
  2998. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  2999. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3000. }
  3001. lb_build_stmt(p, rs->body);
  3002. }
  3003. }
  3004. break;
  3005. default:
  3006. GB_PANIC("Invalid inline for type");
  3007. break;
  3008. }
  3009. }
  3010. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3011. }
  3012. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  3013. if (ss->init != nullptr) {
  3014. lb_build_stmt(p, ss->init);
  3015. }
  3016. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3017. if (ss->tag != nullptr) {
  3018. tag = lb_build_expr(p, ss->tag);
  3019. }
  3020. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3021. ast_node(body, BlockStmt, ss->body);
  3022. Array<Ast *> default_stmts = {};
  3023. lbBlock *default_fall = nullptr;
  3024. lbBlock *default_block = nullptr;
  3025. lbBlock *fall = nullptr;
  3026. isize case_count = body->stmts.count;
  3027. for_array(i, body->stmts) {
  3028. Ast *clause = body->stmts[i];
  3029. ast_node(cc, CaseClause, clause);
  3030. lbBlock *body = fall;
  3031. if (body == nullptr) {
  3032. body = lb_create_block(p, "switch.case.body");
  3033. }
  3034. fall = done;
  3035. if (i+1 < case_count) {
  3036. fall = lb_create_block(p, "switch.fall.body");
  3037. }
  3038. if (cc->list.count == 0) {
  3039. // default case
  3040. default_stmts = cc->stmts;
  3041. default_fall = fall;
  3042. default_block = body;
  3043. continue;
  3044. }
  3045. lbBlock *next_cond = nullptr;
  3046. for_array(j, cc->list) {
  3047. Ast *expr = unparen_expr(cc->list[j]);
  3048. next_cond = lb_create_block(p, "switch.case.next");
  3049. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3050. if (is_ast_range(expr)) {
  3051. ast_node(ie, BinaryExpr, expr);
  3052. TokenKind op = Token_Invalid;
  3053. switch (ie->op.kind) {
  3054. case Token_Ellipsis: op = Token_LtEq; break;
  3055. case Token_RangeHalf: op = Token_Lt; break;
  3056. default: GB_PANIC("Invalid interval operator"); break;
  3057. }
  3058. lbValue lhs = lb_build_expr(p, ie->left);
  3059. lbValue rhs = lb_build_expr(p, ie->right);
  3060. // TODO(bill): do short circuit here
  3061. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3062. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3063. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3064. } else {
  3065. if (expr->tav.mode == Addressing_Type) {
  3066. GB_ASSERT(is_type_typeid(tag.type));
  3067. lbValue e = lb_typeid(p->module, expr->tav.type);
  3068. e = lb_emit_conv(p, e, tag.type);
  3069. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3070. } else {
  3071. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3072. }
  3073. }
  3074. lb_emit_if(p, cond, body, next_cond);
  3075. lb_start_block(p, next_cond);
  3076. }
  3077. lb_start_block(p, body);
  3078. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3079. lb_open_scope(p);
  3080. lb_build_stmt_list(p, cc->stmts);
  3081. lb_close_scope(p, lbDeferExit_Default, body);
  3082. lb_pop_target_list(p);
  3083. lb_emit_jump(p, done);
  3084. lb_start_block(p, next_cond);
  3085. }
  3086. if (default_block != nullptr) {
  3087. lb_emit_jump(p, default_block);
  3088. lb_start_block(p, default_block);
  3089. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3090. lb_open_scope(p);
  3091. lb_build_stmt_list(p, default_stmts);
  3092. lb_close_scope(p, lbDeferExit_Default, default_block);
  3093. lb_pop_target_list(p);
  3094. }
  3095. lb_emit_jump(p, done);
  3096. lb_start_block(p, done);
  3097. }
  3098. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3099. Entity *e = implicit_entity_of_node(clause);
  3100. GB_ASSERT(e != nullptr);
  3101. if (e->flags & EntityFlag_Value) {
  3102. // by value
  3103. GB_ASSERT(are_types_identical(e->type, value.type));
  3104. lbAddr x = lb_add_local(p, e->type, e, false);
  3105. lb_addr_store(p, x, value);
  3106. } else {
  3107. // by reference
  3108. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3109. lb_add_entity(p->module, e, value);
  3110. }
  3111. }
  3112. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3113. Entity *e = entity_of_node(stmt_val);
  3114. if (e == nullptr) {
  3115. return {};
  3116. }
  3117. if ((e->flags & EntityFlag_Value) == 0) {
  3118. if (LLVMIsALoadInst(value.value)) {
  3119. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3120. lb_add_entity(p->module, e, ptr);
  3121. return lb_addr(ptr);
  3122. }
  3123. }
  3124. // by value
  3125. lbAddr addr = lb_add_local(p, e->type, e, false);
  3126. lb_addr_store(p, addr, value);
  3127. return addr;
  3128. }
  3129. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3130. ast_node(cc, CaseClause, clause);
  3131. lb_push_target_list(p, label, done, nullptr, nullptr);
  3132. lb_open_scope(p);
  3133. lb_build_stmt_list(p, cc->stmts);
  3134. lb_close_scope(p, lbDeferExit_Default, body);
  3135. lb_pop_target_list(p);
  3136. lb_emit_jump(p, done);
  3137. }
  3138. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3139. lbModule *m = p->module;
  3140. ast_node(as, AssignStmt, ss->tag);
  3141. GB_ASSERT(as->lhs.count == 1);
  3142. GB_ASSERT(as->rhs.count == 1);
  3143. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3144. bool is_parent_ptr = is_type_pointer(parent.type);
  3145. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3146. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3147. lbValue parent_value = parent;
  3148. lbValue parent_ptr = parent;
  3149. if (!is_parent_ptr) {
  3150. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3151. }
  3152. lbValue tag_index = {};
  3153. lbValue union_data = {};
  3154. if (switch_kind == TypeSwitch_Union) {
  3155. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3156. tag_index = lb_emit_load(p, tag_ptr);
  3157. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3158. }
  3159. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3160. lb_emit_jump(p, start_block);
  3161. lb_start_block(p, start_block);
  3162. // NOTE(bill): Append this later
  3163. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3164. Ast *default_ = nullptr;
  3165. ast_node(body, BlockStmt, ss->body);
  3166. gb_local_persist i32 weird_count = 0;
  3167. for_array(i, body->stmts) {
  3168. Ast *clause = body->stmts[i];
  3169. ast_node(cc, CaseClause, clause);
  3170. if (cc->list.count == 0) {
  3171. default_ = clause;
  3172. continue;
  3173. }
  3174. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3175. lbBlock *next = nullptr;
  3176. Type *case_type = nullptr;
  3177. for_array(type_index, cc->list) {
  3178. next = lb_create_block(p, "typeswitch.next");
  3179. case_type = type_of_expr(cc->list[type_index]);
  3180. lbValue cond = {};
  3181. if (switch_kind == TypeSwitch_Union) {
  3182. Type *ut = base_type(type_deref(parent.type));
  3183. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3184. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3185. } else if (switch_kind == TypeSwitch_Any) {
  3186. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3187. lbValue case_typeid = lb_typeid(m, case_type);
  3188. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3189. }
  3190. GB_ASSERT(cond.value != nullptr);
  3191. lb_emit_if(p, cond, body, next);
  3192. lb_start_block(p, next);
  3193. }
  3194. Entity *case_entity = implicit_entity_of_node(clause);
  3195. lbValue value = parent_value;
  3196. lb_start_block(p, body);
  3197. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3198. if (cc->list.count == 1) {
  3199. lbValue data = {};
  3200. if (switch_kind == TypeSwitch_Union) {
  3201. data = union_data;
  3202. } else if (switch_kind == TypeSwitch_Any) {
  3203. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3204. data = any_data;
  3205. }
  3206. Type *ct = case_entity->type;
  3207. Type *ct_ptr = alloc_type_pointer(ct);
  3208. value = lb_emit_conv(p, data, ct_ptr);
  3209. if (!by_reference) {
  3210. value = lb_emit_load(p, value);
  3211. }
  3212. }
  3213. lb_store_type_case_implicit(p, clause, value);
  3214. lb_type_case_body(p, ss->label, clause, body, done);
  3215. lb_start_block(p, next);
  3216. }
  3217. if (default_ != nullptr) {
  3218. lb_store_type_case_implicit(p, default_, parent_value);
  3219. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3220. } else {
  3221. lb_emit_jump(p, done);
  3222. }
  3223. lb_start_block(p, done);
  3224. }
  3225. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3226. lbModule *m = p->module;
  3227. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3228. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3229. type = default_type(type);
  3230. lbValue short_circuit = {};
  3231. if (op == Token_CmpAnd) {
  3232. lb_build_cond(p, left, rhs, done);
  3233. short_circuit = lb_const_bool(m, type, false);
  3234. } else if (op == Token_CmpOr) {
  3235. lb_build_cond(p, left, done, rhs);
  3236. short_circuit = lb_const_bool(m, type, true);
  3237. }
  3238. if (rhs->preds.count == 0) {
  3239. lb_start_block(p, done);
  3240. return short_circuit;
  3241. }
  3242. if (done->preds.count == 0) {
  3243. lb_start_block(p, rhs);
  3244. return lb_build_expr(p, right);
  3245. }
  3246. Array<LLVMValueRef> incoming_values = {};
  3247. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3248. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3249. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3250. for_array(i, done->preds) {
  3251. incoming_values[i] = short_circuit.value;
  3252. incoming_blocks[i] = done->preds[i]->block;
  3253. }
  3254. lb_start_block(p, rhs);
  3255. lbValue edge = lb_build_expr(p, right);
  3256. incoming_values[done->preds.count] = edge.value;
  3257. incoming_blocks[done->preds.count] = p->curr_block->block;
  3258. lb_emit_jump(p, done);
  3259. lb_start_block(p, done);
  3260. lbValue res = {};
  3261. res.type = type;
  3262. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3263. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3264. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3265. return res;
  3266. }
  3267. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3268. Ast *prev_stmt = p->curr_stmt;
  3269. defer (p->curr_stmt = prev_stmt);
  3270. p->curr_stmt = node;
  3271. if (p->curr_block != nullptr) {
  3272. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3273. if (lb_is_instr_terminating(last_instr)) {
  3274. return;
  3275. }
  3276. }
  3277. u64 prev_state_flags = p->module->state_flags;
  3278. defer (p->module->state_flags = prev_state_flags);
  3279. if (node->state_flags != 0) {
  3280. u64 in = node->state_flags;
  3281. u64 out = p->module->state_flags;
  3282. if (in & StateFlag_bounds_check) {
  3283. out |= StateFlag_bounds_check;
  3284. out &= ~StateFlag_no_bounds_check;
  3285. } else if (in & StateFlag_no_bounds_check) {
  3286. out |= StateFlag_no_bounds_check;
  3287. out &= ~StateFlag_bounds_check;
  3288. }
  3289. p->module->state_flags = out;
  3290. }
  3291. switch (node->kind) {
  3292. case_ast_node(bs, EmptyStmt, node);
  3293. case_end;
  3294. case_ast_node(us, UsingStmt, node);
  3295. case_end;
  3296. case_ast_node(ws, WhenStmt, node);
  3297. lb_build_when_stmt(p, ws);
  3298. case_end;
  3299. case_ast_node(bs, BlockStmt, node);
  3300. if (bs->label != nullptr) {
  3301. lbBlock *done = lb_create_block(p, "block.done");
  3302. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3303. tl->is_block = true;
  3304. lb_open_scope(p);
  3305. lb_build_stmt_list(p, bs->stmts);
  3306. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3307. lb_emit_jump(p, done);
  3308. lb_start_block(p, done);
  3309. } else {
  3310. lb_open_scope(p);
  3311. lb_build_stmt_list(p, bs->stmts);
  3312. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3313. }
  3314. case_end;
  3315. case_ast_node(vd, ValueDecl, node);
  3316. if (!vd->is_mutable) {
  3317. return;
  3318. }
  3319. bool is_static = false;
  3320. if (vd->names.count > 0) {
  3321. Entity *e = entity_of_node(vd->names[0]);
  3322. if (e->flags & EntityFlag_Static) {
  3323. // NOTE(bill): If one of the entities is static, they all are
  3324. is_static = true;
  3325. }
  3326. }
  3327. if (is_static) {
  3328. for_array(i, vd->names) {
  3329. lbValue value = {};
  3330. if (vd->values.count > 0) {
  3331. GB_ASSERT(vd->names.count == vd->values.count);
  3332. Ast *ast_value = vd->values[i];
  3333. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3334. ast_value->tav.mode == Addressing_Invalid);
  3335. bool allow_local = false;
  3336. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3337. }
  3338. Ast *ident = vd->names[i];
  3339. GB_ASSERT(!is_blank_ident(ident));
  3340. Entity *e = entity_of_node(ident);
  3341. GB_ASSERT(e->flags & EntityFlag_Static);
  3342. String name = e->token.string;
  3343. String mangled_name = {};
  3344. {
  3345. gbString str = gb_string_make_length(heap_allocator(), p->name.text, p->name.len);
  3346. str = gb_string_appendc(str, "-");
  3347. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3348. mangled_name.text = cast(u8 *)str;
  3349. mangled_name.len = gb_string_length(str);
  3350. }
  3351. char *c_name = alloc_cstring(heap_allocator(), mangled_name);
  3352. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3353. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3354. if (value.value != nullptr) {
  3355. LLVMSetInitializer(global, value.value);
  3356. } else {
  3357. }
  3358. if (e->Variable.thread_local_model != "") {
  3359. LLVMSetThreadLocal(global, true);
  3360. String m = e->Variable.thread_local_model;
  3361. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3362. if (m == "default") {
  3363. mode = LLVMGeneralDynamicTLSModel;
  3364. } else if (m == "localdynamic") {
  3365. mode = LLVMLocalDynamicTLSModel;
  3366. } else if (m == "initialexec") {
  3367. mode = LLVMInitialExecTLSModel;
  3368. } else if (m == "localexec") {
  3369. mode = LLVMLocalExecTLSModel;
  3370. } else {
  3371. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3372. }
  3373. LLVMSetThreadLocalMode(global, mode);
  3374. } else {
  3375. LLVMSetLinkage(global, LLVMInternalLinkage);
  3376. }
  3377. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3378. lb_add_entity(p->module, e, global_val);
  3379. lb_add_member(p->module, mangled_name, global_val);
  3380. }
  3381. return;
  3382. }
  3383. if (vd->values.count == 0) { // declared and zero-initialized
  3384. for_array(i, vd->names) {
  3385. Ast *name = vd->names[i];
  3386. if (!is_blank_ident(name)) {
  3387. Entity *e = entity_of_node(name);
  3388. lb_add_local(p, e->type, e, true);
  3389. }
  3390. }
  3391. } else { // Tuple(s)
  3392. auto lvals = array_make<lbAddr>(heap_allocator(), 0, vd->names.count);
  3393. auto inits = array_make<lbValue>(heap_allocator(), 0, vd->names.count);
  3394. for_array(i, vd->names) {
  3395. Ast *name = vd->names[i];
  3396. lbAddr lval = {};
  3397. if (!is_blank_ident(name)) {
  3398. Entity *e = entity_of_node(name);
  3399. lval = lb_add_local(p, e->type, e, false);
  3400. }
  3401. array_add(&lvals, lval);
  3402. }
  3403. for_array(i, vd->values) {
  3404. lbValue init = lb_build_expr(p, vd->values[i]);
  3405. Type *t = init.type;
  3406. if (t->kind == Type_Tuple) {
  3407. for_array(i, t->Tuple.variables) {
  3408. Entity *e = t->Tuple.variables[i];
  3409. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3410. array_add(&inits, v);
  3411. }
  3412. } else {
  3413. array_add(&inits, init);
  3414. }
  3415. }
  3416. for_array(i, inits) {
  3417. lbAddr lval = lvals[i];
  3418. lbValue init = inits[i];
  3419. lb_addr_store(p, lval, init);
  3420. }
  3421. }
  3422. case_end;
  3423. case_ast_node(as, AssignStmt, node);
  3424. if (as->op.kind == Token_Eq) {
  3425. auto lvals = array_make<lbAddr>(heap_allocator(), 0, as->lhs.count);
  3426. for_array(i, as->lhs) {
  3427. Ast *lhs = as->lhs[i];
  3428. lbAddr lval = {};
  3429. if (!is_blank_ident(lhs)) {
  3430. lval = lb_build_addr(p, lhs);
  3431. }
  3432. array_add(&lvals, lval);
  3433. }
  3434. if (as->lhs.count == as->rhs.count) {
  3435. if (as->lhs.count == 1) {
  3436. lbAddr lval = lvals[0];
  3437. Ast *rhs = as->rhs[0];
  3438. lbValue init = lb_build_expr(p, rhs);
  3439. lb_addr_store(p, lvals[0], init);
  3440. } else {
  3441. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  3442. for_array(i, as->rhs) {
  3443. lbValue init = lb_build_expr(p, as->rhs[i]);
  3444. array_add(&inits, init);
  3445. }
  3446. for_array(i, inits) {
  3447. lbAddr lval = lvals[i];
  3448. lbValue init = inits[i];
  3449. lb_addr_store(p, lval, init);
  3450. }
  3451. }
  3452. } else {
  3453. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  3454. for_array(i, as->rhs) {
  3455. lbValue init = lb_build_expr(p, as->rhs[i]);
  3456. Type *t = init.type;
  3457. // TODO(bill): refactor for code reuse as this is repeated a bit
  3458. if (t->kind == Type_Tuple) {
  3459. for_array(i, t->Tuple.variables) {
  3460. Entity *e = t->Tuple.variables[i];
  3461. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3462. array_add(&inits, v);
  3463. }
  3464. } else {
  3465. array_add(&inits, init);
  3466. }
  3467. }
  3468. for_array(i, inits) {
  3469. lbAddr lval = lvals[i];
  3470. lbValue init = inits[i];
  3471. lb_addr_store(p, lval, init);
  3472. }
  3473. }
  3474. } else {
  3475. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  3476. // +=, -=, etc
  3477. i32 op = cast(i32)as->op.kind;
  3478. op += Token_Add - Token_AddEq; // Convert += to +
  3479. if (op == Token_CmpAnd || op == Token_CmpOr) {
  3480. Type *type = as->lhs[0]->tav.type;
  3481. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  3482. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3483. lb_addr_store(p, lhs, new_value);
  3484. } else {
  3485. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3486. lbValue value = lb_build_expr(p, as->rhs[0]);
  3487. lbValue old_value = lb_addr_load(p, lhs);
  3488. Type *type = old_value.type;
  3489. lbValue change = lb_emit_conv(p, value, type);
  3490. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  3491. lb_addr_store(p, lhs, new_value);
  3492. }
  3493. return;
  3494. }
  3495. case_end;
  3496. case_ast_node(es, ExprStmt, node);
  3497. lb_build_expr(p, es->expr);
  3498. case_end;
  3499. case_ast_node(ds, DeferStmt, node);
  3500. isize scope_index = p->scope_index;
  3501. lb_add_defer_node(p, scope_index, ds->stmt);
  3502. case_end;
  3503. case_ast_node(rs, ReturnStmt, node);
  3504. lbValue res = {};
  3505. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  3506. isize return_count = p->type->Proc.result_count;
  3507. isize res_count = rs->results.count;
  3508. if (return_count == 0) {
  3509. // No return values
  3510. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3511. LLVMBuildRetVoid(p->builder);
  3512. return;
  3513. } else if (return_count == 1) {
  3514. Entity *e = tuple->variables[0];
  3515. if (res_count == 0) {
  3516. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3517. GB_ASSERT(found);
  3518. res = lb_emit_load(p, *found);
  3519. } else {
  3520. res = lb_build_expr(p, rs->results[0]);
  3521. res = lb_emit_conv(p, res, e->type);
  3522. }
  3523. if (p->type->Proc.has_named_results) {
  3524. // NOTE(bill): store the named values before returning
  3525. if (e->token.string != "") {
  3526. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3527. GB_ASSERT(found != nullptr);
  3528. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  3529. }
  3530. }
  3531. } else {
  3532. auto results = array_make<lbValue>(heap_allocator(), 0, return_count);
  3533. if (res_count != 0) {
  3534. for (isize res_index = 0; res_index < res_count; res_index++) {
  3535. lbValue res = lb_build_expr(p, rs->results[res_index]);
  3536. Type *t = res.type;
  3537. if (t->kind == Type_Tuple) {
  3538. for_array(i, t->Tuple.variables) {
  3539. Entity *e = t->Tuple.variables[i];
  3540. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  3541. array_add(&results, v);
  3542. }
  3543. } else {
  3544. array_add(&results, res);
  3545. }
  3546. }
  3547. } else {
  3548. for (isize res_index = 0; res_index < return_count; res_index++) {
  3549. Entity *e = tuple->variables[res_index];
  3550. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3551. GB_ASSERT(found);
  3552. lbValue res = lb_emit_load(p, *found);
  3553. array_add(&results, res);
  3554. }
  3555. }
  3556. GB_ASSERT(results.count == return_count);
  3557. if (p->type->Proc.has_named_results) {
  3558. // NOTE(bill): store the named values before returning
  3559. for_array(i, p->type->Proc.results->Tuple.variables) {
  3560. Entity *e = p->type->Proc.results->Tuple.variables[i];
  3561. if (e->kind != Entity_Variable) {
  3562. continue;
  3563. }
  3564. if (e->token.string == "") {
  3565. continue;
  3566. }
  3567. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3568. GB_ASSERT(found != nullptr);
  3569. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  3570. }
  3571. }
  3572. Type *ret_type = p->type->Proc.results;
  3573. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3574. res = lb_add_local_generated(p, ret_type, false).addr;
  3575. for_array(i, results) {
  3576. Entity *e = tuple->variables[i];
  3577. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  3578. lbValue val = lb_emit_conv(p, results[i], e->type);
  3579. lb_emit_store(p, field, val);
  3580. }
  3581. res = lb_emit_load(p, res);
  3582. }
  3583. if (p->type->Proc.return_by_pointer) {
  3584. if (res.value != nullptr) {
  3585. lb_addr_store(p, p->return_ptr, res);
  3586. } else {
  3587. lb_addr_store(p, p->return_ptr, lb_const_nil(p->module, p->type->Proc.abi_compat_result_type));
  3588. }
  3589. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3590. LLVMBuildRetVoid(p->builder);
  3591. } else {
  3592. GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name));
  3593. Type *abi_rt = p->type->Proc.abi_compat_result_type;
  3594. if (!are_types_identical(res.type, abi_rt)) {
  3595. res = lb_emit_transmute(p, res, abi_rt);
  3596. }
  3597. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3598. LLVMBuildRet(p->builder, res.value);
  3599. }
  3600. case_end;
  3601. case_ast_node(is, IfStmt, node);
  3602. lb_open_scope(p); // Scope #1
  3603. if (is->init != nullptr) {
  3604. // TODO(bill): Should this have a separate block to begin with?
  3605. #if 1
  3606. lbBlock *init = lb_create_block(p, "if.init");
  3607. lb_emit_jump(p, init);
  3608. lb_start_block(p, init);
  3609. #endif
  3610. lb_build_stmt(p, is->init);
  3611. }
  3612. lbBlock *then = lb_create_block(p, "if.then");
  3613. lbBlock *done = lb_create_block(p, "if.done");
  3614. lbBlock *else_ = done;
  3615. if (is->else_stmt != nullptr) {
  3616. else_ = lb_create_block(p, "if.else");
  3617. }
  3618. lb_build_cond(p, is->cond, then, else_);
  3619. lb_start_block(p, then);
  3620. if (is->label != nullptr) {
  3621. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  3622. tl->is_block = true;
  3623. }
  3624. lb_build_stmt(p, is->body);
  3625. lb_emit_jump(p, done);
  3626. if (is->else_stmt != nullptr) {
  3627. lb_start_block(p, else_);
  3628. lb_open_scope(p);
  3629. lb_build_stmt(p, is->else_stmt);
  3630. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3631. lb_emit_jump(p, done);
  3632. }
  3633. lb_start_block(p, done);
  3634. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3635. case_end;
  3636. case_ast_node(fs, ForStmt, node);
  3637. lb_open_scope(p); // Open Scope here
  3638. if (fs->init != nullptr) {
  3639. #if 1
  3640. lbBlock *init = lb_create_block(p, "for.init");
  3641. lb_emit_jump(p, init);
  3642. lb_start_block(p, init);
  3643. #endif
  3644. lb_build_stmt(p, fs->init);
  3645. }
  3646. lbBlock *body = lb_create_block(p, "for.body");
  3647. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  3648. lbBlock *loop = body;
  3649. if (fs->cond != nullptr) {
  3650. loop = lb_create_block(p, "for.loop");
  3651. }
  3652. lbBlock *post = loop;
  3653. if (fs->post != nullptr) {
  3654. post = lb_create_block(p, "for.post");
  3655. }
  3656. lb_emit_jump(p, loop);
  3657. lb_start_block(p, loop);
  3658. if (loop != body) {
  3659. lb_build_cond(p, fs->cond, body, done);
  3660. lb_start_block(p, body);
  3661. }
  3662. lb_push_target_list(p, fs->label, done, post, nullptr);
  3663. lb_build_stmt(p, fs->body);
  3664. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3665. lb_pop_target_list(p);
  3666. lb_emit_jump(p, post);
  3667. if (fs->post != nullptr) {
  3668. lb_start_block(p, post);
  3669. lb_build_stmt(p, fs->post);
  3670. lb_emit_jump(p, loop);
  3671. }
  3672. lb_start_block(p, done);
  3673. case_end;
  3674. case_ast_node(rs, RangeStmt, node);
  3675. lb_build_range_stmt(p, rs);
  3676. case_end;
  3677. case_ast_node(rs, InlineRangeStmt, node);
  3678. lb_build_inline_range_stmt(p, rs);
  3679. case_end;
  3680. case_ast_node(ss, SwitchStmt, node);
  3681. lb_build_switch_stmt(p, ss);
  3682. case_end;
  3683. case_ast_node(ss, TypeSwitchStmt, node);
  3684. lb_build_type_switch_stmt(p, ss);
  3685. case_end;
  3686. case_ast_node(bs, BranchStmt, node);
  3687. lbBlock *block = nullptr;
  3688. if (bs->label != nullptr) {
  3689. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  3690. switch (bs->token.kind) {
  3691. case Token_break: block = bb.break_; break;
  3692. case Token_continue: block = bb.continue_; break;
  3693. case Token_fallthrough:
  3694. GB_PANIC("fallthrough cannot have a label");
  3695. break;
  3696. }
  3697. } else {
  3698. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  3699. if (t->is_block) {
  3700. continue;
  3701. }
  3702. switch (bs->token.kind) {
  3703. case Token_break: block = t->break_; break;
  3704. case Token_continue: block = t->continue_; break;
  3705. case Token_fallthrough: block = t->fallthrough_; break;
  3706. }
  3707. }
  3708. }
  3709. if (block != nullptr) {
  3710. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  3711. }
  3712. lb_emit_jump(p, block);
  3713. case_end;
  3714. }
  3715. }
  3716. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  3717. cond = lb_emit_conv(p, cond, t_llvm_bool);
  3718. lbValue res = {};
  3719. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  3720. res.type = x.type;
  3721. return res;
  3722. }
  3723. lbValue lb_const_nil(lbModule *m, Type *type) {
  3724. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  3725. return lbValue{v, type};
  3726. }
  3727. lbValue lb_const_undef(lbModule *m, Type *type) {
  3728. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  3729. return lbValue{v, type};
  3730. }
  3731. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  3732. lbValue res = {};
  3733. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  3734. res.type = type;
  3735. return res;
  3736. }
  3737. lbValue lb_const_string(lbModule *m, String const &value) {
  3738. return lb_const_value(m, t_string, exact_value_string(value));
  3739. }
  3740. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  3741. lbValue res = {};
  3742. res.value = LLVMConstInt(lb_type(m, type), value, false);
  3743. res.type = type;
  3744. return res;
  3745. }
  3746. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  3747. GB_ASSERT(type_size_of(type) == 4);
  3748. u32 u = bit_cast<u32>(f);
  3749. if (is_type_different_to_arch_endianness(type)) {
  3750. u = gb_endian_swap32(u);
  3751. }
  3752. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  3753. return LLVMConstBitCast(i, lb_type(m, type));
  3754. }
  3755. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3756. x = lb_emit_conv(p, x, t);
  3757. y = lb_emit_conv(p, y, t);
  3758. if (is_type_float(t)) {
  3759. gbAllocator a = heap_allocator();
  3760. i64 sz = 8*type_size_of(t);
  3761. auto args = array_make<lbValue>(heap_allocator(), 2);
  3762. args[0] = x;
  3763. args[1] = y;
  3764. switch (sz) {
  3765. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  3766. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  3767. }
  3768. GB_PANIC("Unknown float type");
  3769. }
  3770. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  3771. }
  3772. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3773. x = lb_emit_conv(p, x, t);
  3774. y = lb_emit_conv(p, y, t);
  3775. if (is_type_float(t)) {
  3776. gbAllocator a = heap_allocator();
  3777. i64 sz = 8*type_size_of(t);
  3778. auto args = array_make<lbValue>(heap_allocator(), 2);
  3779. args[0] = x;
  3780. args[1] = y;
  3781. switch (sz) {
  3782. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  3783. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  3784. }
  3785. GB_PANIC("Unknown float type");
  3786. }
  3787. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  3788. }
  3789. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  3790. lbValue z = {};
  3791. z = lb_emit_max(p, t, x, min);
  3792. z = lb_emit_min(p, t, z, max);
  3793. return z;
  3794. }
  3795. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  3796. StringHashKey key = string_hash_string(str);
  3797. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  3798. if (found != nullptr) {
  3799. return *found;
  3800. } else {
  3801. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  3802. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3803. cast(char const *)str.text,
  3804. cast(unsigned)str.len,
  3805. false);
  3806. isize max_len = 7+8+1;
  3807. char *name = gb_alloc_array(heap_allocator(), char, max_len);
  3808. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3809. len -= 1;
  3810. m->global_array_index++;
  3811. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3812. LLVMSetInitializer(global_data, data);
  3813. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  3814. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3815. string_map_set(&m->const_strings, key, ptr);
  3816. return ptr;
  3817. }
  3818. }
  3819. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  3820. LLVMValueRef ptr = nullptr;
  3821. if (str.len != 0) {
  3822. ptr = lb_find_or_add_entity_string_ptr(m, str);
  3823. } else {
  3824. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  3825. }
  3826. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3827. LLVMValueRef values[2] = {ptr, str_len};
  3828. lbValue res = {};
  3829. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  3830. res.type = t_string;
  3831. return res;
  3832. }
  3833. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  3834. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  3835. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3836. cast(char const *)str.text,
  3837. cast(unsigned)str.len,
  3838. false);
  3839. char *name = nullptr;
  3840. {
  3841. isize max_len = 7+8+1;
  3842. name = gb_alloc_array(heap_allocator(), char, max_len);
  3843. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3844. len -= 1;
  3845. m->global_array_index++;
  3846. }
  3847. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3848. LLVMSetInitializer(global_data, data);
  3849. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  3850. LLVMValueRef ptr = nullptr;
  3851. if (str.len != 0) {
  3852. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3853. } else {
  3854. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  3855. }
  3856. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3857. LLVMValueRef values[2] = {ptr, len};
  3858. lbValue res = {};
  3859. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  3860. res.type = t_u8_slice;
  3861. return res;
  3862. }
  3863. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  3864. isize index = type_info_index(info, type, false);
  3865. if (index >= 0) {
  3866. auto *set = &info->minimum_dependency_type_info_set;
  3867. for_array(i, set->entries) {
  3868. if (set->entries[i].ptr == index) {
  3869. return i+1;
  3870. }
  3871. }
  3872. }
  3873. if (err_on_not_found) {
  3874. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  3875. }
  3876. return -1;
  3877. }
  3878. lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type) {
  3879. type = default_type(type);
  3880. u64 id = cast(u64)lb_type_info_index(m->info, type);
  3881. GB_ASSERT(id >= 0);
  3882. u64 kind = Typeid_Invalid;
  3883. u64 named = is_type_named(type) && type->kind != Type_Basic;
  3884. u64 special = 0;
  3885. u64 reserved = 0;
  3886. Type *bt = base_type(type);
  3887. TypeKind tk = bt->kind;
  3888. switch (tk) {
  3889. case Type_Basic: {
  3890. u32 flags = bt->Basic.flags;
  3891. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  3892. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  3893. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  3894. if (flags & BasicFlag_Float) kind = Typeid_Float;
  3895. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  3896. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  3897. if (flags & BasicFlag_String) kind = Typeid_String;
  3898. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  3899. } break;
  3900. case Type_Pointer: kind = Typeid_Pointer; break;
  3901. case Type_Array: kind = Typeid_Array; break;
  3902. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  3903. case Type_Slice: kind = Typeid_Slice; break;
  3904. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  3905. case Type_Map: kind = Typeid_Map; break;
  3906. case Type_Struct: kind = Typeid_Struct; break;
  3907. case Type_Enum: kind = Typeid_Enum; break;
  3908. case Type_Union: kind = Typeid_Union; break;
  3909. case Type_Tuple: kind = Typeid_Tuple; break;
  3910. case Type_Proc: kind = Typeid_Procedure; break;
  3911. case Type_BitField: kind = Typeid_Bit_Field; break;
  3912. case Type_BitSet: kind = Typeid_Bit_Set; break;
  3913. case Type_Opaque: kind = Typeid_Opaque; break;
  3914. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  3915. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  3916. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  3917. }
  3918. if (is_type_cstring(type)) {
  3919. special = 1;
  3920. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  3921. special = 1;
  3922. }
  3923. u64 data = 0;
  3924. if (build_context.word_size == 4) {
  3925. data |= (id &~ (1u<<24)) << 0u; // index
  3926. data |= (kind &~ (1u<<5)) << 24u; // kind
  3927. data |= (named &~ (1u<<1)) << 29u; // kind
  3928. data |= (special &~ (1u<<1)) << 30u; // kind
  3929. data |= (reserved &~ (1u<<1)) << 31u; // kind
  3930. } else {
  3931. GB_ASSERT(build_context.word_size == 8);
  3932. data |= (id &~ (1ull<<56)) << 0ul; // index
  3933. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  3934. data |= (named &~ (1ull<<1)) << 61ull; // kind
  3935. data |= (special &~ (1ull<<1)) << 62ull; // kind
  3936. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  3937. }
  3938. lbValue res = {};
  3939. res.value = LLVMConstInt(lb_type(m, typeid_type), data, false);
  3940. res.type = typeid_type;
  3941. return res;
  3942. }
  3943. lbValue lb_type_info(lbModule *m, Type *type) {
  3944. type = default_type(type);
  3945. isize index = lb_type_info_index(m->info, type);
  3946. GB_ASSERT(index >= 0);
  3947. LLVMTypeRef it = lb_type(m, t_int);
  3948. LLVMValueRef indices[2] = {
  3949. LLVMConstInt(it, 0, false),
  3950. LLVMConstInt(it, index, true),
  3951. };
  3952. lbValue value = {};
  3953. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  3954. value.type = t_type_info_ptr;
  3955. return value;
  3956. }
  3957. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  3958. LLVMContextRef ctx = m->ctx;
  3959. type = default_type(type);
  3960. Type *original_type = type;
  3961. lbValue res = {};
  3962. res.type = original_type;
  3963. type = core_type(type);
  3964. value = convert_exact_value_for_type(value, type);
  3965. if (value.kind == ExactValue_Typeid) {
  3966. return lb_typeid(m, value.value_typeid, original_type);
  3967. }
  3968. if (value.kind == ExactValue_Invalid) {
  3969. return lb_const_nil(m, type);
  3970. }
  3971. if (value.kind == ExactValue_Procedure) {
  3972. Ast *expr = unparen_expr(value.value_procedure);
  3973. if (expr->kind == Ast_ProcLit) {
  3974. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  3975. }
  3976. Entity *e = entity_from_expr(expr);
  3977. e = strip_entity_wrapping(e);
  3978. GB_ASSERT(e != nullptr);
  3979. auto *found = map_get(&m->values, hash_entity(e));
  3980. if (found) {
  3981. return *found;
  3982. }
  3983. 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));
  3984. }
  3985. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  3986. if (is_type_slice(type)) {
  3987. if (value.kind == ExactValue_String) {
  3988. GB_ASSERT(is_type_u8_slice(type));
  3989. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  3990. return res;
  3991. } else {
  3992. ast_node(cl, CompoundLit, value.value_compound);
  3993. isize count = cl->elems.count;
  3994. if (count == 0) {
  3995. return lb_const_nil(m, type);
  3996. }
  3997. count = gb_max(cl->max_count, count);
  3998. Type *elem = base_type(type)->Slice.elem;
  3999. Type *t = alloc_type_array(elem, count);
  4000. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4001. LLVMValueRef array_data = nullptr;
  4002. if (allow_local && m->curr_procedure != nullptr) {
  4003. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4004. // its backing data on the stack
  4005. lbProcedure *p = m->curr_procedure;
  4006. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4007. LLVMTypeRef llvm_type = lb_type(m, t);
  4008. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4009. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4010. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4011. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4012. {
  4013. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4014. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4015. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4016. lbAddr slice = lb_add_local_generated(p, type, false);
  4017. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4018. return lb_addr_load(p, slice);
  4019. }
  4020. } else {
  4021. isize max_len = 7+8+1;
  4022. char *str = gb_alloc_array(heap_allocator(), char, max_len);
  4023. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4024. m->global_array_index++;
  4025. String name = make_string(cast(u8 *)str, len-1);
  4026. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4027. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4028. LLVMSetInitializer(array_data, backing_array.value);
  4029. lbValue g = {};
  4030. g.value = array_data;
  4031. g.type = t;
  4032. lb_add_entity(m, e, g);
  4033. lb_add_member(m, name, g);
  4034. {
  4035. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4036. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4037. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4038. LLVMValueRef values[2] = {ptr, len};
  4039. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4040. return res;
  4041. }
  4042. }
  4043. }
  4044. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4045. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4046. cast(char const *)value.value_string.text,
  4047. cast(unsigned)value.value_string.len,
  4048. false);
  4049. res.value = data;
  4050. return res;
  4051. } else if (is_type_array(type) &&
  4052. value.kind != ExactValue_Invalid &&
  4053. value.kind != ExactValue_String &&
  4054. value.kind != ExactValue_Compound) {
  4055. i64 count = type->Array.count;
  4056. Type *elem = type->Array.elem;
  4057. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4058. LLVMValueRef *elems = gb_alloc_array(heap_allocator(), LLVMValueRef, count);
  4059. for (i64 i = 0; i < count; i++) {
  4060. elems[i] = single_elem.value;
  4061. }
  4062. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  4063. return res;
  4064. }
  4065. switch (value.kind) {
  4066. case ExactValue_Invalid:
  4067. res.value = LLVMConstNull(lb_type(m, original_type));
  4068. return res;
  4069. case ExactValue_Bool:
  4070. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4071. return res;
  4072. case ExactValue_String:
  4073. {
  4074. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4075. lbValue res = {};
  4076. res.type = default_type(original_type);
  4077. if (is_type_cstring(res.type)) {
  4078. res.value = ptr;
  4079. } else {
  4080. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4081. LLVMValueRef values[2] = {ptr, str_len};
  4082. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4083. }
  4084. return res;
  4085. }
  4086. case ExactValue_Integer:
  4087. if (is_type_pointer(type)) {
  4088. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4089. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4090. } else {
  4091. unsigned len = cast(unsigned)value.value_integer.len;
  4092. if (len == 0) {
  4093. u64 word = 0;
  4094. res.value = LLVMConstNull(lb_type(m, original_type));
  4095. } else {
  4096. u64 *words = big_int_ptr(&value.value_integer);
  4097. if (is_type_different_to_arch_endianness(type)) {
  4098. // NOTE(bill): Swap byte order for different endianness
  4099. i64 sz = type_size_of(type);
  4100. isize byte_len = gb_size_of(u64)*len;
  4101. u8 *old_bytes = cast(u8 *)words;
  4102. // TODO(bill): Use a different allocator here for a temporary allocation
  4103. u8 *new_bytes = cast(u8 *)gb_alloc_align(heap_allocator(), byte_len, gb_align_of(u64));
  4104. for (i64 i = 0; i < sz; i++) {
  4105. new_bytes[i] = old_bytes[sz-1-i];
  4106. }
  4107. words = cast(u64 *)new_bytes;
  4108. }
  4109. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4110. if (value.value_integer.neg) {
  4111. res.value = LLVMConstNeg(res.value);
  4112. }
  4113. }
  4114. }
  4115. return res;
  4116. case ExactValue_Float:
  4117. if (type_size_of(type) == 4) {
  4118. f32 f = cast(f32)value.value_float;
  4119. res.value = lb_const_f32(m, f, type);
  4120. return res;
  4121. }
  4122. if (is_type_different_to_arch_endianness(type)) {
  4123. u64 u = bit_cast<u64>(value.value_float);
  4124. u = gb_endian_swap64(u);
  4125. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4126. } else {
  4127. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4128. }
  4129. return res;
  4130. case ExactValue_Complex:
  4131. {
  4132. LLVMValueRef values[2] = {};
  4133. switch (8*type_size_of(type)) {
  4134. case 64:
  4135. values[0] = lb_const_f32(m, cast(f32)value.value_complex.real);
  4136. values[1] = lb_const_f32(m, cast(f32)value.value_complex.imag);
  4137. break;
  4138. case 128:
  4139. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real);
  4140. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.imag);
  4141. break;
  4142. }
  4143. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4144. return res;
  4145. }
  4146. break;
  4147. case ExactValue_Quaternion:
  4148. {
  4149. LLVMValueRef values[4] = {};
  4150. switch (8*type_size_of(type)) {
  4151. case 128:
  4152. // @QuaternionLayout
  4153. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion.real);
  4154. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion.imag);
  4155. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion.jmag);
  4156. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion.kmag);
  4157. break;
  4158. case 256:
  4159. // @QuaternionLayout
  4160. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.real);
  4161. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.imag);
  4162. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.jmag);
  4163. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.kmag);
  4164. break;
  4165. }
  4166. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  4167. return res;
  4168. }
  4169. break;
  4170. case ExactValue_Pointer:
  4171. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4172. return res;
  4173. case ExactValue_Compound:
  4174. if (is_type_slice(type)) {
  4175. return lb_const_value(m, type, value, allow_local);
  4176. } else if (is_type_array(type)) {
  4177. ast_node(cl, CompoundLit, value.value_compound);
  4178. Type *elem_type = type->Array.elem;
  4179. isize elem_count = cl->elems.count;
  4180. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4181. return lb_const_nil(m, original_type);
  4182. }
  4183. if (cl->elems[0]->kind == Ast_FieldValue) {
  4184. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4185. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  4186. defer (gb_free(heap_allocator(), values));
  4187. isize value_index = 0;
  4188. for (i64 i = 0; i < type->Array.count; i++) {
  4189. bool found = false;
  4190. for (isize j = 0; j < elem_count; j++) {
  4191. Ast *elem = cl->elems[j];
  4192. ast_node(fv, FieldValue, elem);
  4193. if (is_ast_range(fv->field)) {
  4194. ast_node(ie, BinaryExpr, fv->field);
  4195. TypeAndValue lo_tav = ie->left->tav;
  4196. TypeAndValue hi_tav = ie->right->tav;
  4197. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4198. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4199. TokenKind op = ie->op.kind;
  4200. i64 lo = exact_value_to_i64(lo_tav.value);
  4201. i64 hi = exact_value_to_i64(hi_tav.value);
  4202. if (op == Token_Ellipsis) {
  4203. hi += 1;
  4204. }
  4205. if (lo == i) {
  4206. TypeAndValue tav = fv->value->tav;
  4207. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4208. for (i64 k = lo; k < hi; k++) {
  4209. values[value_index++] = val;
  4210. }
  4211. found = true;
  4212. i += (hi-lo-1);
  4213. break;
  4214. }
  4215. } else {
  4216. TypeAndValue index_tav = fv->field->tav;
  4217. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4218. i64 index = exact_value_to_i64(index_tav.value);
  4219. if (index == i) {
  4220. TypeAndValue tav = fv->value->tav;
  4221. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4222. values[value_index++] = val;
  4223. found = true;
  4224. break;
  4225. }
  4226. }
  4227. }
  4228. if (!found) {
  4229. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4230. }
  4231. }
  4232. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  4233. return res;
  4234. } else {
  4235. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4236. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  4237. defer (gb_free(heap_allocator(), values));
  4238. for (isize i = 0; i < elem_count; i++) {
  4239. TypeAndValue tav = cl->elems[i]->tav;
  4240. GB_ASSERT(tav.mode != Addressing_Invalid);
  4241. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4242. }
  4243. for (isize i = elem_count; i < type->Array.count; i++) {
  4244. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4245. }
  4246. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  4247. return res;
  4248. }
  4249. } else if (is_type_enumerated_array(type)) {
  4250. ast_node(cl, CompoundLit, value.value_compound);
  4251. Type *elem_type = type->EnumeratedArray.elem;
  4252. isize elem_count = cl->elems.count;
  4253. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4254. return lb_const_nil(m, original_type);
  4255. }
  4256. if (cl->elems[0]->kind == Ast_FieldValue) {
  4257. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4258. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4259. defer (gb_free(heap_allocator(), values));
  4260. isize value_index = 0;
  4261. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4262. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4263. for (i64 i = total_lo; i <= total_hi; i++) {
  4264. bool found = false;
  4265. for (isize j = 0; j < elem_count; j++) {
  4266. Ast *elem = cl->elems[j];
  4267. ast_node(fv, FieldValue, elem);
  4268. if (is_ast_range(fv->field)) {
  4269. ast_node(ie, BinaryExpr, fv->field);
  4270. TypeAndValue lo_tav = ie->left->tav;
  4271. TypeAndValue hi_tav = ie->right->tav;
  4272. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4273. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4274. TokenKind op = ie->op.kind;
  4275. i64 lo = exact_value_to_i64(lo_tav.value);
  4276. i64 hi = exact_value_to_i64(hi_tav.value);
  4277. if (op == Token_Ellipsis) {
  4278. hi += 1;
  4279. }
  4280. if (lo == i) {
  4281. TypeAndValue tav = fv->value->tav;
  4282. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4283. for (i64 k = lo; k < hi; k++) {
  4284. values[value_index++] = val;
  4285. }
  4286. found = true;
  4287. i += (hi-lo-1);
  4288. break;
  4289. }
  4290. } else {
  4291. TypeAndValue index_tav = fv->field->tav;
  4292. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4293. i64 index = exact_value_to_i64(index_tav.value);
  4294. if (index == i) {
  4295. TypeAndValue tav = fv->value->tav;
  4296. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4297. values[value_index++] = val;
  4298. found = true;
  4299. break;
  4300. }
  4301. }
  4302. }
  4303. if (!found) {
  4304. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4305. }
  4306. }
  4307. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  4308. return res;
  4309. } else {
  4310. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4311. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4312. defer (gb_free(heap_allocator(), values));
  4313. for (isize i = 0; i < elem_count; i++) {
  4314. TypeAndValue tav = cl->elems[i]->tav;
  4315. GB_ASSERT(tav.mode != Addressing_Invalid);
  4316. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4317. }
  4318. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4319. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4320. }
  4321. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  4322. return res;
  4323. }
  4324. } else if (is_type_simd_vector(type)) {
  4325. ast_node(cl, CompoundLit, value.value_compound);
  4326. Type *elem_type = type->SimdVector.elem;
  4327. isize elem_count = cl->elems.count;
  4328. if (elem_count == 0) {
  4329. return lb_const_nil(m, original_type);
  4330. }
  4331. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4332. isize total_elem_count = type->SimdVector.count;
  4333. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, total_elem_count);
  4334. defer (gb_free(heap_allocator(), values));
  4335. for (isize i = 0; i < elem_count; i++) {
  4336. TypeAndValue tav = cl->elems[i]->tav;
  4337. GB_ASSERT(tav.mode != Addressing_Invalid);
  4338. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4339. }
  4340. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  4341. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4342. }
  4343. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  4344. return res;
  4345. } else if (is_type_struct(type)) {
  4346. ast_node(cl, CompoundLit, value.value_compound);
  4347. if (cl->elems.count == 0) {
  4348. return lb_const_nil(m, original_type);
  4349. }
  4350. isize offset = 0;
  4351. if (type->Struct.custom_align > 0) {
  4352. offset = 1;
  4353. }
  4354. isize value_count = type->Struct.fields.count + offset;
  4355. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, value_count);
  4356. bool *visited = gb_alloc_array(heap_allocator(), bool, value_count);
  4357. defer (gb_free(heap_allocator(), values));
  4358. defer (gb_free(heap_allocator(), visited));
  4359. if (cl->elems.count > 0) {
  4360. if (cl->elems[0]->kind == Ast_FieldValue) {
  4361. isize elem_count = cl->elems.count;
  4362. for (isize i = 0; i < elem_count; i++) {
  4363. ast_node(fv, FieldValue, cl->elems[i]);
  4364. String name = fv->field->Ident.token.string;
  4365. TypeAndValue tav = fv->value->tav;
  4366. GB_ASSERT(tav.mode != Addressing_Invalid);
  4367. Selection sel = lookup_field(type, name, false);
  4368. Entity *f = type->Struct.fields[sel.index[0]];
  4369. if (elem_type_can_be_constant(f->type)) {
  4370. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  4371. visited[offset+f->Variable.field_index] = true;
  4372. }
  4373. }
  4374. } else {
  4375. for_array(i, cl->elems) {
  4376. Entity *f = type->Struct.fields[i];
  4377. TypeAndValue tav = cl->elems[i]->tav;
  4378. ExactValue val = {};
  4379. if (tav.mode != Addressing_Invalid) {
  4380. val = tav.value;
  4381. }
  4382. if (elem_type_can_be_constant(f->type)) {
  4383. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  4384. visited[offset+f->Variable.field_index] = true;
  4385. }
  4386. }
  4387. }
  4388. }
  4389. for (isize i = 0; i < type->Struct.fields.count; i++) {
  4390. if (!visited[offset+i]) {
  4391. GB_ASSERT(values[offset+i] == nullptr);
  4392. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  4393. }
  4394. }
  4395. if (type->Struct.custom_align > 0) {
  4396. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  4397. }
  4398. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  4399. return res;
  4400. } else if (is_type_bit_set(type)) {
  4401. ast_node(cl, CompoundLit, value.value_compound);
  4402. if (cl->elems.count == 0) {
  4403. return lb_const_nil(m, original_type);
  4404. }
  4405. i64 sz = type_size_of(type);
  4406. if (sz == 0) {
  4407. return lb_const_nil(m, original_type);
  4408. }
  4409. u64 bits = 0;
  4410. for_array(i, cl->elems) {
  4411. Ast *e = cl->elems[i];
  4412. GB_ASSERT(e->kind != Ast_FieldValue);
  4413. TypeAndValue tav = e->tav;
  4414. if (tav.mode != Addressing_Constant) {
  4415. continue;
  4416. }
  4417. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  4418. i64 v = big_int_to_i64(&tav.value.value_integer);
  4419. i64 lower = type->BitSet.lower;
  4420. bits |= 1ull<<cast(u64)(v-lower);
  4421. }
  4422. if (is_type_different_to_arch_endianness(type)) {
  4423. i64 size = type_size_of(type);
  4424. switch (size) {
  4425. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  4426. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  4427. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  4428. }
  4429. }
  4430. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  4431. return res;
  4432. } else {
  4433. return lb_const_nil(m, original_type);
  4434. }
  4435. break;
  4436. case ExactValue_Procedure:
  4437. {
  4438. Ast *expr = value.value_procedure;
  4439. GB_ASSERT(expr != nullptr);
  4440. if (expr->kind == Ast_ProcLit) {
  4441. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4442. }
  4443. }
  4444. break;
  4445. case ExactValue_Typeid:
  4446. return lb_typeid(m, value.value_typeid, original_type);
  4447. }
  4448. return lb_const_nil(m, original_type);
  4449. }
  4450. u64 lb_generate_source_code_location_hash(TokenPos const &pos) {
  4451. u64 h = 0xcbf29ce484222325;
  4452. for (isize i = 0; i < pos.file.len; i++) {
  4453. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  4454. }
  4455. h = h ^ (u64(pos.line) * 0x100000001b3);
  4456. h = h ^ (u64(pos.column) * 0x100000001b3);
  4457. return h;
  4458. }
  4459. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  4460. lbModule *m = p->module;
  4461. LLVMValueRef fields[5] = {};
  4462. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  4463. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  4464. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  4465. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  4466. fields[4]/*hash*/ = lb_const_int(m, t_u64, lb_generate_source_code_location_hash(pos)).value;
  4467. lbValue res = {};
  4468. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, 5);
  4469. res.type = t_source_code_location;
  4470. return res;
  4471. }
  4472. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  4473. String proc_name = {};
  4474. if (p->entity) {
  4475. proc_name = p->entity->token.string;
  4476. }
  4477. TokenPos pos = {};
  4478. if (node) {
  4479. pos = ast_token(node).pos;
  4480. }
  4481. return lb_emit_source_code_location(p, proc_name, pos);
  4482. }
  4483. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  4484. switch (op) {
  4485. case Token_Add:
  4486. return x;
  4487. case Token_Not: // Boolean not
  4488. case Token_Xor: // Bitwise not
  4489. case Token_Sub: // Number negation
  4490. break;
  4491. case Token_Pointer:
  4492. GB_PANIC("This should be handled elsewhere");
  4493. break;
  4494. }
  4495. if (is_type_array(x.type)) {
  4496. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  4497. Type *tl = base_type(x.type);
  4498. lbValue val = lb_address_from_load_or_generate_local(p, x);
  4499. GB_ASSERT(is_type_array(type));
  4500. Type *elem_type = base_array_type(type);
  4501. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4502. lbAddr res_addr = lb_add_local_generated(p, type, false);
  4503. lbValue res = lb_addr_get_ptr(p, res_addr);
  4504. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4505. i32 count = cast(i32)tl->Array.count;
  4506. if (inline_array_arith) {
  4507. // inline
  4508. for (i32 i = 0; i < count; i++) {
  4509. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  4510. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4511. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  4512. }
  4513. } else {
  4514. auto loop_data = lb_loop_start(p, count, t_i32);
  4515. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  4516. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4517. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  4518. lb_loop_end(p, loop_data);
  4519. }
  4520. return lb_emit_load(p, res);
  4521. }
  4522. if (op == Token_Xor) {
  4523. lbValue cmp = {};
  4524. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  4525. cmp.type = x.type;
  4526. return lb_emit_conv(p, cmp, type);
  4527. }
  4528. if (op == Token_Not) {
  4529. lbValue cmp = {};
  4530. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  4531. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  4532. cmp.type = t_llvm_bool;
  4533. return lb_emit_conv(p, cmp, type);
  4534. }
  4535. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4536. Type *platform_type = integer_endian_type_to_platform_type(type);
  4537. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4538. lbValue res = {};
  4539. res.value = LLVMBuildNeg(p->builder, v.value, "");
  4540. res.type = platform_type;
  4541. return lb_emit_byte_swap(p, res, type);
  4542. }
  4543. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4544. Type *platform_type = integer_endian_type_to_platform_type(type);
  4545. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4546. lbValue res = {};
  4547. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  4548. res.type = platform_type;
  4549. return lb_emit_byte_swap(p, res, type);
  4550. }
  4551. lbValue res = {};
  4552. switch (op) {
  4553. case Token_Not: // Boolean not
  4554. case Token_Xor: // Bitwise not
  4555. res.value = LLVMBuildNot(p->builder, x.value, "");
  4556. res.type = x.type;
  4557. return res;
  4558. case Token_Sub: // Number negation
  4559. if (is_type_integer(x.type)) {
  4560. res.value = LLVMBuildNeg(p->builder, x.value, "");
  4561. } else if (is_type_float(x.type)) {
  4562. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  4563. } else if (is_type_complex(x.type)) {
  4564. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4565. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4566. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4567. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4568. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4569. return lb_addr_load(p, addr);
  4570. } else if (is_type_quaternion(x.type)) {
  4571. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4572. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4573. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  4574. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  4575. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4576. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4577. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4578. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  4579. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  4580. return lb_addr_load(p, addr);
  4581. } else {
  4582. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  4583. }
  4584. res.type = x.type;
  4585. return res;
  4586. }
  4587. return res;
  4588. }
  4589. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  4590. lbModule *m = p->module;
  4591. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  4592. lhs = lb_emit_conv(p, lhs, type);
  4593. rhs = lb_emit_conv(p, rhs, type);
  4594. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  4595. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4596. GB_ASSERT(is_type_array(type));
  4597. Type *elem_type = base_array_type(type);
  4598. lbAddr res = lb_add_local_generated(p, type, false);
  4599. i64 count = base_type(type)->Array.count;
  4600. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4601. if (inline_array_arith) {
  4602. for (i64 i = 0; i < count; i++) {
  4603. lbValue a = lb_emit_load(p, lb_emit_array_epi(p, x, i));
  4604. lbValue b = lb_emit_load(p, lb_emit_array_epi(p, y, i));
  4605. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4606. lb_emit_store(p, lb_emit_array_epi(p, res.addr, i), c);
  4607. }
  4608. } else {
  4609. auto loop_data = lb_loop_start(p, count);
  4610. lbValue a = lb_emit_load(p, lb_emit_array_ep(p, x, loop_data.idx));
  4611. lbValue b = lb_emit_load(p, lb_emit_array_ep(p, y, loop_data.idx));
  4612. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4613. lb_emit_store(p, lb_emit_array_ep(p, res.addr, loop_data.idx), c);
  4614. lb_loop_end(p, loop_data);
  4615. }
  4616. return lb_addr_load(p, res);
  4617. } else if (is_type_complex(type)) {
  4618. lhs = lb_emit_conv(p, lhs, type);
  4619. rhs = lb_emit_conv(p, rhs, type);
  4620. Type *ft = base_complex_elem_type(type);
  4621. if (op == Token_Quo) {
  4622. auto args = array_make<lbValue>(heap_allocator(), 2);
  4623. args[0] = lhs;
  4624. args[1] = rhs;
  4625. switch (type_size_of(ft)) {
  4626. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  4627. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  4628. default: GB_PANIC("Unknown float type"); break;
  4629. }
  4630. }
  4631. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4632. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  4633. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  4634. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  4635. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  4636. lbValue real = {};
  4637. lbValue imag = {};
  4638. switch (op) {
  4639. case Token_Add:
  4640. real = lb_emit_arith(p, Token_Add, a, c, ft);
  4641. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  4642. break;
  4643. case Token_Sub:
  4644. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  4645. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  4646. break;
  4647. case Token_Mul: {
  4648. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  4649. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  4650. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  4651. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  4652. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  4653. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  4654. break;
  4655. }
  4656. }
  4657. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  4658. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  4659. return lb_addr_load(p, res);
  4660. } else if (is_type_quaternion(type)) {
  4661. lhs = lb_emit_conv(p, lhs, type);
  4662. rhs = lb_emit_conv(p, rhs, type);
  4663. Type *ft = base_complex_elem_type(type);
  4664. if (op == Token_Add || op == Token_Sub) {
  4665. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4666. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  4667. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  4668. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  4669. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  4670. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  4671. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  4672. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  4673. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  4674. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  4675. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  4676. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  4677. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  4678. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  4679. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  4680. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  4681. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  4682. return lb_addr_load(p, res);
  4683. } else if (op == Token_Mul) {
  4684. auto args = array_make<lbValue>(heap_allocator(), 2);
  4685. args[0] = lhs;
  4686. args[1] = rhs;
  4687. switch (8*type_size_of(ft)) {
  4688. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  4689. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  4690. default: GB_PANIC("Unknown float type"); break;
  4691. }
  4692. } else if (op == Token_Quo) {
  4693. auto args = array_make<lbValue>(heap_allocator(), 2);
  4694. args[0] = lhs;
  4695. args[1] = rhs;
  4696. switch (8*type_size_of(ft)) {
  4697. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  4698. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  4699. default: GB_PANIC("Unknown float type"); break;
  4700. }
  4701. }
  4702. }
  4703. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4704. switch (op) {
  4705. case Token_AndNot:
  4706. case Token_And:
  4707. case Token_Or:
  4708. case Token_Xor:
  4709. goto handle_op;
  4710. }
  4711. Type *platform_type = integer_endian_type_to_platform_type(type);
  4712. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4713. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4714. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4715. return lb_emit_byte_swap(p, res, type);
  4716. }
  4717. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4718. Type *platform_type = integer_endian_type_to_platform_type(type);
  4719. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4720. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4721. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4722. return lb_emit_byte_swap(p, res, type);
  4723. }
  4724. handle_op:
  4725. lhs = lb_emit_conv(p, lhs, type);
  4726. rhs = lb_emit_conv(p, rhs, type);
  4727. lbValue res = {};
  4728. res.type = type;
  4729. switch (op) {
  4730. case Token_Add:
  4731. if (is_type_float(type)) {
  4732. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  4733. return res;
  4734. }
  4735. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  4736. return res;
  4737. case Token_Sub:
  4738. if (is_type_float(type)) {
  4739. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  4740. return res;
  4741. }
  4742. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  4743. return res;
  4744. case Token_Mul:
  4745. if (is_type_float(type)) {
  4746. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  4747. return res;
  4748. }
  4749. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  4750. return res;
  4751. case Token_Quo:
  4752. if (is_type_float(type)) {
  4753. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  4754. return res;
  4755. } else if (is_type_unsigned(type)) {
  4756. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  4757. return res;
  4758. }
  4759. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  4760. return res;
  4761. case Token_Mod:
  4762. if (is_type_float(type)) {
  4763. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  4764. return res;
  4765. } else if (is_type_unsigned(type)) {
  4766. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  4767. return res;
  4768. }
  4769. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  4770. return res;
  4771. case Token_ModMod:
  4772. if (is_type_unsigned(type)) {
  4773. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  4774. return res;
  4775. } else {
  4776. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  4777. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  4778. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  4779. res.value = c;
  4780. return res;
  4781. }
  4782. case Token_And:
  4783. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  4784. return res;
  4785. case Token_Or:
  4786. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  4787. return res;
  4788. case Token_Xor:
  4789. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  4790. return res;
  4791. case Token_Shl:
  4792. {
  4793. rhs = lb_emit_conv(p, rhs, lhs.type);
  4794. LLVMValueRef lhsval = lhs.value;
  4795. LLVMValueRef bits = rhs.value;
  4796. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  4797. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  4798. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  4799. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  4800. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  4801. return res;
  4802. }
  4803. case Token_Shr:
  4804. {
  4805. rhs = lb_emit_conv(p, rhs, lhs.type);
  4806. LLVMValueRef lhsval = lhs.value;
  4807. LLVMValueRef bits = rhs.value;
  4808. bool is_unsigned = is_type_unsigned(type);
  4809. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  4810. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  4811. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  4812. if (is_unsigned) {
  4813. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  4814. } else {
  4815. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  4816. }
  4817. return res;
  4818. }
  4819. case Token_AndNot:
  4820. {
  4821. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  4822. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  4823. return res;
  4824. }
  4825. break;
  4826. }
  4827. GB_PANIC("unhandled operator of lb_emit_arith");
  4828. return {};
  4829. }
  4830. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  4831. ast_node(be, BinaryExpr, expr);
  4832. TypeAndValue tv = type_and_value_of_expr(expr);
  4833. switch (be->op.kind) {
  4834. case Token_Add:
  4835. case Token_Sub:
  4836. case Token_Mul:
  4837. case Token_Quo:
  4838. case Token_Mod:
  4839. case Token_ModMod:
  4840. case Token_And:
  4841. case Token_Or:
  4842. case Token_Xor:
  4843. case Token_AndNot:
  4844. case Token_Shl:
  4845. case Token_Shr: {
  4846. Type *type = default_type(tv.type);
  4847. lbValue left = lb_build_expr(p, be->left);
  4848. lbValue right = lb_build_expr(p, be->right);
  4849. return lb_emit_arith(p, be->op.kind, left, right, type);
  4850. }
  4851. case Token_CmpEq:
  4852. case Token_NotEq:
  4853. case Token_Lt:
  4854. case Token_LtEq:
  4855. case Token_Gt:
  4856. case Token_GtEq:
  4857. {
  4858. lbValue left = {};
  4859. lbValue right = {};
  4860. if (be->left->tav.mode == Addressing_Type) {
  4861. left = lb_typeid(p->module, be->left->tav.type, t_typeid);
  4862. }
  4863. if (be->right->tav.mode == Addressing_Type) {
  4864. right = lb_typeid(p->module, be->right->tav.type, t_typeid);
  4865. }
  4866. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  4867. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  4868. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  4869. Type *type = default_type(tv.type);
  4870. return lb_emit_conv(p, cmp, type);
  4871. }
  4872. case Token_CmpAnd:
  4873. case Token_CmpOr:
  4874. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  4875. case Token_in:
  4876. case Token_not_in:
  4877. {
  4878. lbValue left = lb_build_expr(p, be->left);
  4879. Type *type = default_type(tv.type);
  4880. lbValue right = lb_build_expr(p, be->right);
  4881. Type *rt = base_type(right.type);
  4882. switch (rt->kind) {
  4883. case Type_Map:
  4884. {
  4885. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  4886. lbValue h = lb_gen_map_header(p, addr, rt);
  4887. lbValue key = lb_gen_map_key(p, left, rt->Map.key);
  4888. auto args = array_make<lbValue>(heap_allocator(), 2);
  4889. args[0] = h;
  4890. args[1] = key;
  4891. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  4892. if (be->op.kind == Token_in) {
  4893. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  4894. } else {
  4895. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  4896. }
  4897. }
  4898. break;
  4899. case Type_BitSet:
  4900. {
  4901. Type *key_type = rt->BitSet.elem;
  4902. GB_ASSERT(are_types_identical(left.type, key_type));
  4903. Type *it = bit_set_to_int(rt);
  4904. left = lb_emit_conv(p, left, it);
  4905. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  4906. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  4907. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  4908. bit = lb_emit_conv(p, bit, it);
  4909. lbValue old_value = lb_emit_transmute(p, right, it);
  4910. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  4911. if (be->op.kind == Token_in) {
  4912. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  4913. } else {
  4914. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  4915. }
  4916. }
  4917. break;
  4918. default:
  4919. GB_PANIC("Invalid 'in' type");
  4920. }
  4921. break;
  4922. }
  4923. break;
  4924. default:
  4925. GB_PANIC("Invalid binary expression");
  4926. break;
  4927. }
  4928. return {};
  4929. }
  4930. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  4931. Type *prev_src = src;
  4932. // Type *prev_dst = dst;
  4933. src = base_type(type_deref(src));
  4934. // dst = base_type(type_deref(dst));
  4935. bool src_is_ptr = src != prev_src;
  4936. // bool dst_is_ptr = dst != prev_dst;
  4937. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  4938. for_array(i, src->Struct.fields) {
  4939. Entity *f = src->Struct.fields[i];
  4940. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  4941. if (are_types_identical(dst, f->type)) {
  4942. return f->token.string;
  4943. }
  4944. if (src_is_ptr && is_type_pointer(dst)) {
  4945. if (are_types_identical(type_deref(dst), f->type)) {
  4946. return f->token.string;
  4947. }
  4948. }
  4949. if (is_type_struct(f->type)) {
  4950. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  4951. if (name.len > 0) {
  4952. return name;
  4953. }
  4954. }
  4955. }
  4956. }
  4957. return str_lit("");
  4958. }
  4959. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  4960. GB_ASSERT(is_type_pointer(value.type));
  4961. GB_ASSERT(is_type_pointer(t));
  4962. GB_ASSERT(lb_is_const(value));
  4963. lbValue res = {};
  4964. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  4965. res.type = t;
  4966. return res;
  4967. }
  4968. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  4969. lbModule *m = p->module;
  4970. t = reduce_tuple_to_single_type(t);
  4971. Type *src_type = value.type;
  4972. if (are_types_identical(t, src_type)) {
  4973. return value;
  4974. }
  4975. Type *src = core_type(src_type);
  4976. Type *dst = core_type(t);
  4977. GB_ASSERT(src != nullptr);
  4978. GB_ASSERT(dst != nullptr);
  4979. if (is_type_untyped_nil(src)) {
  4980. return lb_const_nil(m, t);
  4981. }
  4982. if (is_type_untyped_undef(src)) {
  4983. return lb_const_undef(m, t);
  4984. }
  4985. if (LLVMIsConstant(value.value)) {
  4986. if (is_type_any(dst)) {
  4987. Type *st = default_type(src_type);
  4988. lbAddr default_value = lb_add_local_generated(p, st, false);
  4989. lb_addr_store(p, default_value, value);
  4990. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  4991. lbValue id = lb_typeid(m, st);
  4992. lbAddr res = lb_add_local_generated(p, t, false);
  4993. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  4994. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  4995. lb_emit_store(p, a0, data);
  4996. lb_emit_store(p, a1, id);
  4997. return lb_addr_load(p, res);
  4998. } else if (dst->kind == Type_Basic) {
  4999. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5000. String str = lb_get_const_string(m, value);
  5001. lbValue res = {};
  5002. res.type = t;
  5003. res.value = llvm_cstring(m, str);
  5004. return res;
  5005. }
  5006. // if (is_type_float(dst)) {
  5007. // return value;
  5008. // } else if (is_type_integer(dst)) {
  5009. // return value;
  5010. // }
  5011. // ExactValue ev = value->Constant.value;
  5012. // if (is_type_float(dst)) {
  5013. // ev = exact_value_to_float(ev);
  5014. // } else if (is_type_complex(dst)) {
  5015. // ev = exact_value_to_complex(ev);
  5016. // } else if (is_type_quaternion(dst)) {
  5017. // ev = exact_value_to_quaternion(ev);
  5018. // } else if (is_type_string(dst)) {
  5019. // // Handled elsewhere
  5020. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5021. // } else if (is_type_integer(dst)) {
  5022. // ev = exact_value_to_integer(ev);
  5023. // } else if (is_type_pointer(dst)) {
  5024. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5025. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5026. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5027. // }
  5028. // return lb_const_value(p->module, t, ev);
  5029. }
  5030. }
  5031. if (are_types_identical(src, dst)) {
  5032. if (!are_types_identical(src_type, t)) {
  5033. return lb_emit_transmute(p, value, t);
  5034. }
  5035. return value;
  5036. }
  5037. // bool <-> llvm bool
  5038. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5039. lbValue res = {};
  5040. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5041. res.type = dst;
  5042. return res;
  5043. }
  5044. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5045. lbValue res = {};
  5046. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5047. res.type = dst;
  5048. return res;
  5049. }
  5050. // integer -> integer
  5051. if (is_type_integer(src) && is_type_integer(dst)) {
  5052. GB_ASSERT(src->kind == Type_Basic &&
  5053. dst->kind == Type_Basic);
  5054. i64 sz = type_size_of(default_type(src));
  5055. i64 dz = type_size_of(default_type(dst));
  5056. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5057. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5058. value = lb_emit_byte_swap(p, value, platform_src_type);
  5059. }
  5060. LLVMOpcode op = LLVMTrunc;
  5061. if (dz < sz) {
  5062. op = LLVMTrunc;
  5063. } else if (dz == sz) {
  5064. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5065. // NOTE(bill): Copy the value just for type correctness
  5066. op = LLVMBitCast;
  5067. } else if (dz > sz) {
  5068. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5069. }
  5070. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5071. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5072. lbValue res = {};
  5073. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5074. res.type = t;
  5075. return lb_emit_byte_swap(p, res, t);
  5076. } else {
  5077. lbValue res = {};
  5078. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5079. res.type = t;
  5080. return res;
  5081. }
  5082. }
  5083. // boolean -> boolean/integer
  5084. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5085. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5086. lbValue res = {};
  5087. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5088. res.type = t;
  5089. return res;
  5090. }
  5091. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5092. return lb_emit_transmute(p, value, dst);
  5093. }
  5094. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5095. return lb_emit_transmute(p, value, dst);
  5096. }
  5097. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5098. return lb_emit_transmute(p, value, dst);
  5099. }
  5100. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5101. return lb_emit_transmute(p, value, dst);
  5102. }
  5103. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5104. lbValue c = lb_emit_conv(p, value, t_cstring);
  5105. auto args = array_make<lbValue>(heap_allocator(), 1);
  5106. args[0] = c;
  5107. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5108. return lb_emit_conv(p, s, dst);
  5109. }
  5110. // integer -> boolean
  5111. if (is_type_integer(src) && is_type_boolean(dst)) {
  5112. lbValue res = {};
  5113. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5114. res.type = t_llvm_bool;
  5115. return lb_emit_conv(p, res, t);
  5116. }
  5117. // float -> float
  5118. if (is_type_float(src) && is_type_float(dst)) {
  5119. gbAllocator a = heap_allocator();
  5120. i64 sz = type_size_of(src);
  5121. i64 dz = type_size_of(dst);
  5122. if (dz == sz) {
  5123. if (types_have_same_internal_endian(src, dst)) {
  5124. lbValue res = {};
  5125. res.type = t;
  5126. res.value = value.value;
  5127. return res;
  5128. } else {
  5129. return lb_emit_byte_swap(p, value, t);
  5130. }
  5131. }
  5132. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5133. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5134. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5135. lbValue res = {};
  5136. res = lb_emit_conv(p, value, platform_src_type);
  5137. res = lb_emit_conv(p, res, platform_dst_type);
  5138. if (is_type_different_to_arch_endianness(dst)) {
  5139. res = lb_emit_byte_swap(p, res, t);
  5140. }
  5141. return lb_emit_conv(p, res, t);
  5142. }
  5143. lbValue res = {};
  5144. res.type = t;
  5145. if (dz >= sz) {
  5146. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5147. } else {
  5148. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5149. }
  5150. return res;
  5151. }
  5152. if (is_type_complex(src) && is_type_complex(dst)) {
  5153. Type *ft = base_complex_elem_type(dst);
  5154. lbAddr gen = lb_add_local_generated(p, dst, false);
  5155. lbValue gp = lb_addr_get_ptr(p, gen);
  5156. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5157. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5158. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5159. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5160. return lb_addr_load(p, gen);
  5161. }
  5162. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5163. // @QuaternionLayout
  5164. Type *ft = base_complex_elem_type(dst);
  5165. lbAddr gen = lb_add_local_generated(p, dst, false);
  5166. lbValue gp = lb_addr_get_ptr(p, gen);
  5167. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5168. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5169. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5170. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5171. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5172. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5173. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5174. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5175. return lb_addr_load(p, gen);
  5176. }
  5177. if (is_type_float(src) && is_type_complex(dst)) {
  5178. Type *ft = base_complex_elem_type(dst);
  5179. lbAddr gen = lb_add_local_generated(p, dst, true);
  5180. lbValue gp = lb_addr_get_ptr(p, gen);
  5181. lbValue real = lb_emit_conv(p, value, ft);
  5182. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5183. return lb_addr_load(p, gen);
  5184. }
  5185. if (is_type_float(src) && is_type_quaternion(dst)) {
  5186. Type *ft = base_complex_elem_type(dst);
  5187. lbAddr gen = lb_add_local_generated(p, dst, true);
  5188. lbValue gp = lb_addr_get_ptr(p, gen);
  5189. lbValue real = lb_emit_conv(p, value, ft);
  5190. // @QuaternionLayout
  5191. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5192. return lb_addr_load(p, gen);
  5193. }
  5194. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5195. Type *ft = base_complex_elem_type(dst);
  5196. lbAddr gen = lb_add_local_generated(p, dst, true);
  5197. lbValue gp = lb_addr_get_ptr(p, gen);
  5198. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5199. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5200. // @QuaternionLayout
  5201. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5202. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5203. return lb_addr_load(p, gen);
  5204. }
  5205. // float <-> integer
  5206. if (is_type_float(src) && is_type_integer(dst)) {
  5207. lbValue res = {};
  5208. res.type = t;
  5209. if (is_type_unsigned(dst)) {
  5210. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5211. } else {
  5212. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5213. }
  5214. return res;
  5215. }
  5216. if (is_type_integer(src) && is_type_float(dst)) {
  5217. lbValue res = {};
  5218. res.type = t;
  5219. if (is_type_unsigned(src)) {
  5220. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5221. } else {
  5222. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5223. }
  5224. return res;
  5225. }
  5226. // Pointer <-> uintptr
  5227. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5228. lbValue res = {};
  5229. res.type = t;
  5230. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5231. return res;
  5232. }
  5233. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5234. lbValue res = {};
  5235. res.type = t;
  5236. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5237. return res;
  5238. }
  5239. #if 1
  5240. if (is_type_union(dst)) {
  5241. for_array(i, dst->Union.variants) {
  5242. Type *vt = dst->Union.variants[i];
  5243. if (are_types_identical(vt, src_type)) {
  5244. lbAddr parent = lb_add_local_generated(p, t, true);
  5245. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5246. return lb_addr_load(p, parent);
  5247. }
  5248. }
  5249. }
  5250. #endif
  5251. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5252. // subtype polymorphism casting
  5253. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5254. Type *st = type_deref(src_type);
  5255. Type *pst = st;
  5256. st = type_deref(st);
  5257. bool st_is_ptr = is_type_pointer(src_type);
  5258. st = base_type(st);
  5259. Type *dt = t;
  5260. bool dt_is_ptr = type_deref(dt) != dt;
  5261. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5262. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  5263. if (field_name.len > 0) {
  5264. // NOTE(bill): It can be casted
  5265. Selection sel = lookup_field(st, field_name, false, true);
  5266. if (sel.entity != nullptr) {
  5267. if (st_is_ptr) {
  5268. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  5269. Type *rt = res.type;
  5270. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5271. res = lb_emit_load(p, res);
  5272. }
  5273. return res;
  5274. } else {
  5275. if (is_type_pointer(value.type)) {
  5276. Type *rt = value.type;
  5277. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5278. value = lb_emit_load(p, value);
  5279. } else {
  5280. value = lb_emit_deep_field_gep(p, value, sel);
  5281. return lb_emit_load(p, value);
  5282. }
  5283. }
  5284. return lb_emit_deep_field_ev(p, value, sel);
  5285. }
  5286. } else {
  5287. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5288. }
  5289. }
  5290. }
  5291. // Pointer <-> Pointer
  5292. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5293. lbValue res = {};
  5294. res.type = t;
  5295. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5296. return res;
  5297. }
  5298. // proc <-> proc
  5299. if (is_type_proc(src) && is_type_proc(dst)) {
  5300. lbValue res = {};
  5301. res.type = t;
  5302. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5303. return res;
  5304. }
  5305. // pointer -> proc
  5306. if (is_type_pointer(src) && is_type_proc(dst)) {
  5307. lbValue res = {};
  5308. res.type = t;
  5309. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5310. return res;
  5311. }
  5312. // proc -> pointer
  5313. if (is_type_proc(src) && is_type_pointer(dst)) {
  5314. lbValue res = {};
  5315. res.type = t;
  5316. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5317. return res;
  5318. }
  5319. // []byte/[]u8 <-> string
  5320. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5321. return lb_emit_transmute(p, value, t);
  5322. }
  5323. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5324. return lb_emit_transmute(p, value, t);
  5325. }
  5326. if (is_type_array(dst)) {
  5327. Type *elem = dst->Array.elem;
  5328. lbValue e = lb_emit_conv(p, value, elem);
  5329. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5330. lbAddr v = lb_add_local_generated(p, t, false);
  5331. isize index_count = cast(isize)dst->Array.count;
  5332. for (isize i = 0; i < index_count; i++) {
  5333. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  5334. lb_emit_store(p, elem, e);
  5335. }
  5336. return lb_addr_load(p, v);
  5337. }
  5338. if (is_type_any(dst)) {
  5339. if (is_type_untyped_nil(src)) {
  5340. return lb_const_nil(p->module, t);
  5341. }
  5342. if (is_type_untyped_undef(src)) {
  5343. return lb_const_undef(p->module, t);
  5344. }
  5345. lbAddr result = lb_add_local_generated(p, t, true);
  5346. Type *st = default_type(src_type);
  5347. lbValue data = lb_address_from_load_or_generate_local(p, value);
  5348. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  5349. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5350. data = lb_emit_conv(p, data, t_rawptr);
  5351. lbValue id = lb_typeid(p->module, st);
  5352. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  5353. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  5354. lb_emit_store(p, any_data, data);
  5355. lb_emit_store(p, any_id, id);
  5356. return lb_addr_load(p, result);
  5357. }
  5358. if (is_type_untyped(src)) {
  5359. if (is_type_string(src) && is_type_string(dst)) {
  5360. lbAddr result = lb_add_local_generated(p, t, false);
  5361. lb_addr_store(p, result, value);
  5362. return lb_addr_load(p, result);
  5363. }
  5364. }
  5365. gb_printf_err("%.*s\n", LIT(p->name));
  5366. gb_printf_err("lb_emit_conv: src -> dst\n");
  5367. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5368. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5369. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  5370. gb_printf_err("Not Identical %p != %p\n", src, dst);
  5371. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5372. type_to_string(src_type), type_to_string(t),
  5373. LIT(p->name));
  5374. return {};
  5375. }
  5376. bool lb_is_type_aggregate(Type *t) {
  5377. t = base_type(t);
  5378. switch (t->kind) {
  5379. case Type_Basic:
  5380. switch (t->Basic.kind) {
  5381. case Basic_string:
  5382. case Basic_any:
  5383. return true;
  5384. // case Basic_complex32:
  5385. case Basic_complex64:
  5386. case Basic_complex128:
  5387. case Basic_quaternion128:
  5388. case Basic_quaternion256:
  5389. return true;
  5390. }
  5391. break;
  5392. case Type_Pointer:
  5393. return false;
  5394. case Type_Array:
  5395. case Type_Slice:
  5396. case Type_Struct:
  5397. case Type_Union:
  5398. case Type_Tuple:
  5399. case Type_DynamicArray:
  5400. case Type_Map:
  5401. case Type_BitField:
  5402. case Type_SimdVector:
  5403. return true;
  5404. case Type_Named:
  5405. return lb_is_type_aggregate(t->Named.base);
  5406. }
  5407. return false;
  5408. }
  5409. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  5410. Type *src_type = value.type;
  5411. if (are_types_identical(t, src_type)) {
  5412. return value;
  5413. }
  5414. lbValue res = {};
  5415. res.type = t;
  5416. Type *src = base_type(src_type);
  5417. Type *dst = base_type(t);
  5418. lbModule *m = p->module;
  5419. i64 sz = type_size_of(src);
  5420. i64 dz = type_size_of(dst);
  5421. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5422. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5423. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5424. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5425. return res;
  5426. }
  5427. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5428. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5429. return res;
  5430. }
  5431. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5432. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5433. return res;
  5434. }
  5435. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5436. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5437. return res;
  5438. }
  5439. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5440. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5441. return res;
  5442. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5443. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5444. return res;
  5445. }
  5446. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5447. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  5448. return res;
  5449. }
  5450. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  5451. lbValue s = lb_address_from_load_or_generate_local(p, value);
  5452. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  5453. return lb_emit_load(p, d);
  5454. }
  5455. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  5456. // GB_PANIC("lb_emit_transmute");
  5457. return res;
  5458. }
  5459. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  5460. GB_ASSERT(addr.kind == lbAddr_Context);
  5461. GB_ASSERT(addr.ctx.sel.index.count == 0);
  5462. lbModule *m = p->module;
  5463. gbAllocator a = heap_allocator();
  5464. auto args = array_make<lbValue>(a, 1);
  5465. args[0] = addr.addr;
  5466. lb_emit_runtime_call(p, "__init_context", args);
  5467. }
  5468. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  5469. ctx.kind = lbAddr_Context;
  5470. lbContextData cd = {ctx, p->scope_index};
  5471. array_add(&p->context_stack, cd);
  5472. }
  5473. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  5474. if (p->context_stack.count > 0) {
  5475. return p->context_stack[p->context_stack.count-1].ctx;
  5476. }
  5477. Type *pt = base_type(p->type);
  5478. GB_ASSERT(pt->kind == Type_Proc);
  5479. {
  5480. lbAddr c = lb_add_local_generated(p, t_context, false);
  5481. c.kind = lbAddr_Context;
  5482. lb_emit_init_context(p, c);
  5483. lb_push_context_onto_stack(p, c);
  5484. return c;
  5485. }
  5486. }
  5487. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  5488. if (LLVMIsALoadInst(value.value)) {
  5489. lbValue res = {};
  5490. res.value = LLVMGetOperand(value.value, 0);
  5491. res.type = alloc_type_pointer(value.type);
  5492. return res;
  5493. }
  5494. GB_ASSERT(is_type_typed(value.type));
  5495. lbAddr res = lb_add_local_generated(p, value.type, false);
  5496. lb_addr_store(p, res, value);
  5497. return res.addr;
  5498. }
  5499. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  5500. if (LLVMIsALoadInst(value.value)) {
  5501. lbValue res = {};
  5502. res.value = LLVMGetOperand(value.value, 0);
  5503. res.type = alloc_type_pointer(value.type);
  5504. return res;
  5505. }
  5506. GB_PANIC("lb_address_from_load");
  5507. return {};
  5508. }
  5509. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  5510. i64 type_alignment = type_align_of(new_type);
  5511. if (alignment < type_alignment) {
  5512. alignment = type_alignment;
  5513. }
  5514. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  5515. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  5516. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  5517. lb_addr_store(p, ptr, val);
  5518. ptr.kind = lbAddr_Context;
  5519. return ptr.addr;
  5520. }
  5521. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  5522. gbAllocator a = heap_allocator();
  5523. GB_ASSERT(is_type_pointer(s.type));
  5524. Type *t = base_type(type_deref(s.type));
  5525. Type *result_type = nullptr;
  5526. if (t->kind == Type_Opaque) {
  5527. t = t->Opaque.elem;
  5528. }
  5529. if (is_type_relative_pointer(t)) {
  5530. s = lb_addr_get_ptr(p, lb_addr(s));
  5531. }
  5532. if (is_type_struct(t)) {
  5533. result_type = get_struct_field_type(t, index);
  5534. } else if (is_type_union(t)) {
  5535. GB_ASSERT(index == -1);
  5536. return lb_emit_union_tag_ptr(p, s);
  5537. } else if (is_type_tuple(t)) {
  5538. GB_ASSERT(t->Tuple.variables.count > 0);
  5539. result_type = t->Tuple.variables[index]->type;
  5540. } else if (is_type_complex(t)) {
  5541. Type *ft = base_complex_elem_type(t);
  5542. switch (index) {
  5543. case 0: result_type = ft; break;
  5544. case 1: result_type = ft; break;
  5545. }
  5546. } else if (is_type_quaternion(t)) {
  5547. Type *ft = base_complex_elem_type(t);
  5548. switch (index) {
  5549. case 0: result_type = ft; break;
  5550. case 1: result_type = ft; break;
  5551. case 2: result_type = ft; break;
  5552. case 3: result_type = ft; break;
  5553. }
  5554. } else if (is_type_slice(t)) {
  5555. switch (index) {
  5556. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5557. case 1: result_type = t_int; break;
  5558. }
  5559. } else if (is_type_string(t)) {
  5560. switch (index) {
  5561. case 0: result_type = t_u8_ptr; break;
  5562. case 1: result_type = t_int; break;
  5563. }
  5564. } else if (is_type_any(t)) {
  5565. switch (index) {
  5566. case 0: result_type = t_rawptr; break;
  5567. case 1: result_type = t_typeid; break;
  5568. }
  5569. } else if (is_type_dynamic_array(t)) {
  5570. switch (index) {
  5571. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5572. case 1: result_type = t_int; break;
  5573. case 2: result_type = t_int; break;
  5574. case 3: result_type = t_allocator; break;
  5575. }
  5576. } else if (is_type_map(t)) {
  5577. init_map_internal_types(t);
  5578. Type *itp = alloc_type_pointer(t->Map.internal_type);
  5579. s = lb_emit_transmute(p, s, itp);
  5580. Type *gst = t->Map.internal_type;
  5581. GB_ASSERT(gst->kind == Type_Struct);
  5582. switch (index) {
  5583. case 0: result_type = get_struct_field_type(gst, 0); break;
  5584. case 1: result_type = get_struct_field_type(gst, 1); break;
  5585. }
  5586. } else if (is_type_array(t)) {
  5587. return lb_emit_array_epi(p, s, index);
  5588. } else if (is_type_relative_slice(t)) {
  5589. switch (index) {
  5590. case 0: result_type = t->RelativeSlice.base_integer; break;
  5591. case 1: result_type = t->RelativeSlice.base_integer; break;
  5592. }
  5593. } else {
  5594. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  5595. }
  5596. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  5597. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5598. index += 1;
  5599. }
  5600. if (lb_is_const(s)) {
  5601. lbModule *m = p->module;
  5602. lbValue res = {};
  5603. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  5604. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  5605. res.type = alloc_type_pointer(result_type);
  5606. return res;
  5607. } else {
  5608. lbValue res = {};
  5609. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  5610. res.type = alloc_type_pointer(result_type);
  5611. return res;
  5612. }
  5613. }
  5614. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  5615. if (LLVMIsALoadInst(s.value)) {
  5616. lbValue res = {};
  5617. res.value = LLVMGetOperand(s.value, 0);
  5618. res.type = alloc_type_pointer(s.type);
  5619. lbValue ptr = lb_emit_struct_ep(p, res, index);
  5620. return lb_emit_load(p, ptr);
  5621. }
  5622. gbAllocator a = heap_allocator();
  5623. Type *t = base_type(s.type);
  5624. Type *result_type = nullptr;
  5625. switch (t->kind) {
  5626. case Type_Basic:
  5627. switch (t->Basic.kind) {
  5628. case Basic_string:
  5629. switch (index) {
  5630. case 0: result_type = t_u8_ptr; break;
  5631. case 1: result_type = t_int; break;
  5632. }
  5633. break;
  5634. case Basic_any:
  5635. switch (index) {
  5636. case 0: result_type = t_rawptr; break;
  5637. case 1: result_type = t_typeid; break;
  5638. }
  5639. break;
  5640. case Basic_complex64: case Basic_complex128:
  5641. {
  5642. Type *ft = base_complex_elem_type(t);
  5643. switch (index) {
  5644. case 0: result_type = ft; break;
  5645. case 1: result_type = ft; break;
  5646. }
  5647. break;
  5648. }
  5649. case Basic_quaternion128: case Basic_quaternion256:
  5650. {
  5651. Type *ft = base_complex_elem_type(t);
  5652. switch (index) {
  5653. case 0: result_type = ft; break;
  5654. case 1: result_type = ft; break;
  5655. case 2: result_type = ft; break;
  5656. case 3: result_type = ft; break;
  5657. }
  5658. break;
  5659. }
  5660. }
  5661. break;
  5662. case Type_Struct:
  5663. result_type = get_struct_field_type(t, index);
  5664. break;
  5665. case Type_Union:
  5666. GB_ASSERT(index == -1);
  5667. // return lb_emit_union_tag_value(p, s);
  5668. GB_PANIC("lb_emit_union_tag_value");
  5669. case Type_Tuple:
  5670. GB_ASSERT(t->Tuple.variables.count > 0);
  5671. result_type = t->Tuple.variables[index]->type;
  5672. if (t->Tuple.variables.count == 1) {
  5673. return s;
  5674. }
  5675. break;
  5676. case Type_Slice:
  5677. switch (index) {
  5678. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5679. case 1: result_type = t_int; break;
  5680. }
  5681. break;
  5682. case Type_DynamicArray:
  5683. switch (index) {
  5684. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5685. case 1: result_type = t_int; break;
  5686. case 2: result_type = t_int; break;
  5687. case 3: result_type = t_allocator; break;
  5688. }
  5689. break;
  5690. case Type_Map:
  5691. {
  5692. init_map_internal_types(t);
  5693. Type *gst = t->Map.generated_struct_type;
  5694. switch (index) {
  5695. case 0: result_type = get_struct_field_type(gst, 0); break;
  5696. case 1: result_type = get_struct_field_type(gst, 1); break;
  5697. }
  5698. }
  5699. break;
  5700. case Type_Array:
  5701. result_type = t->Array.elem;
  5702. break;
  5703. default:
  5704. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  5705. break;
  5706. }
  5707. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  5708. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5709. index += 1;
  5710. }
  5711. lbValue res = {};
  5712. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  5713. res.type = result_type;
  5714. return res;
  5715. }
  5716. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  5717. GB_ASSERT(sel.index.count > 0);
  5718. Type *type = type_deref(e.type);
  5719. gbAllocator a = heap_allocator();
  5720. for_array(i, sel.index) {
  5721. i32 index = cast(i32)sel.index[i];
  5722. if (is_type_pointer(type)) {
  5723. type = type_deref(type);
  5724. e = lb_emit_load(p, e);
  5725. }
  5726. type = core_type(type);
  5727. if (type->kind == Type_Opaque) {
  5728. type = type->Opaque.elem;
  5729. }
  5730. if (is_type_quaternion(type)) {
  5731. e = lb_emit_struct_ep(p, e, index);
  5732. } else if (is_type_raw_union(type)) {
  5733. type = get_struct_field_type(type, index);
  5734. GB_ASSERT(is_type_pointer(e.type));
  5735. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  5736. } else if (is_type_struct(type)) {
  5737. type = get_struct_field_type(type, index);
  5738. e = lb_emit_struct_ep(p, e, index);
  5739. } else if (type->kind == Type_Union) {
  5740. GB_ASSERT(index == -1);
  5741. type = t_type_info_ptr;
  5742. e = lb_emit_struct_ep(p, e, index);
  5743. } else if (type->kind == Type_Tuple) {
  5744. type = type->Tuple.variables[index]->type;
  5745. e = lb_emit_struct_ep(p, e, index);
  5746. } else if (type->kind == Type_Basic) {
  5747. switch (type->Basic.kind) {
  5748. case Basic_any: {
  5749. if (index == 0) {
  5750. type = t_rawptr;
  5751. } else if (index == 1) {
  5752. type = t_type_info_ptr;
  5753. }
  5754. e = lb_emit_struct_ep(p, e, index);
  5755. break;
  5756. }
  5757. case Basic_string:
  5758. e = lb_emit_struct_ep(p, e, index);
  5759. break;
  5760. default:
  5761. GB_PANIC("un-gep-able type %s", type_to_string(type));
  5762. break;
  5763. }
  5764. } else if (type->kind == Type_Slice) {
  5765. e = lb_emit_struct_ep(p, e, index);
  5766. } else if (type->kind == Type_DynamicArray) {
  5767. e = lb_emit_struct_ep(p, e, index);
  5768. } else if (type->kind == Type_Array) {
  5769. e = lb_emit_array_epi(p, e, index);
  5770. } else if (type->kind == Type_Map) {
  5771. e = lb_emit_struct_ep(p, e, index);
  5772. } else if (type->kind == Type_RelativePointer) {
  5773. e = lb_emit_struct_ep(p, e, index);
  5774. } else {
  5775. GB_PANIC("un-gep-able type %s", type_to_string(type));
  5776. }
  5777. }
  5778. return e;
  5779. }
  5780. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  5781. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  5782. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  5783. return lb_emit_load(p, res);
  5784. }
  5785. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  5786. // NOTE(bill): The prev block may defer injection before it's terminator
  5787. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  5788. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  5789. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  5790. return;
  5791. }
  5792. isize prev_context_stack_count = p->context_stack.count;
  5793. defer (p->context_stack.count = prev_context_stack_count);
  5794. p->context_stack.count = d.context_stack_count;
  5795. lbBlock *b = lb_create_block(p, "defer");
  5796. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  5797. lb_emit_jump(p, b);
  5798. }
  5799. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  5800. lb_emit_jump(p, b);
  5801. }
  5802. lb_start_block(p, b);
  5803. if (d.kind == lbDefer_Node) {
  5804. lb_build_stmt(p, d.stmt);
  5805. } else if (d.kind == lbDefer_Instr) {
  5806. // NOTE(bill): Need to make a new copy
  5807. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  5808. LLVMInsertIntoBuilder(p->builder, instr);
  5809. } else if (d.kind == lbDefer_Proc) {
  5810. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  5811. }
  5812. }
  5813. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  5814. isize count = p->defer_stmts.count;
  5815. isize i = count;
  5816. while (i --> 0) {
  5817. lbDefer d = p->defer_stmts[i];
  5818. isize prev_context_stack_count = p->context_stack.count;
  5819. defer (p->context_stack.count = prev_context_stack_count);
  5820. p->context_stack.count = d.context_stack_count;
  5821. if (kind == lbDeferExit_Default) {
  5822. if (p->scope_index == d.scope_index &&
  5823. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  5824. lb_build_defer_stmt(p, d);
  5825. array_pop(&p->defer_stmts);
  5826. continue;
  5827. } else {
  5828. break;
  5829. }
  5830. } else if (kind == lbDeferExit_Return) {
  5831. lb_build_defer_stmt(p, d);
  5832. } else if (kind == lbDeferExit_Branch) {
  5833. GB_ASSERT(block != nullptr);
  5834. isize lower_limit = block->scope_index;
  5835. if (lower_limit < d.scope_index) {
  5836. lb_build_defer_stmt(p, d);
  5837. }
  5838. }
  5839. }
  5840. }
  5841. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  5842. lbDefer d = {lbDefer_Node};
  5843. d.scope_index = scope_index;
  5844. d.context_stack_count = p->context_stack.count;
  5845. d.block = p->curr_block;
  5846. d.stmt = stmt;
  5847. array_add(&p->defer_stmts, d);
  5848. return d;
  5849. }
  5850. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  5851. lbDefer d = {lbDefer_Proc};
  5852. d.scope_index = p->scope_index;
  5853. d.block = p->curr_block;
  5854. d.proc.deferred = deferred;
  5855. d.proc.result_as_args = result_as_args;
  5856. array_add(&p->defer_stmts, d);
  5857. return d;
  5858. }
  5859. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  5860. Array<lbValue> array = {};
  5861. Type *t = base_type(value.type);
  5862. if (t == nullptr) {
  5863. // Do nothing
  5864. } else if (is_type_tuple(t)) {
  5865. GB_ASSERT(t->kind == Type_Tuple);
  5866. auto *rt = &t->Tuple;
  5867. if (rt->variables.count > 0) {
  5868. array = array_make<lbValue>(heap_allocator(), rt->variables.count);
  5869. for_array(i, rt->variables) {
  5870. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  5871. array[i] = elem;
  5872. }
  5873. }
  5874. } else {
  5875. array = array_make<lbValue>(heap_allocator(), 1);
  5876. array[0] = value;
  5877. }
  5878. return array;
  5879. }
  5880. 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) {
  5881. unsigned arg_count = cast(unsigned)processed_args.count;
  5882. if (return_ptr.value != nullptr) {
  5883. arg_count += 1;
  5884. }
  5885. if (context_ptr.addr.value != nullptr) {
  5886. arg_count += 1;
  5887. }
  5888. LLVMValueRef *args = gb_alloc_array(heap_allocator(), LLVMValueRef, arg_count);
  5889. isize arg_index = 0;
  5890. if (return_ptr.value != nullptr) {
  5891. args[arg_index++] = return_ptr.value;
  5892. }
  5893. for_array(i, processed_args) {
  5894. lbValue arg = processed_args[i];
  5895. args[arg_index++] = arg.value;
  5896. }
  5897. if (context_ptr.addr.value != nullptr) {
  5898. args[arg_index++] = context_ptr.addr.value;
  5899. }
  5900. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  5901. GB_ASSERT(curr_block != p->decl_block->block);
  5902. LLVMValueRef ret = LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(p->module, value.type)), value.value, args, arg_count, "");;
  5903. lbValue res = {};
  5904. res.value = ret;
  5905. res.type = abi_rt;
  5906. return res;
  5907. }
  5908. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  5909. String name = make_string_c(c_name);
  5910. AstPackage *pkg = p->module->info->runtime_package;
  5911. Entity *e = scope_lookup_current(pkg->scope, name);
  5912. lbValue *found = nullptr;
  5913. if (p->module != e->code_gen_module) {
  5914. gb_mutex_lock(&p->module->mutex);
  5915. }
  5916. found = map_get(&e->code_gen_module->values, hash_entity(e));
  5917. if (p->module != e->code_gen_module) {
  5918. gb_mutex_unlock(&p->module->mutex);
  5919. }
  5920. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  5921. return lb_emit_call(p, *found, args);
  5922. }
  5923. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  5924. lbModule *m = p->module;
  5925. Type *pt = base_type(value.type);
  5926. GB_ASSERT(pt->kind == Type_Proc);
  5927. Type *results = pt->Proc.results;
  5928. if (p->entity != nullptr) {
  5929. if (p->entity->flags & EntityFlag_Disabled) {
  5930. return {};
  5931. }
  5932. }
  5933. lbAddr context_ptr = {};
  5934. if (pt->Proc.calling_convention == ProcCC_Odin) {
  5935. context_ptr = lb_find_or_generate_context_ptr(p);
  5936. }
  5937. defer (if (pt->Proc.diverging) {
  5938. LLVMBuildUnreachable(p->builder);
  5939. });
  5940. set_procedure_abi_types(heap_allocator(), pt);
  5941. bool is_c_vararg = pt->Proc.c_vararg;
  5942. isize param_count = pt->Proc.param_count;
  5943. if (is_c_vararg) {
  5944. GB_ASSERT(param_count-1 <= args.count);
  5945. param_count -= 1;
  5946. } else {
  5947. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  5948. }
  5949. auto processed_args = array_make<lbValue>(heap_allocator(), 0, args.count);
  5950. for (isize i = 0; i < param_count; i++) {
  5951. Entity *e = pt->Proc.params->Tuple.variables[i];
  5952. if (e->kind != Entity_Variable) {
  5953. // array_add(&processed_args, args[i]);
  5954. continue;
  5955. }
  5956. GB_ASSERT(e->flags & EntityFlag_Param);
  5957. Type *original_type = e->type;
  5958. Type *new_type = pt->Proc.abi_compat_params[i];
  5959. Type *arg_type = args[i].type;
  5960. if (are_types_identical(arg_type, new_type)) {
  5961. // NOTE(bill): Done
  5962. array_add(&processed_args, args[i]);
  5963. } else if (!are_types_identical(original_type, new_type)) {
  5964. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  5965. Type *av = core_type(type_deref(new_type));
  5966. if (are_types_identical(av, core_type(original_type))) {
  5967. if (e->flags&EntityFlag_ImplicitReference) {
  5968. array_add(&processed_args, lb_address_from_load_or_generate_local(p, args[i]));
  5969. } else if (!is_type_pointer(arg_type)) {
  5970. array_add(&processed_args, lb_copy_value_to_ptr(p, args[i], original_type, 16));
  5971. }
  5972. } else {
  5973. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  5974. }
  5975. } else if (new_type == t_llvm_bool) {
  5976. array_add(&processed_args, lb_emit_conv(p, args[i], new_type));
  5977. } else if (is_type_integer(new_type) || is_type_float(new_type) || is_type_boolean(new_type)) {
  5978. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  5979. } else if (is_type_simd_vector(new_type)) {
  5980. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  5981. } else if (is_type_tuple(new_type)) {
  5982. Type *abi_type = pt->Proc.abi_compat_params[i];
  5983. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  5984. lbValue x = {};
  5985. i64 st_sz = type_size_of(st);
  5986. i64 arg_sz = type_size_of(args[i].type);
  5987. if (st_sz == arg_sz) {
  5988. x = lb_emit_transmute(p, args[i], st);
  5989. } else {
  5990. // NOTE(bill): struct{f32, f32, f32} != struct{#simd[2]f32, f32}
  5991. GB_ASSERT(st_sz > arg_sz);
  5992. lbAddr xx = lb_add_local_generated(p, st, false);
  5993. lbValue pp = lb_emit_conv(p, xx.addr, alloc_type_pointer(args[i].type));
  5994. lb_emit_store(p, pp, args[i]);
  5995. x = lb_addr_load(p, xx);
  5996. }
  5997. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  5998. lbValue xx = lb_emit_struct_ev(p, x, cast(i32)j);
  5999. array_add(&processed_args, xx);
  6000. }
  6001. }
  6002. } else {
  6003. lbValue x = lb_emit_conv(p, args[i], new_type);
  6004. array_add(&processed_args, x);
  6005. }
  6006. }
  6007. if (inlining == ProcInlining_none) {
  6008. inlining = p->inlining;
  6009. }
  6010. lbValue result = {};
  6011. Type *abi_rt = reduce_tuple_to_single_type(pt->Proc.abi_compat_result_type);
  6012. Type *rt = reduce_tuple_to_single_type(results);
  6013. if (pt->Proc.return_by_pointer) {
  6014. lbValue return_ptr = {};
  6015. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6016. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6017. return_ptr = p->return_ptr_hint_value;
  6018. p->return_ptr_hint_used = true;
  6019. }
  6020. }
  6021. if (return_ptr.value == nullptr) {
  6022. lbAddr r = lb_add_local_generated(p, rt, true);
  6023. return_ptr = r.addr;
  6024. }
  6025. GB_ASSERT(is_type_pointer(return_ptr.type));
  6026. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6027. result = lb_emit_load(p, return_ptr);
  6028. } else {
  6029. result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining);
  6030. if (abi_rt != rt) {
  6031. result = lb_emit_transmute(p, result, rt);
  6032. }
  6033. }
  6034. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6035. if (found != nullptr) {
  6036. Entity *e = *found;
  6037. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6038. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6039. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6040. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6041. GB_ASSERT(deferred_found != nullptr);
  6042. lbValue deferred = *deferred_found;
  6043. auto in_args = args;
  6044. Array<lbValue> result_as_args = {};
  6045. switch (kind) {
  6046. case DeferredProcedure_none:
  6047. break;
  6048. case DeferredProcedure_in:
  6049. result_as_args = in_args;
  6050. break;
  6051. case DeferredProcedure_out:
  6052. result_as_args = lb_value_to_array(p, result);
  6053. break;
  6054. case DeferredProcedure_in_out:
  6055. {
  6056. auto out_args = lb_value_to_array(p, result);
  6057. array_init(&result_as_args, heap_allocator(), in_args.count + out_args.count);
  6058. array_copy(&result_as_args, in_args, 0);
  6059. array_copy(&result_as_args, out_args, in_args.count);
  6060. }
  6061. break;
  6062. }
  6063. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6064. }
  6065. }
  6066. return result;
  6067. }
  6068. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6069. Type *t = s.type;
  6070. GB_ASSERT(is_type_pointer(t));
  6071. Type *st = base_type(type_deref(t));
  6072. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6073. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6074. LLVMValueRef indices[2] = {};
  6075. indices[0] = llvm_zero(p->module);
  6076. indices[1] = lb_emit_conv(p, index, t_int).value;
  6077. Type *ptr = base_array_type(st);
  6078. lbValue res = {};
  6079. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6080. res.type = alloc_type_pointer(ptr);
  6081. return res;
  6082. }
  6083. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6084. Type *t = s.type;
  6085. GB_ASSERT(is_type_pointer(t));
  6086. Type *st = base_type(type_deref(t));
  6087. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6088. GB_ASSERT(0 <= index);
  6089. Type *ptr = base_array_type(st);
  6090. LLVMValueRef indices[2] = {
  6091. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6092. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6093. };
  6094. lbValue res = {};
  6095. if (lb_is_const(s)) {
  6096. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6097. } else {
  6098. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6099. }
  6100. res.type = alloc_type_pointer(ptr);
  6101. return res;
  6102. }
  6103. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6104. LLVMValueRef indices[1] = {index.value};
  6105. lbValue res = {};
  6106. res.type = ptr.type;
  6107. if (lb_is_const(ptr) && lb_is_const(index)) {
  6108. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6109. } else {
  6110. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6111. }
  6112. return res;
  6113. }
  6114. LLVMValueRef llvm_const_slice(lbValue data, lbValue len) {
  6115. GB_ASSERT(is_type_pointer(data.type));
  6116. GB_ASSERT(are_types_identical(len.type, t_int));
  6117. LLVMValueRef vals[2] = {
  6118. data.value,
  6119. len.value,
  6120. };
  6121. return LLVMConstStruct(vals, gb_count_of(vals), false);
  6122. }
  6123. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6124. Type *t = lb_addr_type(slice);
  6125. GB_ASSERT(is_type_slice(t));
  6126. lbValue ptr = lb_addr_get_ptr(p, slice);
  6127. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6128. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6129. }
  6130. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6131. Type *t = lb_addr_type(string);
  6132. GB_ASSERT(is_type_string(t));
  6133. lbValue ptr = lb_addr_get_ptr(p, string);
  6134. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6135. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6136. }
  6137. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6138. Type *t = base_type(string.type);
  6139. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6140. return lb_emit_struct_ev(p, string, 0);
  6141. }
  6142. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6143. Type *t = base_type(string.type);
  6144. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6145. return lb_emit_struct_ev(p, string, 1);
  6146. }
  6147. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6148. GB_ASSERT(is_type_cstring(value.type));
  6149. auto args = array_make<lbValue>(heap_allocator(), 1);
  6150. args[0] = lb_emit_conv(p, value, t_cstring);
  6151. return lb_emit_runtime_call(p, "cstring_len", args);
  6152. }
  6153. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6154. Type *t = type_deref(array_ptr.type);
  6155. GB_ASSERT(is_type_array(t));
  6156. return lb_emit_struct_ep(p, array_ptr, 0);
  6157. }
  6158. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6159. GB_ASSERT(is_type_slice(slice.type));
  6160. return lb_emit_struct_ev(p, slice, 0);
  6161. }
  6162. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6163. GB_ASSERT(is_type_slice(slice.type));
  6164. return lb_emit_struct_ev(p, slice, 1);
  6165. }
  6166. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6167. GB_ASSERT(is_type_dynamic_array(da.type));
  6168. return lb_emit_struct_ev(p, da, 0);
  6169. }
  6170. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6171. GB_ASSERT(is_type_dynamic_array(da.type));
  6172. return lb_emit_struct_ev(p, da, 1);
  6173. }
  6174. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6175. GB_ASSERT(is_type_dynamic_array(da.type));
  6176. return lb_emit_struct_ev(p, da, 2);
  6177. }
  6178. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6179. GB_ASSERT(is_type_dynamic_array(da.type));
  6180. return lb_emit_struct_ev(p, da, 3);
  6181. }
  6182. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6183. gbAllocator a = heap_allocator();
  6184. Type *t = base_type(value.type);
  6185. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6186. init_map_internal_types(t);
  6187. Type *gst = t->Map.generated_struct_type;
  6188. i32 index = 1;
  6189. lbValue entries = lb_emit_struct_ev(p, value, index);
  6190. return entries;
  6191. }
  6192. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6193. gbAllocator a = heap_allocator();
  6194. Type *t = base_type(type_deref(value.type));
  6195. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6196. init_map_internal_types(t);
  6197. Type *gst = t->Map.generated_struct_type;
  6198. i32 index = 1;
  6199. lbValue entries = lb_emit_struct_ep(p, value, index);
  6200. return entries;
  6201. }
  6202. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  6203. lbValue entries = lb_map_entries(p, value);
  6204. return lb_dynamic_array_len(p, entries);
  6205. }
  6206. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  6207. lbValue entries = lb_map_entries(p, value);
  6208. return lb_dynamic_array_cap(p, entries);
  6209. }
  6210. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  6211. Type *t = base_type(value.type);
  6212. bool is_ptr = false;
  6213. if (is_type_pointer(t)) {
  6214. is_ptr = true;
  6215. t = base_type(type_deref(t));
  6216. }
  6217. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6218. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6219. }
  6220. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  6221. t->Struct.soa_kind == StructSoa_Dynamic);
  6222. isize n = 0;
  6223. Type *elem = base_type(t->Struct.soa_elem);
  6224. if (elem->kind == Type_Struct) {
  6225. n = elem->Struct.fields.count;
  6226. } else if (elem->kind == Type_Array) {
  6227. n = elem->Array.count;
  6228. } else {
  6229. GB_PANIC("Unreachable");
  6230. }
  6231. if (is_ptr) {
  6232. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6233. return lb_emit_load(p, v);
  6234. }
  6235. return lb_emit_struct_ev(p, value, cast(i32)n);
  6236. }
  6237. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  6238. Type *t = base_type(value.type);
  6239. bool is_ptr = false;
  6240. if (is_type_pointer(t)) {
  6241. is_ptr = true;
  6242. t = base_type(type_deref(t));
  6243. }
  6244. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6245. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6246. }
  6247. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  6248. isize n = 0;
  6249. Type *elem = base_type(t->Struct.soa_elem);
  6250. if (elem->kind == Type_Struct) {
  6251. n = elem->Struct.fields.count+1;
  6252. } else if (elem->kind == Type_Array) {
  6253. n = elem->Array.count+1;
  6254. } else {
  6255. GB_PANIC("Unreachable");
  6256. }
  6257. if (is_ptr) {
  6258. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6259. return lb_emit_load(p, v);
  6260. }
  6261. return lb_emit_struct_ev(p, value, cast(i32)n);
  6262. }
  6263. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  6264. ast_node(ce, CallExpr, expr);
  6265. switch (id) {
  6266. case BuiltinProc_DIRECTIVE: {
  6267. ast_node(bd, BasicDirective, ce->proc);
  6268. String name = bd->name;
  6269. GB_ASSERT(name == "location");
  6270. String procedure = p->entity->token.string;
  6271. TokenPos pos = ast_token(ce->proc).pos;
  6272. if (ce->args.count > 0) {
  6273. Ast *ident = unselector_expr(ce->args[0]);
  6274. GB_ASSERT(ident->kind == Ast_Ident);
  6275. Entity *e = entity_of_node(ident);
  6276. GB_ASSERT(e != nullptr);
  6277. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  6278. procedure = e->parent_proc_decl->entity->token.string;
  6279. } else {
  6280. procedure = str_lit("");
  6281. }
  6282. pos = e->token.pos;
  6283. }
  6284. return lb_emit_source_code_location(p, procedure, pos);
  6285. }
  6286. case BuiltinProc_type_info_of: {
  6287. Ast *arg = ce->args[0];
  6288. TypeAndValue tav = type_and_value_of_expr(arg);
  6289. if (tav.mode == Addressing_Type) {
  6290. Type *t = default_type(type_of_expr(arg));
  6291. return lb_type_info(p->module, t);
  6292. }
  6293. GB_ASSERT(is_type_typeid(tav.type));
  6294. auto args = array_make<lbValue>(heap_allocator(), 1);
  6295. args[0] = lb_build_expr(p, arg);
  6296. return lb_emit_runtime_call(p, "__type_info_of", args);
  6297. }
  6298. case BuiltinProc_typeid_of: {
  6299. Ast *arg = ce->args[0];
  6300. TypeAndValue tav = type_and_value_of_expr(arg);
  6301. if (tav.mode == Addressing_Type) {
  6302. Type *t = default_type(type_of_expr(arg));
  6303. return lb_typeid(p->module, t);
  6304. }
  6305. Type *t = base_type(tav.type);
  6306. GB_ASSERT(are_types_identical(t, t_type_info_ptr));
  6307. auto args = array_make<lbValue>(heap_allocator(), 1);
  6308. args[0] = lb_emit_conv(p, lb_build_expr(p, arg), t_type_info_ptr);
  6309. return lb_emit_runtime_call(p, "__typeid_of", args);
  6310. }
  6311. case BuiltinProc_len: {
  6312. lbValue v = lb_build_expr(p, ce->args[0]);
  6313. Type *t = base_type(v.type);
  6314. if (is_type_pointer(t)) {
  6315. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6316. v = lb_emit_load(p, v);
  6317. t = type_deref(t);
  6318. }
  6319. if (is_type_cstring(t)) {
  6320. return lb_cstring_len(p, v);
  6321. } else if (is_type_string(t)) {
  6322. return lb_string_len(p, v);
  6323. } else if (is_type_array(t)) {
  6324. GB_PANIC("Array lengths are constant");
  6325. } else if (is_type_slice(t)) {
  6326. return lb_slice_len(p, v);
  6327. } else if (is_type_dynamic_array(t)) {
  6328. return lb_dynamic_array_len(p, v);
  6329. } else if (is_type_map(t)) {
  6330. return lb_map_len(p, v);
  6331. } else if (is_type_soa_struct(t)) {
  6332. return lb_soa_struct_len(p, v);
  6333. }
  6334. GB_PANIC("Unreachable");
  6335. break;
  6336. }
  6337. case BuiltinProc_cap: {
  6338. lbValue v = lb_build_expr(p, ce->args[0]);
  6339. Type *t = base_type(v.type);
  6340. if (is_type_pointer(t)) {
  6341. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6342. v = lb_emit_load(p, v);
  6343. t = type_deref(t);
  6344. }
  6345. if (is_type_string(t)) {
  6346. GB_PANIC("Unreachable");
  6347. } else if (is_type_array(t)) {
  6348. GB_PANIC("Array lengths are constant");
  6349. } else if (is_type_slice(t)) {
  6350. return lb_slice_len(p, v);
  6351. } else if (is_type_dynamic_array(t)) {
  6352. return lb_dynamic_array_cap(p, v);
  6353. } else if (is_type_map(t)) {
  6354. return lb_map_cap(p, v);
  6355. } else if (is_type_soa_struct(t)) {
  6356. return lb_soa_struct_cap(p, v);
  6357. }
  6358. GB_PANIC("Unreachable");
  6359. break;
  6360. }
  6361. case BuiltinProc_swizzle: {
  6362. isize index_count = ce->args.count-1;
  6363. if (is_type_simd_vector(tv.type)) {
  6364. lbValue vec = lb_build_expr(p, ce->args[0]);
  6365. if (index_count == 0) {
  6366. return vec;
  6367. }
  6368. unsigned mask_len = cast(unsigned)index_count;
  6369. LLVMValueRef *mask_elems = gb_alloc_array(heap_allocator(), LLVMValueRef, index_count);
  6370. for (isize i = 1; i < ce->args.count; i++) {
  6371. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6372. GB_ASSERT(is_type_integer(tv.type));
  6373. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6374. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  6375. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  6376. }
  6377. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  6378. LLVMValueRef v1 = vec.value;
  6379. LLVMValueRef v2 = vec.value;
  6380. lbValue res = {};
  6381. res.type = tv.type;
  6382. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  6383. return res;
  6384. }
  6385. lbAddr addr = lb_build_addr(p, ce->args[0]);
  6386. if (index_count == 0) {
  6387. return lb_addr_load(p, addr);
  6388. }
  6389. lbValue src = lb_addr_get_ptr(p, addr);
  6390. // TODO(bill): Should this be zeroed or not?
  6391. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  6392. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  6393. for (i32 i = 1; i < ce->args.count; i++) {
  6394. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6395. GB_ASSERT(is_type_integer(tv.type));
  6396. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6397. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  6398. i32 dst_index = i-1;
  6399. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  6400. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  6401. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  6402. }
  6403. return lb_addr_load(p, dst);
  6404. }
  6405. case BuiltinProc_complex: {
  6406. lbValue real = lb_build_expr(p, ce->args[0]);
  6407. lbValue imag = lb_build_expr(p, ce->args[1]);
  6408. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6409. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6410. Type *ft = base_complex_elem_type(tv.type);
  6411. real = lb_emit_conv(p, real, ft);
  6412. imag = lb_emit_conv(p, imag, ft);
  6413. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  6414. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  6415. return lb_emit_load(p, dst);
  6416. }
  6417. case BuiltinProc_quaternion: {
  6418. lbValue real = lb_build_expr(p, ce->args[0]);
  6419. lbValue imag = lb_build_expr(p, ce->args[1]);
  6420. lbValue jmag = lb_build_expr(p, ce->args[2]);
  6421. lbValue kmag = lb_build_expr(p, ce->args[3]);
  6422. // @QuaternionLayout
  6423. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6424. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6425. Type *ft = base_complex_elem_type(tv.type);
  6426. real = lb_emit_conv(p, real, ft);
  6427. imag = lb_emit_conv(p, imag, ft);
  6428. jmag = lb_emit_conv(p, jmag, ft);
  6429. kmag = lb_emit_conv(p, kmag, ft);
  6430. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  6431. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  6432. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  6433. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  6434. return lb_emit_load(p, dst);
  6435. }
  6436. case BuiltinProc_real: {
  6437. lbValue val = lb_build_expr(p, ce->args[0]);
  6438. if (is_type_complex(val.type)) {
  6439. lbValue real = lb_emit_struct_ev(p, val, 0);
  6440. return lb_emit_conv(p, real, tv.type);
  6441. } else if (is_type_quaternion(val.type)) {
  6442. // @QuaternionLayout
  6443. lbValue real = lb_emit_struct_ev(p, val, 3);
  6444. return lb_emit_conv(p, real, tv.type);
  6445. }
  6446. GB_PANIC("invalid type for real");
  6447. return {};
  6448. }
  6449. case BuiltinProc_imag: {
  6450. lbValue val = lb_build_expr(p, ce->args[0]);
  6451. if (is_type_complex(val.type)) {
  6452. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6453. return lb_emit_conv(p, imag, tv.type);
  6454. } else if (is_type_quaternion(val.type)) {
  6455. // @QuaternionLayout
  6456. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6457. return lb_emit_conv(p, imag, tv.type);
  6458. }
  6459. GB_PANIC("invalid type for imag");
  6460. return {};
  6461. }
  6462. case BuiltinProc_jmag: {
  6463. lbValue val = lb_build_expr(p, ce->args[0]);
  6464. if (is_type_quaternion(val.type)) {
  6465. // @QuaternionLayout
  6466. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6467. return lb_emit_conv(p, imag, tv.type);
  6468. }
  6469. GB_PANIC("invalid type for jmag");
  6470. return {};
  6471. }
  6472. case BuiltinProc_kmag: {
  6473. lbValue val = lb_build_expr(p, ce->args[0]);
  6474. if (is_type_quaternion(val.type)) {
  6475. // @QuaternionLayout
  6476. lbValue imag = lb_emit_struct_ev(p, val, 2);
  6477. return lb_emit_conv(p, imag, tv.type);
  6478. }
  6479. GB_PANIC("invalid type for kmag");
  6480. return {};
  6481. }
  6482. case BuiltinProc_conj: {
  6483. lbValue val = lb_build_expr(p, ce->args[0]);
  6484. lbValue res = {};
  6485. Type *t = val.type;
  6486. if (is_type_complex(t)) {
  6487. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6488. lbValue real = lb_emit_struct_ev(p, val, 0);
  6489. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6490. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6491. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  6492. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  6493. } else if (is_type_quaternion(t)) {
  6494. // @QuaternionLayout
  6495. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6496. lbValue real = lb_emit_struct_ev(p, val, 3);
  6497. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6498. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  6499. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  6500. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6501. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  6502. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  6503. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  6504. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  6505. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  6506. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  6507. }
  6508. return lb_emit_load(p, res);
  6509. }
  6510. case BuiltinProc_expand_to_tuple: {
  6511. lbValue val = lb_build_expr(p, ce->args[0]);
  6512. Type *t = base_type(val.type);
  6513. if (!is_type_tuple(tv.type)) {
  6514. if (t->kind == Type_Struct) {
  6515. GB_ASSERT(t->Struct.fields.count == 1);
  6516. return lb_emit_struct_ev(p, val, 0);
  6517. } else if (t->kind == Type_Array) {
  6518. GB_ASSERT(t->Array.count == 1);
  6519. return lb_emit_array_epi(p, val, 0);
  6520. } else {
  6521. GB_PANIC("Unknown type of expand_to_tuple");
  6522. }
  6523. }
  6524. GB_ASSERT(is_type_tuple(tv.type));
  6525. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6526. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6527. if (t->kind == Type_Struct) {
  6528. for_array(src_index, t->Struct.fields) {
  6529. Entity *field = t->Struct.fields[src_index];
  6530. i32 field_index = field->Variable.field_index;
  6531. lbValue f = lb_emit_struct_ev(p, val, field_index);
  6532. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  6533. lb_emit_store(p, ep, f);
  6534. }
  6535. } else if (t->kind == Type_Array) {
  6536. // TODO(bill): Clean-up this code
  6537. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  6538. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  6539. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  6540. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  6541. lb_emit_store(p, ep, f);
  6542. }
  6543. } else {
  6544. GB_PANIC("Unknown type of expand_to_tuple");
  6545. }
  6546. return lb_emit_load(p, tuple);
  6547. }
  6548. case BuiltinProc_min: {
  6549. Type *t = type_of_expr(expr);
  6550. if (ce->args.count == 2) {
  6551. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6552. } else {
  6553. lbValue x = lb_build_expr(p, ce->args[0]);
  6554. for (isize i = 1; i < ce->args.count; i++) {
  6555. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  6556. }
  6557. return x;
  6558. }
  6559. }
  6560. case BuiltinProc_max: {
  6561. Type *t = type_of_expr(expr);
  6562. if (ce->args.count == 2) {
  6563. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6564. } else {
  6565. lbValue x = lb_build_expr(p, ce->args[0]);
  6566. for (isize i = 1; i < ce->args.count; i++) {
  6567. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  6568. }
  6569. return x;
  6570. }
  6571. }
  6572. case BuiltinProc_abs: {
  6573. gbAllocator a = heap_allocator();
  6574. lbValue x = lb_build_expr(p, ce->args[0]);
  6575. Type *t = x.type;
  6576. if (is_type_unsigned(t)) {
  6577. return x;
  6578. }
  6579. if (is_type_quaternion(t)) {
  6580. i64 sz = 8*type_size_of(t);
  6581. auto args = array_make<lbValue>(heap_allocator(), 1);
  6582. args[0] = x;
  6583. switch (sz) {
  6584. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  6585. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  6586. }
  6587. GB_PANIC("Unknown complex type");
  6588. } else if (is_type_complex(t)) {
  6589. i64 sz = 8*type_size_of(t);
  6590. auto args = array_make<lbValue>(heap_allocator(), 1);
  6591. args[0] = x;
  6592. switch (sz) {
  6593. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  6594. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  6595. }
  6596. GB_PANIC("Unknown complex type");
  6597. } else if (is_type_float(t)) {
  6598. i64 sz = 8*type_size_of(t);
  6599. auto args = array_make<lbValue>(heap_allocator(), 1);
  6600. args[0] = x;
  6601. switch (sz) {
  6602. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  6603. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  6604. }
  6605. GB_PANIC("Unknown float type");
  6606. }
  6607. lbValue zero = lb_const_nil(p->module, t);
  6608. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  6609. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  6610. return lb_emit_select(p, cond, neg, x);
  6611. }
  6612. case BuiltinProc_clamp:
  6613. return lb_emit_clamp(p, type_of_expr(expr),
  6614. lb_build_expr(p, ce->args[0]),
  6615. lb_build_expr(p, ce->args[1]),
  6616. lb_build_expr(p, ce->args[2]));
  6617. // "Intrinsics"
  6618. case BuiltinProc_alloca:
  6619. {
  6620. lbValue sz = lb_build_expr(p, ce->args[0]);
  6621. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  6622. lbValue res = {};
  6623. res.type = t_u8_ptr;
  6624. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  6625. LLVMSetAlignment(res.value, cast(unsigned)al);
  6626. return res;
  6627. }
  6628. case BuiltinProc_cpu_relax:
  6629. // TODO(bill): BuiltinProc_cpu_relax
  6630. // ir_write_str_lit(f, "call void asm sideeffect \"pause\", \"\"()");
  6631. return {};
  6632. case BuiltinProc_atomic_fence:
  6633. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  6634. return {};
  6635. case BuiltinProc_atomic_fence_acq:
  6636. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  6637. return {};
  6638. case BuiltinProc_atomic_fence_rel:
  6639. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  6640. return {};
  6641. case BuiltinProc_atomic_fence_acqrel:
  6642. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  6643. return {};
  6644. case BuiltinProc_atomic_store:
  6645. case BuiltinProc_atomic_store_rel:
  6646. case BuiltinProc_atomic_store_relaxed:
  6647. case BuiltinProc_atomic_store_unordered: {
  6648. lbValue dst = lb_build_expr(p, ce->args[0]);
  6649. lbValue val = lb_build_expr(p, ce->args[1]);
  6650. val = lb_emit_conv(p, val, type_deref(dst.type));
  6651. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  6652. switch (id) {
  6653. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  6654. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  6655. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  6656. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  6657. }
  6658. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  6659. return {};
  6660. }
  6661. case BuiltinProc_atomic_load:
  6662. case BuiltinProc_atomic_load_acq:
  6663. case BuiltinProc_atomic_load_relaxed:
  6664. case BuiltinProc_atomic_load_unordered: {
  6665. lbValue dst = lb_build_expr(p, ce->args[0]);
  6666. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  6667. switch (id) {
  6668. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  6669. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  6670. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  6671. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  6672. }
  6673. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  6674. lbValue res = {};
  6675. res.value = instr;
  6676. res.type = type_deref(dst.type);
  6677. return res;
  6678. }
  6679. case BuiltinProc_atomic_add:
  6680. case BuiltinProc_atomic_add_acq:
  6681. case BuiltinProc_atomic_add_rel:
  6682. case BuiltinProc_atomic_add_acqrel:
  6683. case BuiltinProc_atomic_add_relaxed:
  6684. case BuiltinProc_atomic_sub:
  6685. case BuiltinProc_atomic_sub_acq:
  6686. case BuiltinProc_atomic_sub_rel:
  6687. case BuiltinProc_atomic_sub_acqrel:
  6688. case BuiltinProc_atomic_sub_relaxed:
  6689. case BuiltinProc_atomic_and:
  6690. case BuiltinProc_atomic_and_acq:
  6691. case BuiltinProc_atomic_and_rel:
  6692. case BuiltinProc_atomic_and_acqrel:
  6693. case BuiltinProc_atomic_and_relaxed:
  6694. case BuiltinProc_atomic_nand:
  6695. case BuiltinProc_atomic_nand_acq:
  6696. case BuiltinProc_atomic_nand_rel:
  6697. case BuiltinProc_atomic_nand_acqrel:
  6698. case BuiltinProc_atomic_nand_relaxed:
  6699. case BuiltinProc_atomic_or:
  6700. case BuiltinProc_atomic_or_acq:
  6701. case BuiltinProc_atomic_or_rel:
  6702. case BuiltinProc_atomic_or_acqrel:
  6703. case BuiltinProc_atomic_or_relaxed:
  6704. case BuiltinProc_atomic_xor:
  6705. case BuiltinProc_atomic_xor_acq:
  6706. case BuiltinProc_atomic_xor_rel:
  6707. case BuiltinProc_atomic_xor_acqrel:
  6708. case BuiltinProc_atomic_xor_relaxed:
  6709. case BuiltinProc_atomic_xchg:
  6710. case BuiltinProc_atomic_xchg_acq:
  6711. case BuiltinProc_atomic_xchg_rel:
  6712. case BuiltinProc_atomic_xchg_acqrel:
  6713. case BuiltinProc_atomic_xchg_relaxed: {
  6714. lbValue dst = lb_build_expr(p, ce->args[0]);
  6715. lbValue val = lb_build_expr(p, ce->args[1]);
  6716. val = lb_emit_conv(p, val, type_deref(dst.type));
  6717. LLVMAtomicRMWBinOp op = {};
  6718. LLVMAtomicOrdering ordering = {};
  6719. switch (id) {
  6720. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6721. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  6722. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  6723. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6724. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  6725. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6726. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  6727. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  6728. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6729. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  6730. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6731. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  6732. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  6733. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6734. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  6735. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6736. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  6737. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  6738. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6739. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  6740. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6741. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  6742. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  6743. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6744. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  6745. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6746. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  6747. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  6748. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6749. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  6750. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6751. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  6752. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  6753. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6754. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  6755. }
  6756. lbValue res = {};
  6757. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  6758. res.type = tv.type;
  6759. return res;
  6760. }
  6761. case BuiltinProc_atomic_cxchg:
  6762. case BuiltinProc_atomic_cxchg_acq:
  6763. case BuiltinProc_atomic_cxchg_rel:
  6764. case BuiltinProc_atomic_cxchg_acqrel:
  6765. case BuiltinProc_atomic_cxchg_relaxed:
  6766. case BuiltinProc_atomic_cxchg_failrelaxed:
  6767. case BuiltinProc_atomic_cxchg_failacq:
  6768. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  6769. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  6770. case BuiltinProc_atomic_cxchgweak:
  6771. case BuiltinProc_atomic_cxchgweak_acq:
  6772. case BuiltinProc_atomic_cxchgweak_rel:
  6773. case BuiltinProc_atomic_cxchgweak_acqrel:
  6774. case BuiltinProc_atomic_cxchgweak_relaxed:
  6775. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  6776. case BuiltinProc_atomic_cxchgweak_failacq:
  6777. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  6778. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  6779. Type *type = expr->tav.type;
  6780. lbValue address = lb_build_expr(p, ce->args[0]);
  6781. Type *elem = type_deref(address.type);
  6782. lbValue old_value = lb_build_expr(p, ce->args[1]);
  6783. lbValue new_value = lb_build_expr(p, ce->args[2]);
  6784. old_value = lb_emit_conv(p, old_value, elem);
  6785. new_value = lb_emit_conv(p, new_value, elem);
  6786. LLVMAtomicOrdering success_ordering = {};
  6787. LLVMAtomicOrdering failure_ordering = {};
  6788. LLVMBool weak = false;
  6789. switch (id) {
  6790. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6791. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6792. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6793. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6794. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6795. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6796. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  6797. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6798. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6799. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6800. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6801. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6802. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6803. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6804. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6805. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  6806. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6807. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6808. }
  6809. // TODO(bill): Figure out how to make it weak
  6810. LLVMBool single_threaded = weak;
  6811. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  6812. p->builder, address.value,
  6813. old_value.value, new_value.value,
  6814. success_ordering,
  6815. failure_ordering,
  6816. single_threaded
  6817. );
  6818. GB_ASSERT(tv.type->kind == Type_Tuple);
  6819. Type *fix_typed = alloc_type_tuple();
  6820. array_init(&fix_typed->Tuple.variables, heap_allocator(), 2);
  6821. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  6822. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  6823. lbValue res = {};
  6824. res.value = value;
  6825. res.type = fix_typed;
  6826. return res;
  6827. }
  6828. }
  6829. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  6830. return {};
  6831. }
  6832. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  6833. lbModule *m = p->module;
  6834. TypeAndValue tv = type_and_value_of_expr(expr);
  6835. ast_node(ce, CallExpr, expr);
  6836. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  6837. AddressingMode proc_mode = proc_tv.mode;
  6838. if (proc_mode == Addressing_Type) {
  6839. GB_ASSERT(ce->args.count == 1);
  6840. lbValue x = lb_build_expr(p, ce->args[0]);
  6841. lbValue y = lb_emit_conv(p, x, tv.type);
  6842. return y;
  6843. }
  6844. Ast *pexpr = unparen_expr(ce->proc);
  6845. if (proc_mode == Addressing_Builtin) {
  6846. Entity *e = entity_of_node(pexpr);
  6847. BuiltinProcId id = BuiltinProc_Invalid;
  6848. if (e != nullptr) {
  6849. id = cast(BuiltinProcId)e->Builtin.id;
  6850. } else {
  6851. id = BuiltinProc_DIRECTIVE;
  6852. }
  6853. return lb_build_builtin_proc(p, expr, tv, id);
  6854. }
  6855. // NOTE(bill): Regular call
  6856. lbValue value = {};
  6857. Ast *proc_expr = unparen_expr(ce->proc);
  6858. if (proc_expr->tav.mode == Addressing_Constant) {
  6859. ExactValue v = proc_expr->tav.value;
  6860. switch (v.kind) {
  6861. case ExactValue_Integer:
  6862. {
  6863. u64 u = big_int_to_u64(&v.value_integer);
  6864. lbValue x = {};
  6865. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  6866. x.type = t_uintptr;
  6867. x = lb_emit_conv(p, x, t_rawptr);
  6868. value = lb_emit_conv(p, x, proc_expr->tav.type);
  6869. break;
  6870. }
  6871. case ExactValue_Pointer:
  6872. {
  6873. u64 u = cast(u64)v.value_pointer;
  6874. lbValue x = {};
  6875. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  6876. x.type = t_uintptr;
  6877. x = lb_emit_conv(p, x, t_rawptr);
  6878. value = lb_emit_conv(p, x, proc_expr->tav.type);
  6879. break;
  6880. }
  6881. }
  6882. }
  6883. if (value.value == nullptr) {
  6884. value = lb_build_expr(p, proc_expr);
  6885. }
  6886. GB_ASSERT(value.value != nullptr);
  6887. Type *proc_type_ = base_type(value.type);
  6888. GB_ASSERT(proc_type_->kind == Type_Proc);
  6889. TypeProc *pt = &proc_type_->Proc;
  6890. set_procedure_abi_types(heap_allocator(), proc_type_);
  6891. if (is_call_expr_field_value(ce)) {
  6892. auto args = array_make<lbValue>(heap_allocator(), pt->param_count);
  6893. for_array(arg_index, ce->args) {
  6894. Ast *arg = ce->args[arg_index];
  6895. ast_node(fv, FieldValue, arg);
  6896. GB_ASSERT(fv->field->kind == Ast_Ident);
  6897. String name = fv->field->Ident.token.string;
  6898. isize index = lookup_procedure_parameter(pt, name);
  6899. GB_ASSERT(index >= 0);
  6900. TypeAndValue tav = type_and_value_of_expr(fv->value);
  6901. if (tav.mode == Addressing_Type) {
  6902. args[index] = lb_const_nil(m, tav.type);
  6903. } else {
  6904. args[index] = lb_build_expr(p, fv->value);
  6905. }
  6906. }
  6907. TypeTuple *params = &pt->params->Tuple;
  6908. for (isize i = 0; i < args.count; i++) {
  6909. Entity *e = params->variables[i];
  6910. if (e->kind == Entity_TypeName) {
  6911. args[i] = lb_const_nil(m, e->type);
  6912. } else if (e->kind == Entity_Constant) {
  6913. continue;
  6914. } else {
  6915. GB_ASSERT(e->kind == Entity_Variable);
  6916. if (args[i].value == nullptr) {
  6917. switch (e->Variable.param_value.kind) {
  6918. case ParameterValue_Constant:
  6919. args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  6920. break;
  6921. case ParameterValue_Nil:
  6922. args[i] = lb_const_nil(m, e->type);
  6923. break;
  6924. case ParameterValue_Location:
  6925. args[i] = lb_emit_source_code_location(p, p->entity->token.string, ast_token(expr).pos);
  6926. break;
  6927. case ParameterValue_Value:
  6928. args[i] = lb_build_expr(p, e->Variable.param_value.ast_value);
  6929. break;
  6930. }
  6931. } else {
  6932. args[i] = lb_emit_conv(p, args[i], e->type);
  6933. }
  6934. }
  6935. }
  6936. for (isize i = 0; i < args.count; i++) {
  6937. Entity *e = params->variables[i];
  6938. if (args[i].type == nullptr) {
  6939. continue;
  6940. } else if (is_type_untyped_nil(args[i].type)) {
  6941. args[i] = lb_const_nil(m, e->type);
  6942. } else if (is_type_untyped_undef(args[i].type)) {
  6943. args[i] = lb_const_undef(m, e->type);
  6944. }
  6945. }
  6946. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  6947. }
  6948. isize arg_index = 0;
  6949. isize arg_count = 0;
  6950. for_array(i, ce->args) {
  6951. Ast *arg = ce->args[i];
  6952. TypeAndValue tav = type_and_value_of_expr(arg);
  6953. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  6954. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  6955. Type *at = tav.type;
  6956. if (at->kind == Type_Tuple) {
  6957. arg_count += at->Tuple.variables.count;
  6958. } else {
  6959. arg_count++;
  6960. }
  6961. }
  6962. isize param_count = 0;
  6963. if (pt->params) {
  6964. GB_ASSERT(pt->params->kind == Type_Tuple);
  6965. param_count = pt->params->Tuple.variables.count;
  6966. }
  6967. auto args = array_make<lbValue>(heap_allocator(), cast(isize)gb_max(param_count, arg_count));
  6968. isize variadic_index = pt->variadic_index;
  6969. bool variadic = pt->variadic && variadic_index >= 0;
  6970. bool vari_expand = ce->ellipsis.pos.line != 0;
  6971. bool is_c_vararg = pt->c_vararg;
  6972. String proc_name = {};
  6973. if (p->entity != nullptr) {
  6974. proc_name = p->entity->token.string;
  6975. }
  6976. TokenPos pos = ast_token(ce->proc).pos;
  6977. TypeTuple *param_tuple = nullptr;
  6978. if (pt->params) {
  6979. GB_ASSERT(pt->params->kind == Type_Tuple);
  6980. param_tuple = &pt->params->Tuple;
  6981. }
  6982. for_array(i, ce->args) {
  6983. Ast *arg = ce->args[i];
  6984. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  6985. if (arg_tv.mode == Addressing_Type) {
  6986. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  6987. } else {
  6988. lbValue a = lb_build_expr(p, arg);
  6989. Type *at = a.type;
  6990. if (at->kind == Type_Tuple) {
  6991. for_array(i, at->Tuple.variables) {
  6992. Entity *e = at->Tuple.variables[i];
  6993. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  6994. args[arg_index++] = v;
  6995. }
  6996. } else {
  6997. args[arg_index++] = a;
  6998. }
  6999. }
  7000. }
  7001. if (param_count > 0) {
  7002. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7003. GB_ASSERT(param_count < 1000000);
  7004. if (arg_count < param_count) {
  7005. isize end = cast(isize)param_count;
  7006. if (variadic) {
  7007. end = variadic_index;
  7008. }
  7009. while (arg_index < end) {
  7010. Entity *e = param_tuple->variables[arg_index];
  7011. GB_ASSERT(e->kind == Entity_Variable);
  7012. switch (e->Variable.param_value.kind) {
  7013. case ParameterValue_Constant:
  7014. args[arg_index++] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  7015. break;
  7016. case ParameterValue_Nil:
  7017. args[arg_index++] = lb_const_nil(m, e->type);
  7018. break;
  7019. case ParameterValue_Location:
  7020. args[arg_index++] = lb_emit_source_code_location(p, proc_name, pos);
  7021. break;
  7022. case ParameterValue_Value:
  7023. args[arg_index++] = lb_build_expr(p, e->Variable.param_value.ast_value);
  7024. break;
  7025. }
  7026. }
  7027. }
  7028. if (is_c_vararg) {
  7029. GB_ASSERT(variadic);
  7030. GB_ASSERT(!vari_expand);
  7031. isize i = 0;
  7032. for (; i < variadic_index; i++) {
  7033. Entity *e = param_tuple->variables[i];
  7034. if (e->kind == Entity_Variable) {
  7035. args[i] = lb_emit_conv(p, args[i], e->type);
  7036. }
  7037. }
  7038. Type *variadic_type = param_tuple->variables[i]->type;
  7039. GB_ASSERT(is_type_slice(variadic_type));
  7040. variadic_type = base_type(variadic_type)->Slice.elem;
  7041. if (!is_type_any(variadic_type)) {
  7042. for (; i < arg_count; i++) {
  7043. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7044. }
  7045. } else {
  7046. for (; i < arg_count; i++) {
  7047. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7048. }
  7049. }
  7050. } else if (variadic) {
  7051. isize i = 0;
  7052. for (; i < variadic_index; i++) {
  7053. Entity *e = param_tuple->variables[i];
  7054. if (e->kind == Entity_Variable) {
  7055. args[i] = lb_emit_conv(p, args[i], e->type);
  7056. }
  7057. }
  7058. if (!vari_expand) {
  7059. Type *variadic_type = param_tuple->variables[i]->type;
  7060. GB_ASSERT(is_type_slice(variadic_type));
  7061. variadic_type = base_type(variadic_type)->Slice.elem;
  7062. for (; i < arg_count; i++) {
  7063. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7064. }
  7065. }
  7066. } else {
  7067. for (isize i = 0; i < param_count; i++) {
  7068. Entity *e = param_tuple->variables[i];
  7069. if (e->kind == Entity_Variable) {
  7070. if (args[i].value == nullptr) {
  7071. continue;
  7072. }
  7073. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7074. args[i] = lb_emit_conv(p, args[i], e->type);
  7075. }
  7076. }
  7077. }
  7078. if (variadic && !vari_expand && !is_c_vararg) {
  7079. // variadic call argument generation
  7080. gbAllocator allocator = heap_allocator();
  7081. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7082. Type *elem_type = base_type(slice_type)->Slice.elem;
  7083. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7084. isize slice_len = arg_count+1 - (variadic_index+1);
  7085. if (slice_len > 0) {
  7086. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7087. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7088. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7089. lb_emit_store(p, addr, args[i]);
  7090. }
  7091. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7092. lbValue len = lb_const_int(m, t_int, slice_len);
  7093. lb_fill_slice(p, slice, base_elem, len);
  7094. }
  7095. arg_count = param_count;
  7096. args[variadic_index] = lb_addr_load(p, slice);
  7097. }
  7098. }
  7099. if (variadic && variadic_index+1 < param_count) {
  7100. for (isize i = variadic_index+1; i < param_count; i++) {
  7101. Entity *e = param_tuple->variables[i];
  7102. switch (e->Variable.param_value.kind) {
  7103. case ParameterValue_Constant:
  7104. args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  7105. break;
  7106. case ParameterValue_Nil:
  7107. args[i] = lb_const_nil(m, e->type);
  7108. break;
  7109. case ParameterValue_Location:
  7110. args[i] = lb_emit_source_code_location(p, proc_name, pos);
  7111. break;
  7112. case ParameterValue_Value:
  7113. args[i] = lb_build_expr(p, e->Variable.param_value.ast_value);
  7114. break;
  7115. }
  7116. }
  7117. }
  7118. isize final_count = param_count;
  7119. if (is_c_vararg) {
  7120. final_count = arg_count;
  7121. }
  7122. if (param_tuple != nullptr) {
  7123. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7124. Entity *e = param_tuple->variables[i];
  7125. if (args[i].type == nullptr) {
  7126. continue;
  7127. } else if (is_type_untyped_nil(args[i].type)) {
  7128. args[i] = lb_const_nil(m, e->type);
  7129. } else if (is_type_untyped_undef(args[i].type)) {
  7130. args[i] = lb_const_undef(m, e->type);
  7131. }
  7132. }
  7133. }
  7134. auto call_args = array_slice(args, 0, final_count);
  7135. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  7136. }
  7137. bool lb_is_const(lbValue value) {
  7138. LLVMValueRef v = value.value;
  7139. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  7140. // TODO(bill): Is this correct behaviour?
  7141. return true;
  7142. }
  7143. if (LLVMIsConstant(v)) {
  7144. return true;
  7145. }
  7146. return false;
  7147. }
  7148. bool lb_is_const_nil(lbValue value) {
  7149. LLVMValueRef v = value.value;
  7150. if (LLVMIsConstant(v)) {
  7151. if (LLVMIsAConstantAggregateZero(v)) {
  7152. return true;
  7153. } else if (LLVMIsAConstantPointerNull(v)) {
  7154. return true;
  7155. }
  7156. }
  7157. return false;
  7158. }
  7159. String lb_get_const_string(lbModule *m, lbValue value) {
  7160. GB_ASSERT(lb_is_const(value));
  7161. Type *t = base_type(value.type);
  7162. GB_ASSERT(are_types_identical(t, t_string));
  7163. unsigned ptr_indices[1] = {0};
  7164. unsigned len_indices[1] = {1};
  7165. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  7166. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  7167. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  7168. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  7169. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  7170. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  7171. size_t length = 0;
  7172. char const *text = LLVMGetAsString(underlying_ptr, &length);
  7173. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  7174. return make_string(cast(u8 const *)text, real_length);
  7175. }
  7176. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  7177. GB_ASSERT(is_type_pointer(addr.type));
  7178. Type *type = type_deref(addr.type);
  7179. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  7180. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  7181. }
  7182. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7183. AstPackage *pkg = m->info->runtime_package;
  7184. Entity *e = scope_lookup_current(pkg->scope, name);
  7185. lbValue *found = nullptr;
  7186. if (m != e->code_gen_module) {
  7187. gb_mutex_lock(&m->mutex);
  7188. }
  7189. found = map_get(&e->code_gen_module->values, hash_entity(e));
  7190. if (m != e->code_gen_module) {
  7191. gb_mutex_unlock(&m->mutex);
  7192. }
  7193. GB_ASSERT(found != nullptr);
  7194. return found->value;
  7195. }
  7196. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  7197. Type *vt = core_type(value.type);
  7198. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  7199. // TODO(bill): lb_emit_byte_swap
  7200. lbValue res = {};
  7201. res.type = platform_type;
  7202. res.value = value.value;
  7203. int sz = cast(int)type_size_of(vt);
  7204. if (sz > 1) {
  7205. if (is_type_float(platform_type)) {
  7206. String name = {};
  7207. switch (sz) {
  7208. case 4: name = str_lit("bswap_f32"); break;
  7209. case 8: name = str_lit("bswap_f64"); break;
  7210. default: GB_PANIC("unhandled byteswap size"); break;
  7211. }
  7212. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7213. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7214. } else {
  7215. GB_ASSERT(is_type_integer(platform_type));
  7216. String name = {};
  7217. switch (sz) {
  7218. case 2: name = str_lit("bswap_16"); break;
  7219. case 4: name = str_lit("bswap_32"); break;
  7220. case 8: name = str_lit("bswap_64"); break;
  7221. case 16: name = str_lit("bswap_128"); break;
  7222. default: GB_PANIC("unhandled byteswap size"); break;
  7223. }
  7224. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7225. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7226. }
  7227. }
  7228. return res;
  7229. }
  7230. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  7231. lbLoopData data = {};
  7232. lbValue max = lb_const_int(p->module, t_int, count);
  7233. data.idx_addr = lb_add_local_generated(p, index_type, true);
  7234. data.body = lb_create_block(p, "loop.body");
  7235. data.done = lb_create_block(p, "loop.done");
  7236. data.loop = lb_create_block(p, "loop.loop");
  7237. lb_emit_jump(p, data.loop);
  7238. lb_start_block(p, data.loop);
  7239. data.idx = lb_addr_load(p, data.idx_addr);
  7240. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  7241. lb_emit_if(p, cond, data.body, data.done);
  7242. lb_start_block(p, data.body);
  7243. return data;
  7244. }
  7245. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  7246. if (data.idx_addr.addr.value != nullptr) {
  7247. lb_emit_increment(p, data.idx_addr.addr);
  7248. lb_emit_jump(p, data.loop);
  7249. lb_start_block(p, data.done);
  7250. }
  7251. }
  7252. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  7253. lbValue res = {};
  7254. res.type = t_llvm_bool;
  7255. Type *t = x.type;
  7256. if (is_type_pointer(t)) {
  7257. if (op_kind == Token_CmpEq) {
  7258. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7259. } else if (op_kind == Token_NotEq) {
  7260. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7261. }
  7262. return res;
  7263. } else if (is_type_cstring(t)) {
  7264. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  7265. if (op_kind == Token_CmpEq) {
  7266. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  7267. } else if (op_kind == Token_NotEq) {
  7268. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  7269. }
  7270. return res;
  7271. } else if (is_type_proc(t)) {
  7272. if (op_kind == Token_CmpEq) {
  7273. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7274. } else if (op_kind == Token_NotEq) {
  7275. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7276. }
  7277. return res;
  7278. } else if (is_type_any(t)) {
  7279. // TODO(bill): is this correct behaviour for nil comparison for any?
  7280. lbValue data = lb_emit_struct_ev(p, x, 0);
  7281. lbValue ti = lb_emit_struct_ev(p, x, 1);
  7282. if (op_kind == Token_CmpEq) {
  7283. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  7284. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  7285. res.value = LLVMBuildOr(p->builder, a, b, "");
  7286. return res;
  7287. } else if (op_kind == Token_NotEq) {
  7288. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  7289. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  7290. res.value = LLVMBuildAnd(p->builder, a, b, "");
  7291. return res;
  7292. }
  7293. } else if (is_type_slice(t)) {
  7294. lbValue len = lb_emit_struct_ev(p, x, 1);
  7295. if (op_kind == Token_CmpEq) {
  7296. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7297. return res;
  7298. } else if (op_kind == Token_NotEq) {
  7299. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7300. return res;
  7301. }
  7302. } else if (is_type_dynamic_array(t)) {
  7303. lbValue cap = lb_emit_struct_ev(p, x, 2);
  7304. if (op_kind == Token_CmpEq) {
  7305. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7306. return res;
  7307. } else if (op_kind == Token_NotEq) {
  7308. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7309. return res;
  7310. }
  7311. } else if (is_type_map(t)) {
  7312. lbValue cap = lb_map_cap(p, x);
  7313. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  7314. } else if (is_type_union(t)) {
  7315. if (type_size_of(t) == 0) {
  7316. if (op_kind == Token_CmpEq) {
  7317. return lb_const_bool(p->module, t_llvm_bool, true);
  7318. } else if (op_kind == Token_NotEq) {
  7319. return lb_const_bool(p->module, t_llvm_bool, false);
  7320. }
  7321. } else {
  7322. lbValue tag = lb_emit_union_tag_value(p, x);
  7323. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  7324. }
  7325. } else if (is_type_typeid(t)) {
  7326. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  7327. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  7328. } else if (is_type_bit_field(t)) {
  7329. auto args = array_make<lbValue>(heap_allocator(), 2);
  7330. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7331. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7332. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7333. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7334. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7335. return res;
  7336. } else if (is_type_soa_struct(t)) {
  7337. Type *bt = base_type(t);
  7338. if (bt->Struct.soa_kind == StructSoa_Slice) {
  7339. lbValue len = lb_soa_struct_len(p, x);
  7340. if (op_kind == Token_CmpEq) {
  7341. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7342. return res;
  7343. } else if (op_kind == Token_NotEq) {
  7344. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7345. return res;
  7346. }
  7347. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  7348. lbValue cap = lb_soa_struct_cap(p, x);
  7349. if (op_kind == Token_CmpEq) {
  7350. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7351. return res;
  7352. } else if (op_kind == Token_NotEq) {
  7353. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7354. return res;
  7355. }
  7356. }
  7357. } else if (is_type_struct(t) && type_has_nil(t)) {
  7358. auto args = array_make<lbValue>(heap_allocator(), 2);
  7359. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7360. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7361. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7362. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7363. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7364. return res;
  7365. }
  7366. return {};
  7367. }
  7368. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  7369. Type *a = core_type(left.type);
  7370. Type *b = core_type(right.type);
  7371. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  7372. lbValue nil_check = {};
  7373. if (is_type_untyped_nil(left.type)) {
  7374. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  7375. } else if (is_type_untyped_nil(right.type)) {
  7376. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  7377. }
  7378. if (nil_check.value != nullptr) {
  7379. return nil_check;
  7380. }
  7381. if (are_types_identical(a, b)) {
  7382. // NOTE(bill): No need for a conversion
  7383. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  7384. left = lb_emit_conv(p, left, right.type);
  7385. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  7386. right = lb_emit_conv(p, right, left.type);
  7387. } else {
  7388. gbAllocator a = heap_allocator();
  7389. Type *lt = left.type;
  7390. Type *rt = right.type;
  7391. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  7392. Type *blt = base_type(lt);
  7393. Type *brt = base_type(rt);
  7394. GB_ASSERT(is_type_bit_field_value(blt));
  7395. GB_ASSERT(is_type_bit_field_value(brt));
  7396. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  7397. i64 bytes = bits / 8;
  7398. switch (bytes) {
  7399. case 1:
  7400. left = lb_emit_conv(p, left, t_u8);
  7401. right = lb_emit_conv(p, right, t_u8);
  7402. break;
  7403. case 2:
  7404. left = lb_emit_conv(p, left, t_u16);
  7405. right = lb_emit_conv(p, right, t_u16);
  7406. break;
  7407. case 4:
  7408. left = lb_emit_conv(p, left, t_u32);
  7409. right = lb_emit_conv(p, right, t_u32);
  7410. break;
  7411. case 8:
  7412. left = lb_emit_conv(p, left, t_u64);
  7413. right = lb_emit_conv(p, right, t_u64);
  7414. break;
  7415. default: GB_PANIC("Unknown integer size"); break;
  7416. }
  7417. }
  7418. lt = left.type;
  7419. rt = right.type;
  7420. i64 ls = type_size_of(lt);
  7421. i64 rs = type_size_of(rt);
  7422. if (ls < rs) {
  7423. left = lb_emit_conv(p, left, rt);
  7424. } else if (ls > rs) {
  7425. right = lb_emit_conv(p, right, lt);
  7426. } else {
  7427. right = lb_emit_conv(p, right, lt);
  7428. }
  7429. }
  7430. if (is_type_array(a)) {
  7431. Type *tl = base_type(a);
  7432. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  7433. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  7434. TokenKind cmp_op = Token_And;
  7435. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  7436. if (op_kind == Token_NotEq) {
  7437. res = lb_const_bool(p->module, t_llvm_bool, false);
  7438. cmp_op = Token_Or;
  7439. } else if (op_kind == Token_CmpEq) {
  7440. res = lb_const_bool(p->module, t_llvm_bool, true);
  7441. cmp_op = Token_And;
  7442. }
  7443. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  7444. i32 count = cast(i32)tl->Array.count;
  7445. if (inline_array_arith) {
  7446. // inline
  7447. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7448. lb_addr_store(p, val, res);
  7449. for (i32 i = 0; i < count; i++) {
  7450. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  7451. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  7452. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7453. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7454. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7455. }
  7456. return lb_addr_load(p, val);
  7457. } else {
  7458. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  7459. // TODO(bill): Test to see if this is actually faster!!!!
  7460. auto args = array_make<lbValue>(heap_allocator(), 3);
  7461. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7462. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  7463. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  7464. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  7465. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  7466. return lb_emit_conv(p, res, t_bool);
  7467. } else {
  7468. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7469. lb_addr_store(p, val, res);
  7470. auto loop_data = lb_loop_start(p, count, t_i32);
  7471. {
  7472. lbValue i = loop_data.idx;
  7473. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  7474. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  7475. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7476. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7477. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7478. }
  7479. lb_loop_end(p, loop_data);
  7480. return lb_addr_load(p, val);
  7481. }
  7482. }
  7483. }
  7484. if (is_type_string(a)) {
  7485. if (is_type_cstring(a)) {
  7486. left = lb_emit_conv(p, left, t_string);
  7487. right = lb_emit_conv(p, right, t_string);
  7488. }
  7489. char const *runtime_procedure = nullptr;
  7490. switch (op_kind) {
  7491. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  7492. case Token_NotEq: runtime_procedure = "string_ne"; break;
  7493. case Token_Lt: runtime_procedure = "string_lt"; break;
  7494. case Token_Gt: runtime_procedure = "string_gt"; break;
  7495. case Token_LtEq: runtime_procedure = "string_le"; break;
  7496. case Token_GtEq: runtime_procedure = "string_gt"; break;
  7497. }
  7498. GB_ASSERT(runtime_procedure != nullptr);
  7499. auto args = array_make<lbValue>(heap_allocator(), 2);
  7500. args[0] = left;
  7501. args[1] = right;
  7502. return lb_emit_runtime_call(p, runtime_procedure, args);
  7503. }
  7504. if (is_type_complex(a)) {
  7505. char const *runtime_procedure = "";
  7506. i64 sz = 8*type_size_of(a);
  7507. switch (sz) {
  7508. case 64:
  7509. switch (op_kind) {
  7510. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  7511. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  7512. }
  7513. break;
  7514. case 128:
  7515. switch (op_kind) {
  7516. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  7517. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  7518. }
  7519. break;
  7520. }
  7521. GB_ASSERT(runtime_procedure != nullptr);
  7522. auto args = array_make<lbValue>(heap_allocator(), 2);
  7523. args[0] = left;
  7524. args[1] = right;
  7525. return lb_emit_runtime_call(p, runtime_procedure, args);
  7526. }
  7527. if (is_type_quaternion(a)) {
  7528. char const *runtime_procedure = "";
  7529. i64 sz = 8*type_size_of(a);
  7530. switch (sz) {
  7531. case 128:
  7532. switch (op_kind) {
  7533. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  7534. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  7535. }
  7536. break;
  7537. case 256:
  7538. switch (op_kind) {
  7539. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  7540. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  7541. }
  7542. break;
  7543. }
  7544. GB_ASSERT(runtime_procedure != nullptr);
  7545. auto args = array_make<lbValue>(heap_allocator(), 2);
  7546. args[0] = left;
  7547. args[1] = right;
  7548. return lb_emit_runtime_call(p, runtime_procedure, args);
  7549. }
  7550. if (is_type_bit_set(a)) {
  7551. switch (op_kind) {
  7552. case Token_Lt:
  7553. case Token_LtEq:
  7554. case Token_Gt:
  7555. case Token_GtEq:
  7556. {
  7557. Type *it = bit_set_to_int(a);
  7558. lbValue lhs = lb_emit_transmute(p, left, it);
  7559. lbValue rhs = lb_emit_transmute(p, right, it);
  7560. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  7561. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  7562. // (lhs & rhs) == lhs
  7563. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  7564. res.type = t_llvm_bool;
  7565. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  7566. // (lhs & rhs) == rhs
  7567. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  7568. res.type = t_llvm_bool;
  7569. }
  7570. // NOTE(bill): Strict subsets
  7571. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  7572. // res &~ (lhs == rhs)
  7573. lbValue eq = {};
  7574. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  7575. eq.type = t_llvm_bool;
  7576. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  7577. }
  7578. return res;
  7579. }
  7580. case Token_CmpEq:
  7581. case Token_NotEq:
  7582. {
  7583. LLVMIntPredicate pred = {};
  7584. switch (op_kind) {
  7585. case Token_CmpEq: pred = LLVMIntEQ; break;
  7586. case Token_NotEq: pred = LLVMIntNE; break;
  7587. }
  7588. lbValue res = {};
  7589. res.type = t_llvm_bool;
  7590. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7591. return res;
  7592. }
  7593. }
  7594. }
  7595. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  7596. Type *t = left.type;
  7597. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  7598. Type *platform_type = integer_endian_type_to_platform_type(t);
  7599. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  7600. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  7601. left = x;
  7602. right = y;
  7603. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  7604. Type *platform_type = integer_endian_type_to_platform_type(t);
  7605. lbValue x = lb_emit_conv(p, left, platform_type);
  7606. lbValue y = lb_emit_conv(p, right, platform_type);
  7607. left = x;
  7608. right = y;
  7609. }
  7610. }
  7611. a = core_type(left.type);
  7612. b = core_type(right.type);
  7613. lbValue res = {};
  7614. res.type = t_llvm_bool;
  7615. if (is_type_integer(a) ||
  7616. is_type_boolean(a) ||
  7617. is_type_pointer(a) ||
  7618. is_type_proc(a) ||
  7619. is_type_enum(a)) {
  7620. LLVMIntPredicate pred = {};
  7621. if (is_type_unsigned(left.type)) {
  7622. switch (op_kind) {
  7623. case Token_Gt: pred = LLVMIntUGT; break;
  7624. case Token_GtEq: pred = LLVMIntUGE; break;
  7625. case Token_Lt: pred = LLVMIntULT; break;
  7626. case Token_LtEq: pred = LLVMIntULE; break;
  7627. }
  7628. } else {
  7629. switch (op_kind) {
  7630. case Token_Gt: pred = LLVMIntSGT; break;
  7631. case Token_GtEq: pred = LLVMIntSGE; break;
  7632. case Token_Lt: pred = LLVMIntSLT; break;
  7633. case Token_LtEq: pred = LLVMIntSLE; break;
  7634. }
  7635. }
  7636. switch (op_kind) {
  7637. case Token_CmpEq: pred = LLVMIntEQ; break;
  7638. case Token_NotEq: pred = LLVMIntNE; break;
  7639. }
  7640. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7641. } else if (is_type_float(a)) {
  7642. LLVMRealPredicate pred = {};
  7643. switch (op_kind) {
  7644. case Token_CmpEq: pred = LLVMRealOEQ; break;
  7645. case Token_Gt: pred = LLVMRealOGT; break;
  7646. case Token_GtEq: pred = LLVMRealOGE; break;
  7647. case Token_Lt: pred = LLVMRealOLT; break;
  7648. case Token_LtEq: pred = LLVMRealOLE; break;
  7649. case Token_NotEq: pred = LLVMRealONE; break;
  7650. }
  7651. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  7652. } else if (is_type_typeid(a)) {
  7653. LLVMIntPredicate pred = {};
  7654. switch (op_kind) {
  7655. case Token_Gt: pred = LLVMIntUGT; break;
  7656. case Token_GtEq: pred = LLVMIntUGE; break;
  7657. case Token_Lt: pred = LLVMIntULT; break;
  7658. case Token_LtEq: pred = LLVMIntULE; break;
  7659. case Token_CmpEq: pred = LLVMIntEQ; break;
  7660. case Token_NotEq: pred = LLVMIntNE; break;
  7661. }
  7662. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7663. } else {
  7664. 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)));
  7665. }
  7666. return res;
  7667. }
  7668. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  7669. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  7670. if (found != nullptr) {
  7671. lbValue value = {};
  7672. value.value = (*found)->value;
  7673. value.type = (*found)->type;
  7674. return value;
  7675. }
  7676. ast_node(pl, ProcLit, expr);
  7677. // NOTE(bill): Generate a new name
  7678. // parent$count
  7679. isize name_len = prefix_name.len + 1 + 8 + 1;
  7680. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  7681. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  7682. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  7683. String name = make_string((u8 *)name_text, name_len-1);
  7684. Type *type = type_of_expr(expr);
  7685. set_procedure_abi_types(heap_allocator(), type);
  7686. Token token = {};
  7687. token.pos = ast_token(expr).pos;
  7688. token.kind = Token_Ident;
  7689. token.string = name;
  7690. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  7691. e->decl_info = pl->decl;
  7692. lbProcedure *p = lb_create_procedure(m, e);
  7693. lbValue value = {};
  7694. value.value = p->value;
  7695. value.type = p->type;
  7696. array_add(&m->procedures_to_generate, p);
  7697. if (parent != nullptr) {
  7698. array_add(&parent->children, p);
  7699. } else {
  7700. string_map_set(&m->members, name, value);
  7701. }
  7702. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  7703. return value;
  7704. }
  7705. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  7706. lbModule *m = p->module;
  7707. Type *src_type = value.type;
  7708. bool is_ptr = is_type_pointer(src_type);
  7709. bool is_tuple = true;
  7710. Type *tuple = type;
  7711. if (type->kind != Type_Tuple) {
  7712. is_tuple = false;
  7713. tuple = make_optional_ok_type(type);
  7714. }
  7715. lbAddr v = lb_add_local_generated(p, tuple, true);
  7716. if (is_ptr) {
  7717. value = lb_emit_load(p, value);
  7718. }
  7719. Type *src = base_type(type_deref(src_type));
  7720. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  7721. Type *dst = tuple->Tuple.variables[0]->type;
  7722. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  7723. lbValue tag = {};
  7724. lbValue dst_tag = {};
  7725. lbValue cond = {};
  7726. lbValue data = {};
  7727. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  7728. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  7729. if (is_type_union_maybe_pointer(src)) {
  7730. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  7731. } else {
  7732. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  7733. dst_tag = lb_const_union_tag(m, src, dst);
  7734. }
  7735. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  7736. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  7737. if (data.value != nullptr) {
  7738. GB_ASSERT(is_type_union_maybe_pointer(src));
  7739. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  7740. } else {
  7741. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  7742. }
  7743. lb_emit_if(p, cond, ok_block, end_block);
  7744. lb_start_block(p, ok_block);
  7745. if (data.value == nullptr) {
  7746. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  7747. }
  7748. lb_emit_store(p, gep0, data);
  7749. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  7750. lb_emit_jump(p, end_block);
  7751. lb_start_block(p, end_block);
  7752. if (!is_tuple) {
  7753. if (do_conversion_check) {
  7754. // NOTE(bill): Panic on invalid conversion
  7755. Type *dst_type = tuple->Tuple.variables[0]->type;
  7756. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  7757. auto args = array_make<lbValue>(heap_allocator(), 6);
  7758. args[0] = ok;
  7759. args[1] = lb_const_string(m, pos.file);
  7760. args[2] = lb_const_int(m, t_int, pos.line);
  7761. args[3] = lb_const_int(m, t_int, pos.column);
  7762. args[4] = lb_typeid(m, src_type);
  7763. args[5] = lb_typeid(m, dst_type);
  7764. lb_emit_runtime_call(p, "type_assertion_check", args);
  7765. }
  7766. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  7767. }
  7768. return lb_addr_load(p, v);
  7769. }
  7770. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  7771. lbModule *m = p->module;
  7772. Type *src_type = value.type;
  7773. if (is_type_pointer(src_type)) {
  7774. value = lb_emit_load(p, value);
  7775. }
  7776. bool is_tuple = true;
  7777. Type *tuple = type;
  7778. if (type->kind != Type_Tuple) {
  7779. is_tuple = false;
  7780. tuple = make_optional_ok_type(type);
  7781. }
  7782. Type *dst_type = tuple->Tuple.variables[0]->type;
  7783. lbAddr v = lb_add_local_generated(p, tuple, true);
  7784. lbValue dst_typeid = lb_typeid(m, dst_type);
  7785. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  7786. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  7787. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  7788. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  7789. lb_emit_if(p, cond, ok_block, end_block);
  7790. lb_start_block(p, ok_block);
  7791. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  7792. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  7793. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  7794. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  7795. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  7796. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  7797. lb_emit_jump(p, end_block);
  7798. lb_start_block(p, end_block);
  7799. if (!is_tuple) {
  7800. // NOTE(bill): Panic on invalid conversion
  7801. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  7802. auto args = array_make<lbValue>(heap_allocator(), 6);
  7803. args[0] = ok;
  7804. args[1] = lb_const_string(m, pos.file);
  7805. args[2] = lb_const_int(m, t_int, pos.line);
  7806. args[3] = lb_const_int(m, t_int, pos.column);
  7807. args[4] = any_typeid;
  7808. args[5] = dst_typeid;
  7809. lb_emit_runtime_call(p, "type_assertion_check", args);
  7810. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  7811. }
  7812. return v;
  7813. }
  7814. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  7815. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  7816. }
  7817. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  7818. lbModule *m = p->module;
  7819. u64 prev_state_flags = p->module->state_flags;
  7820. defer (p->module->state_flags = prev_state_flags);
  7821. if (expr->state_flags != 0) {
  7822. u64 in = expr->state_flags;
  7823. u64 out = p->module->state_flags;
  7824. if (in & StateFlag_bounds_check) {
  7825. out |= StateFlag_bounds_check;
  7826. out &= ~StateFlag_no_bounds_check;
  7827. } else if (in & StateFlag_no_bounds_check) {
  7828. out |= StateFlag_no_bounds_check;
  7829. out &= ~StateFlag_bounds_check;
  7830. }
  7831. p->module->state_flags = out;
  7832. }
  7833. expr = unparen_expr(expr);
  7834. TypeAndValue tv = type_and_value_of_expr(expr);
  7835. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "%s", expr_to_string(expr));
  7836. GB_ASSERT(tv.mode != Addressing_Type);
  7837. if (tv.value.kind != ExactValue_Invalid) {
  7838. // NOTE(bill): Short on constant values
  7839. return lb_const_value(p->module, tv.type, tv.value);
  7840. }
  7841. switch (expr->kind) {
  7842. case_ast_node(bl, BasicLit, expr);
  7843. TokenPos pos = bl->token.pos;
  7844. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  7845. case_end;
  7846. case_ast_node(bd, BasicDirective, expr);
  7847. TokenPos pos = bd->token.pos;
  7848. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  7849. case_end;
  7850. case_ast_node(i, Implicit, expr);
  7851. return lb_addr_load(p, lb_build_addr(p, expr));
  7852. case_end;
  7853. case_ast_node(u, Undef, expr)
  7854. lbValue res = {};
  7855. if (is_type_untyped(tv.type)) {
  7856. res.value = nullptr;
  7857. res.type = t_untyped_undef;
  7858. } else {
  7859. res.value = LLVMGetUndef(lb_type(m, tv.type));
  7860. res.type = tv.type;
  7861. }
  7862. return res;
  7863. case_end;
  7864. case_ast_node(i, Ident, expr);
  7865. Entity *e = entity_from_expr(expr);
  7866. e = strip_entity_wrapping(e);
  7867. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  7868. if (e->kind == Entity_Builtin) {
  7869. Token token = ast_token(expr);
  7870. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  7871. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  7872. LIT(token.pos.file), token.pos.line, token.pos.column);
  7873. return {};
  7874. } else if (e->kind == Entity_Nil) {
  7875. lbValue res = {};
  7876. res.value = nullptr;
  7877. res.type = e->type;
  7878. return res;
  7879. }
  7880. GB_ASSERT(e->kind != Entity_ProcGroup);
  7881. auto *found = map_get(&p->module->values, hash_entity(e));
  7882. if (found) {
  7883. auto v = *found;
  7884. // NOTE(bill): This is because pointers are already pointers in LLVM
  7885. if (is_type_proc(v.type)) {
  7886. return v;
  7887. }
  7888. return lb_emit_load(p, v);
  7889. } else if (e != nullptr && e->kind == Entity_Variable) {
  7890. return lb_addr_load(p, lb_build_addr(p, expr));
  7891. }
  7892. gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  7893. String pkg = {};
  7894. if (e->pkg) {
  7895. pkg = e->pkg->name;
  7896. }
  7897. 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);
  7898. return {};
  7899. case_end;
  7900. case_ast_node(de, DerefExpr, expr);
  7901. return lb_addr_load(p, lb_build_addr(p, expr));
  7902. case_end;
  7903. case_ast_node(se, SelectorExpr, expr);
  7904. TypeAndValue tav = type_and_value_of_expr(expr);
  7905. GB_ASSERT(tav.mode != Addressing_Invalid);
  7906. return lb_addr_load(p, lb_build_addr(p, expr));
  7907. case_end;
  7908. case_ast_node(ise, ImplicitSelectorExpr, expr);
  7909. TypeAndValue tav = type_and_value_of_expr(expr);
  7910. GB_ASSERT(tav.mode == Addressing_Constant);
  7911. return lb_const_value(p->module, tv.type, tv.value);
  7912. case_end;
  7913. case_ast_node(se, SelectorCallExpr, expr);
  7914. GB_ASSERT(se->modified_call);
  7915. TypeAndValue tav = type_and_value_of_expr(expr);
  7916. GB_ASSERT(tav.mode != Addressing_Invalid);
  7917. return lb_build_expr(p, se->call);
  7918. case_end;
  7919. case_ast_node(te, TernaryExpr, expr);
  7920. LLVMValueRef incoming_values[2] = {};
  7921. LLVMBasicBlockRef incoming_blocks[2] = {};
  7922. GB_ASSERT(te->y != nullptr);
  7923. lbBlock *then = lb_create_block(p, "if.then");
  7924. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  7925. lbBlock *else_ = lb_create_block(p, "if.else");
  7926. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  7927. lb_start_block(p, then);
  7928. Type *type = default_type(type_of_expr(expr));
  7929. lb_open_scope(p);
  7930. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  7931. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7932. lb_emit_jump(p, done);
  7933. lb_start_block(p, else_);
  7934. lb_open_scope(p);
  7935. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  7936. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7937. lb_emit_jump(p, done);
  7938. lb_start_block(p, done);
  7939. lbValue res = {};
  7940. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  7941. res.type = type;
  7942. GB_ASSERT(p->curr_block->preds.count >= 2);
  7943. incoming_blocks[0] = p->curr_block->preds[0]->block;
  7944. incoming_blocks[1] = p->curr_block->preds[1]->block;
  7945. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  7946. return res;
  7947. case_end;
  7948. case_ast_node(te, TernaryIfExpr, expr);
  7949. LLVMValueRef incoming_values[2] = {};
  7950. LLVMBasicBlockRef incoming_blocks[2] = {};
  7951. GB_ASSERT(te->y != nullptr);
  7952. lbBlock *then = lb_create_block(p, "if.then");
  7953. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  7954. lbBlock *else_ = lb_create_block(p, "if.else");
  7955. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  7956. lb_start_block(p, then);
  7957. Type *type = default_type(type_of_expr(expr));
  7958. lb_open_scope(p);
  7959. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  7960. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7961. lb_emit_jump(p, done);
  7962. lb_start_block(p, else_);
  7963. lb_open_scope(p);
  7964. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  7965. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7966. lb_emit_jump(p, done);
  7967. lb_start_block(p, done);
  7968. lbValue res = {};
  7969. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  7970. res.type = type;
  7971. GB_ASSERT(p->curr_block->preds.count >= 2);
  7972. incoming_blocks[0] = p->curr_block->preds[0]->block;
  7973. incoming_blocks[1] = p->curr_block->preds[1]->block;
  7974. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  7975. return res;
  7976. case_end;
  7977. case_ast_node(te, TernaryWhenExpr, expr);
  7978. TypeAndValue tav = type_and_value_of_expr(te->cond);
  7979. GB_ASSERT(tav.mode == Addressing_Constant);
  7980. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  7981. if (tav.value.value_bool) {
  7982. return lb_build_expr(p, te->x);
  7983. } else {
  7984. return lb_build_expr(p, te->y);
  7985. }
  7986. case_end;
  7987. case_ast_node(ta, TypeAssertion, expr);
  7988. TokenPos pos = ast_token(expr).pos;
  7989. Type *type = tv.type;
  7990. lbValue e = lb_build_expr(p, ta->expr);
  7991. Type *t = type_deref(e.type);
  7992. if (is_type_union(t)) {
  7993. return lb_emit_union_cast(p, e, type, pos);
  7994. } else if (is_type_any(t)) {
  7995. return lb_emit_any_cast(p, e, type, pos);
  7996. } else {
  7997. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  7998. }
  7999. case_end;
  8000. case_ast_node(tc, TypeCast, expr);
  8001. lbValue e = lb_build_expr(p, tc->expr);
  8002. switch (tc->token.kind) {
  8003. case Token_cast:
  8004. return lb_emit_conv(p, e, tv.type);
  8005. case Token_transmute:
  8006. return lb_emit_transmute(p, e, tv.type);
  8007. }
  8008. GB_PANIC("Invalid AST TypeCast");
  8009. case_end;
  8010. case_ast_node(ac, AutoCast, expr);
  8011. return lb_build_expr(p, ac->expr);
  8012. case_end;
  8013. case_ast_node(ue, UnaryExpr, expr);
  8014. switch (ue->op.kind) {
  8015. case Token_And: {
  8016. Ast *ue_expr = unparen_expr(ue->expr);
  8017. if (ue_expr->kind == Ast_CompoundLit) {
  8018. lbValue v = lb_build_expr(p, ue->expr);
  8019. Type *type = v.type;
  8020. lbAddr addr = {};
  8021. if (p->is_startup) {
  8022. addr = lb_add_global_generated(p->module, type, v);
  8023. } else {
  8024. addr = lb_add_local_generated(p, type, false);
  8025. }
  8026. lb_addr_store(p, addr, v);
  8027. return addr.addr;
  8028. } else if (ue_expr->kind == Ast_TypeAssertion) {
  8029. gbAllocator a = heap_allocator();
  8030. GB_ASSERT(is_type_pointer(tv.type));
  8031. ast_node(ta, TypeAssertion, ue_expr);
  8032. TokenPos pos = ast_token(expr).pos;
  8033. Type *type = type_of_expr(ue_expr);
  8034. GB_ASSERT(!is_type_tuple(type));
  8035. lbValue e = lb_build_expr(p, ta->expr);
  8036. Type *t = type_deref(e.type);
  8037. if (is_type_union(t)) {
  8038. lbValue v = e;
  8039. if (!is_type_pointer(v.type)) {
  8040. v = lb_address_from_load_or_generate_local(p, v);
  8041. }
  8042. Type *src_type = type_deref(v.type);
  8043. Type *dst_type = type;
  8044. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  8045. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  8046. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  8047. auto args = array_make<lbValue>(heap_allocator(), 6);
  8048. args[0] = ok;
  8049. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8050. args[2] = lb_const_int(p->module, t_int, pos.line);
  8051. args[3] = lb_const_int(p->module, t_int, pos.column);
  8052. args[4] = lb_typeid(p->module, src_type);
  8053. args[5] = lb_typeid(p->module, dst_type);
  8054. lb_emit_runtime_call(p, "type_assertion_check", args);
  8055. lbValue data_ptr = v;
  8056. return lb_emit_conv(p, data_ptr, tv.type);
  8057. } else if (is_type_any(t)) {
  8058. lbValue v = e;
  8059. if (is_type_pointer(v.type)) {
  8060. v = lb_emit_load(p, v);
  8061. }
  8062. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  8063. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  8064. lbValue id = lb_typeid(p->module, type);
  8065. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  8066. auto args = array_make<lbValue>(heap_allocator(), 6);
  8067. args[0] = ok;
  8068. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8069. args[2] = lb_const_int(p->module, t_int, pos.line);
  8070. args[3] = lb_const_int(p->module, t_int, pos.column);
  8071. args[4] = any_id;
  8072. args[5] = id;
  8073. lb_emit_runtime_call(p, "type_assertion_check", args);
  8074. return lb_emit_conv(p, data_ptr, tv.type);
  8075. } else {
  8076. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  8077. }
  8078. }
  8079. return lb_build_addr_ptr(p, ue->expr);
  8080. }
  8081. default:
  8082. {
  8083. lbValue v = lb_build_expr(p, ue->expr);
  8084. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  8085. }
  8086. }
  8087. case_end;
  8088. case_ast_node(be, BinaryExpr, expr);
  8089. return lb_build_binary_expr(p, expr);
  8090. case_end;
  8091. case_ast_node(pl, ProcLit, expr);
  8092. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  8093. case_end;
  8094. case_ast_node(cl, CompoundLit, expr);
  8095. return lb_addr_load(p, lb_build_addr(p, expr));
  8096. case_end;
  8097. case_ast_node(ce, CallExpr, expr);
  8098. lbValue res = lb_build_call_expr(p, expr);
  8099. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  8100. GB_ASSERT(is_type_tuple(res.type));
  8101. GB_ASSERT(res.type->Tuple.variables.count == 2);
  8102. return lb_emit_struct_ev(p, res, 0);
  8103. }
  8104. return res;
  8105. case_end;
  8106. case_ast_node(se, SliceExpr, expr);
  8107. return lb_addr_load(p, lb_build_addr(p, expr));
  8108. case_end;
  8109. case_ast_node(ie, IndexExpr, expr);
  8110. return lb_addr_load(p, lb_build_addr(p, expr));
  8111. case_end;
  8112. }
  8113. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  8114. return {};
  8115. }
  8116. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  8117. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  8118. String name = e->token.string;
  8119. Entity *parent = e->using_parent;
  8120. Selection sel = lookup_field(parent->type, name, false);
  8121. GB_ASSERT(sel.entity != nullptr);
  8122. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  8123. lbValue v = {};
  8124. if (pv != nullptr) {
  8125. v = *pv;
  8126. } else {
  8127. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  8128. v = lb_build_addr_ptr(p, e->using_expr);
  8129. }
  8130. GB_ASSERT(v.value != nullptr);
  8131. GB_ASSERT(parent->type == type_deref(v.type));
  8132. return lb_emit_deep_field_gep(p, v, sel);
  8133. }
  8134. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  8135. GB_ASSERT(e != nullptr);
  8136. if (e->kind == Entity_Constant) {
  8137. Type *t = default_type(type_of_expr(expr));
  8138. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  8139. lbAddr g = lb_add_global_generated(p->module, t, v);
  8140. return g;
  8141. }
  8142. lbValue v = {};
  8143. lbValue *found = map_get(&p->module->values, hash_entity(e));
  8144. if (found) {
  8145. v = *found;
  8146. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  8147. // NOTE(bill): Calculate the using variable every time
  8148. v = lb_get_using_variable(p, e);
  8149. }
  8150. if (v.value == nullptr) {
  8151. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  8152. LIT(p->name),
  8153. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  8154. GB_PANIC("Unknown value");
  8155. }
  8156. return lb_addr(v);
  8157. }
  8158. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  8159. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  8160. gbAllocator a = heap_allocator();
  8161. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  8162. map_type = base_type(map_type);
  8163. GB_ASSERT(map_type->kind == Type_Map);
  8164. Type *key_type = map_type->Map.key;
  8165. Type *val_type = map_type->Map.value;
  8166. // NOTE(bill): Removes unnecessary allocation if split gep
  8167. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  8168. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  8169. lb_emit_store(p, gep0, m);
  8170. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_const_bool(p->module, t_bool, is_type_string(key_type)));
  8171. i64 entry_size = type_size_of (map_type->Map.entry_type);
  8172. i64 entry_align = type_align_of (map_type->Map.entry_type);
  8173. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  8174. i64 value_size = type_size_of (map_type->Map.value);
  8175. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  8176. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  8177. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, value_offset));
  8178. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, value_size));
  8179. return lb_addr_load(p, h);
  8180. }
  8181. lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) {
  8182. Type *hash_type = t_u64;
  8183. lbAddr v = lb_add_local_generated(p, t_map_key, true);
  8184. lbValue vp = lb_addr_get_ptr(p, v);
  8185. Type *t = base_type(key.type);
  8186. key = lb_emit_conv(p, key, key_type);
  8187. if (is_type_string(t)) {
  8188. lbValue str = lb_emit_conv(p, key, t_string);
  8189. lbValue hashed_str = {};
  8190. if (lb_is_const(str)) {
  8191. String v = lb_get_const_string(p->module, str);
  8192. u64 hs = fnv64a(v.text, v.len);
  8193. hashed_str = lb_const_int(p->module, t_u64, hs);
  8194. } else {
  8195. auto args = array_make<lbValue>(heap_allocator(), 1);
  8196. args[0] = str;
  8197. hashed_str = lb_emit_runtime_call(p, "default_hash_string", args);
  8198. }
  8199. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_str);
  8200. lbValue key_data = lb_emit_struct_ep(p, vp, 1);
  8201. key_data = lb_emit_conv(p, key_data, alloc_type_pointer(key_type));
  8202. lb_emit_store(p, key_data, str);
  8203. } else {
  8204. i64 sz = type_size_of(t);
  8205. GB_ASSERT(sz <= 8);
  8206. if (sz != 0) {
  8207. auto args = array_make<lbValue>(heap_allocator(), 2);
  8208. args[0] = lb_address_from_load_or_generate_local(p, key);
  8209. args[1] = lb_const_int(p->module, t_int, sz);
  8210. lbValue hash = lb_emit_runtime_call(p, "default_hash_ptr", args);
  8211. lbValue hash_ptr = lb_emit_struct_ep(p, vp, 0);
  8212. lbValue key_data = lb_emit_struct_ep(p, vp, 1);
  8213. key_data = lb_emit_conv(p, key_data, alloc_type_pointer(key_type));
  8214. lb_emit_store(p, hash_ptr, hash);
  8215. lb_emit_store(p, key_data, key);
  8216. }
  8217. }
  8218. return lb_addr_load(p, v);
  8219. }
  8220. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  8221. lbValue map_key, lbValue map_value, Ast *node) {
  8222. map_type = base_type(map_type);
  8223. GB_ASSERT(map_type->kind == Type_Map);
  8224. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  8225. lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key);
  8226. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  8227. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  8228. lb_addr_store(p, value_addr, v);
  8229. auto args = array_make<lbValue>(heap_allocator(), 4);
  8230. args[0] = h;
  8231. args[1] = key;
  8232. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  8233. args[3] = lb_emit_source_code_location(p, node);
  8234. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  8235. }
  8236. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  8237. expr = unparen_expr(expr);
  8238. switch (expr->kind) {
  8239. case_ast_node(i, Implicit, expr);
  8240. lbAddr v = {};
  8241. switch (i->kind) {
  8242. case Token_context:
  8243. v = lb_find_or_generate_context_ptr(p);
  8244. break;
  8245. }
  8246. GB_ASSERT(v.addr.value != nullptr);
  8247. return v;
  8248. case_end;
  8249. case_ast_node(i, Ident, expr);
  8250. if (is_blank_ident(expr)) {
  8251. lbAddr val = {};
  8252. return val;
  8253. }
  8254. String name = i->token.string;
  8255. Entity *e = entity_of_node(expr);
  8256. return lb_build_addr_from_entity(p, e, expr);
  8257. case_end;
  8258. case_ast_node(se, SelectorExpr, expr);
  8259. Ast *sel = unparen_expr(se->selector);
  8260. if (sel->kind == Ast_Ident) {
  8261. String selector = sel->Ident.token.string;
  8262. TypeAndValue tav = type_and_value_of_expr(se->expr);
  8263. if (tav.mode == Addressing_Invalid) {
  8264. // NOTE(bill): Imports
  8265. Entity *imp = entity_of_node(se->expr);
  8266. if (imp != nullptr) {
  8267. GB_ASSERT(imp->kind == Entity_ImportName);
  8268. }
  8269. return lb_build_addr(p, unparen_expr(se->selector));
  8270. }
  8271. Type *type = base_type(tav.type);
  8272. if (tav.mode == Addressing_Type) { // Addressing_Type
  8273. Selection sel = lookup_field(type, selector, true);
  8274. Entity *e = sel.entity;
  8275. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  8276. GB_ASSERT(e->flags & EntityFlag_TypeField);
  8277. String name = e->token.string;
  8278. /*if (name == "names") {
  8279. lbValue ti_ptr = lb_type_info(m, type);
  8280. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  8281. lbValue names_ptr = nullptr;
  8282. if (is_type_enum(type)) {
  8283. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  8284. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  8285. } else if (type->kind == Type_Struct) {
  8286. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  8287. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  8288. }
  8289. return ir_addr(names_ptr);
  8290. } else */{
  8291. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  8292. }
  8293. GB_PANIC("Unreachable");
  8294. }
  8295. Selection sel = lookup_field(type, selector, false);
  8296. GB_ASSERT(sel.entity != nullptr);
  8297. if (sel.entity->type->kind == Type_BitFieldValue) {
  8298. lbAddr addr = lb_build_addr(p, se->expr);
  8299. Type *bft = type_deref(lb_addr_type(addr));
  8300. if (sel.index.count == 1) {
  8301. GB_ASSERT(is_type_bit_field(bft));
  8302. i32 index = sel.index[0];
  8303. return lb_addr_bit_field(lb_addr_get_ptr(p, addr), index);
  8304. } else {
  8305. Selection s = sel;
  8306. s.index.count--;
  8307. i32 index = s.index[s.index.count-1];
  8308. lbValue a = lb_addr_get_ptr(p, addr);
  8309. a = lb_emit_deep_field_gep(p, a, s);
  8310. return lb_addr_bit_field(a, index);
  8311. }
  8312. } else {
  8313. lbAddr addr = lb_build_addr(p, se->expr);
  8314. if (addr.kind == lbAddr_Map) {
  8315. lbValue v = lb_addr_load(p, addr);
  8316. lbValue a = lb_address_from_load_or_generate_local(p, v);
  8317. a = lb_emit_deep_field_gep(p, a, sel);
  8318. return lb_addr(a);
  8319. } else if (addr.kind == lbAddr_Context) {
  8320. GB_ASSERT(sel.index.count > 0);
  8321. if (addr.ctx.sel.index.count >= 0) {
  8322. sel = selection_combine(addr.ctx.sel, sel);
  8323. }
  8324. addr.ctx.sel = sel;
  8325. addr.kind = lbAddr_Context;
  8326. return addr;
  8327. } else if (addr.kind == lbAddr_SoaVariable) {
  8328. lbValue index = addr.soa.index;
  8329. i32 first_index = sel.index[0];
  8330. Selection sub_sel = sel;
  8331. sub_sel.index.data += 1;
  8332. sub_sel.index.count -= 1;
  8333. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  8334. Type *t = base_type(type_deref(addr.addr.type));
  8335. GB_ASSERT(is_type_soa_struct(t));
  8336. // TODO(bill): Bounds check
  8337. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  8338. lbValue len = lb_soa_struct_len(p, addr.addr);
  8339. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  8340. }
  8341. lbValue item = {};
  8342. if (t->Struct.soa_kind == StructSoa_Fixed) {
  8343. item = lb_emit_array_ep(p, arr, index);
  8344. } else {
  8345. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  8346. }
  8347. if (sub_sel.index.count > 0) {
  8348. item = lb_emit_deep_field_gep(p, item, sub_sel);
  8349. }
  8350. return lb_addr(item);
  8351. }
  8352. lbValue a = lb_addr_get_ptr(p, addr);
  8353. a = lb_emit_deep_field_gep(p, a, sel);
  8354. return lb_addr(a);
  8355. }
  8356. } else {
  8357. GB_PANIC("Unsupported selector expression");
  8358. }
  8359. case_end;
  8360. case_ast_node(se, SelectorCallExpr, expr);
  8361. GB_ASSERT(se->modified_call);
  8362. TypeAndValue tav = type_and_value_of_expr(expr);
  8363. GB_ASSERT(tav.mode != Addressing_Invalid);
  8364. return lb_build_addr(p, se->call);
  8365. case_end;
  8366. case_ast_node(ta, TypeAssertion, expr);
  8367. gbAllocator a = heap_allocator();
  8368. TokenPos pos = ast_token(expr).pos;
  8369. lbValue e = lb_build_expr(p, ta->expr);
  8370. Type *t = type_deref(e.type);
  8371. if (is_type_union(t)) {
  8372. Type *type = type_of_expr(expr);
  8373. lbAddr v = lb_add_local_generated(p, type, false);
  8374. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  8375. return v;
  8376. } else if (is_type_any(t)) {
  8377. Type *type = type_of_expr(expr);
  8378. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  8379. } else {
  8380. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8381. }
  8382. case_end;
  8383. case_ast_node(ue, UnaryExpr, expr);
  8384. switch (ue->op.kind) {
  8385. case Token_And: {
  8386. return lb_build_addr(p, ue->expr);
  8387. }
  8388. default:
  8389. GB_PANIC("Invalid unary expression for lb_build_addr");
  8390. }
  8391. case_end;
  8392. case_ast_node(be, BinaryExpr, expr);
  8393. lbValue v = lb_build_expr(p, expr);
  8394. Type *t = v.type;
  8395. if (is_type_pointer(t)) {
  8396. return lb_addr(v);
  8397. }
  8398. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  8399. case_end;
  8400. case_ast_node(ie, IndexExpr, expr);
  8401. Type *t = base_type(type_of_expr(ie->expr));
  8402. gbAllocator a = heap_allocator();
  8403. bool deref = is_type_pointer(t);
  8404. t = base_type(type_deref(t));
  8405. if (is_type_soa_struct(t)) {
  8406. // SOA STRUCTURES!!!!
  8407. lbValue val = lb_build_addr_ptr(p, ie->expr);
  8408. if (deref) {
  8409. val = lb_emit_load(p, val);
  8410. }
  8411. lbValue index = lb_build_expr(p, ie->index);
  8412. return lb_addr_soa_variable(val, index, ie->index);
  8413. }
  8414. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  8415. // SOA Structures for slices/dynamic arrays
  8416. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  8417. lbValue field = lb_build_expr(p, ie->expr);
  8418. lbValue index = lb_build_expr(p, ie->index);
  8419. if (!build_context.no_bounds_check) {
  8420. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  8421. // GB_ASSERT(LLVMIsALoadInst(field.value));
  8422. // lbValue a = {};
  8423. // a.value = LLVMGetOperand(field.value, 0);
  8424. // a.type = alloc_type_pointer(field.type);
  8425. // irInstr *b = &a->Instr;
  8426. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  8427. // lbValue base_struct = b->StructElementPtr.address;
  8428. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  8429. // lbValue len = ir_soa_struct_len(p, base_struct);
  8430. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8431. }
  8432. lbValue val = lb_emit_ptr_offset(p, field, index);
  8433. return lb_addr(val);
  8434. }
  8435. if (!is_type_indexable(t)) {
  8436. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8437. if (found != nullptr) {
  8438. if (found->kind == TypeAtomOp_index_get) {
  8439. return lb_build_addr(p, found->node);
  8440. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  8441. return lb_addr(lb_build_expr(p, found->node));
  8442. } else if (found->kind == TypeAtomOp_index_set) {
  8443. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  8444. if (deref) {
  8445. ptr = lb_emit_load(p, ptr);
  8446. }
  8447. lbAddr addr = {lbAddr_AtomOp_index_set};
  8448. addr.addr = ptr;
  8449. addr.index_set.index = lb_build_expr(p, ie->index);
  8450. addr.index_set.node = found->node;
  8451. return addr;
  8452. }
  8453. }
  8454. }
  8455. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  8456. if (is_type_map(t)) {
  8457. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  8458. if (deref) {
  8459. map_val = lb_emit_load(p, map_val);
  8460. }
  8461. lbValue key = lb_build_expr(p, ie->index);
  8462. key = lb_emit_conv(p, key, t->Map.key);
  8463. Type *result_type = type_of_expr(expr);
  8464. return lb_addr_map(map_val, key, t, result_type);
  8465. }
  8466. switch (t->kind) {
  8467. case Type_Array: {
  8468. lbValue array = {};
  8469. array = lb_build_addr_ptr(p, ie->expr);
  8470. if (deref) {
  8471. array = lb_emit_load(p, array);
  8472. }
  8473. lbValue index = lb_build_expr(p, ie->index);
  8474. index = lb_emit_conv(p, index, t_int);
  8475. lbValue elem = lb_emit_array_ep(p, array, index);
  8476. auto index_tv = type_and_value_of_expr(ie->index);
  8477. if (index_tv.mode != Addressing_Constant) {
  8478. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  8479. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8480. }
  8481. return lb_addr(elem);
  8482. }
  8483. case Type_EnumeratedArray: {
  8484. lbValue array = {};
  8485. array = lb_build_addr_ptr(p, ie->expr);
  8486. if (deref) {
  8487. array = lb_emit_load(p, array);
  8488. }
  8489. Type *index_type = t->EnumeratedArray.index;
  8490. auto index_tv = type_and_value_of_expr(ie->index);
  8491. lbValue index = {};
  8492. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  8493. if (index_tv.mode == Addressing_Constant) {
  8494. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  8495. index = lb_const_value(p->module, index_type, idx);
  8496. } else {
  8497. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8498. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  8499. }
  8500. } else {
  8501. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8502. }
  8503. lbValue elem = lb_emit_array_ep(p, array, index);
  8504. if (index_tv.mode != Addressing_Constant) {
  8505. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  8506. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8507. }
  8508. return lb_addr(elem);
  8509. }
  8510. case Type_Slice: {
  8511. lbValue slice = {};
  8512. slice = lb_build_expr(p, ie->expr);
  8513. if (deref) {
  8514. slice = lb_emit_load(p, slice);
  8515. }
  8516. lbValue elem = lb_slice_elem(p, slice);
  8517. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8518. lbValue len = lb_slice_len(p, slice);
  8519. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8520. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8521. return lb_addr(v);
  8522. }
  8523. case Type_RelativeSlice: {
  8524. lbAddr slice_addr = {};
  8525. if (deref) {
  8526. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  8527. } else {
  8528. slice_addr = lb_build_addr(p, ie->expr);
  8529. }
  8530. lbValue slice = lb_addr_load(p, slice_addr);
  8531. lbValue elem = lb_slice_elem(p, slice);
  8532. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8533. lbValue len = lb_slice_len(p, slice);
  8534. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8535. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8536. return lb_addr(v);
  8537. }
  8538. case Type_DynamicArray: {
  8539. lbValue dynamic_array = {};
  8540. dynamic_array = lb_build_expr(p, ie->expr);
  8541. if (deref) {
  8542. dynamic_array = lb_emit_load(p, dynamic_array);
  8543. }
  8544. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  8545. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  8546. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8547. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8548. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8549. return lb_addr(v);
  8550. }
  8551. case Type_Basic: { // Basic_string
  8552. lbValue str;
  8553. lbValue elem;
  8554. lbValue len;
  8555. lbValue index;
  8556. str = lb_build_expr(p, ie->expr);
  8557. if (deref) {
  8558. str = lb_emit_load(p, str);
  8559. }
  8560. elem = lb_string_elem(p, str);
  8561. len = lb_string_len(p, str);
  8562. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8563. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8564. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  8565. }
  8566. }
  8567. case_end;
  8568. case_ast_node(se, SliceExpr, expr);
  8569. gbAllocator a = heap_allocator();
  8570. lbValue low = lb_const_int(p->module, t_int, 0);
  8571. lbValue high = {};
  8572. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  8573. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  8574. bool no_indices = se->low == nullptr && se->high == nullptr;
  8575. {
  8576. Type *type = base_type(type_of_expr(se->expr));
  8577. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  8578. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  8579. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  8580. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8581. if (found) {
  8582. lbValue base = lb_build_expr(p, found->node);
  8583. Type *slice_type = base.type;
  8584. lbValue len = lb_slice_len(p, base);
  8585. if (high.value == nullptr) high = len;
  8586. if (!no_indices) {
  8587. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8588. }
  8589. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8590. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8591. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8592. lb_fill_slice(p, slice, elem, new_len);
  8593. return slice;
  8594. }
  8595. }
  8596. }
  8597. }
  8598. lbAddr addr = lb_build_addr(p, se->expr);
  8599. lbValue base = lb_addr_load(p, addr);
  8600. Type *type = base_type(base.type);
  8601. if (is_type_pointer(type)) {
  8602. type = base_type(type_deref(type));
  8603. addr = lb_addr(base);
  8604. base = lb_addr_load(p, addr);
  8605. }
  8606. switch (type->kind) {
  8607. case Type_Slice: {
  8608. Type *slice_type = type;
  8609. lbValue len = lb_slice_len(p, base);
  8610. if (high.value == nullptr) high = len;
  8611. if (!no_indices) {
  8612. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8613. }
  8614. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8615. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8616. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8617. lb_fill_slice(p, slice, elem, new_len);
  8618. return slice;
  8619. }
  8620. case Type_RelativeSlice:
  8621. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  8622. break;
  8623. case Type_DynamicArray: {
  8624. Type *elem_type = type->DynamicArray.elem;
  8625. Type *slice_type = alloc_type_slice(elem_type);
  8626. lbValue len = lb_dynamic_array_len(p, base);
  8627. if (high.value == nullptr) high = len;
  8628. if (!no_indices) {
  8629. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8630. }
  8631. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  8632. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8633. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8634. lb_fill_slice(p, slice, elem, new_len);
  8635. return slice;
  8636. }
  8637. case Type_Array: {
  8638. Type *slice_type = alloc_type_slice(type->Array.elem);
  8639. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  8640. if (high.value == nullptr) high = len;
  8641. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  8642. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  8643. if (!low_const || !high_const) {
  8644. if (!no_indices) {
  8645. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8646. }
  8647. }
  8648. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  8649. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8650. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8651. lb_fill_slice(p, slice, elem, new_len);
  8652. return slice;
  8653. }
  8654. case Type_Basic: {
  8655. GB_ASSERT(type == t_string);
  8656. lbValue len = lb_string_len(p, base);
  8657. if (high.value == nullptr) high = len;
  8658. if (!no_indices) {
  8659. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8660. }
  8661. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  8662. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8663. lbAddr str = lb_add_local_generated(p, t_string, false);
  8664. lb_fill_string(p, str, elem, new_len);
  8665. return str;
  8666. }
  8667. case Type_Struct:
  8668. if (is_type_soa_struct(type)) {
  8669. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  8670. if (high.value == nullptr) high = len;
  8671. if (!no_indices) {
  8672. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8673. }
  8674. #if 1
  8675. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  8676. if (type->Struct.soa_kind == StructSoa_Fixed) {
  8677. i32 field_count = cast(i32)type->Struct.fields.count;
  8678. for (i32 i = 0; i < field_count; i++) {
  8679. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8680. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  8681. field_src = lb_emit_array_ep(p, field_src, low);
  8682. lb_emit_store(p, field_dst, field_src);
  8683. }
  8684. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  8685. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8686. lb_emit_store(p, len_dst, new_len);
  8687. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  8688. if (no_indices) {
  8689. lb_addr_store(p, dst, base);
  8690. } else {
  8691. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  8692. for (i32 i = 0; i < field_count; i++) {
  8693. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8694. lbValue field_src = lb_emit_struct_ev(p, base, i);
  8695. field_src = lb_emit_ptr_offset(p, field_src, low);
  8696. lb_emit_store(p, field_dst, field_src);
  8697. }
  8698. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  8699. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8700. lb_emit_store(p, len_dst, new_len);
  8701. }
  8702. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  8703. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  8704. for (i32 i = 0; i < field_count; i++) {
  8705. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8706. lbValue field_src = lb_emit_struct_ev(p, base, i);
  8707. field_src = lb_emit_ptr_offset(p, field_src, low);
  8708. lb_emit_store(p, field_dst, field_src);
  8709. }
  8710. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  8711. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8712. lb_emit_store(p, len_dst, new_len);
  8713. }
  8714. return dst;
  8715. #endif
  8716. }
  8717. break;
  8718. }
  8719. GB_PANIC("Unknown slicable type");
  8720. case_end;
  8721. case_ast_node(de, DerefExpr, expr);
  8722. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  8723. lbAddr addr = lb_build_addr(p, de->expr);
  8724. addr.relative.deref = true;
  8725. return addr;
  8726. }
  8727. lbValue addr = lb_build_expr(p, de->expr);
  8728. return lb_addr(addr);
  8729. case_end;
  8730. case_ast_node(ce, CallExpr, expr);
  8731. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  8732. lbValue e = lb_build_expr(p, expr);
  8733. lbAddr v = lb_add_local_generated(p, e.type, false);
  8734. lb_addr_store(p, v, e);
  8735. return v;
  8736. case_end;
  8737. case_ast_node(cl, CompoundLit, expr);
  8738. Type *type = type_of_expr(expr);
  8739. Type *bt = base_type(type);
  8740. lbAddr v = lb_add_local_generated(p, type, true);
  8741. Type *et = nullptr;
  8742. switch (bt->kind) {
  8743. case Type_Array: et = bt->Array.elem; break;
  8744. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  8745. case Type_Slice: et = bt->Slice.elem; break;
  8746. case Type_BitSet: et = bt->BitSet.elem; break;
  8747. case Type_SimdVector: et = bt->SimdVector.elem; break;
  8748. }
  8749. String proc_name = {};
  8750. if (p->entity) {
  8751. proc_name = p->entity->token.string;
  8752. }
  8753. TokenPos pos = ast_token(expr).pos;
  8754. switch (bt->kind) {
  8755. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  8756. case Type_Struct: {
  8757. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  8758. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  8759. bool is_raw_union = is_type_raw_union(bt);
  8760. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  8761. TypeStruct *st = &bt->Struct;
  8762. if (cl->elems.count > 0) {
  8763. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8764. for_array(field_index, cl->elems) {
  8765. Ast *elem = cl->elems[field_index];
  8766. lbValue field_expr = {};
  8767. Entity *field = nullptr;
  8768. isize index = field_index;
  8769. if (elem->kind == Ast_FieldValue) {
  8770. ast_node(fv, FieldValue, elem);
  8771. String name = fv->field->Ident.token.string;
  8772. Selection sel = lookup_field(bt, name, false);
  8773. index = sel.index[0];
  8774. elem = fv->value;
  8775. TypeAndValue tav = type_and_value_of_expr(elem);
  8776. } else {
  8777. TypeAndValue tav = type_and_value_of_expr(elem);
  8778. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  8779. index = sel.index[0];
  8780. }
  8781. field = st->fields[index];
  8782. Type *ft = field->type;
  8783. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  8784. continue;
  8785. }
  8786. field_expr = lb_build_expr(p, elem);
  8787. Type *fet = field_expr.type;
  8788. GB_ASSERT(fet->kind != Type_Tuple);
  8789. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  8790. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  8791. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  8792. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  8793. lb_emit_store_union_variant(p, gep, field_expr, fet);
  8794. } else {
  8795. lbValue fv = lb_emit_conv(p, field_expr, ft);
  8796. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  8797. lb_emit_store(p, gep, fv);
  8798. }
  8799. }
  8800. }
  8801. break;
  8802. }
  8803. case Type_Map: {
  8804. if (cl->elems.count == 0) {
  8805. break;
  8806. }
  8807. gbAllocator a = heap_allocator();
  8808. {
  8809. auto args = array_make<lbValue>(a, 3);
  8810. args[0] = lb_gen_map_header(p, v.addr, type);
  8811. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  8812. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  8813. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  8814. }
  8815. for_array(field_index, cl->elems) {
  8816. Ast *elem = cl->elems[field_index];
  8817. ast_node(fv, FieldValue, elem);
  8818. lbValue key = lb_build_expr(p, fv->field);
  8819. lbValue value = lb_build_expr(p, fv->value);
  8820. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  8821. }
  8822. break;
  8823. }
  8824. case Type_Array: {
  8825. if (cl->elems.count > 0) {
  8826. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8827. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  8828. defer (array_free(&temp_data));
  8829. // NOTE(bill): Separate value, gep, store into their own chunks
  8830. for_array(i, cl->elems) {
  8831. Ast *elem = cl->elems[i];
  8832. if (elem->kind == Ast_FieldValue) {
  8833. ast_node(fv, FieldValue, elem);
  8834. if (lb_is_elem_const(fv->value, et)) {
  8835. continue;
  8836. }
  8837. if (is_ast_range(fv->field)) {
  8838. ast_node(ie, BinaryExpr, fv->field);
  8839. TypeAndValue lo_tav = ie->left->tav;
  8840. TypeAndValue hi_tav = ie->right->tav;
  8841. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  8842. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  8843. TokenKind op = ie->op.kind;
  8844. i64 lo = exact_value_to_i64(lo_tav.value);
  8845. i64 hi = exact_value_to_i64(hi_tav.value);
  8846. if (op == Token_Ellipsis) {
  8847. hi += 1;
  8848. }
  8849. lbValue value = lb_build_expr(p, fv->value);
  8850. for (i64 k = lo; k < hi; k++) {
  8851. lbCompoundLitElemTempData data = {};
  8852. data.value = value;
  8853. data.elem_index = cast(i32)k;
  8854. array_add(&temp_data, data);
  8855. }
  8856. } else {
  8857. auto tav = fv->field->tav;
  8858. GB_ASSERT(tav.mode == Addressing_Constant);
  8859. i64 index = exact_value_to_i64(tav.value);
  8860. lbValue value = lb_build_expr(p, fv->value);
  8861. lbCompoundLitElemTempData data = {};
  8862. data.value = lb_emit_conv(p, value, et);
  8863. data.expr = fv->value;
  8864. data.elem_index = cast(i32)index;
  8865. array_add(&temp_data, data);
  8866. }
  8867. } else {
  8868. if (lb_is_elem_const(elem, et)) {
  8869. continue;
  8870. }
  8871. lbCompoundLitElemTempData data = {};
  8872. data.expr = elem;
  8873. data.elem_index = cast(i32)i;
  8874. array_add(&temp_data, data);
  8875. }
  8876. }
  8877. for_array(i, temp_data) {
  8878. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  8879. }
  8880. for_array(i, temp_data) {
  8881. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  8882. auto return_ptr_hint_value = p->return_ptr_hint_value;
  8883. auto return_ptr_hint_used = p->return_ptr_hint_used;
  8884. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  8885. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  8886. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  8887. lbValue field_expr = temp_data[i].value;
  8888. Ast *expr = temp_data[i].expr;
  8889. p->return_ptr_hint_value = temp_data[i].gep;
  8890. p->return_ptr_hint_ast = unparen_expr(expr);
  8891. if (field_expr.value == nullptr) {
  8892. field_expr = lb_build_expr(p, expr);
  8893. }
  8894. Type *t = field_expr.type;
  8895. GB_ASSERT(t->kind != Type_Tuple);
  8896. lbValue ev = lb_emit_conv(p, field_expr, et);
  8897. if (!p->return_ptr_hint_used) {
  8898. temp_data[i].value = ev;
  8899. }
  8900. }
  8901. for_array(i, temp_data) {
  8902. if (temp_data[i].value.value != nullptr) {
  8903. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  8904. }
  8905. }
  8906. }
  8907. break;
  8908. }
  8909. case Type_EnumeratedArray: {
  8910. if (cl->elems.count > 0) {
  8911. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8912. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  8913. defer (array_free(&temp_data));
  8914. // NOTE(bill): Separate value, gep, store into their own chunks
  8915. for_array(i, cl->elems) {
  8916. Ast *elem = cl->elems[i];
  8917. if (elem->kind == Ast_FieldValue) {
  8918. ast_node(fv, FieldValue, elem);
  8919. if (lb_is_elem_const(fv->value, et)) {
  8920. continue;
  8921. }
  8922. if (is_ast_range(fv->field)) {
  8923. ast_node(ie, BinaryExpr, fv->field);
  8924. TypeAndValue lo_tav = ie->left->tav;
  8925. TypeAndValue hi_tav = ie->right->tav;
  8926. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  8927. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  8928. TokenKind op = ie->op.kind;
  8929. i64 lo = exact_value_to_i64(lo_tav.value);
  8930. i64 hi = exact_value_to_i64(hi_tav.value);
  8931. if (op == Token_Ellipsis) {
  8932. hi += 1;
  8933. }
  8934. lbValue value = lb_build_expr(p, fv->value);
  8935. for (i64 k = lo; k < hi; k++) {
  8936. lbCompoundLitElemTempData data = {};
  8937. data.value = value;
  8938. data.elem_index = cast(i32)k;
  8939. array_add(&temp_data, data);
  8940. }
  8941. } else {
  8942. auto tav = fv->field->tav;
  8943. GB_ASSERT(tav.mode == Addressing_Constant);
  8944. i64 index = exact_value_to_i64(tav.value);
  8945. lbValue value = lb_build_expr(p, fv->value);
  8946. lbCompoundLitElemTempData data = {};
  8947. data.value = lb_emit_conv(p, value, et);
  8948. data.expr = fv->value;
  8949. data.elem_index = cast(i32)index;
  8950. array_add(&temp_data, data);
  8951. }
  8952. } else {
  8953. if (lb_is_elem_const(elem, et)) {
  8954. continue;
  8955. }
  8956. lbCompoundLitElemTempData data = {};
  8957. data.expr = elem;
  8958. data.elem_index = cast(i32)i;
  8959. array_add(&temp_data, data);
  8960. }
  8961. }
  8962. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  8963. for_array(i, temp_data) {
  8964. i32 index = temp_data[i].elem_index - index_offset;
  8965. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  8966. }
  8967. for_array(i, temp_data) {
  8968. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  8969. auto return_ptr_hint_value = p->return_ptr_hint_value;
  8970. auto return_ptr_hint_used = p->return_ptr_hint_used;
  8971. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  8972. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  8973. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  8974. lbValue field_expr = temp_data[i].value;
  8975. Ast *expr = temp_data[i].expr;
  8976. p->return_ptr_hint_value = temp_data[i].gep;
  8977. p->return_ptr_hint_ast = unparen_expr(expr);
  8978. if (field_expr.value == nullptr) {
  8979. field_expr = lb_build_expr(p, expr);
  8980. }
  8981. Type *t = field_expr.type;
  8982. GB_ASSERT(t->kind != Type_Tuple);
  8983. lbValue ev = lb_emit_conv(p, field_expr, et);
  8984. if (!p->return_ptr_hint_used) {
  8985. temp_data[i].value = ev;
  8986. }
  8987. }
  8988. for_array(i, temp_data) {
  8989. if (temp_data[i].value.value != nullptr) {
  8990. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  8991. }
  8992. }
  8993. }
  8994. break;
  8995. }
  8996. case Type_Slice: {
  8997. if (cl->elems.count > 0) {
  8998. Type *elem_type = bt->Slice.elem;
  8999. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  9000. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  9001. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  9002. lbValue data = lb_slice_elem(p, slice);
  9003. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  9004. defer (array_free(&temp_data));
  9005. for_array(i, cl->elems) {
  9006. Ast *elem = cl->elems[i];
  9007. if (elem->kind == Ast_FieldValue) {
  9008. ast_node(fv, FieldValue, elem);
  9009. if (lb_is_elem_const(fv->value, et)) {
  9010. continue;
  9011. }
  9012. if (is_ast_range(fv->field)) {
  9013. ast_node(ie, BinaryExpr, fv->field);
  9014. TypeAndValue lo_tav = ie->left->tav;
  9015. TypeAndValue hi_tav = ie->right->tav;
  9016. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9017. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9018. TokenKind op = ie->op.kind;
  9019. i64 lo = exact_value_to_i64(lo_tav.value);
  9020. i64 hi = exact_value_to_i64(hi_tav.value);
  9021. if (op == Token_Ellipsis) {
  9022. hi += 1;
  9023. }
  9024. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9025. for (i64 k = lo; k < hi; k++) {
  9026. lbCompoundLitElemTempData data = {};
  9027. data.value = value;
  9028. data.elem_index = cast(i32)k;
  9029. array_add(&temp_data, data);
  9030. }
  9031. } else {
  9032. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9033. i64 index = exact_value_to_i64(fv->field->tav.value);
  9034. lbValue field_expr = lb_build_expr(p, fv->value);
  9035. GB_ASSERT(!is_type_tuple(field_expr.type));
  9036. lbValue ev = lb_emit_conv(p, field_expr, et);
  9037. lbCompoundLitElemTempData data = {};
  9038. data.value = ev;
  9039. data.elem_index = cast(i32)index;
  9040. array_add(&temp_data, data);
  9041. }
  9042. } else {
  9043. if (lb_is_elem_const(elem, et)) {
  9044. continue;
  9045. }
  9046. lbValue field_expr = lb_build_expr(p, elem);
  9047. GB_ASSERT(!is_type_tuple(field_expr.type));
  9048. lbValue ev = lb_emit_conv(p, field_expr, et);
  9049. lbCompoundLitElemTempData data = {};
  9050. data.value = ev;
  9051. data.elem_index = cast(i32)i;
  9052. array_add(&temp_data, data);
  9053. }
  9054. }
  9055. for_array(i, temp_data) {
  9056. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  9057. }
  9058. for_array(i, temp_data) {
  9059. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9060. }
  9061. {
  9062. lbValue count = {};
  9063. count.type = t_int;
  9064. if (lb_is_const(slice)) {
  9065. unsigned indices[1] = {1};
  9066. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  9067. } else {
  9068. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  9069. }
  9070. lb_fill_slice(p, v, data, count);
  9071. }
  9072. }
  9073. break;
  9074. }
  9075. case Type_DynamicArray: {
  9076. if (cl->elems.count == 0) {
  9077. break;
  9078. }
  9079. Type *et = bt->DynamicArray.elem;
  9080. gbAllocator a = heap_allocator();
  9081. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  9082. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  9083. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  9084. {
  9085. auto args = array_make<lbValue>(a, 5);
  9086. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  9087. args[1] = size;
  9088. args[2] = align;
  9089. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  9090. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  9091. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  9092. }
  9093. lbValue items = lb_generate_local_array(p, et, item_count);
  9094. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  9095. for_array(i, cl->elems) {
  9096. Ast *elem = cl->elems[i];
  9097. if (elem->kind == Ast_FieldValue) {
  9098. ast_node(fv, FieldValue, elem);
  9099. if (is_ast_range(fv->field)) {
  9100. ast_node(ie, BinaryExpr, fv->field);
  9101. TypeAndValue lo_tav = ie->left->tav;
  9102. TypeAndValue hi_tav = ie->right->tav;
  9103. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9104. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9105. TokenKind op = ie->op.kind;
  9106. i64 lo = exact_value_to_i64(lo_tav.value);
  9107. i64 hi = exact_value_to_i64(hi_tav.value);
  9108. if (op == Token_Ellipsis) {
  9109. hi += 1;
  9110. }
  9111. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9112. for (i64 k = lo; k < hi; k++) {
  9113. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  9114. lb_emit_store(p, ep, value);
  9115. }
  9116. } else {
  9117. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9118. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  9119. lbValue ev = lb_build_expr(p, fv->value);
  9120. lbValue value = lb_emit_conv(p, ev, et);
  9121. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  9122. lb_emit_store(p, ep, value);
  9123. }
  9124. } else {
  9125. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  9126. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  9127. lb_emit_store(p, ep, value);
  9128. }
  9129. }
  9130. {
  9131. auto args = array_make<lbValue>(a, 6);
  9132. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  9133. args[1] = size;
  9134. args[2] = align;
  9135. args[3] = lb_emit_conv(p, items, t_rawptr);
  9136. args[4] = lb_const_int(p->module, t_int, item_count);
  9137. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  9138. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  9139. }
  9140. break;
  9141. }
  9142. case Type_Basic: {
  9143. GB_ASSERT(is_type_any(bt));
  9144. if (cl->elems.count > 0) {
  9145. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9146. String field_names[2] = {
  9147. str_lit("data"),
  9148. str_lit("id"),
  9149. };
  9150. Type *field_types[2] = {
  9151. t_rawptr,
  9152. t_typeid,
  9153. };
  9154. for_array(field_index, cl->elems) {
  9155. Ast *elem = cl->elems[field_index];
  9156. lbValue field_expr = {};
  9157. isize index = field_index;
  9158. if (elem->kind == Ast_FieldValue) {
  9159. ast_node(fv, FieldValue, elem);
  9160. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  9161. index = sel.index[0];
  9162. elem = fv->value;
  9163. } else {
  9164. TypeAndValue tav = type_and_value_of_expr(elem);
  9165. Selection sel = lookup_field(bt, field_names[field_index], false);
  9166. index = sel.index[0];
  9167. }
  9168. field_expr = lb_build_expr(p, elem);
  9169. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  9170. Type *ft = field_types[index];
  9171. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9172. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9173. lb_emit_store(p, gep, fv);
  9174. }
  9175. }
  9176. break;
  9177. }
  9178. case Type_BitSet: {
  9179. i64 sz = type_size_of(type);
  9180. if (cl->elems.count > 0 && sz > 0) {
  9181. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9182. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  9183. for_array(i, cl->elems) {
  9184. Ast *elem = cl->elems[i];
  9185. GB_ASSERT(elem->kind != Ast_FieldValue);
  9186. if (lb_is_elem_const(elem, et)) {
  9187. continue;
  9188. }
  9189. lbValue expr = lb_build_expr(p, elem);
  9190. GB_ASSERT(expr.type->kind != Type_Tuple);
  9191. Type *it = bit_set_to_int(bt);
  9192. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  9193. lbValue e = lb_emit_conv(p, expr, it);
  9194. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  9195. e = lb_emit_arith(p, Token_Shl, one, e, it);
  9196. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  9197. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  9198. new_value = lb_emit_transmute(p, new_value, type);
  9199. lb_addr_store(p, v, new_value);
  9200. }
  9201. }
  9202. break;
  9203. }
  9204. }
  9205. return v;
  9206. case_end;
  9207. case_ast_node(tc, TypeCast, expr);
  9208. Type *type = type_of_expr(expr);
  9209. lbValue x = lb_build_expr(p, tc->expr);
  9210. lbValue e = {};
  9211. switch (tc->token.kind) {
  9212. case Token_cast:
  9213. e = lb_emit_conv(p, x, type);
  9214. break;
  9215. case Token_transmute:
  9216. e = lb_emit_transmute(p, x, type);
  9217. break;
  9218. default:
  9219. GB_PANIC("Invalid AST TypeCast");
  9220. }
  9221. lbAddr v = lb_add_local_generated(p, type, false);
  9222. lb_addr_store(p, v, e);
  9223. return v;
  9224. case_end;
  9225. case_ast_node(ac, AutoCast, expr);
  9226. return lb_build_addr(p, ac->expr);
  9227. case_end;
  9228. }
  9229. TokenPos token_pos = ast_token(expr).pos;
  9230. GB_PANIC("Unexpected address expression\n"
  9231. "\tAst: %.*s @ "
  9232. "%.*s(%td:%td)\n",
  9233. LIT(ast_strings[expr->kind]),
  9234. LIT(token_pos.file), token_pos.line, token_pos.column);
  9235. return {};
  9236. }
  9237. void lb_init_module(lbModule *m, Checker *c) {
  9238. m->info = &c->info;
  9239. m->ctx = LLVMGetGlobalContext();
  9240. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  9241. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  9242. m->state_flags = 0;
  9243. m->state_flags |= StateFlag_bounds_check;
  9244. gb_mutex_init(&m->mutex);
  9245. gbAllocator a = heap_allocator();
  9246. map_init(&m->types, a);
  9247. map_init(&m->values, a);
  9248. string_map_init(&m->members, a);
  9249. map_init(&m->procedure_values, a);
  9250. string_map_init(&m->procedures, a);
  9251. string_map_init(&m->const_strings, a);
  9252. map_init(&m->anonymous_proc_lits, a);
  9253. array_init(&m->procedures_to_generate, a);
  9254. array_init(&m->foreign_library_paths, a);
  9255. map_init(&m->debug_values, a);
  9256. }
  9257. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  9258. if (global_error_collector.count != 0) {
  9259. return false;
  9260. }
  9261. isize tc = c->parser->total_token_count;
  9262. if (tc < 2) {
  9263. return false;
  9264. }
  9265. String init_fullpath = c->parser->init_fullpath;
  9266. if (build_context.out_filepath.len == 0) {
  9267. gen->output_name = remove_directory_from_path(init_fullpath);
  9268. gen->output_name = remove_extension_from_path(gen->output_name);
  9269. gen->output_name = string_trim_whitespace(gen->output_name);
  9270. if (gen->output_name.len == 0) {
  9271. gen->output_name = c->info.init_scope->pkg->name;
  9272. }
  9273. gen->output_base = gen->output_name;
  9274. } else {
  9275. gen->output_name = build_context.out_filepath;
  9276. gen->output_name = string_trim_whitespace(gen->output_name);
  9277. if (gen->output_name.len == 0) {
  9278. gen->output_name = c->info.init_scope->pkg->name;
  9279. }
  9280. isize pos = string_extension_position(gen->output_name);
  9281. if (pos < 0) {
  9282. gen->output_base = gen->output_name;
  9283. } else {
  9284. gen->output_base = substring(gen->output_name, 0, pos);
  9285. }
  9286. }
  9287. gbAllocator ha = heap_allocator();
  9288. array_init(&gen->output_object_paths, ha);
  9289. gen->output_base = path_to_full_path(ha, gen->output_base);
  9290. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  9291. output_file_path = gb_string_appendc(output_file_path, ".obj");
  9292. defer (gb_string_free(output_file_path));
  9293. gen->info = &c->info;
  9294. lb_init_module(&gen->module, c);
  9295. return true;
  9296. }
  9297. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  9298. GB_ASSERT(type != nullptr);
  9299. type = default_type(type);
  9300. isize max_len = 7+8+1;
  9301. u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len);
  9302. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  9303. m->global_generated_index++;
  9304. String name = make_string(str, len-1);
  9305. Scope *scope = nullptr;
  9306. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  9307. lbValue g = {};
  9308. g.type = alloc_type_pointer(type);
  9309. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  9310. if (value.value != nullptr) {
  9311. GB_ASSERT(LLVMIsConstant(value.value));
  9312. LLVMSetInitializer(g.value, value.value);
  9313. } else {
  9314. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  9315. }
  9316. lb_add_entity(m, e, g);
  9317. lb_add_member(m, name, g);
  9318. return lb_addr(g);
  9319. }
  9320. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  9321. AstPackage *p = m->info->runtime_package;
  9322. Entity *e = scope_lookup_current(p->scope, name);
  9323. lbValue *found = map_get(&m->values, hash_entity(e));
  9324. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  9325. lbValue value = *found;
  9326. return value;
  9327. }
  9328. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  9329. i32 index = cast(i32)lb_type_info_index(m->info, type);
  9330. GB_ASSERT(index >= 0);
  9331. // gb_printf_err("%d %s\n", index, type_to_string(type));
  9332. LLVMValueRef indices[2] = {
  9333. LLVMConstInt(lb_type(m, t_int), 0, false),
  9334. LLVMConstInt(lb_type(m, t_int), index, false),
  9335. };
  9336. lbValue res = {};
  9337. res.type = t_type_info_ptr;
  9338. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  9339. return res;
  9340. }
  9341. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  9342. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  9343. lb_global_type_info_member_types_index += cast(i32)count;
  9344. return offset;
  9345. }
  9346. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  9347. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  9348. lb_global_type_info_member_names_index += cast(i32)count;
  9349. return offset;
  9350. }
  9351. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  9352. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  9353. lb_global_type_info_member_offsets_index += cast(i32)count;
  9354. return offset;
  9355. }
  9356. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  9357. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  9358. lb_global_type_info_member_usings_index += cast(i32)count;
  9359. return offset;
  9360. }
  9361. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  9362. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  9363. lb_global_type_info_member_tags_index += cast(i32)count;
  9364. return offset;
  9365. }
  9366. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  9367. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  9368. return lb_addr_get_ptr(p, addr);
  9369. }
  9370. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  9371. gbAllocator a = heap_allocator();
  9372. Token token = {Token_Ident};
  9373. isize name_len = prefix.len + 1 + 20;
  9374. auto suffix_id = cast(unsigned long long)id;
  9375. char *text = gb_alloc_array(a, char, name_len+1);
  9376. gb_snprintf(text, name_len,
  9377. "%.*s-%llu", LIT(prefix), suffix_id);
  9378. text[name_len] = 0;
  9379. String s = make_string_c(text);
  9380. Type *t = alloc_type_array(elem_type, count);
  9381. lbValue g = {};
  9382. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  9383. g.type = alloc_type_pointer(t);
  9384. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  9385. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  9386. string_map_set(&m->members, s, g);
  9387. return g;
  9388. }
  9389. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  9390. lbModule *m = p->module;
  9391. LLVMContextRef ctx = m->ctx;
  9392. gbAllocator a = heap_allocator();
  9393. CheckerInfo *info = m->info;
  9394. {
  9395. // NOTE(bill): Set the type_table slice with the global backing array
  9396. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  9397. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  9398. GB_ASSERT(is_type_array(type));
  9399. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  9400. LLVMValueRef values[2] = {
  9401. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  9402. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  9403. };
  9404. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  9405. LLVMSetInitializer(global_type_table.value, slice);
  9406. }
  9407. // Useful types
  9408. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  9409. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  9410. i32 type_info_member_types_index = 0;
  9411. i32 type_info_member_names_index = 0;
  9412. i32 type_info_member_offsets_index = 0;
  9413. for_array(type_info_type_index, info->type_info_types) {
  9414. Type *t = info->type_info_types[type_info_type_index];
  9415. t = default_type(t);
  9416. if (t == t_invalid) {
  9417. continue;
  9418. }
  9419. isize entry_index = lb_type_info_index(info, t, false);
  9420. if (entry_index <= 0) {
  9421. continue;
  9422. }
  9423. lbValue tag = {};
  9424. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  9425. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 3);
  9426. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  9427. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  9428. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), lb_typeid(m, t));
  9429. switch (t->kind) {
  9430. case Type_Named: {
  9431. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  9432. LLVMValueRef vals[2] = {
  9433. lb_const_string(p->module, t->Named.type_name->token.string).value,
  9434. lb_get_type_info_ptr(m, t->Named.base).value,
  9435. };
  9436. lbValue res = {};
  9437. res.type = type_deref(tag.type);
  9438. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9439. lb_emit_store(p, tag, res);
  9440. break;
  9441. }
  9442. case Type_Basic:
  9443. switch (t->Basic.kind) {
  9444. case Basic_bool:
  9445. case Basic_b8:
  9446. case Basic_b16:
  9447. case Basic_b32:
  9448. case Basic_b64:
  9449. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  9450. break;
  9451. case Basic_i8:
  9452. case Basic_u8:
  9453. case Basic_i16:
  9454. case Basic_u16:
  9455. case Basic_i32:
  9456. case Basic_u32:
  9457. case Basic_i64:
  9458. case Basic_u64:
  9459. case Basic_i128:
  9460. case Basic_u128:
  9461. case Basic_i16le:
  9462. case Basic_u16le:
  9463. case Basic_i32le:
  9464. case Basic_u32le:
  9465. case Basic_i64le:
  9466. case Basic_u64le:
  9467. case Basic_i128le:
  9468. case Basic_u128le:
  9469. case Basic_i16be:
  9470. case Basic_u16be:
  9471. case Basic_i32be:
  9472. case Basic_u32be:
  9473. case Basic_i64be:
  9474. case Basic_u64be:
  9475. case Basic_i128be:
  9476. case Basic_u128be:
  9477. case Basic_int:
  9478. case Basic_uint:
  9479. case Basic_uintptr: {
  9480. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  9481. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  9482. // NOTE(bill): This is matches the runtime layout
  9483. u8 endianness_value = 0;
  9484. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9485. endianness_value = 1;
  9486. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9487. endianness_value = 2;
  9488. }
  9489. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9490. LLVMValueRef vals[2] = {
  9491. is_signed.value,
  9492. endianness.value,
  9493. };
  9494. lbValue res = {};
  9495. res.type = type_deref(tag.type);
  9496. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9497. lb_emit_store(p, tag, res);
  9498. break;
  9499. }
  9500. case Basic_rune:
  9501. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  9502. break;
  9503. // case Basic_f16:
  9504. case Basic_f32:
  9505. case Basic_f64:
  9506. case Basic_f32le:
  9507. case Basic_f64le:
  9508. case Basic_f32be:
  9509. case Basic_f64be:
  9510. {
  9511. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  9512. // NOTE(bill): This is matches the runtime layout
  9513. u8 endianness_value = 0;
  9514. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9515. endianness_value = 1;
  9516. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9517. endianness_value = 2;
  9518. }
  9519. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9520. LLVMValueRef vals[1] = {
  9521. endianness.value,
  9522. };
  9523. lbValue res = {};
  9524. res.type = type_deref(tag.type);
  9525. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9526. lb_emit_store(p, tag, res);
  9527. }
  9528. break;
  9529. // case Basic_complex32:
  9530. case Basic_complex64:
  9531. case Basic_complex128:
  9532. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  9533. break;
  9534. case Basic_quaternion128:
  9535. case Basic_quaternion256:
  9536. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  9537. break;
  9538. case Basic_rawptr:
  9539. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9540. break;
  9541. case Basic_string:
  9542. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9543. break;
  9544. case Basic_cstring:
  9545. {
  9546. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9547. LLVMValueRef vals[1] = {
  9548. lb_const_bool(m, t_bool, true).value,
  9549. };
  9550. lbValue res = {};
  9551. res.type = type_deref(tag.type);
  9552. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9553. lb_emit_store(p, tag, res);
  9554. }
  9555. break;
  9556. case Basic_any:
  9557. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  9558. break;
  9559. case Basic_typeid:
  9560. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  9561. break;
  9562. }
  9563. break;
  9564. case Type_Pointer: {
  9565. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9566. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  9567. LLVMValueRef vals[1] = {
  9568. gep.value,
  9569. };
  9570. lbValue res = {};
  9571. res.type = type_deref(tag.type);
  9572. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9573. lb_emit_store(p, tag, res);
  9574. break;
  9575. }
  9576. case Type_Array: {
  9577. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  9578. i64 ez = type_size_of(t->Array.elem);
  9579. LLVMValueRef vals[3] = {
  9580. lb_get_type_info_ptr(m, t->Array.elem).value,
  9581. lb_const_int(m, t_int, ez).value,
  9582. lb_const_int(m, t_int, t->Array.count).value,
  9583. };
  9584. lbValue res = {};
  9585. res.type = type_deref(tag.type);
  9586. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9587. lb_emit_store(p, tag, res);
  9588. break;
  9589. }
  9590. case Type_EnumeratedArray: {
  9591. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  9592. LLVMValueRef vals[6] = {
  9593. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  9594. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  9595. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  9596. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  9597. // Unions
  9598. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9599. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9600. };
  9601. lbValue res = {};
  9602. res.type = type_deref(tag.type);
  9603. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9604. lb_emit_store(p, tag, res);
  9605. // NOTE(bill): Union assignment
  9606. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  9607. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  9608. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  9609. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  9610. lb_emit_store(p, min_value, min_v);
  9611. lb_emit_store(p, max_value, max_v);
  9612. break;
  9613. }
  9614. case Type_DynamicArray: {
  9615. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  9616. LLVMValueRef vals[2] = {
  9617. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  9618. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  9619. };
  9620. lbValue res = {};
  9621. res.type = type_deref(tag.type);
  9622. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9623. lb_emit_store(p, tag, res);
  9624. break;
  9625. }
  9626. case Type_Slice: {
  9627. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  9628. LLVMValueRef vals[2] = {
  9629. lb_get_type_info_ptr(m, t->Slice.elem).value,
  9630. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  9631. };
  9632. lbValue res = {};
  9633. res.type = type_deref(tag.type);
  9634. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9635. lb_emit_store(p, tag, res);
  9636. break;
  9637. }
  9638. case Type_Proc: {
  9639. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  9640. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9641. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9642. if (t->Proc.params != nullptr) {
  9643. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  9644. }
  9645. if (t->Proc.results != nullptr) {
  9646. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  9647. }
  9648. LLVMValueRef vals[4] = {
  9649. params,
  9650. results,
  9651. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  9652. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  9653. };
  9654. lbValue res = {};
  9655. res.type = type_deref(tag.type);
  9656. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9657. lb_emit_store(p, tag, res);
  9658. break;
  9659. }
  9660. case Type_Tuple: {
  9661. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  9662. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  9663. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  9664. for_array(i, t->Tuple.variables) {
  9665. // NOTE(bill): offset is not used for tuples
  9666. Entity *f = t->Tuple.variables[i];
  9667. lbValue index = lb_const_int(m, t_int, i);
  9668. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  9669. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  9670. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  9671. if (f->token.string.len > 0) {
  9672. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  9673. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  9674. }
  9675. }
  9676. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  9677. LLVMValueRef types_slice = llvm_const_slice(memory_types, count);
  9678. LLVMValueRef names_slice = llvm_const_slice(memory_names, count);
  9679. LLVMValueRef vals[2] = {
  9680. types_slice,
  9681. names_slice,
  9682. };
  9683. lbValue res = {};
  9684. res.type = type_deref(tag.type);
  9685. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9686. lb_emit_store(p, tag, res);
  9687. break;
  9688. }
  9689. case Type_Enum:
  9690. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  9691. {
  9692. GB_ASSERT(t->Enum.base_type != nullptr);
  9693. // GB_ASSERT_MSG(type_size_of(t_type_info_enum_value) == 16, "%lld == 16", cast(long long)type_size_of(t_type_info_enum_value));
  9694. LLVMValueRef vals[3] = {};
  9695. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  9696. if (t->Enum.fields.count > 0) {
  9697. auto fields = t->Enum.fields;
  9698. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  9699. str_lit("$enum_names"), cast(i64)entry_index);
  9700. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  9701. str_lit("$enum_values"), cast(i64)entry_index);
  9702. LLVMValueRef *name_values = gb_alloc_array(heap_allocator(), LLVMValueRef, fields.count);
  9703. LLVMValueRef *value_values = gb_alloc_array(heap_allocator(), LLVMValueRef, fields.count);
  9704. defer (gb_free(heap_allocator(), name_values));
  9705. defer (gb_free(heap_allocator(), value_values));
  9706. GB_ASSERT(is_type_integer(t->Enum.base_type));
  9707. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  9708. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  9709. for_array(i, fields) {
  9710. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  9711. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  9712. }
  9713. LLVMValueRef name_init = LLVMConstArray(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  9714. LLVMValueRef value_init = LLVMConstArray(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  9715. LLVMSetInitializer(name_array.value, name_init);
  9716. LLVMSetInitializer(value_array.value, value_init);
  9717. lbValue v_count = lb_const_int(m, t_int, fields.count);
  9718. vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count);
  9719. vals[2] = llvm_const_slice(lb_array_elem(p, value_array), v_count);
  9720. } else {
  9721. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  9722. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  9723. }
  9724. lbValue res = {};
  9725. res.type = type_deref(tag.type);
  9726. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9727. lb_emit_store(p, tag, res);
  9728. }
  9729. break;
  9730. case Type_Union: {
  9731. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  9732. {
  9733. LLVMValueRef vals[6] = {};
  9734. isize variant_count = gb_max(0, t->Union.variants.count);
  9735. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  9736. // NOTE(bill): Zeroth is nil so ignore it
  9737. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  9738. Type *vt = t->Union.variants[variant_index];
  9739. lbValue tip = lb_get_type_info_ptr(m, vt);
  9740. lbValue index = lb_const_int(m, t_int, variant_index);
  9741. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  9742. lb_emit_store(p, type_info, lb_type_info(m, vt));
  9743. }
  9744. lbValue count = lb_const_int(m, t_int, variant_count);
  9745. vals[0] = llvm_const_slice(memory_types, count);
  9746. i64 tag_size = union_tag_size(t);
  9747. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  9748. if (tag_size > 0) {
  9749. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  9750. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  9751. } else {
  9752. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  9753. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9754. }
  9755. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  9756. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  9757. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  9758. lbValue res = {};
  9759. res.type = type_deref(tag.type);
  9760. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9761. lb_emit_store(p, tag, res);
  9762. }
  9763. break;
  9764. }
  9765. case Type_Struct: {
  9766. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  9767. LLVMValueRef vals[11] = {};
  9768. {
  9769. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  9770. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  9771. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  9772. vals[5] = is_packed.value;
  9773. vals[6] = is_raw_union.value;
  9774. vals[7] = is_custom_align.value;
  9775. if (t->Struct.soa_kind != StructSoa_None) {
  9776. lbValue kind = lb_emit_struct_ep(p, tag, 8);
  9777. Type *kind_type = type_deref(kind.type);
  9778. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  9779. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  9780. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  9781. vals[8] = soa_kind.value;
  9782. vals[9] = soa_type.value;
  9783. vals[10] = soa_len.value;
  9784. }
  9785. }
  9786. isize count = t->Struct.fields.count;
  9787. if (count > 0) {
  9788. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  9789. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  9790. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  9791. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  9792. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  9793. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  9794. for (isize source_index = 0; source_index < count; source_index++) {
  9795. // TODO(bill): Order fields in source order not layout order
  9796. Entity *f = t->Struct.fields[source_index];
  9797. lbValue tip = lb_get_type_info_ptr(m, f->type);
  9798. i64 foffset = 0;
  9799. if (!t->Struct.is_raw_union) {
  9800. foffset = t->Struct.offsets[f->Variable.field_index];
  9801. }
  9802. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  9803. lbValue index = lb_const_int(m, t_int, source_index);
  9804. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  9805. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  9806. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  9807. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  9808. if (f->token.string.len > 0) {
  9809. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  9810. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  9811. }
  9812. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  9813. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  9814. if (t->Struct.tags.count > 0) {
  9815. String tag_string = t->Struct.tags[source_index];
  9816. if (tag_string.len > 0) {
  9817. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  9818. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  9819. }
  9820. }
  9821. }
  9822. lbValue cv = lb_const_int(m, t_int, count);
  9823. vals[0] = llvm_const_slice(memory_types, cv);
  9824. vals[1] = llvm_const_slice(memory_names, cv);
  9825. vals[2] = llvm_const_slice(memory_offsets, cv);
  9826. vals[3] = llvm_const_slice(memory_usings, cv);
  9827. vals[4] = llvm_const_slice(memory_tags, cv);
  9828. }
  9829. for (isize i = 0; i < gb_count_of(vals); i++) {
  9830. if (vals[i] == nullptr) {
  9831. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  9832. }
  9833. }
  9834. lbValue res = {};
  9835. res.type = type_deref(tag.type);
  9836. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9837. lb_emit_store(p, tag, res);
  9838. break;
  9839. }
  9840. case Type_Map: {
  9841. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  9842. init_map_internal_types(t);
  9843. LLVMValueRef vals[3] = {
  9844. lb_get_type_info_ptr(m, t->Map.key).value,
  9845. lb_get_type_info_ptr(m, t->Map.value).value,
  9846. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  9847. };
  9848. lbValue res = {};
  9849. res.type = type_deref(tag.type);
  9850. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9851. lb_emit_store(p, tag, res);
  9852. break;
  9853. }
  9854. case Type_BitField: {
  9855. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_field_ptr);
  9856. // names: []string;
  9857. // bits: []u32;
  9858. // offsets: []u32;
  9859. isize count = t->BitField.fields.count;
  9860. if (count > 0) {
  9861. auto fields = t->BitField.fields;
  9862. lbValue name_array = lb_generate_global_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  9863. lbValue bit_array = lb_generate_global_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  9864. lbValue offset_array = lb_generate_global_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  9865. for (isize i = 0; i < count; i++) {
  9866. Entity *f = fields[i];
  9867. GB_ASSERT(f->type != nullptr);
  9868. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  9869. lbValue name_ep = lb_emit_array_epi(p, name_array, cast(i32)i);
  9870. lbValue bit_ep = lb_emit_array_epi(p, bit_array, cast(i32)i);
  9871. lbValue offset_ep = lb_emit_array_epi(p, offset_array, cast(i32)i);
  9872. lb_emit_store(p, name_ep, lb_const_string(m, f->token.string));
  9873. lb_emit_store(p, bit_ep, lb_const_int(m, t_i32, f->type->BitFieldValue.bits));
  9874. lb_emit_store(p, offset_ep, lb_const_int(m, t_i32, t->BitField.offsets[i]));
  9875. }
  9876. lbValue v_count = lb_const_int(m, t_int, count);
  9877. lbValue name_array_elem = lb_array_elem(p, name_array);
  9878. lbValue bit_array_elem = lb_array_elem(p, bit_array);
  9879. lbValue offset_array_elem = lb_array_elem(p, offset_array);
  9880. LLVMValueRef vals[3] = {
  9881. llvm_const_slice(name_array_elem, v_count),
  9882. llvm_const_slice(bit_array_elem, v_count),
  9883. llvm_const_slice(offset_array_elem, v_count),
  9884. };
  9885. lbValue res = {};
  9886. res.type = type_deref(tag.type);
  9887. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9888. lb_emit_store(p, tag, res);
  9889. }
  9890. break;
  9891. }
  9892. case Type_BitSet:
  9893. {
  9894. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  9895. GB_ASSERT(is_type_typed(t->BitSet.elem));
  9896. LLVMValueRef vals[4] = {
  9897. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  9898. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  9899. lb_const_int(m, t_i64, t->BitSet.lower).value,
  9900. lb_const_int(m, t_i64, t->BitSet.upper).value,
  9901. };
  9902. if (t->BitSet.underlying != nullptr) {
  9903. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  9904. }
  9905. lbValue res = {};
  9906. res.type = type_deref(tag.type);
  9907. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9908. lb_emit_store(p, tag, res);
  9909. }
  9910. break;
  9911. case Type_Opaque:
  9912. {
  9913. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_opaque_ptr);
  9914. LLVMValueRef vals[1] = {
  9915. lb_get_type_info_ptr(m, t->Opaque.elem).value,
  9916. };
  9917. lbValue res = {};
  9918. res.type = type_deref(tag.type);
  9919. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9920. lb_emit_store(p, tag, res);
  9921. }
  9922. break;
  9923. case Type_SimdVector:
  9924. {
  9925. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  9926. LLVMValueRef vals[4] = {};
  9927. if (t->SimdVector.is_x86_mmx) {
  9928. vals[3] = lb_const_bool(m, t_bool, true).value;
  9929. } else {
  9930. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  9931. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  9932. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  9933. }
  9934. lbValue res = {};
  9935. res.type = type_deref(tag.type);
  9936. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9937. lb_emit_store(p, tag, res);
  9938. }
  9939. break;
  9940. case Type_RelativePointer:
  9941. {
  9942. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  9943. LLVMValueRef vals[2] = {
  9944. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  9945. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  9946. };
  9947. lbValue res = {};
  9948. res.type = type_deref(tag.type);
  9949. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9950. lb_emit_store(p, tag, res);
  9951. }
  9952. break;
  9953. case Type_RelativeSlice:
  9954. {
  9955. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  9956. LLVMValueRef vals[2] = {
  9957. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  9958. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  9959. };
  9960. lbValue res = {};
  9961. res.type = type_deref(tag.type);
  9962. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9963. lb_emit_store(p, tag, res);
  9964. }
  9965. break;
  9966. }
  9967. if (tag.value != nullptr) {
  9968. Type *tag_type = type_deref(tag.type);
  9969. GB_ASSERT(is_type_named(tag_type));
  9970. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  9971. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  9972. } else {
  9973. if (t != t_llvm_bool) {
  9974. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  9975. }
  9976. }
  9977. }
  9978. }
  9979. void lb_generate_code(lbGenerator *gen) {
  9980. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  9981. TIME_SECTION("LLVM Initializtion");
  9982. lbModule *m = &gen->module;
  9983. LLVMModuleRef mod = gen->module.mod;
  9984. CheckerInfo *info = gen->info;
  9985. Arena temp_arena = {};
  9986. arena_init(&temp_arena, heap_allocator());
  9987. gbAllocator temp_allocator = arena_allocator(&temp_arena);
  9988. gen->module.global_default_context = lb_add_global_generated(m, t_context, {});
  9989. gen->module.global_default_context.kind = lbAddr_Context;
  9990. auto *min_dep_set = &info->minimum_dependency_set;
  9991. LLVMInitializeAllTargetInfos();
  9992. LLVMInitializeAllTargets();
  9993. LLVMInitializeAllTargetMCs();
  9994. LLVMInitializeAllAsmPrinters();
  9995. LLVMInitializeAllAsmParsers();
  9996. LLVMInitializeAllDisassemblers();
  9997. LLVMInitializeNativeTarget();
  9998. char const *target_triple = alloc_cstring(heap_allocator(), build_context.metrics.target_triplet);
  9999. char const *target_data_layout = alloc_cstring(heap_allocator(), build_context.metrics.target_data_layout);
  10000. LLVMSetTarget(mod, target_triple);
  10001. LLVMTargetRef target = {};
  10002. char *llvm_error = nullptr;
  10003. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  10004. GB_ASSERT(target != nullptr);
  10005. TIME_SECTION("LLVM Create Target Machine");
  10006. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  10007. if (build_context.metrics.arch == TargetArch_wasm32) {
  10008. code_mode = LLVMCodeModelJITDefault;
  10009. }
  10010. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, code_mode);
  10011. defer (LLVMDisposeTargetMachine(target_machine));
  10012. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  10013. { // Debug Info
  10014. for_array(i, info->files.entries) {
  10015. AstFile *f = info->files.entries[i].value;
  10016. String fullpath = f->fullpath;
  10017. String filename = filename_from_path(fullpath);
  10018. String directory = directory_from_path(fullpath);
  10019. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  10020. cast(char const *)filename.text, filename.len,
  10021. cast(char const *)directory.text, directory.len);
  10022. map_set(&m->debug_values, hash_pointer(f), res);
  10023. f->llvm_metadata = res;
  10024. }
  10025. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  10026. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  10027. "odin", 4,
  10028. false, "", 0,
  10029. 1, "", 0,
  10030. LLVMDWARFEmissionFull, 0, true,
  10031. true
  10032. );
  10033. }
  10034. TIME_SECTION("LLVM Global Variables");
  10035. {
  10036. { // Add type info data
  10037. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  10038. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  10039. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  10040. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  10041. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10042. LLVMSetLinkage(g, LLVMInternalLinkage);
  10043. lbValue value = {};
  10044. value.value = g;
  10045. value.type = alloc_type_pointer(t);
  10046. lb_global_type_info_data = lb_addr(value);
  10047. }
  10048. { // Type info member buffer
  10049. // NOTE(bill): Removes need for heap allocation by making it global memory
  10050. isize count = 0;
  10051. for_array(entry_index, m->info->type_info_types) {
  10052. Type *t = m->info->type_info_types[entry_index];
  10053. isize index = lb_type_info_index(m->info, t, false);
  10054. if (index < 0) {
  10055. continue;
  10056. }
  10057. switch (t->kind) {
  10058. case Type_Union:
  10059. count += t->Union.variants.count;
  10060. break;
  10061. case Type_Struct:
  10062. count += t->Struct.fields.count;
  10063. break;
  10064. case Type_Tuple:
  10065. count += t->Tuple.variables.count;
  10066. break;
  10067. }
  10068. }
  10069. if (count > 0) {
  10070. {
  10071. char const *name = LB_TYPE_INFO_TYPES_NAME;
  10072. Type *t = alloc_type_array(t_type_info_ptr, count);
  10073. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10074. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10075. LLVMSetLinkage(g, LLVMInternalLinkage);
  10076. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  10077. }
  10078. {
  10079. char const *name = LB_TYPE_INFO_NAMES_NAME;
  10080. Type *t = alloc_type_array(t_string, count);
  10081. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10082. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10083. LLVMSetLinkage(g, LLVMInternalLinkage);
  10084. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  10085. }
  10086. {
  10087. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  10088. Type *t = alloc_type_array(t_uintptr, count);
  10089. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10090. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10091. LLVMSetLinkage(g, LLVMInternalLinkage);
  10092. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  10093. }
  10094. {
  10095. char const *name = LB_TYPE_INFO_USINGS_NAME;
  10096. Type *t = alloc_type_array(t_bool, count);
  10097. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10098. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10099. LLVMSetLinkage(g, LLVMInternalLinkage);
  10100. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  10101. }
  10102. {
  10103. char const *name = LB_TYPE_INFO_TAGS_NAME;
  10104. Type *t = alloc_type_array(t_string, count);
  10105. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10106. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10107. LLVMSetLinkage(g, LLVMInternalLinkage);
  10108. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  10109. }
  10110. }
  10111. }
  10112. }
  10113. isize global_variable_max_count = 0;
  10114. Entity *entry_point = info->entry_point;
  10115. bool has_dll_main = false;
  10116. bool has_win_main = false;
  10117. for_array(i, info->entities) {
  10118. Entity *e = info->entities[i];
  10119. String name = e->token.string;
  10120. bool is_global = e->pkg != nullptr;
  10121. if (e->kind == Entity_Variable) {
  10122. global_variable_max_count++;
  10123. } else if (e->kind == Entity_Procedure && !is_global) {
  10124. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  10125. GB_ASSERT(e == entry_point);
  10126. // entry_point = e;
  10127. }
  10128. if (e->Procedure.is_export ||
  10129. (e->Procedure.link_name.len > 0) ||
  10130. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  10131. if (!has_dll_main && name == "DllMain") {
  10132. has_dll_main = true;
  10133. } else if (!has_win_main && name == "WinMain") {
  10134. has_win_main = true;
  10135. }
  10136. }
  10137. }
  10138. }
  10139. struct GlobalVariable {
  10140. lbValue var;
  10141. lbValue init;
  10142. DeclInfo *decl;
  10143. };
  10144. auto global_variables = array_make<GlobalVariable>(heap_allocator(), 0, global_variable_max_count);
  10145. for_array(i, info->variable_init_order) {
  10146. DeclInfo *d = info->variable_init_order[i];
  10147. Entity *e = d->entity;
  10148. if ((e->scope->flags & ScopeFlag_File) == 0) {
  10149. continue;
  10150. }
  10151. if (!ptr_set_exists(min_dep_set, e)) {
  10152. continue;
  10153. }
  10154. DeclInfo *decl = decl_info_of_entity(e);
  10155. if (decl == nullptr) {
  10156. continue;
  10157. }
  10158. GB_ASSERT(e->kind == Entity_Variable);
  10159. bool is_foreign = e->Variable.is_foreign;
  10160. bool is_export = e->Variable.is_export;
  10161. String name = lb_get_entity_name(m, e);
  10162. lbValue g = {};
  10163. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(heap_allocator(), name));
  10164. g.type = alloc_type_pointer(e->type);
  10165. if (e->Variable.thread_local_model != "") {
  10166. LLVMSetThreadLocal(g.value, true);
  10167. String m = e->Variable.thread_local_model;
  10168. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  10169. if (m == "default") {
  10170. mode = LLVMGeneralDynamicTLSModel;
  10171. } else if (m == "localdynamic") {
  10172. mode = LLVMLocalDynamicTLSModel;
  10173. } else if (m == "initialexec") {
  10174. mode = LLVMInitialExecTLSModel;
  10175. } else if (m == "localexec") {
  10176. mode = LLVMLocalExecTLSModel;
  10177. } else {
  10178. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  10179. }
  10180. LLVMSetThreadLocalMode(g.value, mode);
  10181. }
  10182. if (is_foreign) {
  10183. LLVMSetExternallyInitialized(g.value, true);
  10184. } else {
  10185. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  10186. }
  10187. if (is_export) {
  10188. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  10189. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  10190. }
  10191. GlobalVariable var = {};
  10192. var.var = g;
  10193. var.decl = decl;
  10194. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  10195. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  10196. if (tav.mode != Addressing_Invalid) {
  10197. if (tav.value.kind != ExactValue_Invalid) {
  10198. ExactValue v = tav.value;
  10199. lbValue init = lb_const_value(m, tav.type, v);
  10200. LLVMSetInitializer(g.value, init.value);
  10201. }
  10202. }
  10203. }
  10204. array_add(&global_variables, var);
  10205. lb_add_entity(m, e, g);
  10206. lb_add_member(m, name, g);
  10207. }
  10208. TIME_SECTION("LLVM Global Procedures and Types");
  10209. for_array(i, info->entities) {
  10210. // arena_free_all(&temp_arena);
  10211. // gbAllocator a = temp_allocator;
  10212. Entity *e = info->entities[i];
  10213. String name = e->token.string;
  10214. DeclInfo *decl = e->decl_info;
  10215. Scope * scope = e->scope;
  10216. if ((scope->flags & ScopeFlag_File) == 0) {
  10217. continue;
  10218. }
  10219. Scope *package_scope = scope->parent;
  10220. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  10221. switch (e->kind) {
  10222. case Entity_Variable:
  10223. // NOTE(bill): Handled above as it requires a specific load order
  10224. continue;
  10225. case Entity_ProcGroup:
  10226. continue;
  10227. case Entity_TypeName:
  10228. case Entity_Procedure:
  10229. break;
  10230. }
  10231. bool polymorphic_struct = false;
  10232. if (e->type != nullptr && e->kind == Entity_TypeName) {
  10233. Type *bt = base_type(e->type);
  10234. if (bt->kind == Type_Struct) {
  10235. polymorphic_struct = is_type_polymorphic(bt);
  10236. }
  10237. }
  10238. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  10239. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  10240. continue;
  10241. }
  10242. String mangled_name = lb_get_entity_name(m, e);
  10243. switch (e->kind) {
  10244. case Entity_TypeName:
  10245. lb_type(m, e->type);
  10246. break;
  10247. case Entity_Procedure:
  10248. {
  10249. lbProcedure *p = lb_create_procedure(m, e);
  10250. array_add(&m->procedures_to_generate, p);
  10251. }
  10252. break;
  10253. }
  10254. }
  10255. TIME_SECTION("LLVM Registry Initializtion");
  10256. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  10257. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  10258. defer (LLVMDisposePassManager(default_function_pass_manager));
  10259. {
  10260. LLVMAddMemCpyOptPass(default_function_pass_manager);
  10261. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10262. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  10263. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  10264. LLVMAddConstantPropagationPass(default_function_pass_manager);
  10265. LLVMAddAggressiveDCEPass(default_function_pass_manager);
  10266. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  10267. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10268. LLVMAddCFGSimplificationPass(default_function_pass_manager);
  10269. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager);
  10270. if (build_context.optimization_level >= 2) {
  10271. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  10272. LLVMAddEarlyCSEPass(default_function_pass_manager);
  10273. LLVMAddEarlyCSEMemSSAPass(default_function_pass_manager);
  10274. LLVMAddLowerExpectIntrinsicPass(default_function_pass_manager);
  10275. LLVMAddAlignmentFromAssumptionsPass(default_function_pass_manager);
  10276. LLVMAddLoopRotatePass(default_function_pass_manager);
  10277. LLVMAddDeadStoreEliminationPass(default_function_pass_manager);
  10278. LLVMAddScalarizerPass(default_function_pass_manager);
  10279. LLVMAddReassociatePass(default_function_pass_manager);
  10280. LLVMAddAddDiscriminatorsPass(default_function_pass_manager);
  10281. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10282. LLVMAddCorrelatedValuePropagationPass(default_function_pass_manager);
  10283. LLVMAddSLPVectorizePass(default_function_pass_manager);
  10284. LLVMAddLoopVectorizePass(default_function_pass_manager);
  10285. }
  10286. }
  10287. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  10288. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  10289. {
  10290. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  10291. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  10292. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager_without_memcpy);
  10293. LLVMAddConstantPropagationPass(default_function_pass_manager_without_memcpy);
  10294. LLVMAddAggressiveDCEPass(default_function_pass_manager_without_memcpy);
  10295. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  10296. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  10297. LLVMAddCFGSimplificationPass(default_function_pass_manager_without_memcpy);
  10298. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager_without_memcpy);
  10299. }
  10300. TIME_SECTION("LLVM Runtime Creation");
  10301. lbProcedure *startup_type_info = nullptr;
  10302. lbProcedure *startup_context = nullptr;
  10303. lbProcedure *startup_runtime = nullptr;
  10304. { // Startup Type Info
  10305. Type *params = alloc_type_tuple();
  10306. Type *results = alloc_type_tuple();
  10307. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10308. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  10309. p->is_startup = true;
  10310. startup_type_info = p;
  10311. lb_begin_procedure_body(p);
  10312. lb_setup_type_info_data(p);
  10313. lb_end_procedure_body(p);
  10314. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10315. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10316. LLVMDumpValue(p->value);
  10317. gb_printf_err("\n\n\n\n");
  10318. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10319. }
  10320. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10321. }
  10322. { // Startup Context
  10323. Type *params = alloc_type_tuple();
  10324. Type *results = alloc_type_tuple();
  10325. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10326. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_CONTEXT_PROC_NAME), proc_type);
  10327. p->is_startup = true;
  10328. startup_context = p;
  10329. lb_begin_procedure_body(p);
  10330. lb_emit_init_context(p, p->module->global_default_context);
  10331. lb_end_procedure_body(p);
  10332. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10333. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10334. LLVMDumpValue(p->value);
  10335. gb_printf_err("\n\n\n\n");
  10336. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10337. }
  10338. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10339. }
  10340. { // Startup Runtime
  10341. Type *params = alloc_type_tuple();
  10342. Type *results = alloc_type_tuple();
  10343. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10344. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  10345. p->is_startup = true;
  10346. startup_runtime = p;
  10347. lb_begin_procedure_body(p);
  10348. for_array(i, global_variables) {
  10349. auto *var = &global_variables[i];
  10350. if (var->decl->init_expr != nullptr) {
  10351. lbValue init = lb_build_expr(p, var->decl->init_expr);
  10352. if (!lb_is_const(init)) {
  10353. var->init = init;
  10354. }
  10355. }
  10356. Entity *e = var->decl->entity;
  10357. GB_ASSERT(e->kind == Entity_Variable);
  10358. if (e->Variable.is_foreign) {
  10359. Entity *fl = e->Procedure.foreign_library;
  10360. lb_add_foreign_library_path(m, fl);
  10361. }
  10362. if (e->flags & EntityFlag_Static) {
  10363. LLVMSetLinkage(var->var.value, LLVMInternalLinkage);
  10364. }
  10365. if (var->init.value != nullptr) {
  10366. Type *t = type_deref(var->var.type);
  10367. if (is_type_any(t)) {
  10368. // NOTE(bill): Edge case for 'any' type
  10369. Type *var_type = default_type(var->init.type);
  10370. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  10371. lb_addr_store(p, g, var->init);
  10372. lbValue gp = lb_addr_get_ptr(p, g);
  10373. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  10374. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  10375. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  10376. lb_emit_store(p, ti, lb_type_info(m, var_type));
  10377. } else {
  10378. lb_emit_store(p, var->var, lb_emit_conv(p, var->init, t));
  10379. }
  10380. }
  10381. }
  10382. lb_end_procedure_body(p);
  10383. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10384. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10385. LLVMDumpValue(p->value);
  10386. gb_printf_err("\n\n\n\n");
  10387. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10388. }
  10389. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10390. /*{
  10391. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  10392. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  10393. instr != last_instr;
  10394. instr = LLVMGetNextInstruction(instr)) {
  10395. if (LLVMIsAAllocaInst(instr)) {
  10396. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  10397. LLVMValueRef sz_val = LLVMSizeOf(type);
  10398. GB_ASSERT(LLVMIsConstant(sz_val));
  10399. gb_printf_err(">> 0x%p\n", sz_val);
  10400. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  10401. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  10402. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  10403. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  10404. gb_printf_err(">> %ll\n", sz);
  10405. }
  10406. }
  10407. }*/
  10408. }
  10409. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  10410. Type *params = alloc_type_tuple();
  10411. Type *results = alloc_type_tuple();
  10412. String name = str_lit("main");
  10413. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  10414. name = str_lit("mainCRTStartup");
  10415. } else {
  10416. array_init(&params->Tuple.variables, heap_allocator(), 2);
  10417. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  10418. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  10419. }
  10420. array_init(&results->Tuple.variables, heap_allocator(), 1);
  10421. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  10422. Type *proc_type = alloc_type_proc(nullptr,
  10423. params, params->Tuple.variables.count,
  10424. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  10425. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  10426. p->is_startup = true;
  10427. lb_begin_procedure_body(p);
  10428. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  10429. GB_ASSERT(found != nullptr);
  10430. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  10431. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_context->type)), startup_context->value, nullptr, 0, "");
  10432. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  10433. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  10434. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  10435. lb_end_procedure_body(p);
  10436. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10437. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10438. LLVMDumpValue(p->value);
  10439. gb_printf_err("\n\n\n\n");
  10440. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10441. }
  10442. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10443. }
  10444. TIME_SECTION("LLVM Procedure Generation");
  10445. for_array(i, m->procedures_to_generate) {
  10446. lbProcedure *p = m->procedures_to_generate[i];
  10447. if (p->is_done) {
  10448. continue;
  10449. }
  10450. if (p->body != nullptr) { // Build Procedure
  10451. m->curr_procedure = p;
  10452. lb_begin_procedure_body(p);
  10453. lb_build_stmt(p, p->body);
  10454. lb_end_procedure_body(p);
  10455. p->is_done = true;
  10456. m->curr_procedure = nullptr;
  10457. }
  10458. lb_end_procedure(p);
  10459. // Add Flags
  10460. if (p->body != nullptr) {
  10461. if (p->name == "memcpy" || p->name == "memmove" ||
  10462. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  10463. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  10464. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  10465. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  10466. }
  10467. }
  10468. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10469. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  10470. LLVMDumpValue(p->value);
  10471. gb_printf_err("\n\n\n\n");
  10472. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10473. }
  10474. }
  10475. TIME_SECTION("LLVM Function Pass");
  10476. for_array(i, m->procedures_to_generate) {
  10477. lbProcedure *p = m->procedures_to_generate[i];
  10478. if (p->body != nullptr) { // Build Procedure
  10479. for (i32 i = 0; i <= build_context.optimization_level; i++) {
  10480. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  10481. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  10482. } else {
  10483. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10484. }
  10485. }
  10486. }
  10487. }
  10488. TIME_SECTION("LLVM Module Pass");
  10489. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  10490. defer (LLVMDisposePassManager(module_pass_manager));
  10491. LLVMAddAlwaysInlinerPass(module_pass_manager);
  10492. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  10493. // if (build_context.optimization_level >= 2) {
  10494. // LLVMAddArgumentPromotionPass(module_pass_manager);
  10495. // LLVMAddConstantMergePass(module_pass_manager);
  10496. // LLVMAddGlobalDCEPass(module_pass_manager);
  10497. // LLVMAddDeadArgEliminationPass(module_pass_manager);
  10498. // }
  10499. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  10500. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  10501. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level);
  10502. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level);
  10503. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  10504. LLVMRunPassManager(module_pass_manager, mod);
  10505. llvm_error = nullptr;
  10506. defer (LLVMDisposeMessage(llvm_error));
  10507. String filepath_ll = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".ll"));
  10508. defer (gb_free(heap_allocator(), filepath_ll.text));
  10509. String filepath_obj = {};
  10510. switch (build_context.metrics.os) {
  10511. case TargetOs_windows:
  10512. filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".obj"));
  10513. break;
  10514. case TargetOs_darwin:
  10515. case TargetOs_linux:
  10516. case TargetOs_essence:
  10517. filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".o"));
  10518. break;
  10519. case TargetOs_js:
  10520. filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  10521. break;
  10522. }
  10523. LLVMDIBuilderFinalize(m->debug_builder);
  10524. if (LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error)) {
  10525. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10526. return;
  10527. }
  10528. llvm_error = nullptr;
  10529. if (build_context.keep_temp_files) {
  10530. TIME_SECTION("LLVM Print Module to File");
  10531. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  10532. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10533. return;
  10534. }
  10535. }
  10536. TIME_SECTION("LLVM Object Generation");
  10537. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  10538. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  10539. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10540. gb_exit(1);
  10541. return;
  10542. }
  10543. array_add(&gen->output_object_paths, filepath_obj);
  10544. for_array(i, m->info->required_foreign_imports_through_force) {
  10545. Entity *e = m->info->required_foreign_imports_through_force[i];
  10546. lb_add_foreign_library_path(m, e);
  10547. }
  10548. #undef TIME_SECTION
  10549. }