llvm_backend.cpp 434 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879
  1. #include "llvm_backend.hpp"
  2. #include "llvm_abi.cpp"
  3. #include "llvm_backend_opt.cpp"
  4. gb_global lbAddr lb_global_type_info_data = {};
  5. gb_global lbAddr lb_global_type_info_member_types = {};
  6. gb_global lbAddr lb_global_type_info_member_names = {};
  7. gb_global lbAddr lb_global_type_info_member_offsets = {};
  8. gb_global lbAddr lb_global_type_info_member_usings = {};
  9. gb_global lbAddr lb_global_type_info_member_tags = {};
  10. gb_global isize lb_global_type_info_data_index = 0;
  11. gb_global isize lb_global_type_info_member_types_index = 0;
  12. gb_global isize lb_global_type_info_member_names_index = 0;
  13. gb_global isize lb_global_type_info_member_offsets_index = 0;
  14. gb_global isize lb_global_type_info_member_usings_index = 0;
  15. gb_global isize lb_global_type_info_member_tags_index = 0;
  16. struct lbLoopData {
  17. lbAddr idx_addr;
  18. lbValue idx;
  19. lbBlock *body;
  20. lbBlock *done;
  21. lbBlock *loop;
  22. };
  23. struct lbCompoundLitElemTempData {
  24. Ast * expr;
  25. lbValue value;
  26. i32 elem_index;
  27. lbValue gep;
  28. };
  29. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  30. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  31. LLVMValueRef llvm_zero(lbModule *m) {
  32. return LLVMConstInt(lb_type(m, t_int), 0, false);
  33. }
  34. LLVMValueRef llvm_one(lbModule *m) {
  35. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  36. }
  37. lbValue lb_zero(lbModule *m, Type *t) {
  38. lbValue v = {};
  39. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  40. v.type = t;
  41. return v;
  42. }
  43. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  44. lbValue v = lb_find_or_add_entity_string(m, str);
  45. unsigned indices[1] = {0};
  46. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  47. }
  48. bool lb_is_instr_terminating(LLVMValueRef instr) {
  49. if (instr != nullptr) {
  50. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  51. switch (op) {
  52. case LLVMRet:
  53. case LLVMBr:
  54. case LLVMSwitch:
  55. case LLVMIndirectBr:
  56. case LLVMInvoke:
  57. case LLVMUnreachable:
  58. case LLVMCallBr:
  59. return true;
  60. }
  61. }
  62. return false;
  63. }
  64. lbAddr lb_addr(lbValue addr) {
  65. lbAddr v = {lbAddr_Default, addr};
  66. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  67. GB_ASSERT(is_type_pointer(addr.type));
  68. v.kind = lbAddr_RelativePointer;
  69. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  70. GB_ASSERT(is_type_pointer(addr.type));
  71. v.kind = lbAddr_RelativeSlice;
  72. }
  73. return v;
  74. }
  75. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  76. lbAddr v = {lbAddr_Map, addr};
  77. v.map.key = map_key;
  78. v.map.type = map_type;
  79. v.map.result = map_result;
  80. return v;
  81. }
  82. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  83. lbAddr v = {lbAddr_SoaVariable, addr};
  84. v.soa.index = index;
  85. v.soa.index_expr = index_expr;
  86. return v;
  87. }
  88. Type *lb_addr_type(lbAddr const &addr) {
  89. if (addr.addr.value == nullptr) {
  90. return nullptr;
  91. }
  92. if (addr.kind == lbAddr_Map) {
  93. Type *t = base_type(addr.map.type);
  94. GB_ASSERT(is_type_map(t));
  95. return t->Map.value;
  96. }
  97. return type_deref(addr.addr.type);
  98. }
  99. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  100. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  101. }
  102. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  103. if (addr.addr.value == nullptr) {
  104. GB_PANIC("Illegal addr -> nullptr");
  105. return {};
  106. }
  107. switch (addr.kind) {
  108. case lbAddr_Map: {
  109. Type *map_type = base_type(addr.map.type);
  110. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  111. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  112. auto args = array_make<lbValue>(permanent_allocator(), 2);
  113. args[0] = h;
  114. args[1] = key;
  115. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  116. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  117. }
  118. case lbAddr_RelativePointer: {
  119. Type *rel_ptr = base_type(lb_addr_type(addr));
  120. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  121. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  122. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  123. offset = lb_emit_load(p, offset);
  124. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  125. offset = lb_emit_conv(p, offset, t_i64);
  126. }
  127. offset = lb_emit_conv(p, offset, t_uintptr);
  128. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  129. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  130. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  131. // NOTE(bill): nil check
  132. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  133. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  134. return final_ptr;
  135. }
  136. case lbAddr_SoaVariable: {
  137. // TODO(bill): FIX THIS HACK
  138. return lb_address_from_load(p, lb_addr_load(p, addr));
  139. }
  140. case lbAddr_Context:
  141. GB_PANIC("lbAddr_Context should be handled elsewhere");
  142. }
  143. return addr.addr;
  144. }
  145. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  146. lbAddr addr = lb_build_addr(p, expr);
  147. return lb_addr_get_ptr(p, addr);
  148. }
  149. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  150. if (build_context.no_bounds_check) {
  151. return;
  152. }
  153. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  154. return;
  155. }
  156. index = lb_emit_conv(p, index, t_int);
  157. len = lb_emit_conv(p, len, t_int);
  158. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  159. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  160. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  161. auto args = array_make<lbValue>(permanent_allocator(), 5);
  162. args[0] = file;
  163. args[1] = line;
  164. args[2] = column;
  165. args[3] = index;
  166. args[4] = len;
  167. lb_emit_runtime_call(p, "bounds_check_error", args);
  168. }
  169. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  170. if (build_context.no_bounds_check) {
  171. return;
  172. }
  173. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  174. return;
  175. }
  176. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  177. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  178. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  179. high = lb_emit_conv(p, high, t_int);
  180. if (!lower_value_used) {
  181. auto args = array_make<lbValue>(permanent_allocator(), 5);
  182. args[0] = file;
  183. args[1] = line;
  184. args[2] = column;
  185. args[3] = high;
  186. args[4] = len;
  187. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  188. } else {
  189. // No need to convert unless used
  190. low = lb_emit_conv(p, low, t_int);
  191. auto args = array_make<lbValue>(permanent_allocator(), 6);
  192. args[0] = file;
  193. args[1] = line;
  194. args[2] = column;
  195. args[3] = low;
  196. args[4] = high;
  197. args[5] = len;
  198. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  199. }
  200. }
  201. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  202. if (addr.addr.value == nullptr) {
  203. return;
  204. }
  205. GB_ASSERT(value.type != nullptr);
  206. if (is_type_untyped_undef(value.type)) {
  207. Type *t = lb_addr_type(addr);
  208. value.type = t;
  209. value.value = LLVMGetUndef(lb_type(p->module, t));
  210. } else if (is_type_untyped_nil(value.type)) {
  211. Type *t = lb_addr_type(addr);
  212. value.type = t;
  213. value.value = LLVMConstNull(lb_type(p->module, t));
  214. }
  215. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  216. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  217. }
  218. if (addr.kind == lbAddr_RelativePointer) {
  219. Type *rel_ptr = base_type(lb_addr_type(addr));
  220. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  221. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  222. GB_ASSERT(is_type_pointer(addr.addr.type));
  223. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  224. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  225. lbValue offset = {};
  226. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  227. offset.type = t_uintptr;
  228. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  229. offset = lb_emit_conv(p, offset, t_i64);
  230. }
  231. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  232. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  233. offset = lb_emit_select(p,
  234. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  235. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  236. offset
  237. );
  238. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  239. return;
  240. } else if (addr.kind == lbAddr_RelativeSlice) {
  241. Type *rel_ptr = base_type(lb_addr_type(addr));
  242. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  243. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  244. GB_ASSERT(is_type_pointer(addr.addr.type));
  245. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  246. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  247. lbValue offset = {};
  248. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  249. offset.type = t_uintptr;
  250. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  251. offset = lb_emit_conv(p, offset, t_i64);
  252. }
  253. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  254. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  255. offset = lb_emit_select(p,
  256. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  257. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  258. offset
  259. );
  260. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  261. lbValue len = lb_slice_len(p, value);
  262. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  263. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  264. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  265. return;
  266. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  267. lbValue ptr = addr.addr;
  268. lbValue index = addr.index_set.index;
  269. Ast *node = addr.index_set.node;
  270. ast_node(ce, CallExpr, node);
  271. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  272. proc_type = base_type(proc_type);
  273. GB_ASSERT(is_type_proc(proc_type));
  274. TypeProc *pt = &proc_type->Proc;
  275. isize arg_count = 3;
  276. isize param_count = 0;
  277. if (pt->params) {
  278. GB_ASSERT(pt->params->kind == Type_Tuple);
  279. param_count = pt->params->Tuple.variables.count;
  280. }
  281. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  282. args[0] = ptr;
  283. args[1] = index;
  284. args[2] = value;
  285. isize arg_index = arg_count;
  286. if (arg_count < param_count) {
  287. lbModule *m = p->module;
  288. String proc_name = {};
  289. if (p->entity != nullptr) {
  290. proc_name = p->entity->token.string;
  291. }
  292. TokenPos pos = ast_token(ce->proc).pos;
  293. TypeTuple *param_tuple = &pt->params->Tuple;
  294. isize end = cast(isize)param_count;
  295. while (arg_index < end) {
  296. Entity *e = param_tuple->variables[arg_index];
  297. GB_ASSERT(e->kind == Entity_Variable);
  298. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  299. }
  300. }
  301. Entity *e = entity_from_expr(ce->proc);
  302. GB_ASSERT(e != nullptr);
  303. GB_ASSERT(is_type_polymorphic(e->type));
  304. {
  305. lbValue *found = nullptr;
  306. if (p->module != e->code_gen_module) {
  307. gb_mutex_lock(&p->module->mutex);
  308. }
  309. GB_ASSERT(e->code_gen_module != nullptr);
  310. found = map_get(&e->code_gen_module->values, hash_entity(e));
  311. if (p->module != e->code_gen_module) {
  312. gb_mutex_unlock(&p->module->mutex);
  313. }
  314. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  315. lb_emit_call(p, *found, args);
  316. }
  317. return;
  318. } else if (addr.kind == lbAddr_Map) {
  319. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  320. return;
  321. } else if (addr.kind == lbAddr_Context) {
  322. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  323. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  324. lb_addr_store(p, next_addr, old);
  325. lb_push_context_onto_stack(p, next_addr);
  326. lbValue next = lb_addr_get_ptr(p, next_addr);
  327. if (addr.ctx.sel.index.count > 0) {
  328. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  329. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  330. lb_emit_store(p, lhs, rhs);
  331. } else {
  332. lbValue lhs = next;
  333. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  334. lb_emit_store(p, lhs, rhs);
  335. }
  336. return;
  337. } else if (addr.kind == lbAddr_SoaVariable) {
  338. Type *t = type_deref(addr.addr.type);
  339. t = base_type(t);
  340. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  341. Type *elem_type = t->Struct.soa_elem;
  342. value = lb_emit_conv(p, value, elem_type);
  343. elem_type = base_type(elem_type);
  344. lbValue index = addr.soa.index;
  345. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  346. Type *t = base_type(type_deref(addr.addr.type));
  347. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  348. lbValue len = lb_soa_struct_len(p, addr.addr);
  349. if (addr.soa.index_expr != nullptr) {
  350. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  351. }
  352. }
  353. isize field_count = 0;
  354. switch (elem_type->kind) {
  355. case Type_Struct:
  356. field_count = elem_type->Struct.fields.count;
  357. break;
  358. case Type_Array:
  359. field_count = elem_type->Array.count;
  360. break;
  361. }
  362. for (isize i = 0; i < field_count; i++) {
  363. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  364. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  365. if (t->Struct.soa_kind == StructSoa_Fixed) {
  366. dst = lb_emit_array_ep(p, dst, index);
  367. lb_emit_store(p, dst, src);
  368. } else {
  369. lbValue field = lb_emit_load(p, dst);
  370. dst = lb_emit_ptr_offset(p, field, index);
  371. lb_emit_store(p, dst, src);
  372. }
  373. }
  374. return;
  375. }
  376. GB_ASSERT(value.value != nullptr);
  377. value = lb_emit_conv(p, value, lb_addr_type(addr));
  378. // if (lb_is_const_or_global(value)) {
  379. // // NOTE(bill): Just bypass the actual storage and set the initializer
  380. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  381. // LLVMValueRef dst = addr.addr.value;
  382. // LLVMValueRef src = value.value;
  383. // LLVMSetInitializer(dst, src);
  384. // return;
  385. // }
  386. // }
  387. lb_emit_store(p, addr.addr, value);
  388. }
  389. void lb_const_store(lbValue ptr, lbValue value) {
  390. GB_ASSERT(lb_is_const(ptr));
  391. GB_ASSERT(lb_is_const(value));
  392. GB_ASSERT(is_type_pointer(ptr.type));
  393. LLVMSetInitializer(ptr.value, value.value);
  394. }
  395. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  396. GB_ASSERT(value.value != nullptr);
  397. Type *a = type_deref(ptr.type);
  398. if (is_type_boolean(a)) {
  399. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  400. value = lb_emit_conv(p, value, a);
  401. }
  402. Type *ca = core_type(a);
  403. if (ca->kind == Type_Basic) {
  404. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  405. }
  406. if (is_type_proc(a)) {
  407. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  408. // stored as regular pointer with no procedure information
  409. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  410. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  411. LLVMBuildStore(p->builder, v, ptr.value);
  412. } else {
  413. Type *ca = core_type(a);
  414. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  415. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  416. } else {
  417. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  418. }
  419. LLVMBuildStore(p->builder, value.value, ptr.value);
  420. }
  421. }
  422. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  423. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  424. }
  425. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  426. lbModule *m = p->module;
  427. GB_ASSERT(value.value != nullptr);
  428. GB_ASSERT(is_type_pointer(value.type));
  429. Type *t = type_deref(value.type);
  430. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  431. return lbValue{v, t};
  432. }
  433. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  434. GB_ASSERT(addr.addr.value != nullptr);
  435. if (addr.kind == lbAddr_RelativePointer) {
  436. Type *rel_ptr = base_type(lb_addr_type(addr));
  437. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  438. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  439. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  440. offset = lb_emit_load(p, offset);
  441. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  442. offset = lb_emit_conv(p, offset, t_i64);
  443. }
  444. offset = lb_emit_conv(p, offset, t_uintptr);
  445. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  446. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  447. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  448. // NOTE(bill): nil check
  449. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  450. lbValue final_ptr = {};
  451. final_ptr.type = absolute_ptr.type;
  452. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  453. return lb_emit_load(p, final_ptr);
  454. } else if (addr.kind == lbAddr_RelativeSlice) {
  455. Type *rel_ptr = base_type(lb_addr_type(addr));
  456. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  457. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  458. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  459. lbValue offset = lb_emit_load(p, offset_ptr);
  460. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  461. offset = lb_emit_conv(p, offset, t_i64);
  462. }
  463. offset = lb_emit_conv(p, offset, t_uintptr);
  464. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  465. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  466. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  467. Type *slice_elem = slice_type->Slice.elem;
  468. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  469. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  470. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  471. // NOTE(bill): nil check
  472. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  473. lbValue data = {};
  474. data.type = absolute_ptr.type;
  475. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  476. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  477. len = lb_emit_conv(p, len, t_int);
  478. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  479. lb_fill_slice(p, slice, data, len);
  480. return lb_addr_load(p, slice);
  481. } else if (addr.kind == lbAddr_Map) {
  482. Type *map_type = base_type(addr.map.type);
  483. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  484. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  485. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  486. auto args = array_make<lbValue>(permanent_allocator(), 2);
  487. args[0] = h;
  488. args[1] = key;
  489. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  490. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  491. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  492. lbBlock *then = lb_create_block(p, "map.get.then");
  493. lbBlock *done = lb_create_block(p, "map.get.done");
  494. lb_emit_if(p, ok, then, done);
  495. lb_start_block(p, then);
  496. {
  497. // TODO(bill): mem copy it instead?
  498. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  499. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  500. lb_emit_store(p, gep0, lb_emit_load(p, value));
  501. }
  502. lb_emit_jump(p, done);
  503. lb_start_block(p, done);
  504. if (is_type_tuple(addr.map.result)) {
  505. return lb_addr_load(p, v);
  506. } else {
  507. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  508. return lb_emit_load(p, single);
  509. }
  510. } else if (addr.kind == lbAddr_Context) {
  511. lbValue a = addr.addr;
  512. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  513. if (addr.ctx.sel.index.count > 0) {
  514. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  515. return lb_emit_load(p, b);
  516. } else {
  517. return lb_emit_load(p, a);
  518. }
  519. } else if (addr.kind == lbAddr_SoaVariable) {
  520. Type *t = type_deref(addr.addr.type);
  521. t = base_type(t);
  522. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  523. Type *elem = t->Struct.soa_elem;
  524. lbValue len = {};
  525. if (t->Struct.soa_kind == StructSoa_Fixed) {
  526. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  527. } else {
  528. lbValue v = lb_emit_load(p, addr.addr);
  529. len = lb_soa_struct_len(p, v);
  530. }
  531. lbAddr res = lb_add_local_generated(p, elem, true);
  532. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  533. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  534. }
  535. if (t->Struct.soa_kind == StructSoa_Fixed) {
  536. for_array(i, t->Struct.fields) {
  537. Entity *field = t->Struct.fields[i];
  538. Type *base_type = field->type;
  539. GB_ASSERT(base_type->kind == Type_Array);
  540. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  541. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  542. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  543. lbValue src = lb_emit_load(p, src_ptr);
  544. lb_emit_store(p, dst, src);
  545. }
  546. } else {
  547. isize field_count = t->Struct.fields.count;
  548. if (t->Struct.soa_kind == StructSoa_Slice) {
  549. field_count -= 1;
  550. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  551. field_count -= 3;
  552. }
  553. for (isize i = 0; i < field_count; i++) {
  554. Entity *field = t->Struct.fields[i];
  555. Type *base_type = field->type;
  556. GB_ASSERT(base_type->kind == Type_Pointer);
  557. Type *elem = base_type->Pointer.elem;
  558. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  559. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  560. lbValue src = lb_emit_load(p, src_ptr);
  561. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  562. src = lb_emit_load(p, src);
  563. lb_emit_store(p, dst, src);
  564. }
  565. }
  566. return lb_addr_load(p, res);
  567. }
  568. if (is_type_proc(addr.addr.type)) {
  569. return addr.addr;
  570. }
  571. return lb_emit_load(p, addr.addr);
  572. }
  573. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  574. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  575. }
  576. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  577. Type *t = u.type;
  578. GB_ASSERT_MSG(is_type_pointer(t) &&
  579. is_type_union(type_deref(t)), "%s", type_to_string(t));
  580. Type *ut = type_deref(t);
  581. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  582. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  583. GB_ASSERT(type_size_of(ut) > 0);
  584. Type *tag_type = union_tag_type(ut);
  585. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  586. unsigned element_count = LLVMCountStructElementTypes(uvt);
  587. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  588. lbValue tag_ptr = {};
  589. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  590. tag_ptr.type = alloc_type_pointer(tag_type);
  591. return tag_ptr;
  592. }
  593. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  594. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  595. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  596. return lb_emit_load(p, tag_ptr);
  597. }
  598. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  599. Type *t = type_deref(parent.type);
  600. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  601. // No tag needed!
  602. } else {
  603. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  604. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  605. }
  606. }
  607. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  608. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  609. lb_emit_store(p, underlying, variant);
  610. lb_emit_store_union_variant_tag(p, parent, variant_type);
  611. }
  612. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  613. unsigned field_count = LLVMCountStructElementTypes(src);
  614. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  615. LLVMGetStructElementTypes(src, fields);
  616. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  617. }
  618. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  619. switch (alignment) {
  620. case 1:
  621. return LLVMArrayType(lb_type(m, t_u8), 0);
  622. case 2:
  623. return LLVMArrayType(lb_type(m, t_u16), 0);
  624. case 4:
  625. return LLVMArrayType(lb_type(m, t_u32), 0);
  626. case 8:
  627. return LLVMArrayType(lb_type(m, t_u64), 0);
  628. case 16:
  629. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  630. default:
  631. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  632. break;
  633. }
  634. return nullptr;
  635. }
  636. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  637. if (!elem_type_can_be_constant(elem_type)) {
  638. return false;
  639. }
  640. if (elem->kind == Ast_FieldValue) {
  641. elem = elem->FieldValue.value;
  642. }
  643. TypeAndValue tav = type_and_value_of_expr(elem);
  644. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  645. return tav.value.kind != ExactValue_Invalid;
  646. }
  647. String lb_mangle_name(lbModule *m, Entity *e) {
  648. String name = e->token.string;
  649. AstPackage *pkg = e->pkg;
  650. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  651. String pkgn = pkg->name;
  652. GB_ASSERT(!rune_is_digit(pkgn[0]));
  653. if (pkgn == "llvm") {
  654. pkgn = str_lit("llvm$");
  655. }
  656. isize max_len = pkgn.len + 1 + name.len + 1;
  657. bool require_suffix_id = is_type_polymorphic(e->type, true);
  658. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  659. require_suffix_id = true;
  660. } else if (is_blank_ident(e->token)) {
  661. require_suffix_id = true;
  662. }if (e->flags & EntityFlag_NotExported) {
  663. require_suffix_id = true;
  664. }
  665. if (require_suffix_id) {
  666. max_len += 21;
  667. }
  668. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  669. isize new_name_len = gb_snprintf(
  670. new_name, max_len,
  671. "%.*s.%.*s", LIT(pkgn), LIT(name)
  672. );
  673. if (require_suffix_id) {
  674. char *str = new_name + new_name_len-1;
  675. isize len = max_len-new_name_len;
  676. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  677. new_name_len += extra-1;
  678. }
  679. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  680. return mangled_name;
  681. }
  682. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  683. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  684. // and as a result, the declaration does not have time to determine what it should be
  685. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  686. if (e->TypeName.ir_mangled_name.len != 0) {
  687. return e->TypeName.ir_mangled_name;
  688. }
  689. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  690. if (p == nullptr) {
  691. Entity *proc = nullptr;
  692. if (e->parent_proc_decl != nullptr) {
  693. proc = e->parent_proc_decl->entity;
  694. } else {
  695. Scope *scope = e->scope;
  696. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  697. scope = scope->parent;
  698. }
  699. GB_ASSERT(scope != nullptr);
  700. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  701. proc = scope->procedure_entity;
  702. }
  703. GB_ASSERT(proc->kind == Entity_Procedure);
  704. if (proc->code_gen_procedure != nullptr) {
  705. p = proc->code_gen_procedure;
  706. }
  707. }
  708. // NOTE(bill): Generate a new name
  709. // parent_proc.name-guid
  710. String ts_name = e->token.string;
  711. if (p != nullptr) {
  712. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  713. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  714. u32 guid = ++p->module->nested_type_name_guid;
  715. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  716. String name = make_string(cast(u8 *)name_text, name_len-1);
  717. e->TypeName.ir_mangled_name = name;
  718. return name;
  719. } else {
  720. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  721. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  722. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  723. static u32 guid = 0;
  724. guid += 1;
  725. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  726. String name = make_string(cast(u8 *)name_text, name_len-1);
  727. e->TypeName.ir_mangled_name = name;
  728. return name;
  729. }
  730. }
  731. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  732. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  733. return e->TypeName.ir_mangled_name;
  734. }
  735. GB_ASSERT(e != nullptr);
  736. if (e->pkg == nullptr) {
  737. return e->token.string;
  738. }
  739. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  740. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  741. }
  742. String name = {};
  743. bool no_name_mangle = false;
  744. if (e->kind == Entity_Variable) {
  745. bool is_foreign = e->Variable.is_foreign;
  746. bool is_export = e->Variable.is_export;
  747. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  748. if (e->Variable.link_name.len > 0) {
  749. return e->Variable.link_name;
  750. }
  751. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  752. return e->Procedure.link_name;
  753. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  754. no_name_mangle = true;
  755. }
  756. if (!no_name_mangle) {
  757. name = lb_mangle_name(m, e);
  758. }
  759. if (name.len == 0) {
  760. name = e->token.string;
  761. }
  762. if (e->kind == Entity_TypeName) {
  763. e->TypeName.ir_mangled_name = name;
  764. } else if (e->kind == Entity_Procedure) {
  765. e->Procedure.link_name = name;
  766. }
  767. return name;
  768. }
  769. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  770. Type *original_type = type;
  771. LLVMContextRef ctx = m->ctx;
  772. i64 size = type_size_of(type); // Check size
  773. GB_ASSERT(type != t_invalid);
  774. switch (type->kind) {
  775. case Type_Basic:
  776. switch (type->Basic.kind) {
  777. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  778. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  779. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  780. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  781. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  782. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  783. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  784. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  785. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  786. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  787. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  788. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  789. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  790. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  791. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  792. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  793. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  794. // Basic_f16,
  795. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  796. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  797. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  798. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  799. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  800. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  801. // Basic_complex32,
  802. case Basic_complex64:
  803. {
  804. char const *name = "..complex64";
  805. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  806. if (type != nullptr) {
  807. return type;
  808. }
  809. type = LLVMStructCreateNamed(ctx, name);
  810. LLVMTypeRef fields[2] = {
  811. lb_type(m, t_f32),
  812. lb_type(m, t_f32),
  813. };
  814. LLVMStructSetBody(type, fields, 2, false);
  815. return type;
  816. }
  817. case Basic_complex128:
  818. {
  819. char const *name = "..complex128";
  820. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  821. if (type != nullptr) {
  822. return type;
  823. }
  824. type = LLVMStructCreateNamed(ctx, name);
  825. LLVMTypeRef fields[2] = {
  826. lb_type(m, t_f64),
  827. lb_type(m, t_f64),
  828. };
  829. LLVMStructSetBody(type, fields, 2, false);
  830. return type;
  831. }
  832. case Basic_quaternion128:
  833. {
  834. char const *name = "..quaternion128";
  835. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  836. if (type != nullptr) {
  837. return type;
  838. }
  839. type = LLVMStructCreateNamed(ctx, name);
  840. LLVMTypeRef fields[4] = {
  841. lb_type(m, t_f32),
  842. lb_type(m, t_f32),
  843. lb_type(m, t_f32),
  844. lb_type(m, t_f32),
  845. };
  846. LLVMStructSetBody(type, fields, 4, false);
  847. return type;
  848. }
  849. case Basic_quaternion256:
  850. {
  851. char const *name = "..quaternion256";
  852. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  853. if (type != nullptr) {
  854. return type;
  855. }
  856. type = LLVMStructCreateNamed(ctx, name);
  857. LLVMTypeRef fields[4] = {
  858. lb_type(m, t_f64),
  859. lb_type(m, t_f64),
  860. lb_type(m, t_f64),
  861. lb_type(m, t_f64),
  862. };
  863. LLVMStructSetBody(type, fields, 4, false);
  864. return type;
  865. }
  866. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  867. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  868. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  869. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  870. case Basic_string:
  871. {
  872. char const *name = "..string";
  873. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  874. if (type != nullptr) {
  875. return type;
  876. }
  877. type = LLVMStructCreateNamed(ctx, name);
  878. LLVMTypeRef fields[2] = {
  879. LLVMPointerType(lb_type(m, t_u8), 0),
  880. lb_type(m, t_int),
  881. };
  882. LLVMStructSetBody(type, fields, 2, false);
  883. return type;
  884. }
  885. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  886. case Basic_any:
  887. {
  888. char const *name = "..any";
  889. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  890. if (type != nullptr) {
  891. return type;
  892. }
  893. type = LLVMStructCreateNamed(ctx, name);
  894. LLVMTypeRef fields[2] = {
  895. lb_type(m, t_rawptr),
  896. lb_type(m, t_typeid),
  897. };
  898. LLVMStructSetBody(type, fields, 2, false);
  899. return type;
  900. }
  901. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  902. // Endian Specific Types
  903. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  904. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  905. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  906. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  907. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  908. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  909. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  910. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  911. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  912. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  913. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  914. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  915. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  916. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  917. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  918. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  919. // Untyped types
  920. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  921. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  922. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  923. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  924. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  925. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  926. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  927. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  928. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  929. }
  930. break;
  931. case Type_Named:
  932. {
  933. Type *base = base_type(type->Named.base);
  934. switch (base->kind) {
  935. case Type_Basic:
  936. return lb_type_internal(m, base);
  937. case Type_Named:
  938. case Type_Generic:
  939. GB_PANIC("INVALID TYPE");
  940. break;
  941. case Type_Pointer:
  942. case Type_Array:
  943. case Type_EnumeratedArray:
  944. case Type_Slice:
  945. case Type_DynamicArray:
  946. case Type_Map:
  947. case Type_Enum:
  948. case Type_BitSet:
  949. case Type_SimdVector:
  950. return lb_type_internal(m, base);
  951. // TODO(bill): Deal with this correctly. Can this be named?
  952. case Type_Proc:
  953. return lb_type_internal(m, base);
  954. case Type_Tuple:
  955. return lb_type_internal(m, base);
  956. }
  957. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  958. if (found) {
  959. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  960. if (kind == LLVMStructTypeKind) {
  961. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  962. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  963. if (llvm_type != nullptr) {
  964. return llvm_type;
  965. }
  966. llvm_type = LLVMStructCreateNamed(ctx, name);
  967. map_set(&m->types, hash_type(type), llvm_type);
  968. lb_clone_struct_type(llvm_type, *found);
  969. return llvm_type;
  970. }
  971. }
  972. switch (base->kind) {
  973. case Type_Struct:
  974. case Type_Union:
  975. {
  976. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  977. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  978. if (llvm_type != nullptr) {
  979. return llvm_type;
  980. }
  981. llvm_type = LLVMStructCreateNamed(ctx, name);
  982. map_set(&m->types, hash_type(type), llvm_type);
  983. lb_clone_struct_type(llvm_type, lb_type(m, base));
  984. return llvm_type;
  985. }
  986. }
  987. return lb_type_internal(m, base);
  988. }
  989. case Type_Pointer:
  990. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  991. case Type_Array: {
  992. m->internal_type_level -= 1;
  993. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  994. m->internal_type_level += 1;
  995. return t;
  996. }
  997. case Type_EnumeratedArray: {
  998. m->internal_type_level -= 1;
  999. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1000. m->internal_type_level += 1;
  1001. return t;
  1002. }
  1003. case Type_Slice:
  1004. {
  1005. LLVMTypeRef fields[2] = {
  1006. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1007. lb_type(m, t_int), // len
  1008. };
  1009. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1010. }
  1011. break;
  1012. case Type_DynamicArray:
  1013. {
  1014. LLVMTypeRef fields[4] = {
  1015. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1016. lb_type(m, t_int), // len
  1017. lb_type(m, t_int), // cap
  1018. lb_type(m, t_allocator), // allocator
  1019. };
  1020. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1021. }
  1022. break;
  1023. case Type_Map:
  1024. return lb_type(m, type->Map.internal_type);
  1025. case Type_Struct:
  1026. {
  1027. if (type->Struct.is_raw_union) {
  1028. unsigned field_count = 2;
  1029. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1030. i64 alignment = type_align_of(type);
  1031. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1032. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1033. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1034. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1035. }
  1036. isize offset = 0;
  1037. if (type->Struct.custom_align > 0) {
  1038. offset = 1;
  1039. }
  1040. m->internal_type_level += 1;
  1041. defer (m->internal_type_level -= 1);
  1042. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1043. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1044. for_array(i, type->Struct.fields) {
  1045. Entity *field = type->Struct.fields[i];
  1046. fields[i+offset] = lb_type(m, field->type);
  1047. }
  1048. if (type->Struct.custom_align > 0) {
  1049. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1050. }
  1051. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1052. }
  1053. break;
  1054. case Type_Union:
  1055. if (type->Union.variants.count == 0) {
  1056. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1057. } else {
  1058. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1059. // LLVM takes the first element's alignment as the entire alignment (like C)
  1060. i64 align = type_align_of(type);
  1061. i64 size = type_size_of(type);
  1062. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1063. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1064. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1065. }
  1066. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1067. LLVMTypeRef fields[3] = {};
  1068. unsigned field_count = 1;
  1069. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1070. if (is_type_union_maybe_pointer(type)) {
  1071. field_count += 1;
  1072. fields[1] = lb_type(m, type->Union.variants[0]);
  1073. } else {
  1074. field_count += 2;
  1075. if (block_size == align) {
  1076. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1077. } else {
  1078. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1079. }
  1080. fields[2] = lb_type(m, union_tag_type(type));
  1081. }
  1082. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1083. }
  1084. break;
  1085. case Type_Enum:
  1086. return lb_type(m, base_enum_type(type));
  1087. case Type_Tuple:
  1088. if (type->Tuple.variables.count == 1) {
  1089. return lb_type(m, type->Tuple.variables[0]->type);
  1090. } else {
  1091. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1092. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1093. for_array(i, type->Tuple.variables) {
  1094. Entity *field = type->Tuple.variables[i];
  1095. LLVMTypeRef param_type = nullptr;
  1096. param_type = lb_type(m, field->type);
  1097. fields[i] = param_type;
  1098. }
  1099. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1100. }
  1101. case Type_Proc:
  1102. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1103. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1104. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1105. } else {
  1106. unsigned param_count = 0;
  1107. if (type->Proc.calling_convention == ProcCC_Odin) {
  1108. param_count += 1;
  1109. }
  1110. if (type->Proc.param_count != 0) {
  1111. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1112. for_array(i, type->Proc.params->Tuple.variables) {
  1113. Entity *e = type->Proc.params->Tuple.variables[i];
  1114. if (e->kind != Entity_Variable) {
  1115. continue;
  1116. }
  1117. param_count += 1;
  1118. }
  1119. }
  1120. m->internal_type_level += 1;
  1121. defer (m->internal_type_level -= 1);
  1122. LLVMTypeRef ret = nullptr;
  1123. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1124. if (type->Proc.result_count != 0) {
  1125. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1126. ret = lb_type(m, single_ret);
  1127. if (ret != nullptr) {
  1128. if (is_type_boolean(single_ret) &&
  1129. is_calling_convention_none(type->Proc.calling_convention) &&
  1130. type_size_of(single_ret) <= 1) {
  1131. ret = LLVMInt1TypeInContext(m->ctx);
  1132. }
  1133. }
  1134. }
  1135. isize param_index = 0;
  1136. if (type->Proc.param_count != 0) {
  1137. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1138. for_array(i, type->Proc.params->Tuple.variables) {
  1139. Entity *e = type->Proc.params->Tuple.variables[i];
  1140. if (e->kind != Entity_Variable) {
  1141. continue;
  1142. }
  1143. Type *e_type = reduce_tuple_to_single_type(e->type);
  1144. LLVMTypeRef param_type = nullptr;
  1145. if (is_type_boolean(e_type) &&
  1146. type_size_of(e_type) <= 1) {
  1147. param_type = LLVMInt1TypeInContext(m->ctx);
  1148. } else {
  1149. if (is_type_proc(e_type)) {
  1150. param_type = lb_type(m, t_rawptr);
  1151. } else {
  1152. param_type = lb_type(m, e_type);
  1153. }
  1154. }
  1155. params[param_index++] = param_type;
  1156. }
  1157. }
  1158. if (param_index < param_count) {
  1159. params[param_index++] = lb_type(m, t_rawptr);
  1160. // params[param_index++] = lb_type(m, t_context_ptr);
  1161. }
  1162. GB_ASSERT(param_index == param_count);
  1163. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1164. map_set(&m->function_type_map, hash_type(type), ft);
  1165. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1166. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1167. // LLVMTypeRef new_ret = LLVMGetReturnType(new_abi_fn_type);
  1168. // LLVMTypeRef old_ret = LLVMGetReturnType(old_abi_fn_type);
  1169. // unsigned new_count = LLVMCountParamTypes(new_abi_fn_type);
  1170. // unsigned old_count = LLVMCountParamTypes(old_abi_fn_type);
  1171. // GB_ASSERT_MSG(new_count == old_count, "%u %u, %s %s", new_count, old_count, LLVMPrintTypeToString(new_abi_fn_type), LLVMPrintTypeToString(old_abi_fn_type));
  1172. return new_abi_fn_ptr_type;
  1173. }
  1174. break;
  1175. case Type_BitSet:
  1176. {
  1177. Type *ut = bit_set_to_int(type);
  1178. return lb_type(m, ut);
  1179. }
  1180. case Type_SimdVector:
  1181. if (type->SimdVector.is_x86_mmx) {
  1182. return LLVMX86MMXTypeInContext(ctx);
  1183. }
  1184. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1185. case Type_RelativePointer:
  1186. return lb_type_internal(m, type->RelativePointer.base_integer);
  1187. case Type_RelativeSlice:
  1188. {
  1189. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1190. unsigned field_count = 2;
  1191. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1192. fields[0] = base_integer;
  1193. fields[1] = base_integer;
  1194. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1195. }
  1196. }
  1197. GB_PANIC("Invalid type %s", type_to_string(type));
  1198. return LLVMInt32TypeInContext(ctx);
  1199. }
  1200. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1201. type = default_type(type);
  1202. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1203. if (found) {
  1204. return *found;
  1205. }
  1206. LLVMTypeRef llvm_type = nullptr;
  1207. m->internal_type_level += 1;
  1208. llvm_type = lb_type_internal(m, type);
  1209. m->internal_type_level -= 1;
  1210. if (m->internal_type_level == 0) {
  1211. map_set(&m->types, hash_type(type), llvm_type);
  1212. if (is_type_named(type)) {
  1213. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1214. }
  1215. }
  1216. return llvm_type;
  1217. }
  1218. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1219. if (key == nullptr) {
  1220. return nullptr;
  1221. }
  1222. auto found = map_get(&m->debug_values, hash_pointer(key));
  1223. if (found) {
  1224. return *found;
  1225. }
  1226. return nullptr;
  1227. }
  1228. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1229. if (key != nullptr) {
  1230. map_set(&m->debug_values, hash_pointer(key), value);
  1231. }
  1232. }
  1233. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1234. if (node == nullptr) {
  1235. return nullptr;
  1236. }
  1237. return lb_get_llvm_metadata(m, node->file);
  1238. }
  1239. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1240. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1241. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1242. Scope *s = p->scope_stack[i];
  1243. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1244. if (md) {
  1245. return md;
  1246. }
  1247. }
  1248. return p->debug_info;
  1249. }
  1250. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1251. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1252. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1253. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1254. }
  1255. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1256. GB_ASSERT(node != nullptr);
  1257. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1258. }
  1259. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1260. Type *original_type = type;
  1261. LLVMContextRef ctx = m->ctx;
  1262. i64 size = type_size_of(type); // Check size
  1263. GB_ASSERT(type != t_invalid);
  1264. unsigned const word_size = cast(unsigned)build_context.word_size;
  1265. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1266. GB_ASSERT(type->kind == Type_Proc);
  1267. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1268. unsigned parameter_count = 1;
  1269. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1270. Entity *e = type->Proc.params->Tuple.variables[i];
  1271. if (e->kind == Entity_Variable) {
  1272. parameter_count += 1;
  1273. }
  1274. }
  1275. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1276. unsigned param_index = 0;
  1277. if (type->Proc.result_count == 0) {
  1278. parameters[param_index++] = nullptr;
  1279. } else {
  1280. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1281. }
  1282. LLVMMetadataRef parent_scope = nullptr;
  1283. LLVMMetadataRef scope = nullptr;
  1284. LLVMMetadataRef file = nullptr;
  1285. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1286. Entity *e = type->Proc.params->Tuple.variables[i];
  1287. if (e->kind != Entity_Variable) {
  1288. continue;
  1289. }
  1290. parameters[param_index] = lb_debug_type(m, e->type);
  1291. param_index += 1;
  1292. }
  1293. LLVMDIFlags flags = LLVMDIFlagZero;
  1294. if (type->Proc.diverging) {
  1295. flags = LLVMDIFlagNoReturn;
  1296. }
  1297. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1298. }
  1299. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1300. unsigned field_line = 1;
  1301. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1302. AstPackage *pkg = m->info->runtime_package;
  1303. GB_ASSERT(pkg->files.count != 0);
  1304. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1305. LLVMMetadataRef scope = file;
  1306. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1307. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1308. field_flags, lb_debug_type(m, type)
  1309. );
  1310. }
  1311. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1312. AstPackage *pkg = m->info->runtime_package;
  1313. GB_ASSERT(pkg->files.count != 0);
  1314. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1315. LLVMMetadataRef scope = file;
  1316. return LLVMDIBuilderCreateStructType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, 1, size_in_bits, align_in_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1317. }
  1318. LLVMMetadataRef lb_debug_type_basic_type(lbModule *m, String const &name, u64 size_in_bits, LLVMDWARFTypeEncoding encoding, LLVMDIFlags flags = LLVMDIFlagZero) {
  1319. LLVMMetadataRef basic_type = LLVMDIBuilderCreateBasicType(m->debug_builder, cast(char const *)name.text, name.len, size_in_bits, encoding, flags);
  1320. #if 1
  1321. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, basic_type, cast(char const *)name.text, name.len, nullptr, 0, nullptr, cast(u32)size_in_bits);
  1322. return final_decl;
  1323. #else
  1324. return basic_type;
  1325. #endif
  1326. }
  1327. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1328. Type *original_type = type;
  1329. LLVMContextRef ctx = m->ctx;
  1330. i64 size = type_size_of(type); // Check size
  1331. GB_ASSERT(type != t_invalid);
  1332. unsigned const word_size = cast(unsigned)build_context.word_size;
  1333. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1334. switch (type->kind) {
  1335. case Type_Basic:
  1336. switch (type->Basic.kind) {
  1337. case Basic_llvm_bool: return lb_debug_type_basic_type(m, str_lit("llvm bool"), 1, LLVMDWARFTypeEncoding_Boolean);
  1338. case Basic_bool: return lb_debug_type_basic_type(m, str_lit("bool"), 8, LLVMDWARFTypeEncoding_Boolean);
  1339. case Basic_b8: return lb_debug_type_basic_type(m, str_lit("b8"), 8, LLVMDWARFTypeEncoding_Boolean);
  1340. case Basic_b16: return lb_debug_type_basic_type(m, str_lit("b16"), 16, LLVMDWARFTypeEncoding_Boolean);
  1341. case Basic_b32: return lb_debug_type_basic_type(m, str_lit("b32"), 32, LLVMDWARFTypeEncoding_Boolean);
  1342. case Basic_b64: return lb_debug_type_basic_type(m, str_lit("b64"), 64, LLVMDWARFTypeEncoding_Boolean);
  1343. case Basic_i8: return lb_debug_type_basic_type(m, str_lit("i8"), 8, LLVMDWARFTypeEncoding_Signed);
  1344. case Basic_u8: return lb_debug_type_basic_type(m, str_lit("u8"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1345. case Basic_i16: return lb_debug_type_basic_type(m, str_lit("i16"), 16, LLVMDWARFTypeEncoding_Signed);
  1346. case Basic_u16: return lb_debug_type_basic_type(m, str_lit("u16"), 16, LLVMDWARFTypeEncoding_Unsigned);
  1347. case Basic_i32: return lb_debug_type_basic_type(m, str_lit("i32"), 32, LLVMDWARFTypeEncoding_Signed);
  1348. case Basic_u32: return lb_debug_type_basic_type(m, str_lit("u32"), 32, LLVMDWARFTypeEncoding_Unsigned);
  1349. case Basic_i64: return lb_debug_type_basic_type(m, str_lit("i64"), 64, LLVMDWARFTypeEncoding_Signed);
  1350. case Basic_u64: return lb_debug_type_basic_type(m, str_lit("u64"), 64, LLVMDWARFTypeEncoding_Unsigned);
  1351. case Basic_i128: return lb_debug_type_basic_type(m, str_lit("i128"), 128, LLVMDWARFTypeEncoding_Signed);
  1352. case Basic_u128: return lb_debug_type_basic_type(m, str_lit("u128"), 128, LLVMDWARFTypeEncoding_Unsigned);
  1353. case Basic_rune: return lb_debug_type_basic_type(m, str_lit("rune"), 32, LLVMDWARFTypeEncoding_Utf);
  1354. // Basic_f16,
  1355. case Basic_f32: return lb_debug_type_basic_type(m, str_lit("f32"), 32, LLVMDWARFTypeEncoding_Float);
  1356. case Basic_f64: return lb_debug_type_basic_type(m, str_lit("f64"), 64, LLVMDWARFTypeEncoding_Float);
  1357. case Basic_int: return lb_debug_type_basic_type(m, str_lit("int"), word_bits, LLVMDWARFTypeEncoding_Signed);
  1358. case Basic_uint: return lb_debug_type_basic_type(m, str_lit("uint"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1359. case Basic_uintptr: return lb_debug_type_basic_type(m, str_lit("uintptr"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1360. case Basic_typeid:
  1361. return lb_debug_type_basic_type(m, str_lit("typeid"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1362. // Endian Specific Types
  1363. case Basic_i16le: return lb_debug_type_basic_type(m, str_lit("i16le"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1364. case Basic_u16le: return lb_debug_type_basic_type(m, str_lit("u16le"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1365. case Basic_i32le: return lb_debug_type_basic_type(m, str_lit("i32le"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1366. case Basic_u32le: return lb_debug_type_basic_type(m, str_lit("u32le"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1367. case Basic_i64le: return lb_debug_type_basic_type(m, str_lit("i64le"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1368. case Basic_u64le: return lb_debug_type_basic_type(m, str_lit("u64le"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1369. case Basic_i128le: return lb_debug_type_basic_type(m, str_lit("i128le"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1370. case Basic_u128le: return lb_debug_type_basic_type(m, str_lit("u128le"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1371. case Basic_f32le: return lb_debug_type_basic_type(m, str_lit("f32le"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1372. case Basic_f64le: return lb_debug_type_basic_type(m, str_lit("f64le"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1373. case Basic_i16be: return lb_debug_type_basic_type(m, str_lit("i16be"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1374. case Basic_u16be: return lb_debug_type_basic_type(m, str_lit("u16be"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1375. case Basic_i32be: return lb_debug_type_basic_type(m, str_lit("i32be"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1376. case Basic_u32be: return lb_debug_type_basic_type(m, str_lit("u32be"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1377. case Basic_i64be: return lb_debug_type_basic_type(m, str_lit("i64be"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1378. case Basic_u64be: return lb_debug_type_basic_type(m, str_lit("u64be"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1379. case Basic_i128be: return lb_debug_type_basic_type(m, str_lit("i128be"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1380. case Basic_u128be: return lb_debug_type_basic_type(m, str_lit("u128be"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1381. case Basic_f32be: return lb_debug_type_basic_type(m, str_lit("f32be"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1382. case Basic_f64be: return lb_debug_type_basic_type(m, str_lit("f64be"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1383. // Basic_complex32,
  1384. case Basic_complex64:
  1385. {
  1386. LLVMMetadataRef elements[2] = {};
  1387. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1388. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1389. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1390. }
  1391. case Basic_complex128:
  1392. {
  1393. LLVMMetadataRef elements[2] = {};
  1394. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1395. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1396. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1397. }
  1398. case Basic_quaternion128:
  1399. {
  1400. LLVMMetadataRef elements[4] = {};
  1401. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1402. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1403. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1404. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1405. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1406. }
  1407. case Basic_quaternion256:
  1408. {
  1409. LLVMMetadataRef elements[4] = {};
  1410. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1411. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1412. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1413. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1414. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1415. }
  1416. case Basic_rawptr:
  1417. {
  1418. LLVMMetadataRef void_type = lb_debug_type_basic_type(m, str_lit("void"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1419. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1420. }
  1421. case Basic_string:
  1422. {
  1423. LLVMMetadataRef elements[2] = {};
  1424. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1425. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1426. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1427. }
  1428. case Basic_cstring:
  1429. {
  1430. LLVMMetadataRef char_type = lb_debug_type_basic_type(m, str_lit("char"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1431. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1432. }
  1433. case Basic_any:
  1434. {
  1435. LLVMMetadataRef elements[2] = {};
  1436. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1437. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1438. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1439. }
  1440. // Untyped types
  1441. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1442. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1443. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1444. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1445. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1446. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1447. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1448. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1449. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1450. default: GB_PANIC("Basic Unhandled"); break;
  1451. }
  1452. break;
  1453. case Type_Named:
  1454. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1455. case Type_Pointer:
  1456. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1457. case Type_Array:
  1458. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1459. type->Array.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->Array.elem), nullptr, 0);
  1460. case Type_EnumeratedArray: {
  1461. LLVMMetadataRef array_type = LLVMDIBuilderCreateArrayType(m->debug_builder,
  1462. type->EnumeratedArray.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->EnumeratedArray.elem), nullptr, 0);
  1463. gbString name = type_to_string(type, temporary_allocator());
  1464. return LLVMDIBuilderCreateTypedef(m->debug_builder, array_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1465. }
  1466. case Type_Struct:
  1467. case Type_Union:
  1468. case Type_Slice:
  1469. case Type_DynamicArray:
  1470. case Type_Map:
  1471. case Type_BitSet:
  1472. {
  1473. unsigned tag = DW_TAG_structure_type;
  1474. if (is_type_raw_union(type) || is_type_union(type)) {
  1475. tag = DW_TAG_union_type;
  1476. }
  1477. u64 size_in_bits = cast(u64)(8*type_size_of(type));
  1478. u32 align_in_bits = cast(u32)(8*type_size_of(type));
  1479. LLVMDIFlags flags = LLVMDIFlagZero;
  1480. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1481. m->debug_builder, tag, "", 0, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1482. );
  1483. lbIncompleteDebugType idt = {};
  1484. idt.type = type;
  1485. idt.metadata = temp_forward_decl;
  1486. array_add(&m->debug_incomplete_types, idt);
  1487. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1488. return temp_forward_decl;
  1489. }
  1490. case Type_Enum:
  1491. {
  1492. LLVMMetadataRef scope = nullptr;
  1493. LLVMMetadataRef file = nullptr;
  1494. unsigned line = 0;
  1495. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1496. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1497. Type *bt = base_enum_type(type);
  1498. LLVMBool is_unsigned = is_type_unsigned(bt);
  1499. for (unsigned i = 0; i < element_count; i++) {
  1500. Entity *f = type->Enum.fields[i];
  1501. GB_ASSERT(f->kind == Entity_Constant);
  1502. String name = f->token.string;
  1503. i64 value = exact_value_to_i64(f->Constant.value);
  1504. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1505. }
  1506. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1507. return LLVMDIBuilderCreateEnumerationType(m->debug_builder, scope, "", 0, file, line, 8*type_size_of(type), 8*cast(unsigned)type_align_of(type), elements, element_count, class_type);
  1508. }
  1509. case Type_Tuple:
  1510. if (type->Tuple.variables.count == 1) {
  1511. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1512. } else {
  1513. type_set_offsets(type);
  1514. LLVMMetadataRef parent_scope = nullptr;
  1515. LLVMMetadataRef scope = nullptr;
  1516. LLVMMetadataRef file = nullptr;
  1517. unsigned line = 0;
  1518. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1519. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1520. LLVMDIFlags flags = LLVMDIFlagZero;
  1521. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1522. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1523. for (unsigned i = 0; i < element_count; i++) {
  1524. Entity *f = type->Tuple.variables[i];
  1525. GB_ASSERT(f->kind == Entity_Variable);
  1526. String name = f->token.string;
  1527. unsigned field_line = 0;
  1528. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1529. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1530. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1531. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1532. field_flags, lb_debug_type(m, f->type)
  1533. );
  1534. }
  1535. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1536. size_in_bits, align_in_bits, flags,
  1537. nullptr, elements, element_count, 0, nullptr,
  1538. "", 0
  1539. );
  1540. }
  1541. case Type_Proc:
  1542. {
  1543. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1544. LLVMMetadataRef pointer_type = LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1545. gbString name = type_to_string(type, temporary_allocator());
  1546. return LLVMDIBuilderCreateTypedef(m->debug_builder, pointer_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1547. }
  1548. break;
  1549. case Type_SimdVector:
  1550. if (type->SimdVector.is_x86_mmx) {
  1551. return LLVMDIBuilderCreateVectorType(m->debug_builder, 2, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, t_f64), nullptr, 0);
  1552. }
  1553. return LLVMDIBuilderCreateVectorType(m->debug_builder, cast(unsigned)type->SimdVector.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->SimdVector.elem), nullptr, 0);
  1554. case Type_RelativePointer: {
  1555. LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativePointer.base_integer);
  1556. gbString name = type_to_string(type, temporary_allocator());
  1557. return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1558. }
  1559. case Type_RelativeSlice:
  1560. {
  1561. unsigned element_count = 0;
  1562. LLVMMetadataRef elements[2] = {};
  1563. Type *base_integer = type->RelativeSlice.base_integer;
  1564. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1565. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1566. gbString name = type_to_string(type, temporary_allocator());
  1567. return LLVMDIBuilderCreateStructType(m->debug_builder, nullptr, name, gb_string_length(name), nullptr, 0, 2*word_bits, word_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1568. }
  1569. }
  1570. GB_PANIC("Invalid type %s", type_to_string(type));
  1571. return nullptr;
  1572. }
  1573. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1574. GB_ASSERT(type != nullptr);
  1575. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1576. if (found != nullptr) {
  1577. return found;
  1578. }
  1579. if (type->kind == Type_Named) {
  1580. LLVMMetadataRef file = nullptr;
  1581. unsigned line = 0;
  1582. LLVMMetadataRef scope = nullptr;
  1583. if (type->Named.type_name != nullptr) {
  1584. Entity *e = type->Named.type_name;
  1585. scope = lb_get_llvm_metadata(m, e->scope);
  1586. if (scope != nullptr) {
  1587. file = LLVMDIScopeGetFile(scope);
  1588. }
  1589. line = cast(unsigned)e->token.pos.line;
  1590. }
  1591. // TODO(bill): location data for Type_Named
  1592. u64 size_in_bits = 8*type_size_of(type);
  1593. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1594. String name = type->Named.name;
  1595. char const *name_text = cast(char const *)name.text;
  1596. size_t name_len = cast(size_t)name.len;
  1597. unsigned tag = DW_TAG_structure_type;
  1598. if (is_type_raw_union(type) || is_type_union(type)) {
  1599. tag = DW_TAG_union_type;
  1600. }
  1601. LLVMDIFlags flags = LLVMDIFlagZero;
  1602. Type *bt = base_type(type->Named.base);
  1603. lbIncompleteDebugType idt = {};
  1604. idt.type = type;
  1605. switch (bt->kind) {
  1606. case Type_Enum:
  1607. {
  1608. LLVMMetadataRef scope = nullptr;
  1609. LLVMMetadataRef file = nullptr;
  1610. unsigned line = 0;
  1611. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1612. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1613. Type *ct = base_enum_type(type);
  1614. LLVMBool is_unsigned = is_type_unsigned(ct);
  1615. for (unsigned i = 0; i < element_count; i++) {
  1616. Entity *f = bt->Enum.fields[i];
  1617. GB_ASSERT(f->kind == Entity_Constant);
  1618. String name = f->token.string;
  1619. i64 value = exact_value_to_i64(f->Constant.value);
  1620. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1621. }
  1622. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1623. return LLVMDIBuilderCreateEnumerationType(m->debug_builder, scope, name_text, name_len, file, line, 8*type_size_of(type), 8*cast(unsigned)type_align_of(type), elements, element_count, class_type);
  1624. }
  1625. case Type_Basic:
  1626. case Type_Pointer:
  1627. case Type_Array:
  1628. case Type_EnumeratedArray:
  1629. case Type_Tuple:
  1630. case Type_Proc:
  1631. case Type_SimdVector:
  1632. case Type_RelativePointer:
  1633. case Type_RelativeSlice:
  1634. {
  1635. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1636. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1637. lb_set_llvm_metadata(m, type, final_decl);
  1638. return final_decl;
  1639. }
  1640. case Type_Slice:
  1641. case Type_DynamicArray:
  1642. case Type_Map:
  1643. case Type_Struct:
  1644. case Type_Union:
  1645. case Type_BitSet:
  1646. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1647. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1648. );
  1649. idt.metadata = temp_forward_decl;
  1650. array_add(&m->debug_incomplete_types, idt);
  1651. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1652. return temp_forward_decl;
  1653. }
  1654. }
  1655. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1656. lb_set_llvm_metadata(m, type, dt);
  1657. return dt;
  1658. }
  1659. void lb_debug_complete_types(lbModule *m) {
  1660. unsigned const word_size = cast(unsigned)build_context.word_size;
  1661. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1662. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1663. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1664. GB_ASSERT(idt.type != nullptr);
  1665. GB_ASSERT(idt.metadata != nullptr);
  1666. Type *t = idt.type;
  1667. Type *bt = base_type(t);
  1668. LLVMMetadataRef parent_scope = nullptr;
  1669. LLVMMetadataRef file = nullptr;
  1670. unsigned line_number = 0;
  1671. u64 size_in_bits = 8*type_size_of(t);
  1672. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1673. LLVMDIFlags flags = LLVMDIFlagZero;
  1674. LLVMMetadataRef derived_from = nullptr;
  1675. LLVMMetadataRef *elements = nullptr;
  1676. unsigned element_count = 0;
  1677. unsigned runtime_lang = 0; // Objective-C runtime version
  1678. char const *unique_id = "";
  1679. LLVMMetadataRef vtable_holder = nullptr;
  1680. size_t unique_id_len = 0;
  1681. LLVMMetadataRef record_scope = nullptr;
  1682. switch (bt->kind) {
  1683. case Type_Slice:
  1684. case Type_DynamicArray:
  1685. case Type_Map:
  1686. case Type_Struct:
  1687. case Type_Union:
  1688. case Type_BitSet: {
  1689. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1690. String name = str_lit("<anonymous-struct>");
  1691. if (t->kind == Type_Named) {
  1692. name = t->Named.name;
  1693. if (t->Named.type_name && t->Named.type_name->pkg && t->Named.type_name->pkg->name.len != 0) {
  1694. name = concatenate3_strings(temporary_allocator(), t->Named.type_name->pkg->name, str_lit("."), t->Named.name);
  1695. }
  1696. LLVMMetadataRef file = nullptr;
  1697. unsigned line = 0;
  1698. LLVMMetadataRef file_scope = nullptr;
  1699. if (t->Named.type_name != nullptr) {
  1700. Entity *e = t->Named.type_name;
  1701. file_scope = lb_get_llvm_metadata(m, e->scope);
  1702. if (file_scope != nullptr) {
  1703. file = LLVMDIScopeGetFile(file_scope);
  1704. }
  1705. line = cast(unsigned)e->token.pos.line;
  1706. }
  1707. // TODO(bill): location data for Type_Named
  1708. } else {
  1709. name = make_string_c(type_to_string(t, temporary_allocator()));
  1710. }
  1711. switch (bt->kind) {
  1712. case Type_Slice:
  1713. element_count = 2;
  1714. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1715. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->Slice.elem), 0*word_bits);
  1716. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1717. break;
  1718. case Type_DynamicArray:
  1719. element_count = 4;
  1720. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1721. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->DynamicArray.elem), 0*word_bits);
  1722. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1723. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1724. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1725. break;
  1726. case Type_Map:
  1727. bt = bt->Map.internal_type;
  1728. /*fallthrough*/
  1729. case Type_Struct:
  1730. if (file == nullptr) {
  1731. if (bt->Struct.node) {
  1732. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1733. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1734. }
  1735. }
  1736. type_set_offsets(bt);
  1737. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  1738. element_count = cast(unsigned)bt->Struct.fields.count;
  1739. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1740. for_array(j, bt->Struct.fields) {
  1741. Entity *f = bt->Struct.fields[j];
  1742. String fname = f->token.string;
  1743. unsigned field_line = 0;
  1744. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1745. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  1746. elements[j] = LLVMDIBuilderCreateMemberType(
  1747. m->debug_builder, record_scope,
  1748. cast(char const *)fname.text, cast(size_t)fname.len,
  1749. file, field_line,
  1750. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  1751. offset_in_bits,
  1752. field_flags, lb_debug_type(m, f->type)
  1753. );
  1754. }
  1755. break;
  1756. case Type_Union:
  1757. {
  1758. if (file == nullptr) {
  1759. GB_ASSERT(bt->Union.node != nullptr);
  1760. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  1761. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  1762. }
  1763. isize index_offset = 1;
  1764. if (is_type_union_maybe_pointer(bt)) {
  1765. index_offset = 0;
  1766. }
  1767. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  1768. element_count = cast(unsigned)bt->Union.variants.count;
  1769. if (index_offset > 0) {
  1770. element_count += 1;
  1771. }
  1772. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1773. if (index_offset > 0) {
  1774. Type *tag_type = union_tag_type(bt);
  1775. unsigned field_line = 0;
  1776. u64 offset_in_bits = 8*cast(u64)bt->Union.variant_block_size;
  1777. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1778. elements[0] = LLVMDIBuilderCreateMemberType(
  1779. m->debug_builder, record_scope,
  1780. "tag", 3,
  1781. file, field_line,
  1782. 8*cast(u64)type_size_of(tag_type), 8*cast(u32)type_align_of(tag_type),
  1783. offset_in_bits,
  1784. field_flags, lb_debug_type(m, tag_type)
  1785. );
  1786. }
  1787. for_array(j, bt->Union.variants) {
  1788. Type *variant = bt->Union.variants[j];
  1789. unsigned field_index = cast(unsigned)(index_offset+j);
  1790. char name[16] = {};
  1791. gb_snprintf(name, gb_size_of(name), "v%u", field_index);
  1792. isize name_len = gb_strlen(name);
  1793. unsigned field_line = 0;
  1794. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1795. u64 offset_in_bits = 0;
  1796. elements[field_index] = LLVMDIBuilderCreateMemberType(
  1797. m->debug_builder, record_scope,
  1798. name, name_len,
  1799. file, field_line,
  1800. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  1801. offset_in_bits,
  1802. field_flags, lb_debug_type(m, variant)
  1803. );
  1804. }
  1805. }
  1806. break;
  1807. case Type_BitSet:
  1808. {
  1809. if (file == nullptr) {
  1810. GB_ASSERT(bt->BitSet.node != nullptr);
  1811. file = lb_get_llvm_metadata(m, bt->BitSet.node->file);
  1812. line_number = cast(unsigned)ast_token(bt->BitSet.node).pos.line;
  1813. }
  1814. LLVMMetadataRef bit_set_field_type = lb_debug_type(m, t_bool);
  1815. LLVMMetadataRef scope = file;
  1816. Type *elem = base_type(bt->BitSet.elem);
  1817. if (elem->kind == Type_Enum) {
  1818. element_count = cast(unsigned)elem->Enum.fields.count;
  1819. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1820. for_array(i, elem->Enum.fields) {
  1821. Entity *f = elem->Enum.fields[i];
  1822. GB_ASSERT(f->kind == Entity_Constant);
  1823. i64 val = exact_value_to_i64(f->Constant.value);
  1824. String name = f->token.string;
  1825. u64 offset_in_bits = cast(u64)(val - bt->BitSet.lower);
  1826. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1827. m->debug_builder,
  1828. scope,
  1829. cast(char const *)name.text, name.len,
  1830. file, line_number,
  1831. 1,
  1832. offset_in_bits,
  1833. 0,
  1834. LLVMDIFlagZero,
  1835. bit_set_field_type
  1836. );
  1837. }
  1838. } else {
  1839. char name[32] = {};
  1840. GB_ASSERT(is_type_integer(elem));
  1841. i64 count = bt->BitSet.upper - bt->BitSet.lower + 1;
  1842. GB_ASSERT(0 <= count);
  1843. element_count = cast(unsigned)count;
  1844. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1845. for (unsigned i = 0; i < element_count; i++) {
  1846. u64 offset_in_bits = i;
  1847. i64 val = bt->BitSet.lower + cast(i64)i;
  1848. gb_snprintf(name, gb_count_of(name), "%lld", val);
  1849. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1850. m->debug_builder,
  1851. scope,
  1852. name, gb_strlen(name),
  1853. file, line_number,
  1854. 1,
  1855. offset_in_bits,
  1856. 0,
  1857. LLVMDIFlagZero,
  1858. bit_set_field_type
  1859. );
  1860. }
  1861. }
  1862. }
  1863. }
  1864. LLVMMetadataRef final_metadata = nullptr;
  1865. if (is_union) {
  1866. final_metadata = LLVMDIBuilderCreateUnionType(
  1867. m->debug_builder,
  1868. parent_scope,
  1869. cast(char const *)name.text, cast(size_t)name.len,
  1870. file, line_number,
  1871. size_in_bits, align_in_bits,
  1872. flags,
  1873. elements, element_count,
  1874. runtime_lang,
  1875. unique_id, unique_id_len
  1876. );
  1877. } else {
  1878. final_metadata = LLVMDIBuilderCreateStructType(
  1879. m->debug_builder,
  1880. parent_scope,
  1881. cast(char const *)name.text, cast(size_t)name.len,
  1882. file, line_number,
  1883. size_in_bits, align_in_bits,
  1884. flags,
  1885. derived_from,
  1886. elements, element_count,
  1887. runtime_lang,
  1888. vtable_holder,
  1889. unique_id, unique_id_len
  1890. );
  1891. }
  1892. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  1893. lb_set_llvm_metadata(m, idt.type, final_metadata);
  1894. } break;
  1895. default:
  1896. GB_PANIC("invalid incomplete debug type");
  1897. break;
  1898. }
  1899. }
  1900. array_clear(&m->debug_incomplete_types);
  1901. }
  1902. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1903. if (e != nullptr) {
  1904. map_set(&m->values, hash_entity(e), val);
  1905. }
  1906. }
  1907. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1908. if (name.len > 0) {
  1909. string_map_set(&m->members, name, val);
  1910. }
  1911. }
  1912. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1913. string_map_set(&m->members, key, val);
  1914. }
  1915. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1916. if (p->entity != nullptr) {
  1917. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1918. }
  1919. string_map_set(&m->procedures, p->name, p);
  1920. }
  1921. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  1922. LLVMTypeRef src = LLVMTypeOf(val);
  1923. if (src == dst) {
  1924. return val;
  1925. }
  1926. if (LLVMIsNull(val)) {
  1927. return LLVMConstNull(dst);
  1928. }
  1929. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  1930. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  1931. switch (kind) {
  1932. case LLVMPointerTypeKind:
  1933. return LLVMConstPointerCast(val, dst);
  1934. case LLVMStructTypeKind:
  1935. return LLVMConstBitCast(val, dst);
  1936. default:
  1937. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  1938. }
  1939. return val;
  1940. }
  1941. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  1942. unsigned value_count = cast(unsigned)value_count_;
  1943. unsigned elem_count = LLVMCountStructElementTypes(t);
  1944. GB_ASSERT(value_count == elem_count);
  1945. for (unsigned i = 0; i < elem_count; i++) {
  1946. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  1947. values[i] = llvm_const_cast(values[i], elem_type);
  1948. }
  1949. return LLVMConstNamedStruct(t, values, value_count);
  1950. }
  1951. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  1952. unsigned value_count = cast(unsigned)value_count_;
  1953. for (unsigned i = 0; i < value_count; i++) {
  1954. values[i] = llvm_const_cast(values[i], elem_type);
  1955. }
  1956. return LLVMConstArray(elem_type, values, value_count);
  1957. }
  1958. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  1959. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  1960. LLVMValueRef values[2] = {
  1961. str_elem.value,
  1962. str_len.value,
  1963. };
  1964. lbValue res = {};
  1965. res.type = t_string;
  1966. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  1967. return res;
  1968. } else {
  1969. lbAddr res = lb_add_local_generated(p, t_string, false);
  1970. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  1971. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  1972. return lb_addr_load(p, res);
  1973. }
  1974. }
  1975. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1976. String s = make_string_c(name);
  1977. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  1978. // and the current LLVM C API does not expose this functionality yet.
  1979. // It is better to ignore the attributes for the time being
  1980. if (s == "byval") {
  1981. return nullptr;
  1982. } else if (s == "byref") {
  1983. return nullptr;
  1984. } else if (s == "preallocated") {
  1985. return nullptr;
  1986. } else if (s == "sret") {
  1987. return nullptr;
  1988. }
  1989. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1990. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1991. return LLVMCreateEnumAttribute(ctx, kind, value);
  1992. }
  1993. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1994. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1995. GB_ASSERT(attr != nullptr);
  1996. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1997. }
  1998. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1999. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  2000. }
  2001. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2002. if (p->abi_function_type != nullptr) {
  2003. return;
  2004. }
  2005. auto hash = hash_type(p->type);
  2006. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  2007. if (ft_found == nullptr) {
  2008. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2009. ft_found = map_get(&m->function_type_map, hash);
  2010. }
  2011. GB_ASSERT(ft_found != nullptr);
  2012. p->abi_function_type = *ft_found;
  2013. GB_ASSERT(p->abi_function_type != nullptr);
  2014. }
  2015. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  2016. GB_ASSERT(entity != nullptr);
  2017. String link_name = lb_get_entity_name(m, entity);
  2018. {
  2019. StringHashKey key = string_hash_string(link_name);
  2020. lbValue *found = string_map_get(&m->members, key);
  2021. if (found) {
  2022. lb_add_entity(m, entity, *found);
  2023. lbProcedure **p_found = string_map_get(&m->procedures, key);
  2024. GB_ASSERT(p_found != nullptr);
  2025. return *p_found;
  2026. }
  2027. }
  2028. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2029. p->module = m;
  2030. entity->code_gen_module = m;
  2031. entity->code_gen_procedure = p;
  2032. p->entity = entity;
  2033. p->name = link_name;
  2034. DeclInfo *decl = entity->decl_info;
  2035. ast_node(pl, ProcLit, decl->proc_lit);
  2036. Type *pt = base_type(entity->type);
  2037. GB_ASSERT(pt->kind == Type_Proc);
  2038. set_procedure_abi_types(entity->type);
  2039. p->type = entity->type;
  2040. p->type_expr = decl->type_expr;
  2041. p->body = pl->body;
  2042. p->tags = pt->Proc.tags;
  2043. p->inlining = ProcInlining_none;
  2044. p->is_foreign = entity->Procedure.is_foreign;
  2045. p->is_export = entity->Procedure.is_export;
  2046. p->is_entry_point = false;
  2047. gbAllocator a = heap_allocator();
  2048. p->children.allocator = a;
  2049. p->params.allocator = a;
  2050. p->defer_stmts.allocator = a;
  2051. p->blocks.allocator = a;
  2052. p->branch_blocks.allocator = a;
  2053. p->context_stack.allocator = a;
  2054. p->scope_stack.allocator = a;
  2055. if (p->is_foreign) {
  2056. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2057. }
  2058. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2059. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2060. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2061. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2062. lb_ensure_abi_function_type(m, p);
  2063. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2064. if (false) {
  2065. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2066. // TODO(bill): Clean up this logic
  2067. if (build_context.metrics.os != TargetOs_js) {
  2068. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2069. }
  2070. LLVMSetFunctionCallConv(p->value, cc_kind);
  2071. }
  2072. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2073. // // TODO(bill): Clean up this logic
  2074. // if (build_context.metrics.os != TargetOs_js) {
  2075. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2076. // }
  2077. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2078. lbValue proc_value = {p->value, p->type};
  2079. lb_add_entity(m, entity, proc_value);
  2080. lb_add_member(m, p->name, proc_value);
  2081. lb_add_procedure_value(m, p);
  2082. if (p->is_export) {
  2083. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2084. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2085. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2086. if (build_context.metrics.os == TargetOs_js) {
  2087. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2088. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2089. }
  2090. }
  2091. if (p->is_foreign) {
  2092. if (build_context.metrics.os == TargetOs_js) {
  2093. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2094. char const *module_name = "env";
  2095. if (entity->Procedure.foreign_library != nullptr) {
  2096. Entity *foreign_library = entity->Procedure.foreign_library;
  2097. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2098. if (foreign_library->LibraryName.paths.count > 0) {
  2099. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2100. }
  2101. }
  2102. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2103. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2104. }
  2105. }
  2106. // NOTE(bill): offset==0 is the return value
  2107. isize offset = 1;
  2108. if (pt->Proc.return_by_pointer) {
  2109. offset = 2;
  2110. }
  2111. isize parameter_index = 0;
  2112. if (pt->Proc.param_count) {
  2113. TypeTuple *params = &pt->Proc.params->Tuple;
  2114. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2115. Entity *e = params->variables[i];
  2116. Type *original_type = e->type;
  2117. Type *abi_type = pt->Proc.abi_compat_params[i];
  2118. if (e->kind != Entity_Variable) continue;
  2119. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2120. continue;
  2121. }
  2122. if (is_type_tuple(abi_type)) {
  2123. for_array(j, abi_type->Tuple.variables) {
  2124. Type *tft = abi_type->Tuple.variables[j]->type;
  2125. if (e->flags&EntityFlag_NoAlias) {
  2126. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  2127. }
  2128. }
  2129. parameter_index += abi_type->Tuple.variables.count;
  2130. } else {
  2131. if (e->flags&EntityFlag_NoAlias) {
  2132. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2133. }
  2134. parameter_index += 1;
  2135. }
  2136. }
  2137. }
  2138. if (m->debug_builder) { // Debug Information
  2139. Type *bt = base_type(p->type);
  2140. unsigned line = cast(unsigned)entity->token.pos.line;
  2141. LLVMMetadataRef scope = nullptr;
  2142. LLVMMetadataRef file = nullptr;
  2143. LLVMMetadataRef type = nullptr;
  2144. scope = p->module->debug_compile_unit;
  2145. type = lb_debug_type_internal_proc(m, bt);
  2146. if (entity->file != nullptr) {
  2147. file = lb_get_llvm_metadata(m, entity->file);
  2148. scope = file;
  2149. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2150. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2151. scope = file;
  2152. } else if (entity->scope != nullptr) {
  2153. file = lb_get_llvm_metadata(m, entity->scope->file);
  2154. scope = file;
  2155. }
  2156. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2157. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2158. LLVMBool is_local_to_unit = false;
  2159. LLVMBool is_definition = p->body != nullptr;
  2160. unsigned scope_line = line;
  2161. u32 flags = LLVMDIFlagStaticMember;
  2162. LLVMBool is_optimized = false;
  2163. if (bt->Proc.diverging) {
  2164. flags |= LLVMDIFlagNoReturn;
  2165. }
  2166. if (p->body == nullptr) {
  2167. flags |= LLVMDIFlagPrototyped;
  2168. is_optimized = false;
  2169. }
  2170. if (p->body != nullptr) {
  2171. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2172. cast(char const *)entity->token.string.text, entity->token.string.len,
  2173. cast(char const *)p->name.text, p->name.len,
  2174. file, line, type,
  2175. is_local_to_unit, is_definition,
  2176. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2177. );
  2178. GB_ASSERT(p->debug_info != nullptr);
  2179. LLVMSetSubprogram(p->value, p->debug_info);
  2180. lb_set_llvm_metadata(m, p, p->debug_info);
  2181. }
  2182. }
  2183. return p;
  2184. }
  2185. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2186. {
  2187. lbValue *found = string_map_get(&m->members, link_name);
  2188. GB_ASSERT(found == nullptr);
  2189. }
  2190. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2191. p->module = m;
  2192. p->name = link_name;
  2193. p->type = type;
  2194. p->type_expr = nullptr;
  2195. p->body = nullptr;
  2196. p->tags = 0;
  2197. p->inlining = ProcInlining_none;
  2198. p->is_foreign = false;
  2199. p->is_export = false;
  2200. p->is_entry_point = false;
  2201. gbAllocator a = permanent_allocator();
  2202. p->children.allocator = a;
  2203. p->params.allocator = a;
  2204. p->defer_stmts.allocator = a;
  2205. p->blocks.allocator = a;
  2206. p->branch_blocks.allocator = a;
  2207. p->context_stack.allocator = a;
  2208. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2209. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2210. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2211. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2212. Type *pt = p->type;
  2213. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2214. // TODO(bill): Clean up this logic
  2215. if (build_context.metrics.os != TargetOs_js) {
  2216. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2217. }
  2218. LLVMSetFunctionCallConv(p->value, cc_kind);
  2219. lbValue proc_value = {p->value, p->type};
  2220. lb_add_member(m, p->name, proc_value);
  2221. lb_add_procedure_value(m, p);
  2222. // NOTE(bill): offset==0 is the return value
  2223. isize offset = 1;
  2224. if (pt->Proc.return_by_pointer) {
  2225. lb_add_proc_attribute_at_index(p, 1, "sret");
  2226. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2227. offset = 2;
  2228. }
  2229. isize parameter_index = 0;
  2230. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2231. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2232. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2233. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2234. }
  2235. return p;
  2236. }
  2237. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2238. lbParamPasskind kind = lbParamPass_Value;
  2239. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2240. if (is_type_pointer(abi_type)) {
  2241. GB_ASSERT(e->kind == Entity_Variable);
  2242. Type *av = core_type(type_deref(abi_type));
  2243. if (are_types_identical(av, core_type(e->type))) {
  2244. kind = lbParamPass_Pointer;
  2245. if (e->flags&EntityFlag_Value) {
  2246. kind = lbParamPass_ConstRef;
  2247. }
  2248. } else {
  2249. kind = lbParamPass_BitCast;
  2250. }
  2251. } else if (is_type_integer(abi_type)) {
  2252. kind = lbParamPass_Integer;
  2253. } else if (abi_type == t_llvm_bool) {
  2254. kind = lbParamPass_Value;
  2255. } else if (is_type_boolean(abi_type)) {
  2256. kind = lbParamPass_Integer;
  2257. } else if (is_type_simd_vector(abi_type)) {
  2258. kind = lbParamPass_BitCast;
  2259. } else if (is_type_float(abi_type)) {
  2260. kind = lbParamPass_BitCast;
  2261. } else if (is_type_tuple(abi_type)) {
  2262. kind = lbParamPass_Tuple;
  2263. } else if (is_type_proc(abi_type)) {
  2264. kind = lbParamPass_Value;
  2265. } else {
  2266. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2267. }
  2268. }
  2269. if (kind_) *kind_ = kind;
  2270. lbValue res = {};
  2271. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2272. res.type = abi_type;
  2273. return res;
  2274. }
  2275. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  2276. lbParamPasskind kind = lbParamPass_Value;
  2277. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  2278. array_add(&p->params, v);
  2279. lbValue res = {};
  2280. switch (kind) {
  2281. case lbParamPass_Value: {
  2282. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2283. lbValue x = v;
  2284. if (abi_type == t_llvm_bool) {
  2285. x = lb_emit_conv(p, x, t_bool);
  2286. }
  2287. lb_addr_store(p, l, x);
  2288. return x;
  2289. }
  2290. case lbParamPass_Pointer:
  2291. lb_add_entity(p->module, e, v);
  2292. return lb_emit_load(p, v);
  2293. case lbParamPass_Integer: {
  2294. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2295. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  2296. lb_emit_store(p, iptr, v);
  2297. return lb_addr_load(p, l);
  2298. }
  2299. case lbParamPass_ConstRef:
  2300. lb_add_entity(p->module, e, v);
  2301. return lb_emit_load(p, v);
  2302. case lbParamPass_BitCast: {
  2303. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2304. lbValue x = lb_emit_transmute(p, v, e->type);
  2305. lb_addr_store(p, l, x);
  2306. return x;
  2307. }
  2308. case lbParamPass_Tuple: {
  2309. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2310. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2311. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2312. if (abi_type->Tuple.variables.count > 0) {
  2313. array_pop(&p->params);
  2314. }
  2315. for_array(i, abi_type->Tuple.variables) {
  2316. Type *t = abi_type->Tuple.variables[i]->type;
  2317. GB_ASSERT(!is_type_tuple(t));
  2318. lbParamPasskind elem_kind = lbParamPass_Value;
  2319. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2320. array_add(&p->params, elem);
  2321. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2322. lb_emit_store(p, dst, elem);
  2323. }
  2324. return lb_addr_load(p, l);
  2325. }
  2326. }
  2327. GB_PANIC("Unreachable");
  2328. return {};
  2329. }
  2330. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2331. GB_ASSERT(b != nullptr);
  2332. if (!b->appended) {
  2333. b->appended = true;
  2334. LLVMAppendExistingBasicBlock(p->value, b->block);
  2335. }
  2336. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2337. p->curr_block = b;
  2338. }
  2339. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2340. LLVMContextRef ctx = p->module->ctx;
  2341. LLVMTypeRef src_type = LLVMTypeOf(val);
  2342. if (src_type == dst_type) {
  2343. return val;
  2344. }
  2345. i64 src_size = lb_sizeof(src_type);
  2346. i64 dst_size = lb_sizeof(dst_type);
  2347. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2348. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2349. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2350. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2351. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2352. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2353. }
  2354. if (src_size != dst_size && (lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2355. // Okay
  2356. } else {
  2357. GB_ASSERT_MSG(src_size == dst_size, "%s == %s", LLVMPrintTypeToString(src_type), LLVMPrintTypeToString(dst_type));
  2358. }
  2359. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2360. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2361. if (src_kind == dst_kind) {
  2362. if (src_kind == LLVMPointerTypeKind) {
  2363. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2364. } else if (src_kind == LLVMArrayTypeKind) {
  2365. // ignore
  2366. } else if (src_kind != LLVMStructTypeKind) {
  2367. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2368. }
  2369. } else {
  2370. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2371. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2372. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2373. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2374. }
  2375. }
  2376. if (LLVMIsALoadInst(val)) {
  2377. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2378. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2379. return LLVMBuildLoad(p->builder, val_ptr, "");
  2380. } else {
  2381. GB_ASSERT(p->decl_block != p->curr_block);
  2382. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2383. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2384. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2385. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2386. max_align = gb_max(max_align, 4);
  2387. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2388. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2389. LLVMBuildStore(p->builder, val, nptr);
  2390. return LLVMBuildLoad(p->builder, ptr, "");
  2391. }
  2392. }
  2393. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2394. if (p->debug_info == nullptr) {
  2395. return;
  2396. }
  2397. if (type == nullptr) {
  2398. return;
  2399. }
  2400. if (type == t_invalid) {
  2401. return;
  2402. }
  2403. if (p->body == nullptr) {
  2404. return;
  2405. }
  2406. lbModule *m = p->module;
  2407. String const &name = token.string;
  2408. if (name == "" || name == "_") {
  2409. return;
  2410. }
  2411. if (lb_get_llvm_metadata(m, ptr) != nullptr) {
  2412. // Already been set
  2413. return;
  2414. }
  2415. AstFile *file = p->body->file;
  2416. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2417. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2418. GB_ASSERT(llvm_scope != nullptr);
  2419. if (llvm_file == nullptr) {
  2420. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2421. }
  2422. if (llvm_file == nullptr) {
  2423. return;
  2424. }
  2425. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2426. LLVMDIFlags flags = LLVMDIFlagZero;
  2427. LLVMBool always_preserve = build_context.optimization_level == 0;
  2428. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2429. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2430. m->debug_builder, llvm_scope,
  2431. cast(char const *)name.text, cast(size_t)name.len,
  2432. llvm_file, token.pos.line,
  2433. debug_type,
  2434. always_preserve, flags, alignment_in_bits
  2435. );
  2436. LLVMValueRef storage = ptr;
  2437. LLVMValueRef instr = ptr;
  2438. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2439. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2440. lb_set_llvm_metadata(m, ptr, llvm_expr);
  2441. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2442. }
  2443. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2444. if (!p->debug_info || !p->body) {
  2445. return;
  2446. }
  2447. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2448. if (!loc) {
  2449. return;
  2450. }
  2451. TokenPos pos = {};
  2452. pos.file_id = p->body->file ? p->body->file->id : 0;
  2453. pos.line = LLVMDILocationGetLine(loc);
  2454. pos.column = LLVMDILocationGetColumn(loc);
  2455. Token token = {};
  2456. token.kind = Token_context;
  2457. token.string = str_lit("context");
  2458. token.pos = pos;
  2459. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2460. }
  2461. void lb_begin_procedure_body(lbProcedure *p) {
  2462. DeclInfo *decl = decl_info_of_entity(p->entity);
  2463. if (decl != nullptr) {
  2464. for_array(i, decl->labels) {
  2465. BlockLabel bl = decl->labels[i];
  2466. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2467. array_add(&p->branch_blocks, bb);
  2468. }
  2469. }
  2470. if (p->tags != 0) {
  2471. u64 in = p->tags;
  2472. u64 out = p->module->state_flags;
  2473. if (in & ProcTag_bounds_check) {
  2474. out |= StateFlag_bounds_check;
  2475. out &= ~StateFlag_no_bounds_check;
  2476. } else if (in & ProcTag_no_bounds_check) {
  2477. out |= StateFlag_no_bounds_check;
  2478. out &= ~StateFlag_bounds_check;
  2479. }
  2480. p->module->state_flags = out;
  2481. }
  2482. p->builder = LLVMCreateBuilder();
  2483. p->decl_block = lb_create_block(p, "decls", true);
  2484. p->entry_block = lb_create_block(p, "entry", true);
  2485. lb_start_block(p, p->entry_block);
  2486. GB_ASSERT(p->type != nullptr);
  2487. lb_ensure_abi_function_type(p->module, p);
  2488. {
  2489. lbFunctionType *ft = p->abi_function_type;
  2490. unsigned param_offset = 0;
  2491. lbValue return_ptr_value = {};
  2492. if (ft->ret.kind == lbArg_Indirect) {
  2493. // NOTE(bill): this must be parameter 0
  2494. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2495. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2496. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2497. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2498. return_ptr_value.type = ptr_type;
  2499. p->return_ptr = lb_addr(return_ptr_value);
  2500. lb_add_entity(p->module, e, return_ptr_value);
  2501. param_offset += 1;
  2502. }
  2503. if (p->type->Proc.params != nullptr) {
  2504. TypeTuple *params = &p->type->Proc.params->Tuple;
  2505. unsigned param_index = 0;
  2506. for_array(i, params->variables) {
  2507. Entity *e = params->variables[i];
  2508. if (e->kind != Entity_Variable) {
  2509. continue;
  2510. }
  2511. lbArgType *arg_type = &ft->args[param_index];
  2512. if (arg_type->kind == lbArg_Ignore) {
  2513. continue;
  2514. } else if (arg_type->kind == lbArg_Direct) {
  2515. lbParamPasskind kind = lbParamPass_Value;
  2516. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2517. if (param_type != arg_type->type) {
  2518. kind = lbParamPass_BitCast;
  2519. }
  2520. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2521. value = OdinLLVMBuildTransmute(p, value, param_type);
  2522. lbValue param = {};
  2523. param.value = value;
  2524. param.type = e->type;
  2525. array_add(&p->params, param);
  2526. if (e->token.string.len != 0) {
  2527. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2528. lb_addr_store(p, l, param);
  2529. }
  2530. param_index += 1;
  2531. } else if (arg_type->kind == lbArg_Indirect) {
  2532. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2533. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2534. lbValue param = {};
  2535. param.value = value;
  2536. param.type = e->type;
  2537. array_add(&p->params, param);
  2538. lbValue ptr = {};
  2539. ptr.value = value_ptr;
  2540. ptr.type = alloc_type_pointer(e->type);
  2541. lb_add_entity(p->module, e, ptr);
  2542. param_index += 1;
  2543. }
  2544. }
  2545. }
  2546. if (p->type->Proc.has_named_results) {
  2547. GB_ASSERT(p->type->Proc.result_count > 0);
  2548. TypeTuple *results = &p->type->Proc.results->Tuple;
  2549. for_array(i, results->variables) {
  2550. Entity *e = results->variables[i];
  2551. GB_ASSERT(e->kind == Entity_Variable);
  2552. if (e->token.string != "") {
  2553. GB_ASSERT(!is_blank_ident(e->token));
  2554. lbAddr res = {};
  2555. if (return_ptr_value.value) {
  2556. lbValue ptr = return_ptr_value;
  2557. if (results->variables.count != 1) {
  2558. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2559. }
  2560. res = lb_addr(ptr);
  2561. lb_add_entity(p->module, e, ptr);
  2562. } else {
  2563. res = lb_add_local(p, e->type, e);
  2564. }
  2565. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2566. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2567. lb_addr_store(p, res, c);
  2568. }
  2569. }
  2570. }
  2571. }
  2572. }
  2573. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2574. lb_push_context_onto_stack_from_implicit_parameter(p);
  2575. }
  2576. lb_start_block(p, p->entry_block);
  2577. if (p->debug_info != nullptr) {
  2578. TokenPos pos = {};
  2579. if (p->body != nullptr) {
  2580. pos = ast_token(p->body).pos;
  2581. } else if (p->type_expr != nullptr) {
  2582. pos = ast_token(p->type_expr).pos;
  2583. } else if (p->entity != nullptr) {
  2584. pos = p->entity->token.pos;
  2585. }
  2586. if (pos.file_id != 0) {
  2587. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2588. }
  2589. if (p->context_stack.count != 0) {
  2590. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2591. }
  2592. }
  2593. }
  2594. void lb_end_procedure_body(lbProcedure *p) {
  2595. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2596. LLVMBuildBr(p->builder, p->entry_block->block);
  2597. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2598. // Make sure there is a "ret void" at the end of a procedure with no return type
  2599. if (p->type->Proc.result_count == 0) {
  2600. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2601. if (!lb_is_instr_terminating(instr)) {
  2602. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2603. LLVMBuildRetVoid(p->builder);
  2604. }
  2605. }
  2606. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2607. LLVMBasicBlockRef block = nullptr;
  2608. // Make sure every block terminates, and if not, make it unreachable
  2609. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2610. LLVMValueRef instr = LLVMGetLastInstruction(block);
  2611. if (instr == nullptr) {
  2612. LLVMPositionBuilderAtEnd(p->builder, block);
  2613. LLVMBuildUnreachable(p->builder);
  2614. }
  2615. }
  2616. p->curr_block = nullptr;
  2617. p->module->state_flags = 0;
  2618. }
  2619. void lb_end_procedure(lbProcedure *p) {
  2620. LLVMDisposeBuilder(p->builder);
  2621. }
  2622. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2623. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2624. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2625. array_add(&from->succs, to);
  2626. array_add(&to->preds, from);
  2627. }
  2628. }
  2629. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2630. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2631. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2632. b->appended = false;
  2633. if (append) {
  2634. b->appended = true;
  2635. LLVMAppendExistingBasicBlock(p->value, b->block);
  2636. }
  2637. b->scope = p->curr_scope;
  2638. b->scope_index = p->scope_index;
  2639. b->preds.allocator = heap_allocator();
  2640. b->succs.allocator = heap_allocator();
  2641. array_add(&p->blocks, b);
  2642. return b;
  2643. }
  2644. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2645. if (p->curr_block == nullptr) {
  2646. return;
  2647. }
  2648. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2649. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2650. return;
  2651. }
  2652. lb_add_edge(p->curr_block, target_block);
  2653. LLVMBuildBr(p->builder, target_block->block);
  2654. p->curr_block = nullptr;
  2655. }
  2656. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2657. lbBlock *b = p->curr_block;
  2658. if (b == nullptr) {
  2659. return;
  2660. }
  2661. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2662. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2663. return;
  2664. }
  2665. lb_add_edge(b, true_block);
  2666. lb_add_edge(b, false_block);
  2667. LLVMValueRef cv = cond.value;
  2668. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2669. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2670. }
  2671. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2672. GB_ASSERT(cond != nullptr);
  2673. GB_ASSERT(true_block != nullptr);
  2674. GB_ASSERT(false_block != nullptr);
  2675. switch (cond->kind) {
  2676. case_ast_node(pe, ParenExpr, cond);
  2677. return lb_build_cond(p, pe->expr, true_block, false_block);
  2678. case_end;
  2679. case_ast_node(ue, UnaryExpr, cond);
  2680. if (ue->op.kind == Token_Not) {
  2681. return lb_build_cond(p, ue->expr, false_block, true_block);
  2682. }
  2683. case_end;
  2684. case_ast_node(be, BinaryExpr, cond);
  2685. if (be->op.kind == Token_CmpAnd) {
  2686. lbBlock *block = lb_create_block(p, "cmp.and");
  2687. lb_build_cond(p, be->left, block, false_block);
  2688. lb_start_block(p, block);
  2689. return lb_build_cond(p, be->right, true_block, false_block);
  2690. } else if (be->op.kind == Token_CmpOr) {
  2691. lbBlock *block = lb_create_block(p, "cmp.or");
  2692. lb_build_cond(p, be->left, true_block, block);
  2693. lb_start_block(p, block);
  2694. return lb_build_cond(p, be->right, true_block, false_block);
  2695. }
  2696. case_end;
  2697. }
  2698. lbValue v = lb_build_expr(p, cond);
  2699. // v = lb_emit_conv(p, v, t_bool);
  2700. v = lb_emit_conv(p, v, t_llvm_bool);
  2701. lb_emit_if(p, v, true_block, false_block);
  2702. return v;
  2703. }
  2704. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2705. GB_ASSERT(p->decl_block != p->curr_block);
  2706. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2707. char const *name = "";
  2708. if (e != nullptr) {
  2709. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2710. }
  2711. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2712. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2713. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2714. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2715. LLVMSetAlignment(ptr, alignment);
  2716. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2717. if (zero_init) {
  2718. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2719. switch (kind) {
  2720. case LLVMStructTypeKind:
  2721. case LLVMArrayTypeKind:
  2722. {
  2723. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2724. LLVMTypeRef type_i8 = LLVMInt8TypeInContext(p->module->ctx);
  2725. LLVMTypeRef type_i32 = LLVMInt32TypeInContext(p->module->ctx);
  2726. i32 sz = cast(i32)type_size_of(type);
  2727. LLVMBuildMemSet(p->builder, ptr, LLVMConstNull(type_i8), LLVMConstInt(type_i32, sz, false), alignment);
  2728. }
  2729. break;
  2730. default:
  2731. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2732. break;
  2733. }
  2734. }
  2735. lbValue val = {};
  2736. val.value = ptr;
  2737. val.type = alloc_type_pointer(type);
  2738. if (e != nullptr) {
  2739. lb_add_entity(p->module, e, val);
  2740. lb_add_debug_local_variable(p, ptr, type, e->token);
  2741. }
  2742. return lb_addr(val);
  2743. }
  2744. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2745. return lb_add_local(p, type, nullptr, zero_init);
  2746. }
  2747. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2748. GB_ASSERT(pd->body != nullptr);
  2749. lbModule *m = p->module;
  2750. auto *min_dep_set = &m->info->minimum_dependency_set;
  2751. if (ptr_set_exists(min_dep_set, e) == false) {
  2752. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2753. return;
  2754. }
  2755. // NOTE(bill): Generate a new name
  2756. // parent.name-guid
  2757. String original_name = e->token.string;
  2758. String pd_name = original_name;
  2759. if (e->Procedure.link_name.len > 0) {
  2760. pd_name = e->Procedure.link_name;
  2761. }
  2762. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2763. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2764. i32 guid = cast(i32)p->children.count;
  2765. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2766. String name = make_string(cast(u8 *)name_text, name_len-1);
  2767. set_procedure_abi_types(e->type);
  2768. e->Procedure.link_name = name;
  2769. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2770. e->code_gen_procedure = nested_proc;
  2771. lbValue value = {};
  2772. value.value = nested_proc->value;
  2773. value.type = nested_proc->type;
  2774. lb_add_entity(m, e, value);
  2775. array_add(&p->children, nested_proc);
  2776. array_add(&m->procedures_to_generate, nested_proc);
  2777. }
  2778. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2779. if (e == nullptr) {
  2780. return;
  2781. }
  2782. GB_ASSERT(e->kind == Entity_LibraryName);
  2783. GB_ASSERT(e->flags & EntityFlag_Used);
  2784. for_array(i, e->LibraryName.paths) {
  2785. String library_path = e->LibraryName.paths[i];
  2786. if (library_path.len == 0) {
  2787. continue;
  2788. }
  2789. bool ok = true;
  2790. for_array(path_index, m->foreign_library_paths) {
  2791. String path = m->foreign_library_paths[path_index];
  2792. #if defined(GB_SYSTEM_WINDOWS)
  2793. if (str_eq_ignore_case(path, library_path)) {
  2794. #else
  2795. if (str_eq(path, library_path)) {
  2796. #endif
  2797. ok = false;
  2798. break;
  2799. }
  2800. }
  2801. if (ok) {
  2802. array_add(&m->foreign_library_paths, library_path);
  2803. }
  2804. }
  2805. }
  2806. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2807. if (vd == nullptr || vd->is_mutable) {
  2808. return;
  2809. }
  2810. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2811. static i32 global_guid = 0;
  2812. for_array(i, vd->names) {
  2813. Ast *ident = vd->names[i];
  2814. GB_ASSERT(ident->kind == Ast_Ident);
  2815. Entity *e = entity_of_node(ident);
  2816. GB_ASSERT(e != nullptr);
  2817. if (e->kind != Entity_TypeName) {
  2818. continue;
  2819. }
  2820. bool polymorphic_struct = false;
  2821. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2822. Type *bt = base_type(e->type);
  2823. if (bt->kind == Type_Struct) {
  2824. polymorphic_struct = bt->Struct.is_polymorphic;
  2825. }
  2826. }
  2827. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2828. continue;
  2829. }
  2830. if (e->TypeName.ir_mangled_name.len != 0) {
  2831. // NOTE(bill): Already set
  2832. continue;
  2833. }
  2834. lb_set_nested_type_name_ir_mangled_name(e, p);
  2835. }
  2836. for_array(i, vd->names) {
  2837. Ast *ident = vd->names[i];
  2838. GB_ASSERT(ident->kind == Ast_Ident);
  2839. Entity *e = entity_of_node(ident);
  2840. GB_ASSERT(e != nullptr);
  2841. if (e->kind != Entity_Procedure) {
  2842. continue;
  2843. }
  2844. CheckerInfo *info = p->module->info;
  2845. DeclInfo *decl = decl_info_of_entity(e);
  2846. ast_node(pl, ProcLit, decl->proc_lit);
  2847. if (pl->body != nullptr) {
  2848. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2849. if (found) {
  2850. auto procs = *found;
  2851. for_array(i, procs) {
  2852. Entity *e = procs[i];
  2853. if (!ptr_set_exists(min_dep_set, e)) {
  2854. continue;
  2855. }
  2856. DeclInfo *d = decl_info_of_entity(e);
  2857. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2858. }
  2859. } else {
  2860. lb_build_nested_proc(p, pl, e);
  2861. }
  2862. } else {
  2863. // FFI - Foreign function interace
  2864. String original_name = e->token.string;
  2865. String name = original_name;
  2866. if (e->Procedure.is_foreign) {
  2867. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2868. }
  2869. if (e->Procedure.link_name.len > 0) {
  2870. name = e->Procedure.link_name;
  2871. }
  2872. lbValue *prev_value = string_map_get(&p->module->members, name);
  2873. if (prev_value != nullptr) {
  2874. // NOTE(bill): Don't do mutliple declarations in the IR
  2875. return;
  2876. }
  2877. set_procedure_abi_types(e->type);
  2878. e->Procedure.link_name = name;
  2879. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2880. lbValue value = {};
  2881. value.value = nested_proc->value;
  2882. value.type = nested_proc->type;
  2883. array_add(&p->module->procedures_to_generate, nested_proc);
  2884. if (p != nullptr) {
  2885. array_add(&p->children, nested_proc);
  2886. } else {
  2887. string_map_set(&p->module->members, name, value);
  2888. }
  2889. }
  2890. }
  2891. }
  2892. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  2893. for_array(i, stmts) {
  2894. Ast *stmt = stmts[i];
  2895. switch (stmt->kind) {
  2896. case_ast_node(vd, ValueDecl, stmt);
  2897. lb_build_constant_value_decl(p, vd);
  2898. case_end;
  2899. case_ast_node(fb, ForeignBlockDecl, stmt);
  2900. ast_node(block, BlockStmt, fb->body);
  2901. lb_build_stmt_list(p, block->stmts);
  2902. case_end;
  2903. }
  2904. }
  2905. for_array(i, stmts) {
  2906. lb_build_stmt(p, stmts[i]);
  2907. }
  2908. }
  2909. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2910. GB_ASSERT(ident->kind == Ast_Ident);
  2911. Entity *e = entity_of_node(ident);
  2912. GB_ASSERT(e->kind == Entity_Label);
  2913. for_array(i, p->branch_blocks) {
  2914. lbBranchBlocks *b = &p->branch_blocks[i];
  2915. if (b->label == e->Label.node) {
  2916. return *b;
  2917. }
  2918. }
  2919. GB_PANIC("Unreachable");
  2920. lbBranchBlocks empty = {};
  2921. return empty;
  2922. }
  2923. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2924. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  2925. tl->prev = p->target_list;
  2926. tl->break_ = break_;
  2927. tl->continue_ = continue_;
  2928. tl->fallthrough_ = fallthrough_;
  2929. p->target_list = tl;
  2930. if (label != nullptr) { // Set label blocks
  2931. GB_ASSERT(label->kind == Ast_Label);
  2932. for_array(i, p->branch_blocks) {
  2933. lbBranchBlocks *b = &p->branch_blocks[i];
  2934. GB_ASSERT(b->label != nullptr && label != nullptr);
  2935. GB_ASSERT(b->label->kind == Ast_Label);
  2936. if (b->label == label) {
  2937. b->break_ = break_;
  2938. b->continue_ = continue_;
  2939. return tl;
  2940. }
  2941. }
  2942. GB_PANIC("Unreachable");
  2943. }
  2944. return tl;
  2945. }
  2946. void lb_pop_target_list(lbProcedure *p) {
  2947. p->target_list = p->target_list->prev;
  2948. }
  2949. void lb_open_scope(lbProcedure *p, Scope *s) {
  2950. lbModule *m = p->module;
  2951. if (m->debug_builder) {
  2952. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  2953. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  2954. Token token = ast_token(s->node);
  2955. unsigned line = cast(unsigned)token.pos.line;
  2956. unsigned column = cast(unsigned)token.pos.column;
  2957. LLVMMetadataRef file = nullptr;
  2958. if (s->node->file != nullptr) {
  2959. file = lb_get_llvm_metadata(m, s->node->file);
  2960. }
  2961. LLVMMetadataRef scope = nullptr;
  2962. if (p->scope_stack.count > 0) {
  2963. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  2964. }
  2965. if (scope == nullptr) {
  2966. scope = lb_get_llvm_metadata(m, p);
  2967. }
  2968. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  2969. if (m->debug_builder) {
  2970. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  2971. file, line, column
  2972. );
  2973. lb_set_llvm_metadata(m, s, res);
  2974. }
  2975. }
  2976. }
  2977. p->scope_index += 1;
  2978. array_add(&p->scope_stack, s);
  2979. }
  2980. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  2981. lb_emit_defer_stmts(p, kind, block);
  2982. GB_ASSERT(p->scope_index > 0);
  2983. // NOTE(bill): Remove `context`s made in that scope
  2984. while (p->context_stack.count > 0) {
  2985. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  2986. if (ctx->scope_index >= p->scope_index) {
  2987. array_pop(&p->context_stack);
  2988. } else {
  2989. break;
  2990. }
  2991. }
  2992. p->scope_index -= 1;
  2993. array_pop(&p->scope_stack);
  2994. }
  2995. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  2996. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  2997. GB_ASSERT(is_type_boolean(tv.type));
  2998. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  2999. if (tv.value.value_bool) {
  3000. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  3001. } else if (ws->else_stmt) {
  3002. switch (ws->else_stmt->kind) {
  3003. case Ast_BlockStmt:
  3004. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  3005. break;
  3006. case Ast_WhenStmt:
  3007. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  3008. break;
  3009. default:
  3010. GB_PANIC("Invalid 'else' statement in 'when' statement");
  3011. break;
  3012. }
  3013. }
  3014. }
  3015. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  3016. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3017. lbModule *m = p->module;
  3018. lbValue count = {};
  3019. Type *expr_type = base_type(type_deref(expr.type));
  3020. switch (expr_type->kind) {
  3021. case Type_Array:
  3022. count = lb_const_int(m, t_int, expr_type->Array.count);
  3023. break;
  3024. }
  3025. lbValue val = {};
  3026. lbValue idx = {};
  3027. lbBlock *loop = nullptr;
  3028. lbBlock *done = nullptr;
  3029. lbBlock *body = nullptr;
  3030. lbAddr index = lb_add_local_generated(p, t_int, false);
  3031. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  3032. loop = lb_create_block(p, "for.index.loop");
  3033. lb_emit_jump(p, loop);
  3034. lb_start_block(p, loop);
  3035. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  3036. lb_addr_store(p, index, incr);
  3037. body = lb_create_block(p, "for.index.body");
  3038. done = lb_create_block(p, "for.index.done");
  3039. if (count.value == nullptr) {
  3040. GB_ASSERT(count_ptr.value != nullptr);
  3041. count = lb_emit_load(p, count_ptr);
  3042. }
  3043. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3044. lb_emit_if(p, cond, body, done);
  3045. lb_start_block(p, body);
  3046. idx = lb_addr_load(p, index);
  3047. switch (expr_type->kind) {
  3048. case Type_Array: {
  3049. if (val_type != nullptr) {
  3050. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3051. }
  3052. break;
  3053. }
  3054. case Type_EnumeratedArray: {
  3055. if (val_type != nullptr) {
  3056. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3057. // NOTE(bill): Override the idx value for the enumeration
  3058. Type *index_type = expr_type->EnumeratedArray.index;
  3059. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3060. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3061. }
  3062. }
  3063. break;
  3064. }
  3065. case Type_Slice: {
  3066. if (val_type != nullptr) {
  3067. lbValue elem = lb_slice_elem(p, expr);
  3068. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3069. }
  3070. break;
  3071. }
  3072. case Type_DynamicArray: {
  3073. if (val_type != nullptr) {
  3074. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3075. elem = lb_emit_load(p, elem);
  3076. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3077. }
  3078. break;
  3079. }
  3080. case Type_Map: {
  3081. lbValue entries = lb_map_entries_ptr(p, expr);
  3082. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3083. elem = lb_emit_load(p, elem);
  3084. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3085. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3086. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3087. break;
  3088. }
  3089. case Type_Struct: {
  3090. GB_ASSERT(is_type_soa_struct(expr_type));
  3091. break;
  3092. }
  3093. default:
  3094. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3095. break;
  3096. }
  3097. if (val_) *val_ = val;
  3098. if (idx_) *idx_ = idx;
  3099. if (loop_) *loop_ = loop;
  3100. if (done_) *done_ = done;
  3101. }
  3102. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3103. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3104. lbModule *m = p->module;
  3105. lbValue count = lb_const_int(m, t_int, 0);
  3106. Type *expr_type = base_type(expr.type);
  3107. switch (expr_type->kind) {
  3108. case Type_Basic:
  3109. count = lb_string_len(p, expr);
  3110. break;
  3111. default:
  3112. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3113. break;
  3114. }
  3115. lbValue val = {};
  3116. lbValue idx = {};
  3117. lbBlock *loop = nullptr;
  3118. lbBlock *done = nullptr;
  3119. lbBlock *body = nullptr;
  3120. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3121. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3122. loop = lb_create_block(p, "for.string.loop");
  3123. lb_emit_jump(p, loop);
  3124. lb_start_block(p, loop);
  3125. body = lb_create_block(p, "for.string.body");
  3126. done = lb_create_block(p, "for.string.done");
  3127. lbValue offset = lb_addr_load(p, offset_);
  3128. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3129. lb_emit_if(p, cond, body, done);
  3130. lb_start_block(p, body);
  3131. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3132. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3133. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3134. args[0] = lb_emit_string(p, str_elem, str_len);
  3135. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3136. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3137. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3138. idx = offset;
  3139. if (val_type != nullptr) {
  3140. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3141. }
  3142. if (val_) *val_ = val;
  3143. if (idx_) *idx_ = idx;
  3144. if (loop_) *loop_ = loop;
  3145. if (done_) *done_ = done;
  3146. }
  3147. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  3148. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3149. lbModule *m = p->module;
  3150. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  3151. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  3152. lbValue lower = lb_build_expr(p, node->left);
  3153. lbValue upper = {};
  3154. lbValue val = {};
  3155. lbValue idx = {};
  3156. lbBlock *loop = nullptr;
  3157. lbBlock *done = nullptr;
  3158. lbBlock *body = nullptr;
  3159. if (val_type == nullptr) {
  3160. val_type = lower.type;
  3161. }
  3162. lbAddr value = lb_add_local_generated(p, val_type, false);
  3163. lb_addr_store(p, value, lower);
  3164. lbAddr index = lb_add_local_generated(p, t_int, false);
  3165. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3166. loop = lb_create_block(p, "for.interval.loop");
  3167. lb_emit_jump(p, loop);
  3168. lb_start_block(p, loop);
  3169. body = lb_create_block(p, "for.interval.body");
  3170. done = lb_create_block(p, "for.interval.done");
  3171. TokenKind op = Token_Lt;
  3172. switch (node->op.kind) {
  3173. case Token_Ellipsis: op = Token_LtEq; break;
  3174. case Token_RangeHalf: op = Token_Lt; break;
  3175. default: GB_PANIC("Invalid interval operator"); break;
  3176. }
  3177. upper = lb_build_expr(p, node->right);
  3178. lbValue curr_value = lb_addr_load(p, value);
  3179. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3180. lb_emit_if(p, cond, body, done);
  3181. lb_start_block(p, body);
  3182. val = lb_addr_load(p, value);
  3183. idx = lb_addr_load(p, index);
  3184. lb_emit_increment(p, value.addr);
  3185. lb_emit_increment(p, index.addr);
  3186. if (val_) *val_ = val;
  3187. if (idx_) *idx_ = idx;
  3188. if (loop_) *loop_ = loop;
  3189. if (done_) *done_ = done;
  3190. }
  3191. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3192. lbModule *m = p->module;
  3193. Type *t = enum_type;
  3194. GB_ASSERT(is_type_enum(t));
  3195. Type *enum_ptr = alloc_type_pointer(t);
  3196. t = base_type(t);
  3197. Type *core_elem = core_type(t);
  3198. GB_ASSERT(t->kind == Type_Enum);
  3199. i64 enum_count = t->Enum.fields.count;
  3200. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3201. lbValue ti = lb_type_info(m, t);
  3202. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3203. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3204. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3205. lbValue values_data = lb_slice_elem(p, values);
  3206. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3207. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3208. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3209. lb_emit_jump(p, loop);
  3210. lb_start_block(p, loop);
  3211. lbBlock *body = lb_create_block(p, "for.enum.body");
  3212. lbBlock *done = lb_create_block(p, "for.enum.done");
  3213. lbValue offset = lb_addr_load(p, offset_);
  3214. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3215. lb_emit_if(p, cond, body, done);
  3216. lb_start_block(p, body);
  3217. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3218. lb_emit_increment(p, offset_.addr);
  3219. lbValue val = {};
  3220. if (val_type != nullptr) {
  3221. GB_ASSERT(are_types_identical(enum_type, val_type));
  3222. if (is_type_integer(core_elem)) {
  3223. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3224. val = lb_emit_conv(p, i, t);
  3225. } else {
  3226. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3227. }
  3228. }
  3229. if (val_) *val_ = val;
  3230. if (idx_) *idx_ = offset;
  3231. if (loop_) *loop_ = loop;
  3232. if (done_) *done_ = done;
  3233. }
  3234. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3235. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3236. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3237. lb_emit_jump(p, loop);
  3238. lb_start_block(p, loop);
  3239. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3240. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3241. lbValue tuple_value = lb_build_expr(p, expr);
  3242. Type *tuple = tuple_value.type;
  3243. GB_ASSERT(tuple->kind == Type_Tuple);
  3244. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3245. i32 cond_index = tuple_count-1;
  3246. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3247. lb_emit_if(p, cond, body, done);
  3248. lb_start_block(p, body);
  3249. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3250. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3251. if (loop_) *loop_ = loop;
  3252. if (done_) *done_ = done;
  3253. }
  3254. void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3255. Ast *expr = unparen_expr(rs->expr);
  3256. TypeAndValue tav = type_and_value_of_expr(expr);
  3257. lbBlock *loop = nullptr;
  3258. lbBlock *body = nullptr;
  3259. lbBlock *done = nullptr;
  3260. lb_open_scope(p, scope);
  3261. Type *val_types[2] = {};
  3262. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3263. val_types[0] = type_of_expr(rs->vals[0]);
  3264. }
  3265. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3266. val_types[1] = type_of_expr(rs->vals[1]);
  3267. }
  3268. lbAddr array = lb_build_addr(p, expr);
  3269. if (is_type_pointer(type_deref(lb_addr_type(array)))) {
  3270. array = lb_addr(lb_addr_load(p, array));
  3271. }
  3272. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  3273. lbAddr index = lb_add_local_generated(p, t_int, false);
  3274. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  3275. loop = lb_create_block(p, "for.soa.loop");
  3276. lb_emit_jump(p, loop);
  3277. lb_start_block(p, loop);
  3278. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  3279. lb_addr_store(p, index, incr);
  3280. body = lb_create_block(p, "for.soa.body");
  3281. done = lb_create_block(p, "for.soa.done");
  3282. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3283. lb_emit_if(p, cond, body, done);
  3284. lb_start_block(p, body);
  3285. if (val_types[0]) {
  3286. Entity *e = entity_of_node(rs->vals[0]);
  3287. if (e != nullptr) {
  3288. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  3289. map_set(&p->module->soa_values, hash_entity(e), soa_val);
  3290. }
  3291. }
  3292. if (val_types[1]) {
  3293. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  3294. }
  3295. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3296. lb_build_stmt(p, rs->body);
  3297. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3298. lb_pop_target_list(p);
  3299. lb_emit_jump(p, loop);
  3300. lb_start_block(p, done);
  3301. }
  3302. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3303. Ast *expr = unparen_expr(rs->expr);
  3304. Type *expr_type = type_of_expr(expr);
  3305. if (expr_type != nullptr) {
  3306. Type *et = base_type(type_deref(expr_type));
  3307. if (is_type_soa_struct(et)) {
  3308. lb_build_range_stmt_struct_soa(p, rs, scope);
  3309. return;
  3310. }
  3311. }
  3312. lb_open_scope(p, scope);
  3313. Type *val0_type = nullptr;
  3314. Type *val1_type = nullptr;
  3315. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3316. val0_type = type_of_expr(rs->vals[0]);
  3317. }
  3318. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3319. val1_type = type_of_expr(rs->vals[1]);
  3320. }
  3321. if (val0_type != nullptr) {
  3322. Entity *e = entity_of_node(rs->vals[0]);
  3323. lb_add_local(p, e->type, e, true);
  3324. }
  3325. if (val1_type != nullptr) {
  3326. Entity *e = entity_of_node(rs->vals[1]);
  3327. lb_add_local(p, e->type, e, true);
  3328. }
  3329. lbValue val = {};
  3330. lbValue key = {};
  3331. lbBlock *loop = nullptr;
  3332. lbBlock *done = nullptr;
  3333. bool is_map = false;
  3334. TypeAndValue tav = type_and_value_of_expr(expr);
  3335. if (is_ast_range(expr)) {
  3336. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  3337. } else if (tav.mode == Addressing_Type) {
  3338. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3339. } else {
  3340. Type *expr_type = type_of_expr(expr);
  3341. Type *et = base_type(type_deref(expr_type));
  3342. switch (et->kind) {
  3343. case Type_Map: {
  3344. is_map = true;
  3345. lbValue map = lb_build_addr_ptr(p, expr);
  3346. if (is_type_pointer(type_deref(map.type))) {
  3347. map = lb_emit_load(p, map);
  3348. }
  3349. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3350. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3351. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3352. break;
  3353. }
  3354. case Type_Array: {
  3355. lbValue array = lb_build_addr_ptr(p, expr);
  3356. if (is_type_pointer(type_deref(array.type))) {
  3357. array = lb_emit_load(p, array);
  3358. }
  3359. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3360. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3361. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3362. break;
  3363. }
  3364. case Type_EnumeratedArray: {
  3365. lbValue array = lb_build_addr_ptr(p, expr);
  3366. if (is_type_pointer(type_deref(array.type))) {
  3367. array = lb_emit_load(p, array);
  3368. }
  3369. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3370. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3371. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3372. break;
  3373. }
  3374. case Type_DynamicArray: {
  3375. lbValue count_ptr = {};
  3376. lbValue array = lb_build_addr_ptr(p, expr);
  3377. if (is_type_pointer(type_deref(array.type))) {
  3378. array = lb_emit_load(p, array);
  3379. }
  3380. count_ptr = lb_emit_struct_ep(p, array, 1);
  3381. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3382. break;
  3383. }
  3384. case Type_Slice: {
  3385. lbValue count_ptr = {};
  3386. lbValue slice = lb_build_expr(p, expr);
  3387. if (is_type_pointer(slice.type)) {
  3388. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3389. slice = lb_emit_load(p, slice);
  3390. } else {
  3391. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3392. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3393. }
  3394. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3395. break;
  3396. }
  3397. case Type_Basic: {
  3398. lbValue string = lb_build_expr(p, expr);
  3399. if (is_type_pointer(string.type)) {
  3400. string = lb_emit_load(p, string);
  3401. }
  3402. if (is_type_untyped(expr_type)) {
  3403. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3404. lb_addr_store(p, s, string);
  3405. string = lb_addr_load(p, s);
  3406. }
  3407. Type *t = base_type(string.type);
  3408. GB_ASSERT(!is_type_cstring(t));
  3409. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3410. break;
  3411. }
  3412. case Type_Tuple:
  3413. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3414. break;
  3415. default:
  3416. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3417. break;
  3418. }
  3419. }
  3420. if (is_map) {
  3421. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  3422. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  3423. } else {
  3424. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3425. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  3426. }
  3427. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3428. lb_build_stmt(p, rs->body);
  3429. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3430. lb_pop_target_list(p);
  3431. lb_emit_jump(p, loop);
  3432. lb_start_block(p, done);
  3433. }
  3434. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs, Scope *scope) {
  3435. lbModule *m = p->module;
  3436. lb_open_scope(p, scope); // Open scope here
  3437. Type *val0_type = nullptr;
  3438. Type *val1_type = nullptr;
  3439. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3440. val0_type = type_of_expr(rs->val0);
  3441. }
  3442. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3443. val1_type = type_of_expr(rs->val1);
  3444. }
  3445. if (val0_type != nullptr) {
  3446. Entity *e = entity_of_node(rs->val0);
  3447. lb_add_local(p, e->type, e, true);
  3448. }
  3449. if (val1_type != nullptr) {
  3450. Entity *e = entity_of_node(rs->val1);
  3451. lb_add_local(p, e->type, e, true);
  3452. }
  3453. lbValue val = {};
  3454. lbValue key = {};
  3455. lbBlock *loop = nullptr;
  3456. lbBlock *done = nullptr;
  3457. Ast *expr = unparen_expr(rs->expr);
  3458. TypeAndValue tav = type_and_value_of_expr(expr);
  3459. if (is_ast_range(expr)) {
  3460. lbAddr val0_addr = {};
  3461. lbAddr val1_addr = {};
  3462. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3463. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3464. TokenKind op = expr->BinaryExpr.op.kind;
  3465. Ast *start_expr = expr->BinaryExpr.left;
  3466. Ast *end_expr = expr->BinaryExpr.right;
  3467. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3468. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3469. ExactValue start = start_expr->tav.value;
  3470. ExactValue end = end_expr->tav.value;
  3471. if (op == Token_Ellipsis) { // .. [start, end]
  3472. ExactValue index = exact_value_i64(0);
  3473. for (ExactValue val = start;
  3474. compare_exact_values(Token_LtEq, val, end);
  3475. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3476. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3477. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3478. lb_build_stmt(p, rs->body);
  3479. }
  3480. } else if (op == Token_RangeHalf) { // ..< [start, end)
  3481. ExactValue index = exact_value_i64(0);
  3482. for (ExactValue val = start;
  3483. compare_exact_values(Token_Lt, val, end);
  3484. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3485. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3486. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3487. lb_build_stmt(p, rs->body);
  3488. }
  3489. }
  3490. } else if (tav.mode == Addressing_Type) {
  3491. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3492. Type *et = type_deref(tav.type);
  3493. Type *bet = base_type(et);
  3494. lbAddr val0_addr = {};
  3495. lbAddr val1_addr = {};
  3496. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3497. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3498. for_array(i, bet->Enum.fields) {
  3499. Entity *field = bet->Enum.fields[i];
  3500. GB_ASSERT(field->kind == Entity_Constant);
  3501. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3502. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3503. lb_build_stmt(p, rs->body);
  3504. }
  3505. } else {
  3506. lbAddr val0_addr = {};
  3507. lbAddr val1_addr = {};
  3508. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3509. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3510. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3511. Type *t = base_type(expr->tav.type);
  3512. switch (t->kind) {
  3513. case Type_Basic:
  3514. GB_ASSERT(is_type_string(t));
  3515. {
  3516. ExactValue value = expr->tav.value;
  3517. GB_ASSERT(value.kind == ExactValue_String);
  3518. String str = value.value_string;
  3519. Rune codepoint = 0;
  3520. isize offset = 0;
  3521. do {
  3522. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3523. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3524. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3525. lb_build_stmt(p, rs->body);
  3526. offset += width;
  3527. } while (offset < str.len);
  3528. }
  3529. break;
  3530. case Type_Array:
  3531. if (t->Array.count > 0) {
  3532. lbValue val = lb_build_expr(p, expr);
  3533. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3534. for (i64 i = 0; i < t->Array.count; i++) {
  3535. if (val0_type) {
  3536. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3537. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3538. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3539. }
  3540. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3541. lb_build_stmt(p, rs->body);
  3542. }
  3543. }
  3544. break;
  3545. case Type_EnumeratedArray:
  3546. if (t->EnumeratedArray.count > 0) {
  3547. lbValue val = lb_build_expr(p, expr);
  3548. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3549. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3550. if (val0_type) {
  3551. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3552. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3553. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3554. }
  3555. if (val1_type) {
  3556. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3557. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3558. }
  3559. lb_build_stmt(p, rs->body);
  3560. }
  3561. }
  3562. break;
  3563. default:
  3564. GB_PANIC("Invalid '#unroll for' type");
  3565. break;
  3566. }
  3567. }
  3568. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3569. }
  3570. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  3571. lb_open_scope(p, scope);
  3572. if (ss->init != nullptr) {
  3573. lb_build_stmt(p, ss->init);
  3574. }
  3575. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3576. if (ss->tag != nullptr) {
  3577. tag = lb_build_expr(p, ss->tag);
  3578. }
  3579. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3580. ast_node(body, BlockStmt, ss->body);
  3581. Slice<Ast *> default_stmts = {};
  3582. lbBlock *default_fall = nullptr;
  3583. lbBlock *default_block = nullptr;
  3584. lbBlock *fall = nullptr;
  3585. isize case_count = body->stmts.count;
  3586. for_array(i, body->stmts) {
  3587. Ast *clause = body->stmts[i];
  3588. ast_node(cc, CaseClause, clause);
  3589. lbBlock *body = fall;
  3590. if (body == nullptr) {
  3591. body = lb_create_block(p, "switch.case.body");
  3592. }
  3593. fall = done;
  3594. if (i+1 < case_count) {
  3595. fall = lb_create_block(p, "switch.fall.body");
  3596. }
  3597. if (cc->list.count == 0) {
  3598. // default case
  3599. default_stmts = cc->stmts;
  3600. default_fall = fall;
  3601. default_block = body;
  3602. continue;
  3603. }
  3604. lbBlock *next_cond = nullptr;
  3605. for_array(j, cc->list) {
  3606. Ast *expr = unparen_expr(cc->list[j]);
  3607. next_cond = lb_create_block(p, "switch.case.next");
  3608. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3609. if (is_ast_range(expr)) {
  3610. ast_node(ie, BinaryExpr, expr);
  3611. TokenKind op = Token_Invalid;
  3612. switch (ie->op.kind) {
  3613. case Token_Ellipsis: op = Token_LtEq; break;
  3614. case Token_RangeHalf: op = Token_Lt; break;
  3615. default: GB_PANIC("Invalid interval operator"); break;
  3616. }
  3617. lbValue lhs = lb_build_expr(p, ie->left);
  3618. lbValue rhs = lb_build_expr(p, ie->right);
  3619. // TODO(bill): do short circuit here
  3620. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3621. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3622. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3623. } else {
  3624. if (expr->tav.mode == Addressing_Type) {
  3625. GB_ASSERT(is_type_typeid(tag.type));
  3626. lbValue e = lb_typeid(p->module, expr->tav.type);
  3627. e = lb_emit_conv(p, e, tag.type);
  3628. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3629. } else {
  3630. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3631. }
  3632. }
  3633. lb_emit_if(p, cond, body, next_cond);
  3634. lb_start_block(p, next_cond);
  3635. }
  3636. lb_start_block(p, body);
  3637. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3638. lb_open_scope(p, body->scope);
  3639. lb_build_stmt_list(p, cc->stmts);
  3640. lb_close_scope(p, lbDeferExit_Default, body);
  3641. lb_pop_target_list(p);
  3642. lb_emit_jump(p, done);
  3643. lb_start_block(p, next_cond);
  3644. }
  3645. if (default_block != nullptr) {
  3646. lb_emit_jump(p, default_block);
  3647. lb_start_block(p, default_block);
  3648. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3649. lb_open_scope(p, default_block->scope);
  3650. lb_build_stmt_list(p, default_stmts);
  3651. lb_close_scope(p, lbDeferExit_Default, default_block);
  3652. lb_pop_target_list(p);
  3653. }
  3654. lb_emit_jump(p, done);
  3655. lb_close_scope(p, lbDeferExit_Default, done);
  3656. lb_start_block(p, done);
  3657. }
  3658. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3659. Entity *e = implicit_entity_of_node(clause);
  3660. GB_ASSERT(e != nullptr);
  3661. if (e->flags & EntityFlag_Value) {
  3662. // by value
  3663. GB_ASSERT(are_types_identical(e->type, value.type));
  3664. lbAddr x = lb_add_local(p, e->type, e, false);
  3665. lb_addr_store(p, x, value);
  3666. } else {
  3667. // by reference
  3668. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3669. lb_add_entity(p->module, e, value);
  3670. }
  3671. }
  3672. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3673. Entity *e = entity_of_node(stmt_val);
  3674. if (e == nullptr) {
  3675. return {};
  3676. }
  3677. if ((e->flags & EntityFlag_Value) == 0) {
  3678. if (LLVMIsALoadInst(value.value)) {
  3679. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3680. lb_add_entity(p->module, e, ptr);
  3681. return lb_addr(ptr);
  3682. }
  3683. }
  3684. // by value
  3685. lbAddr addr = lb_add_local(p, e->type, e, false);
  3686. lb_addr_store(p, addr, value);
  3687. return addr;
  3688. }
  3689. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3690. ast_node(cc, CaseClause, clause);
  3691. lb_push_target_list(p, label, done, nullptr, nullptr);
  3692. lb_open_scope(p, body->scope);
  3693. lb_build_stmt_list(p, cc->stmts);
  3694. lb_close_scope(p, lbDeferExit_Default, body);
  3695. lb_pop_target_list(p);
  3696. lb_emit_jump(p, done);
  3697. }
  3698. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3699. lbModule *m = p->module;
  3700. ast_node(as, AssignStmt, ss->tag);
  3701. GB_ASSERT(as->lhs.count == 1);
  3702. GB_ASSERT(as->rhs.count == 1);
  3703. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3704. bool is_parent_ptr = is_type_pointer(parent.type);
  3705. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3706. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3707. lbValue parent_value = parent;
  3708. lbValue parent_ptr = parent;
  3709. if (!is_parent_ptr) {
  3710. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3711. }
  3712. lbValue tag_index = {};
  3713. lbValue union_data = {};
  3714. if (switch_kind == TypeSwitch_Union) {
  3715. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3716. tag_index = lb_emit_load(p, tag_ptr);
  3717. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3718. }
  3719. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3720. lb_emit_jump(p, start_block);
  3721. lb_start_block(p, start_block);
  3722. // NOTE(bill): Append this later
  3723. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3724. Ast *default_ = nullptr;
  3725. ast_node(body, BlockStmt, ss->body);
  3726. gb_local_persist i32 weird_count = 0;
  3727. for_array(i, body->stmts) {
  3728. Ast *clause = body->stmts[i];
  3729. ast_node(cc, CaseClause, clause);
  3730. if (cc->list.count == 0) {
  3731. default_ = clause;
  3732. continue;
  3733. }
  3734. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3735. lbBlock *next = nullptr;
  3736. Type *case_type = nullptr;
  3737. for_array(type_index, cc->list) {
  3738. next = lb_create_block(p, "typeswitch.next");
  3739. case_type = type_of_expr(cc->list[type_index]);
  3740. lbValue cond = {};
  3741. if (switch_kind == TypeSwitch_Union) {
  3742. Type *ut = base_type(type_deref(parent.type));
  3743. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3744. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3745. } else if (switch_kind == TypeSwitch_Any) {
  3746. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3747. lbValue case_typeid = lb_typeid(m, case_type);
  3748. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3749. }
  3750. GB_ASSERT(cond.value != nullptr);
  3751. lb_emit_if(p, cond, body, next);
  3752. lb_start_block(p, next);
  3753. }
  3754. Entity *case_entity = implicit_entity_of_node(clause);
  3755. lbValue value = parent_value;
  3756. lb_start_block(p, body);
  3757. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3758. if (cc->list.count == 1) {
  3759. lbValue data = {};
  3760. if (switch_kind == TypeSwitch_Union) {
  3761. data = union_data;
  3762. } else if (switch_kind == TypeSwitch_Any) {
  3763. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3764. data = any_data;
  3765. }
  3766. Type *ct = case_entity->type;
  3767. Type *ct_ptr = alloc_type_pointer(ct);
  3768. value = lb_emit_conv(p, data, ct_ptr);
  3769. if (!by_reference) {
  3770. value = lb_emit_load(p, value);
  3771. }
  3772. }
  3773. lb_store_type_case_implicit(p, clause, value);
  3774. lb_type_case_body(p, ss->label, clause, body, done);
  3775. lb_start_block(p, next);
  3776. }
  3777. if (default_ != nullptr) {
  3778. lb_store_type_case_implicit(p, default_, parent_value);
  3779. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3780. } else {
  3781. lb_emit_jump(p, done);
  3782. }
  3783. lb_start_block(p, done);
  3784. }
  3785. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3786. lbModule *m = p->module;
  3787. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3788. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3789. type = default_type(type);
  3790. lbValue short_circuit = {};
  3791. if (op == Token_CmpAnd) {
  3792. lb_build_cond(p, left, rhs, done);
  3793. short_circuit = lb_const_bool(m, type, false);
  3794. } else if (op == Token_CmpOr) {
  3795. lb_build_cond(p, left, done, rhs);
  3796. short_circuit = lb_const_bool(m, type, true);
  3797. }
  3798. if (rhs->preds.count == 0) {
  3799. lb_start_block(p, done);
  3800. return short_circuit;
  3801. }
  3802. if (done->preds.count == 0) {
  3803. lb_start_block(p, rhs);
  3804. return lb_build_expr(p, right);
  3805. }
  3806. Array<LLVMValueRef> incoming_values = {};
  3807. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3808. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3809. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3810. for_array(i, done->preds) {
  3811. incoming_values[i] = short_circuit.value;
  3812. incoming_blocks[i] = done->preds[i]->block;
  3813. }
  3814. lb_start_block(p, rhs);
  3815. lbValue edge = lb_build_expr(p, right);
  3816. incoming_values[done->preds.count] = edge.value;
  3817. incoming_blocks[done->preds.count] = p->curr_block->block;
  3818. lb_emit_jump(p, done);
  3819. lb_start_block(p, done);
  3820. lbValue res = {};
  3821. res.type = type;
  3822. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3823. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3824. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3825. return res;
  3826. }
  3827. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3828. Ast *prev_stmt = p->curr_stmt;
  3829. defer (p->curr_stmt = prev_stmt);
  3830. p->curr_stmt = node;
  3831. if (p->curr_block != nullptr) {
  3832. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3833. if (lb_is_instr_terminating(last_instr)) {
  3834. return;
  3835. }
  3836. }
  3837. LLVMMetadataRef prev_debug_location = nullptr;
  3838. if (p->debug_info != nullptr) {
  3839. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  3840. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  3841. }
  3842. defer (if (prev_debug_location != nullptr) {
  3843. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  3844. });
  3845. u64 prev_state_flags = p->module->state_flags;
  3846. defer (p->module->state_flags = prev_state_flags);
  3847. if (node->state_flags != 0) {
  3848. u64 in = node->state_flags;
  3849. u64 out = p->module->state_flags;
  3850. if (in & StateFlag_bounds_check) {
  3851. out |= StateFlag_bounds_check;
  3852. out &= ~StateFlag_no_bounds_check;
  3853. } else if (in & StateFlag_no_bounds_check) {
  3854. out |= StateFlag_no_bounds_check;
  3855. out &= ~StateFlag_bounds_check;
  3856. }
  3857. p->module->state_flags = out;
  3858. }
  3859. switch (node->kind) {
  3860. case_ast_node(bs, EmptyStmt, node);
  3861. case_end;
  3862. case_ast_node(us, UsingStmt, node);
  3863. case_end;
  3864. case_ast_node(ws, WhenStmt, node);
  3865. lb_build_when_stmt(p, ws);
  3866. case_end;
  3867. case_ast_node(bs, BlockStmt, node);
  3868. lbBlock *done = nullptr;
  3869. if (bs->label != nullptr) {
  3870. done = lb_create_block(p, "block.done");
  3871. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3872. tl->is_block = true;
  3873. }
  3874. lb_open_scope(p, node->scope);
  3875. lb_build_stmt_list(p, bs->stmts);
  3876. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3877. if (done != nullptr) {
  3878. lb_emit_jump(p, done);
  3879. lb_start_block(p, done);
  3880. }
  3881. case_end;
  3882. case_ast_node(vd, ValueDecl, node);
  3883. if (!vd->is_mutable) {
  3884. return;
  3885. }
  3886. bool is_static = false;
  3887. if (vd->names.count > 0) {
  3888. Entity *e = entity_of_node(vd->names[0]);
  3889. if (e->flags & EntityFlag_Static) {
  3890. // NOTE(bill): If one of the entities is static, they all are
  3891. is_static = true;
  3892. }
  3893. }
  3894. if (is_static) {
  3895. for_array(i, vd->names) {
  3896. lbValue value = {};
  3897. if (vd->values.count > 0) {
  3898. GB_ASSERT(vd->names.count == vd->values.count);
  3899. Ast *ast_value = vd->values[i];
  3900. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3901. ast_value->tav.mode == Addressing_Invalid);
  3902. bool allow_local = false;
  3903. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3904. }
  3905. Ast *ident = vd->names[i];
  3906. GB_ASSERT(!is_blank_ident(ident));
  3907. Entity *e = entity_of_node(ident);
  3908. GB_ASSERT(e->flags & EntityFlag_Static);
  3909. String name = e->token.string;
  3910. String mangled_name = {};
  3911. {
  3912. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  3913. str = gb_string_appendc(str, "-");
  3914. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3915. mangled_name.text = cast(u8 *)str;
  3916. mangled_name.len = gb_string_length(str);
  3917. }
  3918. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  3919. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3920. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3921. if (value.value != nullptr) {
  3922. LLVMSetInitializer(global, value.value);
  3923. } else {
  3924. }
  3925. if (e->Variable.thread_local_model != "") {
  3926. LLVMSetThreadLocal(global, true);
  3927. String m = e->Variable.thread_local_model;
  3928. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3929. if (m == "default") {
  3930. mode = LLVMGeneralDynamicTLSModel;
  3931. } else if (m == "localdynamic") {
  3932. mode = LLVMLocalDynamicTLSModel;
  3933. } else if (m == "initialexec") {
  3934. mode = LLVMInitialExecTLSModel;
  3935. } else if (m == "localexec") {
  3936. mode = LLVMLocalExecTLSModel;
  3937. } else {
  3938. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3939. }
  3940. LLVMSetThreadLocalMode(global, mode);
  3941. } else {
  3942. LLVMSetLinkage(global, LLVMInternalLinkage);
  3943. }
  3944. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3945. lb_add_entity(p->module, e, global_val);
  3946. lb_add_member(p->module, mangled_name, global_val);
  3947. }
  3948. return;
  3949. }
  3950. if (vd->values.count == 0) { // declared and zero-initialized
  3951. for_array(i, vd->names) {
  3952. Ast *name = vd->names[i];
  3953. if (!is_blank_ident(name)) {
  3954. Entity *e = entity_of_node(name);
  3955. lb_add_local(p, e->type, e, true);
  3956. }
  3957. }
  3958. } else { // Tuple(s)
  3959. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  3960. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  3961. for_array(i, vd->names) {
  3962. Ast *name = vd->names[i];
  3963. lbAddr lval = {};
  3964. if (!is_blank_ident(name)) {
  3965. Entity *e = entity_of_node(name);
  3966. lval = lb_add_local(p, e->type, e, false);
  3967. }
  3968. array_add(&lvals, lval);
  3969. }
  3970. for_array(i, vd->values) {
  3971. lbValue init = lb_build_expr(p, vd->values[i]);
  3972. Type *t = init.type;
  3973. if (t->kind == Type_Tuple) {
  3974. for_array(i, t->Tuple.variables) {
  3975. Entity *e = t->Tuple.variables[i];
  3976. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3977. array_add(&inits, v);
  3978. }
  3979. } else {
  3980. array_add(&inits, init);
  3981. }
  3982. }
  3983. for_array(i, inits) {
  3984. lbAddr lval = lvals[i];
  3985. lbValue init = inits[i];
  3986. lb_addr_store(p, lval, init);
  3987. }
  3988. }
  3989. case_end;
  3990. case_ast_node(as, AssignStmt, node);
  3991. if (as->op.kind == Token_Eq) {
  3992. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  3993. for_array(i, as->lhs) {
  3994. Ast *lhs = as->lhs[i];
  3995. lbAddr lval = {};
  3996. if (!is_blank_ident(lhs)) {
  3997. lval = lb_build_addr(p, lhs);
  3998. }
  3999. array_add(&lvals, lval);
  4000. }
  4001. if (as->lhs.count == as->rhs.count) {
  4002. if (as->lhs.count == 1) {
  4003. lbAddr lval = lvals[0];
  4004. Ast *rhs = as->rhs[0];
  4005. lbValue init = lb_build_expr(p, rhs);
  4006. lb_addr_store(p, lvals[0], init);
  4007. } else {
  4008. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4009. for_array(i, as->rhs) {
  4010. lbValue init = lb_build_expr(p, as->rhs[i]);
  4011. array_add(&inits, init);
  4012. }
  4013. for_array(i, inits) {
  4014. lbAddr lval = lvals[i];
  4015. lbValue init = inits[i];
  4016. lb_addr_store(p, lval, init);
  4017. }
  4018. }
  4019. } else {
  4020. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4021. for_array(i, as->rhs) {
  4022. lbValue init = lb_build_expr(p, as->rhs[i]);
  4023. Type *t = init.type;
  4024. // TODO(bill): refactor for code reuse as this is repeated a bit
  4025. if (t->kind == Type_Tuple) {
  4026. for_array(i, t->Tuple.variables) {
  4027. Entity *e = t->Tuple.variables[i];
  4028. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4029. array_add(&inits, v);
  4030. }
  4031. } else {
  4032. array_add(&inits, init);
  4033. }
  4034. }
  4035. for_array(i, inits) {
  4036. lbAddr lval = lvals[i];
  4037. lbValue init = inits[i];
  4038. lb_addr_store(p, lval, init);
  4039. }
  4040. }
  4041. } else {
  4042. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  4043. // +=, -=, etc
  4044. i32 op = cast(i32)as->op.kind;
  4045. op += Token_Add - Token_AddEq; // Convert += to +
  4046. if (op == Token_CmpAnd || op == Token_CmpOr) {
  4047. Type *type = as->lhs[0]->tav.type;
  4048. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  4049. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4050. lb_addr_store(p, lhs, new_value);
  4051. } else {
  4052. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4053. lbValue value = lb_build_expr(p, as->rhs[0]);
  4054. lbValue old_value = lb_addr_load(p, lhs);
  4055. Type *type = old_value.type;
  4056. lbValue change = lb_emit_conv(p, value, type);
  4057. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  4058. lb_addr_store(p, lhs, new_value);
  4059. }
  4060. return;
  4061. }
  4062. case_end;
  4063. case_ast_node(es, ExprStmt, node);
  4064. lb_build_expr(p, es->expr);
  4065. case_end;
  4066. case_ast_node(ds, DeferStmt, node);
  4067. isize scope_index = p->scope_index;
  4068. lb_add_defer_node(p, scope_index, ds->stmt);
  4069. case_end;
  4070. case_ast_node(rs, ReturnStmt, node);
  4071. lbValue res = {};
  4072. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  4073. isize return_count = p->type->Proc.result_count;
  4074. isize res_count = rs->results.count;
  4075. if (return_count == 0) {
  4076. // No return values
  4077. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4078. LLVMBuildRetVoid(p->builder);
  4079. return;
  4080. } else if (return_count == 1) {
  4081. Entity *e = tuple->variables[0];
  4082. if (res_count == 0) {
  4083. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4084. GB_ASSERT(found);
  4085. res = lb_emit_load(p, *found);
  4086. } else {
  4087. res = lb_build_expr(p, rs->results[0]);
  4088. res = lb_emit_conv(p, res, e->type);
  4089. }
  4090. if (p->type->Proc.has_named_results) {
  4091. // NOTE(bill): store the named values before returning
  4092. if (e->token.string != "") {
  4093. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4094. GB_ASSERT(found != nullptr);
  4095. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  4096. }
  4097. }
  4098. } else {
  4099. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4100. if (res_count != 0) {
  4101. for (isize res_index = 0; res_index < res_count; res_index++) {
  4102. lbValue res = lb_build_expr(p, rs->results[res_index]);
  4103. Type *t = res.type;
  4104. if (t->kind == Type_Tuple) {
  4105. for_array(i, t->Tuple.variables) {
  4106. Entity *e = t->Tuple.variables[i];
  4107. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4108. array_add(&results, v);
  4109. }
  4110. } else {
  4111. array_add(&results, res);
  4112. }
  4113. }
  4114. } else {
  4115. for (isize res_index = 0; res_index < return_count; res_index++) {
  4116. Entity *e = tuple->variables[res_index];
  4117. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4118. GB_ASSERT(found);
  4119. lbValue res = lb_emit_load(p, *found);
  4120. array_add(&results, res);
  4121. }
  4122. }
  4123. GB_ASSERT(results.count == return_count);
  4124. if (p->type->Proc.has_named_results) {
  4125. // NOTE(bill): store the named values before returning
  4126. for_array(i, p->type->Proc.results->Tuple.variables) {
  4127. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4128. if (e->kind != Entity_Variable) {
  4129. continue;
  4130. }
  4131. if (e->token.string == "") {
  4132. continue;
  4133. }
  4134. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4135. GB_ASSERT(found != nullptr);
  4136. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  4137. }
  4138. }
  4139. Type *ret_type = p->type->Proc.results;
  4140. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4141. res = lb_add_local_generated(p, ret_type, false).addr;
  4142. for_array(i, results) {
  4143. Entity *e = tuple->variables[i];
  4144. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  4145. lbValue val = lb_emit_conv(p, results[i], e->type);
  4146. lb_emit_store(p, field, val);
  4147. }
  4148. res = lb_emit_load(p, res);
  4149. }
  4150. lb_ensure_abi_function_type(p->module, p);
  4151. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  4152. if (res.value != nullptr) {
  4153. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4154. } else {
  4155. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4156. }
  4157. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4158. LLVMBuildRetVoid(p->builder);
  4159. } else {
  4160. LLVMValueRef ret_val = res.value;
  4161. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4162. if (p->abi_function_type->ret.cast_type != nullptr) {
  4163. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4164. }
  4165. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4166. LLVMBuildRet(p->builder, ret_val);
  4167. }
  4168. case_end;
  4169. case_ast_node(is, IfStmt, node);
  4170. lb_open_scope(p, node->scope); // Scope #1
  4171. if (is->init != nullptr) {
  4172. // TODO(bill): Should this have a separate block to begin with?
  4173. #if 1
  4174. lbBlock *init = lb_create_block(p, "if.init");
  4175. lb_emit_jump(p, init);
  4176. lb_start_block(p, init);
  4177. #endif
  4178. lb_build_stmt(p, is->init);
  4179. }
  4180. lbBlock *then = lb_create_block(p, "if.then");
  4181. lbBlock *done = lb_create_block(p, "if.done");
  4182. lbBlock *else_ = done;
  4183. if (is->else_stmt != nullptr) {
  4184. else_ = lb_create_block(p, "if.else");
  4185. }
  4186. lb_build_cond(p, is->cond, then, else_);
  4187. lb_start_block(p, then);
  4188. if (is->label != nullptr) {
  4189. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4190. tl->is_block = true;
  4191. }
  4192. lb_build_stmt(p, is->body);
  4193. lb_emit_jump(p, done);
  4194. if (is->else_stmt != nullptr) {
  4195. lb_start_block(p, else_);
  4196. lb_open_scope(p, is->else_stmt->scope);
  4197. lb_build_stmt(p, is->else_stmt);
  4198. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4199. lb_emit_jump(p, done);
  4200. }
  4201. lb_start_block(p, done);
  4202. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4203. case_end;
  4204. case_ast_node(fs, ForStmt, node);
  4205. lb_open_scope(p, node->scope); // Open Scope here
  4206. if (fs->init != nullptr) {
  4207. #if 1
  4208. lbBlock *init = lb_create_block(p, "for.init");
  4209. lb_emit_jump(p, init);
  4210. lb_start_block(p, init);
  4211. #endif
  4212. lb_build_stmt(p, fs->init);
  4213. }
  4214. lbBlock *body = lb_create_block(p, "for.body");
  4215. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4216. lbBlock *loop = body;
  4217. if (fs->cond != nullptr) {
  4218. loop = lb_create_block(p, "for.loop");
  4219. }
  4220. lbBlock *post = loop;
  4221. if (fs->post != nullptr) {
  4222. post = lb_create_block(p, "for.post");
  4223. }
  4224. lb_emit_jump(p, loop);
  4225. lb_start_block(p, loop);
  4226. if (loop != body) {
  4227. lb_build_cond(p, fs->cond, body, done);
  4228. lb_start_block(p, body);
  4229. }
  4230. lb_push_target_list(p, fs->label, done, post, nullptr);
  4231. lb_build_stmt(p, fs->body);
  4232. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4233. lb_pop_target_list(p);
  4234. lb_emit_jump(p, post);
  4235. if (fs->post != nullptr) {
  4236. lb_start_block(p, post);
  4237. lb_build_stmt(p, fs->post);
  4238. lb_emit_jump(p, loop);
  4239. }
  4240. lb_start_block(p, done);
  4241. case_end;
  4242. case_ast_node(rs, RangeStmt, node);
  4243. lb_build_range_stmt(p, rs, node->scope);
  4244. case_end;
  4245. case_ast_node(rs, InlineRangeStmt, node);
  4246. lb_build_inline_range_stmt(p, rs, node->scope);
  4247. case_end;
  4248. case_ast_node(ss, SwitchStmt, node);
  4249. lb_build_switch_stmt(p, ss, node->scope);
  4250. case_end;
  4251. case_ast_node(ss, TypeSwitchStmt, node);
  4252. lb_build_type_switch_stmt(p, ss);
  4253. case_end;
  4254. case_ast_node(bs, BranchStmt, node);
  4255. lbBlock *block = nullptr;
  4256. if (bs->label != nullptr) {
  4257. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4258. switch (bs->token.kind) {
  4259. case Token_break: block = bb.break_; break;
  4260. case Token_continue: block = bb.continue_; break;
  4261. case Token_fallthrough:
  4262. GB_PANIC("fallthrough cannot have a label");
  4263. break;
  4264. }
  4265. } else {
  4266. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4267. if (t->is_block) {
  4268. continue;
  4269. }
  4270. switch (bs->token.kind) {
  4271. case Token_break: block = t->break_; break;
  4272. case Token_continue: block = t->continue_; break;
  4273. case Token_fallthrough: block = t->fallthrough_; break;
  4274. }
  4275. }
  4276. }
  4277. if (block != nullptr) {
  4278. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  4279. }
  4280. lb_emit_jump(p, block);
  4281. case_end;
  4282. }
  4283. }
  4284. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  4285. cond = lb_emit_conv(p, cond, t_llvm_bool);
  4286. lbValue res = {};
  4287. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  4288. res.type = x.type;
  4289. return res;
  4290. }
  4291. lbValue lb_const_nil(lbModule *m, Type *type) {
  4292. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  4293. return lbValue{v, type};
  4294. }
  4295. lbValue lb_const_undef(lbModule *m, Type *type) {
  4296. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  4297. return lbValue{v, type};
  4298. }
  4299. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4300. lbValue res = {};
  4301. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4302. res.type = type;
  4303. return res;
  4304. }
  4305. lbValue lb_const_string(lbModule *m, String const &value) {
  4306. return lb_const_value(m, t_string, exact_value_string(value));
  4307. }
  4308. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  4309. lbValue res = {};
  4310. res.value = LLVMConstInt(lb_type(m, type), value, false);
  4311. res.type = type;
  4312. return res;
  4313. }
  4314. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4315. GB_ASSERT(type_size_of(type) == 4);
  4316. u32 u = bit_cast<u32>(f);
  4317. if (is_type_different_to_arch_endianness(type)) {
  4318. u = gb_endian_swap32(u);
  4319. }
  4320. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4321. return LLVMConstBitCast(i, lb_type(m, type));
  4322. }
  4323. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4324. x = lb_emit_conv(p, x, t);
  4325. y = lb_emit_conv(p, y, t);
  4326. if (is_type_float(t)) {
  4327. i64 sz = 8*type_size_of(t);
  4328. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4329. args[0] = x;
  4330. args[1] = y;
  4331. switch (sz) {
  4332. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  4333. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  4334. }
  4335. GB_PANIC("Unknown float type");
  4336. }
  4337. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4338. }
  4339. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4340. x = lb_emit_conv(p, x, t);
  4341. y = lb_emit_conv(p, y, t);
  4342. if (is_type_float(t)) {
  4343. i64 sz = 8*type_size_of(t);
  4344. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4345. args[0] = x;
  4346. args[1] = y;
  4347. switch (sz) {
  4348. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4349. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4350. }
  4351. GB_PANIC("Unknown float type");
  4352. }
  4353. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4354. }
  4355. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4356. lbValue z = {};
  4357. z = lb_emit_max(p, t, x, min);
  4358. z = lb_emit_min(p, t, z, max);
  4359. return z;
  4360. }
  4361. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4362. StringHashKey key = string_hash_string(str);
  4363. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4364. if (found != nullptr) {
  4365. return *found;
  4366. } else {
  4367. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4368. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4369. cast(char const *)str.text,
  4370. cast(unsigned)str.len,
  4371. false);
  4372. isize max_len = 7+8+1;
  4373. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4374. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4375. len -= 1;
  4376. m->global_array_index++;
  4377. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4378. LLVMSetInitializer(global_data, data);
  4379. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4380. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4381. string_map_set(&m->const_strings, key, ptr);
  4382. return ptr;
  4383. }
  4384. }
  4385. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4386. LLVMValueRef ptr = nullptr;
  4387. if (str.len != 0) {
  4388. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4389. } else {
  4390. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4391. }
  4392. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4393. LLVMValueRef values[2] = {ptr, str_len};
  4394. lbValue res = {};
  4395. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  4396. res.type = t_string;
  4397. return res;
  4398. }
  4399. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4400. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4401. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4402. cast(char const *)str.text,
  4403. cast(unsigned)str.len,
  4404. false);
  4405. char *name = nullptr;
  4406. {
  4407. isize max_len = 7+8+1;
  4408. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4409. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4410. len -= 1;
  4411. m->global_array_index++;
  4412. }
  4413. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4414. LLVMSetInitializer(global_data, data);
  4415. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4416. LLVMValueRef ptr = nullptr;
  4417. if (str.len != 0) {
  4418. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4419. } else {
  4420. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4421. }
  4422. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4423. LLVMValueRef values[2] = {ptr, len};
  4424. lbValue res = {};
  4425. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  4426. res.type = t_u8_slice;
  4427. return res;
  4428. }
  4429. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4430. isize index = type_info_index(info, type, false);
  4431. if (index >= 0) {
  4432. auto *set = &info->minimum_dependency_type_info_set;
  4433. for_array(i, set->entries) {
  4434. if (set->entries[i].ptr == index) {
  4435. return i+1;
  4436. }
  4437. }
  4438. }
  4439. if (err_on_not_found) {
  4440. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4441. }
  4442. return -1;
  4443. }
  4444. lbValue lb_typeid(lbModule *m, Type *type) {
  4445. type = default_type(type);
  4446. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4447. GB_ASSERT(id >= 0);
  4448. u64 kind = Typeid_Invalid;
  4449. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4450. u64 special = 0;
  4451. u64 reserved = 0;
  4452. Type *bt = base_type(type);
  4453. TypeKind tk = bt->kind;
  4454. switch (tk) {
  4455. case Type_Basic: {
  4456. u32 flags = bt->Basic.flags;
  4457. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4458. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4459. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4460. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4461. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4462. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4463. if (flags & BasicFlag_String) kind = Typeid_String;
  4464. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4465. } break;
  4466. case Type_Pointer: kind = Typeid_Pointer; break;
  4467. case Type_Array: kind = Typeid_Array; break;
  4468. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4469. case Type_Slice: kind = Typeid_Slice; break;
  4470. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4471. case Type_Map: kind = Typeid_Map; break;
  4472. case Type_Struct: kind = Typeid_Struct; break;
  4473. case Type_Enum: kind = Typeid_Enum; break;
  4474. case Type_Union: kind = Typeid_Union; break;
  4475. case Type_Tuple: kind = Typeid_Tuple; break;
  4476. case Type_Proc: kind = Typeid_Procedure; break;
  4477. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4478. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4479. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4480. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4481. }
  4482. if (is_type_cstring(type)) {
  4483. special = 1;
  4484. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4485. special = 1;
  4486. }
  4487. u64 data = 0;
  4488. if (build_context.word_size == 4) {
  4489. GB_ASSERT(id <= (1u<<24u));
  4490. data |= (id &~ (1u<<24)) << 0u; // index
  4491. data |= (kind &~ (1u<<5)) << 24u; // kind
  4492. data |= (named &~ (1u<<1)) << 29u; // kind
  4493. data |= (special &~ (1u<<1)) << 30u; // kind
  4494. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4495. } else {
  4496. GB_ASSERT(build_context.word_size == 8);
  4497. GB_ASSERT(id <= (1ull<<56u));
  4498. data |= (id &~ (1ull<<56)) << 0ul; // index
  4499. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4500. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4501. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4502. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4503. }
  4504. lbValue res = {};
  4505. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4506. res.type = t_typeid;
  4507. return res;
  4508. }
  4509. lbValue lb_type_info(lbModule *m, Type *type) {
  4510. type = default_type(type);
  4511. isize index = lb_type_info_index(m->info, type);
  4512. GB_ASSERT(index >= 0);
  4513. LLVMTypeRef it = lb_type(m, t_int);
  4514. LLVMValueRef indices[2] = {
  4515. LLVMConstInt(it, 0, false),
  4516. LLVMConstInt(it, index, true),
  4517. };
  4518. lbValue value = {};
  4519. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  4520. value.type = t_type_info_ptr;
  4521. return value;
  4522. }
  4523. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  4524. bool is_local = allow_local && m->curr_procedure != nullptr;
  4525. bool is_const = true;
  4526. if (is_local) {
  4527. for (isize i = 0; i < count; i++) {
  4528. GB_ASSERT(values[i] != nullptr);
  4529. if (!LLVMIsConstant(values[i])) {
  4530. is_const = false;
  4531. break;
  4532. }
  4533. }
  4534. }
  4535. if (!is_const) {
  4536. lbProcedure *p = m->curr_procedure;
  4537. GB_ASSERT(p != nullptr);
  4538. lbAddr v = lb_add_local_generated(p, type, false);
  4539. lbValue ptr = lb_addr_get_ptr(p, v);
  4540. for (isize i = 0; i < count; i++) {
  4541. lbValue elem = lb_emit_array_epi(p, ptr, i);
  4542. LLVMBuildStore(p->builder, values[i], elem.value);
  4543. }
  4544. return lb_addr_load(p, v).value;
  4545. }
  4546. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  4547. }
  4548. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4549. LLVMContextRef ctx = m->ctx;
  4550. type = default_type(type);
  4551. Type *original_type = type;
  4552. lbValue res = {};
  4553. res.type = original_type;
  4554. type = core_type(type);
  4555. value = convert_exact_value_for_type(value, type);
  4556. if (value.kind == ExactValue_Typeid) {
  4557. return lb_typeid(m, value.value_typeid);
  4558. }
  4559. if (value.kind == ExactValue_Invalid) {
  4560. return lb_const_nil(m, type);
  4561. }
  4562. if (value.kind == ExactValue_Procedure) {
  4563. Ast *expr = unparen_expr(value.value_procedure);
  4564. if (expr->kind == Ast_ProcLit) {
  4565. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4566. }
  4567. Entity *e = entity_from_expr(expr);
  4568. e = strip_entity_wrapping(e);
  4569. GB_ASSERT(e != nullptr);
  4570. auto *found = map_get(&m->values, hash_entity(e));
  4571. if (found) {
  4572. return *found;
  4573. }
  4574. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  4575. }
  4576. bool is_local = allow_local && m->curr_procedure != nullptr;
  4577. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4578. if (is_type_slice(type)) {
  4579. if (value.kind == ExactValue_String) {
  4580. GB_ASSERT(is_type_u8_slice(type));
  4581. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4582. return res;
  4583. } else {
  4584. ast_node(cl, CompoundLit, value.value_compound);
  4585. isize count = cl->elems.count;
  4586. if (count == 0) {
  4587. return lb_const_nil(m, type);
  4588. }
  4589. count = gb_max(cl->max_count, count);
  4590. Type *elem = base_type(type)->Slice.elem;
  4591. Type *t = alloc_type_array(elem, count);
  4592. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4593. LLVMValueRef array_data = nullptr;
  4594. if (is_local) {
  4595. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4596. // its backing data on the stack
  4597. lbProcedure *p = m->curr_procedure;
  4598. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4599. LLVMTypeRef llvm_type = lb_type(m, t);
  4600. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4601. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4602. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4603. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4604. {
  4605. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4606. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4607. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4608. lbAddr slice = lb_add_local_generated(p, type, false);
  4609. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4610. return lb_addr_load(p, slice);
  4611. }
  4612. } else {
  4613. isize max_len = 7+8+1;
  4614. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4615. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4616. m->global_array_index++;
  4617. String name = make_string(cast(u8 *)str, len-1);
  4618. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4619. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4620. LLVMSetInitializer(array_data, backing_array.value);
  4621. lbValue g = {};
  4622. g.value = array_data;
  4623. g.type = t;
  4624. lb_add_entity(m, e, g);
  4625. lb_add_member(m, name, g);
  4626. {
  4627. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4628. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4629. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4630. LLVMValueRef values[2] = {ptr, len};
  4631. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4632. return res;
  4633. }
  4634. }
  4635. }
  4636. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4637. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4638. i64 count = type->Array.count;
  4639. Type *elem = type->Array.elem;
  4640. LLVMTypeRef et = lb_type(m, elem);
  4641. Rune rune;
  4642. isize offset = 0;
  4643. isize width = 1;
  4644. String s = value.value_string;
  4645. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4646. for (i64 i = 0; i < count && offset < s.len; i++) {
  4647. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4648. offset += width;
  4649. elems[i] = LLVMConstInt(et, rune, true);
  4650. }
  4651. GB_ASSERT(offset == s.len);
  4652. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  4653. return res;
  4654. }
  4655. GB_PANIC("HERE!\n");
  4656. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4657. cast(char const *)value.value_string.text,
  4658. cast(unsigned)value.value_string.len,
  4659. false /*DontNullTerminate*/);
  4660. res.value = data;
  4661. return res;
  4662. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4663. GB_ASSERT(type->Array.count == value.value_string.len);
  4664. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4665. cast(char const *)value.value_string.text,
  4666. cast(unsigned)value.value_string.len,
  4667. true /*DontNullTerminate*/);
  4668. res.value = data;
  4669. return res;
  4670. } else if (is_type_array(type) &&
  4671. value.kind != ExactValue_Invalid &&
  4672. value.kind != ExactValue_String &&
  4673. value.kind != ExactValue_Compound) {
  4674. i64 count = type->Array.count;
  4675. Type *elem = type->Array.elem;
  4676. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4677. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4678. for (i64 i = 0; i < count; i++) {
  4679. elems[i] = single_elem.value;
  4680. }
  4681. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  4682. return res;
  4683. }
  4684. switch (value.kind) {
  4685. case ExactValue_Invalid:
  4686. res.value = LLVMConstNull(lb_type(m, original_type));
  4687. return res;
  4688. case ExactValue_Bool:
  4689. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4690. return res;
  4691. case ExactValue_String:
  4692. {
  4693. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4694. lbValue res = {};
  4695. res.type = default_type(original_type);
  4696. if (is_type_cstring(res.type)) {
  4697. res.value = ptr;
  4698. } else {
  4699. if (value.value_string.len == 0) {
  4700. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4701. }
  4702. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4703. LLVMValueRef values[2] = {ptr, str_len};
  4704. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4705. }
  4706. return res;
  4707. }
  4708. case ExactValue_Integer:
  4709. if (is_type_pointer(type)) {
  4710. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4711. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4712. } else {
  4713. unsigned len = cast(unsigned)value.value_integer.len;
  4714. if (len == 0) {
  4715. u64 word = 0;
  4716. res.value = LLVMConstNull(lb_type(m, original_type));
  4717. } else {
  4718. u64 *words = big_int_ptr(&value.value_integer);
  4719. if (is_type_different_to_arch_endianness(type)) {
  4720. // NOTE(bill): Swap byte order for different endianness
  4721. i64 sz = type_size_of(type);
  4722. isize byte_len = gb_size_of(u64)*len;
  4723. u8 *old_bytes = cast(u8 *)words;
  4724. // TODO(bill): Use a different allocator here for a temporary allocation
  4725. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4726. for (i64 i = 0; i < sz; i++) {
  4727. new_bytes[i] = old_bytes[sz-1-i];
  4728. }
  4729. words = cast(u64 *)new_bytes;
  4730. }
  4731. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4732. if (value.value_integer.neg) {
  4733. res.value = LLVMConstNeg(res.value);
  4734. }
  4735. }
  4736. }
  4737. return res;
  4738. case ExactValue_Float:
  4739. if (type_size_of(type) == 4) {
  4740. f32 f = cast(f32)value.value_float;
  4741. res.value = lb_const_f32(m, f, type);
  4742. return res;
  4743. }
  4744. if (is_type_different_to_arch_endianness(type)) {
  4745. u64 u = bit_cast<u64>(value.value_float);
  4746. u = gb_endian_swap64(u);
  4747. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4748. } else {
  4749. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4750. }
  4751. return res;
  4752. case ExactValue_Complex:
  4753. {
  4754. LLVMValueRef values[2] = {};
  4755. switch (8*type_size_of(type)) {
  4756. case 64:
  4757. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  4758. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  4759. break;
  4760. case 128:
  4761. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  4762. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  4763. break;
  4764. }
  4765. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4766. return res;
  4767. }
  4768. break;
  4769. case ExactValue_Quaternion:
  4770. {
  4771. LLVMValueRef values[4] = {};
  4772. switch (8*type_size_of(type)) {
  4773. case 128:
  4774. // @QuaternionLayout
  4775. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  4776. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  4777. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  4778. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  4779. break;
  4780. case 256:
  4781. // @QuaternionLayout
  4782. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  4783. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  4784. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  4785. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  4786. break;
  4787. }
  4788. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  4789. return res;
  4790. }
  4791. break;
  4792. case ExactValue_Pointer:
  4793. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4794. return res;
  4795. case ExactValue_Compound:
  4796. if (is_type_slice(type)) {
  4797. return lb_const_value(m, type, value, allow_local);
  4798. } else if (is_type_array(type)) {
  4799. ast_node(cl, CompoundLit, value.value_compound);
  4800. Type *elem_type = type->Array.elem;
  4801. isize elem_count = cl->elems.count;
  4802. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4803. return lb_const_nil(m, original_type);
  4804. }
  4805. if (cl->elems[0]->kind == Ast_FieldValue) {
  4806. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4807. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4808. isize value_index = 0;
  4809. for (i64 i = 0; i < type->Array.count; i++) {
  4810. bool found = false;
  4811. for (isize j = 0; j < elem_count; j++) {
  4812. Ast *elem = cl->elems[j];
  4813. ast_node(fv, FieldValue, elem);
  4814. if (is_ast_range(fv->field)) {
  4815. ast_node(ie, BinaryExpr, fv->field);
  4816. TypeAndValue lo_tav = ie->left->tav;
  4817. TypeAndValue hi_tav = ie->right->tav;
  4818. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4819. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4820. TokenKind op = ie->op.kind;
  4821. i64 lo = exact_value_to_i64(lo_tav.value);
  4822. i64 hi = exact_value_to_i64(hi_tav.value);
  4823. if (op == Token_Ellipsis) {
  4824. hi += 1;
  4825. }
  4826. if (lo == i) {
  4827. TypeAndValue tav = fv->value->tav;
  4828. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4829. for (i64 k = lo; k < hi; k++) {
  4830. values[value_index++] = val;
  4831. }
  4832. found = true;
  4833. i += (hi-lo-1);
  4834. break;
  4835. }
  4836. } else {
  4837. TypeAndValue index_tav = fv->field->tav;
  4838. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4839. i64 index = exact_value_to_i64(index_tav.value);
  4840. if (index == i) {
  4841. TypeAndValue tav = fv->value->tav;
  4842. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4843. values[value_index++] = val;
  4844. found = true;
  4845. break;
  4846. }
  4847. }
  4848. }
  4849. if (!found) {
  4850. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4851. }
  4852. }
  4853. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4854. return res;
  4855. } else {
  4856. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4857. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4858. for (isize i = 0; i < elem_count; i++) {
  4859. TypeAndValue tav = cl->elems[i]->tav;
  4860. GB_ASSERT(tav.mode != Addressing_Invalid);
  4861. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4862. }
  4863. for (isize i = elem_count; i < type->Array.count; i++) {
  4864. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4865. }
  4866. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4867. return res;
  4868. }
  4869. } else if (is_type_enumerated_array(type)) {
  4870. ast_node(cl, CompoundLit, value.value_compound);
  4871. Type *elem_type = type->EnumeratedArray.elem;
  4872. isize elem_count = cl->elems.count;
  4873. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4874. return lb_const_nil(m, original_type);
  4875. }
  4876. if (cl->elems[0]->kind == Ast_FieldValue) {
  4877. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4878. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4879. isize value_index = 0;
  4880. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4881. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4882. for (i64 i = total_lo; i <= total_hi; i++) {
  4883. bool found = false;
  4884. for (isize j = 0; j < elem_count; j++) {
  4885. Ast *elem = cl->elems[j];
  4886. ast_node(fv, FieldValue, elem);
  4887. if (is_ast_range(fv->field)) {
  4888. ast_node(ie, BinaryExpr, fv->field);
  4889. TypeAndValue lo_tav = ie->left->tav;
  4890. TypeAndValue hi_tav = ie->right->tav;
  4891. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4892. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4893. TokenKind op = ie->op.kind;
  4894. i64 lo = exact_value_to_i64(lo_tav.value);
  4895. i64 hi = exact_value_to_i64(hi_tav.value);
  4896. if (op == Token_Ellipsis) {
  4897. hi += 1;
  4898. }
  4899. if (lo == i) {
  4900. TypeAndValue tav = fv->value->tav;
  4901. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4902. for (i64 k = lo; k < hi; k++) {
  4903. values[value_index++] = val;
  4904. }
  4905. found = true;
  4906. i += (hi-lo-1);
  4907. break;
  4908. }
  4909. } else {
  4910. TypeAndValue index_tav = fv->field->tav;
  4911. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4912. i64 index = exact_value_to_i64(index_tav.value);
  4913. if (index == i) {
  4914. TypeAndValue tav = fv->value->tav;
  4915. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4916. values[value_index++] = val;
  4917. found = true;
  4918. break;
  4919. }
  4920. }
  4921. }
  4922. if (!found) {
  4923. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4924. }
  4925. }
  4926. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4927. return res;
  4928. } else {
  4929. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4930. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4931. for (isize i = 0; i < elem_count; i++) {
  4932. TypeAndValue tav = cl->elems[i]->tav;
  4933. GB_ASSERT(tav.mode != Addressing_Invalid);
  4934. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4935. }
  4936. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4937. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4938. }
  4939. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4940. return res;
  4941. }
  4942. } else if (is_type_simd_vector(type)) {
  4943. ast_node(cl, CompoundLit, value.value_compound);
  4944. Type *elem_type = type->SimdVector.elem;
  4945. isize elem_count = cl->elems.count;
  4946. if (elem_count == 0) {
  4947. return lb_const_nil(m, original_type);
  4948. }
  4949. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4950. isize total_elem_count = type->SimdVector.count;
  4951. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  4952. for (isize i = 0; i < elem_count; i++) {
  4953. TypeAndValue tav = cl->elems[i]->tav;
  4954. GB_ASSERT(tav.mode != Addressing_Invalid);
  4955. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4956. }
  4957. LLVMTypeRef et = lb_type(m, elem_type);
  4958. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  4959. values[i] = LLVMConstNull(et);
  4960. }
  4961. for (isize i = 0; i< total_elem_count; i++) {
  4962. values[i] = llvm_const_cast(values[i], et);
  4963. }
  4964. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  4965. return res;
  4966. } else if (is_type_struct(type)) {
  4967. ast_node(cl, CompoundLit, value.value_compound);
  4968. if (cl->elems.count == 0) {
  4969. return lb_const_nil(m, original_type);
  4970. }
  4971. isize offset = 0;
  4972. if (type->Struct.custom_align > 0) {
  4973. offset = 1;
  4974. }
  4975. isize value_count = type->Struct.fields.count + offset;
  4976. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  4977. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  4978. if (cl->elems.count > 0) {
  4979. if (cl->elems[0]->kind == Ast_FieldValue) {
  4980. isize elem_count = cl->elems.count;
  4981. for (isize i = 0; i < elem_count; i++) {
  4982. ast_node(fv, FieldValue, cl->elems[i]);
  4983. String name = fv->field->Ident.token.string;
  4984. TypeAndValue tav = fv->value->tav;
  4985. GB_ASSERT(tav.mode != Addressing_Invalid);
  4986. Selection sel = lookup_field(type, name, false);
  4987. Entity *f = type->Struct.fields[sel.index[0]];
  4988. if (elem_type_can_be_constant(f->type)) {
  4989. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  4990. visited[offset+f->Variable.field_index] = true;
  4991. }
  4992. }
  4993. } else {
  4994. for_array(i, cl->elems) {
  4995. Entity *f = type->Struct.fields[i];
  4996. TypeAndValue tav = cl->elems[i]->tav;
  4997. ExactValue val = {};
  4998. if (tav.mode != Addressing_Invalid) {
  4999. val = tav.value;
  5000. }
  5001. if (elem_type_can_be_constant(f->type)) {
  5002. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  5003. visited[offset+f->Variable.field_index] = true;
  5004. }
  5005. }
  5006. }
  5007. }
  5008. for (isize i = 0; i < type->Struct.fields.count; i++) {
  5009. if (!visited[offset+i]) {
  5010. GB_ASSERT(values[offset+i] == nullptr);
  5011. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  5012. }
  5013. }
  5014. if (type->Struct.custom_align > 0) {
  5015. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  5016. }
  5017. for (isize i = 0; i < value_count; i++) {
  5018. GB_ASSERT(LLVMIsConstant(values[i]));
  5019. }
  5020. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  5021. return res;
  5022. } else if (is_type_bit_set(type)) {
  5023. ast_node(cl, CompoundLit, value.value_compound);
  5024. if (cl->elems.count == 0) {
  5025. return lb_const_nil(m, original_type);
  5026. }
  5027. i64 sz = type_size_of(type);
  5028. if (sz == 0) {
  5029. return lb_const_nil(m, original_type);
  5030. }
  5031. u64 bits = 0;
  5032. for_array(i, cl->elems) {
  5033. Ast *e = cl->elems[i];
  5034. GB_ASSERT(e->kind != Ast_FieldValue);
  5035. TypeAndValue tav = e->tav;
  5036. if (tav.mode != Addressing_Constant) {
  5037. continue;
  5038. }
  5039. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  5040. i64 v = big_int_to_i64(&tav.value.value_integer);
  5041. i64 lower = type->BitSet.lower;
  5042. bits |= 1ull<<cast(u64)(v-lower);
  5043. }
  5044. if (is_type_different_to_arch_endianness(type)) {
  5045. i64 size = type_size_of(type);
  5046. switch (size) {
  5047. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  5048. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  5049. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  5050. }
  5051. }
  5052. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  5053. return res;
  5054. } else {
  5055. return lb_const_nil(m, original_type);
  5056. }
  5057. break;
  5058. case ExactValue_Procedure:
  5059. {
  5060. Ast *expr = value.value_procedure;
  5061. GB_ASSERT(expr != nullptr);
  5062. if (expr->kind == Ast_ProcLit) {
  5063. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5064. }
  5065. }
  5066. break;
  5067. case ExactValue_Typeid:
  5068. return lb_typeid(m, value.value_typeid);
  5069. }
  5070. return lb_const_nil(m, original_type);
  5071. }
  5072. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  5073. lbModule *m = p->module;
  5074. LLVMValueRef fields[4] = {};
  5075. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  5076. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  5077. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  5078. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  5079. lbValue res = {};
  5080. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  5081. res.type = t_source_code_location;
  5082. return res;
  5083. }
  5084. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  5085. String proc_name = {};
  5086. if (p->entity) {
  5087. proc_name = p->entity->token.string;
  5088. }
  5089. TokenPos pos = {};
  5090. if (node) {
  5091. pos = ast_token(node).pos;
  5092. }
  5093. return lb_emit_source_code_location(p, proc_name, pos);
  5094. }
  5095. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  5096. switch (op) {
  5097. case Token_Add:
  5098. return x;
  5099. case Token_Not: // Boolean not
  5100. case Token_Xor: // Bitwise not
  5101. case Token_Sub: // Number negation
  5102. break;
  5103. case Token_Pointer:
  5104. GB_PANIC("This should be handled elsewhere");
  5105. break;
  5106. }
  5107. if (is_type_array(x.type)) {
  5108. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5109. Type *tl = base_type(x.type);
  5110. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5111. GB_ASSERT(is_type_array(type));
  5112. Type *elem_type = base_array_type(type);
  5113. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5114. lbAddr res_addr = lb_add_local_generated(p, type, false);
  5115. lbValue res = lb_addr_get_ptr(p, res_addr);
  5116. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5117. i32 count = cast(i32)tl->Array.count;
  5118. if (inline_array_arith) {
  5119. // inline
  5120. for (i32 i = 0; i < count; i++) {
  5121. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5122. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5123. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  5124. }
  5125. } else {
  5126. auto loop_data = lb_loop_start(p, count, t_i32);
  5127. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  5128. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5129. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  5130. lb_loop_end(p, loop_data);
  5131. }
  5132. return lb_emit_load(p, res);
  5133. }
  5134. if (op == Token_Xor) {
  5135. lbValue cmp = {};
  5136. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  5137. cmp.type = x.type;
  5138. return lb_emit_conv(p, cmp, type);
  5139. }
  5140. if (op == Token_Not) {
  5141. lbValue cmp = {};
  5142. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  5143. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  5144. cmp.type = t_llvm_bool;
  5145. return lb_emit_conv(p, cmp, type);
  5146. }
  5147. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5148. Type *platform_type = integer_endian_type_to_platform_type(type);
  5149. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5150. lbValue res = {};
  5151. res.value = LLVMBuildNeg(p->builder, v.value, "");
  5152. res.type = platform_type;
  5153. return lb_emit_byte_swap(p, res, type);
  5154. }
  5155. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5156. Type *platform_type = integer_endian_type_to_platform_type(type);
  5157. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5158. lbValue res = {};
  5159. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  5160. res.type = platform_type;
  5161. return lb_emit_byte_swap(p, res, type);
  5162. }
  5163. lbValue res = {};
  5164. switch (op) {
  5165. case Token_Not: // Boolean not
  5166. case Token_Xor: // Bitwise not
  5167. res.value = LLVMBuildNot(p->builder, x.value, "");
  5168. res.type = x.type;
  5169. return res;
  5170. case Token_Sub: // Number negation
  5171. if (is_type_integer(x.type)) {
  5172. res.value = LLVMBuildNeg(p->builder, x.value, "");
  5173. } else if (is_type_float(x.type)) {
  5174. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  5175. } else if (is_type_complex(x.type)) {
  5176. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5177. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5178. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5179. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5180. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5181. return lb_addr_load(p, addr);
  5182. } else if (is_type_quaternion(x.type)) {
  5183. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5184. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5185. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  5186. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  5187. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5188. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5189. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5190. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  5191. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  5192. return lb_addr_load(p, addr);
  5193. } else {
  5194. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  5195. }
  5196. res.type = x.type;
  5197. return res;
  5198. }
  5199. return res;
  5200. }
  5201. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  5202. lbModule *m = p->module;
  5203. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  5204. lhs = lb_emit_conv(p, lhs, type);
  5205. rhs = lb_emit_conv(p, rhs, type);
  5206. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  5207. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  5208. GB_ASSERT(is_type_array(type));
  5209. Type *elem_type = base_array_type(type);
  5210. lbAddr res = lb_add_local_generated(p, type, false);
  5211. i64 count = base_type(type)->Array.count;
  5212. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5213. if (inline_array_arith) {
  5214. for (i64 i = 0; i < count; i++) {
  5215. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  5216. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  5217. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  5218. lbValue a = lb_emit_load(p, a_ptr);
  5219. lbValue b = lb_emit_load(p, b_ptr);
  5220. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5221. lb_emit_store(p, dst_ptr, c);
  5222. }
  5223. } else {
  5224. auto loop_data = lb_loop_start(p, count, t_i32);
  5225. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  5226. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  5227. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  5228. lbValue a = lb_emit_load(p, a_ptr);
  5229. lbValue b = lb_emit_load(p, b_ptr);
  5230. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5231. lb_emit_store(p, dst_ptr, c);
  5232. lb_loop_end(p, loop_data);
  5233. }
  5234. return lb_addr_load(p, res);
  5235. } else if (is_type_complex(type)) {
  5236. lhs = lb_emit_conv(p, lhs, type);
  5237. rhs = lb_emit_conv(p, rhs, type);
  5238. Type *ft = base_complex_elem_type(type);
  5239. if (op == Token_Quo) {
  5240. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5241. args[0] = lhs;
  5242. args[1] = rhs;
  5243. switch (type_size_of(ft)) {
  5244. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  5245. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  5246. default: GB_PANIC("Unknown float type"); break;
  5247. }
  5248. }
  5249. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5250. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  5251. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  5252. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  5253. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  5254. lbValue real = {};
  5255. lbValue imag = {};
  5256. switch (op) {
  5257. case Token_Add:
  5258. real = lb_emit_arith(p, Token_Add, a, c, ft);
  5259. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  5260. break;
  5261. case Token_Sub:
  5262. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  5263. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  5264. break;
  5265. case Token_Mul: {
  5266. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  5267. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  5268. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  5269. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  5270. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  5271. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  5272. break;
  5273. }
  5274. }
  5275. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  5276. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  5277. return lb_addr_load(p, res);
  5278. } else if (is_type_quaternion(type)) {
  5279. lhs = lb_emit_conv(p, lhs, type);
  5280. rhs = lb_emit_conv(p, rhs, type);
  5281. Type *ft = base_complex_elem_type(type);
  5282. if (op == Token_Add || op == Token_Sub) {
  5283. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5284. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  5285. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  5286. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  5287. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  5288. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  5289. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  5290. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  5291. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  5292. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  5293. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  5294. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  5295. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  5296. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  5297. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  5298. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  5299. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  5300. return lb_addr_load(p, res);
  5301. } else if (op == Token_Mul) {
  5302. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5303. args[0] = lhs;
  5304. args[1] = rhs;
  5305. switch (8*type_size_of(ft)) {
  5306. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  5307. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  5308. default: GB_PANIC("Unknown float type"); break;
  5309. }
  5310. } else if (op == Token_Quo) {
  5311. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5312. args[0] = lhs;
  5313. args[1] = rhs;
  5314. switch (8*type_size_of(ft)) {
  5315. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  5316. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  5317. default: GB_PANIC("Unknown float type"); break;
  5318. }
  5319. }
  5320. }
  5321. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5322. switch (op) {
  5323. case Token_AndNot:
  5324. case Token_And:
  5325. case Token_Or:
  5326. case Token_Xor:
  5327. goto handle_op;
  5328. }
  5329. Type *platform_type = integer_endian_type_to_platform_type(type);
  5330. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5331. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5332. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5333. return lb_emit_byte_swap(p, res, type);
  5334. }
  5335. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5336. Type *platform_type = integer_endian_type_to_platform_type(type);
  5337. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5338. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5339. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5340. return lb_emit_byte_swap(p, res, type);
  5341. }
  5342. handle_op:
  5343. lhs = lb_emit_conv(p, lhs, type);
  5344. rhs = lb_emit_conv(p, rhs, type);
  5345. lbValue res = {};
  5346. res.type = type;
  5347. // NOTE(bill): Bit Set Aliases for + and -
  5348. if (is_type_bit_set(type)) {
  5349. switch (op) {
  5350. case Token_Add: op = Token_Or; break;
  5351. case Token_Sub: op = Token_AndNot; break;
  5352. }
  5353. }
  5354. switch (op) {
  5355. case Token_Add:
  5356. if (is_type_float(type)) {
  5357. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  5358. return res;
  5359. }
  5360. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  5361. return res;
  5362. case Token_Sub:
  5363. if (is_type_float(type)) {
  5364. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  5365. return res;
  5366. }
  5367. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  5368. return res;
  5369. case Token_Mul:
  5370. if (is_type_float(type)) {
  5371. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  5372. return res;
  5373. }
  5374. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  5375. return res;
  5376. case Token_Quo:
  5377. if (is_type_float(type)) {
  5378. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  5379. return res;
  5380. } else if (is_type_unsigned(type)) {
  5381. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  5382. return res;
  5383. }
  5384. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  5385. return res;
  5386. case Token_Mod:
  5387. if (is_type_float(type)) {
  5388. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  5389. return res;
  5390. } else if (is_type_unsigned(type)) {
  5391. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5392. return res;
  5393. }
  5394. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5395. return res;
  5396. case Token_ModMod:
  5397. if (is_type_unsigned(type)) {
  5398. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5399. return res;
  5400. } else {
  5401. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5402. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5403. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5404. res.value = c;
  5405. return res;
  5406. }
  5407. case Token_And:
  5408. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5409. return res;
  5410. case Token_Or:
  5411. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5412. return res;
  5413. case Token_Xor:
  5414. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5415. return res;
  5416. case Token_Shl:
  5417. {
  5418. rhs = lb_emit_conv(p, rhs, lhs.type);
  5419. LLVMValueRef lhsval = lhs.value;
  5420. LLVMValueRef bits = rhs.value;
  5421. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5422. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULT, bits, max, "");
  5423. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5424. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5425. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  5426. return res;
  5427. }
  5428. case Token_Shr:
  5429. {
  5430. rhs = lb_emit_conv(p, rhs, lhs.type);
  5431. LLVMValueRef lhsval = lhs.value;
  5432. LLVMValueRef bits = rhs.value;
  5433. bool is_unsigned = is_type_unsigned(type);
  5434. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5435. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULT, bits, max, "");
  5436. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  5437. if (is_unsigned) {
  5438. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  5439. } else {
  5440. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5441. }
  5442. return res;
  5443. }
  5444. case Token_AndNot:
  5445. {
  5446. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5447. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5448. return res;
  5449. }
  5450. break;
  5451. }
  5452. GB_PANIC("unhandled operator of lb_emit_arith");
  5453. return {};
  5454. }
  5455. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5456. ast_node(be, BinaryExpr, expr);
  5457. TypeAndValue tv = type_and_value_of_expr(expr);
  5458. switch (be->op.kind) {
  5459. case Token_Add:
  5460. case Token_Sub:
  5461. case Token_Mul:
  5462. case Token_Quo:
  5463. case Token_Mod:
  5464. case Token_ModMod:
  5465. case Token_And:
  5466. case Token_Or:
  5467. case Token_Xor:
  5468. case Token_AndNot:
  5469. case Token_Shl:
  5470. case Token_Shr: {
  5471. Type *type = default_type(tv.type);
  5472. lbValue left = lb_build_expr(p, be->left);
  5473. lbValue right = lb_build_expr(p, be->right);
  5474. return lb_emit_arith(p, be->op.kind, left, right, type);
  5475. }
  5476. case Token_CmpEq:
  5477. case Token_NotEq:
  5478. case Token_Lt:
  5479. case Token_LtEq:
  5480. case Token_Gt:
  5481. case Token_GtEq:
  5482. {
  5483. lbValue left = {};
  5484. lbValue right = {};
  5485. if (be->left->tav.mode == Addressing_Type) {
  5486. left = lb_typeid(p->module, be->left->tav.type);
  5487. }
  5488. if (be->right->tav.mode == Addressing_Type) {
  5489. right = lb_typeid(p->module, be->right->tav.type);
  5490. }
  5491. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5492. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5493. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5494. Type *type = default_type(tv.type);
  5495. return lb_emit_conv(p, cmp, type);
  5496. }
  5497. case Token_CmpAnd:
  5498. case Token_CmpOr:
  5499. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5500. case Token_in:
  5501. case Token_not_in:
  5502. {
  5503. lbValue left = lb_build_expr(p, be->left);
  5504. Type *type = default_type(tv.type);
  5505. lbValue right = lb_build_expr(p, be->right);
  5506. Type *rt = base_type(right.type);
  5507. switch (rt->kind) {
  5508. case Type_Map:
  5509. {
  5510. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5511. lbValue h = lb_gen_map_header(p, addr, rt);
  5512. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  5513. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5514. args[0] = h;
  5515. args[1] = key;
  5516. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5517. if (be->op.kind == Token_in) {
  5518. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5519. } else {
  5520. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  5521. }
  5522. }
  5523. break;
  5524. case Type_BitSet:
  5525. {
  5526. Type *key_type = rt->BitSet.elem;
  5527. GB_ASSERT(are_types_identical(left.type, key_type));
  5528. Type *it = bit_set_to_int(rt);
  5529. left = lb_emit_conv(p, left, it);
  5530. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  5531. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  5532. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  5533. bit = lb_emit_conv(p, bit, it);
  5534. lbValue old_value = lb_emit_transmute(p, right, it);
  5535. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  5536. if (be->op.kind == Token_in) {
  5537. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5538. } else {
  5539. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5540. }
  5541. }
  5542. break;
  5543. default:
  5544. GB_PANIC("Invalid 'in' type");
  5545. }
  5546. break;
  5547. }
  5548. break;
  5549. default:
  5550. GB_PANIC("Invalid binary expression");
  5551. break;
  5552. }
  5553. return {};
  5554. }
  5555. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5556. Type *prev_src = src;
  5557. // Type *prev_dst = dst;
  5558. src = base_type(type_deref(src));
  5559. // dst = base_type(type_deref(dst));
  5560. bool src_is_ptr = src != prev_src;
  5561. // bool dst_is_ptr = dst != prev_dst;
  5562. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5563. for_array(i, src->Struct.fields) {
  5564. Entity *f = src->Struct.fields[i];
  5565. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5566. if (are_types_identical(dst, f->type)) {
  5567. return f->token.string;
  5568. }
  5569. if (src_is_ptr && is_type_pointer(dst)) {
  5570. if (are_types_identical(type_deref(dst), f->type)) {
  5571. return f->token.string;
  5572. }
  5573. }
  5574. if (is_type_struct(f->type)) {
  5575. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5576. if (name.len > 0) {
  5577. return name;
  5578. }
  5579. }
  5580. }
  5581. }
  5582. return str_lit("");
  5583. }
  5584. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5585. GB_ASSERT(is_type_pointer(value.type));
  5586. GB_ASSERT(is_type_pointer(t));
  5587. GB_ASSERT(lb_is_const(value));
  5588. lbValue res = {};
  5589. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5590. res.type = t;
  5591. return res;
  5592. }
  5593. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5594. lbModule *m = p->module;
  5595. t = reduce_tuple_to_single_type(t);
  5596. Type *src_type = value.type;
  5597. if (are_types_identical(t, src_type)) {
  5598. return value;
  5599. }
  5600. Type *src = core_type(src_type);
  5601. Type *dst = core_type(t);
  5602. GB_ASSERT(src != nullptr);
  5603. GB_ASSERT(dst != nullptr);
  5604. if (is_type_untyped_nil(src)) {
  5605. return lb_const_nil(m, t);
  5606. }
  5607. if (is_type_untyped_undef(src)) {
  5608. return lb_const_undef(m, t);
  5609. }
  5610. if (LLVMIsConstant(value.value)) {
  5611. if (is_type_any(dst)) {
  5612. Type *st = default_type(src_type);
  5613. lbAddr default_value = lb_add_local_generated(p, st, false);
  5614. lb_addr_store(p, default_value, value);
  5615. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5616. lbValue id = lb_typeid(m, st);
  5617. lbAddr res = lb_add_local_generated(p, t, false);
  5618. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5619. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5620. lb_emit_store(p, a0, data);
  5621. lb_emit_store(p, a1, id);
  5622. return lb_addr_load(p, res);
  5623. } else if (dst->kind == Type_Basic) {
  5624. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5625. String str = lb_get_const_string(m, value);
  5626. lbValue res = {};
  5627. res.type = t;
  5628. res.value = llvm_cstring(m, str);
  5629. return res;
  5630. }
  5631. // if (is_type_float(dst)) {
  5632. // return value;
  5633. // } else if (is_type_integer(dst)) {
  5634. // return value;
  5635. // }
  5636. // ExactValue ev = value->Constant.value;
  5637. // if (is_type_float(dst)) {
  5638. // ev = exact_value_to_float(ev);
  5639. // } else if (is_type_complex(dst)) {
  5640. // ev = exact_value_to_complex(ev);
  5641. // } else if (is_type_quaternion(dst)) {
  5642. // ev = exact_value_to_quaternion(ev);
  5643. // } else if (is_type_string(dst)) {
  5644. // // Handled elsewhere
  5645. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5646. // } else if (is_type_integer(dst)) {
  5647. // ev = exact_value_to_integer(ev);
  5648. // } else if (is_type_pointer(dst)) {
  5649. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5650. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5651. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5652. // }
  5653. // return lb_const_value(p->module, t, ev);
  5654. }
  5655. }
  5656. if (are_types_identical(src, dst)) {
  5657. if (!are_types_identical(src_type, t)) {
  5658. return lb_emit_transmute(p, value, t);
  5659. }
  5660. return value;
  5661. }
  5662. // bool <-> llvm bool
  5663. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5664. lbValue res = {};
  5665. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5666. res.type = dst;
  5667. return res;
  5668. }
  5669. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5670. lbValue res = {};
  5671. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5672. res.type = dst;
  5673. return res;
  5674. }
  5675. // integer -> integer
  5676. if (is_type_integer(src) && is_type_integer(dst)) {
  5677. GB_ASSERT(src->kind == Type_Basic &&
  5678. dst->kind == Type_Basic);
  5679. i64 sz = type_size_of(default_type(src));
  5680. i64 dz = type_size_of(default_type(dst));
  5681. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5682. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5683. value = lb_emit_byte_swap(p, value, platform_src_type);
  5684. }
  5685. LLVMOpcode op = LLVMTrunc;
  5686. if (dz < sz) {
  5687. op = LLVMTrunc;
  5688. } else if (dz == sz) {
  5689. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5690. // NOTE(bill): Copy the value just for type correctness
  5691. op = LLVMBitCast;
  5692. } else if (dz > sz) {
  5693. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5694. }
  5695. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5696. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5697. lbValue res = {};
  5698. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5699. res.type = t;
  5700. return lb_emit_byte_swap(p, res, t);
  5701. } else {
  5702. lbValue res = {};
  5703. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5704. res.type = t;
  5705. return res;
  5706. }
  5707. }
  5708. // boolean -> boolean/integer
  5709. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5710. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5711. lbValue res = {};
  5712. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5713. res.type = t;
  5714. return res;
  5715. }
  5716. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5717. return lb_emit_transmute(p, value, dst);
  5718. }
  5719. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5720. return lb_emit_transmute(p, value, dst);
  5721. }
  5722. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5723. return lb_emit_transmute(p, value, dst);
  5724. }
  5725. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5726. return lb_emit_transmute(p, value, dst);
  5727. }
  5728. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5729. lbValue c = lb_emit_conv(p, value, t_cstring);
  5730. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5731. args[0] = c;
  5732. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5733. return lb_emit_conv(p, s, dst);
  5734. }
  5735. // integer -> boolean
  5736. if (is_type_integer(src) && is_type_boolean(dst)) {
  5737. lbValue res = {};
  5738. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5739. res.type = t_llvm_bool;
  5740. return lb_emit_conv(p, res, t);
  5741. }
  5742. // float -> float
  5743. if (is_type_float(src) && is_type_float(dst)) {
  5744. i64 sz = type_size_of(src);
  5745. i64 dz = type_size_of(dst);
  5746. if (dz == sz) {
  5747. if (types_have_same_internal_endian(src, dst)) {
  5748. lbValue res = {};
  5749. res.type = t;
  5750. res.value = value.value;
  5751. return res;
  5752. } else {
  5753. return lb_emit_byte_swap(p, value, t);
  5754. }
  5755. }
  5756. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5757. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5758. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5759. lbValue res = {};
  5760. res = lb_emit_conv(p, value, platform_src_type);
  5761. res = lb_emit_conv(p, res, platform_dst_type);
  5762. if (is_type_different_to_arch_endianness(dst)) {
  5763. res = lb_emit_byte_swap(p, res, t);
  5764. }
  5765. return lb_emit_conv(p, res, t);
  5766. }
  5767. lbValue res = {};
  5768. res.type = t;
  5769. if (dz >= sz) {
  5770. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5771. } else {
  5772. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5773. }
  5774. return res;
  5775. }
  5776. if (is_type_complex(src) && is_type_complex(dst)) {
  5777. Type *ft = base_complex_elem_type(dst);
  5778. lbAddr gen = lb_add_local_generated(p, dst, false);
  5779. lbValue gp = lb_addr_get_ptr(p, gen);
  5780. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5781. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5782. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5783. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5784. return lb_addr_load(p, gen);
  5785. }
  5786. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5787. // @QuaternionLayout
  5788. Type *ft = base_complex_elem_type(dst);
  5789. lbAddr gen = lb_add_local_generated(p, dst, false);
  5790. lbValue gp = lb_addr_get_ptr(p, gen);
  5791. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5792. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5793. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5794. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5795. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5796. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5797. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5798. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5799. return lb_addr_load(p, gen);
  5800. }
  5801. if (is_type_float(src) && is_type_complex(dst)) {
  5802. Type *ft = base_complex_elem_type(dst);
  5803. lbAddr gen = lb_add_local_generated(p, dst, true);
  5804. lbValue gp = lb_addr_get_ptr(p, gen);
  5805. lbValue real = lb_emit_conv(p, value, ft);
  5806. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5807. return lb_addr_load(p, gen);
  5808. }
  5809. if (is_type_float(src) && is_type_quaternion(dst)) {
  5810. Type *ft = base_complex_elem_type(dst);
  5811. lbAddr gen = lb_add_local_generated(p, dst, true);
  5812. lbValue gp = lb_addr_get_ptr(p, gen);
  5813. lbValue real = lb_emit_conv(p, value, ft);
  5814. // @QuaternionLayout
  5815. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5816. return lb_addr_load(p, gen);
  5817. }
  5818. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5819. Type *ft = base_complex_elem_type(dst);
  5820. lbAddr gen = lb_add_local_generated(p, dst, true);
  5821. lbValue gp = lb_addr_get_ptr(p, gen);
  5822. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5823. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5824. // @QuaternionLayout
  5825. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5826. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5827. return lb_addr_load(p, gen);
  5828. }
  5829. // float <-> integer
  5830. if (is_type_float(src) && is_type_integer(dst)) {
  5831. lbValue res = {};
  5832. res.type = t;
  5833. if (is_type_unsigned(dst)) {
  5834. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5835. } else {
  5836. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5837. }
  5838. return res;
  5839. }
  5840. if (is_type_integer(src) && is_type_float(dst)) {
  5841. lbValue res = {};
  5842. res.type = t;
  5843. if (is_type_unsigned(src)) {
  5844. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5845. } else {
  5846. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5847. }
  5848. return res;
  5849. }
  5850. // Pointer <-> uintptr
  5851. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5852. lbValue res = {};
  5853. res.type = t;
  5854. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5855. return res;
  5856. }
  5857. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5858. lbValue res = {};
  5859. res.type = t;
  5860. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5861. return res;
  5862. }
  5863. #if 1
  5864. if (is_type_union(dst)) {
  5865. for_array(i, dst->Union.variants) {
  5866. Type *vt = dst->Union.variants[i];
  5867. if (are_types_identical(vt, src_type)) {
  5868. lbAddr parent = lb_add_local_generated(p, t, true);
  5869. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5870. return lb_addr_load(p, parent);
  5871. }
  5872. }
  5873. }
  5874. #endif
  5875. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5876. // subtype polymorphism casting
  5877. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5878. Type *st = type_deref(src_type);
  5879. Type *pst = st;
  5880. st = type_deref(st);
  5881. bool st_is_ptr = is_type_pointer(src_type);
  5882. st = base_type(st);
  5883. Type *dt = t;
  5884. bool dt_is_ptr = type_deref(dt) != dt;
  5885. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5886. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  5887. if (field_name.len > 0) {
  5888. // NOTE(bill): It can be casted
  5889. Selection sel = lookup_field(st, field_name, false, true);
  5890. if (sel.entity != nullptr) {
  5891. if (st_is_ptr) {
  5892. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  5893. Type *rt = res.type;
  5894. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5895. res = lb_emit_load(p, res);
  5896. }
  5897. return res;
  5898. } else {
  5899. if (is_type_pointer(value.type)) {
  5900. Type *rt = value.type;
  5901. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5902. value = lb_emit_load(p, value);
  5903. } else {
  5904. value = lb_emit_deep_field_gep(p, value, sel);
  5905. return lb_emit_load(p, value);
  5906. }
  5907. }
  5908. return lb_emit_deep_field_ev(p, value, sel);
  5909. }
  5910. } else {
  5911. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5912. }
  5913. }
  5914. }
  5915. // Pointer <-> Pointer
  5916. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5917. lbValue res = {};
  5918. res.type = t;
  5919. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5920. return res;
  5921. }
  5922. // proc <-> proc
  5923. if (is_type_proc(src) && is_type_proc(dst)) {
  5924. lbValue res = {};
  5925. res.type = t;
  5926. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5927. return res;
  5928. }
  5929. // pointer -> proc
  5930. if (is_type_pointer(src) && is_type_proc(dst)) {
  5931. lbValue res = {};
  5932. res.type = t;
  5933. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5934. return res;
  5935. }
  5936. // proc -> pointer
  5937. if (is_type_proc(src) && is_type_pointer(dst)) {
  5938. lbValue res = {};
  5939. res.type = t;
  5940. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5941. return res;
  5942. }
  5943. // []byte/[]u8 <-> string
  5944. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5945. return lb_emit_transmute(p, value, t);
  5946. }
  5947. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5948. return lb_emit_transmute(p, value, t);
  5949. }
  5950. if (is_type_array(dst)) {
  5951. Type *elem = dst->Array.elem;
  5952. lbValue e = lb_emit_conv(p, value, elem);
  5953. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5954. lbAddr v = lb_add_local_generated(p, t, false);
  5955. isize index_count = cast(isize)dst->Array.count;
  5956. for (isize i = 0; i < index_count; i++) {
  5957. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  5958. lb_emit_store(p, elem, e);
  5959. }
  5960. return lb_addr_load(p, v);
  5961. }
  5962. if (is_type_any(dst)) {
  5963. if (is_type_untyped_nil(src)) {
  5964. return lb_const_nil(p->module, t);
  5965. }
  5966. if (is_type_untyped_undef(src)) {
  5967. return lb_const_undef(p->module, t);
  5968. }
  5969. lbAddr result = lb_add_local_generated(p, t, true);
  5970. Type *st = default_type(src_type);
  5971. lbValue data = lb_address_from_load_or_generate_local(p, value);
  5972. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  5973. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5974. data = lb_emit_conv(p, data, t_rawptr);
  5975. lbValue id = lb_typeid(p->module, st);
  5976. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  5977. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  5978. lb_emit_store(p, any_data, data);
  5979. lb_emit_store(p, any_id, id);
  5980. return lb_addr_load(p, result);
  5981. }
  5982. i64 src_sz = type_size_of(src);
  5983. i64 dst_sz = type_size_of(dst);
  5984. if (src_sz == dst_sz) {
  5985. // bit_set <-> integer
  5986. if (is_type_integer(src) && is_type_bit_set(dst)) {
  5987. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  5988. res.type = dst;
  5989. return res;
  5990. }
  5991. if (is_type_bit_set(src) && is_type_integer(dst)) {
  5992. lbValue bs = value;
  5993. bs.type = bit_set_to_int(src);
  5994. return lb_emit_conv(p, bs, dst);
  5995. }
  5996. // typeid <-> integer
  5997. if (is_type_integer(src) && is_type_typeid(dst)) {
  5998. return lb_emit_transmute(p, value, dst);
  5999. }
  6000. if (is_type_typeid(src) && is_type_integer(dst)) {
  6001. return lb_emit_transmute(p, value, dst);
  6002. }
  6003. }
  6004. if (is_type_untyped(src)) {
  6005. if (is_type_string(src) && is_type_string(dst)) {
  6006. lbAddr result = lb_add_local_generated(p, t, false);
  6007. lb_addr_store(p, result, value);
  6008. return lb_addr_load(p, result);
  6009. }
  6010. }
  6011. gb_printf_err("%.*s\n", LIT(p->name));
  6012. gb_printf_err("lb_emit_conv: src -> dst\n");
  6013. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  6014. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  6015. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  6016. gb_printf_err("Not Identical %p != %p\n", src, dst);
  6017. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  6018. type_to_string(src_type), type_to_string(t),
  6019. LIT(p->name));
  6020. return {};
  6021. }
  6022. bool lb_is_type_aggregate(Type *t) {
  6023. t = base_type(t);
  6024. switch (t->kind) {
  6025. case Type_Basic:
  6026. switch (t->Basic.kind) {
  6027. case Basic_string:
  6028. case Basic_any:
  6029. return true;
  6030. // case Basic_complex32:
  6031. case Basic_complex64:
  6032. case Basic_complex128:
  6033. case Basic_quaternion128:
  6034. case Basic_quaternion256:
  6035. return true;
  6036. }
  6037. break;
  6038. case Type_Pointer:
  6039. return false;
  6040. case Type_Array:
  6041. case Type_Slice:
  6042. case Type_Struct:
  6043. case Type_Union:
  6044. case Type_Tuple:
  6045. case Type_DynamicArray:
  6046. case Type_Map:
  6047. case Type_SimdVector:
  6048. return true;
  6049. case Type_Named:
  6050. return lb_is_type_aggregate(t->Named.base);
  6051. }
  6052. return false;
  6053. }
  6054. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  6055. Type *src_type = value.type;
  6056. if (are_types_identical(t, src_type)) {
  6057. return value;
  6058. }
  6059. lbValue res = {};
  6060. res.type = t;
  6061. Type *src = base_type(src_type);
  6062. Type *dst = base_type(t);
  6063. lbModule *m = p->module;
  6064. i64 sz = type_size_of(src);
  6065. i64 dz = type_size_of(dst);
  6066. if (sz != dz) {
  6067. LLVMTypeRef s = lb_type(m, src);
  6068. LLVMTypeRef d = lb_type(m, dst);
  6069. i64 llvm_sz = lb_sizeof(s);
  6070. i64 llvm_dz = lb_sizeof(d);
  6071. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  6072. }
  6073. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  6074. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  6075. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6076. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6077. return res;
  6078. }
  6079. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6080. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6081. return res;
  6082. }
  6083. if (is_type_uintptr(src) && is_type_proc(dst)) {
  6084. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6085. return res;
  6086. }
  6087. if (is_type_proc(src) && is_type_uintptr(dst)) {
  6088. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6089. return res;
  6090. }
  6091. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  6092. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6093. return res;
  6094. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  6095. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6096. return res;
  6097. }
  6098. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6099. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  6100. return res;
  6101. }
  6102. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  6103. lbValue s = lb_address_from_load_or_generate_local(p, value);
  6104. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  6105. return lb_emit_load(p, d);
  6106. }
  6107. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  6108. // GB_PANIC("lb_emit_transmute");
  6109. return res;
  6110. }
  6111. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  6112. GB_ASSERT(addr.kind == lbAddr_Context);
  6113. GB_ASSERT(addr.ctx.sel.index.count == 0);
  6114. lbModule *m = p->module;
  6115. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6116. args[0] = addr.addr;
  6117. lb_emit_runtime_call(p, "__init_context", args);
  6118. }
  6119. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  6120. Type *pt = base_type(p->type);
  6121. GB_ASSERT(pt->kind == Type_Proc);
  6122. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  6123. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  6124. e->flags |= EntityFlag_NoAlias;
  6125. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  6126. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  6127. lbValue param = {context_ptr, e->type};
  6128. lb_add_entity(p->module, e, param);
  6129. lbAddr ctx_addr = {};
  6130. ctx_addr.kind = lbAddr_Context;
  6131. ctx_addr.addr = param;
  6132. lbContextData *cd = array_add_and_get(&p->context_stack);
  6133. cd->ctx = ctx_addr;
  6134. cd->scope_index = -1;
  6135. return cd;
  6136. }
  6137. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  6138. ctx.kind = lbAddr_Context;
  6139. lbContextData *cd = array_add_and_get(&p->context_stack);
  6140. cd->ctx = ctx;
  6141. cd->scope_index = p->scope_index;
  6142. return cd;
  6143. }
  6144. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  6145. if (p->context_stack.count > 0) {
  6146. return p->context_stack[p->context_stack.count-1].ctx;
  6147. }
  6148. Type *pt = base_type(p->type);
  6149. GB_ASSERT(pt->kind == Type_Proc);
  6150. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  6151. lbAddr c = lb_add_local_generated(p, t_context, true);
  6152. c.kind = lbAddr_Context;
  6153. lb_emit_init_context(p, c);
  6154. lb_push_context_onto_stack(p, c);
  6155. lb_add_debug_context_variable(p, c);
  6156. return c;
  6157. }
  6158. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  6159. if (LLVMIsALoadInst(value.value)) {
  6160. lbValue res = {};
  6161. res.value = LLVMGetOperand(value.value, 0);
  6162. res.type = alloc_type_pointer(value.type);
  6163. return res;
  6164. }
  6165. GB_ASSERT(is_type_typed(value.type));
  6166. lbAddr res = lb_add_local_generated(p, value.type, false);
  6167. lb_addr_store(p, res, value);
  6168. return res.addr;
  6169. }
  6170. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  6171. if (LLVMIsALoadInst(value.value)) {
  6172. lbValue res = {};
  6173. res.value = LLVMGetOperand(value.value, 0);
  6174. res.type = alloc_type_pointer(value.type);
  6175. return res;
  6176. }
  6177. GB_PANIC("lb_address_from_load");
  6178. return {};
  6179. }
  6180. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  6181. i64 type_alignment = type_align_of(new_type);
  6182. if (alignment < type_alignment) {
  6183. alignment = type_alignment;
  6184. }
  6185. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  6186. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  6187. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  6188. lb_addr_store(p, ptr, val);
  6189. // ptr.kind = lbAddr_Context;
  6190. return ptr.addr;
  6191. }
  6192. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  6193. GB_ASSERT(is_type_pointer(s.type));
  6194. Type *t = base_type(type_deref(s.type));
  6195. Type *result_type = nullptr;
  6196. if (is_type_relative_pointer(t)) {
  6197. s = lb_addr_get_ptr(p, lb_addr(s));
  6198. }
  6199. if (is_type_struct(t)) {
  6200. result_type = get_struct_field_type(t, index);
  6201. } else if (is_type_union(t)) {
  6202. GB_ASSERT(index == -1);
  6203. return lb_emit_union_tag_ptr(p, s);
  6204. } else if (is_type_tuple(t)) {
  6205. GB_ASSERT(t->Tuple.variables.count > 0);
  6206. result_type = t->Tuple.variables[index]->type;
  6207. } else if (is_type_complex(t)) {
  6208. Type *ft = base_complex_elem_type(t);
  6209. switch (index) {
  6210. case 0: result_type = ft; break;
  6211. case 1: result_type = ft; break;
  6212. }
  6213. } else if (is_type_quaternion(t)) {
  6214. Type *ft = base_complex_elem_type(t);
  6215. switch (index) {
  6216. case 0: result_type = ft; break;
  6217. case 1: result_type = ft; break;
  6218. case 2: result_type = ft; break;
  6219. case 3: result_type = ft; break;
  6220. }
  6221. } else if (is_type_slice(t)) {
  6222. switch (index) {
  6223. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6224. case 1: result_type = t_int; break;
  6225. }
  6226. } else if (is_type_string(t)) {
  6227. switch (index) {
  6228. case 0: result_type = t_u8_ptr; break;
  6229. case 1: result_type = t_int; break;
  6230. }
  6231. } else if (is_type_any(t)) {
  6232. switch (index) {
  6233. case 0: result_type = t_rawptr; break;
  6234. case 1: result_type = t_typeid; break;
  6235. }
  6236. } else if (is_type_dynamic_array(t)) {
  6237. switch (index) {
  6238. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6239. case 1: result_type = t_int; break;
  6240. case 2: result_type = t_int; break;
  6241. case 3: result_type = t_allocator; break;
  6242. }
  6243. } else if (is_type_map(t)) {
  6244. init_map_internal_types(t);
  6245. Type *itp = alloc_type_pointer(t->Map.internal_type);
  6246. s = lb_emit_transmute(p, s, itp);
  6247. Type *gst = t->Map.internal_type;
  6248. GB_ASSERT(gst->kind == Type_Struct);
  6249. switch (index) {
  6250. case 0: result_type = get_struct_field_type(gst, 0); break;
  6251. case 1: result_type = get_struct_field_type(gst, 1); break;
  6252. }
  6253. } else if (is_type_array(t)) {
  6254. return lb_emit_array_epi(p, s, index);
  6255. } else if (is_type_relative_slice(t)) {
  6256. switch (index) {
  6257. case 0: result_type = t->RelativeSlice.base_integer; break;
  6258. case 1: result_type = t->RelativeSlice.base_integer; break;
  6259. }
  6260. } else {
  6261. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  6262. }
  6263. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  6264. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6265. index += 1;
  6266. }
  6267. if (lb_is_const(s)) {
  6268. lbModule *m = p->module;
  6269. lbValue res = {};
  6270. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  6271. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6272. res.type = alloc_type_pointer(result_type);
  6273. return res;
  6274. } else {
  6275. lbValue res = {};
  6276. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  6277. res.type = alloc_type_pointer(result_type);
  6278. return res;
  6279. }
  6280. }
  6281. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  6282. if (LLVMIsALoadInst(s.value)) {
  6283. lbValue res = {};
  6284. res.value = LLVMGetOperand(s.value, 0);
  6285. res.type = alloc_type_pointer(s.type);
  6286. lbValue ptr = lb_emit_struct_ep(p, res, index);
  6287. return lb_emit_load(p, ptr);
  6288. }
  6289. Type *t = base_type(s.type);
  6290. Type *result_type = nullptr;
  6291. switch (t->kind) {
  6292. case Type_Basic:
  6293. switch (t->Basic.kind) {
  6294. case Basic_string:
  6295. switch (index) {
  6296. case 0: result_type = t_u8_ptr; break;
  6297. case 1: result_type = t_int; break;
  6298. }
  6299. break;
  6300. case Basic_any:
  6301. switch (index) {
  6302. case 0: result_type = t_rawptr; break;
  6303. case 1: result_type = t_typeid; break;
  6304. }
  6305. break;
  6306. case Basic_complex64: case Basic_complex128:
  6307. {
  6308. Type *ft = base_complex_elem_type(t);
  6309. switch (index) {
  6310. case 0: result_type = ft; break;
  6311. case 1: result_type = ft; break;
  6312. }
  6313. break;
  6314. }
  6315. case Basic_quaternion128: case Basic_quaternion256:
  6316. {
  6317. Type *ft = base_complex_elem_type(t);
  6318. switch (index) {
  6319. case 0: result_type = ft; break;
  6320. case 1: result_type = ft; break;
  6321. case 2: result_type = ft; break;
  6322. case 3: result_type = ft; break;
  6323. }
  6324. break;
  6325. }
  6326. }
  6327. break;
  6328. case Type_Struct:
  6329. result_type = get_struct_field_type(t, index);
  6330. break;
  6331. case Type_Union:
  6332. GB_ASSERT(index == -1);
  6333. // return lb_emit_union_tag_value(p, s);
  6334. GB_PANIC("lb_emit_union_tag_value");
  6335. case Type_Tuple:
  6336. GB_ASSERT(t->Tuple.variables.count > 0);
  6337. result_type = t->Tuple.variables[index]->type;
  6338. if (t->Tuple.variables.count == 1) {
  6339. return s;
  6340. }
  6341. break;
  6342. case Type_Slice:
  6343. switch (index) {
  6344. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6345. case 1: result_type = t_int; break;
  6346. }
  6347. break;
  6348. case Type_DynamicArray:
  6349. switch (index) {
  6350. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6351. case 1: result_type = t_int; break;
  6352. case 2: result_type = t_int; break;
  6353. case 3: result_type = t_allocator; break;
  6354. }
  6355. break;
  6356. case Type_Map:
  6357. {
  6358. init_map_internal_types(t);
  6359. Type *gst = t->Map.generated_struct_type;
  6360. switch (index) {
  6361. case 0: result_type = get_struct_field_type(gst, 0); break;
  6362. case 1: result_type = get_struct_field_type(gst, 1); break;
  6363. }
  6364. }
  6365. break;
  6366. case Type_Array:
  6367. result_type = t->Array.elem;
  6368. break;
  6369. default:
  6370. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  6371. break;
  6372. }
  6373. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  6374. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6375. index += 1;
  6376. }
  6377. lbValue res = {};
  6378. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  6379. res.type = result_type;
  6380. return res;
  6381. }
  6382. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  6383. GB_ASSERT(sel.index.count > 0);
  6384. Type *type = type_deref(e.type);
  6385. for_array(i, sel.index) {
  6386. i32 index = cast(i32)sel.index[i];
  6387. if (is_type_pointer(type)) {
  6388. type = type_deref(type);
  6389. e = lb_emit_load(p, e);
  6390. }
  6391. type = core_type(type);
  6392. if (is_type_quaternion(type)) {
  6393. e = lb_emit_struct_ep(p, e, index);
  6394. } else if (is_type_raw_union(type)) {
  6395. type = get_struct_field_type(type, index);
  6396. GB_ASSERT(is_type_pointer(e.type));
  6397. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  6398. } else if (is_type_struct(type)) {
  6399. type = get_struct_field_type(type, index);
  6400. e = lb_emit_struct_ep(p, e, index);
  6401. } else if (type->kind == Type_Union) {
  6402. GB_ASSERT(index == -1);
  6403. type = t_type_info_ptr;
  6404. e = lb_emit_struct_ep(p, e, index);
  6405. } else if (type->kind == Type_Tuple) {
  6406. type = type->Tuple.variables[index]->type;
  6407. e = lb_emit_struct_ep(p, e, index);
  6408. } else if (type->kind == Type_Basic) {
  6409. switch (type->Basic.kind) {
  6410. case Basic_any: {
  6411. if (index == 0) {
  6412. type = t_rawptr;
  6413. } else if (index == 1) {
  6414. type = t_type_info_ptr;
  6415. }
  6416. e = lb_emit_struct_ep(p, e, index);
  6417. break;
  6418. }
  6419. case Basic_string:
  6420. e = lb_emit_struct_ep(p, e, index);
  6421. break;
  6422. default:
  6423. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6424. break;
  6425. }
  6426. } else if (type->kind == Type_Slice) {
  6427. e = lb_emit_struct_ep(p, e, index);
  6428. } else if (type->kind == Type_DynamicArray) {
  6429. e = lb_emit_struct_ep(p, e, index);
  6430. } else if (type->kind == Type_Array) {
  6431. e = lb_emit_array_epi(p, e, index);
  6432. } else if (type->kind == Type_Map) {
  6433. e = lb_emit_struct_ep(p, e, index);
  6434. } else if (type->kind == Type_RelativePointer) {
  6435. e = lb_emit_struct_ep(p, e, index);
  6436. } else {
  6437. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6438. }
  6439. }
  6440. return e;
  6441. }
  6442. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6443. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6444. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6445. return lb_emit_load(p, res);
  6446. }
  6447. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  6448. // NOTE(bill): The prev block may defer injection before it's terminator
  6449. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6450. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6451. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6452. return;
  6453. }
  6454. isize prev_context_stack_count = p->context_stack.count;
  6455. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  6456. defer (p->context_stack.count = prev_context_stack_count);
  6457. p->context_stack.count = d.context_stack_count;
  6458. lbBlock *b = lb_create_block(p, "defer");
  6459. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6460. lb_emit_jump(p, b);
  6461. }
  6462. lb_start_block(p, b);
  6463. if (d.kind == lbDefer_Node) {
  6464. lb_build_stmt(p, d.stmt);
  6465. } else if (d.kind == lbDefer_Instr) {
  6466. // NOTE(bill): Need to make a new copy
  6467. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6468. LLVMInsertIntoBuilder(p->builder, instr);
  6469. } else if (d.kind == lbDefer_Proc) {
  6470. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6471. }
  6472. }
  6473. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6474. isize count = p->defer_stmts.count;
  6475. isize i = count;
  6476. while (i --> 0) {
  6477. lbDefer const &d = p->defer_stmts[i];
  6478. if (kind == lbDeferExit_Default) {
  6479. if (p->scope_index == d.scope_index &&
  6480. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6481. lb_build_defer_stmt(p, d);
  6482. array_pop(&p->defer_stmts);
  6483. continue;
  6484. } else {
  6485. break;
  6486. }
  6487. } else if (kind == lbDeferExit_Return) {
  6488. lb_build_defer_stmt(p, d);
  6489. } else if (kind == lbDeferExit_Branch) {
  6490. GB_ASSERT(block != nullptr);
  6491. isize lower_limit = block->scope_index;
  6492. if (lower_limit < d.scope_index) {
  6493. lb_build_defer_stmt(p, d);
  6494. }
  6495. }
  6496. }
  6497. }
  6498. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  6499. Type *pt = base_type(p->type);
  6500. GB_ASSERT(pt->kind == Type_Proc);
  6501. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6502. GB_ASSERT(p->context_stack.count != 0);
  6503. }
  6504. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6505. d->kind = lbDefer_Node;
  6506. d->scope_index = scope_index;
  6507. d->context_stack_count = p->context_stack.count;
  6508. d->block = p->curr_block;
  6509. d->stmt = stmt;
  6510. }
  6511. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  6512. Type *pt = base_type(p->type);
  6513. GB_ASSERT(pt->kind == Type_Proc);
  6514. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6515. GB_ASSERT(p->context_stack.count != 0);
  6516. }
  6517. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6518. d->kind = lbDefer_Proc;
  6519. d->scope_index = p->scope_index;
  6520. d->block = p->curr_block;
  6521. d->context_stack_count = p->context_stack.count;
  6522. d->proc.deferred = deferred;
  6523. d->proc.result_as_args = result_as_args;
  6524. }
  6525. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  6526. Array<lbValue> array = {};
  6527. Type *t = base_type(value.type);
  6528. if (t == nullptr) {
  6529. // Do nothing
  6530. } else if (is_type_tuple(t)) {
  6531. GB_ASSERT(t->kind == Type_Tuple);
  6532. auto *rt = &t->Tuple;
  6533. if (rt->variables.count > 0) {
  6534. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  6535. for_array(i, rt->variables) {
  6536. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  6537. array[i] = elem;
  6538. }
  6539. }
  6540. } else {
  6541. array = array_make<lbValue>(permanent_allocator(), 1);
  6542. array[0] = value;
  6543. }
  6544. return array;
  6545. }
  6546. 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) {
  6547. unsigned arg_count = cast(unsigned)processed_args.count;
  6548. if (return_ptr.value != nullptr) {
  6549. arg_count += 1;
  6550. }
  6551. if (context_ptr.addr.value != nullptr) {
  6552. arg_count += 1;
  6553. }
  6554. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  6555. isize arg_index = 0;
  6556. if (return_ptr.value != nullptr) {
  6557. args[arg_index++] = return_ptr.value;
  6558. }
  6559. for_array(i, processed_args) {
  6560. lbValue arg = processed_args[i];
  6561. args[arg_index++] = arg.value;
  6562. }
  6563. if (context_ptr.addr.value != nullptr) {
  6564. LLVMValueRef cp = context_ptr.addr.value;
  6565. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  6566. args[arg_index++] = cp;
  6567. }
  6568. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  6569. GB_ASSERT(curr_block != p->decl_block->block);
  6570. {
  6571. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6572. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6573. LLVMValueRef fn = value.value;
  6574. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6575. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6576. }
  6577. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6578. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6579. LLVMValueRef ret = LLVMBuildCall2(p->builder, ft, fn, args, arg_count, "");;
  6580. lbValue res = {};
  6581. res.value = ret;
  6582. res.type = abi_rt;
  6583. return res;
  6584. }
  6585. }
  6586. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6587. // LLVMMetadataRef curr_loc = LLVMGetCurrentDebugLocation2(p->builder);
  6588. // LLVMSetCurrentDebugLocation2(p->builder, nullptr);
  6589. // defer (if (curr_loc) {
  6590. // LLVMSetCurrentDebugLocation2(p->builder, curr_loc);
  6591. // });
  6592. String name = make_string_c(c_name);
  6593. AstPackage *pkg = p->module->info->runtime_package;
  6594. Entity *e = scope_lookup_current(pkg->scope, name);
  6595. lbValue *found = nullptr;
  6596. if (p->module != e->code_gen_module) {
  6597. gb_mutex_lock(&p->module->mutex);
  6598. }
  6599. GB_ASSERT(e->code_gen_module != nullptr);
  6600. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6601. if (p->module != e->code_gen_module) {
  6602. gb_mutex_unlock(&p->module->mutex);
  6603. }
  6604. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6605. return lb_emit_call(p, *found, args);
  6606. }
  6607. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6608. lbModule *m = p->module;
  6609. Type *pt = base_type(value.type);
  6610. GB_ASSERT(pt->kind == Type_Proc);
  6611. Type *results = pt->Proc.results;
  6612. if (p->entity != nullptr) {
  6613. if (p->entity->flags & EntityFlag_Disabled) {
  6614. return {};
  6615. }
  6616. }
  6617. lbAddr context_ptr = {};
  6618. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6619. context_ptr = lb_find_or_generate_context_ptr(p);
  6620. }
  6621. defer (if (pt->Proc.diverging) {
  6622. LLVMBuildUnreachable(p->builder);
  6623. });
  6624. set_procedure_abi_types(pt);
  6625. bool is_c_vararg = pt->Proc.c_vararg;
  6626. isize param_count = pt->Proc.param_count;
  6627. if (is_c_vararg) {
  6628. GB_ASSERT(param_count-1 <= args.count);
  6629. param_count -= 1;
  6630. } else {
  6631. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6632. }
  6633. lbValue result = {};
  6634. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6635. {
  6636. lbFunctionType **ft_found = nullptr;
  6637. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6638. if (!ft_found) {
  6639. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6640. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6641. }
  6642. GB_ASSERT(ft_found != nullptr);
  6643. lbFunctionType *ft = *ft_found;
  6644. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6645. unsigned param_index = 0;
  6646. for (isize i = 0; i < param_count; i++) {
  6647. Entity *e = pt->Proc.params->Tuple.variables[i];
  6648. if (e->kind != Entity_Variable) {
  6649. continue;
  6650. }
  6651. GB_ASSERT(e->flags & EntityFlag_Param);
  6652. Type *original_type = e->type;
  6653. lbArgType *arg = &ft->args[param_index];
  6654. if (arg->kind == lbArg_Ignore) {
  6655. continue;
  6656. }
  6657. lbValue x = lb_emit_conv(p, args[i], original_type);
  6658. LLVMTypeRef xt = lb_type(p->module, x.type);
  6659. if (arg->kind == lbArg_Direct) {
  6660. LLVMTypeRef abi_type = arg->cast_type;
  6661. if (!abi_type) {
  6662. abi_type = arg->type;
  6663. }
  6664. if (xt == abi_type) {
  6665. array_add(&processed_args, x);
  6666. } else {
  6667. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6668. array_add(&processed_args, x);
  6669. }
  6670. } else if (arg->kind == lbArg_Indirect) {
  6671. lbValue ptr = {};
  6672. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6673. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6674. // i.e. `T const &` in C++
  6675. ptr = lb_address_from_load_or_generate_local(p, x);
  6676. } else {
  6677. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6678. }
  6679. array_add(&processed_args, ptr);
  6680. }
  6681. param_index += 1;
  6682. }
  6683. if (inlining == ProcInlining_none) {
  6684. inlining = p->inlining;
  6685. }
  6686. Type *rt = reduce_tuple_to_single_type(results);
  6687. if (return_by_pointer) {
  6688. lbValue return_ptr = {};
  6689. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6690. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6691. return_ptr = p->return_ptr_hint_value;
  6692. p->return_ptr_hint_used = true;
  6693. }
  6694. }
  6695. if (return_ptr.value == nullptr) {
  6696. lbAddr r = lb_add_local_generated(p, rt, true);
  6697. return_ptr = r.addr;
  6698. }
  6699. GB_ASSERT(is_type_pointer(return_ptr.type));
  6700. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6701. result = lb_emit_load(p, return_ptr);
  6702. } else if (rt != nullptr) {
  6703. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  6704. if (ft->ret.cast_type) {
  6705. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  6706. }
  6707. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  6708. result.type = rt;
  6709. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  6710. result.type = t_llvm_bool;
  6711. }
  6712. if (!is_type_tuple(rt)) {
  6713. result = lb_emit_conv(p, result, rt);
  6714. }
  6715. } else {
  6716. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  6717. }
  6718. }
  6719. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6720. if (found != nullptr) {
  6721. Entity *e = *found;
  6722. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6723. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6724. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6725. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6726. GB_ASSERT(deferred_found != nullptr);
  6727. lbValue deferred = *deferred_found;
  6728. auto in_args = args;
  6729. Array<lbValue> result_as_args = {};
  6730. switch (kind) {
  6731. case DeferredProcedure_none:
  6732. break;
  6733. case DeferredProcedure_in:
  6734. result_as_args = in_args;
  6735. break;
  6736. case DeferredProcedure_out:
  6737. result_as_args = lb_value_to_array(p, result);
  6738. break;
  6739. case DeferredProcedure_in_out:
  6740. {
  6741. auto out_args = lb_value_to_array(p, result);
  6742. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  6743. array_copy(&result_as_args, in_args, 0);
  6744. array_copy(&result_as_args, out_args, in_args.count);
  6745. }
  6746. break;
  6747. }
  6748. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6749. }
  6750. }
  6751. return result;
  6752. }
  6753. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6754. Type *t = s.type;
  6755. GB_ASSERT(is_type_pointer(t));
  6756. Type *st = base_type(type_deref(t));
  6757. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6758. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6759. LLVMValueRef indices[2] = {};
  6760. indices[0] = llvm_zero(p->module);
  6761. indices[1] = lb_emit_conv(p, index, t_int).value;
  6762. Type *ptr = base_array_type(st);
  6763. lbValue res = {};
  6764. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6765. res.type = alloc_type_pointer(ptr);
  6766. return res;
  6767. }
  6768. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6769. Type *t = s.type;
  6770. GB_ASSERT(is_type_pointer(t));
  6771. Type *st = base_type(type_deref(t));
  6772. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6773. GB_ASSERT(0 <= index);
  6774. Type *ptr = base_array_type(st);
  6775. LLVMValueRef indices[2] = {
  6776. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6777. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6778. };
  6779. lbValue res = {};
  6780. if (lb_is_const(s)) {
  6781. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6782. } else {
  6783. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6784. }
  6785. res.type = alloc_type_pointer(ptr);
  6786. return res;
  6787. }
  6788. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6789. LLVMValueRef indices[1] = {index.value};
  6790. lbValue res = {};
  6791. res.type = ptr.type;
  6792. if (lb_is_const(ptr) && lb_is_const(index)) {
  6793. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6794. } else {
  6795. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6796. }
  6797. return res;
  6798. }
  6799. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  6800. GB_ASSERT(is_type_pointer(data.type));
  6801. GB_ASSERT(are_types_identical(len.type, t_int));
  6802. LLVMValueRef vals[2] = {
  6803. data.value,
  6804. len.value,
  6805. };
  6806. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  6807. }
  6808. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6809. Type *t = lb_addr_type(slice);
  6810. GB_ASSERT(is_type_slice(t));
  6811. lbValue ptr = lb_addr_get_ptr(p, slice);
  6812. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6813. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6814. }
  6815. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6816. Type *t = lb_addr_type(string);
  6817. GB_ASSERT(is_type_string(t));
  6818. lbValue ptr = lb_addr_get_ptr(p, string);
  6819. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6820. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6821. }
  6822. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6823. Type *t = base_type(string.type);
  6824. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6825. return lb_emit_struct_ev(p, string, 0);
  6826. }
  6827. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6828. Type *t = base_type(string.type);
  6829. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6830. return lb_emit_struct_ev(p, string, 1);
  6831. }
  6832. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6833. GB_ASSERT(is_type_cstring(value.type));
  6834. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6835. args[0] = lb_emit_conv(p, value, t_cstring);
  6836. return lb_emit_runtime_call(p, "cstring_len", args);
  6837. }
  6838. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6839. Type *t = type_deref(array_ptr.type);
  6840. GB_ASSERT(is_type_array(t));
  6841. return lb_emit_struct_ep(p, array_ptr, 0);
  6842. }
  6843. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6844. GB_ASSERT(is_type_slice(slice.type));
  6845. return lb_emit_struct_ev(p, slice, 0);
  6846. }
  6847. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6848. GB_ASSERT(is_type_slice(slice.type));
  6849. return lb_emit_struct_ev(p, slice, 1);
  6850. }
  6851. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6852. GB_ASSERT(is_type_dynamic_array(da.type));
  6853. return lb_emit_struct_ev(p, da, 0);
  6854. }
  6855. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6856. GB_ASSERT(is_type_dynamic_array(da.type));
  6857. return lb_emit_struct_ev(p, da, 1);
  6858. }
  6859. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6860. GB_ASSERT(is_type_dynamic_array(da.type));
  6861. return lb_emit_struct_ev(p, da, 2);
  6862. }
  6863. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6864. GB_ASSERT(is_type_dynamic_array(da.type));
  6865. return lb_emit_struct_ev(p, da, 3);
  6866. }
  6867. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6868. Type *t = base_type(value.type);
  6869. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6870. init_map_internal_types(t);
  6871. Type *gst = t->Map.generated_struct_type;
  6872. i32 index = 1;
  6873. lbValue entries = lb_emit_struct_ev(p, value, index);
  6874. return entries;
  6875. }
  6876. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6877. Type *t = base_type(type_deref(value.type));
  6878. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6879. init_map_internal_types(t);
  6880. Type *gst = t->Map.generated_struct_type;
  6881. i32 index = 1;
  6882. lbValue entries = lb_emit_struct_ep(p, value, index);
  6883. return entries;
  6884. }
  6885. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  6886. lbValue entries = lb_map_entries(p, value);
  6887. return lb_dynamic_array_len(p, entries);
  6888. }
  6889. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  6890. lbValue entries = lb_map_entries(p, value);
  6891. return lb_dynamic_array_cap(p, entries);
  6892. }
  6893. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  6894. Type *t = base_type(value.type);
  6895. bool is_ptr = false;
  6896. if (is_type_pointer(t)) {
  6897. is_ptr = true;
  6898. t = base_type(type_deref(t));
  6899. }
  6900. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6901. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6902. }
  6903. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  6904. t->Struct.soa_kind == StructSoa_Dynamic);
  6905. isize n = 0;
  6906. Type *elem = base_type(t->Struct.soa_elem);
  6907. if (elem->kind == Type_Struct) {
  6908. n = elem->Struct.fields.count;
  6909. } else if (elem->kind == Type_Array) {
  6910. n = elem->Array.count;
  6911. } else {
  6912. GB_PANIC("Unreachable");
  6913. }
  6914. if (is_ptr) {
  6915. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6916. return lb_emit_load(p, v);
  6917. }
  6918. return lb_emit_struct_ev(p, value, cast(i32)n);
  6919. }
  6920. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  6921. Type *t = base_type(value.type);
  6922. bool is_ptr = false;
  6923. if (is_type_pointer(t)) {
  6924. is_ptr = true;
  6925. t = base_type(type_deref(t));
  6926. }
  6927. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6928. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6929. }
  6930. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  6931. isize n = 0;
  6932. Type *elem = base_type(t->Struct.soa_elem);
  6933. if (elem->kind == Type_Struct) {
  6934. n = elem->Struct.fields.count+1;
  6935. } else if (elem->kind == Type_Array) {
  6936. n = elem->Array.count+1;
  6937. } else {
  6938. GB_PANIC("Unreachable");
  6939. }
  6940. if (is_ptr) {
  6941. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6942. return lb_emit_load(p, v);
  6943. }
  6944. return lb_emit_struct_ev(p, value, cast(i32)n);
  6945. }
  6946. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  6947. GB_ASSERT(ce->args.count > 0);
  6948. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  6949. for_array(i, slices) {
  6950. Ast *arg = ce->args[i];
  6951. if (arg->kind == Ast_FieldValue) {
  6952. arg = arg->FieldValue.value;
  6953. }
  6954. slices[i] = lb_build_expr(p, arg);
  6955. }
  6956. lbValue len = lb_slice_len(p, slices[0]);
  6957. for (isize i = 1; i < slices.count; i++) {
  6958. lbValue other_len = lb_slice_len(p, slices[i]);
  6959. len = lb_emit_min(p, t_int, len, other_len);
  6960. }
  6961. GB_ASSERT(is_type_soa_struct(tv.type));
  6962. lbAddr res = lb_add_local_generated(p, tv.type, true);
  6963. for_array(i, slices) {
  6964. lbValue src = lb_slice_elem(p, slices[i]);
  6965. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  6966. lb_emit_store(p, dst, src);
  6967. }
  6968. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  6969. lb_emit_store(p, len_dst, len);
  6970. return lb_addr_load(p, res);
  6971. }
  6972. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  6973. GB_ASSERT(ce->args.count == 1);
  6974. lbValue arg = lb_build_expr(p, ce->args[0]);
  6975. Type *t = base_type(arg.type);
  6976. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  6977. lbValue len = lb_soa_struct_len(p, arg);
  6978. lbAddr res = lb_add_local_generated(p, tv.type, true);
  6979. if (is_type_tuple(tv.type)) {
  6980. lbValue rp = lb_addr_get_ptr(p, res);
  6981. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  6982. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  6983. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  6984. lb_fill_slice(p, dst, ptr, len);
  6985. }
  6986. } else {
  6987. GB_ASSERT(is_type_slice(tv.type));
  6988. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  6989. lb_fill_slice(p, res, ptr, len);
  6990. }
  6991. return lb_addr_load(p, res);
  6992. }
  6993. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  6994. ast_node(ce, CallExpr, expr);
  6995. switch (id) {
  6996. case BuiltinProc_DIRECTIVE: {
  6997. ast_node(bd, BasicDirective, ce->proc);
  6998. String name = bd->name;
  6999. GB_ASSERT(name == "location");
  7000. String procedure = p->entity->token.string;
  7001. TokenPos pos = ast_token(ce->proc).pos;
  7002. if (ce->args.count > 0) {
  7003. Ast *ident = unselector_expr(ce->args[0]);
  7004. GB_ASSERT(ident->kind == Ast_Ident);
  7005. Entity *e = entity_of_node(ident);
  7006. GB_ASSERT(e != nullptr);
  7007. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  7008. procedure = e->parent_proc_decl->entity->token.string;
  7009. } else {
  7010. procedure = str_lit("");
  7011. }
  7012. pos = e->token.pos;
  7013. }
  7014. return lb_emit_source_code_location(p, procedure, pos);
  7015. }
  7016. case BuiltinProc_type_info_of: {
  7017. Ast *arg = ce->args[0];
  7018. TypeAndValue tav = type_and_value_of_expr(arg);
  7019. if (tav.mode == Addressing_Type) {
  7020. Type *t = default_type(type_of_expr(arg));
  7021. return lb_type_info(p->module, t);
  7022. }
  7023. GB_ASSERT(is_type_typeid(tav.type));
  7024. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7025. args[0] = lb_build_expr(p, arg);
  7026. return lb_emit_runtime_call(p, "__type_info_of", args);
  7027. }
  7028. case BuiltinProc_typeid_of: {
  7029. Ast *arg = ce->args[0];
  7030. TypeAndValue tav = type_and_value_of_expr(arg);
  7031. GB_ASSERT(tav.mode == Addressing_Type);
  7032. Type *t = default_type(type_of_expr(arg));
  7033. return lb_typeid(p->module, t);
  7034. }
  7035. case BuiltinProc_len: {
  7036. lbValue v = lb_build_expr(p, ce->args[0]);
  7037. Type *t = base_type(v.type);
  7038. if (is_type_pointer(t)) {
  7039. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7040. v = lb_emit_load(p, v);
  7041. t = type_deref(t);
  7042. }
  7043. if (is_type_cstring(t)) {
  7044. return lb_cstring_len(p, v);
  7045. } else if (is_type_string(t)) {
  7046. return lb_string_len(p, v);
  7047. } else if (is_type_array(t)) {
  7048. GB_PANIC("Array lengths are constant");
  7049. } else if (is_type_slice(t)) {
  7050. return lb_slice_len(p, v);
  7051. } else if (is_type_dynamic_array(t)) {
  7052. return lb_dynamic_array_len(p, v);
  7053. } else if (is_type_map(t)) {
  7054. return lb_map_len(p, v);
  7055. } else if (is_type_soa_struct(t)) {
  7056. return lb_soa_struct_len(p, v);
  7057. }
  7058. GB_PANIC("Unreachable");
  7059. break;
  7060. }
  7061. case BuiltinProc_cap: {
  7062. lbValue v = lb_build_expr(p, ce->args[0]);
  7063. Type *t = base_type(v.type);
  7064. if (is_type_pointer(t)) {
  7065. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7066. v = lb_emit_load(p, v);
  7067. t = type_deref(t);
  7068. }
  7069. if (is_type_string(t)) {
  7070. GB_PANIC("Unreachable");
  7071. } else if (is_type_array(t)) {
  7072. GB_PANIC("Array lengths are constant");
  7073. } else if (is_type_slice(t)) {
  7074. return lb_slice_len(p, v);
  7075. } else if (is_type_dynamic_array(t)) {
  7076. return lb_dynamic_array_cap(p, v);
  7077. } else if (is_type_map(t)) {
  7078. return lb_map_cap(p, v);
  7079. } else if (is_type_soa_struct(t)) {
  7080. return lb_soa_struct_cap(p, v);
  7081. }
  7082. GB_PANIC("Unreachable");
  7083. break;
  7084. }
  7085. case BuiltinProc_swizzle: {
  7086. isize index_count = ce->args.count-1;
  7087. if (is_type_simd_vector(tv.type)) {
  7088. lbValue vec = lb_build_expr(p, ce->args[0]);
  7089. if (index_count == 0) {
  7090. return vec;
  7091. }
  7092. unsigned mask_len = cast(unsigned)index_count;
  7093. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  7094. for (isize i = 1; i < ce->args.count; i++) {
  7095. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7096. GB_ASSERT(is_type_integer(tv.type));
  7097. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7098. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  7099. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  7100. }
  7101. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  7102. LLVMValueRef v1 = vec.value;
  7103. LLVMValueRef v2 = vec.value;
  7104. lbValue res = {};
  7105. res.type = tv.type;
  7106. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  7107. return res;
  7108. }
  7109. lbAddr addr = lb_build_addr(p, ce->args[0]);
  7110. if (index_count == 0) {
  7111. return lb_addr_load(p, addr);
  7112. }
  7113. lbValue src = lb_addr_get_ptr(p, addr);
  7114. // TODO(bill): Should this be zeroed or not?
  7115. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  7116. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  7117. for (i32 i = 1; i < ce->args.count; i++) {
  7118. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7119. GB_ASSERT(is_type_integer(tv.type));
  7120. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7121. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  7122. i32 dst_index = i-1;
  7123. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  7124. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  7125. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  7126. }
  7127. return lb_addr_load(p, dst);
  7128. }
  7129. case BuiltinProc_complex: {
  7130. lbValue real = lb_build_expr(p, ce->args[0]);
  7131. lbValue imag = lb_build_expr(p, ce->args[1]);
  7132. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7133. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7134. Type *ft = base_complex_elem_type(tv.type);
  7135. real = lb_emit_conv(p, real, ft);
  7136. imag = lb_emit_conv(p, imag, ft);
  7137. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  7138. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  7139. return lb_emit_load(p, dst);
  7140. }
  7141. case BuiltinProc_quaternion: {
  7142. lbValue real = lb_build_expr(p, ce->args[0]);
  7143. lbValue imag = lb_build_expr(p, ce->args[1]);
  7144. lbValue jmag = lb_build_expr(p, ce->args[2]);
  7145. lbValue kmag = lb_build_expr(p, ce->args[3]);
  7146. // @QuaternionLayout
  7147. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7148. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7149. Type *ft = base_complex_elem_type(tv.type);
  7150. real = lb_emit_conv(p, real, ft);
  7151. imag = lb_emit_conv(p, imag, ft);
  7152. jmag = lb_emit_conv(p, jmag, ft);
  7153. kmag = lb_emit_conv(p, kmag, ft);
  7154. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  7155. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  7156. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  7157. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  7158. return lb_emit_load(p, dst);
  7159. }
  7160. case BuiltinProc_real: {
  7161. lbValue val = lb_build_expr(p, ce->args[0]);
  7162. if (is_type_complex(val.type)) {
  7163. lbValue real = lb_emit_struct_ev(p, val, 0);
  7164. return lb_emit_conv(p, real, tv.type);
  7165. } else if (is_type_quaternion(val.type)) {
  7166. // @QuaternionLayout
  7167. lbValue real = lb_emit_struct_ev(p, val, 3);
  7168. return lb_emit_conv(p, real, tv.type);
  7169. }
  7170. GB_PANIC("invalid type for real");
  7171. return {};
  7172. }
  7173. case BuiltinProc_imag: {
  7174. lbValue val = lb_build_expr(p, ce->args[0]);
  7175. if (is_type_complex(val.type)) {
  7176. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7177. return lb_emit_conv(p, imag, tv.type);
  7178. } else if (is_type_quaternion(val.type)) {
  7179. // @QuaternionLayout
  7180. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7181. return lb_emit_conv(p, imag, tv.type);
  7182. }
  7183. GB_PANIC("invalid type for imag");
  7184. return {};
  7185. }
  7186. case BuiltinProc_jmag: {
  7187. lbValue val = lb_build_expr(p, ce->args[0]);
  7188. if (is_type_quaternion(val.type)) {
  7189. // @QuaternionLayout
  7190. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7191. return lb_emit_conv(p, imag, tv.type);
  7192. }
  7193. GB_PANIC("invalid type for jmag");
  7194. return {};
  7195. }
  7196. case BuiltinProc_kmag: {
  7197. lbValue val = lb_build_expr(p, ce->args[0]);
  7198. if (is_type_quaternion(val.type)) {
  7199. // @QuaternionLayout
  7200. lbValue imag = lb_emit_struct_ev(p, val, 2);
  7201. return lb_emit_conv(p, imag, tv.type);
  7202. }
  7203. GB_PANIC("invalid type for kmag");
  7204. return {};
  7205. }
  7206. case BuiltinProc_conj: {
  7207. lbValue val = lb_build_expr(p, ce->args[0]);
  7208. lbValue res = {};
  7209. Type *t = val.type;
  7210. if (is_type_complex(t)) {
  7211. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7212. lbValue real = lb_emit_struct_ev(p, val, 0);
  7213. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7214. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7215. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  7216. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  7217. } else if (is_type_quaternion(t)) {
  7218. // @QuaternionLayout
  7219. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7220. lbValue real = lb_emit_struct_ev(p, val, 3);
  7221. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7222. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  7223. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  7224. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7225. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  7226. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  7227. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  7228. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  7229. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  7230. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  7231. }
  7232. return lb_emit_load(p, res);
  7233. }
  7234. case BuiltinProc_expand_to_tuple: {
  7235. lbValue val = lb_build_expr(p, ce->args[0]);
  7236. Type *t = base_type(val.type);
  7237. if (!is_type_tuple(tv.type)) {
  7238. if (t->kind == Type_Struct) {
  7239. GB_ASSERT(t->Struct.fields.count == 1);
  7240. return lb_emit_struct_ev(p, val, 0);
  7241. } else if (t->kind == Type_Array) {
  7242. GB_ASSERT(t->Array.count == 1);
  7243. return lb_emit_array_epi(p, val, 0);
  7244. } else {
  7245. GB_PANIC("Unknown type of expand_to_tuple");
  7246. }
  7247. }
  7248. GB_ASSERT(is_type_tuple(tv.type));
  7249. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7250. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7251. if (t->kind == Type_Struct) {
  7252. for_array(src_index, t->Struct.fields) {
  7253. Entity *field = t->Struct.fields[src_index];
  7254. i32 field_index = field->Variable.field_index;
  7255. lbValue f = lb_emit_struct_ev(p, val, field_index);
  7256. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  7257. lb_emit_store(p, ep, f);
  7258. }
  7259. } else if (t->kind == Type_Array) {
  7260. // TODO(bill): Clean-up this code
  7261. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  7262. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  7263. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  7264. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  7265. lb_emit_store(p, ep, f);
  7266. }
  7267. } else {
  7268. GB_PANIC("Unknown type of expand_to_tuple");
  7269. }
  7270. return lb_emit_load(p, tuple);
  7271. }
  7272. case BuiltinProc_min: {
  7273. Type *t = type_of_expr(expr);
  7274. if (ce->args.count == 2) {
  7275. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7276. } else {
  7277. lbValue x = lb_build_expr(p, ce->args[0]);
  7278. for (isize i = 1; i < ce->args.count; i++) {
  7279. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  7280. }
  7281. return x;
  7282. }
  7283. }
  7284. case BuiltinProc_max: {
  7285. Type *t = type_of_expr(expr);
  7286. if (ce->args.count == 2) {
  7287. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7288. } else {
  7289. lbValue x = lb_build_expr(p, ce->args[0]);
  7290. for (isize i = 1; i < ce->args.count; i++) {
  7291. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  7292. }
  7293. return x;
  7294. }
  7295. }
  7296. case BuiltinProc_abs: {
  7297. lbValue x = lb_build_expr(p, ce->args[0]);
  7298. Type *t = x.type;
  7299. if (is_type_unsigned(t)) {
  7300. return x;
  7301. }
  7302. if (is_type_quaternion(t)) {
  7303. i64 sz = 8*type_size_of(t);
  7304. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7305. args[0] = x;
  7306. switch (sz) {
  7307. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  7308. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  7309. }
  7310. GB_PANIC("Unknown complex type");
  7311. } else if (is_type_complex(t)) {
  7312. i64 sz = 8*type_size_of(t);
  7313. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7314. args[0] = x;
  7315. switch (sz) {
  7316. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  7317. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  7318. }
  7319. GB_PANIC("Unknown complex type");
  7320. } else if (is_type_float(t)) {
  7321. i64 sz = 8*type_size_of(t);
  7322. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7323. args[0] = x;
  7324. switch (sz) {
  7325. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  7326. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  7327. }
  7328. GB_PANIC("Unknown float type");
  7329. }
  7330. lbValue zero = lb_const_nil(p->module, t);
  7331. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  7332. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  7333. return lb_emit_select(p, cond, neg, x);
  7334. }
  7335. case BuiltinProc_clamp:
  7336. return lb_emit_clamp(p, type_of_expr(expr),
  7337. lb_build_expr(p, ce->args[0]),
  7338. lb_build_expr(p, ce->args[1]),
  7339. lb_build_expr(p, ce->args[2]));
  7340. case BuiltinProc_soa_zip:
  7341. return lb_soa_zip(p, ce, tv);
  7342. case BuiltinProc_soa_unzip:
  7343. return lb_soa_unzip(p, ce, tv);
  7344. // "Intrinsics"
  7345. case BuiltinProc_alloca:
  7346. {
  7347. lbValue sz = lb_build_expr(p, ce->args[0]);
  7348. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  7349. lbValue res = {};
  7350. res.type = t_u8_ptr;
  7351. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  7352. LLVMSetAlignment(res.value, cast(unsigned)al);
  7353. return res;
  7354. }
  7355. case BuiltinProc_cpu_relax:
  7356. if (build_context.metrics.arch == TargetArch_386 ||
  7357. build_context.metrics.arch == TargetArch_amd64) {
  7358. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7359. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7360. cast(char *)"pause", 5,
  7361. cast(char *)"", 0,
  7362. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7363. LLVMInlineAsmDialectATT
  7364. );
  7365. GB_ASSERT(the_asm != nullptr);
  7366. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7367. }
  7368. return {};
  7369. case BuiltinProc_atomic_fence:
  7370. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  7371. return {};
  7372. case BuiltinProc_atomic_fence_acq:
  7373. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  7374. return {};
  7375. case BuiltinProc_atomic_fence_rel:
  7376. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  7377. return {};
  7378. case BuiltinProc_atomic_fence_acqrel:
  7379. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  7380. return {};
  7381. case BuiltinProc_volatile_store:
  7382. case BuiltinProc_atomic_store:
  7383. case BuiltinProc_atomic_store_rel:
  7384. case BuiltinProc_atomic_store_relaxed:
  7385. case BuiltinProc_atomic_store_unordered: {
  7386. lbValue dst = lb_build_expr(p, ce->args[0]);
  7387. lbValue val = lb_build_expr(p, ce->args[1]);
  7388. val = lb_emit_conv(p, val, type_deref(dst.type));
  7389. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  7390. switch (id) {
  7391. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  7392. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7393. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  7394. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7395. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7396. }
  7397. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7398. return {};
  7399. }
  7400. case BuiltinProc_volatile_load:
  7401. case BuiltinProc_atomic_load:
  7402. case BuiltinProc_atomic_load_acq:
  7403. case BuiltinProc_atomic_load_relaxed:
  7404. case BuiltinProc_atomic_load_unordered: {
  7405. lbValue dst = lb_build_expr(p, ce->args[0]);
  7406. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  7407. switch (id) {
  7408. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  7409. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7410. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  7411. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7412. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7413. }
  7414. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7415. lbValue res = {};
  7416. res.value = instr;
  7417. res.type = type_deref(dst.type);
  7418. return res;
  7419. }
  7420. case BuiltinProc_atomic_add:
  7421. case BuiltinProc_atomic_add_acq:
  7422. case BuiltinProc_atomic_add_rel:
  7423. case BuiltinProc_atomic_add_acqrel:
  7424. case BuiltinProc_atomic_add_relaxed:
  7425. case BuiltinProc_atomic_sub:
  7426. case BuiltinProc_atomic_sub_acq:
  7427. case BuiltinProc_atomic_sub_rel:
  7428. case BuiltinProc_atomic_sub_acqrel:
  7429. case BuiltinProc_atomic_sub_relaxed:
  7430. case BuiltinProc_atomic_and:
  7431. case BuiltinProc_atomic_and_acq:
  7432. case BuiltinProc_atomic_and_rel:
  7433. case BuiltinProc_atomic_and_acqrel:
  7434. case BuiltinProc_atomic_and_relaxed:
  7435. case BuiltinProc_atomic_nand:
  7436. case BuiltinProc_atomic_nand_acq:
  7437. case BuiltinProc_atomic_nand_rel:
  7438. case BuiltinProc_atomic_nand_acqrel:
  7439. case BuiltinProc_atomic_nand_relaxed:
  7440. case BuiltinProc_atomic_or:
  7441. case BuiltinProc_atomic_or_acq:
  7442. case BuiltinProc_atomic_or_rel:
  7443. case BuiltinProc_atomic_or_acqrel:
  7444. case BuiltinProc_atomic_or_relaxed:
  7445. case BuiltinProc_atomic_xor:
  7446. case BuiltinProc_atomic_xor_acq:
  7447. case BuiltinProc_atomic_xor_rel:
  7448. case BuiltinProc_atomic_xor_acqrel:
  7449. case BuiltinProc_atomic_xor_relaxed:
  7450. case BuiltinProc_atomic_xchg:
  7451. case BuiltinProc_atomic_xchg_acq:
  7452. case BuiltinProc_atomic_xchg_rel:
  7453. case BuiltinProc_atomic_xchg_acqrel:
  7454. case BuiltinProc_atomic_xchg_relaxed: {
  7455. lbValue dst = lb_build_expr(p, ce->args[0]);
  7456. lbValue val = lb_build_expr(p, ce->args[1]);
  7457. val = lb_emit_conv(p, val, type_deref(dst.type));
  7458. LLVMAtomicRMWBinOp op = {};
  7459. LLVMAtomicOrdering ordering = {};
  7460. switch (id) {
  7461. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7462. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  7463. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  7464. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7465. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  7466. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7467. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  7468. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  7469. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7470. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  7471. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7472. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  7473. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  7474. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7475. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  7476. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7477. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  7478. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  7479. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7480. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  7481. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7482. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  7483. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  7484. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7485. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  7486. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7487. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  7488. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  7489. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7490. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  7491. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7492. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  7493. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  7494. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7495. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  7496. }
  7497. lbValue res = {};
  7498. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  7499. res.type = tv.type;
  7500. return res;
  7501. }
  7502. case BuiltinProc_atomic_cxchg:
  7503. case BuiltinProc_atomic_cxchg_acq:
  7504. case BuiltinProc_atomic_cxchg_rel:
  7505. case BuiltinProc_atomic_cxchg_acqrel:
  7506. case BuiltinProc_atomic_cxchg_relaxed:
  7507. case BuiltinProc_atomic_cxchg_failrelaxed:
  7508. case BuiltinProc_atomic_cxchg_failacq:
  7509. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  7510. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  7511. case BuiltinProc_atomic_cxchgweak:
  7512. case BuiltinProc_atomic_cxchgweak_acq:
  7513. case BuiltinProc_atomic_cxchgweak_rel:
  7514. case BuiltinProc_atomic_cxchgweak_acqrel:
  7515. case BuiltinProc_atomic_cxchgweak_relaxed:
  7516. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  7517. case BuiltinProc_atomic_cxchgweak_failacq:
  7518. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  7519. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  7520. Type *type = expr->tav.type;
  7521. lbValue address = lb_build_expr(p, ce->args[0]);
  7522. Type *elem = type_deref(address.type);
  7523. lbValue old_value = lb_build_expr(p, ce->args[1]);
  7524. lbValue new_value = lb_build_expr(p, ce->args[2]);
  7525. old_value = lb_emit_conv(p, old_value, elem);
  7526. new_value = lb_emit_conv(p, new_value, elem);
  7527. LLVMAtomicOrdering success_ordering = {};
  7528. LLVMAtomicOrdering failure_ordering = {};
  7529. LLVMBool weak = false;
  7530. switch (id) {
  7531. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7532. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7533. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7534. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7535. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7536. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7537. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  7538. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7539. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7540. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7541. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7542. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7543. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7544. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7545. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7546. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  7547. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7548. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7549. }
  7550. // TODO(bill): Figure out how to make it weak
  7551. LLVMBool single_threaded = weak;
  7552. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  7553. p->builder, address.value,
  7554. old_value.value, new_value.value,
  7555. success_ordering,
  7556. failure_ordering,
  7557. single_threaded
  7558. );
  7559. GB_ASSERT(tv.type->kind == Type_Tuple);
  7560. Type *fix_typed = alloc_type_tuple();
  7561. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  7562. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  7563. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7564. lbValue res = {};
  7565. res.value = value;
  7566. res.type = fix_typed;
  7567. return res;
  7568. }
  7569. case BuiltinProc_type_equal_proc:
  7570. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  7571. case BuiltinProc_type_hasher_proc:
  7572. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  7573. }
  7574. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  7575. return {};
  7576. }
  7577. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  7578. switch (param_value.kind) {
  7579. case ParameterValue_Constant:
  7580. if (is_type_constant_type(parameter_type)) {
  7581. return lb_const_value(p->module, parameter_type, param_value.value);
  7582. } else {
  7583. ExactValue ev = param_value.value;
  7584. lbValue arg = {};
  7585. Type *type = type_of_expr(param_value.original_ast_expr);
  7586. if (type != nullptr) {
  7587. arg = lb_const_value(p->module, type, ev);
  7588. } else {
  7589. arg = lb_const_value(p->module, parameter_type, param_value.value);
  7590. }
  7591. return lb_emit_conv(p, arg, parameter_type);
  7592. }
  7593. case ParameterValue_Nil:
  7594. return lb_const_nil(p->module, parameter_type);
  7595. case ParameterValue_Location:
  7596. {
  7597. String proc_name = {};
  7598. if (p->entity != nullptr) {
  7599. proc_name = p->entity->token.string;
  7600. }
  7601. return lb_emit_source_code_location(p, proc_name, pos);
  7602. }
  7603. case ParameterValue_Value:
  7604. return lb_build_expr(p, param_value.ast_value);
  7605. }
  7606. return lb_const_nil(p->module, parameter_type);
  7607. }
  7608. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  7609. lbModule *m = p->module;
  7610. TypeAndValue tv = type_and_value_of_expr(expr);
  7611. ast_node(ce, CallExpr, expr);
  7612. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  7613. AddressingMode proc_mode = proc_tv.mode;
  7614. if (proc_mode == Addressing_Type) {
  7615. GB_ASSERT(ce->args.count == 1);
  7616. lbValue x = lb_build_expr(p, ce->args[0]);
  7617. lbValue y = lb_emit_conv(p, x, tv.type);
  7618. return y;
  7619. }
  7620. Ast *pexpr = unparen_expr(ce->proc);
  7621. if (proc_mode == Addressing_Builtin) {
  7622. Entity *e = entity_of_node(pexpr);
  7623. BuiltinProcId id = BuiltinProc_Invalid;
  7624. if (e != nullptr) {
  7625. id = cast(BuiltinProcId)e->Builtin.id;
  7626. } else {
  7627. id = BuiltinProc_DIRECTIVE;
  7628. }
  7629. return lb_build_builtin_proc(p, expr, tv, id);
  7630. }
  7631. // NOTE(bill): Regular call
  7632. lbValue value = {};
  7633. Ast *proc_expr = unparen_expr(ce->proc);
  7634. if (proc_expr->tav.mode == Addressing_Constant) {
  7635. ExactValue v = proc_expr->tav.value;
  7636. switch (v.kind) {
  7637. case ExactValue_Integer:
  7638. {
  7639. u64 u = big_int_to_u64(&v.value_integer);
  7640. lbValue x = {};
  7641. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7642. x.type = t_uintptr;
  7643. x = lb_emit_conv(p, x, t_rawptr);
  7644. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7645. break;
  7646. }
  7647. case ExactValue_Pointer:
  7648. {
  7649. u64 u = cast(u64)v.value_pointer;
  7650. lbValue x = {};
  7651. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7652. x.type = t_uintptr;
  7653. x = lb_emit_conv(p, x, t_rawptr);
  7654. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7655. break;
  7656. }
  7657. }
  7658. }
  7659. if (value.value == nullptr) {
  7660. value = lb_build_expr(p, proc_expr);
  7661. }
  7662. GB_ASSERT(value.value != nullptr);
  7663. Type *proc_type_ = base_type(value.type);
  7664. GB_ASSERT(proc_type_->kind == Type_Proc);
  7665. TypeProc *pt = &proc_type_->Proc;
  7666. set_procedure_abi_types(proc_type_);
  7667. if (is_call_expr_field_value(ce)) {
  7668. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  7669. for_array(arg_index, ce->args) {
  7670. Ast *arg = ce->args[arg_index];
  7671. ast_node(fv, FieldValue, arg);
  7672. GB_ASSERT(fv->field->kind == Ast_Ident);
  7673. String name = fv->field->Ident.token.string;
  7674. isize index = lookup_procedure_parameter(pt, name);
  7675. GB_ASSERT(index >= 0);
  7676. TypeAndValue tav = type_and_value_of_expr(fv->value);
  7677. if (tav.mode == Addressing_Type) {
  7678. args[index] = lb_const_nil(m, tav.type);
  7679. } else {
  7680. args[index] = lb_build_expr(p, fv->value);
  7681. }
  7682. }
  7683. TypeTuple *params = &pt->params->Tuple;
  7684. for (isize i = 0; i < args.count; i++) {
  7685. Entity *e = params->variables[i];
  7686. if (e->kind == Entity_TypeName) {
  7687. args[i] = lb_const_nil(m, e->type);
  7688. } else if (e->kind == Entity_Constant) {
  7689. continue;
  7690. } else {
  7691. GB_ASSERT(e->kind == Entity_Variable);
  7692. if (args[i].value == nullptr) {
  7693. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7694. } else {
  7695. args[i] = lb_emit_conv(p, args[i], e->type);
  7696. }
  7697. }
  7698. }
  7699. for (isize i = 0; i < args.count; i++) {
  7700. Entity *e = params->variables[i];
  7701. if (args[i].type == nullptr) {
  7702. continue;
  7703. } else if (is_type_untyped_nil(args[i].type)) {
  7704. args[i] = lb_const_nil(m, e->type);
  7705. } else if (is_type_untyped_undef(args[i].type)) {
  7706. args[i] = lb_const_undef(m, e->type);
  7707. }
  7708. }
  7709. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  7710. }
  7711. isize arg_index = 0;
  7712. isize arg_count = 0;
  7713. for_array(i, ce->args) {
  7714. Ast *arg = ce->args[i];
  7715. TypeAndValue tav = type_and_value_of_expr(arg);
  7716. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  7717. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  7718. Type *at = tav.type;
  7719. if (at->kind == Type_Tuple) {
  7720. arg_count += at->Tuple.variables.count;
  7721. } else {
  7722. arg_count++;
  7723. }
  7724. }
  7725. isize param_count = 0;
  7726. if (pt->params) {
  7727. GB_ASSERT(pt->params->kind == Type_Tuple);
  7728. param_count = pt->params->Tuple.variables.count;
  7729. }
  7730. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  7731. isize variadic_index = pt->variadic_index;
  7732. bool variadic = pt->variadic && variadic_index >= 0;
  7733. bool vari_expand = ce->ellipsis.pos.line != 0;
  7734. bool is_c_vararg = pt->c_vararg;
  7735. String proc_name = {};
  7736. if (p->entity != nullptr) {
  7737. proc_name = p->entity->token.string;
  7738. }
  7739. TokenPos pos = ast_token(ce->proc).pos;
  7740. TypeTuple *param_tuple = nullptr;
  7741. if (pt->params) {
  7742. GB_ASSERT(pt->params->kind == Type_Tuple);
  7743. param_tuple = &pt->params->Tuple;
  7744. }
  7745. for_array(i, ce->args) {
  7746. Ast *arg = ce->args[i];
  7747. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  7748. if (arg_tv.mode == Addressing_Type) {
  7749. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  7750. } else {
  7751. lbValue a = lb_build_expr(p, arg);
  7752. Type *at = a.type;
  7753. if (at->kind == Type_Tuple) {
  7754. for_array(i, at->Tuple.variables) {
  7755. Entity *e = at->Tuple.variables[i];
  7756. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  7757. args[arg_index++] = v;
  7758. }
  7759. } else {
  7760. args[arg_index++] = a;
  7761. }
  7762. }
  7763. }
  7764. if (param_count > 0) {
  7765. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7766. GB_ASSERT(param_count < 1000000);
  7767. if (arg_count < param_count) {
  7768. isize end = cast(isize)param_count;
  7769. if (variadic) {
  7770. end = variadic_index;
  7771. }
  7772. while (arg_index < end) {
  7773. Entity *e = param_tuple->variables[arg_index];
  7774. GB_ASSERT(e->kind == Entity_Variable);
  7775. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7776. }
  7777. }
  7778. if (is_c_vararg) {
  7779. GB_ASSERT(variadic);
  7780. GB_ASSERT(!vari_expand);
  7781. isize i = 0;
  7782. for (; i < variadic_index; i++) {
  7783. Entity *e = param_tuple->variables[i];
  7784. if (e->kind == Entity_Variable) {
  7785. args[i] = lb_emit_conv(p, args[i], e->type);
  7786. }
  7787. }
  7788. Type *variadic_type = param_tuple->variables[i]->type;
  7789. GB_ASSERT(is_type_slice(variadic_type));
  7790. variadic_type = base_type(variadic_type)->Slice.elem;
  7791. if (!is_type_any(variadic_type)) {
  7792. for (; i < arg_count; i++) {
  7793. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7794. }
  7795. } else {
  7796. for (; i < arg_count; i++) {
  7797. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7798. }
  7799. }
  7800. } else if (variadic) {
  7801. isize i = 0;
  7802. for (; i < variadic_index; i++) {
  7803. Entity *e = param_tuple->variables[i];
  7804. if (e->kind == Entity_Variable) {
  7805. args[i] = lb_emit_conv(p, args[i], e->type);
  7806. }
  7807. }
  7808. if (!vari_expand) {
  7809. Type *variadic_type = param_tuple->variables[i]->type;
  7810. GB_ASSERT(is_type_slice(variadic_type));
  7811. variadic_type = base_type(variadic_type)->Slice.elem;
  7812. for (; i < arg_count; i++) {
  7813. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7814. }
  7815. }
  7816. } else {
  7817. for (isize i = 0; i < param_count; i++) {
  7818. Entity *e = param_tuple->variables[i];
  7819. if (e->kind == Entity_Variable) {
  7820. if (args[i].value == nullptr) {
  7821. continue;
  7822. }
  7823. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7824. args[i] = lb_emit_conv(p, args[i], e->type);
  7825. }
  7826. }
  7827. }
  7828. if (variadic && !vari_expand && !is_c_vararg) {
  7829. // variadic call argument generation
  7830. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7831. Type *elem_type = base_type(slice_type)->Slice.elem;
  7832. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7833. isize slice_len = arg_count+1 - (variadic_index+1);
  7834. if (slice_len > 0) {
  7835. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7836. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7837. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7838. lb_emit_store(p, addr, args[i]);
  7839. }
  7840. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7841. lbValue len = lb_const_int(m, t_int, slice_len);
  7842. lb_fill_slice(p, slice, base_elem, len);
  7843. }
  7844. arg_count = param_count;
  7845. args[variadic_index] = lb_addr_load(p, slice);
  7846. }
  7847. }
  7848. if (variadic && variadic_index+1 < param_count) {
  7849. for (isize i = variadic_index+1; i < param_count; i++) {
  7850. Entity *e = param_tuple->variables[i];
  7851. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7852. }
  7853. }
  7854. isize final_count = param_count;
  7855. if (is_c_vararg) {
  7856. final_count = arg_count;
  7857. }
  7858. if (param_tuple != nullptr) {
  7859. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7860. Entity *e = param_tuple->variables[i];
  7861. if (args[i].type == nullptr) {
  7862. continue;
  7863. } else if (is_type_untyped_nil(args[i].type)) {
  7864. args[i] = lb_const_nil(m, e->type);
  7865. } else if (is_type_untyped_undef(args[i].type)) {
  7866. args[i] = lb_const_undef(m, e->type);
  7867. }
  7868. }
  7869. }
  7870. auto call_args = array_slice(args, 0, final_count);
  7871. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  7872. }
  7873. bool lb_is_const(lbValue value) {
  7874. LLVMValueRef v = value.value;
  7875. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  7876. // TODO(bill): Is this correct behaviour?
  7877. return true;
  7878. }
  7879. if (LLVMIsConstant(v)) {
  7880. return true;
  7881. }
  7882. return false;
  7883. }
  7884. bool lb_is_const_or_global(lbValue value) {
  7885. if (lb_is_const(value)) {
  7886. return true;
  7887. }
  7888. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  7889. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  7890. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  7891. return false;
  7892. }
  7893. LLVMTypeRef elem = LLVMGetElementType(t);
  7894. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  7895. }
  7896. return false;
  7897. }
  7898. bool lb_is_const_nil(lbValue value) {
  7899. LLVMValueRef v = value.value;
  7900. if (LLVMIsConstant(v)) {
  7901. if (LLVMIsAConstantAggregateZero(v)) {
  7902. return true;
  7903. } else if (LLVMIsAConstantPointerNull(v)) {
  7904. return true;
  7905. }
  7906. }
  7907. return false;
  7908. }
  7909. String lb_get_const_string(lbModule *m, lbValue value) {
  7910. GB_ASSERT(lb_is_const(value));
  7911. Type *t = base_type(value.type);
  7912. GB_ASSERT(are_types_identical(t, t_string));
  7913. unsigned ptr_indices[1] = {0};
  7914. unsigned len_indices[1] = {1};
  7915. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  7916. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  7917. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  7918. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  7919. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  7920. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  7921. size_t length = 0;
  7922. char const *text = LLVMGetAsString(underlying_ptr, &length);
  7923. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  7924. return make_string(cast(u8 const *)text, real_length);
  7925. }
  7926. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  7927. GB_ASSERT(is_type_pointer(addr.type));
  7928. Type *type = type_deref(addr.type);
  7929. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  7930. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  7931. }
  7932. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7933. AstPackage *pkg = m->info->runtime_package;
  7934. Entity *e = scope_lookup_current(pkg->scope, name);
  7935. lbValue *found = nullptr;
  7936. if (m != e->code_gen_module) {
  7937. gb_mutex_lock(&m->mutex);
  7938. }
  7939. GB_ASSERT(e->code_gen_module != nullptr);
  7940. found = map_get(&e->code_gen_module->values, hash_entity(e));
  7941. if (m != e->code_gen_module) {
  7942. gb_mutex_unlock(&m->mutex);
  7943. }
  7944. GB_ASSERT(found != nullptr);
  7945. return found->value;
  7946. }
  7947. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  7948. Type *vt = core_type(value.type);
  7949. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  7950. // TODO(bill): lb_emit_byte_swap
  7951. lbValue res = {};
  7952. res.type = platform_type;
  7953. res.value = value.value;
  7954. int sz = cast(int)type_size_of(vt);
  7955. if (sz > 1) {
  7956. if (is_type_float(platform_type)) {
  7957. String name = {};
  7958. switch (sz) {
  7959. case 4: name = str_lit("bswap_f32"); break;
  7960. case 8: name = str_lit("bswap_f64"); break;
  7961. default: GB_PANIC("unhandled byteswap size"); break;
  7962. }
  7963. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7964. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7965. } else {
  7966. GB_ASSERT(is_type_integer(platform_type));
  7967. String name = {};
  7968. switch (sz) {
  7969. case 2: name = str_lit("bswap_16"); break;
  7970. case 4: name = str_lit("bswap_32"); break;
  7971. case 8: name = str_lit("bswap_64"); break;
  7972. case 16: name = str_lit("bswap_128"); break;
  7973. default: GB_PANIC("unhandled byteswap size"); break;
  7974. }
  7975. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7976. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7977. }
  7978. }
  7979. return res;
  7980. }
  7981. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  7982. lbLoopData data = {};
  7983. lbValue max = lb_const_int(p->module, t_int, count);
  7984. data.idx_addr = lb_add_local_generated(p, index_type, true);
  7985. data.body = lb_create_block(p, "loop.body");
  7986. data.done = lb_create_block(p, "loop.done");
  7987. data.loop = lb_create_block(p, "loop.loop");
  7988. lb_emit_jump(p, data.loop);
  7989. lb_start_block(p, data.loop);
  7990. data.idx = lb_addr_load(p, data.idx_addr);
  7991. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  7992. lb_emit_if(p, cond, data.body, data.done);
  7993. lb_start_block(p, data.body);
  7994. return data;
  7995. }
  7996. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  7997. if (data.idx_addr.addr.value != nullptr) {
  7998. lb_emit_increment(p, data.idx_addr.addr);
  7999. lb_emit_jump(p, data.loop);
  8000. lb_start_block(p, data.done);
  8001. }
  8002. }
  8003. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  8004. lbValue res = {};
  8005. res.type = t_llvm_bool;
  8006. Type *t = x.type;
  8007. if (is_type_pointer(t)) {
  8008. if (op_kind == Token_CmpEq) {
  8009. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8010. } else if (op_kind == Token_NotEq) {
  8011. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8012. }
  8013. return res;
  8014. } else if (is_type_cstring(t)) {
  8015. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  8016. if (op_kind == Token_CmpEq) {
  8017. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  8018. } else if (op_kind == Token_NotEq) {
  8019. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  8020. }
  8021. return res;
  8022. } else if (is_type_proc(t)) {
  8023. if (op_kind == Token_CmpEq) {
  8024. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8025. } else if (op_kind == Token_NotEq) {
  8026. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8027. }
  8028. return res;
  8029. } else if (is_type_any(t)) {
  8030. // TODO(bill): is this correct behaviour for nil comparison for any?
  8031. lbValue data = lb_emit_struct_ev(p, x, 0);
  8032. lbValue ti = lb_emit_struct_ev(p, x, 1);
  8033. if (op_kind == Token_CmpEq) {
  8034. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  8035. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  8036. res.value = LLVMBuildOr(p->builder, a, b, "");
  8037. return res;
  8038. } else if (op_kind == Token_NotEq) {
  8039. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  8040. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  8041. res.value = LLVMBuildAnd(p->builder, a, b, "");
  8042. return res;
  8043. }
  8044. } else if (is_type_slice(t)) {
  8045. lbValue len = lb_emit_struct_ev(p, x, 1);
  8046. if (op_kind == Token_CmpEq) {
  8047. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8048. return res;
  8049. } else if (op_kind == Token_NotEq) {
  8050. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8051. return res;
  8052. }
  8053. } else if (is_type_dynamic_array(t)) {
  8054. lbValue cap = lb_emit_struct_ev(p, x, 2);
  8055. if (op_kind == Token_CmpEq) {
  8056. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8057. return res;
  8058. } else if (op_kind == Token_NotEq) {
  8059. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8060. return res;
  8061. }
  8062. } else if (is_type_map(t)) {
  8063. lbValue cap = lb_map_cap(p, x);
  8064. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  8065. } else if (is_type_union(t)) {
  8066. if (type_size_of(t) == 0) {
  8067. if (op_kind == Token_CmpEq) {
  8068. return lb_const_bool(p->module, t_llvm_bool, true);
  8069. } else if (op_kind == Token_NotEq) {
  8070. return lb_const_bool(p->module, t_llvm_bool, false);
  8071. }
  8072. } else {
  8073. lbValue tag = lb_emit_union_tag_value(p, x);
  8074. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  8075. }
  8076. } else if (is_type_typeid(t)) {
  8077. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  8078. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  8079. } else if (is_type_soa_struct(t)) {
  8080. Type *bt = base_type(t);
  8081. if (bt->Struct.soa_kind == StructSoa_Slice) {
  8082. lbValue len = lb_soa_struct_len(p, x);
  8083. if (op_kind == Token_CmpEq) {
  8084. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8085. return res;
  8086. } else if (op_kind == Token_NotEq) {
  8087. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8088. return res;
  8089. }
  8090. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  8091. lbValue cap = lb_soa_struct_cap(p, x);
  8092. if (op_kind == Token_CmpEq) {
  8093. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8094. return res;
  8095. } else if (op_kind == Token_NotEq) {
  8096. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8097. return res;
  8098. }
  8099. }
  8100. } else if (is_type_struct(t) && type_has_nil(t)) {
  8101. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8102. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  8103. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8104. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  8105. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  8106. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  8107. return res;
  8108. }
  8109. return {};
  8110. }
  8111. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  8112. Type *original_type = type;
  8113. type = base_type(type);
  8114. GB_ASSERT(is_type_comparable(type));
  8115. Type *pt = alloc_type_pointer(type);
  8116. LLVMTypeRef ptr_type = lb_type(m, pt);
  8117. auto key = hash_type(type);
  8118. lbProcedure **found = map_get(&m->equal_procs, key);
  8119. lbProcedure *compare_proc = nullptr;
  8120. if (found) {
  8121. compare_proc = *found;
  8122. GB_ASSERT(compare_proc != nullptr);
  8123. return {compare_proc->value, compare_proc->type};
  8124. }
  8125. static u32 proc_index = 0;
  8126. char buf[16] = {};
  8127. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  8128. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8129. String proc_name = make_string_c(str);
  8130. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  8131. map_set(&m->equal_procs, key, p);
  8132. lb_begin_procedure_body(p);
  8133. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8134. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8135. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  8136. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  8137. lbValue lhs = {x, pt};
  8138. lbValue rhs = {y, pt};
  8139. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  8140. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  8141. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  8142. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  8143. lb_start_block(p, block_same_ptr);
  8144. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8145. lb_start_block(p, block_diff_ptr);
  8146. if (type->kind == Type_Struct) {
  8147. type_set_offsets(type);
  8148. lbBlock *block_false = lb_create_block(p, "bfalse");
  8149. lbValue res = lb_const_bool(m, t_bool, true);
  8150. for_array(i, type->Struct.fields) {
  8151. lbBlock *next_block = lb_create_block(p, "btrue");
  8152. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  8153. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  8154. lbValue left = lb_emit_load(p, pleft);
  8155. lbValue right = lb_emit_load(p, pright);
  8156. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8157. lb_emit_if(p, ok, next_block, block_false);
  8158. lb_emit_jump(p, next_block);
  8159. lb_start_block(p, next_block);
  8160. }
  8161. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8162. lb_start_block(p, block_false);
  8163. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  8164. } else {
  8165. lbValue left = lb_emit_load(p, lhs);
  8166. lbValue right = lb_emit_load(p, rhs);
  8167. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8168. ok = lb_emit_conv(p, ok, t_bool);
  8169. LLVMBuildRet(p->builder, ok.value);
  8170. }
  8171. lb_end_procedure_body(p);
  8172. compare_proc = p;
  8173. return {compare_proc->value, compare_proc->type};
  8174. }
  8175. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  8176. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  8177. i64 sz = type_size_of(type);
  8178. if (1 <= sz && sz <= 16) {
  8179. char name[20] = {};
  8180. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  8181. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8182. args[0] = data;
  8183. args[1] = seed;
  8184. return lb_emit_runtime_call(p, name, args);
  8185. }
  8186. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8187. args[0] = data;
  8188. args[1] = seed;
  8189. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  8190. return lb_emit_runtime_call(p, "default_hasher_n", args);
  8191. }
  8192. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  8193. Type *original_type = type;
  8194. type = core_type(type);
  8195. GB_ASSERT(is_type_valid_for_keys(type));
  8196. Type *pt = alloc_type_pointer(type);
  8197. LLVMTypeRef ptr_type = lb_type(m, pt);
  8198. auto key = hash_type(type);
  8199. lbProcedure **found = map_get(&m->hasher_procs, key);
  8200. if (found) {
  8201. GB_ASSERT(*found != nullptr);
  8202. return {(*found)->value, (*found)->type};
  8203. }
  8204. static u32 proc_index = 0;
  8205. char buf[16] = {};
  8206. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  8207. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8208. String proc_name = make_string_c(str);
  8209. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  8210. map_set(&m->hasher_procs, key, p);
  8211. lb_begin_procedure_body(p);
  8212. defer (lb_end_procedure_body(p));
  8213. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8214. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8215. lbValue data = {x, t_rawptr};
  8216. lbValue seed = {y, t_uintptr};
  8217. if (is_type_simple_compare(type)) {
  8218. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  8219. LLVMBuildRet(p->builder, res.value);
  8220. return {p->value, p->type};
  8221. }
  8222. if (type->kind == Type_Struct) {
  8223. type_set_offsets(type);
  8224. data = lb_emit_conv(p, data, t_u8_ptr);
  8225. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8226. for_array(i, type->Struct.fields) {
  8227. i64 offset = type->Struct.offsets[i];
  8228. Entity *field = type->Struct.fields[i];
  8229. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  8230. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  8231. args[0] = ptr;
  8232. args[1] = seed;
  8233. seed = lb_emit_call(p, field_hasher, args);
  8234. }
  8235. LLVMBuildRet(p->builder, seed.value);
  8236. } else if (type->kind == Type_Array) {
  8237. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  8238. lb_addr_store(p, pres, seed);
  8239. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8240. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  8241. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  8242. data = lb_emit_conv(p, data, pt);
  8243. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8244. args[0] = ptr;
  8245. args[1] = lb_addr_load(p, pres);
  8246. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8247. lb_addr_store(p, pres, new_seed);
  8248. lb_loop_end(p, loop_data);
  8249. lbValue res = lb_addr_load(p, pres);
  8250. LLVMBuildRet(p->builder, res.value);
  8251. } else if (type->kind == Type_EnumeratedArray) {
  8252. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  8253. lb_addr_store(p, res, seed);
  8254. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8255. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  8256. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  8257. data = lb_emit_conv(p, data, pt);
  8258. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8259. args[0] = ptr;
  8260. args[1] = lb_addr_load(p, res);
  8261. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8262. lb_addr_store(p, res, new_seed);
  8263. lb_loop_end(p, loop_data);
  8264. lbValue vres = lb_addr_load(p, res);
  8265. LLVMBuildRet(p->builder, vres.value);
  8266. } else if (is_type_cstring(type)) {
  8267. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8268. args[0] = data;
  8269. args[1] = seed;
  8270. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  8271. LLVMBuildRet(p->builder, res.value);
  8272. } else if (is_type_string(type)) {
  8273. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8274. args[0] = data;
  8275. args[1] = seed;
  8276. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  8277. LLVMBuildRet(p->builder, res.value);
  8278. } else {
  8279. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  8280. }
  8281. return {p->value, p->type};
  8282. }
  8283. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  8284. Type *a = core_type(left.type);
  8285. Type *b = core_type(right.type);
  8286. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  8287. lbValue nil_check = {};
  8288. if (is_type_untyped_nil(left.type)) {
  8289. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  8290. } else if (is_type_untyped_nil(right.type)) {
  8291. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  8292. }
  8293. if (nil_check.value != nullptr) {
  8294. return nil_check;
  8295. }
  8296. if (are_types_identical(a, b)) {
  8297. // NOTE(bill): No need for a conversion
  8298. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  8299. left = lb_emit_conv(p, left, right.type);
  8300. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  8301. right = lb_emit_conv(p, right, left.type);
  8302. } else {
  8303. Type *lt = left.type;
  8304. Type *rt = right.type;
  8305. // if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  8306. // Type *blt = base_type(lt);
  8307. // Type *brt = base_type(rt);
  8308. // i64 bits = gb_max(blt->BitSet.bits, brt->BitSet.bits);
  8309. // i64 bytes = bits / 8;
  8310. // switch (bytes) {
  8311. // case 1:
  8312. // left = lb_emit_conv(p, left, t_u8);
  8313. // right = lb_emit_conv(p, right, t_u8);
  8314. // break;
  8315. // case 2:
  8316. // left = lb_emit_conv(p, left, t_u16);
  8317. // right = lb_emit_conv(p, right, t_u16);
  8318. // break;
  8319. // case 4:
  8320. // left = lb_emit_conv(p, left, t_u32);
  8321. // right = lb_emit_conv(p, right, t_u32);
  8322. // break;
  8323. // case 8:
  8324. // left = lb_emit_conv(p, left, t_u64);
  8325. // right = lb_emit_conv(p, right, t_u64);
  8326. // break;
  8327. // default: GB_PANIC("Unknown integer size"); break;
  8328. // }
  8329. // }
  8330. lt = left.type;
  8331. rt = right.type;
  8332. i64 ls = type_size_of(lt);
  8333. i64 rs = type_size_of(rt);
  8334. if (ls < rs) {
  8335. left = lb_emit_conv(p, left, rt);
  8336. } else if (ls > rs) {
  8337. right = lb_emit_conv(p, right, lt);
  8338. } else {
  8339. right = lb_emit_conv(p, right, lt);
  8340. }
  8341. }
  8342. if (is_type_array(a)) {
  8343. Type *tl = base_type(a);
  8344. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  8345. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  8346. TokenKind cmp_op = Token_And;
  8347. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  8348. if (op_kind == Token_NotEq) {
  8349. res = lb_const_bool(p->module, t_llvm_bool, false);
  8350. cmp_op = Token_Or;
  8351. } else if (op_kind == Token_CmpEq) {
  8352. res = lb_const_bool(p->module, t_llvm_bool, true);
  8353. cmp_op = Token_And;
  8354. }
  8355. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  8356. i32 count = cast(i32)tl->Array.count;
  8357. if (inline_array_arith) {
  8358. // inline
  8359. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8360. lb_addr_store(p, val, res);
  8361. for (i32 i = 0; i < count; i++) {
  8362. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  8363. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  8364. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8365. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8366. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8367. }
  8368. return lb_addr_load(p, val);
  8369. } else {
  8370. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  8371. // TODO(bill): Test to see if this is actually faster!!!!
  8372. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8373. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8374. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  8375. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  8376. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  8377. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  8378. return lb_emit_conv(p, res, t_bool);
  8379. } else {
  8380. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8381. lb_addr_store(p, val, res);
  8382. auto loop_data = lb_loop_start(p, count, t_i32);
  8383. {
  8384. lbValue i = loop_data.idx;
  8385. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  8386. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  8387. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8388. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8389. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8390. }
  8391. lb_loop_end(p, loop_data);
  8392. return lb_addr_load(p, val);
  8393. }
  8394. }
  8395. }
  8396. if (is_type_struct(a) && is_type_comparable(a)) {
  8397. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  8398. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  8399. lbValue res = {};
  8400. if (is_type_simple_compare(a)) {
  8401. // TODO(bill): Test to see if this is actually faster!!!!
  8402. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8403. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8404. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8405. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  8406. res = lb_emit_runtime_call(p, "memory_equal", args);
  8407. } else {
  8408. lbValue value = lb_get_equal_proc_for_type(p->module, a);
  8409. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8410. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8411. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8412. res = lb_emit_call(p, value, args);
  8413. }
  8414. if (op_kind == Token_NotEq) {
  8415. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  8416. }
  8417. return res;
  8418. }
  8419. if (is_type_string(a)) {
  8420. if (is_type_cstring(a)) {
  8421. left = lb_emit_conv(p, left, t_string);
  8422. right = lb_emit_conv(p, right, t_string);
  8423. }
  8424. char const *runtime_procedure = nullptr;
  8425. switch (op_kind) {
  8426. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  8427. case Token_NotEq: runtime_procedure = "string_ne"; break;
  8428. case Token_Lt: runtime_procedure = "string_lt"; break;
  8429. case Token_Gt: runtime_procedure = "string_gt"; break;
  8430. case Token_LtEq: runtime_procedure = "string_le"; break;
  8431. case Token_GtEq: runtime_procedure = "string_gt"; break;
  8432. }
  8433. GB_ASSERT(runtime_procedure != nullptr);
  8434. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8435. args[0] = left;
  8436. args[1] = right;
  8437. return lb_emit_runtime_call(p, runtime_procedure, args);
  8438. }
  8439. if (is_type_complex(a)) {
  8440. char const *runtime_procedure = "";
  8441. i64 sz = 8*type_size_of(a);
  8442. switch (sz) {
  8443. case 64:
  8444. switch (op_kind) {
  8445. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  8446. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  8447. }
  8448. break;
  8449. case 128:
  8450. switch (op_kind) {
  8451. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  8452. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  8453. }
  8454. break;
  8455. }
  8456. GB_ASSERT(runtime_procedure != nullptr);
  8457. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8458. args[0] = left;
  8459. args[1] = right;
  8460. return lb_emit_runtime_call(p, runtime_procedure, args);
  8461. }
  8462. if (is_type_quaternion(a)) {
  8463. char const *runtime_procedure = "";
  8464. i64 sz = 8*type_size_of(a);
  8465. switch (sz) {
  8466. case 128:
  8467. switch (op_kind) {
  8468. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  8469. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  8470. }
  8471. break;
  8472. case 256:
  8473. switch (op_kind) {
  8474. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  8475. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  8476. }
  8477. break;
  8478. }
  8479. GB_ASSERT(runtime_procedure != nullptr);
  8480. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8481. args[0] = left;
  8482. args[1] = right;
  8483. return lb_emit_runtime_call(p, runtime_procedure, args);
  8484. }
  8485. if (is_type_bit_set(a)) {
  8486. switch (op_kind) {
  8487. case Token_Lt:
  8488. case Token_LtEq:
  8489. case Token_Gt:
  8490. case Token_GtEq:
  8491. {
  8492. Type *it = bit_set_to_int(a);
  8493. lbValue lhs = lb_emit_transmute(p, left, it);
  8494. lbValue rhs = lb_emit_transmute(p, right, it);
  8495. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  8496. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  8497. // (lhs & rhs) == lhs
  8498. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  8499. res.type = t_llvm_bool;
  8500. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  8501. // (lhs & rhs) == rhs
  8502. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  8503. res.type = t_llvm_bool;
  8504. }
  8505. // NOTE(bill): Strict subsets
  8506. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  8507. // res &~ (lhs == rhs)
  8508. lbValue eq = {};
  8509. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  8510. eq.type = t_llvm_bool;
  8511. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  8512. }
  8513. return res;
  8514. }
  8515. case Token_CmpEq:
  8516. case Token_NotEq:
  8517. {
  8518. LLVMIntPredicate pred = {};
  8519. switch (op_kind) {
  8520. case Token_CmpEq: pred = LLVMIntEQ; break;
  8521. case Token_NotEq: pred = LLVMIntNE; break;
  8522. }
  8523. lbValue res = {};
  8524. res.type = t_llvm_bool;
  8525. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8526. return res;
  8527. }
  8528. }
  8529. }
  8530. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  8531. Type *t = left.type;
  8532. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  8533. Type *platform_type = integer_endian_type_to_platform_type(t);
  8534. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  8535. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  8536. left = x;
  8537. right = y;
  8538. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  8539. Type *platform_type = integer_endian_type_to_platform_type(t);
  8540. lbValue x = lb_emit_conv(p, left, platform_type);
  8541. lbValue y = lb_emit_conv(p, right, platform_type);
  8542. left = x;
  8543. right = y;
  8544. }
  8545. }
  8546. a = core_type(left.type);
  8547. b = core_type(right.type);
  8548. lbValue res = {};
  8549. res.type = t_llvm_bool;
  8550. if (is_type_integer(a) ||
  8551. is_type_boolean(a) ||
  8552. is_type_pointer(a) ||
  8553. is_type_proc(a) ||
  8554. is_type_enum(a)) {
  8555. LLVMIntPredicate pred = {};
  8556. if (is_type_unsigned(left.type)) {
  8557. switch (op_kind) {
  8558. case Token_Gt: pred = LLVMIntUGT; break;
  8559. case Token_GtEq: pred = LLVMIntUGE; break;
  8560. case Token_Lt: pred = LLVMIntULT; break;
  8561. case Token_LtEq: pred = LLVMIntULE; break;
  8562. }
  8563. } else {
  8564. switch (op_kind) {
  8565. case Token_Gt: pred = LLVMIntSGT; break;
  8566. case Token_GtEq: pred = LLVMIntSGE; break;
  8567. case Token_Lt: pred = LLVMIntSLT; break;
  8568. case Token_LtEq: pred = LLVMIntSLE; break;
  8569. }
  8570. }
  8571. switch (op_kind) {
  8572. case Token_CmpEq: pred = LLVMIntEQ; break;
  8573. case Token_NotEq: pred = LLVMIntNE; break;
  8574. }
  8575. LLVMValueRef lhs = left.value;
  8576. LLVMValueRef rhs = right.value;
  8577. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  8578. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  8579. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  8580. }
  8581. }
  8582. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  8583. } else if (is_type_float(a)) {
  8584. LLVMRealPredicate pred = {};
  8585. switch (op_kind) {
  8586. case Token_CmpEq: pred = LLVMRealOEQ; break;
  8587. case Token_Gt: pred = LLVMRealOGT; break;
  8588. case Token_GtEq: pred = LLVMRealOGE; break;
  8589. case Token_Lt: pred = LLVMRealOLT; break;
  8590. case Token_LtEq: pred = LLVMRealOLE; break;
  8591. case Token_NotEq: pred = LLVMRealONE; break;
  8592. }
  8593. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  8594. } else if (is_type_typeid(a)) {
  8595. LLVMIntPredicate pred = {};
  8596. switch (op_kind) {
  8597. case Token_Gt: pred = LLVMIntUGT; break;
  8598. case Token_GtEq: pred = LLVMIntUGE; break;
  8599. case Token_Lt: pred = LLVMIntULT; break;
  8600. case Token_LtEq: pred = LLVMIntULE; break;
  8601. case Token_CmpEq: pred = LLVMIntEQ; break;
  8602. case Token_NotEq: pred = LLVMIntNE; break;
  8603. }
  8604. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8605. } else {
  8606. 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)));
  8607. }
  8608. return res;
  8609. }
  8610. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  8611. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  8612. if (found != nullptr) {
  8613. lbValue value = {};
  8614. value.value = (*found)->value;
  8615. value.type = (*found)->type;
  8616. return value;
  8617. }
  8618. ast_node(pl, ProcLit, expr);
  8619. // NOTE(bill): Generate a new name
  8620. // parent$count
  8621. isize name_len = prefix_name.len + 1 + 8 + 1;
  8622. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  8623. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  8624. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  8625. String name = make_string((u8 *)name_text, name_len-1);
  8626. Type *type = type_of_expr(expr);
  8627. set_procedure_abi_types(type);
  8628. Token token = {};
  8629. token.pos = ast_token(expr).pos;
  8630. token.kind = Token_Ident;
  8631. token.string = name;
  8632. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  8633. e->file = expr->file;
  8634. e->decl_info = pl->decl;
  8635. lbProcedure *p = lb_create_procedure(m, e);
  8636. lbValue value = {};
  8637. value.value = p->value;
  8638. value.type = p->type;
  8639. array_add(&m->procedures_to_generate, p);
  8640. if (parent != nullptr) {
  8641. array_add(&parent->children, p);
  8642. } else {
  8643. string_map_set(&m->members, name, value);
  8644. }
  8645. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  8646. return value;
  8647. }
  8648. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  8649. lbModule *m = p->module;
  8650. Type *src_type = value.type;
  8651. bool is_ptr = is_type_pointer(src_type);
  8652. bool is_tuple = true;
  8653. Type *tuple = type;
  8654. if (type->kind != Type_Tuple) {
  8655. is_tuple = false;
  8656. tuple = make_optional_ok_type(type);
  8657. }
  8658. lbAddr v = lb_add_local_generated(p, tuple, true);
  8659. if (is_ptr) {
  8660. value = lb_emit_load(p, value);
  8661. }
  8662. Type *src = base_type(type_deref(src_type));
  8663. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  8664. Type *dst = tuple->Tuple.variables[0]->type;
  8665. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  8666. lbValue tag = {};
  8667. lbValue dst_tag = {};
  8668. lbValue cond = {};
  8669. lbValue data = {};
  8670. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8671. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8672. if (is_type_union_maybe_pointer(src)) {
  8673. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8674. } else {
  8675. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  8676. dst_tag = lb_const_union_tag(m, src, dst);
  8677. }
  8678. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  8679. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  8680. if (data.value != nullptr) {
  8681. GB_ASSERT(is_type_union_maybe_pointer(src));
  8682. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  8683. } else {
  8684. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  8685. }
  8686. lb_emit_if(p, cond, ok_block, end_block);
  8687. lb_start_block(p, ok_block);
  8688. if (data.value == nullptr) {
  8689. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8690. }
  8691. lb_emit_store(p, gep0, data);
  8692. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8693. lb_emit_jump(p, end_block);
  8694. lb_start_block(p, end_block);
  8695. if (!is_tuple) {
  8696. if (do_conversion_check) {
  8697. // NOTE(bill): Panic on invalid conversion
  8698. Type *dst_type = tuple->Tuple.variables[0]->type;
  8699. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8700. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8701. args[0] = ok;
  8702. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  8703. args[2] = lb_const_int(m, t_i32, pos.line);
  8704. args[3] = lb_const_int(m, t_i32, pos.column);
  8705. args[4] = lb_typeid(m, src_type);
  8706. args[5] = lb_typeid(m, dst_type);
  8707. args[6] = lb_emit_conv(p, value_, t_rawptr);
  8708. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8709. }
  8710. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  8711. }
  8712. return lb_addr_load(p, v);
  8713. }
  8714. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8715. lbModule *m = p->module;
  8716. Type *src_type = value.type;
  8717. if (is_type_pointer(src_type)) {
  8718. value = lb_emit_load(p, value);
  8719. }
  8720. bool is_tuple = true;
  8721. Type *tuple = type;
  8722. if (type->kind != Type_Tuple) {
  8723. is_tuple = false;
  8724. tuple = make_optional_ok_type(type);
  8725. }
  8726. Type *dst_type = tuple->Tuple.variables[0]->type;
  8727. lbAddr v = lb_add_local_generated(p, tuple, true);
  8728. lbValue dst_typeid = lb_typeid(m, dst_type);
  8729. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  8730. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  8731. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  8732. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  8733. lb_emit_if(p, cond, ok_block, end_block);
  8734. lb_start_block(p, ok_block);
  8735. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8736. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8737. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  8738. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  8739. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  8740. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8741. lb_emit_jump(p, end_block);
  8742. lb_start_block(p, end_block);
  8743. if (!is_tuple) {
  8744. // NOTE(bill): Panic on invalid conversion
  8745. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8746. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8747. args[0] = ok;
  8748. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  8749. args[2] = lb_const_int(m, t_i32, pos.line);
  8750. args[3] = lb_const_int(m, t_i32, pos.column);
  8751. args[4] = any_typeid;
  8752. args[5] = dst_typeid;
  8753. args[6] = lb_emit_struct_ev(p, value, 0);;
  8754. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8755. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  8756. }
  8757. return v;
  8758. }
  8759. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8760. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  8761. }
  8762. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  8763. lbModule *m = p->module;
  8764. u64 prev_state_flags = p->module->state_flags;
  8765. defer (p->module->state_flags = prev_state_flags);
  8766. if (expr->state_flags != 0) {
  8767. u64 in = expr->state_flags;
  8768. u64 out = p->module->state_flags;
  8769. if (in & StateFlag_bounds_check) {
  8770. out |= StateFlag_bounds_check;
  8771. out &= ~StateFlag_no_bounds_check;
  8772. } else if (in & StateFlag_no_bounds_check) {
  8773. out |= StateFlag_no_bounds_check;
  8774. out &= ~StateFlag_bounds_check;
  8775. }
  8776. p->module->state_flags = out;
  8777. }
  8778. expr = unparen_expr(expr);
  8779. TokenPos expr_pos = ast_token(expr).pos;
  8780. TypeAndValue tv = type_and_value_of_expr(expr);
  8781. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %s\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), token_pos_to_string(expr_pos), LIT(p->name), type_to_string(p->type));
  8782. if (tv.value.kind != ExactValue_Invalid) {
  8783. // NOTE(bill): Short on constant values
  8784. return lb_const_value(p->module, tv.type, tv.value);
  8785. }
  8786. #if 0
  8787. LLVMMetadataRef prev_debug_location = nullptr;
  8788. if (p->debug_info != nullptr) {
  8789. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  8790. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  8791. }
  8792. defer (if (prev_debug_location != nullptr) {
  8793. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  8794. });
  8795. #endif
  8796. switch (expr->kind) {
  8797. case_ast_node(bl, BasicLit, expr);
  8798. TokenPos pos = bl->token.pos;
  8799. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  8800. case_end;
  8801. case_ast_node(bd, BasicDirective, expr);
  8802. TokenPos pos = bd->token.pos;
  8803. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name));
  8804. case_end;
  8805. case_ast_node(i, Implicit, expr);
  8806. return lb_addr_load(p, lb_build_addr(p, expr));
  8807. case_end;
  8808. case_ast_node(u, Undef, expr)
  8809. lbValue res = {};
  8810. if (is_type_untyped(tv.type)) {
  8811. res.value = nullptr;
  8812. res.type = t_untyped_undef;
  8813. } else {
  8814. res.value = LLVMGetUndef(lb_type(m, tv.type));
  8815. res.type = tv.type;
  8816. }
  8817. return res;
  8818. case_end;
  8819. case_ast_node(i, Ident, expr);
  8820. Entity *e = entity_from_expr(expr);
  8821. e = strip_entity_wrapping(e);
  8822. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  8823. if (e->kind == Entity_Builtin) {
  8824. Token token = ast_token(expr);
  8825. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  8826. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  8827. token_pos_to_string(token.pos));
  8828. return {};
  8829. } else if (e->kind == Entity_Nil) {
  8830. lbValue res = {};
  8831. res.value = nullptr;
  8832. res.type = e->type;
  8833. return res;
  8834. }
  8835. GB_ASSERT(e->kind != Entity_ProcGroup);
  8836. auto *found = map_get(&p->module->values, hash_entity(e));
  8837. if (found) {
  8838. auto v = *found;
  8839. // NOTE(bill): This is because pointers are already pointers in LLVM
  8840. if (is_type_proc(v.type)) {
  8841. return v;
  8842. }
  8843. return lb_emit_load(p, v);
  8844. } else if (e != nullptr && e->kind == Entity_Variable) {
  8845. return lb_addr_load(p, lb_build_addr(p, expr));
  8846. }
  8847. gb_printf_err("Error in: %s\n", token_pos_to_string(i->token.pos));
  8848. String pkg = {};
  8849. if (e->pkg) {
  8850. pkg = e->pkg->name;
  8851. }
  8852. 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);
  8853. return {};
  8854. case_end;
  8855. case_ast_node(de, DerefExpr, expr);
  8856. return lb_addr_load(p, lb_build_addr(p, expr));
  8857. case_end;
  8858. case_ast_node(se, SelectorExpr, expr);
  8859. TypeAndValue tav = type_and_value_of_expr(expr);
  8860. GB_ASSERT(tav.mode != Addressing_Invalid);
  8861. return lb_addr_load(p, lb_build_addr(p, expr));
  8862. case_end;
  8863. case_ast_node(ise, ImplicitSelectorExpr, expr);
  8864. TypeAndValue tav = type_and_value_of_expr(expr);
  8865. GB_ASSERT(tav.mode == Addressing_Constant);
  8866. return lb_const_value(p->module, tv.type, tv.value);
  8867. case_end;
  8868. case_ast_node(se, SelectorCallExpr, expr);
  8869. GB_ASSERT(se->modified_call);
  8870. TypeAndValue tav = type_and_value_of_expr(expr);
  8871. GB_ASSERT(tav.mode != Addressing_Invalid);
  8872. return lb_build_expr(p, se->call);
  8873. case_end;
  8874. case_ast_node(te, TernaryExpr, expr);
  8875. LLVMValueRef incoming_values[2] = {};
  8876. LLVMBasicBlockRef incoming_blocks[2] = {};
  8877. GB_ASSERT(te->y != nullptr);
  8878. lbBlock *then = lb_create_block(p, "if.then");
  8879. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8880. lbBlock *else_ = lb_create_block(p, "if.else");
  8881. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8882. lb_start_block(p, then);
  8883. Type *type = default_type(type_of_expr(expr));
  8884. lb_open_scope(p, nullptr);
  8885. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8886. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8887. lb_emit_jump(p, done);
  8888. lb_start_block(p, else_);
  8889. lb_open_scope(p, nullptr);
  8890. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8891. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8892. lb_emit_jump(p, done);
  8893. lb_start_block(p, done);
  8894. lbValue res = {};
  8895. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8896. res.type = type;
  8897. GB_ASSERT(p->curr_block->preds.count >= 2);
  8898. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8899. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8900. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8901. return res;
  8902. case_end;
  8903. case_ast_node(te, TernaryIfExpr, expr);
  8904. LLVMValueRef incoming_values[2] = {};
  8905. LLVMBasicBlockRef incoming_blocks[2] = {};
  8906. GB_ASSERT(te->y != nullptr);
  8907. lbBlock *then = lb_create_block(p, "if.then");
  8908. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8909. lbBlock *else_ = lb_create_block(p, "if.else");
  8910. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8911. lb_start_block(p, then);
  8912. Type *type = default_type(type_of_expr(expr));
  8913. lb_open_scope(p, nullptr);
  8914. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8915. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8916. lb_emit_jump(p, done);
  8917. lb_start_block(p, else_);
  8918. lb_open_scope(p, nullptr);
  8919. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8920. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8921. lb_emit_jump(p, done);
  8922. lb_start_block(p, done);
  8923. lbValue res = {};
  8924. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8925. res.type = type;
  8926. GB_ASSERT(p->curr_block->preds.count >= 2);
  8927. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8928. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8929. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8930. return res;
  8931. case_end;
  8932. case_ast_node(te, TernaryWhenExpr, expr);
  8933. TypeAndValue tav = type_and_value_of_expr(te->cond);
  8934. GB_ASSERT(tav.mode == Addressing_Constant);
  8935. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  8936. if (tav.value.value_bool) {
  8937. return lb_build_expr(p, te->x);
  8938. } else {
  8939. return lb_build_expr(p, te->y);
  8940. }
  8941. case_end;
  8942. case_ast_node(ta, TypeAssertion, expr);
  8943. TokenPos pos = ast_token(expr).pos;
  8944. Type *type = tv.type;
  8945. lbValue e = lb_build_expr(p, ta->expr);
  8946. Type *t = type_deref(e.type);
  8947. if (is_type_union(t)) {
  8948. return lb_emit_union_cast(p, e, type, pos);
  8949. } else if (is_type_any(t)) {
  8950. return lb_emit_any_cast(p, e, type, pos);
  8951. } else {
  8952. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8953. }
  8954. case_end;
  8955. case_ast_node(tc, TypeCast, expr);
  8956. lbValue e = lb_build_expr(p, tc->expr);
  8957. switch (tc->token.kind) {
  8958. case Token_cast:
  8959. return lb_emit_conv(p, e, tv.type);
  8960. case Token_transmute:
  8961. return lb_emit_transmute(p, e, tv.type);
  8962. }
  8963. GB_PANIC("Invalid AST TypeCast");
  8964. case_end;
  8965. case_ast_node(ac, AutoCast, expr);
  8966. return lb_build_expr(p, ac->expr);
  8967. case_end;
  8968. case_ast_node(ue, UnaryExpr, expr);
  8969. switch (ue->op.kind) {
  8970. case Token_And: {
  8971. Ast *ue_expr = unparen_expr(ue->expr);
  8972. if (ue_expr->kind == Ast_CompoundLit) {
  8973. lbValue v = lb_build_expr(p, ue->expr);
  8974. Type *type = v.type;
  8975. lbAddr addr = {};
  8976. if (p->is_startup) {
  8977. addr = lb_add_global_generated(p->module, type, v);
  8978. } else {
  8979. addr = lb_add_local_generated(p, type, false);
  8980. }
  8981. lb_addr_store(p, addr, v);
  8982. return addr.addr;
  8983. } else if (ue_expr->kind == Ast_TypeAssertion) {
  8984. GB_ASSERT(is_type_pointer(tv.type));
  8985. ast_node(ta, TypeAssertion, ue_expr);
  8986. TokenPos pos = ast_token(expr).pos;
  8987. Type *type = type_of_expr(ue_expr);
  8988. GB_ASSERT(!is_type_tuple(type));
  8989. lbValue e = lb_build_expr(p, ta->expr);
  8990. Type *t = type_deref(e.type);
  8991. if (is_type_union(t)) {
  8992. lbValue v = e;
  8993. if (!is_type_pointer(v.type)) {
  8994. v = lb_address_from_load_or_generate_local(p, v);
  8995. }
  8996. Type *src_type = type_deref(v.type);
  8997. Type *dst_type = type;
  8998. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  8999. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  9000. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  9001. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9002. args[0] = ok;
  9003. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9004. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9005. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9006. args[4] = lb_typeid(p->module, src_type);
  9007. args[5] = lb_typeid(p->module, dst_type);
  9008. lb_emit_runtime_call(p, "type_assertion_check", args);
  9009. lbValue data_ptr = v;
  9010. return lb_emit_conv(p, data_ptr, tv.type);
  9011. } else if (is_type_any(t)) {
  9012. lbValue v = e;
  9013. if (is_type_pointer(v.type)) {
  9014. v = lb_emit_load(p, v);
  9015. }
  9016. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  9017. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  9018. lbValue id = lb_typeid(p->module, type);
  9019. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  9020. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9021. args[0] = ok;
  9022. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9023. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9024. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9025. args[4] = any_id;
  9026. args[5] = id;
  9027. lb_emit_runtime_call(p, "type_assertion_check", args);
  9028. return lb_emit_conv(p, data_ptr, tv.type);
  9029. } else {
  9030. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  9031. }
  9032. }
  9033. return lb_build_addr_ptr(p, ue->expr);
  9034. }
  9035. default:
  9036. {
  9037. lbValue v = lb_build_expr(p, ue->expr);
  9038. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  9039. }
  9040. }
  9041. case_end;
  9042. case_ast_node(be, BinaryExpr, expr);
  9043. return lb_build_binary_expr(p, expr);
  9044. case_end;
  9045. case_ast_node(pl, ProcLit, expr);
  9046. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  9047. case_end;
  9048. case_ast_node(cl, CompoundLit, expr);
  9049. return lb_addr_load(p, lb_build_addr(p, expr));
  9050. case_end;
  9051. case_ast_node(ce, CallExpr, expr);
  9052. lbValue res = lb_build_call_expr(p, expr);
  9053. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  9054. GB_ASSERT(is_type_tuple(res.type));
  9055. GB_ASSERT(res.type->Tuple.variables.count == 2);
  9056. return lb_emit_struct_ev(p, res, 0);
  9057. }
  9058. return res;
  9059. case_end;
  9060. case_ast_node(se, SliceExpr, expr);
  9061. return lb_addr_load(p, lb_build_addr(p, expr));
  9062. case_end;
  9063. case_ast_node(ie, IndexExpr, expr);
  9064. return lb_addr_load(p, lb_build_addr(p, expr));
  9065. case_end;
  9066. case_ast_node(ia, InlineAsmExpr, expr);
  9067. Type *t = type_of_expr(expr);
  9068. GB_ASSERT(is_type_asm_proc(t));
  9069. String asm_string = {};
  9070. String constraints_string = {};
  9071. TypeAndValue tav;
  9072. tav = type_and_value_of_expr(ia->asm_string);
  9073. GB_ASSERT(is_type_string(tav.type));
  9074. GB_ASSERT(tav.value.kind == ExactValue_String);
  9075. asm_string = tav.value.value_string;
  9076. tav = type_and_value_of_expr(ia->constraints_string);
  9077. GB_ASSERT(is_type_string(tav.type));
  9078. GB_ASSERT(tav.value.kind == ExactValue_String);
  9079. constraints_string = tav.value.value_string;
  9080. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  9081. switch (ia->dialect) {
  9082. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  9083. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  9084. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  9085. default: GB_PANIC("Unhandled inline asm dialect"); break;
  9086. }
  9087. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  9088. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  9089. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  9090. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  9091. ia->has_side_effects, ia->is_align_stack, dialect
  9092. );
  9093. GB_ASSERT(the_asm != nullptr);
  9094. return {the_asm, t};
  9095. case_end;
  9096. }
  9097. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  9098. return {};
  9099. }
  9100. lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  9101. lbAddr *found = map_get(&p->module->soa_values, hash_entity(e));
  9102. GB_ASSERT(found != nullptr);
  9103. return *found;
  9104. }
  9105. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  9106. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  9107. String name = e->token.string;
  9108. Entity *parent = e->using_parent;
  9109. Selection sel = lookup_field(parent->type, name, false);
  9110. GB_ASSERT(sel.entity != nullptr);
  9111. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  9112. lbValue v = {};
  9113. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  9114. // NOTE(bill): using SOA value (probably from for-in statement)
  9115. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  9116. v = lb_addr_get_ptr(p, parent_addr);
  9117. } else if (pv != nullptr) {
  9118. v = *pv;
  9119. } else {
  9120. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  9121. v = lb_build_addr_ptr(p, e->using_expr);
  9122. }
  9123. GB_ASSERT(v.value != nullptr);
  9124. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  9125. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  9126. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  9127. return ptr;
  9128. }
  9129. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  9130. GB_ASSERT(e != nullptr);
  9131. if (e->kind == Entity_Constant) {
  9132. Type *t = default_type(type_of_expr(expr));
  9133. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  9134. lbAddr g = lb_add_global_generated(p->module, t, v);
  9135. return g;
  9136. }
  9137. lbValue v = {};
  9138. lbValue *found = map_get(&p->module->values, hash_entity(e));
  9139. if (found) {
  9140. v = *found;
  9141. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  9142. // NOTE(bill): Calculate the using variable every time
  9143. v = lb_get_using_variable(p, e);
  9144. } else if (e->flags & EntityFlag_SoaPtrField) {
  9145. return lb_get_soa_variable_addr(p, e);
  9146. }
  9147. if (v.value == nullptr) {
  9148. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  9149. LIT(p->name),
  9150. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  9151. GB_PANIC("Unknown value");
  9152. }
  9153. return lb_addr(v);
  9154. }
  9155. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  9156. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  9157. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  9158. map_type = base_type(map_type);
  9159. GB_ASSERT(map_type->kind == Type_Map);
  9160. Type *key_type = map_type->Map.key;
  9161. Type *val_type = map_type->Map.value;
  9162. // NOTE(bill): Removes unnecessary allocation if split gep
  9163. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  9164. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  9165. lb_emit_store(p, gep0, m);
  9166. i64 entry_size = type_size_of (map_type->Map.entry_type);
  9167. i64 entry_align = type_align_of (map_type->Map.entry_type);
  9168. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  9169. i64 key_size = type_size_of (map_type->Map.key);
  9170. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  9171. i64 value_size = type_size_of (map_type->Map.value);
  9172. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  9173. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  9174. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  9175. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  9176. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  9177. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  9178. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  9179. return lb_addr_load(p, h);
  9180. }
  9181. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  9182. if (true) {
  9183. return {};
  9184. }
  9185. lbValue hashed_key = {};
  9186. if (lb_is_const(key)) {
  9187. u64 hash = 0xcbf29ce484222325;
  9188. if (is_type_cstring(key_type)) {
  9189. size_t length = 0;
  9190. char const *text = LLVMGetAsString(key.value, &length);
  9191. hash = fnv64a(text, cast(isize)length);
  9192. } else if (is_type_string(key_type)) {
  9193. unsigned data_indices[] = {0};
  9194. unsigned len_indices[] = {1};
  9195. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  9196. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  9197. isize length = LLVMConstIntGetSExtValue(len);
  9198. char const *text = nullptr;
  9199. if (false && length != 0) {
  9200. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  9201. return {};
  9202. }
  9203. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  9204. size_t ulength = 0;
  9205. text = LLVMGetAsString(data, &ulength);
  9206. gb_printf_err("%td %td %s\n", length, ulength, text);
  9207. length = gb_min(length, cast(isize)ulength);
  9208. }
  9209. hash = fnv64a(text, cast(isize)length);
  9210. } else {
  9211. return {};
  9212. }
  9213. // TODO(bill): other const hash types
  9214. if (build_context.word_size == 4) {
  9215. hash &= 0xffffffffull;
  9216. }
  9217. hashed_key = lb_const_int(m, t_uintptr, hash);
  9218. }
  9219. return hashed_key;
  9220. }
  9221. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  9222. Type *hash_type = t_u64;
  9223. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  9224. lbValue vp = lb_addr_get_ptr(p, v);
  9225. Type *t = base_type(key.type);
  9226. key = lb_emit_conv(p, key, key_type);
  9227. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  9228. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  9229. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  9230. if (hashed_key.value == nullptr) {
  9231. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  9232. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9233. args[0] = key_ptr;
  9234. args[1] = lb_const_int(p->module, t_uintptr, 0);
  9235. hashed_key = lb_emit_call(p, hasher, args);
  9236. }
  9237. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  9238. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  9239. return lb_addr_load(p, v);
  9240. }
  9241. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  9242. lbValue map_key, lbValue map_value, Ast *node) {
  9243. map_type = base_type(map_type);
  9244. GB_ASSERT(map_type->kind == Type_Map);
  9245. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  9246. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  9247. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  9248. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  9249. lb_addr_store(p, value_addr, v);
  9250. auto args = array_make<lbValue>(permanent_allocator(), 4);
  9251. args[0] = h;
  9252. args[1] = key;
  9253. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  9254. args[3] = lb_emit_source_code_location(p, node);
  9255. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  9256. }
  9257. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  9258. expr = unparen_expr(expr);
  9259. switch (expr->kind) {
  9260. case_ast_node(i, Implicit, expr);
  9261. lbAddr v = {};
  9262. switch (i->kind) {
  9263. case Token_context:
  9264. v = lb_find_or_generate_context_ptr(p);
  9265. break;
  9266. }
  9267. GB_ASSERT(v.addr.value != nullptr);
  9268. return v;
  9269. case_end;
  9270. case_ast_node(i, Ident, expr);
  9271. if (is_blank_ident(expr)) {
  9272. lbAddr val = {};
  9273. return val;
  9274. }
  9275. String name = i->token.string;
  9276. Entity *e = entity_of_node(expr);
  9277. return lb_build_addr_from_entity(p, e, expr);
  9278. case_end;
  9279. case_ast_node(se, SelectorExpr, expr);
  9280. Ast *sel = unparen_expr(se->selector);
  9281. if (sel->kind == Ast_Ident) {
  9282. String selector = sel->Ident.token.string;
  9283. TypeAndValue tav = type_and_value_of_expr(se->expr);
  9284. if (tav.mode == Addressing_Invalid) {
  9285. // NOTE(bill): Imports
  9286. Entity *imp = entity_of_node(se->expr);
  9287. if (imp != nullptr) {
  9288. GB_ASSERT(imp->kind == Entity_ImportName);
  9289. }
  9290. return lb_build_addr(p, unparen_expr(se->selector));
  9291. }
  9292. Type *type = base_type(tav.type);
  9293. if (tav.mode == Addressing_Type) { // Addressing_Type
  9294. Selection sel = lookup_field(type, selector, true);
  9295. Entity *e = sel.entity;
  9296. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  9297. GB_ASSERT(e->flags & EntityFlag_TypeField);
  9298. String name = e->token.string;
  9299. /*if (name == "names") {
  9300. lbValue ti_ptr = lb_type_info(m, type);
  9301. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  9302. lbValue names_ptr = nullptr;
  9303. if (is_type_enum(type)) {
  9304. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  9305. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  9306. } else if (type->kind == Type_Struct) {
  9307. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  9308. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  9309. }
  9310. return ir_addr(names_ptr);
  9311. } else */{
  9312. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  9313. }
  9314. GB_PANIC("Unreachable");
  9315. }
  9316. Selection sel = lookup_field(type, selector, false);
  9317. GB_ASSERT(sel.entity != nullptr);
  9318. {
  9319. lbAddr addr = lb_build_addr(p, se->expr);
  9320. if (addr.kind == lbAddr_Map) {
  9321. lbValue v = lb_addr_load(p, addr);
  9322. lbValue a = lb_address_from_load_or_generate_local(p, v);
  9323. a = lb_emit_deep_field_gep(p, a, sel);
  9324. return lb_addr(a);
  9325. } else if (addr.kind == lbAddr_Context) {
  9326. GB_ASSERT(sel.index.count > 0);
  9327. if (addr.ctx.sel.index.count >= 0) {
  9328. sel = selection_combine(addr.ctx.sel, sel);
  9329. }
  9330. addr.ctx.sel = sel;
  9331. addr.kind = lbAddr_Context;
  9332. return addr;
  9333. } else if (addr.kind == lbAddr_SoaVariable) {
  9334. lbValue index = addr.soa.index;
  9335. i32 first_index = sel.index[0];
  9336. Selection sub_sel = sel;
  9337. sub_sel.index.data += 1;
  9338. sub_sel.index.count -= 1;
  9339. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  9340. Type *t = base_type(type_deref(addr.addr.type));
  9341. GB_ASSERT(is_type_soa_struct(t));
  9342. // TODO(bill): Bounds check
  9343. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  9344. lbValue len = lb_soa_struct_len(p, addr.addr);
  9345. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  9346. }
  9347. lbValue item = {};
  9348. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9349. item = lb_emit_array_ep(p, arr, index);
  9350. } else {
  9351. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  9352. }
  9353. if (sub_sel.index.count > 0) {
  9354. item = lb_emit_deep_field_gep(p, item, sub_sel);
  9355. }
  9356. return lb_addr(item);
  9357. }
  9358. lbValue a = lb_addr_get_ptr(p, addr);
  9359. a = lb_emit_deep_field_gep(p, a, sel);
  9360. return lb_addr(a);
  9361. }
  9362. } else {
  9363. GB_PANIC("Unsupported selector expression");
  9364. }
  9365. case_end;
  9366. case_ast_node(se, SelectorCallExpr, expr);
  9367. GB_ASSERT(se->modified_call);
  9368. TypeAndValue tav = type_and_value_of_expr(expr);
  9369. GB_ASSERT(tav.mode != Addressing_Invalid);
  9370. return lb_build_addr(p, se->call);
  9371. case_end;
  9372. case_ast_node(ta, TypeAssertion, expr);
  9373. TokenPos pos = ast_token(expr).pos;
  9374. lbValue e = lb_build_expr(p, ta->expr);
  9375. Type *t = type_deref(e.type);
  9376. if (is_type_union(t)) {
  9377. Type *type = type_of_expr(expr);
  9378. lbAddr v = lb_add_local_generated(p, type, false);
  9379. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  9380. return v;
  9381. } else if (is_type_any(t)) {
  9382. Type *type = type_of_expr(expr);
  9383. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  9384. } else {
  9385. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9386. }
  9387. case_end;
  9388. case_ast_node(ue, UnaryExpr, expr);
  9389. switch (ue->op.kind) {
  9390. case Token_And: {
  9391. return lb_build_addr(p, ue->expr);
  9392. }
  9393. default:
  9394. GB_PANIC("Invalid unary expression for lb_build_addr");
  9395. }
  9396. case_end;
  9397. case_ast_node(be, BinaryExpr, expr);
  9398. lbValue v = lb_build_expr(p, expr);
  9399. Type *t = v.type;
  9400. if (is_type_pointer(t)) {
  9401. return lb_addr(v);
  9402. }
  9403. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  9404. case_end;
  9405. case_ast_node(ie, IndexExpr, expr);
  9406. Type *t = base_type(type_of_expr(ie->expr));
  9407. bool deref = is_type_pointer(t);
  9408. t = base_type(type_deref(t));
  9409. if (is_type_soa_struct(t)) {
  9410. // SOA STRUCTURES!!!!
  9411. lbValue val = lb_build_addr_ptr(p, ie->expr);
  9412. if (deref) {
  9413. val = lb_emit_load(p, val);
  9414. }
  9415. lbValue index = lb_build_expr(p, ie->index);
  9416. return lb_addr_soa_variable(val, index, ie->index);
  9417. }
  9418. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  9419. // SOA Structures for slices/dynamic arrays
  9420. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  9421. lbValue field = lb_build_expr(p, ie->expr);
  9422. lbValue index = lb_build_expr(p, ie->index);
  9423. if (!build_context.no_bounds_check) {
  9424. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  9425. // GB_ASSERT(LLVMIsALoadInst(field.value));
  9426. // lbValue a = {};
  9427. // a.value = LLVMGetOperand(field.value, 0);
  9428. // a.type = alloc_type_pointer(field.type);
  9429. // irInstr *b = &a->Instr;
  9430. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  9431. // lbValue base_struct = b->StructElementPtr.address;
  9432. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  9433. // lbValue len = ir_soa_struct_len(p, base_struct);
  9434. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9435. }
  9436. lbValue val = lb_emit_ptr_offset(p, field, index);
  9437. return lb_addr(val);
  9438. }
  9439. if (!is_type_indexable(t)) {
  9440. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9441. if (found != nullptr) {
  9442. if (found->kind == TypeAtomOp_index_get) {
  9443. return lb_build_addr(p, found->node);
  9444. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  9445. return lb_addr(lb_build_expr(p, found->node));
  9446. } else if (found->kind == TypeAtomOp_index_set) {
  9447. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  9448. if (deref) {
  9449. ptr = lb_emit_load(p, ptr);
  9450. }
  9451. lbAddr addr = {lbAddr_AtomOp_index_set};
  9452. addr.addr = ptr;
  9453. addr.index_set.index = lb_build_expr(p, ie->index);
  9454. addr.index_set.node = found->node;
  9455. return addr;
  9456. }
  9457. }
  9458. }
  9459. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  9460. if (is_type_map(t)) {
  9461. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  9462. if (deref) {
  9463. map_val = lb_emit_load(p, map_val);
  9464. }
  9465. lbValue key = lb_build_expr(p, ie->index);
  9466. key = lb_emit_conv(p, key, t->Map.key);
  9467. Type *result_type = type_of_expr(expr);
  9468. return lb_addr_map(map_val, key, t, result_type);
  9469. }
  9470. switch (t->kind) {
  9471. case Type_Array: {
  9472. lbValue array = {};
  9473. array = lb_build_addr_ptr(p, ie->expr);
  9474. if (deref) {
  9475. array = lb_emit_load(p, array);
  9476. }
  9477. lbValue index = lb_build_expr(p, ie->index);
  9478. index = lb_emit_conv(p, index, t_int);
  9479. lbValue elem = lb_emit_array_ep(p, array, index);
  9480. auto index_tv = type_and_value_of_expr(ie->index);
  9481. if (index_tv.mode != Addressing_Constant) {
  9482. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  9483. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9484. }
  9485. return lb_addr(elem);
  9486. }
  9487. case Type_EnumeratedArray: {
  9488. lbValue array = {};
  9489. array = lb_build_addr_ptr(p, ie->expr);
  9490. if (deref) {
  9491. array = lb_emit_load(p, array);
  9492. }
  9493. Type *index_type = t->EnumeratedArray.index;
  9494. auto index_tv = type_and_value_of_expr(ie->index);
  9495. lbValue index = {};
  9496. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  9497. if (index_tv.mode == Addressing_Constant) {
  9498. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  9499. index = lb_const_value(p->module, index_type, idx);
  9500. } else {
  9501. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9502. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  9503. }
  9504. } else {
  9505. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9506. }
  9507. lbValue elem = lb_emit_array_ep(p, array, index);
  9508. if (index_tv.mode != Addressing_Constant) {
  9509. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  9510. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9511. }
  9512. return lb_addr(elem);
  9513. }
  9514. case Type_Slice: {
  9515. lbValue slice = {};
  9516. slice = lb_build_expr(p, ie->expr);
  9517. if (deref) {
  9518. slice = lb_emit_load(p, slice);
  9519. }
  9520. lbValue elem = lb_slice_elem(p, slice);
  9521. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9522. lbValue len = lb_slice_len(p, slice);
  9523. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9524. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9525. return lb_addr(v);
  9526. }
  9527. case Type_RelativeSlice: {
  9528. lbAddr slice_addr = {};
  9529. if (deref) {
  9530. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  9531. } else {
  9532. slice_addr = lb_build_addr(p, ie->expr);
  9533. }
  9534. lbValue slice = lb_addr_load(p, slice_addr);
  9535. lbValue elem = lb_slice_elem(p, slice);
  9536. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9537. lbValue len = lb_slice_len(p, slice);
  9538. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9539. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9540. return lb_addr(v);
  9541. }
  9542. case Type_DynamicArray: {
  9543. lbValue dynamic_array = {};
  9544. dynamic_array = lb_build_expr(p, ie->expr);
  9545. if (deref) {
  9546. dynamic_array = lb_emit_load(p, dynamic_array);
  9547. }
  9548. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  9549. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  9550. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9551. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9552. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9553. return lb_addr(v);
  9554. }
  9555. case Type_Basic: { // Basic_string
  9556. lbValue str;
  9557. lbValue elem;
  9558. lbValue len;
  9559. lbValue index;
  9560. str = lb_build_expr(p, ie->expr);
  9561. if (deref) {
  9562. str = lb_emit_load(p, str);
  9563. }
  9564. elem = lb_string_elem(p, str);
  9565. len = lb_string_len(p, str);
  9566. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9567. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9568. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  9569. }
  9570. }
  9571. case_end;
  9572. case_ast_node(se, SliceExpr, expr);
  9573. lbValue low = lb_const_int(p->module, t_int, 0);
  9574. lbValue high = {};
  9575. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  9576. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  9577. bool no_indices = se->low == nullptr && se->high == nullptr;
  9578. {
  9579. Type *type = base_type(type_of_expr(se->expr));
  9580. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  9581. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  9582. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  9583. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9584. if (found) {
  9585. lbValue base = lb_build_expr(p, found->node);
  9586. Type *slice_type = base.type;
  9587. lbValue len = lb_slice_len(p, base);
  9588. if (high.value == nullptr) high = len;
  9589. if (!no_indices) {
  9590. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9591. }
  9592. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9593. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9594. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9595. lb_fill_slice(p, slice, elem, new_len);
  9596. return slice;
  9597. }
  9598. }
  9599. }
  9600. }
  9601. lbAddr addr = lb_build_addr(p, se->expr);
  9602. lbValue base = lb_addr_load(p, addr);
  9603. Type *type = base_type(base.type);
  9604. if (is_type_pointer(type)) {
  9605. type = base_type(type_deref(type));
  9606. addr = lb_addr(base);
  9607. base = lb_addr_load(p, addr);
  9608. }
  9609. switch (type->kind) {
  9610. case Type_Slice: {
  9611. Type *slice_type = type;
  9612. lbValue len = lb_slice_len(p, base);
  9613. if (high.value == nullptr) high = len;
  9614. if (!no_indices) {
  9615. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9616. }
  9617. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9618. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9619. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9620. lb_fill_slice(p, slice, elem, new_len);
  9621. return slice;
  9622. }
  9623. case Type_RelativeSlice:
  9624. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  9625. break;
  9626. case Type_DynamicArray: {
  9627. Type *elem_type = type->DynamicArray.elem;
  9628. Type *slice_type = alloc_type_slice(elem_type);
  9629. lbValue len = lb_dynamic_array_len(p, base);
  9630. if (high.value == nullptr) high = len;
  9631. if (!no_indices) {
  9632. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9633. }
  9634. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  9635. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9636. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9637. lb_fill_slice(p, slice, elem, new_len);
  9638. return slice;
  9639. }
  9640. case Type_Array: {
  9641. Type *slice_type = alloc_type_slice(type->Array.elem);
  9642. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  9643. if (high.value == nullptr) high = len;
  9644. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  9645. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  9646. if (!low_const || !high_const) {
  9647. if (!no_indices) {
  9648. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9649. }
  9650. }
  9651. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  9652. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9653. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9654. lb_fill_slice(p, slice, elem, new_len);
  9655. return slice;
  9656. }
  9657. case Type_Basic: {
  9658. GB_ASSERT(type == t_string);
  9659. lbValue len = lb_string_len(p, base);
  9660. if (high.value == nullptr) high = len;
  9661. if (!no_indices) {
  9662. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9663. }
  9664. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  9665. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9666. lbAddr str = lb_add_local_generated(p, t_string, false);
  9667. lb_fill_string(p, str, elem, new_len);
  9668. return str;
  9669. }
  9670. case Type_Struct:
  9671. if (is_type_soa_struct(type)) {
  9672. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  9673. if (high.value == nullptr) high = len;
  9674. if (!no_indices) {
  9675. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9676. }
  9677. #if 1
  9678. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  9679. if (type->Struct.soa_kind == StructSoa_Fixed) {
  9680. i32 field_count = cast(i32)type->Struct.fields.count;
  9681. for (i32 i = 0; i < field_count; i++) {
  9682. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9683. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  9684. field_src = lb_emit_array_ep(p, field_src, low);
  9685. lb_emit_store(p, field_dst, field_src);
  9686. }
  9687. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9688. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9689. lb_emit_store(p, len_dst, new_len);
  9690. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  9691. if (no_indices) {
  9692. lb_addr_store(p, dst, base);
  9693. } else {
  9694. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  9695. for (i32 i = 0; i < field_count; i++) {
  9696. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9697. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9698. field_src = lb_emit_ptr_offset(p, field_src, low);
  9699. lb_emit_store(p, field_dst, field_src);
  9700. }
  9701. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9702. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9703. lb_emit_store(p, len_dst, new_len);
  9704. }
  9705. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  9706. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  9707. for (i32 i = 0; i < field_count; i++) {
  9708. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9709. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9710. field_src = lb_emit_ptr_offset(p, field_src, low);
  9711. lb_emit_store(p, field_dst, field_src);
  9712. }
  9713. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9714. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9715. lb_emit_store(p, len_dst, new_len);
  9716. }
  9717. return dst;
  9718. #endif
  9719. }
  9720. break;
  9721. }
  9722. GB_PANIC("Unknown slicable type");
  9723. case_end;
  9724. case_ast_node(de, DerefExpr, expr);
  9725. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  9726. lbAddr addr = lb_build_addr(p, de->expr);
  9727. addr.relative.deref = true;
  9728. return addr;
  9729. }
  9730. lbValue addr = lb_build_expr(p, de->expr);
  9731. return lb_addr(addr);
  9732. case_end;
  9733. case_ast_node(ce, CallExpr, expr);
  9734. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  9735. lbValue e = lb_build_expr(p, expr);
  9736. lbAddr v = lb_add_local_generated(p, e.type, false);
  9737. lb_addr_store(p, v, e);
  9738. return v;
  9739. case_end;
  9740. case_ast_node(cl, CompoundLit, expr);
  9741. Type *type = type_of_expr(expr);
  9742. Type *bt = base_type(type);
  9743. lbAddr v = lb_add_local_generated(p, type, true);
  9744. Type *et = nullptr;
  9745. switch (bt->kind) {
  9746. case Type_Array: et = bt->Array.elem; break;
  9747. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  9748. case Type_Slice: et = bt->Slice.elem; break;
  9749. case Type_BitSet: et = bt->BitSet.elem; break;
  9750. case Type_SimdVector: et = bt->SimdVector.elem; break;
  9751. }
  9752. String proc_name = {};
  9753. if (p->entity) {
  9754. proc_name = p->entity->token.string;
  9755. }
  9756. TokenPos pos = ast_token(expr).pos;
  9757. switch (bt->kind) {
  9758. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  9759. case Type_Struct: {
  9760. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  9761. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  9762. bool is_raw_union = is_type_raw_union(bt);
  9763. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  9764. TypeStruct *st = &bt->Struct;
  9765. if (cl->elems.count > 0) {
  9766. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9767. for_array(field_index, cl->elems) {
  9768. Ast *elem = cl->elems[field_index];
  9769. lbValue field_expr = {};
  9770. Entity *field = nullptr;
  9771. isize index = field_index;
  9772. if (elem->kind == Ast_FieldValue) {
  9773. ast_node(fv, FieldValue, elem);
  9774. String name = fv->field->Ident.token.string;
  9775. Selection sel = lookup_field(bt, name, false);
  9776. index = sel.index[0];
  9777. elem = fv->value;
  9778. TypeAndValue tav = type_and_value_of_expr(elem);
  9779. } else {
  9780. TypeAndValue tav = type_and_value_of_expr(elem);
  9781. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  9782. index = sel.index[0];
  9783. }
  9784. field = st->fields[index];
  9785. Type *ft = field->type;
  9786. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  9787. continue;
  9788. }
  9789. field_expr = lb_build_expr(p, elem);
  9790. Type *fet = field_expr.type;
  9791. GB_ASSERT(fet->kind != Type_Tuple);
  9792. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  9793. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  9794. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  9795. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9796. lb_emit_store_union_variant(p, gep, field_expr, fet);
  9797. } else {
  9798. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9799. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9800. lb_emit_store(p, gep, fv);
  9801. }
  9802. }
  9803. }
  9804. break;
  9805. }
  9806. case Type_Map: {
  9807. if (cl->elems.count == 0) {
  9808. break;
  9809. }
  9810. {
  9811. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9812. args[0] = lb_gen_map_header(p, v.addr, type);
  9813. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  9814. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  9815. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  9816. }
  9817. for_array(field_index, cl->elems) {
  9818. Ast *elem = cl->elems[field_index];
  9819. ast_node(fv, FieldValue, elem);
  9820. lbValue key = lb_build_expr(p, fv->field);
  9821. lbValue value = lb_build_expr(p, fv->value);
  9822. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  9823. }
  9824. break;
  9825. }
  9826. case Type_Array: {
  9827. if (cl->elems.count > 0) {
  9828. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9829. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9830. // NOTE(bill): Separate value, gep, store into their own chunks
  9831. for_array(i, cl->elems) {
  9832. Ast *elem = cl->elems[i];
  9833. if (elem->kind == Ast_FieldValue) {
  9834. ast_node(fv, FieldValue, elem);
  9835. if (lb_is_elem_const(fv->value, et)) {
  9836. continue;
  9837. }
  9838. if (is_ast_range(fv->field)) {
  9839. ast_node(ie, BinaryExpr, fv->field);
  9840. TypeAndValue lo_tav = ie->left->tav;
  9841. TypeAndValue hi_tav = ie->right->tav;
  9842. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9843. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9844. TokenKind op = ie->op.kind;
  9845. i64 lo = exact_value_to_i64(lo_tav.value);
  9846. i64 hi = exact_value_to_i64(hi_tav.value);
  9847. if (op == Token_Ellipsis) {
  9848. hi += 1;
  9849. }
  9850. lbValue value = lb_build_expr(p, fv->value);
  9851. for (i64 k = lo; k < hi; k++) {
  9852. lbCompoundLitElemTempData data = {};
  9853. data.value = value;
  9854. data.elem_index = cast(i32)k;
  9855. array_add(&temp_data, data);
  9856. }
  9857. } else {
  9858. auto tav = fv->field->tav;
  9859. GB_ASSERT(tav.mode == Addressing_Constant);
  9860. i64 index = exact_value_to_i64(tav.value);
  9861. lbValue value = lb_build_expr(p, fv->value);
  9862. lbCompoundLitElemTempData data = {};
  9863. data.value = lb_emit_conv(p, value, et);
  9864. data.expr = fv->value;
  9865. data.elem_index = cast(i32)index;
  9866. array_add(&temp_data, data);
  9867. }
  9868. } else {
  9869. if (lb_is_elem_const(elem, et)) {
  9870. continue;
  9871. }
  9872. lbCompoundLitElemTempData data = {};
  9873. data.expr = elem;
  9874. data.elem_index = cast(i32)i;
  9875. array_add(&temp_data, data);
  9876. }
  9877. }
  9878. for_array(i, temp_data) {
  9879. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  9880. }
  9881. for_array(i, temp_data) {
  9882. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9883. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9884. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9885. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9886. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9887. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9888. lbValue field_expr = temp_data[i].value;
  9889. Ast *expr = temp_data[i].expr;
  9890. p->return_ptr_hint_value = temp_data[i].gep;
  9891. p->return_ptr_hint_ast = unparen_expr(expr);
  9892. if (field_expr.value == nullptr) {
  9893. field_expr = lb_build_expr(p, expr);
  9894. }
  9895. Type *t = field_expr.type;
  9896. GB_ASSERT(t->kind != Type_Tuple);
  9897. lbValue ev = lb_emit_conv(p, field_expr, et);
  9898. if (!p->return_ptr_hint_used) {
  9899. temp_data[i].value = ev;
  9900. }
  9901. }
  9902. for_array(i, temp_data) {
  9903. if (temp_data[i].value.value != nullptr) {
  9904. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9905. }
  9906. }
  9907. }
  9908. break;
  9909. }
  9910. case Type_EnumeratedArray: {
  9911. if (cl->elems.count > 0) {
  9912. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9913. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9914. // NOTE(bill): Separate value, gep, store into their own chunks
  9915. for_array(i, cl->elems) {
  9916. Ast *elem = cl->elems[i];
  9917. if (elem->kind == Ast_FieldValue) {
  9918. ast_node(fv, FieldValue, elem);
  9919. if (lb_is_elem_const(fv->value, et)) {
  9920. continue;
  9921. }
  9922. if (is_ast_range(fv->field)) {
  9923. ast_node(ie, BinaryExpr, fv->field);
  9924. TypeAndValue lo_tav = ie->left->tav;
  9925. TypeAndValue hi_tav = ie->right->tav;
  9926. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9927. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9928. TokenKind op = ie->op.kind;
  9929. i64 lo = exact_value_to_i64(lo_tav.value);
  9930. i64 hi = exact_value_to_i64(hi_tav.value);
  9931. if (op == Token_Ellipsis) {
  9932. hi += 1;
  9933. }
  9934. lbValue value = lb_build_expr(p, fv->value);
  9935. for (i64 k = lo; k < hi; k++) {
  9936. lbCompoundLitElemTempData data = {};
  9937. data.value = value;
  9938. data.elem_index = cast(i32)k;
  9939. array_add(&temp_data, data);
  9940. }
  9941. } else {
  9942. auto tav = fv->field->tav;
  9943. GB_ASSERT(tav.mode == Addressing_Constant);
  9944. i64 index = exact_value_to_i64(tav.value);
  9945. lbValue value = lb_build_expr(p, fv->value);
  9946. lbCompoundLitElemTempData data = {};
  9947. data.value = lb_emit_conv(p, value, et);
  9948. data.expr = fv->value;
  9949. data.elem_index = cast(i32)index;
  9950. array_add(&temp_data, data);
  9951. }
  9952. } else {
  9953. if (lb_is_elem_const(elem, et)) {
  9954. continue;
  9955. }
  9956. lbCompoundLitElemTempData data = {};
  9957. data.expr = elem;
  9958. data.elem_index = cast(i32)i;
  9959. array_add(&temp_data, data);
  9960. }
  9961. }
  9962. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  9963. for_array(i, temp_data) {
  9964. i32 index = temp_data[i].elem_index - index_offset;
  9965. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  9966. }
  9967. for_array(i, temp_data) {
  9968. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9969. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9970. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9971. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9972. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9973. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9974. lbValue field_expr = temp_data[i].value;
  9975. Ast *expr = temp_data[i].expr;
  9976. p->return_ptr_hint_value = temp_data[i].gep;
  9977. p->return_ptr_hint_ast = unparen_expr(expr);
  9978. if (field_expr.value == nullptr) {
  9979. field_expr = lb_build_expr(p, expr);
  9980. }
  9981. Type *t = field_expr.type;
  9982. GB_ASSERT(t->kind != Type_Tuple);
  9983. lbValue ev = lb_emit_conv(p, field_expr, et);
  9984. if (!p->return_ptr_hint_used) {
  9985. temp_data[i].value = ev;
  9986. }
  9987. }
  9988. for_array(i, temp_data) {
  9989. if (temp_data[i].value.value != nullptr) {
  9990. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9991. }
  9992. }
  9993. }
  9994. break;
  9995. }
  9996. case Type_Slice: {
  9997. if (cl->elems.count > 0) {
  9998. Type *elem_type = bt->Slice.elem;
  9999. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  10000. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  10001. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  10002. lbValue data = lb_slice_elem(p, slice);
  10003. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10004. for_array(i, cl->elems) {
  10005. Ast *elem = cl->elems[i];
  10006. if (elem->kind == Ast_FieldValue) {
  10007. ast_node(fv, FieldValue, elem);
  10008. if (lb_is_elem_const(fv->value, et)) {
  10009. continue;
  10010. }
  10011. if (is_ast_range(fv->field)) {
  10012. ast_node(ie, BinaryExpr, fv->field);
  10013. TypeAndValue lo_tav = ie->left->tav;
  10014. TypeAndValue hi_tav = ie->right->tav;
  10015. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10016. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10017. TokenKind op = ie->op.kind;
  10018. i64 lo = exact_value_to_i64(lo_tav.value);
  10019. i64 hi = exact_value_to_i64(hi_tav.value);
  10020. if (op == Token_Ellipsis) {
  10021. hi += 1;
  10022. }
  10023. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10024. for (i64 k = lo; k < hi; k++) {
  10025. lbCompoundLitElemTempData data = {};
  10026. data.value = value;
  10027. data.elem_index = cast(i32)k;
  10028. array_add(&temp_data, data);
  10029. }
  10030. } else {
  10031. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10032. i64 index = exact_value_to_i64(fv->field->tav.value);
  10033. lbValue field_expr = lb_build_expr(p, fv->value);
  10034. GB_ASSERT(!is_type_tuple(field_expr.type));
  10035. lbValue ev = lb_emit_conv(p, field_expr, et);
  10036. lbCompoundLitElemTempData data = {};
  10037. data.value = ev;
  10038. data.elem_index = cast(i32)index;
  10039. array_add(&temp_data, data);
  10040. }
  10041. } else {
  10042. if (lb_is_elem_const(elem, et)) {
  10043. continue;
  10044. }
  10045. lbValue field_expr = lb_build_expr(p, elem);
  10046. GB_ASSERT(!is_type_tuple(field_expr.type));
  10047. lbValue ev = lb_emit_conv(p, field_expr, et);
  10048. lbCompoundLitElemTempData data = {};
  10049. data.value = ev;
  10050. data.elem_index = cast(i32)i;
  10051. array_add(&temp_data, data);
  10052. }
  10053. }
  10054. for_array(i, temp_data) {
  10055. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  10056. }
  10057. for_array(i, temp_data) {
  10058. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10059. }
  10060. {
  10061. lbValue count = {};
  10062. count.type = t_int;
  10063. if (lb_is_const(slice)) {
  10064. unsigned indices[1] = {1};
  10065. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  10066. } else {
  10067. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  10068. }
  10069. lb_fill_slice(p, v, data, count);
  10070. }
  10071. }
  10072. break;
  10073. }
  10074. case Type_DynamicArray: {
  10075. if (cl->elems.count == 0) {
  10076. break;
  10077. }
  10078. Type *et = bt->DynamicArray.elem;
  10079. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  10080. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  10081. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  10082. {
  10083. auto args = array_make<lbValue>(permanent_allocator(), 5);
  10084. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  10085. args[1] = size;
  10086. args[2] = align;
  10087. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  10088. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  10089. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  10090. }
  10091. lbValue items = lb_generate_local_array(p, et, item_count);
  10092. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  10093. for_array(i, cl->elems) {
  10094. Ast *elem = cl->elems[i];
  10095. if (elem->kind == Ast_FieldValue) {
  10096. ast_node(fv, FieldValue, elem);
  10097. if (is_ast_range(fv->field)) {
  10098. ast_node(ie, BinaryExpr, fv->field);
  10099. TypeAndValue lo_tav = ie->left->tav;
  10100. TypeAndValue hi_tav = ie->right->tav;
  10101. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10102. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10103. TokenKind op = ie->op.kind;
  10104. i64 lo = exact_value_to_i64(lo_tav.value);
  10105. i64 hi = exact_value_to_i64(hi_tav.value);
  10106. if (op == Token_Ellipsis) {
  10107. hi += 1;
  10108. }
  10109. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10110. for (i64 k = lo; k < hi; k++) {
  10111. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  10112. lb_emit_store(p, ep, value);
  10113. }
  10114. } else {
  10115. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10116. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  10117. lbValue ev = lb_build_expr(p, fv->value);
  10118. lbValue value = lb_emit_conv(p, ev, et);
  10119. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  10120. lb_emit_store(p, ep, value);
  10121. }
  10122. } else {
  10123. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  10124. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  10125. lb_emit_store(p, ep, value);
  10126. }
  10127. }
  10128. {
  10129. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10130. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  10131. args[1] = size;
  10132. args[2] = align;
  10133. args[3] = lb_emit_conv(p, items, t_rawptr);
  10134. args[4] = lb_const_int(p->module, t_int, item_count);
  10135. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  10136. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  10137. }
  10138. break;
  10139. }
  10140. case Type_Basic: {
  10141. GB_ASSERT(is_type_any(bt));
  10142. if (cl->elems.count > 0) {
  10143. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10144. String field_names[2] = {
  10145. str_lit("data"),
  10146. str_lit("id"),
  10147. };
  10148. Type *field_types[2] = {
  10149. t_rawptr,
  10150. t_typeid,
  10151. };
  10152. for_array(field_index, cl->elems) {
  10153. Ast *elem = cl->elems[field_index];
  10154. lbValue field_expr = {};
  10155. isize index = field_index;
  10156. if (elem->kind == Ast_FieldValue) {
  10157. ast_node(fv, FieldValue, elem);
  10158. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  10159. index = sel.index[0];
  10160. elem = fv->value;
  10161. } else {
  10162. TypeAndValue tav = type_and_value_of_expr(elem);
  10163. Selection sel = lookup_field(bt, field_names[field_index], false);
  10164. index = sel.index[0];
  10165. }
  10166. field_expr = lb_build_expr(p, elem);
  10167. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  10168. Type *ft = field_types[index];
  10169. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10170. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10171. lb_emit_store(p, gep, fv);
  10172. }
  10173. }
  10174. break;
  10175. }
  10176. case Type_BitSet: {
  10177. i64 sz = type_size_of(type);
  10178. if (cl->elems.count > 0 && sz > 0) {
  10179. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10180. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  10181. for_array(i, cl->elems) {
  10182. Ast *elem = cl->elems[i];
  10183. GB_ASSERT(elem->kind != Ast_FieldValue);
  10184. if (lb_is_elem_const(elem, et)) {
  10185. continue;
  10186. }
  10187. lbValue expr = lb_build_expr(p, elem);
  10188. GB_ASSERT(expr.type->kind != Type_Tuple);
  10189. Type *it = bit_set_to_int(bt);
  10190. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  10191. lbValue e = lb_emit_conv(p, expr, it);
  10192. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  10193. e = lb_emit_arith(p, Token_Shl, one, e, it);
  10194. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  10195. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  10196. new_value = lb_emit_transmute(p, new_value, type);
  10197. lb_addr_store(p, v, new_value);
  10198. }
  10199. }
  10200. break;
  10201. }
  10202. }
  10203. return v;
  10204. case_end;
  10205. case_ast_node(tc, TypeCast, expr);
  10206. Type *type = type_of_expr(expr);
  10207. lbValue x = lb_build_expr(p, tc->expr);
  10208. lbValue e = {};
  10209. switch (tc->token.kind) {
  10210. case Token_cast:
  10211. e = lb_emit_conv(p, x, type);
  10212. break;
  10213. case Token_transmute:
  10214. e = lb_emit_transmute(p, x, type);
  10215. break;
  10216. default:
  10217. GB_PANIC("Invalid AST TypeCast");
  10218. }
  10219. lbAddr v = lb_add_local_generated(p, type, false);
  10220. lb_addr_store(p, v, e);
  10221. return v;
  10222. case_end;
  10223. case_ast_node(ac, AutoCast, expr);
  10224. return lb_build_addr(p, ac->expr);
  10225. case_end;
  10226. }
  10227. TokenPos token_pos = ast_token(expr).pos;
  10228. GB_PANIC("Unexpected address expression\n"
  10229. "\tAst: %.*s @ "
  10230. "%s\n",
  10231. LIT(ast_strings[expr->kind]),
  10232. token_pos_to_string(token_pos));
  10233. return {};
  10234. }
  10235. void lb_init_module(lbModule *m, Checker *c) {
  10236. m->info = &c->info;
  10237. m->ctx = LLVMGetGlobalContext();
  10238. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  10239. // m->debug_builder = nullptr;
  10240. if (build_context.ODIN_DEBUG) {
  10241. enum {DEBUG_METADATA_VERSION = 3};
  10242. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  10243. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  10244. if (build_context.metrics.os == TargetOs_windows) {
  10245. LLVMMetadataRef ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true));
  10246. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "CodeView", 8, ref);
  10247. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  10248. }
  10249. }
  10250. m->state_flags = 0;
  10251. m->state_flags |= StateFlag_bounds_check;
  10252. gb_mutex_init(&m->mutex);
  10253. gbAllocator a = heap_allocator();
  10254. map_init(&m->types, a);
  10255. map_init(&m->llvm_types, a);
  10256. map_init(&m->values, a);
  10257. map_init(&m->soa_values, a);
  10258. string_map_init(&m->members, a);
  10259. map_init(&m->procedure_values, a);
  10260. string_map_init(&m->procedures, a);
  10261. string_map_init(&m->const_strings, a);
  10262. map_init(&m->anonymous_proc_lits, a);
  10263. map_init(&m->function_type_map, a);
  10264. map_init(&m->equal_procs, a);
  10265. map_init(&m->hasher_procs, a);
  10266. array_init(&m->procedures_to_generate, a, 0, 1024);
  10267. array_init(&m->foreign_library_paths, a, 0, 1024);
  10268. map_init(&m->debug_values, a);
  10269. array_init(&m->debug_incomplete_types, a, 0, 1024);
  10270. }
  10271. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  10272. if (global_error_collector.count != 0) {
  10273. return false;
  10274. }
  10275. isize tc = c->parser->total_token_count;
  10276. if (tc < 2) {
  10277. return false;
  10278. }
  10279. String init_fullpath = c->parser->init_fullpath;
  10280. if (build_context.out_filepath.len == 0) {
  10281. gen->output_name = remove_directory_from_path(init_fullpath);
  10282. gen->output_name = remove_extension_from_path(gen->output_name);
  10283. gen->output_name = string_trim_whitespace(gen->output_name);
  10284. if (gen->output_name.len == 0) {
  10285. gen->output_name = c->info.init_scope->pkg->name;
  10286. }
  10287. gen->output_base = gen->output_name;
  10288. } else {
  10289. gen->output_name = build_context.out_filepath;
  10290. gen->output_name = string_trim_whitespace(gen->output_name);
  10291. if (gen->output_name.len == 0) {
  10292. gen->output_name = c->info.init_scope->pkg->name;
  10293. }
  10294. isize pos = string_extension_position(gen->output_name);
  10295. if (pos < 0) {
  10296. gen->output_base = gen->output_name;
  10297. } else {
  10298. gen->output_base = substring(gen->output_name, 0, pos);
  10299. }
  10300. }
  10301. gbAllocator ha = heap_allocator();
  10302. array_init(&gen->output_object_paths, ha);
  10303. gen->output_base = path_to_full_path(ha, gen->output_base);
  10304. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  10305. output_file_path = gb_string_appendc(output_file_path, ".obj");
  10306. defer (gb_string_free(output_file_path));
  10307. gen->info = &c->info;
  10308. lb_init_module(&gen->module, c);
  10309. return true;
  10310. }
  10311. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  10312. GB_ASSERT(type != nullptr);
  10313. type = default_type(type);
  10314. isize max_len = 7+8+1;
  10315. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  10316. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  10317. m->global_generated_index++;
  10318. String name = make_string(str, len-1);
  10319. Scope *scope = nullptr;
  10320. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  10321. lbValue g = {};
  10322. g.type = alloc_type_pointer(type);
  10323. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  10324. if (value.value != nullptr) {
  10325. GB_ASSERT(LLVMIsConstant(value.value));
  10326. LLVMSetInitializer(g.value, value.value);
  10327. } else {
  10328. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  10329. }
  10330. lb_add_entity(m, e, g);
  10331. lb_add_member(m, name, g);
  10332. return lb_addr(g);
  10333. }
  10334. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  10335. AstPackage *p = m->info->runtime_package;
  10336. Entity *e = scope_lookup_current(p->scope, name);
  10337. lbValue *found = map_get(&m->values, hash_entity(e));
  10338. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  10339. lbValue value = *found;
  10340. return value;
  10341. }
  10342. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  10343. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  10344. lbValue *found = map_get(&m->values, hash_entity(e));
  10345. GB_ASSERT_MSG(found != nullptr, "Unable to find value '%.*s.%.*s'", LIT(pkg), LIT(name));
  10346. lbValue value = *found;
  10347. return value;
  10348. }
  10349. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  10350. i32 index = cast(i32)lb_type_info_index(m->info, type);
  10351. GB_ASSERT(index >= 0);
  10352. // gb_printf_err("%d %s\n", index, type_to_string(type));
  10353. LLVMValueRef indices[2] = {
  10354. LLVMConstInt(lb_type(m, t_int), 0, false),
  10355. LLVMConstInt(lb_type(m, t_int), index, false),
  10356. };
  10357. lbValue res = {};
  10358. res.type = t_type_info_ptr;
  10359. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  10360. return res;
  10361. }
  10362. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  10363. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  10364. lb_global_type_info_member_types_index += cast(i32)count;
  10365. return offset;
  10366. }
  10367. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  10368. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  10369. lb_global_type_info_member_names_index += cast(i32)count;
  10370. return offset;
  10371. }
  10372. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  10373. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  10374. lb_global_type_info_member_offsets_index += cast(i32)count;
  10375. return offset;
  10376. }
  10377. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  10378. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  10379. lb_global_type_info_member_usings_index += cast(i32)count;
  10380. return offset;
  10381. }
  10382. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  10383. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  10384. lb_global_type_info_member_tags_index += cast(i32)count;
  10385. return offset;
  10386. }
  10387. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  10388. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  10389. return lb_addr_get_ptr(p, addr);
  10390. }
  10391. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  10392. Token token = {Token_Ident};
  10393. isize name_len = prefix.len + 1 + 20;
  10394. auto suffix_id = cast(unsigned long long)id;
  10395. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  10396. gb_snprintf(text, name_len,
  10397. "%.*s-%llu", LIT(prefix), suffix_id);
  10398. text[name_len] = 0;
  10399. String s = make_string_c(text);
  10400. Type *t = alloc_type_array(elem_type, count);
  10401. lbValue g = {};
  10402. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  10403. g.type = alloc_type_pointer(t);
  10404. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  10405. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  10406. string_map_set(&m->members, s, g);
  10407. return g;
  10408. }
  10409. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  10410. lbModule *m = p->module;
  10411. LLVMContextRef ctx = m->ctx;
  10412. CheckerInfo *info = m->info;
  10413. {
  10414. // NOTE(bill): Set the type_table slice with the global backing array
  10415. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  10416. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  10417. GB_ASSERT(is_type_array(type));
  10418. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  10419. LLVMValueRef values[2] = {
  10420. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  10421. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  10422. };
  10423. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  10424. LLVMSetInitializer(global_type_table.value, slice);
  10425. }
  10426. // Useful types
  10427. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  10428. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  10429. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  10430. Type *t_type_info_flags = type_info_flags_entity->type;
  10431. i32 type_info_member_types_index = 0;
  10432. i32 type_info_member_names_index = 0;
  10433. i32 type_info_member_offsets_index = 0;
  10434. for_array(type_info_type_index, info->type_info_types) {
  10435. Type *t = info->type_info_types[type_info_type_index];
  10436. if (t == nullptr || t == t_invalid) {
  10437. continue;
  10438. }
  10439. isize entry_index = lb_type_info_index(info, t, false);
  10440. if (entry_index <= 0) {
  10441. continue;
  10442. }
  10443. lbValue tag = {};
  10444. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  10445. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  10446. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  10447. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  10448. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  10449. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  10450. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  10451. switch (t->kind) {
  10452. case Type_Named: {
  10453. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  10454. LLVMValueRef pkg_name = nullptr;
  10455. if (t->Named.type_name->pkg) {
  10456. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  10457. } else {
  10458. pkg_name = LLVMConstNull(lb_type(m, t_string));
  10459. }
  10460. String proc_name = {};
  10461. if (t->Named.type_name->parent_proc_decl) {
  10462. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  10463. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  10464. proc_name = decl->entity->token.string;
  10465. }
  10466. }
  10467. TokenPos pos = t->Named.type_name->token.pos;
  10468. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  10469. LLVMValueRef vals[4] = {
  10470. lb_const_string(p->module, t->Named.type_name->token.string).value,
  10471. lb_get_type_info_ptr(m, t->Named.base).value,
  10472. pkg_name,
  10473. loc.value
  10474. };
  10475. lbValue res = {};
  10476. res.type = type_deref(tag.type);
  10477. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10478. lb_emit_store(p, tag, res);
  10479. break;
  10480. }
  10481. case Type_Basic:
  10482. switch (t->Basic.kind) {
  10483. case Basic_bool:
  10484. case Basic_b8:
  10485. case Basic_b16:
  10486. case Basic_b32:
  10487. case Basic_b64:
  10488. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  10489. break;
  10490. case Basic_i8:
  10491. case Basic_u8:
  10492. case Basic_i16:
  10493. case Basic_u16:
  10494. case Basic_i32:
  10495. case Basic_u32:
  10496. case Basic_i64:
  10497. case Basic_u64:
  10498. case Basic_i128:
  10499. case Basic_u128:
  10500. case Basic_i16le:
  10501. case Basic_u16le:
  10502. case Basic_i32le:
  10503. case Basic_u32le:
  10504. case Basic_i64le:
  10505. case Basic_u64le:
  10506. case Basic_i128le:
  10507. case Basic_u128le:
  10508. case Basic_i16be:
  10509. case Basic_u16be:
  10510. case Basic_i32be:
  10511. case Basic_u32be:
  10512. case Basic_i64be:
  10513. case Basic_u64be:
  10514. case Basic_i128be:
  10515. case Basic_u128be:
  10516. case Basic_int:
  10517. case Basic_uint:
  10518. case Basic_uintptr: {
  10519. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  10520. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  10521. // NOTE(bill): This is matches the runtime layout
  10522. u8 endianness_value = 0;
  10523. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10524. endianness_value = 1;
  10525. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10526. endianness_value = 2;
  10527. }
  10528. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10529. LLVMValueRef vals[2] = {
  10530. is_signed.value,
  10531. endianness.value,
  10532. };
  10533. lbValue res = {};
  10534. res.type = type_deref(tag.type);
  10535. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10536. lb_emit_store(p, tag, res);
  10537. break;
  10538. }
  10539. case Basic_rune:
  10540. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  10541. break;
  10542. // case Basic_f16:
  10543. case Basic_f32:
  10544. case Basic_f64:
  10545. case Basic_f32le:
  10546. case Basic_f64le:
  10547. case Basic_f32be:
  10548. case Basic_f64be:
  10549. {
  10550. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  10551. // NOTE(bill): This is matches the runtime layout
  10552. u8 endianness_value = 0;
  10553. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10554. endianness_value = 1;
  10555. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10556. endianness_value = 2;
  10557. }
  10558. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10559. LLVMValueRef vals[1] = {
  10560. endianness.value,
  10561. };
  10562. lbValue res = {};
  10563. res.type = type_deref(tag.type);
  10564. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10565. lb_emit_store(p, tag, res);
  10566. }
  10567. break;
  10568. // case Basic_complex32:
  10569. case Basic_complex64:
  10570. case Basic_complex128:
  10571. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  10572. break;
  10573. case Basic_quaternion128:
  10574. case Basic_quaternion256:
  10575. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  10576. break;
  10577. case Basic_rawptr:
  10578. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10579. break;
  10580. case Basic_string:
  10581. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10582. break;
  10583. case Basic_cstring:
  10584. {
  10585. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10586. LLVMValueRef vals[1] = {
  10587. lb_const_bool(m, t_bool, true).value,
  10588. };
  10589. lbValue res = {};
  10590. res.type = type_deref(tag.type);
  10591. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10592. lb_emit_store(p, tag, res);
  10593. }
  10594. break;
  10595. case Basic_any:
  10596. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  10597. break;
  10598. case Basic_typeid:
  10599. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  10600. break;
  10601. }
  10602. break;
  10603. case Type_Pointer: {
  10604. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10605. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  10606. LLVMValueRef vals[1] = {
  10607. gep.value,
  10608. };
  10609. lbValue res = {};
  10610. res.type = type_deref(tag.type);
  10611. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10612. lb_emit_store(p, tag, res);
  10613. break;
  10614. }
  10615. case Type_Array: {
  10616. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  10617. i64 ez = type_size_of(t->Array.elem);
  10618. LLVMValueRef vals[3] = {
  10619. lb_get_type_info_ptr(m, t->Array.elem).value,
  10620. lb_const_int(m, t_int, ez).value,
  10621. lb_const_int(m, t_int, t->Array.count).value,
  10622. };
  10623. lbValue res = {};
  10624. res.type = type_deref(tag.type);
  10625. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10626. lb_emit_store(p, tag, res);
  10627. break;
  10628. }
  10629. case Type_EnumeratedArray: {
  10630. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  10631. LLVMValueRef vals[6] = {
  10632. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  10633. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  10634. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  10635. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  10636. // Unions
  10637. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10638. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10639. };
  10640. lbValue res = {};
  10641. res.type = type_deref(tag.type);
  10642. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10643. lb_emit_store(p, tag, res);
  10644. // NOTE(bill): Union assignment
  10645. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  10646. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  10647. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  10648. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  10649. lb_emit_store(p, min_value, min_v);
  10650. lb_emit_store(p, max_value, max_v);
  10651. break;
  10652. }
  10653. case Type_DynamicArray: {
  10654. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  10655. LLVMValueRef vals[2] = {
  10656. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  10657. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  10658. };
  10659. lbValue res = {};
  10660. res.type = type_deref(tag.type);
  10661. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10662. lb_emit_store(p, tag, res);
  10663. break;
  10664. }
  10665. case Type_Slice: {
  10666. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  10667. LLVMValueRef vals[2] = {
  10668. lb_get_type_info_ptr(m, t->Slice.elem).value,
  10669. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  10670. };
  10671. lbValue res = {};
  10672. res.type = type_deref(tag.type);
  10673. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10674. lb_emit_store(p, tag, res);
  10675. break;
  10676. }
  10677. case Type_Proc: {
  10678. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  10679. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10680. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10681. if (t->Proc.params != nullptr) {
  10682. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  10683. }
  10684. if (t->Proc.results != nullptr) {
  10685. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  10686. }
  10687. LLVMValueRef vals[4] = {
  10688. params,
  10689. results,
  10690. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  10691. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  10692. };
  10693. lbValue res = {};
  10694. res.type = type_deref(tag.type);
  10695. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10696. lb_emit_store(p, tag, res);
  10697. break;
  10698. }
  10699. case Type_Tuple: {
  10700. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  10701. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  10702. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  10703. for_array(i, t->Tuple.variables) {
  10704. // NOTE(bill): offset is not used for tuples
  10705. Entity *f = t->Tuple.variables[i];
  10706. lbValue index = lb_const_int(m, t_int, i);
  10707. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10708. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  10709. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10710. if (f->token.string.len > 0) {
  10711. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10712. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10713. }
  10714. }
  10715. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  10716. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  10717. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  10718. LLVMValueRef vals[2] = {
  10719. types_slice,
  10720. names_slice,
  10721. };
  10722. lbValue res = {};
  10723. res.type = type_deref(tag.type);
  10724. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10725. lb_emit_store(p, tag, res);
  10726. break;
  10727. }
  10728. case Type_Enum:
  10729. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  10730. {
  10731. GB_ASSERT(t->Enum.base_type != nullptr);
  10732. // 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));
  10733. LLVMValueRef vals[3] = {};
  10734. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  10735. if (t->Enum.fields.count > 0) {
  10736. auto fields = t->Enum.fields;
  10737. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  10738. str_lit("$enum_names"), cast(i64)entry_index);
  10739. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  10740. str_lit("$enum_values"), cast(i64)entry_index);
  10741. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10742. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10743. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10744. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  10745. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  10746. for_array(i, fields) {
  10747. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  10748. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  10749. }
  10750. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  10751. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  10752. LLVMSetInitializer(name_array.value, name_init);
  10753. LLVMSetInitializer(value_array.value, value_init);
  10754. lbValue v_count = lb_const_int(m, t_int, fields.count);
  10755. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  10756. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  10757. } else {
  10758. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  10759. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  10760. }
  10761. lbValue res = {};
  10762. res.type = type_deref(tag.type);
  10763. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10764. lb_emit_store(p, tag, res);
  10765. }
  10766. break;
  10767. case Type_Union: {
  10768. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  10769. {
  10770. LLVMValueRef vals[6] = {};
  10771. isize variant_count = gb_max(0, t->Union.variants.count);
  10772. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  10773. // NOTE(bill): Zeroth is nil so ignore it
  10774. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10775. Type *vt = t->Union.variants[variant_index];
  10776. lbValue tip = lb_get_type_info_ptr(m, vt);
  10777. lbValue index = lb_const_int(m, t_int, variant_index);
  10778. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10779. lb_emit_store(p, type_info, lb_type_info(m, vt));
  10780. }
  10781. lbValue count = lb_const_int(m, t_int, variant_count);
  10782. vals[0] = llvm_const_slice(m, memory_types, count);
  10783. i64 tag_size = union_tag_size(t);
  10784. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10785. if (tag_size > 0) {
  10786. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  10787. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  10788. } else {
  10789. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  10790. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10791. }
  10792. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  10793. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  10794. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  10795. lbValue res = {};
  10796. res.type = type_deref(tag.type);
  10797. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10798. lb_emit_store(p, tag, res);
  10799. }
  10800. break;
  10801. }
  10802. case Type_Struct: {
  10803. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  10804. LLVMValueRef vals[12] = {};
  10805. {
  10806. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  10807. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  10808. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  10809. vals[5] = is_packed.value;
  10810. vals[6] = is_raw_union.value;
  10811. vals[7] = is_custom_align.value;
  10812. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  10813. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  10814. }
  10815. if (t->Struct.soa_kind != StructSoa_None) {
  10816. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  10817. Type *kind_type = type_deref(kind.type);
  10818. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  10819. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  10820. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  10821. vals[9] = soa_kind.value;
  10822. vals[10] = soa_type.value;
  10823. vals[11] = soa_len.value;
  10824. }
  10825. }
  10826. isize count = t->Struct.fields.count;
  10827. if (count > 0) {
  10828. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  10829. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  10830. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  10831. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  10832. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  10833. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10834. for (isize source_index = 0; source_index < count; source_index++) {
  10835. // TODO(bill): Order fields in source order not layout order
  10836. Entity *f = t->Struct.fields[source_index];
  10837. lbValue tip = lb_get_type_info_ptr(m, f->type);
  10838. i64 foffset = 0;
  10839. if (!t->Struct.is_raw_union) {
  10840. foffset = t->Struct.offsets[f->Variable.field_index];
  10841. }
  10842. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10843. lbValue index = lb_const_int(m, t_int, source_index);
  10844. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10845. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  10846. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  10847. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10848. if (f->token.string.len > 0) {
  10849. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10850. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10851. }
  10852. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  10853. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  10854. if (t->Struct.tags.count > 0) {
  10855. String tag_string = t->Struct.tags[source_index];
  10856. if (tag_string.len > 0) {
  10857. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  10858. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  10859. }
  10860. }
  10861. }
  10862. lbValue cv = lb_const_int(m, t_int, count);
  10863. vals[0] = llvm_const_slice(m, memory_types, cv);
  10864. vals[1] = llvm_const_slice(m, memory_names, cv);
  10865. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  10866. vals[3] = llvm_const_slice(m, memory_usings, cv);
  10867. vals[4] = llvm_const_slice(m, memory_tags, cv);
  10868. }
  10869. for (isize i = 0; i < gb_count_of(vals); i++) {
  10870. if (vals[i] == nullptr) {
  10871. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  10872. }
  10873. }
  10874. lbValue res = {};
  10875. res.type = type_deref(tag.type);
  10876. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10877. lb_emit_store(p, tag, res);
  10878. break;
  10879. }
  10880. case Type_Map: {
  10881. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  10882. init_map_internal_types(t);
  10883. LLVMValueRef vals[5] = {
  10884. lb_get_type_info_ptr(m, t->Map.key).value,
  10885. lb_get_type_info_ptr(m, t->Map.value).value,
  10886. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  10887. lb_get_equal_proc_for_type(m, t->Map.key).value,
  10888. lb_get_hasher_proc_for_type(m, t->Map.key).value
  10889. };
  10890. lbValue res = {};
  10891. res.type = type_deref(tag.type);
  10892. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10893. lb_emit_store(p, tag, res);
  10894. break;
  10895. }
  10896. case Type_BitSet:
  10897. {
  10898. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  10899. GB_ASSERT(is_type_typed(t->BitSet.elem));
  10900. LLVMValueRef vals[4] = {
  10901. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  10902. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  10903. lb_const_int(m, t_i64, t->BitSet.lower).value,
  10904. lb_const_int(m, t_i64, t->BitSet.upper).value,
  10905. };
  10906. if (t->BitSet.underlying != nullptr) {
  10907. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  10908. }
  10909. lbValue res = {};
  10910. res.type = type_deref(tag.type);
  10911. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10912. lb_emit_store(p, tag, res);
  10913. }
  10914. break;
  10915. case Type_SimdVector:
  10916. {
  10917. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  10918. LLVMValueRef vals[4] = {};
  10919. if (t->SimdVector.is_x86_mmx) {
  10920. vals[3] = lb_const_bool(m, t_bool, true).value;
  10921. } else {
  10922. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  10923. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  10924. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  10925. }
  10926. lbValue res = {};
  10927. res.type = type_deref(tag.type);
  10928. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10929. lb_emit_store(p, tag, res);
  10930. }
  10931. break;
  10932. case Type_RelativePointer:
  10933. {
  10934. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  10935. LLVMValueRef vals[2] = {
  10936. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  10937. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  10938. };
  10939. lbValue res = {};
  10940. res.type = type_deref(tag.type);
  10941. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10942. lb_emit_store(p, tag, res);
  10943. }
  10944. break;
  10945. case Type_RelativeSlice:
  10946. {
  10947. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  10948. LLVMValueRef vals[2] = {
  10949. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  10950. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  10951. };
  10952. lbValue res = {};
  10953. res.type = type_deref(tag.type);
  10954. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10955. lb_emit_store(p, tag, res);
  10956. }
  10957. break;
  10958. }
  10959. if (tag.value != nullptr) {
  10960. Type *tag_type = type_deref(tag.type);
  10961. GB_ASSERT(is_type_named(tag_type));
  10962. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  10963. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  10964. } else {
  10965. if (t != t_llvm_bool) {
  10966. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  10967. }
  10968. }
  10969. }
  10970. }
  10971. void lb_generate_code(lbGenerator *gen) {
  10972. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  10973. TIME_SECTION("LLVM Initializtion");
  10974. lbModule *m = &gen->module;
  10975. LLVMModuleRef mod = gen->module.mod;
  10976. CheckerInfo *info = gen->info;
  10977. auto *min_dep_set = &info->minimum_dependency_set;
  10978. LLVMInitializeAllTargetInfos();
  10979. LLVMInitializeAllTargets();
  10980. LLVMInitializeAllTargetMCs();
  10981. LLVMInitializeAllAsmPrinters();
  10982. LLVMInitializeAllAsmParsers();
  10983. LLVMInitializeAllDisassemblers();
  10984. LLVMInitializeNativeTarget();
  10985. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  10986. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  10987. LLVMSetTarget(mod, target_triple);
  10988. LLVMTargetRef target = {};
  10989. char *llvm_error = nullptr;
  10990. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  10991. GB_ASSERT(target != nullptr);
  10992. TIME_SECTION("LLVM Create Target Machine");
  10993. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  10994. if (build_context.metrics.arch == TargetArch_wasm32) {
  10995. code_mode = LLVMCodeModelJITDefault;
  10996. }
  10997. char const *host_cpu_name = LLVMGetHostCPUName();
  10998. char const *llvm_cpu = "generic";
  10999. char const *llvm_features = "";
  11000. if (build_context.microarch.len != 0) {
  11001. if (build_context.microarch == "native") {
  11002. llvm_cpu = host_cpu_name;
  11003. } else {
  11004. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  11005. }
  11006. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  11007. llvm_features = LLVMGetHostCPUFeatures();
  11008. }
  11009. }
  11010. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  11011. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  11012. switch (build_context.optimization_level) {
  11013. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  11014. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  11015. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  11016. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  11017. }
  11018. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, llvm_cpu, llvm_features, code_gen_level, LLVMRelocDefault, code_mode);
  11019. defer (LLVMDisposeTargetMachine(target_machine));
  11020. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  11021. if (m->debug_builder) { // Debug Info
  11022. for_array(i, info->files.entries) {
  11023. AstFile *f = info->files.entries[i].value;
  11024. String fullpath = f->fullpath;
  11025. String filename = remove_directory_from_path(fullpath);
  11026. String directory = directory_from_path(fullpath);
  11027. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  11028. cast(char const *)filename.text, filename.len,
  11029. cast(char const *)directory.text, directory.len);
  11030. lb_set_llvm_metadata(m, f, res);
  11031. }
  11032. gbString producer = gb_string_make(heap_allocator(), "odin");
  11033. producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  11034. #ifdef NIGHTLY
  11035. producer = gb_string_appendc(producer, "-nightly");
  11036. #endif
  11037. #ifdef GIT_SHA
  11038. producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  11039. #endif
  11040. gbString split_name = gb_string_make(heap_allocator(), "");
  11041. LLVMBool is_optimized = build_context.optimization_level > 0;
  11042. AstFile *init_file = m->info->init_package->files[0];
  11043. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  11044. init_file = m->info->entry_point->identifier->file;
  11045. }
  11046. LLVMBool split_debug_inlining = false;
  11047. LLVMBool debug_info_for_profiling = false;
  11048. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  11049. lb_get_llvm_metadata(m, init_file),
  11050. producer, gb_string_length(producer),
  11051. is_optimized, "", 0,
  11052. 1, split_name, gb_string_length(split_name),
  11053. LLVMDWARFEmissionFull,
  11054. 0, split_debug_inlining,
  11055. debug_info_for_profiling,
  11056. "", 0, // sys_root
  11057. "", 0 // SDK
  11058. );
  11059. GB_ASSERT(m->debug_compile_unit != nullptr);
  11060. }
  11061. TIME_SECTION("LLVM Global Variables");
  11062. {
  11063. { // Add type info data
  11064. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  11065. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  11066. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  11067. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  11068. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11069. LLVMSetLinkage(g, LLVMInternalLinkage);
  11070. lbValue value = {};
  11071. value.value = g;
  11072. value.type = alloc_type_pointer(t);
  11073. lb_global_type_info_data = lb_addr(value);
  11074. }
  11075. { // Type info member buffer
  11076. // NOTE(bill): Removes need for heap allocation by making it global memory
  11077. isize count = 0;
  11078. for_array(entry_index, m->info->type_info_types) {
  11079. Type *t = m->info->type_info_types[entry_index];
  11080. isize index = lb_type_info_index(m->info, t, false);
  11081. if (index < 0) {
  11082. continue;
  11083. }
  11084. switch (t->kind) {
  11085. case Type_Union:
  11086. count += t->Union.variants.count;
  11087. break;
  11088. case Type_Struct:
  11089. count += t->Struct.fields.count;
  11090. break;
  11091. case Type_Tuple:
  11092. count += t->Tuple.variables.count;
  11093. break;
  11094. }
  11095. }
  11096. if (count > 0) {
  11097. {
  11098. char const *name = LB_TYPE_INFO_TYPES_NAME;
  11099. Type *t = alloc_type_array(t_type_info_ptr, count);
  11100. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11101. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11102. LLVMSetLinkage(g, LLVMInternalLinkage);
  11103. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  11104. }
  11105. {
  11106. char const *name = LB_TYPE_INFO_NAMES_NAME;
  11107. Type *t = alloc_type_array(t_string, count);
  11108. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11109. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11110. LLVMSetLinkage(g, LLVMInternalLinkage);
  11111. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  11112. }
  11113. {
  11114. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  11115. Type *t = alloc_type_array(t_uintptr, count);
  11116. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11117. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11118. LLVMSetLinkage(g, LLVMInternalLinkage);
  11119. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  11120. }
  11121. {
  11122. char const *name = LB_TYPE_INFO_USINGS_NAME;
  11123. Type *t = alloc_type_array(t_bool, count);
  11124. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11125. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11126. LLVMSetLinkage(g, LLVMInternalLinkage);
  11127. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  11128. }
  11129. {
  11130. char const *name = LB_TYPE_INFO_TAGS_NAME;
  11131. Type *t = alloc_type_array(t_string, count);
  11132. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11133. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11134. LLVMSetLinkage(g, LLVMInternalLinkage);
  11135. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  11136. }
  11137. }
  11138. }
  11139. }
  11140. isize global_variable_max_count = 0;
  11141. Entity *entry_point = info->entry_point;
  11142. bool has_dll_main = false;
  11143. bool has_win_main = false;
  11144. for_array(i, info->entities) {
  11145. Entity *e = info->entities[i];
  11146. String name = e->token.string;
  11147. bool is_global = e->pkg != nullptr;
  11148. if (e->kind == Entity_Variable) {
  11149. global_variable_max_count++;
  11150. } else if (e->kind == Entity_Procedure && !is_global) {
  11151. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  11152. GB_ASSERT(e == entry_point);
  11153. // entry_point = e;
  11154. }
  11155. if (e->Procedure.is_export ||
  11156. (e->Procedure.link_name.len > 0) ||
  11157. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  11158. if (!has_dll_main && name == "DllMain") {
  11159. has_dll_main = true;
  11160. } else if (!has_win_main && name == "WinMain") {
  11161. has_win_main = true;
  11162. }
  11163. }
  11164. }
  11165. }
  11166. struct GlobalVariable {
  11167. lbValue var;
  11168. lbValue init;
  11169. DeclInfo *decl;
  11170. bool is_initialized;
  11171. };
  11172. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  11173. for_array(i, info->variable_init_order) {
  11174. DeclInfo *d = info->variable_init_order[i];
  11175. Entity *e = d->entity;
  11176. if ((e->scope->flags & ScopeFlag_File) == 0) {
  11177. continue;
  11178. }
  11179. if (!ptr_set_exists(min_dep_set, e)) {
  11180. continue;
  11181. }
  11182. DeclInfo *decl = decl_info_of_entity(e);
  11183. if (decl == nullptr) {
  11184. continue;
  11185. }
  11186. GB_ASSERT(e->kind == Entity_Variable);
  11187. bool is_foreign = e->Variable.is_foreign;
  11188. bool is_export = e->Variable.is_export;
  11189. String name = lb_get_entity_name(m, e);
  11190. lbValue g = {};
  11191. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  11192. g.type = alloc_type_pointer(e->type);
  11193. if (e->Variable.thread_local_model != "") {
  11194. LLVMSetThreadLocal(g.value, true);
  11195. String m = e->Variable.thread_local_model;
  11196. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  11197. if (m == "default") {
  11198. mode = LLVMGeneralDynamicTLSModel;
  11199. } else if (m == "localdynamic") {
  11200. mode = LLVMLocalDynamicTLSModel;
  11201. } else if (m == "initialexec") {
  11202. mode = LLVMInitialExecTLSModel;
  11203. } else if (m == "localexec") {
  11204. mode = LLVMLocalExecTLSModel;
  11205. } else {
  11206. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  11207. }
  11208. LLVMSetThreadLocalMode(g.value, mode);
  11209. }
  11210. if (is_foreign) {
  11211. LLVMSetExternallyInitialized(g.value, true);
  11212. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  11213. } else {
  11214. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  11215. }
  11216. if (is_export) {
  11217. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  11218. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  11219. }
  11220. if (e->flags & EntityFlag_Static) {
  11221. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  11222. }
  11223. GlobalVariable var = {};
  11224. var.var = g;
  11225. var.decl = decl;
  11226. if (decl->init_expr != nullptr) {
  11227. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  11228. if (!is_type_any(e->type)) {
  11229. if (tav.mode != Addressing_Invalid) {
  11230. if (tav.value.kind != ExactValue_Invalid) {
  11231. ExactValue v = tav.value;
  11232. lbValue init = lb_const_value(m, tav.type, v);
  11233. LLVMSetInitializer(g.value, init.value);
  11234. var.is_initialized = true;
  11235. }
  11236. }
  11237. }
  11238. if (!var.is_initialized &&
  11239. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  11240. var.is_initialized = true;
  11241. }
  11242. }
  11243. array_add(&global_variables, var);
  11244. lb_add_entity(m, e, g);
  11245. lb_add_member(m, name, g);
  11246. if (m->debug_builder) {
  11247. String global_name = e->token.string;
  11248. if (global_name.len != 0 && global_name != "_") {
  11249. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  11250. LLVMMetadataRef llvm_scope = llvm_file;
  11251. LLVMBool local_to_unit = e->flags & EntityFlag_Static;
  11252. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  11253. LLVMMetadataRef llvm_decl = nullptr;
  11254. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  11255. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  11256. m->debug_builder, llvm_scope,
  11257. cast(char const *)global_name.text, global_name.len,
  11258. "", 0, // linkage
  11259. llvm_file, e->token.pos.line,
  11260. lb_debug_type(m, e->type),
  11261. local_to_unit,
  11262. llvm_expr,
  11263. llvm_decl,
  11264. align_in_bits
  11265. );
  11266. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  11267. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  11268. }
  11269. }
  11270. }
  11271. TIME_SECTION("LLVM Global Procedures and Types");
  11272. for_array(i, info->entities) {
  11273. Entity *e = info->entities[i];
  11274. String name = e->token.string;
  11275. DeclInfo *decl = e->decl_info;
  11276. Scope * scope = e->scope;
  11277. if ((scope->flags & ScopeFlag_File) == 0) {
  11278. continue;
  11279. }
  11280. Scope *package_scope = scope->parent;
  11281. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  11282. switch (e->kind) {
  11283. case Entity_Variable:
  11284. // NOTE(bill): Handled above as it requires a specific load order
  11285. continue;
  11286. case Entity_ProcGroup:
  11287. continue;
  11288. case Entity_TypeName:
  11289. case Entity_Procedure:
  11290. break;
  11291. }
  11292. bool polymorphic_struct = false;
  11293. if (e->type != nullptr && e->kind == Entity_TypeName) {
  11294. Type *bt = base_type(e->type);
  11295. if (bt->kind == Type_Struct) {
  11296. polymorphic_struct = is_type_polymorphic(bt);
  11297. }
  11298. }
  11299. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  11300. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  11301. continue;
  11302. }
  11303. String mangled_name = lb_get_entity_name(m, e);
  11304. switch (e->kind) {
  11305. case Entity_TypeName:
  11306. lb_type(m, e->type);
  11307. break;
  11308. case Entity_Procedure:
  11309. {
  11310. lbProcedure *p = lb_create_procedure(m, e);
  11311. array_add(&m->procedures_to_generate, p);
  11312. }
  11313. break;
  11314. }
  11315. }
  11316. TIME_SECTION("LLVM Registry Initializtion");
  11317. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  11318. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  11319. defer (LLVMDisposePassManager(default_function_pass_manager));
  11320. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  11321. lb_populate_function_pass_manager(default_function_pass_manager, false);
  11322. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11323. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  11324. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  11325. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11326. lb_populate_function_pass_manager(default_function_pass_manager_without_memcpy, true);
  11327. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11328. TIME_SECTION("LLVM Runtime Type Information Creation");
  11329. lbProcedure *startup_type_info = nullptr;
  11330. lbProcedure *startup_runtime = nullptr;
  11331. { // Startup Type Info
  11332. Type *params = alloc_type_tuple();
  11333. Type *results = alloc_type_tuple();
  11334. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11335. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  11336. p->is_startup = true;
  11337. startup_type_info = p;
  11338. lb_begin_procedure_body(p);
  11339. lb_setup_type_info_data(p);
  11340. lb_end_procedure_body(p);
  11341. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11342. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11343. LLVMDumpValue(p->value);
  11344. gb_printf_err("\n\n\n\n");
  11345. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11346. }
  11347. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11348. }
  11349. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  11350. { // Startup Runtime
  11351. Type *params = alloc_type_tuple();
  11352. Type *results = alloc_type_tuple();
  11353. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11354. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  11355. p->is_startup = true;
  11356. startup_runtime = p;
  11357. lb_begin_procedure_body(p);
  11358. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  11359. for_array(i, global_variables) {
  11360. auto *var = &global_variables[i];
  11361. if (var->is_initialized) {
  11362. continue;
  11363. }
  11364. Entity *e = var->decl->entity;
  11365. GB_ASSERT(e->kind == Entity_Variable);
  11366. if (var->decl->init_expr != nullptr) {
  11367. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  11368. lbValue init = lb_build_expr(p, var->decl->init_expr);
  11369. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  11370. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  11371. if (lb_is_const_or_global(init)) {
  11372. if (!var->is_initialized) {
  11373. LLVMSetInitializer(var->var.value, init.value);
  11374. var->is_initialized = true;
  11375. continue;
  11376. }
  11377. } else {
  11378. var->init = init;
  11379. }
  11380. }
  11381. if (var->init.value != nullptr) {
  11382. GB_ASSERT(!var->is_initialized);
  11383. Type *t = type_deref(var->var.type);
  11384. if (is_type_any(t)) {
  11385. // NOTE(bill): Edge case for 'any' type
  11386. Type *var_type = default_type(var->init.type);
  11387. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  11388. lb_addr_store(p, g, var->init);
  11389. lbValue gp = lb_addr_get_ptr(p, g);
  11390. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  11391. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  11392. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  11393. lb_emit_store(p, ti, lb_type_info(m, var_type));
  11394. } else {
  11395. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  11396. LLVMTypeRef vt = LLVMGetElementType(pvt);
  11397. lbValue src0 = lb_emit_conv(p, var->init, t);
  11398. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  11399. LLVMValueRef dst = var->var.value;
  11400. LLVMBuildStore(p->builder, src, dst);
  11401. }
  11402. var->is_initialized = true;
  11403. }
  11404. }
  11405. lb_end_procedure_body(p);
  11406. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11407. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11408. LLVMDumpValue(p->value);
  11409. gb_printf_err("\n\n\n\n");
  11410. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11411. }
  11412. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11413. /*{
  11414. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  11415. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  11416. instr != last_instr;
  11417. instr = LLVMGetNextInstruction(instr)) {
  11418. if (LLVMIsAAllocaInst(instr)) {
  11419. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  11420. LLVMValueRef sz_val = LLVMSizeOf(type);
  11421. GB_ASSERT(LLVMIsConstant(sz_val));
  11422. gb_printf_err(">> 0x%p\n", sz_val);
  11423. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  11424. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  11425. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  11426. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  11427. gb_printf_err(">> %ll\n", sz);
  11428. }
  11429. }
  11430. }*/
  11431. }
  11432. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  11433. TIME_SECTION("LLVM DLL main");
  11434. Type *params = alloc_type_tuple();
  11435. Type *results = alloc_type_tuple();
  11436. String name = str_lit("main");
  11437. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  11438. name = str_lit("mainCRTStartup");
  11439. } else {
  11440. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  11441. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  11442. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  11443. }
  11444. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  11445. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  11446. Type *proc_type = alloc_type_proc(nullptr,
  11447. params, params->Tuple.variables.count,
  11448. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  11449. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  11450. p->is_startup = true;
  11451. lb_begin_procedure_body(p);
  11452. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  11453. if (build_context.command_kind == Command_test) {
  11454. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  11455. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  11456. Type *slice_type = alloc_type_slice(t_Internal_Test);
  11457. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  11458. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  11459. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  11460. LLVMValueRef indices[2] = {};
  11461. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  11462. for_array(i, m->info->testing_procedures) {
  11463. Entity *testing_proc = m->info->testing_procedures[i];
  11464. String name = testing_proc->token.string;
  11465. lbValue *found = map_get(&m->values, hash_entity(testing_proc));
  11466. GB_ASSERT(found != nullptr);
  11467. String pkg_name = {};
  11468. if (testing_proc->pkg != nullptr) {
  11469. pkg_name = testing_proc->pkg->name;
  11470. }
  11471. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  11472. lbValue v_name = lb_find_or_add_entity_string(m, name);
  11473. lbValue v_proc = *found;
  11474. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  11475. LLVMValueRef vals[3] = {};
  11476. vals[0] = v_pkg.value;
  11477. vals[1] = v_name.value;
  11478. vals[2] = v_proc.value;
  11479. GB_ASSERT(LLVMIsConstant(vals[0]));
  11480. GB_ASSERT(LLVMIsConstant(vals[1]));
  11481. GB_ASSERT(LLVMIsConstant(vals[2]));
  11482. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  11483. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  11484. LLVMBuildStore(p->builder, src, dst);
  11485. }
  11486. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  11487. lb_fill_slice(p, all_tests_slice,
  11488. lb_array_elem(p, all_tests_array),
  11489. lb_const_int(m, t_int, m->info->testing_procedures.count));
  11490. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  11491. auto args = array_make<lbValue>(heap_allocator(), 1);
  11492. args[0] = lb_addr_load(p, all_tests_slice);
  11493. lb_emit_call(p, runner, args);
  11494. } else {
  11495. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  11496. GB_ASSERT(found != nullptr);
  11497. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  11498. }
  11499. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  11500. lb_end_procedure_body(p);
  11501. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11502. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11503. LLVMDumpValue(p->value);
  11504. gb_printf_err("\n\n\n\n");
  11505. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11506. }
  11507. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11508. }
  11509. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  11510. TIME_SECTION("LLVM Procedure Generation");
  11511. for_array(i, m->procedures_to_generate) {
  11512. lbProcedure *p = m->procedures_to_generate[i];
  11513. if (p->is_done) {
  11514. continue;
  11515. }
  11516. if (p->body != nullptr) { // Build Procedure
  11517. m->curr_procedure = p;
  11518. lb_begin_procedure_body(p);
  11519. lb_build_stmt(p, p->body);
  11520. lb_end_procedure_body(p);
  11521. p->is_done = true;
  11522. m->curr_procedure = nullptr;
  11523. }
  11524. lb_end_procedure(p);
  11525. // Add Flags
  11526. if (p->body != nullptr) {
  11527. if (p->name == "memcpy" || p->name == "memmove" ||
  11528. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  11529. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  11530. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  11531. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  11532. }
  11533. }
  11534. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11535. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  11536. LLVMDumpValue(p->value);
  11537. gb_printf_err("\n\n\n\n");
  11538. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11539. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11540. }
  11541. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  11542. gb_exit(1);
  11543. }
  11544. }
  11545. if (m->debug_builder != nullptr) {
  11546. TIME_SECTION("LLVM Debug Info Complete Types");
  11547. lb_debug_complete_types(m);
  11548. TIME_SECTION("LLVM Print Module to File");
  11549. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11550. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11551. gb_exit(1);
  11552. return;
  11553. }
  11554. TIME_SECTION("LLVM Debug Info Builder Finalize");
  11555. LLVMDIBuilderFinalize(m->debug_builder);
  11556. }
  11557. TIME_SECTION("LLVM Function Pass");
  11558. {
  11559. for_array(i, m->procedures_to_generate) {
  11560. lbProcedure *p = m->procedures_to_generate[i];
  11561. if (p->body != nullptr) { // Build Procedure
  11562. for (i32 i = 0; i <= build_context.optimization_level; i++) {
  11563. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  11564. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  11565. } else {
  11566. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11567. }
  11568. }
  11569. }
  11570. }
  11571. for_array(i, m->equal_procs.entries) {
  11572. lbProcedure *p = m->equal_procs.entries[i].value;
  11573. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11574. }
  11575. for_array(i, m->hasher_procs.entries) {
  11576. lbProcedure *p = m->hasher_procs.entries[i].value;
  11577. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11578. }
  11579. }
  11580. TIME_SECTION("LLVM Module Pass");
  11581. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  11582. defer (LLVMDisposePassManager(module_pass_manager));
  11583. lb_populate_module_pass_manager(target_machine, module_pass_manager);
  11584. LLVMRunPassManager(module_pass_manager, mod);
  11585. llvm_error = nullptr;
  11586. defer (LLVMDisposeMessage(llvm_error));
  11587. String filepath_obj = {};
  11588. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  11589. if (build_context.build_mode == BuildMode_Assembly) {
  11590. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  11591. code_gen_file_type = LLVMAssemblyFile;
  11592. } else {
  11593. switch (build_context.metrics.os) {
  11594. case TargetOs_windows:
  11595. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  11596. break;
  11597. case TargetOs_darwin:
  11598. case TargetOs_linux:
  11599. case TargetOs_essence:
  11600. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  11601. break;
  11602. case TargetOs_js:
  11603. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  11604. break;
  11605. }
  11606. }
  11607. if (LLVMVerifyModule(mod, LLVMReturnStatusAction, &llvm_error)) {
  11608. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  11609. if (build_context.keep_temp_files) {
  11610. TIME_SECTION("LLVM Print Module to File");
  11611. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11612. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11613. gb_exit(1);
  11614. return;
  11615. }
  11616. }
  11617. gb_exit(1);
  11618. return;
  11619. }
  11620. llvm_error = nullptr;
  11621. if (build_context.keep_temp_files) {
  11622. TIME_SECTION("LLVM Print Module to File");
  11623. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11624. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11625. gb_exit(1);
  11626. return;
  11627. }
  11628. }
  11629. TIME_SECTION("LLVM Object Generation");
  11630. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  11631. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11632. gb_exit(1);
  11633. return;
  11634. }
  11635. array_add(&gen->output_object_paths, filepath_obj);
  11636. for_array(i, m->info->required_foreign_imports_through_force) {
  11637. Entity *e = m->info->required_foreign_imports_through_force[i];
  11638. lb_add_foreign_library_path(m, e);
  11639. }
  11640. #undef TIME_SECTION
  11641. }