llvm_backend.cpp 429 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658
  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_Context:
  137. GB_PANIC("lbAddr_Context should be handled elsewhere");
  138. }
  139. return addr.addr;
  140. }
  141. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  142. lbAddr addr = lb_build_addr(p, expr);
  143. return lb_addr_get_ptr(p, addr);
  144. }
  145. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  146. if (build_context.no_bounds_check) {
  147. return;
  148. }
  149. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  150. return;
  151. }
  152. index = lb_emit_conv(p, index, t_int);
  153. len = lb_emit_conv(p, len, t_int);
  154. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  155. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  156. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  157. auto args = array_make<lbValue>(permanent_allocator(), 5);
  158. args[0] = file;
  159. args[1] = line;
  160. args[2] = column;
  161. args[3] = index;
  162. args[4] = len;
  163. lb_emit_runtime_call(p, "bounds_check_error", args);
  164. }
  165. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  166. if (build_context.no_bounds_check) {
  167. return;
  168. }
  169. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  170. return;
  171. }
  172. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  173. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  174. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  175. high = lb_emit_conv(p, high, t_int);
  176. if (!lower_value_used) {
  177. auto args = array_make<lbValue>(permanent_allocator(), 5);
  178. args[0] = file;
  179. args[1] = line;
  180. args[2] = column;
  181. args[3] = high;
  182. args[4] = len;
  183. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  184. } else {
  185. // No need to convert unless used
  186. low = lb_emit_conv(p, low, t_int);
  187. auto args = array_make<lbValue>(permanent_allocator(), 6);
  188. args[0] = file;
  189. args[1] = line;
  190. args[2] = column;
  191. args[3] = low;
  192. args[4] = high;
  193. args[5] = len;
  194. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  195. }
  196. }
  197. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  198. if (addr.addr.value == nullptr) {
  199. return;
  200. }
  201. GB_ASSERT(value.type != nullptr);
  202. if (is_type_untyped_undef(value.type)) {
  203. Type *t = lb_addr_type(addr);
  204. value.type = t;
  205. value.value = LLVMGetUndef(lb_type(p->module, t));
  206. } else if (is_type_untyped_nil(value.type)) {
  207. Type *t = lb_addr_type(addr);
  208. value.type = t;
  209. value.value = LLVMConstNull(lb_type(p->module, t));
  210. }
  211. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  212. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  213. }
  214. if (addr.kind == lbAddr_RelativePointer) {
  215. Type *rel_ptr = base_type(lb_addr_type(addr));
  216. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  217. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  218. GB_ASSERT(is_type_pointer(addr.addr.type));
  219. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  220. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  221. lbValue offset = {};
  222. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  223. offset.type = t_uintptr;
  224. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  225. offset = lb_emit_conv(p, offset, t_i64);
  226. }
  227. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  228. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  229. offset = lb_emit_select(p,
  230. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  231. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  232. offset
  233. );
  234. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  235. return;
  236. } else if (addr.kind == lbAddr_RelativeSlice) {
  237. Type *rel_ptr = base_type(lb_addr_type(addr));
  238. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  239. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  240. GB_ASSERT(is_type_pointer(addr.addr.type));
  241. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  242. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  243. lbValue offset = {};
  244. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  245. offset.type = t_uintptr;
  246. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  247. offset = lb_emit_conv(p, offset, t_i64);
  248. }
  249. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  250. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  251. offset = lb_emit_select(p,
  252. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  253. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  254. offset
  255. );
  256. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  257. lbValue len = lb_slice_len(p, value);
  258. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  259. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  260. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  261. return;
  262. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  263. lbValue ptr = addr.addr;
  264. lbValue index = addr.index_set.index;
  265. Ast *node = addr.index_set.node;
  266. ast_node(ce, CallExpr, node);
  267. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  268. proc_type = base_type(proc_type);
  269. GB_ASSERT(is_type_proc(proc_type));
  270. TypeProc *pt = &proc_type->Proc;
  271. isize arg_count = 3;
  272. isize param_count = 0;
  273. if (pt->params) {
  274. GB_ASSERT(pt->params->kind == Type_Tuple);
  275. param_count = pt->params->Tuple.variables.count;
  276. }
  277. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  278. args[0] = ptr;
  279. args[1] = index;
  280. args[2] = value;
  281. isize arg_index = arg_count;
  282. if (arg_count < param_count) {
  283. lbModule *m = p->module;
  284. String proc_name = {};
  285. if (p->entity != nullptr) {
  286. proc_name = p->entity->token.string;
  287. }
  288. TokenPos pos = ast_token(ce->proc).pos;
  289. TypeTuple *param_tuple = &pt->params->Tuple;
  290. isize end = cast(isize)param_count;
  291. while (arg_index < end) {
  292. Entity *e = param_tuple->variables[arg_index];
  293. GB_ASSERT(e->kind == Entity_Variable);
  294. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  295. }
  296. }
  297. Entity *e = entity_from_expr(ce->proc);
  298. GB_ASSERT(e != nullptr);
  299. GB_ASSERT(is_type_polymorphic(e->type));
  300. {
  301. lbValue *found = nullptr;
  302. if (p->module != e->code_gen_module) {
  303. gb_mutex_lock(&p->module->mutex);
  304. }
  305. GB_ASSERT(e->code_gen_module != nullptr);
  306. found = map_get(&e->code_gen_module->values, hash_entity(e));
  307. if (p->module != e->code_gen_module) {
  308. gb_mutex_unlock(&p->module->mutex);
  309. }
  310. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  311. lb_emit_call(p, *found, args);
  312. }
  313. return;
  314. } else if (addr.kind == lbAddr_Map) {
  315. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  316. return;
  317. } else if (addr.kind == lbAddr_Context) {
  318. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  319. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  320. lb_addr_store(p, next_addr, old);
  321. lb_push_context_onto_stack(p, next_addr);
  322. lbValue next = lb_addr_get_ptr(p, next_addr);
  323. if (addr.ctx.sel.index.count > 0) {
  324. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  325. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  326. lb_emit_store(p, lhs, rhs);
  327. } else {
  328. lbValue lhs = next;
  329. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  330. lb_emit_store(p, lhs, rhs);
  331. }
  332. return;
  333. } else if (addr.kind == lbAddr_SoaVariable) {
  334. Type *t = type_deref(addr.addr.type);
  335. t = base_type(t);
  336. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  337. Type *elem_type = t->Struct.soa_elem;
  338. value = lb_emit_conv(p, value, elem_type);
  339. elem_type = base_type(elem_type);
  340. lbValue index = addr.soa.index;
  341. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  342. Type *t = base_type(type_deref(addr.addr.type));
  343. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  344. lbValue len = lb_soa_struct_len(p, addr.addr);
  345. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  346. }
  347. isize field_count = 0;
  348. switch (elem_type->kind) {
  349. case Type_Struct:
  350. field_count = elem_type->Struct.fields.count;
  351. break;
  352. case Type_Array:
  353. field_count = elem_type->Array.count;
  354. break;
  355. }
  356. for (isize i = 0; i < field_count; i++) {
  357. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  358. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  359. if (t->Struct.soa_kind == StructSoa_Fixed) {
  360. dst = lb_emit_array_ep(p, dst, index);
  361. lb_emit_store(p, dst, src);
  362. } else {
  363. lbValue field = lb_emit_load(p, dst);
  364. dst = lb_emit_ptr_offset(p, field, index);
  365. lb_emit_store(p, dst, src);
  366. }
  367. }
  368. return;
  369. }
  370. GB_ASSERT(value.value != nullptr);
  371. value = lb_emit_conv(p, value, lb_addr_type(addr));
  372. // if (lb_is_const_or_global(value)) {
  373. // // NOTE(bill): Just bypass the actual storage and set the initializer
  374. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  375. // LLVMValueRef dst = addr.addr.value;
  376. // LLVMValueRef src = value.value;
  377. // LLVMSetInitializer(dst, src);
  378. // return;
  379. // }
  380. // }
  381. lb_emit_store(p, addr.addr, value);
  382. }
  383. void lb_const_store(lbValue ptr, lbValue value) {
  384. GB_ASSERT(lb_is_const(ptr));
  385. GB_ASSERT(lb_is_const(value));
  386. GB_ASSERT(is_type_pointer(ptr.type));
  387. LLVMSetInitializer(ptr.value, value.value);
  388. }
  389. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  390. GB_ASSERT(value.value != nullptr);
  391. Type *a = type_deref(ptr.type);
  392. if (is_type_boolean(a)) {
  393. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  394. value = lb_emit_conv(p, value, a);
  395. }
  396. Type *ca = core_type(a);
  397. if (ca->kind == Type_Basic) {
  398. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  399. }
  400. if (is_type_proc(a)) {
  401. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  402. // stored as regular pointer with no procedure information
  403. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  404. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  405. LLVMBuildStore(p->builder, v, ptr.value);
  406. } else {
  407. Type *ca = core_type(a);
  408. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  409. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  410. } else {
  411. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  412. }
  413. LLVMBuildStore(p->builder, value.value, ptr.value);
  414. }
  415. }
  416. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  417. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  418. }
  419. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  420. lbModule *m = p->module;
  421. GB_ASSERT(value.value != nullptr);
  422. GB_ASSERT(is_type_pointer(value.type));
  423. Type *t = type_deref(value.type);
  424. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  425. return lbValue{v, t};
  426. }
  427. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  428. GB_ASSERT(addr.addr.value != nullptr);
  429. if (addr.kind == lbAddr_RelativePointer) {
  430. Type *rel_ptr = base_type(lb_addr_type(addr));
  431. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  432. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  433. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  434. offset = lb_emit_load(p, offset);
  435. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  436. offset = lb_emit_conv(p, offset, t_i64);
  437. }
  438. offset = lb_emit_conv(p, offset, t_uintptr);
  439. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  440. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  441. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  442. // NOTE(bill): nil check
  443. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  444. lbValue final_ptr = {};
  445. final_ptr.type = absolute_ptr.type;
  446. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  447. return lb_emit_load(p, final_ptr);
  448. } else if (addr.kind == lbAddr_RelativeSlice) {
  449. Type *rel_ptr = base_type(lb_addr_type(addr));
  450. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  451. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  452. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  453. lbValue offset = lb_emit_load(p, offset_ptr);
  454. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  455. offset = lb_emit_conv(p, offset, t_i64);
  456. }
  457. offset = lb_emit_conv(p, offset, t_uintptr);
  458. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  459. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  460. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  461. Type *slice_elem = slice_type->Slice.elem;
  462. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  463. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  464. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  465. // NOTE(bill): nil check
  466. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  467. lbValue data = {};
  468. data.type = absolute_ptr.type;
  469. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  470. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  471. len = lb_emit_conv(p, len, t_int);
  472. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  473. lb_fill_slice(p, slice, data, len);
  474. return lb_addr_load(p, slice);
  475. } else if (addr.kind == lbAddr_Map) {
  476. Type *map_type = base_type(addr.map.type);
  477. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  478. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  479. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  480. auto args = array_make<lbValue>(permanent_allocator(), 2);
  481. args[0] = h;
  482. args[1] = key;
  483. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  484. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  485. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  486. lbBlock *then = lb_create_block(p, "map.get.then");
  487. lbBlock *done = lb_create_block(p, "map.get.done");
  488. lb_emit_if(p, ok, then, done);
  489. lb_start_block(p, then);
  490. {
  491. // TODO(bill): mem copy it instead?
  492. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  493. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  494. lb_emit_store(p, gep0, lb_emit_load(p, value));
  495. }
  496. lb_emit_jump(p, done);
  497. lb_start_block(p, done);
  498. if (is_type_tuple(addr.map.result)) {
  499. return lb_addr_load(p, v);
  500. } else {
  501. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  502. return lb_emit_load(p, single);
  503. }
  504. } else if (addr.kind == lbAddr_Context) {
  505. lbValue a = addr.addr;
  506. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  507. if (addr.ctx.sel.index.count > 0) {
  508. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  509. return lb_emit_load(p, b);
  510. } else {
  511. return lb_emit_load(p, a);
  512. }
  513. } else if (addr.kind == lbAddr_SoaVariable) {
  514. Type *t = type_deref(addr.addr.type);
  515. t = base_type(t);
  516. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  517. Type *elem = t->Struct.soa_elem;
  518. lbValue len = {};
  519. if (t->Struct.soa_kind == StructSoa_Fixed) {
  520. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  521. } else {
  522. lbValue v = lb_emit_load(p, addr.addr);
  523. len = lb_soa_struct_len(p, v);
  524. }
  525. lbAddr res = lb_add_local_generated(p, elem, true);
  526. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  527. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  528. }
  529. if (t->Struct.soa_kind == StructSoa_Fixed) {
  530. for_array(i, t->Struct.fields) {
  531. Entity *field = t->Struct.fields[i];
  532. Type *base_type = field->type;
  533. GB_ASSERT(base_type->kind == Type_Array);
  534. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  535. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  536. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  537. lbValue src = lb_emit_load(p, src_ptr);
  538. lb_emit_store(p, dst, src);
  539. }
  540. } else {
  541. isize field_count = t->Struct.fields.count;
  542. if (t->Struct.soa_kind == StructSoa_Slice) {
  543. field_count -= 1;
  544. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  545. field_count -= 3;
  546. }
  547. for (isize i = 0; i < field_count; i++) {
  548. Entity *field = t->Struct.fields[i];
  549. Type *base_type = field->type;
  550. GB_ASSERT(base_type->kind == Type_Pointer);
  551. Type *elem = base_type->Pointer.elem;
  552. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  553. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  554. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  555. lbValue src = lb_emit_load(p, src_ptr);
  556. src = lb_emit_load(p, src);
  557. lb_emit_store(p, dst, src);
  558. }
  559. }
  560. return lb_addr_load(p, res);
  561. }
  562. if (is_type_proc(addr.addr.type)) {
  563. return addr.addr;
  564. }
  565. return lb_emit_load(p, addr.addr);
  566. }
  567. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  568. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  569. }
  570. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  571. Type *t = u.type;
  572. GB_ASSERT_MSG(is_type_pointer(t) &&
  573. is_type_union(type_deref(t)), "%s", type_to_string(t));
  574. Type *ut = type_deref(t);
  575. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  576. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  577. GB_ASSERT(type_size_of(ut) > 0);
  578. Type *tag_type = union_tag_type(ut);
  579. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  580. unsigned element_count = LLVMCountStructElementTypes(uvt);
  581. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  582. lbValue tag_ptr = {};
  583. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  584. tag_ptr.type = alloc_type_pointer(tag_type);
  585. return tag_ptr;
  586. }
  587. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  588. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  589. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  590. return lb_emit_load(p, tag_ptr);
  591. }
  592. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  593. Type *t = type_deref(parent.type);
  594. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  595. // No tag needed!
  596. } else {
  597. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  598. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  599. }
  600. }
  601. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  602. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  603. lb_emit_store(p, underlying, variant);
  604. lb_emit_store_union_variant_tag(p, parent, variant_type);
  605. }
  606. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  607. unsigned field_count = LLVMCountStructElementTypes(src);
  608. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  609. LLVMGetStructElementTypes(src, fields);
  610. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  611. }
  612. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  613. switch (alignment) {
  614. case 1:
  615. return LLVMArrayType(lb_type(m, t_u8), 0);
  616. case 2:
  617. return LLVMArrayType(lb_type(m, t_u16), 0);
  618. case 4:
  619. return LLVMArrayType(lb_type(m, t_u32), 0);
  620. case 8:
  621. return LLVMArrayType(lb_type(m, t_u64), 0);
  622. case 16:
  623. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  624. default:
  625. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  626. break;
  627. }
  628. return nullptr;
  629. }
  630. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  631. if (!elem_type_can_be_constant(elem_type)) {
  632. return false;
  633. }
  634. if (elem->kind == Ast_FieldValue) {
  635. elem = elem->FieldValue.value;
  636. }
  637. TypeAndValue tav = type_and_value_of_expr(elem);
  638. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  639. return tav.value.kind != ExactValue_Invalid;
  640. }
  641. String lb_mangle_name(lbModule *m, Entity *e) {
  642. String name = e->token.string;
  643. AstPackage *pkg = e->pkg;
  644. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  645. String pkgn = pkg->name;
  646. GB_ASSERT(!rune_is_digit(pkgn[0]));
  647. if (pkgn == "llvm") {
  648. pkgn = str_lit("llvm$");
  649. }
  650. isize max_len = pkgn.len + 1 + name.len + 1;
  651. bool require_suffix_id = is_type_polymorphic(e->type, true);
  652. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  653. require_suffix_id = true;
  654. } else if (is_blank_ident(e->token)) {
  655. require_suffix_id = true;
  656. }if (e->flags & EntityFlag_NotExported) {
  657. require_suffix_id = true;
  658. }
  659. if (require_suffix_id) {
  660. max_len += 21;
  661. }
  662. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  663. isize new_name_len = gb_snprintf(
  664. new_name, max_len,
  665. "%.*s.%.*s", LIT(pkgn), LIT(name)
  666. );
  667. if (require_suffix_id) {
  668. char *str = new_name + new_name_len-1;
  669. isize len = max_len-new_name_len;
  670. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  671. new_name_len += extra-1;
  672. }
  673. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  674. return mangled_name;
  675. }
  676. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  677. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  678. // and as a result, the declaration does not have time to determine what it should be
  679. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  680. if (e->TypeName.ir_mangled_name.len != 0) {
  681. return e->TypeName.ir_mangled_name;
  682. }
  683. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  684. if (p == nullptr) {
  685. Entity *proc = nullptr;
  686. if (e->parent_proc_decl != nullptr) {
  687. proc = e->parent_proc_decl->entity;
  688. } else {
  689. Scope *scope = e->scope;
  690. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  691. scope = scope->parent;
  692. }
  693. GB_ASSERT(scope != nullptr);
  694. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  695. proc = scope->procedure_entity;
  696. }
  697. GB_ASSERT(proc->kind == Entity_Procedure);
  698. if (proc->code_gen_procedure != nullptr) {
  699. p = proc->code_gen_procedure;
  700. }
  701. }
  702. // NOTE(bill): Generate a new name
  703. // parent_proc.name-guid
  704. String ts_name = e->token.string;
  705. if (p != nullptr) {
  706. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  707. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  708. u32 guid = ++p->module->nested_type_name_guid;
  709. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  710. String name = make_string(cast(u8 *)name_text, name_len-1);
  711. e->TypeName.ir_mangled_name = name;
  712. return name;
  713. } else {
  714. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  715. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  716. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  717. static u32 guid = 0;
  718. guid += 1;
  719. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  720. String name = make_string(cast(u8 *)name_text, name_len-1);
  721. e->TypeName.ir_mangled_name = name;
  722. return name;
  723. }
  724. }
  725. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  726. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  727. return e->TypeName.ir_mangled_name;
  728. }
  729. GB_ASSERT(e != nullptr);
  730. if (e->pkg == nullptr) {
  731. return e->token.string;
  732. }
  733. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  734. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  735. }
  736. String name = {};
  737. bool no_name_mangle = false;
  738. if (e->kind == Entity_Variable) {
  739. bool is_foreign = e->Variable.is_foreign;
  740. bool is_export = e->Variable.is_export;
  741. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  742. if (e->Variable.link_name.len > 0) {
  743. return e->Variable.link_name;
  744. }
  745. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  746. return e->Procedure.link_name;
  747. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  748. no_name_mangle = true;
  749. }
  750. if (!no_name_mangle) {
  751. name = lb_mangle_name(m, e);
  752. }
  753. if (name.len == 0) {
  754. name = e->token.string;
  755. }
  756. if (e->kind == Entity_TypeName) {
  757. e->TypeName.ir_mangled_name = name;
  758. } else if (e->kind == Entity_Procedure) {
  759. e->Procedure.link_name = name;
  760. }
  761. return name;
  762. }
  763. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  764. Type *original_type = type;
  765. LLVMContextRef ctx = m->ctx;
  766. i64 size = type_size_of(type); // Check size
  767. GB_ASSERT(type != t_invalid);
  768. switch (type->kind) {
  769. case Type_Basic:
  770. switch (type->Basic.kind) {
  771. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  772. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  773. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  774. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  775. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  776. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  777. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  778. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  779. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  780. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  781. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  782. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  783. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  784. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  785. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  786. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  787. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  788. // Basic_f16,
  789. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  790. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  791. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  792. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  793. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  794. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  795. // Basic_complex32,
  796. case Basic_complex64:
  797. {
  798. char const *name = "..complex64";
  799. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  800. if (type != nullptr) {
  801. return type;
  802. }
  803. type = LLVMStructCreateNamed(ctx, name);
  804. LLVMTypeRef fields[2] = {
  805. lb_type(m, t_f32),
  806. lb_type(m, t_f32),
  807. };
  808. LLVMStructSetBody(type, fields, 2, false);
  809. return type;
  810. }
  811. case Basic_complex128:
  812. {
  813. char const *name = "..complex128";
  814. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  815. if (type != nullptr) {
  816. return type;
  817. }
  818. type = LLVMStructCreateNamed(ctx, name);
  819. LLVMTypeRef fields[2] = {
  820. lb_type(m, t_f64),
  821. lb_type(m, t_f64),
  822. };
  823. LLVMStructSetBody(type, fields, 2, false);
  824. return type;
  825. }
  826. case Basic_quaternion128:
  827. {
  828. char const *name = "..quaternion128";
  829. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  830. if (type != nullptr) {
  831. return type;
  832. }
  833. type = LLVMStructCreateNamed(ctx, name);
  834. LLVMTypeRef fields[4] = {
  835. lb_type(m, t_f32),
  836. lb_type(m, t_f32),
  837. lb_type(m, t_f32),
  838. lb_type(m, t_f32),
  839. };
  840. LLVMStructSetBody(type, fields, 4, false);
  841. return type;
  842. }
  843. case Basic_quaternion256:
  844. {
  845. char const *name = "..quaternion256";
  846. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  847. if (type != nullptr) {
  848. return type;
  849. }
  850. type = LLVMStructCreateNamed(ctx, name);
  851. LLVMTypeRef fields[4] = {
  852. lb_type(m, t_f64),
  853. lb_type(m, t_f64),
  854. lb_type(m, t_f64),
  855. lb_type(m, t_f64),
  856. };
  857. LLVMStructSetBody(type, fields, 4, false);
  858. return type;
  859. }
  860. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  861. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  862. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  863. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  864. case Basic_string:
  865. {
  866. char const *name = "..string";
  867. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  868. if (type != nullptr) {
  869. return type;
  870. }
  871. type = LLVMStructCreateNamed(ctx, name);
  872. LLVMTypeRef fields[2] = {
  873. LLVMPointerType(lb_type(m, t_u8), 0),
  874. lb_type(m, t_int),
  875. };
  876. LLVMStructSetBody(type, fields, 2, false);
  877. return type;
  878. }
  879. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  880. case Basic_any:
  881. {
  882. char const *name = "..any";
  883. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  884. if (type != nullptr) {
  885. return type;
  886. }
  887. type = LLVMStructCreateNamed(ctx, name);
  888. LLVMTypeRef fields[2] = {
  889. lb_type(m, t_rawptr),
  890. lb_type(m, t_typeid),
  891. };
  892. LLVMStructSetBody(type, fields, 2, false);
  893. return type;
  894. }
  895. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  896. // Endian Specific Types
  897. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  898. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  899. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  900. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  901. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  902. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  903. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  904. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  905. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  906. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  907. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  908. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  909. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  910. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  911. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  912. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  913. // Untyped types
  914. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  915. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  916. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  917. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  918. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  919. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  920. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  921. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  922. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  923. }
  924. break;
  925. case Type_Named:
  926. {
  927. Type *base = base_type(type->Named.base);
  928. switch (base->kind) {
  929. case Type_Basic:
  930. return lb_type_internal(m, base);
  931. case Type_Named:
  932. case Type_Generic:
  933. GB_PANIC("INVALID TYPE");
  934. break;
  935. case Type_Pointer:
  936. case Type_Array:
  937. case Type_EnumeratedArray:
  938. case Type_Slice:
  939. case Type_DynamicArray:
  940. case Type_Map:
  941. case Type_Enum:
  942. case Type_BitSet:
  943. case Type_SimdVector:
  944. return lb_type_internal(m, base);
  945. // TODO(bill): Deal with this correctly. Can this be named?
  946. case Type_Proc:
  947. return lb_type_internal(m, base);
  948. case Type_Tuple:
  949. return lb_type_internal(m, base);
  950. }
  951. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  952. if (found) {
  953. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  954. if (kind == LLVMStructTypeKind) {
  955. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  956. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  957. if (llvm_type != nullptr) {
  958. return llvm_type;
  959. }
  960. llvm_type = LLVMStructCreateNamed(ctx, name);
  961. map_set(&m->types, hash_type(type), llvm_type);
  962. lb_clone_struct_type(llvm_type, *found);
  963. return llvm_type;
  964. }
  965. }
  966. switch (base->kind) {
  967. case Type_Struct:
  968. case Type_Union:
  969. {
  970. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  971. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  972. if (llvm_type != nullptr) {
  973. return llvm_type;
  974. }
  975. llvm_type = LLVMStructCreateNamed(ctx, name);
  976. map_set(&m->types, hash_type(type), llvm_type);
  977. lb_clone_struct_type(llvm_type, lb_type(m, base));
  978. return llvm_type;
  979. }
  980. }
  981. return lb_type_internal(m, base);
  982. }
  983. case Type_Pointer:
  984. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  985. case Type_Array: {
  986. m->internal_type_level -= 1;
  987. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  988. m->internal_type_level += 1;
  989. return t;
  990. }
  991. case Type_EnumeratedArray: {
  992. m->internal_type_level -= 1;
  993. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  994. m->internal_type_level += 1;
  995. return t;
  996. }
  997. case Type_Slice:
  998. {
  999. LLVMTypeRef fields[2] = {
  1000. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1001. lb_type(m, t_int), // len
  1002. };
  1003. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1004. }
  1005. break;
  1006. case Type_DynamicArray:
  1007. {
  1008. LLVMTypeRef fields[4] = {
  1009. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1010. lb_type(m, t_int), // len
  1011. lb_type(m, t_int), // cap
  1012. lb_type(m, t_allocator), // allocator
  1013. };
  1014. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1015. }
  1016. break;
  1017. case Type_Map:
  1018. return lb_type(m, type->Map.internal_type);
  1019. case Type_Struct:
  1020. {
  1021. if (type->Struct.is_raw_union) {
  1022. unsigned field_count = 2;
  1023. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1024. i64 alignment = type_align_of(type);
  1025. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1026. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1027. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1028. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1029. }
  1030. isize offset = 0;
  1031. if (type->Struct.custom_align > 0) {
  1032. offset = 1;
  1033. }
  1034. m->internal_type_level += 1;
  1035. defer (m->internal_type_level -= 1);
  1036. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1037. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1038. for_array(i, type->Struct.fields) {
  1039. Entity *field = type->Struct.fields[i];
  1040. fields[i+offset] = lb_type(m, field->type);
  1041. }
  1042. if (type->Struct.custom_align > 0) {
  1043. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1044. }
  1045. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1046. }
  1047. break;
  1048. case Type_Union:
  1049. if (type->Union.variants.count == 0) {
  1050. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1051. } else {
  1052. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1053. // LLVM takes the first element's alignment as the entire alignment (like C)
  1054. i64 align = type_align_of(type);
  1055. i64 size = type_size_of(type);
  1056. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1057. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1058. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1059. }
  1060. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1061. LLVMTypeRef fields[3] = {};
  1062. unsigned field_count = 1;
  1063. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1064. if (is_type_union_maybe_pointer(type)) {
  1065. field_count += 1;
  1066. fields[1] = lb_type(m, type->Union.variants[0]);
  1067. } else {
  1068. field_count += 2;
  1069. if (block_size == align) {
  1070. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1071. } else {
  1072. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1073. }
  1074. fields[2] = lb_type(m, union_tag_type(type));
  1075. }
  1076. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1077. }
  1078. break;
  1079. case Type_Enum:
  1080. return lb_type(m, base_enum_type(type));
  1081. case Type_Tuple:
  1082. if (type->Tuple.variables.count == 1) {
  1083. return lb_type(m, type->Tuple.variables[0]->type);
  1084. } else {
  1085. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1086. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1087. for_array(i, type->Tuple.variables) {
  1088. Entity *field = type->Tuple.variables[i];
  1089. LLVMTypeRef param_type = nullptr;
  1090. param_type = lb_type(m, field->type);
  1091. fields[i] = param_type;
  1092. }
  1093. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1094. }
  1095. case Type_Proc:
  1096. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1097. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1098. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1099. } else {
  1100. unsigned param_count = 0;
  1101. if (type->Proc.calling_convention == ProcCC_Odin) {
  1102. param_count += 1;
  1103. }
  1104. if (type->Proc.param_count != 0) {
  1105. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1106. for_array(i, type->Proc.params->Tuple.variables) {
  1107. Entity *e = type->Proc.params->Tuple.variables[i];
  1108. if (e->kind != Entity_Variable) {
  1109. continue;
  1110. }
  1111. param_count += 1;
  1112. }
  1113. }
  1114. m->internal_type_level += 1;
  1115. defer (m->internal_type_level -= 1);
  1116. LLVMTypeRef ret = nullptr;
  1117. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1118. if (type->Proc.result_count != 0) {
  1119. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1120. ret = lb_type(m, single_ret);
  1121. if (ret != nullptr) {
  1122. if (is_type_boolean(single_ret) &&
  1123. is_calling_convention_none(type->Proc.calling_convention) &&
  1124. type_size_of(single_ret) <= 1) {
  1125. ret = LLVMInt1TypeInContext(m->ctx);
  1126. }
  1127. }
  1128. }
  1129. isize param_index = 0;
  1130. if (type->Proc.param_count != 0) {
  1131. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1132. for_array(i, type->Proc.params->Tuple.variables) {
  1133. Entity *e = type->Proc.params->Tuple.variables[i];
  1134. if (e->kind != Entity_Variable) {
  1135. continue;
  1136. }
  1137. Type *e_type = reduce_tuple_to_single_type(e->type);
  1138. LLVMTypeRef param_type = nullptr;
  1139. if (is_type_boolean(e_type) &&
  1140. type_size_of(e_type) <= 1) {
  1141. param_type = LLVMInt1TypeInContext(m->ctx);
  1142. } else {
  1143. if (is_type_proc(e_type)) {
  1144. param_type = lb_type(m, t_rawptr);
  1145. } else {
  1146. param_type = lb_type(m, e_type);
  1147. }
  1148. }
  1149. params[param_index++] = param_type;
  1150. }
  1151. }
  1152. if (param_index < param_count) {
  1153. params[param_index++] = lb_type(m, t_rawptr);
  1154. // params[param_index++] = lb_type(m, t_context_ptr);
  1155. }
  1156. GB_ASSERT(param_index == param_count);
  1157. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1158. map_set(&m->function_type_map, hash_type(type), ft);
  1159. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1160. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1161. // LLVMTypeRef new_ret = LLVMGetReturnType(new_abi_fn_type);
  1162. // LLVMTypeRef old_ret = LLVMGetReturnType(old_abi_fn_type);
  1163. // unsigned new_count = LLVMCountParamTypes(new_abi_fn_type);
  1164. // unsigned old_count = LLVMCountParamTypes(old_abi_fn_type);
  1165. // 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));
  1166. return new_abi_fn_ptr_type;
  1167. }
  1168. break;
  1169. case Type_BitSet:
  1170. {
  1171. Type *ut = bit_set_to_int(type);
  1172. return lb_type(m, ut);
  1173. }
  1174. case Type_SimdVector:
  1175. if (type->SimdVector.is_x86_mmx) {
  1176. return LLVMX86MMXTypeInContext(ctx);
  1177. }
  1178. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1179. case Type_RelativePointer:
  1180. return lb_type_internal(m, type->RelativePointer.base_integer);
  1181. case Type_RelativeSlice:
  1182. {
  1183. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1184. unsigned field_count = 2;
  1185. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1186. fields[0] = base_integer;
  1187. fields[1] = base_integer;
  1188. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1189. }
  1190. }
  1191. GB_PANIC("Invalid type %s", type_to_string(type));
  1192. return LLVMInt32TypeInContext(ctx);
  1193. }
  1194. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1195. type = default_type(type);
  1196. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1197. if (found) {
  1198. return *found;
  1199. }
  1200. LLVMTypeRef llvm_type = nullptr;
  1201. m->internal_type_level += 1;
  1202. llvm_type = lb_type_internal(m, type);
  1203. m->internal_type_level -= 1;
  1204. if (m->internal_type_level == 0) {
  1205. map_set(&m->types, hash_type(type), llvm_type);
  1206. if (is_type_named(type)) {
  1207. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1208. }
  1209. }
  1210. return llvm_type;
  1211. }
  1212. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1213. if (key == nullptr) {
  1214. return nullptr;
  1215. }
  1216. auto found = map_get(&m->debug_values, hash_pointer(key));
  1217. if (found) {
  1218. return *found;
  1219. }
  1220. return nullptr;
  1221. }
  1222. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1223. if (key != nullptr) {
  1224. map_set(&m->debug_values, hash_pointer(key), value);
  1225. }
  1226. }
  1227. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1228. if (node == nullptr) {
  1229. return nullptr;
  1230. }
  1231. return lb_get_llvm_metadata(m, node->file);
  1232. }
  1233. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1234. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1235. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1236. Scope *s = p->scope_stack[i];
  1237. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1238. if (md) {
  1239. return md;
  1240. }
  1241. }
  1242. return p->debug_info;
  1243. }
  1244. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1245. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1246. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1247. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1248. }
  1249. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1250. GB_ASSERT(node != nullptr);
  1251. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1252. }
  1253. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1254. Type *original_type = type;
  1255. LLVMContextRef ctx = m->ctx;
  1256. i64 size = type_size_of(type); // Check size
  1257. GB_ASSERT(type != t_invalid);
  1258. unsigned const word_size = cast(unsigned)build_context.word_size;
  1259. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1260. GB_ASSERT(type->kind == Type_Proc);
  1261. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1262. unsigned parameter_count = 1;
  1263. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1264. Entity *e = type->Proc.params->Tuple.variables[i];
  1265. if (e->kind == Entity_Variable) {
  1266. parameter_count += 1;
  1267. }
  1268. }
  1269. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1270. unsigned param_index = 0;
  1271. if (type->Proc.result_count == 0) {
  1272. parameters[param_index++] = nullptr;
  1273. } else {
  1274. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1275. }
  1276. LLVMMetadataRef parent_scope = nullptr;
  1277. LLVMMetadataRef scope = nullptr;
  1278. LLVMMetadataRef file = nullptr;
  1279. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1280. Entity *e = type->Proc.params->Tuple.variables[i];
  1281. if (e->kind != Entity_Variable) {
  1282. continue;
  1283. }
  1284. parameters[param_index] = lb_debug_type(m, e->type);
  1285. param_index += 1;
  1286. }
  1287. LLVMDIFlags flags = LLVMDIFlagZero;
  1288. if (type->Proc.diverging) {
  1289. flags = LLVMDIFlagNoReturn;
  1290. }
  1291. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1292. }
  1293. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1294. unsigned field_line = 1;
  1295. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1296. AstPackage *pkg = m->info->runtime_package;
  1297. GB_ASSERT(pkg->files.count != 0);
  1298. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1299. LLVMMetadataRef scope = file;
  1300. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1301. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1302. field_flags, lb_debug_type(m, type)
  1303. );
  1304. }
  1305. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1306. AstPackage *pkg = m->info->runtime_package;
  1307. GB_ASSERT(pkg->files.count != 0);
  1308. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1309. LLVMMetadataRef scope = file;
  1310. 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);
  1311. }
  1312. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1313. Type *original_type = type;
  1314. LLVMContextRef ctx = m->ctx;
  1315. i64 size = type_size_of(type); // Check size
  1316. GB_ASSERT(type != t_invalid);
  1317. unsigned const word_size = cast(unsigned)build_context.word_size;
  1318. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1319. switch (type->kind) {
  1320. case Type_Basic:
  1321. switch (type->Basic.kind) {
  1322. case Basic_llvm_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "llvm bool", 9, 1, LLVMDWARFTypeEncoding_Boolean, LLVMDIFlagZero);
  1323. case Basic_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "bool", 4, 8, LLVMDWARFTypeEncoding_Boolean, LLVMDIFlagZero);
  1324. case Basic_b8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b8", 2, 8, LLVMDWARFTypeEncoding_Boolean, LLVMDIFlagZero);
  1325. case Basic_b16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b16", 3, 16, LLVMDWARFTypeEncoding_Boolean, LLVMDIFlagZero);
  1326. case Basic_b32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b32", 3, 32, LLVMDWARFTypeEncoding_Boolean, LLVMDIFlagZero);
  1327. case Basic_b64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b64", 3, 64, LLVMDWARFTypeEncoding_Boolean, LLVMDIFlagZero);
  1328. case Basic_i8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i8", 2, 8, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagZero);
  1329. case Basic_u8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u8", 2, 8, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagZero);
  1330. case Basic_i16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16", 3, 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagZero);
  1331. case Basic_u16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16", 3, 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagZero);
  1332. case Basic_i32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32", 3, 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagZero);
  1333. case Basic_u32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32", 3, 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagZero);
  1334. case Basic_i64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64", 3, 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagZero);
  1335. case Basic_u64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64", 3, 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagZero);
  1336. case Basic_i128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128", 4, 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagZero);
  1337. case Basic_u128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128", 4, 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagZero);
  1338. case Basic_rune: return LLVMDIBuilderCreateBasicType(m->debug_builder, "rune", 4, 32, LLVMDWARFTypeEncoding_Utf, LLVMDIFlagZero);
  1339. // Basic_f16,
  1340. case Basic_f32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32", 3, 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagZero);
  1341. case Basic_f64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64", 3, 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagZero);
  1342. // Basic_complex32,
  1343. case Basic_complex64:
  1344. {
  1345. LLVMMetadataRef elements[2] = {};
  1346. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1347. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1348. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1349. }
  1350. case Basic_complex128:
  1351. {
  1352. LLVMMetadataRef elements[2] = {};
  1353. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1354. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1355. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1356. }
  1357. case Basic_quaternion128:
  1358. {
  1359. LLVMMetadataRef elements[4] = {};
  1360. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1361. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1362. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1363. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1364. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1365. }
  1366. case Basic_quaternion256:
  1367. {
  1368. LLVMMetadataRef elements[4] = {};
  1369. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1370. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1371. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1372. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1373. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1374. }
  1375. case Basic_int: return LLVMDIBuilderCreateBasicType(m->debug_builder, "int", 3, word_bits, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagZero);
  1376. case Basic_uint: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uint", 4, word_bits, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagZero);
  1377. case Basic_uintptr: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uintptr", 7, word_bits, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagZero);
  1378. case Basic_rawptr:
  1379. {
  1380. LLVMMetadataRef void_type = LLVMDIBuilderCreateBasicType(m->debug_builder, "void", 4, 8, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagZero);
  1381. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1382. }
  1383. case Basic_string:
  1384. {
  1385. LLVMMetadataRef elements[2] = {};
  1386. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1387. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1388. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1389. }
  1390. case Basic_cstring:
  1391. {
  1392. LLVMMetadataRef char_type = LLVMDIBuilderCreateBasicType(m->debug_builder, "char", 4, 8, 0, LLVMDIFlagZero);
  1393. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1394. }
  1395. case Basic_any:
  1396. {
  1397. LLVMMetadataRef elements[2] = {};
  1398. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1399. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1400. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1401. }
  1402. case Basic_typeid:
  1403. return LLVMDIBuilderCreateBasicType(m->debug_builder, "typeid", 6, word_bits, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagZero);
  1404. // Endian Specific Types
  1405. case Basic_i16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16le", 5, 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1406. case Basic_u16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16le", 5, 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1407. case Basic_i32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32le", 5, 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1408. case Basic_u32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32le", 5, 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1409. case Basic_i64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64le", 5, 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1410. case Basic_u64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64le", 5, 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1411. case Basic_i128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128le", 6, 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1412. case Basic_u128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128le", 6, 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1413. case Basic_f32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32le", 5, 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1414. case Basic_f64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64le", 5, 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1415. case Basic_i16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16be", 5, 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1416. case Basic_u16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16be", 5, 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1417. case Basic_i32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32be", 5, 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1418. case Basic_u32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32be", 5, 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1419. case Basic_i64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64be", 5, 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1420. case Basic_u64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64be", 5, 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1421. case Basic_i128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128be", 6, 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1422. case Basic_u128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128be", 6, 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1423. case Basic_f32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32be", 5, 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1424. case Basic_f64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64be", 5, 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1425. // Untyped types
  1426. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1427. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1428. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1429. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1430. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1431. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1432. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1433. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1434. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1435. default: GB_PANIC("Basic Unhandled"); break;
  1436. }
  1437. break;
  1438. case Type_Named:
  1439. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1440. case Type_Pointer:
  1441. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1442. case Type_Array:
  1443. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1444. type->Array.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->Array.elem), nullptr, 0);
  1445. case Type_EnumeratedArray:
  1446. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1447. type->EnumeratedArray.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->EnumeratedArray.elem), nullptr, 0);
  1448. case Type_Slice:
  1449. {
  1450. LLVMMetadataRef elements[2] = {};
  1451. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(type->Slice.elem), 0);
  1452. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1453. return lb_debug_basic_struct(m, str_lit("<anonymous-slice>"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1454. }
  1455. break;
  1456. case Type_DynamicArray:
  1457. {
  1458. LLVMMetadataRef elements[4] = {};
  1459. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(type->DynamicArray.elem), 0*word_bits);
  1460. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1461. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1462. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1463. return lb_debug_basic_struct(m, str_lit("<anonymous-dynamic-array>"), 5*word_bits, word_bits, elements, gb_count_of(elements));
  1464. }
  1465. break;
  1466. case Type_Map:
  1467. return lb_debug_type(m, type->Map.internal_type);
  1468. case Type_Struct:
  1469. {
  1470. type_set_offsets(type);
  1471. LLVMMetadataRef parent_scope = nullptr; // lb_get_llvm_metadata(m, type->Struct.scope);
  1472. LLVMMetadataRef scope = parent_scope;
  1473. LLVMMetadataRef file = lb_get_llvm_file_metadata_from_node(m, type->Struct.node);
  1474. unsigned line = 0;
  1475. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1476. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1477. LLVMDIFlags flags = LLVMDIFlagZero;
  1478. unsigned element_count = cast(unsigned)type->Struct.fields.count;
  1479. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1480. for (unsigned i = 0; i < element_count; i++) {
  1481. Entity *f = type->Struct.fields[i];
  1482. GB_ASSERT(f->kind == Entity_Variable);
  1483. String name = f->token.string;
  1484. unsigned field_line = 0;
  1485. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1486. u64 offset_in_bits = 8*cast(u64)type->Struct.offsets[i];
  1487. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1488. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1489. field_flags, lb_debug_type(m, f->type)
  1490. );
  1491. }
  1492. if (type->Struct.is_raw_union) {
  1493. return LLVMDIBuilderCreateUnionType(m->debug_builder, parent_scope, "", 0, file, line,
  1494. size_in_bits, align_in_bits, flags,
  1495. elements, element_count, 0,
  1496. "", 0
  1497. );
  1498. }
  1499. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1500. size_in_bits, align_in_bits, flags,
  1501. nullptr, elements, element_count, 0, nullptr,
  1502. "", 0
  1503. );
  1504. }
  1505. break;
  1506. case Type_Union:
  1507. {
  1508. LLVMMetadataRef scope = lb_get_llvm_metadata(m, type->Union.scope);
  1509. LLVMMetadataRef file = lb_get_llvm_file_metadata_from_node(m, type->Union.node);
  1510. unsigned line = 0;
  1511. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1512. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1513. LLVMDIFlags flags = LLVMDIFlagZero;
  1514. if (type->Union.variants.count == 0) {
  1515. return LLVMDIBuilderCreateStructType(m->debug_builder, scope, "", 0, file, line, size_in_bits, align_in_bits, flags, nullptr, nullptr, 0, 0, nullptr, "", 0);
  1516. } else if (is_type_union_maybe_pointer_original_alignment(type)) {
  1517. return lb_debug_type(m, type->Union.variants[0]);
  1518. }
  1519. unsigned variant_count = cast(unsigned)type->Union.variants.count;
  1520. LLVMMetadataRef *variants = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, variant_count);
  1521. for (unsigned i = 0; i < variant_count; i++) {
  1522. Type *t = type->Union.variants[i];
  1523. char name[16] = {};
  1524. gb_snprintf(name, gb_size_of(name), "v%u", i);
  1525. isize name_len = gb_strlen(name);
  1526. variants[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, name, name_len, file, 0, 8*type_size_of(t), 8*cast(u32)type_align_of(t), 0, LLVMDIFlagZero, lb_debug_type(m, t));
  1527. }
  1528. unsigned top_element_count = 2;
  1529. LLVMMetadataRef top_elements[2] = {};
  1530. top_elements[0] = LLVMDIBuilderCreateUnionType(m->debug_builder, scope, "", 0, file, line, 8*type->Union.variant_block_size, align_in_bits, flags, variants, variant_count, 0, "", 0);
  1531. top_elements[1] = lb_debug_type(m, union_tag_type(type));
  1532. return LLVMDIBuilderCreateStructType(m->debug_builder, scope, "", 0, file, line,
  1533. size_in_bits, align_in_bits, LLVMDIFlagZero, nullptr,
  1534. top_elements, top_element_count, 0, nullptr, "", 0);
  1535. }
  1536. break;
  1537. case Type_Enum:
  1538. {
  1539. #if 0
  1540. return lb_debug_type(m, base_enum_type(type));
  1541. #else
  1542. LLVMMetadataRef scope = nullptr;
  1543. LLVMMetadataRef file = nullptr;
  1544. unsigned line = 0;
  1545. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1546. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1547. Type *bt = base_enum_type(type);
  1548. LLVMBool is_unsigned = is_type_unsigned(bt);
  1549. for (unsigned i = 0; i < element_count; i++) {
  1550. Entity *f = type->Enum.fields[i];
  1551. GB_ASSERT(f->kind == Entity_Constant);
  1552. String name = f->token.string;
  1553. i64 value = exact_value_to_i64(f->Constant.value);
  1554. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1555. }
  1556. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1557. 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);
  1558. #endif
  1559. }
  1560. case Type_Tuple:
  1561. if (type->Tuple.variables.count == 1) {
  1562. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1563. } else {
  1564. type_set_offsets(type);
  1565. LLVMMetadataRef parent_scope = nullptr;
  1566. LLVMMetadataRef scope = nullptr;
  1567. LLVMMetadataRef file = nullptr;
  1568. unsigned line = 0;
  1569. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1570. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1571. LLVMDIFlags flags = LLVMDIFlagZero;
  1572. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1573. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1574. for (unsigned i = 0; i < element_count; i++) {
  1575. Entity *f = type->Tuple.variables[i];
  1576. GB_ASSERT(f->kind == Entity_Variable);
  1577. String name = f->token.string;
  1578. unsigned field_line = 0;
  1579. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1580. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1581. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1582. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1583. field_flags, lb_debug_type(m, f->type)
  1584. );
  1585. }
  1586. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1587. size_in_bits, align_in_bits, flags,
  1588. nullptr, elements, element_count, 0, nullptr,
  1589. "", 0
  1590. );
  1591. }
  1592. case Type_Proc:
  1593. {
  1594. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1595. return LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1596. }
  1597. break;
  1598. case Type_BitSet:
  1599. return lb_debug_type(m, bit_set_to_int(type));
  1600. case Type_SimdVector:
  1601. if (type->SimdVector.is_x86_mmx) {
  1602. GB_PANIC("TODO x86_mmx debug info");
  1603. }
  1604. 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);
  1605. case Type_RelativePointer:
  1606. return lb_debug_type(m, type->RelativePointer.base_integer);
  1607. case Type_RelativeSlice:
  1608. {
  1609. unsigned element_count = 0;
  1610. LLVMMetadataRef elements[2] = {};
  1611. Type *base_integer = type->RelativeSlice.base_integer;
  1612. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1613. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1614. return LLVMDIBuilderCreateStructType(m->debug_builder, nullptr, "", 0, nullptr, 0, 2*word_bits, word_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1615. }
  1616. }
  1617. GB_PANIC("Invalid type %s", type_to_string(type));
  1618. return nullptr;
  1619. }
  1620. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1621. GB_ASSERT(type != nullptr);
  1622. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1623. if (found != nullptr) {
  1624. return found;
  1625. }
  1626. if (type->kind == Type_Named) {
  1627. LLVMMetadataRef file = nullptr;
  1628. unsigned line = 0;
  1629. LLVMMetadataRef scope = nullptr;
  1630. if (type->Named.type_name != nullptr) {
  1631. Entity *e = type->Named.type_name;
  1632. scope = lb_get_llvm_metadata(m, e->scope);
  1633. if (scope != nullptr) {
  1634. file = LLVMDIScopeGetFile(scope);
  1635. }
  1636. line = cast(unsigned)e->token.pos.line;
  1637. }
  1638. // TODO(bill): location data for Type_Named
  1639. u64 size_in_bits = 8*type_size_of(type);
  1640. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1641. String name = type->Named.name;
  1642. char const *name_text = cast(char const *)name.text;
  1643. size_t name_len = cast(size_t)name.len;
  1644. unsigned tag = DW_TAG_structure_type;
  1645. if (is_type_raw_union(type) || is_type_union(type)) {
  1646. tag = DW_TAG_union_type;
  1647. }
  1648. LLVMDIFlags flags = LLVMDIFlagZero;
  1649. Type *bt = base_type(type->Named.base);
  1650. lbIncompleteDebugType idt = {};
  1651. idt.type = type;
  1652. switch (bt->kind) {
  1653. case Type_Enum:
  1654. {
  1655. LLVMMetadataRef scope = nullptr;
  1656. LLVMMetadataRef file = nullptr;
  1657. unsigned line = 0;
  1658. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1659. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1660. Type *ct = base_enum_type(type);
  1661. LLVMBool is_unsigned = is_type_unsigned(ct);
  1662. for (unsigned i = 0; i < element_count; i++) {
  1663. Entity *f = bt->Enum.fields[i];
  1664. GB_ASSERT(f->kind == Entity_Constant);
  1665. String name = f->token.string;
  1666. i64 value = exact_value_to_i64(f->Constant.value);
  1667. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1668. }
  1669. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1670. 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);
  1671. }
  1672. case Type_Basic:
  1673. case Type_Pointer:
  1674. case Type_Array:
  1675. case Type_EnumeratedArray:
  1676. case Type_Tuple:
  1677. case Type_Proc:
  1678. case Type_BitSet:
  1679. case Type_SimdVector:
  1680. case Type_RelativePointer:
  1681. case Type_RelativeSlice:
  1682. case Type_Map: // TODO(bill): Is this okay?
  1683. {
  1684. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1685. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1686. lb_set_llvm_metadata(m, type, final_decl);
  1687. return final_decl;
  1688. }
  1689. case Type_Slice:
  1690. case Type_DynamicArray:
  1691. case Type_Struct:
  1692. case Type_Union:
  1693. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1694. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1695. );
  1696. idt.metadata = temp_forward_decl;
  1697. array_add(&m->debug_incomplete_types, idt);
  1698. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1699. return temp_forward_decl;
  1700. }
  1701. }
  1702. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1703. lb_set_llvm_metadata(m, type, dt);
  1704. return dt;
  1705. }
  1706. void lb_debug_complete_types(lbModule *m) {
  1707. unsigned const word_size = cast(unsigned)build_context.word_size;
  1708. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1709. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1710. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1711. GB_ASSERT(idt.type != nullptr);
  1712. GB_ASSERT(idt.metadata != nullptr);
  1713. Type *t = idt.type;
  1714. Type *bt = base_type(t);
  1715. LLVMMetadataRef parent_scope = nullptr;
  1716. LLVMMetadataRef file = nullptr;
  1717. unsigned line_number = 0;
  1718. u64 size_in_bits = 8*type_size_of(t);
  1719. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1720. LLVMDIFlags flags = LLVMDIFlagZero;
  1721. LLVMMetadataRef derived_from = nullptr;
  1722. LLVMMetadataRef *elements = nullptr;
  1723. unsigned element_count = 0;
  1724. unsigned runtime_lang = 0; // Objective-C runtime version
  1725. char const *unique_id = "";
  1726. LLVMMetadataRef vtable_holder = nullptr;
  1727. size_t unique_id_len = 0;
  1728. LLVMMetadataRef record_scope = nullptr;
  1729. switch (bt->kind) {
  1730. case Type_Slice:
  1731. case Type_DynamicArray:
  1732. case Type_Map:
  1733. case Type_Struct:
  1734. case Type_Union: {
  1735. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1736. String name = str_lit("<anonymous-struct>");
  1737. if (t->kind == Type_Named) {
  1738. name = t->Named.name;
  1739. LLVMMetadataRef file = nullptr;
  1740. unsigned line = 0;
  1741. LLVMMetadataRef file_scope = nullptr;
  1742. if (t->Named.type_name != nullptr) {
  1743. Entity *e = t->Named.type_name;
  1744. file_scope = lb_get_llvm_metadata(m, e->scope);
  1745. if (file_scope != nullptr) {
  1746. file = LLVMDIScopeGetFile(file_scope);
  1747. }
  1748. line = cast(unsigned)e->token.pos.line;
  1749. }
  1750. // TODO(bill): location data for Type_Named
  1751. } else {
  1752. switch (bt->kind) {
  1753. case Type_Slice: name = str_lit("<anonymous-slice>"); break;
  1754. case Type_DynamicArray: name = str_lit("<anonymous-dynamic-array>"); break;
  1755. case Type_Map: name = str_lit("<anonymous-map>"); break;
  1756. case Type_Struct: name = str_lit("<anonymous-struct>"); break;
  1757. case Type_Union: name = str_lit("<anonymous-union>"); break;
  1758. }
  1759. }
  1760. switch (bt->kind) {
  1761. case Type_Slice:
  1762. element_count = 2;
  1763. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1764. elements[0] = LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, bt->Slice.elem), word_bits, word_bits, 0, nullptr, 0);
  1765. elements[1] = lb_debug_type(m, t_int);
  1766. break;
  1767. case Type_DynamicArray:
  1768. element_count = 4;
  1769. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1770. elements[0] = LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, bt->DynamicArray.elem), word_bits, word_bits, 0, nullptr, 0);
  1771. elements[1] = lb_debug_type(m, t_int);
  1772. elements[2] = lb_debug_type(m, t_int);
  1773. elements[3] = lb_debug_type(m, t_allocator);
  1774. break;
  1775. case Type_Map:
  1776. break;
  1777. case Type_Struct:
  1778. if (file == nullptr) {
  1779. GB_ASSERT(bt->Struct.node != nullptr);
  1780. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1781. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1782. }
  1783. type_set_offsets(bt);
  1784. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  1785. element_count = cast(unsigned)bt->Struct.fields.count;
  1786. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1787. for_array(j, bt->Struct.fields) {
  1788. Entity *f = bt->Struct.fields[j];
  1789. String fname = f->token.string;
  1790. unsigned field_line = 0;
  1791. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1792. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  1793. elements[j] = LLVMDIBuilderCreateMemberType(
  1794. m->debug_builder, record_scope,
  1795. cast(char const *)fname.text, cast(size_t)fname.len,
  1796. file, field_line,
  1797. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  1798. offset_in_bits,
  1799. field_flags, lb_debug_type(m, f->type)
  1800. );
  1801. }
  1802. break;
  1803. case Type_Union:
  1804. if (file == nullptr) {
  1805. GB_ASSERT(bt->Union.node != nullptr);
  1806. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  1807. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  1808. }
  1809. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  1810. element_count = cast(unsigned)bt->Union.variants.count;
  1811. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1812. for_array(j, bt->Union.variants) {
  1813. Type *variant = bt->Union.variants[j];
  1814. char name[16] = {};
  1815. gb_snprintf(name, gb_size_of(name), "v%u", cast(unsigned)j);
  1816. isize name_len = gb_strlen(name);
  1817. unsigned field_line = 0;
  1818. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1819. u64 offset_in_bits = 0;
  1820. elements[j] = LLVMDIBuilderCreateMemberType(
  1821. m->debug_builder, record_scope,
  1822. name, name_len,
  1823. file, field_line,
  1824. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  1825. offset_in_bits,
  1826. field_flags, lb_debug_type(m, variant)
  1827. );
  1828. }
  1829. break;
  1830. }
  1831. LLVMMetadataRef final_metadata = nullptr;
  1832. if (is_union) {
  1833. final_metadata = LLVMDIBuilderCreateUnionType(
  1834. m->debug_builder,
  1835. parent_scope,
  1836. cast(char const *)name.text, cast(size_t)name.len,
  1837. file, line_number,
  1838. size_in_bits, align_in_bits,
  1839. flags,
  1840. elements, element_count,
  1841. runtime_lang,
  1842. unique_id, unique_id_len
  1843. );
  1844. } else {
  1845. final_metadata = LLVMDIBuilderCreateStructType(
  1846. m->debug_builder,
  1847. parent_scope,
  1848. cast(char const *)name.text, cast(size_t)name.len,
  1849. file, line_number,
  1850. size_in_bits, align_in_bits,
  1851. flags,
  1852. derived_from,
  1853. elements, element_count,
  1854. runtime_lang,
  1855. vtable_holder,
  1856. unique_id, unique_id_len
  1857. );
  1858. }
  1859. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  1860. lb_set_llvm_metadata(m, idt.type, final_metadata);
  1861. } break;
  1862. default:
  1863. GB_PANIC("invalid incomplete debug type");
  1864. break;
  1865. }
  1866. }
  1867. array_clear(&m->debug_incomplete_types);
  1868. }
  1869. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1870. if (e != nullptr) {
  1871. map_set(&m->values, hash_entity(e), val);
  1872. }
  1873. }
  1874. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1875. if (name.len > 0) {
  1876. string_map_set(&m->members, name, val);
  1877. }
  1878. }
  1879. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1880. string_map_set(&m->members, key, val);
  1881. }
  1882. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1883. if (p->entity != nullptr) {
  1884. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1885. }
  1886. string_map_set(&m->procedures, p->name, p);
  1887. }
  1888. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  1889. LLVMTypeRef src = LLVMTypeOf(val);
  1890. if (src == dst) {
  1891. return val;
  1892. }
  1893. if (LLVMIsNull(val)) {
  1894. return LLVMConstNull(dst);
  1895. }
  1896. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  1897. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  1898. switch (kind) {
  1899. case LLVMPointerTypeKind:
  1900. return LLVMConstPointerCast(val, dst);
  1901. case LLVMStructTypeKind:
  1902. return LLVMConstBitCast(val, dst);
  1903. default:
  1904. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  1905. }
  1906. return val;
  1907. }
  1908. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  1909. unsigned value_count = cast(unsigned)value_count_;
  1910. unsigned elem_count = LLVMCountStructElementTypes(t);
  1911. GB_ASSERT(value_count == elem_count);
  1912. for (unsigned i = 0; i < elem_count; i++) {
  1913. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  1914. values[i] = llvm_const_cast(values[i], elem_type);
  1915. }
  1916. return LLVMConstNamedStruct(t, values, value_count);
  1917. }
  1918. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  1919. unsigned value_count = cast(unsigned)value_count_;
  1920. for (unsigned i = 0; i < value_count; i++) {
  1921. values[i] = llvm_const_cast(values[i], elem_type);
  1922. }
  1923. return LLVMConstArray(elem_type, values, value_count);
  1924. }
  1925. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  1926. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  1927. LLVMValueRef values[2] = {
  1928. str_elem.value,
  1929. str_len.value,
  1930. };
  1931. lbValue res = {};
  1932. res.type = t_string;
  1933. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  1934. return res;
  1935. } else {
  1936. lbAddr res = lb_add_local_generated(p, t_string, false);
  1937. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  1938. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  1939. return lb_addr_load(p, res);
  1940. }
  1941. }
  1942. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1943. String s = make_string_c(name);
  1944. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  1945. // and the current LLVM C API does not expose this functionality yet.
  1946. // It is better to ignore the attributes for the time being
  1947. if (s == "byval") {
  1948. return nullptr;
  1949. } else if (s == "byref") {
  1950. return nullptr;
  1951. } else if (s == "preallocated") {
  1952. return nullptr;
  1953. } else if (s == "sret") {
  1954. return nullptr;
  1955. }
  1956. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1957. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1958. return LLVMCreateEnumAttribute(ctx, kind, value);
  1959. }
  1960. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1961. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1962. GB_ASSERT(attr != nullptr);
  1963. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1964. }
  1965. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1966. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  1967. }
  1968. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  1969. if (p->abi_function_type != nullptr) {
  1970. return;
  1971. }
  1972. auto hash = hash_type(p->type);
  1973. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  1974. if (ft_found == nullptr) {
  1975. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  1976. ft_found = map_get(&m->function_type_map, hash);
  1977. }
  1978. GB_ASSERT(ft_found != nullptr);
  1979. p->abi_function_type = *ft_found;
  1980. GB_ASSERT(p->abi_function_type != nullptr);
  1981. }
  1982. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  1983. GB_ASSERT(entity != nullptr);
  1984. String link_name = lb_get_entity_name(m, entity);
  1985. {
  1986. StringHashKey key = string_hash_string(link_name);
  1987. lbValue *found = string_map_get(&m->members, key);
  1988. if (found) {
  1989. lb_add_entity(m, entity, *found);
  1990. lbProcedure **p_found = string_map_get(&m->procedures, key);
  1991. GB_ASSERT(p_found != nullptr);
  1992. return *p_found;
  1993. }
  1994. }
  1995. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1996. p->module = m;
  1997. entity->code_gen_module = m;
  1998. entity->code_gen_procedure = p;
  1999. p->entity = entity;
  2000. p->name = link_name;
  2001. DeclInfo *decl = entity->decl_info;
  2002. ast_node(pl, ProcLit, decl->proc_lit);
  2003. Type *pt = base_type(entity->type);
  2004. GB_ASSERT(pt->kind == Type_Proc);
  2005. set_procedure_abi_types(entity->type);
  2006. p->type = entity->type;
  2007. p->type_expr = decl->type_expr;
  2008. p->body = pl->body;
  2009. p->tags = pt->Proc.tags;
  2010. p->inlining = ProcInlining_none;
  2011. p->is_foreign = entity->Procedure.is_foreign;
  2012. p->is_export = entity->Procedure.is_export;
  2013. p->is_entry_point = false;
  2014. gbAllocator a = heap_allocator();
  2015. p->children.allocator = a;
  2016. p->params.allocator = a;
  2017. p->defer_stmts.allocator = a;
  2018. p->blocks.allocator = a;
  2019. p->branch_blocks.allocator = a;
  2020. p->context_stack.allocator = a;
  2021. p->scope_stack.allocator = a;
  2022. if (p->is_foreign) {
  2023. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2024. }
  2025. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2026. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2027. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2028. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2029. lb_ensure_abi_function_type(m, p);
  2030. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2031. if (false) {
  2032. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2033. // TODO(bill): Clean up this logic
  2034. if (build_context.metrics.os != TargetOs_js) {
  2035. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2036. }
  2037. LLVMSetFunctionCallConv(p->value, cc_kind);
  2038. }
  2039. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2040. // // TODO(bill): Clean up this logic
  2041. // if (build_context.metrics.os != TargetOs_js) {
  2042. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2043. // }
  2044. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2045. lbValue proc_value = {p->value, p->type};
  2046. lb_add_entity(m, entity, proc_value);
  2047. lb_add_member(m, p->name, proc_value);
  2048. lb_add_procedure_value(m, p);
  2049. if (p->is_export) {
  2050. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2051. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2052. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2053. if (build_context.metrics.os == TargetOs_js) {
  2054. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2055. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2056. }
  2057. }
  2058. if (p->is_foreign) {
  2059. if (build_context.metrics.os == TargetOs_js) {
  2060. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2061. char const *module_name = "env";
  2062. if (entity->Procedure.foreign_library != nullptr) {
  2063. Entity *foreign_library = entity->Procedure.foreign_library;
  2064. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2065. if (foreign_library->LibraryName.paths.count > 0) {
  2066. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2067. }
  2068. }
  2069. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2070. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2071. }
  2072. }
  2073. // NOTE(bill): offset==0 is the return value
  2074. isize offset = 1;
  2075. if (pt->Proc.return_by_pointer) {
  2076. offset = 2;
  2077. }
  2078. isize parameter_index = 0;
  2079. if (pt->Proc.param_count) {
  2080. TypeTuple *params = &pt->Proc.params->Tuple;
  2081. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2082. Entity *e = params->variables[i];
  2083. Type *original_type = e->type;
  2084. Type *abi_type = pt->Proc.abi_compat_params[i];
  2085. if (e->kind != Entity_Variable) continue;
  2086. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2087. continue;
  2088. }
  2089. if (is_type_tuple(abi_type)) {
  2090. for_array(j, abi_type->Tuple.variables) {
  2091. Type *tft = abi_type->Tuple.variables[j]->type;
  2092. if (e->flags&EntityFlag_NoAlias) {
  2093. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  2094. }
  2095. }
  2096. parameter_index += abi_type->Tuple.variables.count;
  2097. } else {
  2098. if (e->flags&EntityFlag_NoAlias) {
  2099. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2100. }
  2101. parameter_index += 1;
  2102. }
  2103. }
  2104. }
  2105. if (m->debug_builder) { // Debug Information
  2106. Type *bt = base_type(p->type);
  2107. unsigned line = cast(unsigned)entity->token.pos.line;
  2108. LLVMMetadataRef scope = nullptr;
  2109. LLVMMetadataRef file = nullptr;
  2110. LLVMMetadataRef type = nullptr;
  2111. scope = p->module->debug_compile_unit;
  2112. type = lb_debug_type_internal_proc(m, bt);
  2113. if (entity->file != nullptr) {
  2114. file = lb_get_llvm_metadata(m, entity->file);
  2115. scope = file;
  2116. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2117. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2118. scope = file;
  2119. } else if (entity->scope != nullptr) {
  2120. file = lb_get_llvm_metadata(m, entity->scope->file);
  2121. scope = file;
  2122. }
  2123. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2124. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2125. LLVMBool is_local_to_unit = false;
  2126. LLVMBool is_definition = p->body != nullptr;
  2127. unsigned scope_line = line;
  2128. u32 flags = LLVMDIFlagStaticMember;
  2129. LLVMBool is_optimized = false;
  2130. if (bt->Proc.diverging) {
  2131. flags |= LLVMDIFlagNoReturn;
  2132. }
  2133. if (p->body == nullptr) {
  2134. flags |= LLVMDIFlagPrototyped;
  2135. is_optimized = false;
  2136. }
  2137. if (p->body != nullptr) {
  2138. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2139. cast(char const *)entity->token.string.text, entity->token.string.len,
  2140. cast(char const *)p->name.text, p->name.len,
  2141. file, line, type,
  2142. is_local_to_unit, is_definition,
  2143. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2144. );
  2145. GB_ASSERT(p->debug_info != nullptr);
  2146. LLVMSetSubprogram(p->value, p->debug_info);
  2147. lb_set_llvm_metadata(m, p, p->debug_info);
  2148. }
  2149. }
  2150. return p;
  2151. }
  2152. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2153. {
  2154. lbValue *found = string_map_get(&m->members, link_name);
  2155. GB_ASSERT(found == nullptr);
  2156. }
  2157. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2158. p->module = m;
  2159. p->name = link_name;
  2160. p->type = type;
  2161. p->type_expr = nullptr;
  2162. p->body = nullptr;
  2163. p->tags = 0;
  2164. p->inlining = ProcInlining_none;
  2165. p->is_foreign = false;
  2166. p->is_export = false;
  2167. p->is_entry_point = false;
  2168. gbAllocator a = permanent_allocator();
  2169. p->children.allocator = a;
  2170. p->params.allocator = a;
  2171. p->defer_stmts.allocator = a;
  2172. p->blocks.allocator = a;
  2173. p->branch_blocks.allocator = a;
  2174. p->context_stack.allocator = a;
  2175. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2176. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2177. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2178. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2179. Type *pt = p->type;
  2180. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2181. // TODO(bill): Clean up this logic
  2182. if (build_context.metrics.os != TargetOs_js) {
  2183. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2184. }
  2185. LLVMSetFunctionCallConv(p->value, cc_kind);
  2186. lbValue proc_value = {p->value, p->type};
  2187. lb_add_member(m, p->name, proc_value);
  2188. lb_add_procedure_value(m, p);
  2189. // NOTE(bill): offset==0 is the return value
  2190. isize offset = 1;
  2191. if (pt->Proc.return_by_pointer) {
  2192. lb_add_proc_attribute_at_index(p, 1, "sret");
  2193. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2194. offset = 2;
  2195. }
  2196. isize parameter_index = 0;
  2197. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2198. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2199. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2200. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2201. }
  2202. return p;
  2203. }
  2204. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2205. lbParamPasskind kind = lbParamPass_Value;
  2206. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2207. if (is_type_pointer(abi_type)) {
  2208. GB_ASSERT(e->kind == Entity_Variable);
  2209. Type *av = core_type(type_deref(abi_type));
  2210. if (are_types_identical(av, core_type(e->type))) {
  2211. kind = lbParamPass_Pointer;
  2212. if (e->flags&EntityFlag_Value) {
  2213. kind = lbParamPass_ConstRef;
  2214. }
  2215. } else {
  2216. kind = lbParamPass_BitCast;
  2217. }
  2218. } else if (is_type_integer(abi_type)) {
  2219. kind = lbParamPass_Integer;
  2220. } else if (abi_type == t_llvm_bool) {
  2221. kind = lbParamPass_Value;
  2222. } else if (is_type_boolean(abi_type)) {
  2223. kind = lbParamPass_Integer;
  2224. } else if (is_type_simd_vector(abi_type)) {
  2225. kind = lbParamPass_BitCast;
  2226. } else if (is_type_float(abi_type)) {
  2227. kind = lbParamPass_BitCast;
  2228. } else if (is_type_tuple(abi_type)) {
  2229. kind = lbParamPass_Tuple;
  2230. } else if (is_type_proc(abi_type)) {
  2231. kind = lbParamPass_Value;
  2232. } else {
  2233. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2234. }
  2235. }
  2236. if (kind_) *kind_ = kind;
  2237. lbValue res = {};
  2238. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2239. res.type = abi_type;
  2240. return res;
  2241. }
  2242. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  2243. lbParamPasskind kind = lbParamPass_Value;
  2244. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  2245. array_add(&p->params, v);
  2246. lbValue res = {};
  2247. switch (kind) {
  2248. case lbParamPass_Value: {
  2249. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2250. lbValue x = v;
  2251. if (abi_type == t_llvm_bool) {
  2252. x = lb_emit_conv(p, x, t_bool);
  2253. }
  2254. lb_addr_store(p, l, x);
  2255. return x;
  2256. }
  2257. case lbParamPass_Pointer:
  2258. lb_add_entity(p->module, e, v);
  2259. return lb_emit_load(p, v);
  2260. case lbParamPass_Integer: {
  2261. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2262. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  2263. lb_emit_store(p, iptr, v);
  2264. return lb_addr_load(p, l);
  2265. }
  2266. case lbParamPass_ConstRef:
  2267. lb_add_entity(p->module, e, v);
  2268. return lb_emit_load(p, v);
  2269. case lbParamPass_BitCast: {
  2270. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2271. lbValue x = lb_emit_transmute(p, v, e->type);
  2272. lb_addr_store(p, l, x);
  2273. return x;
  2274. }
  2275. case lbParamPass_Tuple: {
  2276. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2277. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2278. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2279. if (abi_type->Tuple.variables.count > 0) {
  2280. array_pop(&p->params);
  2281. }
  2282. for_array(i, abi_type->Tuple.variables) {
  2283. Type *t = abi_type->Tuple.variables[i]->type;
  2284. GB_ASSERT(!is_type_tuple(t));
  2285. lbParamPasskind elem_kind = lbParamPass_Value;
  2286. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2287. array_add(&p->params, elem);
  2288. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2289. lb_emit_store(p, dst, elem);
  2290. }
  2291. return lb_addr_load(p, l);
  2292. }
  2293. }
  2294. GB_PANIC("Unreachable");
  2295. return {};
  2296. }
  2297. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2298. GB_ASSERT(b != nullptr);
  2299. if (!b->appended) {
  2300. b->appended = true;
  2301. LLVMAppendExistingBasicBlock(p->value, b->block);
  2302. }
  2303. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2304. p->curr_block = b;
  2305. }
  2306. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2307. LLVMContextRef ctx = p->module->ctx;
  2308. LLVMTypeRef src_type = LLVMTypeOf(val);
  2309. if (src_type == dst_type) {
  2310. return val;
  2311. }
  2312. i64 src_size = lb_sizeof(src_type);
  2313. i64 dst_size = lb_sizeof(dst_type);
  2314. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2315. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2316. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2317. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2318. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2319. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2320. }
  2321. if (src_size != dst_size && (lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2322. // Okay
  2323. } else {
  2324. GB_ASSERT_MSG(src_size == dst_size, "%s == %s", LLVMPrintTypeToString(src_type), LLVMPrintTypeToString(dst_type));
  2325. }
  2326. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2327. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2328. if (src_kind == dst_kind) {
  2329. if (src_kind == LLVMPointerTypeKind) {
  2330. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2331. } else if (src_kind == LLVMArrayTypeKind) {
  2332. // ignore
  2333. } else if (src_kind != LLVMStructTypeKind) {
  2334. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2335. }
  2336. } else {
  2337. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2338. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2339. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2340. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2341. }
  2342. }
  2343. if (LLVMIsALoadInst(val)) {
  2344. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2345. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2346. return LLVMBuildLoad(p->builder, val_ptr, "");
  2347. } else {
  2348. GB_ASSERT(p->decl_block != p->curr_block);
  2349. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2350. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2351. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2352. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2353. max_align = gb_max(max_align, 4);
  2354. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2355. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2356. LLVMBuildStore(p->builder, val, nptr);
  2357. return LLVMBuildLoad(p->builder, ptr, "");
  2358. }
  2359. }
  2360. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2361. if (p->debug_info == nullptr) {
  2362. return;
  2363. }
  2364. if (type == nullptr) {
  2365. return;
  2366. }
  2367. if (type == t_invalid) {
  2368. return;
  2369. }
  2370. if (p->body == nullptr) {
  2371. return;
  2372. }
  2373. lbModule *m = p->module;
  2374. String const &name = token.string;
  2375. if (name == "" || name == "_") {
  2376. return;
  2377. }
  2378. AstFile *file = p->body->file;
  2379. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2380. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2381. GB_ASSERT(llvm_scope != nullptr);
  2382. if (llvm_file == nullptr) {
  2383. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2384. }
  2385. if (llvm_file == nullptr) {
  2386. return;
  2387. }
  2388. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2389. LLVMDIFlags flags = LLVMDIFlagZero;
  2390. LLVMBool always_preserve = build_context.optimization_level == 0;
  2391. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2392. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2393. m->debug_builder, llvm_scope,
  2394. cast(char const *)name.text, cast(size_t)name.len,
  2395. llvm_file, token.pos.line,
  2396. debug_type,
  2397. always_preserve, flags, alignment_in_bits
  2398. );
  2399. LLVMValueRef storage = ptr;
  2400. LLVMValueRef instr = ptr;
  2401. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2402. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2403. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2404. }
  2405. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2406. if (!p->debug_info || !p->body) {
  2407. return;
  2408. }
  2409. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2410. if (!loc) {
  2411. return;
  2412. }
  2413. TokenPos pos = {};
  2414. pos.file_id = p->body->file ? p->body->file->id : 0;
  2415. pos.line = LLVMDILocationGetLine(loc);
  2416. pos.column = LLVMDILocationGetColumn(loc);
  2417. Token token = {};
  2418. token.kind = Token_context;
  2419. token.string = str_lit("context");
  2420. token.pos = pos;
  2421. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2422. }
  2423. void lb_begin_procedure_body(lbProcedure *p) {
  2424. DeclInfo *decl = decl_info_of_entity(p->entity);
  2425. if (decl != nullptr) {
  2426. for_array(i, decl->labels) {
  2427. BlockLabel bl = decl->labels[i];
  2428. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2429. array_add(&p->branch_blocks, bb);
  2430. }
  2431. }
  2432. if (p->tags != 0) {
  2433. u64 in = p->tags;
  2434. u64 out = p->module->state_flags;
  2435. if (in & ProcTag_bounds_check) {
  2436. out |= StateFlag_bounds_check;
  2437. out &= ~StateFlag_no_bounds_check;
  2438. } else if (in & ProcTag_no_bounds_check) {
  2439. out |= StateFlag_no_bounds_check;
  2440. out &= ~StateFlag_bounds_check;
  2441. }
  2442. p->module->state_flags = out;
  2443. }
  2444. p->builder = LLVMCreateBuilder();
  2445. p->decl_block = lb_create_block(p, "decls", true);
  2446. p->entry_block = lb_create_block(p, "entry", true);
  2447. lb_start_block(p, p->entry_block);
  2448. GB_ASSERT(p->type != nullptr);
  2449. lb_ensure_abi_function_type(p->module, p);
  2450. {
  2451. lbFunctionType *ft = p->abi_function_type;
  2452. unsigned param_offset = 0;
  2453. lbValue return_ptr_value = {};
  2454. if (ft->ret.kind == lbArg_Indirect) {
  2455. // NOTE(bill): this must be parameter 0
  2456. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2457. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2458. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2459. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2460. return_ptr_value.type = ptr_type;
  2461. p->return_ptr = lb_addr(return_ptr_value);
  2462. lb_add_entity(p->module, e, return_ptr_value);
  2463. param_offset += 1;
  2464. }
  2465. if (p->type->Proc.params != nullptr) {
  2466. TypeTuple *params = &p->type->Proc.params->Tuple;
  2467. unsigned param_index = 0;
  2468. for_array(i, params->variables) {
  2469. Entity *e = params->variables[i];
  2470. if (e->kind != Entity_Variable) {
  2471. continue;
  2472. }
  2473. lbArgType *arg_type = &ft->args[param_index];
  2474. if (arg_type->kind == lbArg_Ignore) {
  2475. continue;
  2476. } else if (arg_type->kind == lbArg_Direct) {
  2477. lbParamPasskind kind = lbParamPass_Value;
  2478. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2479. if (param_type != arg_type->type) {
  2480. kind = lbParamPass_BitCast;
  2481. }
  2482. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2483. value = OdinLLVMBuildTransmute(p, value, param_type);
  2484. lbValue param = {};
  2485. param.value = value;
  2486. param.type = e->type;
  2487. array_add(&p->params, param);
  2488. if (e->token.string.len != 0) {
  2489. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2490. lb_addr_store(p, l, param);
  2491. }
  2492. param_index += 1;
  2493. } else if (arg_type->kind == lbArg_Indirect) {
  2494. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2495. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2496. lbValue param = {};
  2497. param.value = value;
  2498. param.type = e->type;
  2499. array_add(&p->params, param);
  2500. lbValue ptr = {};
  2501. ptr.value = value_ptr;
  2502. ptr.type = alloc_type_pointer(e->type);
  2503. lb_add_entity(p->module, e, ptr);
  2504. param_index += 1;
  2505. }
  2506. }
  2507. }
  2508. if (p->type->Proc.has_named_results) {
  2509. GB_ASSERT(p->type->Proc.result_count > 0);
  2510. TypeTuple *results = &p->type->Proc.results->Tuple;
  2511. for_array(i, results->variables) {
  2512. Entity *e = results->variables[i];
  2513. GB_ASSERT(e->kind == Entity_Variable);
  2514. if (e->token.string != "") {
  2515. GB_ASSERT(!is_blank_ident(e->token));
  2516. lbAddr res = {};
  2517. if (return_ptr_value.value) {
  2518. lbValue ptr = return_ptr_value;
  2519. if (results->variables.count != 1) {
  2520. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2521. }
  2522. res = lb_addr(ptr);
  2523. lb_add_entity(p->module, e, ptr);
  2524. } else {
  2525. res = lb_add_local(p, e->type, e);
  2526. }
  2527. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2528. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2529. lb_addr_store(p, res, c);
  2530. }
  2531. }
  2532. }
  2533. }
  2534. }
  2535. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2536. lb_push_context_onto_stack_from_implicit_parameter(p);
  2537. }
  2538. lb_start_block(p, p->entry_block);
  2539. if (p->debug_info != nullptr) {
  2540. TokenPos pos = {};
  2541. if (p->body != nullptr) {
  2542. pos = ast_token(p->body).pos;
  2543. } else if (p->type_expr != nullptr) {
  2544. pos = ast_token(p->type_expr).pos;
  2545. } else if (p->entity != nullptr) {
  2546. pos = p->entity->token.pos;
  2547. }
  2548. if (pos.file_id != 0) {
  2549. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2550. }
  2551. if (p->context_stack.count != 0) {
  2552. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2553. }
  2554. }
  2555. }
  2556. void lb_end_procedure_body(lbProcedure *p) {
  2557. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2558. LLVMBuildBr(p->builder, p->entry_block->block);
  2559. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2560. // Make sure there is a "ret void" at the end of a procedure with no return type
  2561. if (p->type->Proc.result_count == 0) {
  2562. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2563. if (!lb_is_instr_terminating(instr)) {
  2564. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2565. LLVMBuildRetVoid(p->builder);
  2566. }
  2567. }
  2568. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2569. LLVMBasicBlockRef block = nullptr;
  2570. // Make sure every block terminates, and if not, make it unreachable
  2571. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2572. LLVMValueRef instr = LLVMGetLastInstruction(block);
  2573. if (instr == nullptr) {
  2574. LLVMPositionBuilderAtEnd(p->builder, block);
  2575. LLVMBuildUnreachable(p->builder);
  2576. }
  2577. }
  2578. p->curr_block = nullptr;
  2579. p->module->state_flags = 0;
  2580. }
  2581. void lb_end_procedure(lbProcedure *p) {
  2582. LLVMDisposeBuilder(p->builder);
  2583. }
  2584. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2585. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2586. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2587. array_add(&from->succs, to);
  2588. array_add(&to->preds, from);
  2589. }
  2590. }
  2591. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2592. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2593. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2594. b->appended = false;
  2595. if (append) {
  2596. b->appended = true;
  2597. LLVMAppendExistingBasicBlock(p->value, b->block);
  2598. }
  2599. b->scope = p->curr_scope;
  2600. b->scope_index = p->scope_index;
  2601. b->preds.allocator = heap_allocator();
  2602. b->succs.allocator = heap_allocator();
  2603. array_add(&p->blocks, b);
  2604. return b;
  2605. }
  2606. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2607. if (p->curr_block == nullptr) {
  2608. return;
  2609. }
  2610. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2611. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2612. return;
  2613. }
  2614. lb_add_edge(p->curr_block, target_block);
  2615. LLVMBuildBr(p->builder, target_block->block);
  2616. p->curr_block = nullptr;
  2617. }
  2618. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2619. lbBlock *b = p->curr_block;
  2620. if (b == nullptr) {
  2621. return;
  2622. }
  2623. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2624. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2625. return;
  2626. }
  2627. lb_add_edge(b, true_block);
  2628. lb_add_edge(b, false_block);
  2629. LLVMValueRef cv = cond.value;
  2630. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2631. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2632. }
  2633. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2634. GB_ASSERT(cond != nullptr);
  2635. GB_ASSERT(true_block != nullptr);
  2636. GB_ASSERT(false_block != nullptr);
  2637. switch (cond->kind) {
  2638. case_ast_node(pe, ParenExpr, cond);
  2639. return lb_build_cond(p, pe->expr, true_block, false_block);
  2640. case_end;
  2641. case_ast_node(ue, UnaryExpr, cond);
  2642. if (ue->op.kind == Token_Not) {
  2643. return lb_build_cond(p, ue->expr, false_block, true_block);
  2644. }
  2645. case_end;
  2646. case_ast_node(be, BinaryExpr, cond);
  2647. if (be->op.kind == Token_CmpAnd) {
  2648. lbBlock *block = lb_create_block(p, "cmp.and");
  2649. lb_build_cond(p, be->left, block, false_block);
  2650. lb_start_block(p, block);
  2651. return lb_build_cond(p, be->right, true_block, false_block);
  2652. } else if (be->op.kind == Token_CmpOr) {
  2653. lbBlock *block = lb_create_block(p, "cmp.or");
  2654. lb_build_cond(p, be->left, true_block, block);
  2655. lb_start_block(p, block);
  2656. return lb_build_cond(p, be->right, true_block, false_block);
  2657. }
  2658. case_end;
  2659. }
  2660. lbValue v = lb_build_expr(p, cond);
  2661. // v = lb_emit_conv(p, v, t_bool);
  2662. v = lb_emit_conv(p, v, t_llvm_bool);
  2663. lb_emit_if(p, v, true_block, false_block);
  2664. return v;
  2665. }
  2666. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2667. GB_ASSERT(p->decl_block != p->curr_block);
  2668. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2669. char const *name = "";
  2670. if (e != nullptr) {
  2671. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2672. }
  2673. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2674. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2675. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2676. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2677. LLVMSetAlignment(ptr, alignment);
  2678. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2679. if (zero_init) {
  2680. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2681. switch (kind) {
  2682. case LLVMStructTypeKind:
  2683. case LLVMArrayTypeKind:
  2684. {
  2685. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2686. LLVMTypeRef type_i8 = LLVMInt8TypeInContext(p->module->ctx);
  2687. LLVMTypeRef type_i32 = LLVMInt32TypeInContext(p->module->ctx);
  2688. i32 sz = cast(i32)type_size_of(type);
  2689. LLVMBuildMemSet(p->builder, ptr, LLVMConstNull(type_i8), LLVMConstInt(type_i32, sz, false), alignment);
  2690. }
  2691. break;
  2692. default:
  2693. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2694. break;
  2695. }
  2696. }
  2697. lbValue val = {};
  2698. val.value = ptr;
  2699. val.type = alloc_type_pointer(type);
  2700. if (e != nullptr) {
  2701. lb_add_entity(p->module, e, val);
  2702. lb_add_debug_local_variable(p, ptr, type, e->token);
  2703. }
  2704. return lb_addr(val);
  2705. }
  2706. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2707. return lb_add_local(p, type, nullptr, zero_init);
  2708. }
  2709. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2710. GB_ASSERT(pd->body != nullptr);
  2711. lbModule *m = p->module;
  2712. auto *min_dep_set = &m->info->minimum_dependency_set;
  2713. if (ptr_set_exists(min_dep_set, e) == false) {
  2714. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2715. return;
  2716. }
  2717. // NOTE(bill): Generate a new name
  2718. // parent.name-guid
  2719. String original_name = e->token.string;
  2720. String pd_name = original_name;
  2721. if (e->Procedure.link_name.len > 0) {
  2722. pd_name = e->Procedure.link_name;
  2723. }
  2724. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2725. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2726. i32 guid = cast(i32)p->children.count;
  2727. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2728. String name = make_string(cast(u8 *)name_text, name_len-1);
  2729. set_procedure_abi_types(e->type);
  2730. e->Procedure.link_name = name;
  2731. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2732. e->code_gen_procedure = nested_proc;
  2733. lbValue value = {};
  2734. value.value = nested_proc->value;
  2735. value.type = nested_proc->type;
  2736. lb_add_entity(m, e, value);
  2737. array_add(&p->children, nested_proc);
  2738. array_add(&m->procedures_to_generate, nested_proc);
  2739. }
  2740. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2741. if (e == nullptr) {
  2742. return;
  2743. }
  2744. GB_ASSERT(e->kind == Entity_LibraryName);
  2745. GB_ASSERT(e->flags & EntityFlag_Used);
  2746. for_array(i, e->LibraryName.paths) {
  2747. String library_path = e->LibraryName.paths[i];
  2748. if (library_path.len == 0) {
  2749. continue;
  2750. }
  2751. bool ok = true;
  2752. for_array(path_index, m->foreign_library_paths) {
  2753. String path = m->foreign_library_paths[path_index];
  2754. #if defined(GB_SYSTEM_WINDOWS)
  2755. if (str_eq_ignore_case(path, library_path)) {
  2756. #else
  2757. if (str_eq(path, library_path)) {
  2758. #endif
  2759. ok = false;
  2760. break;
  2761. }
  2762. }
  2763. if (ok) {
  2764. array_add(&m->foreign_library_paths, library_path);
  2765. }
  2766. }
  2767. }
  2768. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2769. if (vd == nullptr || vd->is_mutable) {
  2770. return;
  2771. }
  2772. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2773. static i32 global_guid = 0;
  2774. for_array(i, vd->names) {
  2775. Ast *ident = vd->names[i];
  2776. GB_ASSERT(ident->kind == Ast_Ident);
  2777. Entity *e = entity_of_node(ident);
  2778. GB_ASSERT(e != nullptr);
  2779. if (e->kind != Entity_TypeName) {
  2780. continue;
  2781. }
  2782. bool polymorphic_struct = false;
  2783. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2784. Type *bt = base_type(e->type);
  2785. if (bt->kind == Type_Struct) {
  2786. polymorphic_struct = bt->Struct.is_polymorphic;
  2787. }
  2788. }
  2789. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2790. continue;
  2791. }
  2792. if (e->TypeName.ir_mangled_name.len != 0) {
  2793. // NOTE(bill): Already set
  2794. continue;
  2795. }
  2796. lb_set_nested_type_name_ir_mangled_name(e, p);
  2797. }
  2798. for_array(i, vd->names) {
  2799. Ast *ident = vd->names[i];
  2800. GB_ASSERT(ident->kind == Ast_Ident);
  2801. Entity *e = entity_of_node(ident);
  2802. GB_ASSERT(e != nullptr);
  2803. if (e->kind != Entity_Procedure) {
  2804. continue;
  2805. }
  2806. CheckerInfo *info = p->module->info;
  2807. DeclInfo *decl = decl_info_of_entity(e);
  2808. ast_node(pl, ProcLit, decl->proc_lit);
  2809. if (pl->body != nullptr) {
  2810. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2811. if (found) {
  2812. auto procs = *found;
  2813. for_array(i, procs) {
  2814. Entity *e = procs[i];
  2815. if (!ptr_set_exists(min_dep_set, e)) {
  2816. continue;
  2817. }
  2818. DeclInfo *d = decl_info_of_entity(e);
  2819. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2820. }
  2821. } else {
  2822. lb_build_nested_proc(p, pl, e);
  2823. }
  2824. } else {
  2825. // FFI - Foreign function interace
  2826. String original_name = e->token.string;
  2827. String name = original_name;
  2828. if (e->Procedure.is_foreign) {
  2829. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2830. }
  2831. if (e->Procedure.link_name.len > 0) {
  2832. name = e->Procedure.link_name;
  2833. }
  2834. lbValue *prev_value = string_map_get(&p->module->members, name);
  2835. if (prev_value != nullptr) {
  2836. // NOTE(bill): Don't do mutliple declarations in the IR
  2837. return;
  2838. }
  2839. set_procedure_abi_types(e->type);
  2840. e->Procedure.link_name = name;
  2841. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2842. lbValue value = {};
  2843. value.value = nested_proc->value;
  2844. value.type = nested_proc->type;
  2845. array_add(&p->module->procedures_to_generate, nested_proc);
  2846. if (p != nullptr) {
  2847. array_add(&p->children, nested_proc);
  2848. } else {
  2849. string_map_set(&p->module->members, name, value);
  2850. }
  2851. }
  2852. }
  2853. }
  2854. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  2855. for_array(i, stmts) {
  2856. Ast *stmt = stmts[i];
  2857. switch (stmt->kind) {
  2858. case_ast_node(vd, ValueDecl, stmt);
  2859. lb_build_constant_value_decl(p, vd);
  2860. case_end;
  2861. case_ast_node(fb, ForeignBlockDecl, stmt);
  2862. ast_node(block, BlockStmt, fb->body);
  2863. lb_build_stmt_list(p, block->stmts);
  2864. case_end;
  2865. }
  2866. }
  2867. for_array(i, stmts) {
  2868. lb_build_stmt(p, stmts[i]);
  2869. }
  2870. }
  2871. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2872. GB_ASSERT(ident->kind == Ast_Ident);
  2873. Entity *e = entity_of_node(ident);
  2874. GB_ASSERT(e->kind == Entity_Label);
  2875. for_array(i, p->branch_blocks) {
  2876. lbBranchBlocks *b = &p->branch_blocks[i];
  2877. if (b->label == e->Label.node) {
  2878. return *b;
  2879. }
  2880. }
  2881. GB_PANIC("Unreachable");
  2882. lbBranchBlocks empty = {};
  2883. return empty;
  2884. }
  2885. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2886. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  2887. tl->prev = p->target_list;
  2888. tl->break_ = break_;
  2889. tl->continue_ = continue_;
  2890. tl->fallthrough_ = fallthrough_;
  2891. p->target_list = tl;
  2892. if (label != nullptr) { // Set label blocks
  2893. GB_ASSERT(label->kind == Ast_Label);
  2894. for_array(i, p->branch_blocks) {
  2895. lbBranchBlocks *b = &p->branch_blocks[i];
  2896. GB_ASSERT(b->label != nullptr && label != nullptr);
  2897. GB_ASSERT(b->label->kind == Ast_Label);
  2898. if (b->label == label) {
  2899. b->break_ = break_;
  2900. b->continue_ = continue_;
  2901. return tl;
  2902. }
  2903. }
  2904. GB_PANIC("Unreachable");
  2905. }
  2906. return tl;
  2907. }
  2908. void lb_pop_target_list(lbProcedure *p) {
  2909. p->target_list = p->target_list->prev;
  2910. }
  2911. void lb_open_scope(lbProcedure *p, Scope *s) {
  2912. lbModule *m = p->module;
  2913. if (m->debug_builder) {
  2914. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  2915. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  2916. Token token = ast_token(s->node);
  2917. unsigned line = cast(unsigned)token.pos.line;
  2918. unsigned column = cast(unsigned)token.pos.column;
  2919. LLVMMetadataRef file = nullptr;
  2920. if (s->node->file != nullptr) {
  2921. file = lb_get_llvm_metadata(m, s->node->file);
  2922. }
  2923. LLVMMetadataRef scope = nullptr;
  2924. if (p->scope_stack.count > 0) {
  2925. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  2926. }
  2927. if (scope == nullptr) {
  2928. scope = lb_get_llvm_metadata(m, p);
  2929. }
  2930. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  2931. if (m->debug_builder) {
  2932. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  2933. file, line, column
  2934. );
  2935. lb_set_llvm_metadata(m, s, res);
  2936. }
  2937. }
  2938. }
  2939. p->scope_index += 1;
  2940. array_add(&p->scope_stack, s);
  2941. }
  2942. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  2943. lb_emit_defer_stmts(p, kind, block);
  2944. GB_ASSERT(p->scope_index > 0);
  2945. // NOTE(bill): Remove `context`s made in that scope
  2946. while (p->context_stack.count > 0) {
  2947. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  2948. if (ctx->scope_index >= p->scope_index) {
  2949. array_pop(&p->context_stack);
  2950. } else {
  2951. break;
  2952. }
  2953. }
  2954. p->scope_index -= 1;
  2955. array_pop(&p->scope_stack);
  2956. }
  2957. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  2958. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  2959. GB_ASSERT(is_type_boolean(tv.type));
  2960. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  2961. if (tv.value.value_bool) {
  2962. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  2963. } else if (ws->else_stmt) {
  2964. switch (ws->else_stmt->kind) {
  2965. case Ast_BlockStmt:
  2966. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  2967. break;
  2968. case Ast_WhenStmt:
  2969. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  2970. break;
  2971. default:
  2972. GB_PANIC("Invalid 'else' statement in 'when' statement");
  2973. break;
  2974. }
  2975. }
  2976. }
  2977. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  2978. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2979. lbModule *m = p->module;
  2980. lbValue count = {};
  2981. Type *expr_type = base_type(type_deref(expr.type));
  2982. switch (expr_type->kind) {
  2983. case Type_Array:
  2984. count = lb_const_int(m, t_int, expr_type->Array.count);
  2985. break;
  2986. }
  2987. lbValue val = {};
  2988. lbValue idx = {};
  2989. lbBlock *loop = nullptr;
  2990. lbBlock *done = nullptr;
  2991. lbBlock *body = nullptr;
  2992. lbAddr index = lb_add_local_generated(p, t_int, false);
  2993. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  2994. loop = lb_create_block(p, "for.index.loop");
  2995. lb_emit_jump(p, loop);
  2996. lb_start_block(p, loop);
  2997. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  2998. lb_addr_store(p, index, incr);
  2999. body = lb_create_block(p, "for.index.body");
  3000. done = lb_create_block(p, "for.index.done");
  3001. if (count.value == nullptr) {
  3002. GB_ASSERT(count_ptr.value != nullptr);
  3003. count = lb_emit_load(p, count_ptr);
  3004. }
  3005. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3006. lb_emit_if(p, cond, body, done);
  3007. lb_start_block(p, body);
  3008. idx = lb_addr_load(p, index);
  3009. switch (expr_type->kind) {
  3010. case Type_Array: {
  3011. if (val_type != nullptr) {
  3012. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3013. }
  3014. break;
  3015. }
  3016. case Type_EnumeratedArray: {
  3017. if (val_type != nullptr) {
  3018. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3019. // NOTE(bill): Override the idx value for the enumeration
  3020. Type *index_type = expr_type->EnumeratedArray.index;
  3021. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3022. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3023. }
  3024. }
  3025. break;
  3026. }
  3027. case Type_Slice: {
  3028. if (val_type != nullptr) {
  3029. lbValue elem = lb_slice_elem(p, expr);
  3030. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3031. }
  3032. break;
  3033. }
  3034. case Type_DynamicArray: {
  3035. if (val_type != nullptr) {
  3036. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3037. elem = lb_emit_load(p, elem);
  3038. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3039. }
  3040. break;
  3041. }
  3042. case Type_Map: {
  3043. lbValue entries = lb_map_entries_ptr(p, expr);
  3044. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3045. elem = lb_emit_load(p, elem);
  3046. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3047. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3048. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3049. break;
  3050. }
  3051. default:
  3052. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3053. break;
  3054. }
  3055. if (val_) *val_ = val;
  3056. if (idx_) *idx_ = idx;
  3057. if (loop_) *loop_ = loop;
  3058. if (done_) *done_ = done;
  3059. }
  3060. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3061. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3062. lbModule *m = p->module;
  3063. lbValue count = lb_const_int(m, t_int, 0);
  3064. Type *expr_type = base_type(expr.type);
  3065. switch (expr_type->kind) {
  3066. case Type_Basic:
  3067. count = lb_string_len(p, expr);
  3068. break;
  3069. default:
  3070. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3071. break;
  3072. }
  3073. lbValue val = {};
  3074. lbValue idx = {};
  3075. lbBlock *loop = nullptr;
  3076. lbBlock *done = nullptr;
  3077. lbBlock *body = nullptr;
  3078. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3079. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3080. loop = lb_create_block(p, "for.string.loop");
  3081. lb_emit_jump(p, loop);
  3082. lb_start_block(p, loop);
  3083. body = lb_create_block(p, "for.string.body");
  3084. done = lb_create_block(p, "for.string.done");
  3085. lbValue offset = lb_addr_load(p, offset_);
  3086. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3087. lb_emit_if(p, cond, body, done);
  3088. lb_start_block(p, body);
  3089. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3090. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3091. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3092. args[0] = lb_emit_string(p, str_elem, str_len);
  3093. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3094. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3095. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3096. idx = offset;
  3097. if (val_type != nullptr) {
  3098. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3099. }
  3100. if (val_) *val_ = val;
  3101. if (idx_) *idx_ = idx;
  3102. if (loop_) *loop_ = loop;
  3103. if (done_) *done_ = done;
  3104. }
  3105. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  3106. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3107. lbModule *m = p->module;
  3108. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  3109. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  3110. lbValue lower = lb_build_expr(p, node->left);
  3111. lbValue upper = {};
  3112. lbValue val = {};
  3113. lbValue idx = {};
  3114. lbBlock *loop = nullptr;
  3115. lbBlock *done = nullptr;
  3116. lbBlock *body = nullptr;
  3117. if (val_type == nullptr) {
  3118. val_type = lower.type;
  3119. }
  3120. lbAddr value = lb_add_local_generated(p, val_type, false);
  3121. lb_addr_store(p, value, lower);
  3122. lbAddr index = lb_add_local_generated(p, t_int, false);
  3123. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3124. loop = lb_create_block(p, "for.interval.loop");
  3125. lb_emit_jump(p, loop);
  3126. lb_start_block(p, loop);
  3127. body = lb_create_block(p, "for.interval.body");
  3128. done = lb_create_block(p, "for.interval.done");
  3129. TokenKind op = Token_Lt;
  3130. switch (node->op.kind) {
  3131. case Token_Ellipsis: op = Token_LtEq; break;
  3132. case Token_RangeHalf: op = Token_Lt; break;
  3133. default: GB_PANIC("Invalid interval operator"); break;
  3134. }
  3135. upper = lb_build_expr(p, node->right);
  3136. lbValue curr_value = lb_addr_load(p, value);
  3137. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3138. lb_emit_if(p, cond, body, done);
  3139. lb_start_block(p, body);
  3140. val = lb_addr_load(p, value);
  3141. idx = lb_addr_load(p, index);
  3142. lb_emit_increment(p, value.addr);
  3143. lb_emit_increment(p, index.addr);
  3144. if (val_) *val_ = val;
  3145. if (idx_) *idx_ = idx;
  3146. if (loop_) *loop_ = loop;
  3147. if (done_) *done_ = done;
  3148. }
  3149. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3150. lbModule *m = p->module;
  3151. Type *t = enum_type;
  3152. GB_ASSERT(is_type_enum(t));
  3153. Type *enum_ptr = alloc_type_pointer(t);
  3154. t = base_type(t);
  3155. Type *core_elem = core_type(t);
  3156. GB_ASSERT(t->kind == Type_Enum);
  3157. i64 enum_count = t->Enum.fields.count;
  3158. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3159. lbValue ti = lb_type_info(m, t);
  3160. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3161. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3162. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3163. lbValue values_data = lb_slice_elem(p, values);
  3164. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3165. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3166. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3167. lb_emit_jump(p, loop);
  3168. lb_start_block(p, loop);
  3169. lbBlock *body = lb_create_block(p, "for.enum.body");
  3170. lbBlock *done = lb_create_block(p, "for.enum.done");
  3171. lbValue offset = lb_addr_load(p, offset_);
  3172. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3173. lb_emit_if(p, cond, body, done);
  3174. lb_start_block(p, body);
  3175. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3176. lb_emit_increment(p, offset_.addr);
  3177. lbValue val = {};
  3178. if (val_type != nullptr) {
  3179. GB_ASSERT(are_types_identical(enum_type, val_type));
  3180. if (is_type_integer(core_elem)) {
  3181. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3182. val = lb_emit_conv(p, i, t);
  3183. } else {
  3184. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3185. }
  3186. }
  3187. if (val_) *val_ = val;
  3188. if (idx_) *idx_ = offset;
  3189. if (loop_) *loop_ = loop;
  3190. if (done_) *done_ = done;
  3191. }
  3192. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3193. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3194. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3195. lb_emit_jump(p, loop);
  3196. lb_start_block(p, loop);
  3197. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3198. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3199. lbValue tuple_value = lb_build_expr(p, expr);
  3200. Type *tuple = tuple_value.type;
  3201. GB_ASSERT(tuple->kind == Type_Tuple);
  3202. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3203. i32 cond_index = tuple_count-1;
  3204. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3205. lb_emit_if(p, cond, body, done);
  3206. lb_start_block(p, body);
  3207. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3208. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3209. if (loop_) *loop_ = loop;
  3210. if (done_) *done_ = done;
  3211. }
  3212. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3213. lb_open_scope(p, scope);
  3214. Type *val0_type = nullptr;
  3215. Type *val1_type = nullptr;
  3216. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3217. val0_type = type_of_expr(rs->val0);
  3218. }
  3219. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3220. val1_type = type_of_expr(rs->val1);
  3221. }
  3222. if (val0_type != nullptr) {
  3223. Entity *e = entity_of_node(rs->val0);
  3224. lb_add_local(p, e->type, e, true);
  3225. }
  3226. if (val1_type != nullptr) {
  3227. Entity *e = entity_of_node(rs->val1);
  3228. lb_add_local(p, e->type, e, true);
  3229. }
  3230. lbValue val = {};
  3231. lbValue key = {};
  3232. lbBlock *loop = nullptr;
  3233. lbBlock *done = nullptr;
  3234. Ast *expr = unparen_expr(rs->expr);
  3235. bool is_map = false;
  3236. TypeAndValue tav = type_and_value_of_expr(expr);
  3237. if (is_ast_range(expr)) {
  3238. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  3239. } else if (tav.mode == Addressing_Type) {
  3240. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3241. } else {
  3242. Type *expr_type = type_of_expr(expr);
  3243. Type *et = base_type(type_deref(expr_type));
  3244. switch (et->kind) {
  3245. case Type_Map: {
  3246. is_map = true;
  3247. lbValue map = lb_build_addr_ptr(p, expr);
  3248. if (is_type_pointer(type_deref(map.type))) {
  3249. map = lb_emit_load(p, map);
  3250. }
  3251. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3252. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3253. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3254. break;
  3255. }
  3256. case Type_Array: {
  3257. lbValue array = lb_build_addr_ptr(p, expr);
  3258. if (is_type_pointer(type_deref(array.type))) {
  3259. array = lb_emit_load(p, array);
  3260. }
  3261. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3262. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3263. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3264. break;
  3265. }
  3266. case Type_EnumeratedArray: {
  3267. lbValue array = lb_build_addr_ptr(p, expr);
  3268. if (is_type_pointer(type_deref(array.type))) {
  3269. array = lb_emit_load(p, array);
  3270. }
  3271. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3272. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3273. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3274. break;
  3275. }
  3276. case Type_DynamicArray: {
  3277. lbValue count_ptr = {};
  3278. lbValue array = lb_build_addr_ptr(p, expr);
  3279. if (is_type_pointer(type_deref(array.type))) {
  3280. array = lb_emit_load(p, array);
  3281. }
  3282. count_ptr = lb_emit_struct_ep(p, array, 1);
  3283. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3284. break;
  3285. }
  3286. case Type_Slice: {
  3287. lbValue count_ptr = {};
  3288. lbValue slice = lb_build_expr(p, expr);
  3289. if (is_type_pointer(slice.type)) {
  3290. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3291. slice = lb_emit_load(p, slice);
  3292. } else {
  3293. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3294. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3295. }
  3296. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3297. break;
  3298. }
  3299. case Type_Basic: {
  3300. lbValue string = lb_build_expr(p, expr);
  3301. if (is_type_pointer(string.type)) {
  3302. string = lb_emit_load(p, string);
  3303. }
  3304. if (is_type_untyped(expr_type)) {
  3305. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3306. lb_addr_store(p, s, string);
  3307. string = lb_addr_load(p, s);
  3308. }
  3309. Type *t = base_type(string.type);
  3310. GB_ASSERT(!is_type_cstring(t));
  3311. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3312. break;
  3313. }
  3314. case Type_Tuple:
  3315. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3316. break;
  3317. default:
  3318. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3319. break;
  3320. }
  3321. }
  3322. if (is_map) {
  3323. if (val0_type) lb_store_range_stmt_val(p, rs->val0, key);
  3324. if (val1_type) lb_store_range_stmt_val(p, rs->val1, val);
  3325. } else {
  3326. if (val0_type) lb_store_range_stmt_val(p, rs->val0, val);
  3327. if (val1_type) lb_store_range_stmt_val(p, rs->val1, key);
  3328. }
  3329. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3330. lb_build_stmt(p, rs->body);
  3331. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3332. lb_pop_target_list(p);
  3333. lb_emit_jump(p, loop);
  3334. lb_start_block(p, done);
  3335. }
  3336. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs, Scope *scope) {
  3337. lbModule *m = p->module;
  3338. lb_open_scope(p, scope); // Open scope here
  3339. Type *val0_type = nullptr;
  3340. Type *val1_type = nullptr;
  3341. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3342. val0_type = type_of_expr(rs->val0);
  3343. }
  3344. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3345. val1_type = type_of_expr(rs->val1);
  3346. }
  3347. if (val0_type != nullptr) {
  3348. Entity *e = entity_of_node(rs->val0);
  3349. lb_add_local(p, e->type, e, true);
  3350. }
  3351. if (val1_type != nullptr) {
  3352. Entity *e = entity_of_node(rs->val1);
  3353. lb_add_local(p, e->type, e, true);
  3354. }
  3355. lbValue val = {};
  3356. lbValue key = {};
  3357. lbBlock *loop = nullptr;
  3358. lbBlock *done = nullptr;
  3359. Ast *expr = unparen_expr(rs->expr);
  3360. TypeAndValue tav = type_and_value_of_expr(expr);
  3361. if (is_ast_range(expr)) {
  3362. lbAddr val0_addr = {};
  3363. lbAddr val1_addr = {};
  3364. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3365. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3366. TokenKind op = expr->BinaryExpr.op.kind;
  3367. Ast *start_expr = expr->BinaryExpr.left;
  3368. Ast *end_expr = expr->BinaryExpr.right;
  3369. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3370. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3371. ExactValue start = start_expr->tav.value;
  3372. ExactValue end = end_expr->tav.value;
  3373. if (op == Token_Ellipsis) { // .. [start, end]
  3374. ExactValue index = exact_value_i64(0);
  3375. for (ExactValue val = start;
  3376. compare_exact_values(Token_LtEq, val, end);
  3377. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3378. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3379. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3380. lb_build_stmt(p, rs->body);
  3381. }
  3382. } else if (op == Token_RangeHalf) { // ..< [start, end)
  3383. ExactValue index = exact_value_i64(0);
  3384. for (ExactValue val = start;
  3385. compare_exact_values(Token_Lt, val, end);
  3386. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3387. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3388. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3389. lb_build_stmt(p, rs->body);
  3390. }
  3391. }
  3392. } else if (tav.mode == Addressing_Type) {
  3393. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3394. Type *et = type_deref(tav.type);
  3395. Type *bet = base_type(et);
  3396. lbAddr val0_addr = {};
  3397. lbAddr val1_addr = {};
  3398. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3399. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3400. for_array(i, bet->Enum.fields) {
  3401. Entity *field = bet->Enum.fields[i];
  3402. GB_ASSERT(field->kind == Entity_Constant);
  3403. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3404. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3405. lb_build_stmt(p, rs->body);
  3406. }
  3407. } else {
  3408. lbAddr val0_addr = {};
  3409. lbAddr val1_addr = {};
  3410. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3411. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3412. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3413. Type *t = base_type(expr->tav.type);
  3414. switch (t->kind) {
  3415. case Type_Basic:
  3416. GB_ASSERT(is_type_string(t));
  3417. {
  3418. ExactValue value = expr->tav.value;
  3419. GB_ASSERT(value.kind == ExactValue_String);
  3420. String str = value.value_string;
  3421. Rune codepoint = 0;
  3422. isize offset = 0;
  3423. do {
  3424. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3425. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3426. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3427. lb_build_stmt(p, rs->body);
  3428. offset += width;
  3429. } while (offset < str.len);
  3430. }
  3431. break;
  3432. case Type_Array:
  3433. if (t->Array.count > 0) {
  3434. lbValue val = lb_build_expr(p, expr);
  3435. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3436. for (i64 i = 0; i < t->Array.count; i++) {
  3437. if (val0_type) {
  3438. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3439. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3440. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3441. }
  3442. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3443. lb_build_stmt(p, rs->body);
  3444. }
  3445. }
  3446. break;
  3447. case Type_EnumeratedArray:
  3448. if (t->EnumeratedArray.count > 0) {
  3449. lbValue val = lb_build_expr(p, expr);
  3450. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3451. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3452. if (val0_type) {
  3453. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3454. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3455. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3456. }
  3457. if (val1_type) {
  3458. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3459. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3460. }
  3461. lb_build_stmt(p, rs->body);
  3462. }
  3463. }
  3464. break;
  3465. default:
  3466. GB_PANIC("Invalid '#unroll for' type");
  3467. break;
  3468. }
  3469. }
  3470. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3471. }
  3472. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  3473. lb_open_scope(p, scope);
  3474. if (ss->init != nullptr) {
  3475. lb_build_stmt(p, ss->init);
  3476. }
  3477. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3478. if (ss->tag != nullptr) {
  3479. tag = lb_build_expr(p, ss->tag);
  3480. }
  3481. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3482. ast_node(body, BlockStmt, ss->body);
  3483. Slice<Ast *> default_stmts = {};
  3484. lbBlock *default_fall = nullptr;
  3485. lbBlock *default_block = nullptr;
  3486. lbBlock *fall = nullptr;
  3487. isize case_count = body->stmts.count;
  3488. for_array(i, body->stmts) {
  3489. Ast *clause = body->stmts[i];
  3490. ast_node(cc, CaseClause, clause);
  3491. lbBlock *body = fall;
  3492. if (body == nullptr) {
  3493. body = lb_create_block(p, "switch.case.body");
  3494. }
  3495. fall = done;
  3496. if (i+1 < case_count) {
  3497. fall = lb_create_block(p, "switch.fall.body");
  3498. }
  3499. if (cc->list.count == 0) {
  3500. // default case
  3501. default_stmts = cc->stmts;
  3502. default_fall = fall;
  3503. default_block = body;
  3504. continue;
  3505. }
  3506. lbBlock *next_cond = nullptr;
  3507. for_array(j, cc->list) {
  3508. Ast *expr = unparen_expr(cc->list[j]);
  3509. next_cond = lb_create_block(p, "switch.case.next");
  3510. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3511. if (is_ast_range(expr)) {
  3512. ast_node(ie, BinaryExpr, expr);
  3513. TokenKind op = Token_Invalid;
  3514. switch (ie->op.kind) {
  3515. case Token_Ellipsis: op = Token_LtEq; break;
  3516. case Token_RangeHalf: op = Token_Lt; break;
  3517. default: GB_PANIC("Invalid interval operator"); break;
  3518. }
  3519. lbValue lhs = lb_build_expr(p, ie->left);
  3520. lbValue rhs = lb_build_expr(p, ie->right);
  3521. // TODO(bill): do short circuit here
  3522. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3523. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3524. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3525. } else {
  3526. if (expr->tav.mode == Addressing_Type) {
  3527. GB_ASSERT(is_type_typeid(tag.type));
  3528. lbValue e = lb_typeid(p->module, expr->tav.type);
  3529. e = lb_emit_conv(p, e, tag.type);
  3530. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3531. } else {
  3532. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3533. }
  3534. }
  3535. lb_emit_if(p, cond, body, next_cond);
  3536. lb_start_block(p, next_cond);
  3537. }
  3538. lb_start_block(p, body);
  3539. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3540. lb_open_scope(p, body->scope);
  3541. lb_build_stmt_list(p, cc->stmts);
  3542. lb_close_scope(p, lbDeferExit_Default, body);
  3543. lb_pop_target_list(p);
  3544. lb_emit_jump(p, done);
  3545. lb_start_block(p, next_cond);
  3546. }
  3547. if (default_block != nullptr) {
  3548. lb_emit_jump(p, default_block);
  3549. lb_start_block(p, default_block);
  3550. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3551. lb_open_scope(p, default_block->scope);
  3552. lb_build_stmt_list(p, default_stmts);
  3553. lb_close_scope(p, lbDeferExit_Default, default_block);
  3554. lb_pop_target_list(p);
  3555. }
  3556. lb_emit_jump(p, done);
  3557. lb_close_scope(p, lbDeferExit_Default, done);
  3558. lb_start_block(p, done);
  3559. }
  3560. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3561. Entity *e = implicit_entity_of_node(clause);
  3562. GB_ASSERT(e != nullptr);
  3563. if (e->flags & EntityFlag_Value) {
  3564. // by value
  3565. GB_ASSERT(are_types_identical(e->type, value.type));
  3566. lbAddr x = lb_add_local(p, e->type, e, false);
  3567. lb_addr_store(p, x, value);
  3568. } else {
  3569. // by reference
  3570. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3571. lb_add_entity(p->module, e, value);
  3572. }
  3573. }
  3574. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3575. Entity *e = entity_of_node(stmt_val);
  3576. if (e == nullptr) {
  3577. return {};
  3578. }
  3579. if ((e->flags & EntityFlag_Value) == 0) {
  3580. if (LLVMIsALoadInst(value.value)) {
  3581. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3582. lb_add_entity(p->module, e, ptr);
  3583. return lb_addr(ptr);
  3584. }
  3585. }
  3586. // by value
  3587. lbAddr addr = lb_add_local(p, e->type, e, false);
  3588. lb_addr_store(p, addr, value);
  3589. return addr;
  3590. }
  3591. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3592. ast_node(cc, CaseClause, clause);
  3593. lb_push_target_list(p, label, done, nullptr, nullptr);
  3594. lb_open_scope(p, body->scope);
  3595. lb_build_stmt_list(p, cc->stmts);
  3596. lb_close_scope(p, lbDeferExit_Default, body);
  3597. lb_pop_target_list(p);
  3598. lb_emit_jump(p, done);
  3599. }
  3600. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3601. lbModule *m = p->module;
  3602. ast_node(as, AssignStmt, ss->tag);
  3603. GB_ASSERT(as->lhs.count == 1);
  3604. GB_ASSERT(as->rhs.count == 1);
  3605. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3606. bool is_parent_ptr = is_type_pointer(parent.type);
  3607. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3608. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3609. lbValue parent_value = parent;
  3610. lbValue parent_ptr = parent;
  3611. if (!is_parent_ptr) {
  3612. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3613. }
  3614. lbValue tag_index = {};
  3615. lbValue union_data = {};
  3616. if (switch_kind == TypeSwitch_Union) {
  3617. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3618. tag_index = lb_emit_load(p, tag_ptr);
  3619. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3620. }
  3621. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3622. lb_emit_jump(p, start_block);
  3623. lb_start_block(p, start_block);
  3624. // NOTE(bill): Append this later
  3625. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3626. Ast *default_ = nullptr;
  3627. ast_node(body, BlockStmt, ss->body);
  3628. gb_local_persist i32 weird_count = 0;
  3629. for_array(i, body->stmts) {
  3630. Ast *clause = body->stmts[i];
  3631. ast_node(cc, CaseClause, clause);
  3632. if (cc->list.count == 0) {
  3633. default_ = clause;
  3634. continue;
  3635. }
  3636. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3637. lbBlock *next = nullptr;
  3638. Type *case_type = nullptr;
  3639. for_array(type_index, cc->list) {
  3640. next = lb_create_block(p, "typeswitch.next");
  3641. case_type = type_of_expr(cc->list[type_index]);
  3642. lbValue cond = {};
  3643. if (switch_kind == TypeSwitch_Union) {
  3644. Type *ut = base_type(type_deref(parent.type));
  3645. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3646. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3647. } else if (switch_kind == TypeSwitch_Any) {
  3648. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3649. lbValue case_typeid = lb_typeid(m, case_type);
  3650. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3651. }
  3652. GB_ASSERT(cond.value != nullptr);
  3653. lb_emit_if(p, cond, body, next);
  3654. lb_start_block(p, next);
  3655. }
  3656. Entity *case_entity = implicit_entity_of_node(clause);
  3657. lbValue value = parent_value;
  3658. lb_start_block(p, body);
  3659. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3660. if (cc->list.count == 1) {
  3661. lbValue data = {};
  3662. if (switch_kind == TypeSwitch_Union) {
  3663. data = union_data;
  3664. } else if (switch_kind == TypeSwitch_Any) {
  3665. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3666. data = any_data;
  3667. }
  3668. Type *ct = case_entity->type;
  3669. Type *ct_ptr = alloc_type_pointer(ct);
  3670. value = lb_emit_conv(p, data, ct_ptr);
  3671. if (!by_reference) {
  3672. value = lb_emit_load(p, value);
  3673. }
  3674. }
  3675. lb_store_type_case_implicit(p, clause, value);
  3676. lb_type_case_body(p, ss->label, clause, body, done);
  3677. lb_start_block(p, next);
  3678. }
  3679. if (default_ != nullptr) {
  3680. lb_store_type_case_implicit(p, default_, parent_value);
  3681. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3682. } else {
  3683. lb_emit_jump(p, done);
  3684. }
  3685. lb_start_block(p, done);
  3686. }
  3687. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3688. lbModule *m = p->module;
  3689. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3690. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3691. type = default_type(type);
  3692. lbValue short_circuit = {};
  3693. if (op == Token_CmpAnd) {
  3694. lb_build_cond(p, left, rhs, done);
  3695. short_circuit = lb_const_bool(m, type, false);
  3696. } else if (op == Token_CmpOr) {
  3697. lb_build_cond(p, left, done, rhs);
  3698. short_circuit = lb_const_bool(m, type, true);
  3699. }
  3700. if (rhs->preds.count == 0) {
  3701. lb_start_block(p, done);
  3702. return short_circuit;
  3703. }
  3704. if (done->preds.count == 0) {
  3705. lb_start_block(p, rhs);
  3706. return lb_build_expr(p, right);
  3707. }
  3708. Array<LLVMValueRef> incoming_values = {};
  3709. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3710. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3711. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3712. for_array(i, done->preds) {
  3713. incoming_values[i] = short_circuit.value;
  3714. incoming_blocks[i] = done->preds[i]->block;
  3715. }
  3716. lb_start_block(p, rhs);
  3717. lbValue edge = lb_build_expr(p, right);
  3718. incoming_values[done->preds.count] = edge.value;
  3719. incoming_blocks[done->preds.count] = p->curr_block->block;
  3720. lb_emit_jump(p, done);
  3721. lb_start_block(p, done);
  3722. lbValue res = {};
  3723. res.type = type;
  3724. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3725. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3726. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3727. return res;
  3728. }
  3729. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3730. Ast *prev_stmt = p->curr_stmt;
  3731. defer (p->curr_stmt = prev_stmt);
  3732. p->curr_stmt = node;
  3733. if (p->curr_block != nullptr) {
  3734. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3735. if (lb_is_instr_terminating(last_instr)) {
  3736. return;
  3737. }
  3738. }
  3739. LLVMMetadataRef prev_debug_location = nullptr;
  3740. if (p->debug_info != nullptr) {
  3741. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  3742. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  3743. }
  3744. defer (if (prev_debug_location != nullptr) {
  3745. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  3746. });
  3747. u64 prev_state_flags = p->module->state_flags;
  3748. defer (p->module->state_flags = prev_state_flags);
  3749. if (node->state_flags != 0) {
  3750. u64 in = node->state_flags;
  3751. u64 out = p->module->state_flags;
  3752. if (in & StateFlag_bounds_check) {
  3753. out |= StateFlag_bounds_check;
  3754. out &= ~StateFlag_no_bounds_check;
  3755. } else if (in & StateFlag_no_bounds_check) {
  3756. out |= StateFlag_no_bounds_check;
  3757. out &= ~StateFlag_bounds_check;
  3758. }
  3759. p->module->state_flags = out;
  3760. }
  3761. switch (node->kind) {
  3762. case_ast_node(bs, EmptyStmt, node);
  3763. case_end;
  3764. case_ast_node(us, UsingStmt, node);
  3765. case_end;
  3766. case_ast_node(ws, WhenStmt, node);
  3767. lb_build_when_stmt(p, ws);
  3768. case_end;
  3769. case_ast_node(bs, BlockStmt, node);
  3770. lbBlock *done = nullptr;
  3771. if (bs->label != nullptr) {
  3772. done = lb_create_block(p, "block.done");
  3773. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3774. tl->is_block = true;
  3775. }
  3776. lb_open_scope(p, node->scope);
  3777. lb_build_stmt_list(p, bs->stmts);
  3778. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3779. if (done != nullptr) {
  3780. lb_emit_jump(p, done);
  3781. lb_start_block(p, done);
  3782. }
  3783. case_end;
  3784. case_ast_node(vd, ValueDecl, node);
  3785. if (!vd->is_mutable) {
  3786. return;
  3787. }
  3788. bool is_static = false;
  3789. if (vd->names.count > 0) {
  3790. Entity *e = entity_of_node(vd->names[0]);
  3791. if (e->flags & EntityFlag_Static) {
  3792. // NOTE(bill): If one of the entities is static, they all are
  3793. is_static = true;
  3794. }
  3795. }
  3796. if (is_static) {
  3797. for_array(i, vd->names) {
  3798. lbValue value = {};
  3799. if (vd->values.count > 0) {
  3800. GB_ASSERT(vd->names.count == vd->values.count);
  3801. Ast *ast_value = vd->values[i];
  3802. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3803. ast_value->tav.mode == Addressing_Invalid);
  3804. bool allow_local = false;
  3805. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3806. }
  3807. Ast *ident = vd->names[i];
  3808. GB_ASSERT(!is_blank_ident(ident));
  3809. Entity *e = entity_of_node(ident);
  3810. GB_ASSERT(e->flags & EntityFlag_Static);
  3811. String name = e->token.string;
  3812. String mangled_name = {};
  3813. {
  3814. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  3815. str = gb_string_appendc(str, "-");
  3816. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3817. mangled_name.text = cast(u8 *)str;
  3818. mangled_name.len = gb_string_length(str);
  3819. }
  3820. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  3821. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3822. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3823. if (value.value != nullptr) {
  3824. LLVMSetInitializer(global, value.value);
  3825. } else {
  3826. }
  3827. if (e->Variable.thread_local_model != "") {
  3828. LLVMSetThreadLocal(global, true);
  3829. String m = e->Variable.thread_local_model;
  3830. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3831. if (m == "default") {
  3832. mode = LLVMGeneralDynamicTLSModel;
  3833. } else if (m == "localdynamic") {
  3834. mode = LLVMLocalDynamicTLSModel;
  3835. } else if (m == "initialexec") {
  3836. mode = LLVMInitialExecTLSModel;
  3837. } else if (m == "localexec") {
  3838. mode = LLVMLocalExecTLSModel;
  3839. } else {
  3840. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3841. }
  3842. LLVMSetThreadLocalMode(global, mode);
  3843. } else {
  3844. LLVMSetLinkage(global, LLVMInternalLinkage);
  3845. }
  3846. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3847. lb_add_entity(p->module, e, global_val);
  3848. lb_add_member(p->module, mangled_name, global_val);
  3849. }
  3850. return;
  3851. }
  3852. if (vd->values.count == 0) { // declared and zero-initialized
  3853. for_array(i, vd->names) {
  3854. Ast *name = vd->names[i];
  3855. if (!is_blank_ident(name)) {
  3856. Entity *e = entity_of_node(name);
  3857. lb_add_local(p, e->type, e, true);
  3858. }
  3859. }
  3860. } else { // Tuple(s)
  3861. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  3862. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  3863. for_array(i, vd->names) {
  3864. Ast *name = vd->names[i];
  3865. lbAddr lval = {};
  3866. if (!is_blank_ident(name)) {
  3867. Entity *e = entity_of_node(name);
  3868. lval = lb_add_local(p, e->type, e, false);
  3869. }
  3870. array_add(&lvals, lval);
  3871. }
  3872. for_array(i, vd->values) {
  3873. lbValue init = lb_build_expr(p, vd->values[i]);
  3874. Type *t = init.type;
  3875. if (t->kind == Type_Tuple) {
  3876. for_array(i, t->Tuple.variables) {
  3877. Entity *e = t->Tuple.variables[i];
  3878. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3879. array_add(&inits, v);
  3880. }
  3881. } else {
  3882. array_add(&inits, init);
  3883. }
  3884. }
  3885. for_array(i, inits) {
  3886. lbAddr lval = lvals[i];
  3887. lbValue init = inits[i];
  3888. lb_addr_store(p, lval, init);
  3889. }
  3890. }
  3891. case_end;
  3892. case_ast_node(as, AssignStmt, node);
  3893. if (as->op.kind == Token_Eq) {
  3894. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  3895. for_array(i, as->lhs) {
  3896. Ast *lhs = as->lhs[i];
  3897. lbAddr lval = {};
  3898. if (!is_blank_ident(lhs)) {
  3899. lval = lb_build_addr(p, lhs);
  3900. }
  3901. array_add(&lvals, lval);
  3902. }
  3903. if (as->lhs.count == as->rhs.count) {
  3904. if (as->lhs.count == 1) {
  3905. lbAddr lval = lvals[0];
  3906. Ast *rhs = as->rhs[0];
  3907. lbValue init = lb_build_expr(p, rhs);
  3908. lb_addr_store(p, lvals[0], init);
  3909. } else {
  3910. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3911. for_array(i, as->rhs) {
  3912. lbValue init = lb_build_expr(p, as->rhs[i]);
  3913. array_add(&inits, init);
  3914. }
  3915. for_array(i, inits) {
  3916. lbAddr lval = lvals[i];
  3917. lbValue init = inits[i];
  3918. lb_addr_store(p, lval, init);
  3919. }
  3920. }
  3921. } else {
  3922. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3923. for_array(i, as->rhs) {
  3924. lbValue init = lb_build_expr(p, as->rhs[i]);
  3925. Type *t = init.type;
  3926. // TODO(bill): refactor for code reuse as this is repeated a bit
  3927. if (t->kind == Type_Tuple) {
  3928. for_array(i, t->Tuple.variables) {
  3929. Entity *e = t->Tuple.variables[i];
  3930. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3931. array_add(&inits, v);
  3932. }
  3933. } else {
  3934. array_add(&inits, init);
  3935. }
  3936. }
  3937. for_array(i, inits) {
  3938. lbAddr lval = lvals[i];
  3939. lbValue init = inits[i];
  3940. lb_addr_store(p, lval, init);
  3941. }
  3942. }
  3943. } else {
  3944. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  3945. // +=, -=, etc
  3946. i32 op = cast(i32)as->op.kind;
  3947. op += Token_Add - Token_AddEq; // Convert += to +
  3948. if (op == Token_CmpAnd || op == Token_CmpOr) {
  3949. Type *type = as->lhs[0]->tav.type;
  3950. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  3951. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3952. lb_addr_store(p, lhs, new_value);
  3953. } else {
  3954. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3955. lbValue value = lb_build_expr(p, as->rhs[0]);
  3956. lbValue old_value = lb_addr_load(p, lhs);
  3957. Type *type = old_value.type;
  3958. lbValue change = lb_emit_conv(p, value, type);
  3959. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  3960. lb_addr_store(p, lhs, new_value);
  3961. }
  3962. return;
  3963. }
  3964. case_end;
  3965. case_ast_node(es, ExprStmt, node);
  3966. lb_build_expr(p, es->expr);
  3967. case_end;
  3968. case_ast_node(ds, DeferStmt, node);
  3969. isize scope_index = p->scope_index;
  3970. lb_add_defer_node(p, scope_index, ds->stmt);
  3971. case_end;
  3972. case_ast_node(rs, ReturnStmt, node);
  3973. lbValue res = {};
  3974. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  3975. isize return_count = p->type->Proc.result_count;
  3976. isize res_count = rs->results.count;
  3977. if (return_count == 0) {
  3978. // No return values
  3979. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3980. LLVMBuildRetVoid(p->builder);
  3981. return;
  3982. } else if (return_count == 1) {
  3983. Entity *e = tuple->variables[0];
  3984. if (res_count == 0) {
  3985. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3986. GB_ASSERT(found);
  3987. res = lb_emit_load(p, *found);
  3988. } else {
  3989. res = lb_build_expr(p, rs->results[0]);
  3990. res = lb_emit_conv(p, res, e->type);
  3991. }
  3992. if (p->type->Proc.has_named_results) {
  3993. // NOTE(bill): store the named values before returning
  3994. if (e->token.string != "") {
  3995. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3996. GB_ASSERT(found != nullptr);
  3997. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  3998. }
  3999. }
  4000. } else {
  4001. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4002. if (res_count != 0) {
  4003. for (isize res_index = 0; res_index < res_count; res_index++) {
  4004. lbValue res = lb_build_expr(p, rs->results[res_index]);
  4005. Type *t = res.type;
  4006. if (t->kind == Type_Tuple) {
  4007. for_array(i, t->Tuple.variables) {
  4008. Entity *e = t->Tuple.variables[i];
  4009. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4010. array_add(&results, v);
  4011. }
  4012. } else {
  4013. array_add(&results, res);
  4014. }
  4015. }
  4016. } else {
  4017. for (isize res_index = 0; res_index < return_count; res_index++) {
  4018. Entity *e = tuple->variables[res_index];
  4019. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4020. GB_ASSERT(found);
  4021. lbValue res = lb_emit_load(p, *found);
  4022. array_add(&results, res);
  4023. }
  4024. }
  4025. GB_ASSERT(results.count == return_count);
  4026. if (p->type->Proc.has_named_results) {
  4027. // NOTE(bill): store the named values before returning
  4028. for_array(i, p->type->Proc.results->Tuple.variables) {
  4029. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4030. if (e->kind != Entity_Variable) {
  4031. continue;
  4032. }
  4033. if (e->token.string == "") {
  4034. continue;
  4035. }
  4036. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4037. GB_ASSERT(found != nullptr);
  4038. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  4039. }
  4040. }
  4041. Type *ret_type = p->type->Proc.results;
  4042. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4043. res = lb_add_local_generated(p, ret_type, false).addr;
  4044. for_array(i, results) {
  4045. Entity *e = tuple->variables[i];
  4046. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  4047. lbValue val = lb_emit_conv(p, results[i], e->type);
  4048. lb_emit_store(p, field, val);
  4049. }
  4050. res = lb_emit_load(p, res);
  4051. }
  4052. lb_ensure_abi_function_type(p->module, p);
  4053. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  4054. if (res.value != nullptr) {
  4055. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4056. } else {
  4057. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4058. }
  4059. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4060. LLVMBuildRetVoid(p->builder);
  4061. } else {
  4062. LLVMValueRef ret_val = res.value;
  4063. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4064. if (p->abi_function_type->ret.cast_type != nullptr) {
  4065. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4066. }
  4067. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4068. LLVMBuildRet(p->builder, ret_val);
  4069. }
  4070. case_end;
  4071. case_ast_node(is, IfStmt, node);
  4072. lb_open_scope(p, node->scope); // Scope #1
  4073. if (is->init != nullptr) {
  4074. // TODO(bill): Should this have a separate block to begin with?
  4075. #if 1
  4076. lbBlock *init = lb_create_block(p, "if.init");
  4077. lb_emit_jump(p, init);
  4078. lb_start_block(p, init);
  4079. #endif
  4080. lb_build_stmt(p, is->init);
  4081. }
  4082. lbBlock *then = lb_create_block(p, "if.then");
  4083. lbBlock *done = lb_create_block(p, "if.done");
  4084. lbBlock *else_ = done;
  4085. if (is->else_stmt != nullptr) {
  4086. else_ = lb_create_block(p, "if.else");
  4087. }
  4088. lb_build_cond(p, is->cond, then, else_);
  4089. lb_start_block(p, then);
  4090. if (is->label != nullptr) {
  4091. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4092. tl->is_block = true;
  4093. }
  4094. lb_build_stmt(p, is->body);
  4095. lb_emit_jump(p, done);
  4096. if (is->else_stmt != nullptr) {
  4097. lb_start_block(p, else_);
  4098. lb_open_scope(p, is->else_stmt->scope);
  4099. lb_build_stmt(p, is->else_stmt);
  4100. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4101. lb_emit_jump(p, done);
  4102. }
  4103. lb_start_block(p, done);
  4104. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4105. case_end;
  4106. case_ast_node(fs, ForStmt, node);
  4107. lb_open_scope(p, node->scope); // Open Scope here
  4108. if (fs->init != nullptr) {
  4109. #if 1
  4110. lbBlock *init = lb_create_block(p, "for.init");
  4111. lb_emit_jump(p, init);
  4112. lb_start_block(p, init);
  4113. #endif
  4114. lb_build_stmt(p, fs->init);
  4115. }
  4116. lbBlock *body = lb_create_block(p, "for.body");
  4117. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4118. lbBlock *loop = body;
  4119. if (fs->cond != nullptr) {
  4120. loop = lb_create_block(p, "for.loop");
  4121. }
  4122. lbBlock *post = loop;
  4123. if (fs->post != nullptr) {
  4124. post = lb_create_block(p, "for.post");
  4125. }
  4126. lb_emit_jump(p, loop);
  4127. lb_start_block(p, loop);
  4128. if (loop != body) {
  4129. lb_build_cond(p, fs->cond, body, done);
  4130. lb_start_block(p, body);
  4131. }
  4132. lb_push_target_list(p, fs->label, done, post, nullptr);
  4133. lb_build_stmt(p, fs->body);
  4134. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4135. lb_pop_target_list(p);
  4136. lb_emit_jump(p, post);
  4137. if (fs->post != nullptr) {
  4138. lb_start_block(p, post);
  4139. lb_build_stmt(p, fs->post);
  4140. lb_emit_jump(p, loop);
  4141. }
  4142. lb_start_block(p, done);
  4143. case_end;
  4144. case_ast_node(rs, RangeStmt, node);
  4145. lb_build_range_stmt(p, rs, node->scope);
  4146. case_end;
  4147. case_ast_node(rs, InlineRangeStmt, node);
  4148. lb_build_inline_range_stmt(p, rs, node->scope);
  4149. case_end;
  4150. case_ast_node(ss, SwitchStmt, node);
  4151. lb_build_switch_stmt(p, ss, node->scope);
  4152. case_end;
  4153. case_ast_node(ss, TypeSwitchStmt, node);
  4154. lb_build_type_switch_stmt(p, ss);
  4155. case_end;
  4156. case_ast_node(bs, BranchStmt, node);
  4157. lbBlock *block = nullptr;
  4158. if (bs->label != nullptr) {
  4159. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4160. switch (bs->token.kind) {
  4161. case Token_break: block = bb.break_; break;
  4162. case Token_continue: block = bb.continue_; break;
  4163. case Token_fallthrough:
  4164. GB_PANIC("fallthrough cannot have a label");
  4165. break;
  4166. }
  4167. } else {
  4168. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4169. if (t->is_block) {
  4170. continue;
  4171. }
  4172. switch (bs->token.kind) {
  4173. case Token_break: block = t->break_; break;
  4174. case Token_continue: block = t->continue_; break;
  4175. case Token_fallthrough: block = t->fallthrough_; break;
  4176. }
  4177. }
  4178. }
  4179. if (block != nullptr) {
  4180. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  4181. }
  4182. lb_emit_jump(p, block);
  4183. case_end;
  4184. }
  4185. }
  4186. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  4187. cond = lb_emit_conv(p, cond, t_llvm_bool);
  4188. lbValue res = {};
  4189. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  4190. res.type = x.type;
  4191. return res;
  4192. }
  4193. lbValue lb_const_nil(lbModule *m, Type *type) {
  4194. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  4195. return lbValue{v, type};
  4196. }
  4197. lbValue lb_const_undef(lbModule *m, Type *type) {
  4198. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  4199. return lbValue{v, type};
  4200. }
  4201. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4202. lbValue res = {};
  4203. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4204. res.type = type;
  4205. return res;
  4206. }
  4207. lbValue lb_const_string(lbModule *m, String const &value) {
  4208. return lb_const_value(m, t_string, exact_value_string(value));
  4209. }
  4210. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  4211. lbValue res = {};
  4212. res.value = LLVMConstInt(lb_type(m, type), value, false);
  4213. res.type = type;
  4214. return res;
  4215. }
  4216. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4217. GB_ASSERT(type_size_of(type) == 4);
  4218. u32 u = bit_cast<u32>(f);
  4219. if (is_type_different_to_arch_endianness(type)) {
  4220. u = gb_endian_swap32(u);
  4221. }
  4222. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4223. return LLVMConstBitCast(i, lb_type(m, type));
  4224. }
  4225. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4226. x = lb_emit_conv(p, x, t);
  4227. y = lb_emit_conv(p, y, t);
  4228. if (is_type_float(t)) {
  4229. i64 sz = 8*type_size_of(t);
  4230. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4231. args[0] = x;
  4232. args[1] = y;
  4233. switch (sz) {
  4234. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  4235. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  4236. }
  4237. GB_PANIC("Unknown float type");
  4238. }
  4239. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4240. }
  4241. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4242. x = lb_emit_conv(p, x, t);
  4243. y = lb_emit_conv(p, y, t);
  4244. if (is_type_float(t)) {
  4245. i64 sz = 8*type_size_of(t);
  4246. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4247. args[0] = x;
  4248. args[1] = y;
  4249. switch (sz) {
  4250. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4251. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4252. }
  4253. GB_PANIC("Unknown float type");
  4254. }
  4255. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4256. }
  4257. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4258. lbValue z = {};
  4259. z = lb_emit_max(p, t, x, min);
  4260. z = lb_emit_min(p, t, z, max);
  4261. return z;
  4262. }
  4263. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4264. StringHashKey key = string_hash_string(str);
  4265. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4266. if (found != nullptr) {
  4267. return *found;
  4268. } else {
  4269. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4270. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4271. cast(char const *)str.text,
  4272. cast(unsigned)str.len,
  4273. false);
  4274. isize max_len = 7+8+1;
  4275. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4276. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4277. len -= 1;
  4278. m->global_array_index++;
  4279. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4280. LLVMSetInitializer(global_data, data);
  4281. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4282. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4283. string_map_set(&m->const_strings, key, ptr);
  4284. return ptr;
  4285. }
  4286. }
  4287. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4288. LLVMValueRef ptr = nullptr;
  4289. if (str.len != 0) {
  4290. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4291. } else {
  4292. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4293. }
  4294. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4295. LLVMValueRef values[2] = {ptr, str_len};
  4296. lbValue res = {};
  4297. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  4298. res.type = t_string;
  4299. return res;
  4300. }
  4301. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4302. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4303. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4304. cast(char const *)str.text,
  4305. cast(unsigned)str.len,
  4306. false);
  4307. char *name = nullptr;
  4308. {
  4309. isize max_len = 7+8+1;
  4310. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4311. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4312. len -= 1;
  4313. m->global_array_index++;
  4314. }
  4315. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4316. LLVMSetInitializer(global_data, data);
  4317. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4318. LLVMValueRef ptr = nullptr;
  4319. if (str.len != 0) {
  4320. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4321. } else {
  4322. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4323. }
  4324. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4325. LLVMValueRef values[2] = {ptr, len};
  4326. lbValue res = {};
  4327. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  4328. res.type = t_u8_slice;
  4329. return res;
  4330. }
  4331. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4332. isize index = type_info_index(info, type, false);
  4333. if (index >= 0) {
  4334. auto *set = &info->minimum_dependency_type_info_set;
  4335. for_array(i, set->entries) {
  4336. if (set->entries[i].ptr == index) {
  4337. return i+1;
  4338. }
  4339. }
  4340. }
  4341. if (err_on_not_found) {
  4342. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4343. }
  4344. return -1;
  4345. }
  4346. lbValue lb_typeid(lbModule *m, Type *type) {
  4347. type = default_type(type);
  4348. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4349. GB_ASSERT(id >= 0);
  4350. u64 kind = Typeid_Invalid;
  4351. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4352. u64 special = 0;
  4353. u64 reserved = 0;
  4354. Type *bt = base_type(type);
  4355. TypeKind tk = bt->kind;
  4356. switch (tk) {
  4357. case Type_Basic: {
  4358. u32 flags = bt->Basic.flags;
  4359. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4360. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4361. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4362. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4363. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4364. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4365. if (flags & BasicFlag_String) kind = Typeid_String;
  4366. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4367. } break;
  4368. case Type_Pointer: kind = Typeid_Pointer; break;
  4369. case Type_Array: kind = Typeid_Array; break;
  4370. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4371. case Type_Slice: kind = Typeid_Slice; break;
  4372. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4373. case Type_Map: kind = Typeid_Map; break;
  4374. case Type_Struct: kind = Typeid_Struct; break;
  4375. case Type_Enum: kind = Typeid_Enum; break;
  4376. case Type_Union: kind = Typeid_Union; break;
  4377. case Type_Tuple: kind = Typeid_Tuple; break;
  4378. case Type_Proc: kind = Typeid_Procedure; break;
  4379. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4380. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4381. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4382. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4383. }
  4384. if (is_type_cstring(type)) {
  4385. special = 1;
  4386. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4387. special = 1;
  4388. }
  4389. u64 data = 0;
  4390. if (build_context.word_size == 4) {
  4391. GB_ASSERT(id <= (1u<<24u));
  4392. data |= (id &~ (1u<<24)) << 0u; // index
  4393. data |= (kind &~ (1u<<5)) << 24u; // kind
  4394. data |= (named &~ (1u<<1)) << 29u; // kind
  4395. data |= (special &~ (1u<<1)) << 30u; // kind
  4396. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4397. } else {
  4398. GB_ASSERT(build_context.word_size == 8);
  4399. GB_ASSERT(id <= (1ull<<56u));
  4400. data |= (id &~ (1ull<<56)) << 0ul; // index
  4401. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4402. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4403. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4404. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4405. }
  4406. lbValue res = {};
  4407. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4408. res.type = t_typeid;
  4409. return res;
  4410. }
  4411. lbValue lb_type_info(lbModule *m, Type *type) {
  4412. type = default_type(type);
  4413. isize index = lb_type_info_index(m->info, type);
  4414. GB_ASSERT(index >= 0);
  4415. LLVMTypeRef it = lb_type(m, t_int);
  4416. LLVMValueRef indices[2] = {
  4417. LLVMConstInt(it, 0, false),
  4418. LLVMConstInt(it, index, true),
  4419. };
  4420. lbValue value = {};
  4421. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  4422. value.type = t_type_info_ptr;
  4423. return value;
  4424. }
  4425. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  4426. bool is_local = allow_local && m->curr_procedure != nullptr;
  4427. bool is_const = true;
  4428. if (is_local) {
  4429. for (isize i = 0; i < count; i++) {
  4430. GB_ASSERT(values[i] != nullptr);
  4431. if (!LLVMIsConstant(values[i])) {
  4432. is_const = false;
  4433. break;
  4434. }
  4435. }
  4436. }
  4437. if (!is_const) {
  4438. lbProcedure *p = m->curr_procedure;
  4439. GB_ASSERT(p != nullptr);
  4440. lbAddr v = lb_add_local_generated(p, type, false);
  4441. lbValue ptr = lb_addr_get_ptr(p, v);
  4442. for (isize i = 0; i < count; i++) {
  4443. lbValue elem = lb_emit_array_epi(p, ptr, i);
  4444. LLVMBuildStore(p->builder, values[i], elem.value);
  4445. }
  4446. return lb_addr_load(p, v).value;
  4447. }
  4448. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  4449. }
  4450. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4451. LLVMContextRef ctx = m->ctx;
  4452. type = default_type(type);
  4453. Type *original_type = type;
  4454. lbValue res = {};
  4455. res.type = original_type;
  4456. type = core_type(type);
  4457. value = convert_exact_value_for_type(value, type);
  4458. if (value.kind == ExactValue_Typeid) {
  4459. return lb_typeid(m, value.value_typeid);
  4460. }
  4461. if (value.kind == ExactValue_Invalid) {
  4462. return lb_const_nil(m, type);
  4463. }
  4464. if (value.kind == ExactValue_Procedure) {
  4465. Ast *expr = unparen_expr(value.value_procedure);
  4466. if (expr->kind == Ast_ProcLit) {
  4467. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4468. }
  4469. Entity *e = entity_from_expr(expr);
  4470. e = strip_entity_wrapping(e);
  4471. GB_ASSERT(e != nullptr);
  4472. auto *found = map_get(&m->values, hash_entity(e));
  4473. if (found) {
  4474. return *found;
  4475. }
  4476. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  4477. }
  4478. bool is_local = allow_local && m->curr_procedure != nullptr;
  4479. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4480. if (is_type_slice(type)) {
  4481. if (value.kind == ExactValue_String) {
  4482. GB_ASSERT(is_type_u8_slice(type));
  4483. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4484. return res;
  4485. } else {
  4486. ast_node(cl, CompoundLit, value.value_compound);
  4487. isize count = cl->elems.count;
  4488. if (count == 0) {
  4489. return lb_const_nil(m, type);
  4490. }
  4491. count = gb_max(cl->max_count, count);
  4492. Type *elem = base_type(type)->Slice.elem;
  4493. Type *t = alloc_type_array(elem, count);
  4494. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4495. LLVMValueRef array_data = nullptr;
  4496. if (is_local) {
  4497. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4498. // its backing data on the stack
  4499. lbProcedure *p = m->curr_procedure;
  4500. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4501. LLVMTypeRef llvm_type = lb_type(m, t);
  4502. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4503. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4504. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4505. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4506. {
  4507. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4508. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4509. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4510. lbAddr slice = lb_add_local_generated(p, type, false);
  4511. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4512. return lb_addr_load(p, slice);
  4513. }
  4514. } else {
  4515. isize max_len = 7+8+1;
  4516. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4517. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4518. m->global_array_index++;
  4519. String name = make_string(cast(u8 *)str, len-1);
  4520. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4521. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4522. LLVMSetInitializer(array_data, backing_array.value);
  4523. lbValue g = {};
  4524. g.value = array_data;
  4525. g.type = t;
  4526. lb_add_entity(m, e, g);
  4527. lb_add_member(m, name, g);
  4528. {
  4529. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4530. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4531. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4532. LLVMValueRef values[2] = {ptr, len};
  4533. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4534. return res;
  4535. }
  4536. }
  4537. }
  4538. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4539. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4540. i64 count = type->Array.count;
  4541. Type *elem = type->Array.elem;
  4542. LLVMTypeRef et = lb_type(m, elem);
  4543. Rune rune;
  4544. isize offset = 0;
  4545. isize width = 1;
  4546. String s = value.value_string;
  4547. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4548. for (i64 i = 0; i < count && offset < s.len; i++) {
  4549. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4550. offset += width;
  4551. elems[i] = LLVMConstInt(et, rune, true);
  4552. }
  4553. GB_ASSERT(offset == s.len);
  4554. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  4555. return res;
  4556. }
  4557. GB_PANIC("HERE!\n");
  4558. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4559. cast(char const *)value.value_string.text,
  4560. cast(unsigned)value.value_string.len,
  4561. false /*DontNullTerminate*/);
  4562. res.value = data;
  4563. return res;
  4564. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4565. GB_ASSERT(type->Array.count == value.value_string.len);
  4566. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4567. cast(char const *)value.value_string.text,
  4568. cast(unsigned)value.value_string.len,
  4569. true /*DontNullTerminate*/);
  4570. res.value = data;
  4571. return res;
  4572. } else if (is_type_array(type) &&
  4573. value.kind != ExactValue_Invalid &&
  4574. value.kind != ExactValue_String &&
  4575. value.kind != ExactValue_Compound) {
  4576. i64 count = type->Array.count;
  4577. Type *elem = type->Array.elem;
  4578. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4579. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4580. for (i64 i = 0; i < count; i++) {
  4581. elems[i] = single_elem.value;
  4582. }
  4583. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  4584. return res;
  4585. }
  4586. switch (value.kind) {
  4587. case ExactValue_Invalid:
  4588. res.value = LLVMConstNull(lb_type(m, original_type));
  4589. return res;
  4590. case ExactValue_Bool:
  4591. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4592. return res;
  4593. case ExactValue_String:
  4594. {
  4595. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4596. lbValue res = {};
  4597. res.type = default_type(original_type);
  4598. if (is_type_cstring(res.type)) {
  4599. res.value = ptr;
  4600. } else {
  4601. if (value.value_string.len == 0) {
  4602. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4603. }
  4604. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4605. LLVMValueRef values[2] = {ptr, str_len};
  4606. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4607. }
  4608. return res;
  4609. }
  4610. case ExactValue_Integer:
  4611. if (is_type_pointer(type)) {
  4612. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4613. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4614. } else {
  4615. unsigned len = cast(unsigned)value.value_integer.len;
  4616. if (len == 0) {
  4617. u64 word = 0;
  4618. res.value = LLVMConstNull(lb_type(m, original_type));
  4619. } else {
  4620. u64 *words = big_int_ptr(&value.value_integer);
  4621. if (is_type_different_to_arch_endianness(type)) {
  4622. // NOTE(bill): Swap byte order for different endianness
  4623. i64 sz = type_size_of(type);
  4624. isize byte_len = gb_size_of(u64)*len;
  4625. u8 *old_bytes = cast(u8 *)words;
  4626. // TODO(bill): Use a different allocator here for a temporary allocation
  4627. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4628. for (i64 i = 0; i < sz; i++) {
  4629. new_bytes[i] = old_bytes[sz-1-i];
  4630. }
  4631. words = cast(u64 *)new_bytes;
  4632. }
  4633. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4634. if (value.value_integer.neg) {
  4635. res.value = LLVMConstNeg(res.value);
  4636. }
  4637. }
  4638. }
  4639. return res;
  4640. case ExactValue_Float:
  4641. if (type_size_of(type) == 4) {
  4642. f32 f = cast(f32)value.value_float;
  4643. res.value = lb_const_f32(m, f, type);
  4644. return res;
  4645. }
  4646. if (is_type_different_to_arch_endianness(type)) {
  4647. u64 u = bit_cast<u64>(value.value_float);
  4648. u = gb_endian_swap64(u);
  4649. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4650. } else {
  4651. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4652. }
  4653. return res;
  4654. case ExactValue_Complex:
  4655. {
  4656. LLVMValueRef values[2] = {};
  4657. switch (8*type_size_of(type)) {
  4658. case 64:
  4659. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  4660. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  4661. break;
  4662. case 128:
  4663. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  4664. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  4665. break;
  4666. }
  4667. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4668. return res;
  4669. }
  4670. break;
  4671. case ExactValue_Quaternion:
  4672. {
  4673. LLVMValueRef values[4] = {};
  4674. switch (8*type_size_of(type)) {
  4675. case 128:
  4676. // @QuaternionLayout
  4677. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  4678. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  4679. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  4680. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  4681. break;
  4682. case 256:
  4683. // @QuaternionLayout
  4684. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  4685. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  4686. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  4687. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  4688. break;
  4689. }
  4690. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  4691. return res;
  4692. }
  4693. break;
  4694. case ExactValue_Pointer:
  4695. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4696. return res;
  4697. case ExactValue_Compound:
  4698. if (is_type_slice(type)) {
  4699. return lb_const_value(m, type, value, allow_local);
  4700. } else if (is_type_array(type)) {
  4701. ast_node(cl, CompoundLit, value.value_compound);
  4702. Type *elem_type = type->Array.elem;
  4703. isize elem_count = cl->elems.count;
  4704. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4705. return lb_const_nil(m, original_type);
  4706. }
  4707. if (cl->elems[0]->kind == Ast_FieldValue) {
  4708. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4709. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4710. isize value_index = 0;
  4711. for (i64 i = 0; i < type->Array.count; i++) {
  4712. bool found = false;
  4713. for (isize j = 0; j < elem_count; j++) {
  4714. Ast *elem = cl->elems[j];
  4715. ast_node(fv, FieldValue, elem);
  4716. if (is_ast_range(fv->field)) {
  4717. ast_node(ie, BinaryExpr, fv->field);
  4718. TypeAndValue lo_tav = ie->left->tav;
  4719. TypeAndValue hi_tav = ie->right->tav;
  4720. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4721. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4722. TokenKind op = ie->op.kind;
  4723. i64 lo = exact_value_to_i64(lo_tav.value);
  4724. i64 hi = exact_value_to_i64(hi_tav.value);
  4725. if (op == Token_Ellipsis) {
  4726. hi += 1;
  4727. }
  4728. if (lo == i) {
  4729. TypeAndValue tav = fv->value->tav;
  4730. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4731. for (i64 k = lo; k < hi; k++) {
  4732. values[value_index++] = val;
  4733. }
  4734. found = true;
  4735. i += (hi-lo-1);
  4736. break;
  4737. }
  4738. } else {
  4739. TypeAndValue index_tav = fv->field->tav;
  4740. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4741. i64 index = exact_value_to_i64(index_tav.value);
  4742. if (index == i) {
  4743. TypeAndValue tav = fv->value->tav;
  4744. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4745. values[value_index++] = val;
  4746. found = true;
  4747. break;
  4748. }
  4749. }
  4750. }
  4751. if (!found) {
  4752. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4753. }
  4754. }
  4755. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4756. return res;
  4757. } else {
  4758. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4759. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4760. for (isize i = 0; i < elem_count; i++) {
  4761. TypeAndValue tav = cl->elems[i]->tav;
  4762. GB_ASSERT(tav.mode != Addressing_Invalid);
  4763. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4764. }
  4765. for (isize i = elem_count; i < type->Array.count; i++) {
  4766. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4767. }
  4768. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4769. return res;
  4770. }
  4771. } else if (is_type_enumerated_array(type)) {
  4772. ast_node(cl, CompoundLit, value.value_compound);
  4773. Type *elem_type = type->EnumeratedArray.elem;
  4774. isize elem_count = cl->elems.count;
  4775. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4776. return lb_const_nil(m, original_type);
  4777. }
  4778. if (cl->elems[0]->kind == Ast_FieldValue) {
  4779. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4780. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4781. isize value_index = 0;
  4782. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4783. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4784. for (i64 i = total_lo; i <= total_hi; i++) {
  4785. bool found = false;
  4786. for (isize j = 0; j < elem_count; j++) {
  4787. Ast *elem = cl->elems[j];
  4788. ast_node(fv, FieldValue, elem);
  4789. if (is_ast_range(fv->field)) {
  4790. ast_node(ie, BinaryExpr, fv->field);
  4791. TypeAndValue lo_tav = ie->left->tav;
  4792. TypeAndValue hi_tav = ie->right->tav;
  4793. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4794. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4795. TokenKind op = ie->op.kind;
  4796. i64 lo = exact_value_to_i64(lo_tav.value);
  4797. i64 hi = exact_value_to_i64(hi_tav.value);
  4798. if (op == Token_Ellipsis) {
  4799. hi += 1;
  4800. }
  4801. if (lo == i) {
  4802. TypeAndValue tav = fv->value->tav;
  4803. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4804. for (i64 k = lo; k < hi; k++) {
  4805. values[value_index++] = val;
  4806. }
  4807. found = true;
  4808. i += (hi-lo-1);
  4809. break;
  4810. }
  4811. } else {
  4812. TypeAndValue index_tav = fv->field->tav;
  4813. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4814. i64 index = exact_value_to_i64(index_tav.value);
  4815. if (index == i) {
  4816. TypeAndValue tav = fv->value->tav;
  4817. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4818. values[value_index++] = val;
  4819. found = true;
  4820. break;
  4821. }
  4822. }
  4823. }
  4824. if (!found) {
  4825. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4826. }
  4827. }
  4828. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4829. return res;
  4830. } else {
  4831. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4832. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4833. for (isize i = 0; i < elem_count; i++) {
  4834. TypeAndValue tav = cl->elems[i]->tav;
  4835. GB_ASSERT(tav.mode != Addressing_Invalid);
  4836. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4837. }
  4838. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4839. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4840. }
  4841. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4842. return res;
  4843. }
  4844. } else if (is_type_simd_vector(type)) {
  4845. ast_node(cl, CompoundLit, value.value_compound);
  4846. Type *elem_type = type->SimdVector.elem;
  4847. isize elem_count = cl->elems.count;
  4848. if (elem_count == 0) {
  4849. return lb_const_nil(m, original_type);
  4850. }
  4851. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4852. isize total_elem_count = type->SimdVector.count;
  4853. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  4854. for (isize i = 0; i < elem_count; i++) {
  4855. TypeAndValue tav = cl->elems[i]->tav;
  4856. GB_ASSERT(tav.mode != Addressing_Invalid);
  4857. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4858. }
  4859. LLVMTypeRef et = lb_type(m, elem_type);
  4860. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  4861. values[i] = LLVMConstNull(et);
  4862. }
  4863. for (isize i = 0; i< total_elem_count; i++) {
  4864. values[i] = llvm_const_cast(values[i], et);
  4865. }
  4866. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  4867. return res;
  4868. } else if (is_type_struct(type)) {
  4869. ast_node(cl, CompoundLit, value.value_compound);
  4870. if (cl->elems.count == 0) {
  4871. return lb_const_nil(m, original_type);
  4872. }
  4873. isize offset = 0;
  4874. if (type->Struct.custom_align > 0) {
  4875. offset = 1;
  4876. }
  4877. isize value_count = type->Struct.fields.count + offset;
  4878. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  4879. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  4880. if (cl->elems.count > 0) {
  4881. if (cl->elems[0]->kind == Ast_FieldValue) {
  4882. isize elem_count = cl->elems.count;
  4883. for (isize i = 0; i < elem_count; i++) {
  4884. ast_node(fv, FieldValue, cl->elems[i]);
  4885. String name = fv->field->Ident.token.string;
  4886. TypeAndValue tav = fv->value->tav;
  4887. GB_ASSERT(tav.mode != Addressing_Invalid);
  4888. Selection sel = lookup_field(type, name, false);
  4889. Entity *f = type->Struct.fields[sel.index[0]];
  4890. if (elem_type_can_be_constant(f->type)) {
  4891. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  4892. visited[offset+f->Variable.field_index] = true;
  4893. }
  4894. }
  4895. } else {
  4896. for_array(i, cl->elems) {
  4897. Entity *f = type->Struct.fields[i];
  4898. TypeAndValue tav = cl->elems[i]->tav;
  4899. ExactValue val = {};
  4900. if (tav.mode != Addressing_Invalid) {
  4901. val = tav.value;
  4902. }
  4903. if (elem_type_can_be_constant(f->type)) {
  4904. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  4905. visited[offset+f->Variable.field_index] = true;
  4906. }
  4907. }
  4908. }
  4909. }
  4910. for (isize i = 0; i < type->Struct.fields.count; i++) {
  4911. if (!visited[offset+i]) {
  4912. GB_ASSERT(values[offset+i] == nullptr);
  4913. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  4914. }
  4915. }
  4916. if (type->Struct.custom_align > 0) {
  4917. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  4918. }
  4919. for (isize i = 0; i < value_count; i++) {
  4920. GB_ASSERT(LLVMIsConstant(values[i]));
  4921. }
  4922. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  4923. return res;
  4924. } else if (is_type_bit_set(type)) {
  4925. ast_node(cl, CompoundLit, value.value_compound);
  4926. if (cl->elems.count == 0) {
  4927. return lb_const_nil(m, original_type);
  4928. }
  4929. i64 sz = type_size_of(type);
  4930. if (sz == 0) {
  4931. return lb_const_nil(m, original_type);
  4932. }
  4933. u64 bits = 0;
  4934. for_array(i, cl->elems) {
  4935. Ast *e = cl->elems[i];
  4936. GB_ASSERT(e->kind != Ast_FieldValue);
  4937. TypeAndValue tav = e->tav;
  4938. if (tav.mode != Addressing_Constant) {
  4939. continue;
  4940. }
  4941. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  4942. i64 v = big_int_to_i64(&tav.value.value_integer);
  4943. i64 lower = type->BitSet.lower;
  4944. bits |= 1ull<<cast(u64)(v-lower);
  4945. }
  4946. if (is_type_different_to_arch_endianness(type)) {
  4947. i64 size = type_size_of(type);
  4948. switch (size) {
  4949. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  4950. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  4951. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  4952. }
  4953. }
  4954. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  4955. return res;
  4956. } else {
  4957. return lb_const_nil(m, original_type);
  4958. }
  4959. break;
  4960. case ExactValue_Procedure:
  4961. {
  4962. Ast *expr = value.value_procedure;
  4963. GB_ASSERT(expr != nullptr);
  4964. if (expr->kind == Ast_ProcLit) {
  4965. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4966. }
  4967. }
  4968. break;
  4969. case ExactValue_Typeid:
  4970. return lb_typeid(m, value.value_typeid);
  4971. }
  4972. return lb_const_nil(m, original_type);
  4973. }
  4974. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  4975. lbModule *m = p->module;
  4976. LLVMValueRef fields[4] = {};
  4977. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  4978. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  4979. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  4980. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  4981. lbValue res = {};
  4982. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  4983. res.type = t_source_code_location;
  4984. return res;
  4985. }
  4986. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  4987. String proc_name = {};
  4988. if (p->entity) {
  4989. proc_name = p->entity->token.string;
  4990. }
  4991. TokenPos pos = {};
  4992. if (node) {
  4993. pos = ast_token(node).pos;
  4994. }
  4995. return lb_emit_source_code_location(p, proc_name, pos);
  4996. }
  4997. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  4998. switch (op) {
  4999. case Token_Add:
  5000. return x;
  5001. case Token_Not: // Boolean not
  5002. case Token_Xor: // Bitwise not
  5003. case Token_Sub: // Number negation
  5004. break;
  5005. case Token_Pointer:
  5006. GB_PANIC("This should be handled elsewhere");
  5007. break;
  5008. }
  5009. if (is_type_array(x.type)) {
  5010. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5011. Type *tl = base_type(x.type);
  5012. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5013. GB_ASSERT(is_type_array(type));
  5014. Type *elem_type = base_array_type(type);
  5015. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5016. lbAddr res_addr = lb_add_local_generated(p, type, false);
  5017. lbValue res = lb_addr_get_ptr(p, res_addr);
  5018. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5019. i32 count = cast(i32)tl->Array.count;
  5020. if (inline_array_arith) {
  5021. // inline
  5022. for (i32 i = 0; i < count; i++) {
  5023. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5024. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5025. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  5026. }
  5027. } else {
  5028. auto loop_data = lb_loop_start(p, count, t_i32);
  5029. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  5030. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5031. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  5032. lb_loop_end(p, loop_data);
  5033. }
  5034. return lb_emit_load(p, res);
  5035. }
  5036. if (op == Token_Xor) {
  5037. lbValue cmp = {};
  5038. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  5039. cmp.type = x.type;
  5040. return lb_emit_conv(p, cmp, type);
  5041. }
  5042. if (op == Token_Not) {
  5043. lbValue cmp = {};
  5044. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  5045. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  5046. cmp.type = t_llvm_bool;
  5047. return lb_emit_conv(p, cmp, type);
  5048. }
  5049. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5050. Type *platform_type = integer_endian_type_to_platform_type(type);
  5051. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5052. lbValue res = {};
  5053. res.value = LLVMBuildNeg(p->builder, v.value, "");
  5054. res.type = platform_type;
  5055. return lb_emit_byte_swap(p, res, type);
  5056. }
  5057. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5058. Type *platform_type = integer_endian_type_to_platform_type(type);
  5059. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5060. lbValue res = {};
  5061. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  5062. res.type = platform_type;
  5063. return lb_emit_byte_swap(p, res, type);
  5064. }
  5065. lbValue res = {};
  5066. switch (op) {
  5067. case Token_Not: // Boolean not
  5068. case Token_Xor: // Bitwise not
  5069. res.value = LLVMBuildNot(p->builder, x.value, "");
  5070. res.type = x.type;
  5071. return res;
  5072. case Token_Sub: // Number negation
  5073. if (is_type_integer(x.type)) {
  5074. res.value = LLVMBuildNeg(p->builder, x.value, "");
  5075. } else if (is_type_float(x.type)) {
  5076. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  5077. } else if (is_type_complex(x.type)) {
  5078. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5079. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5080. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5081. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5082. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5083. return lb_addr_load(p, addr);
  5084. } else if (is_type_quaternion(x.type)) {
  5085. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5086. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5087. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  5088. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  5089. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5090. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5091. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5092. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  5093. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  5094. return lb_addr_load(p, addr);
  5095. } else {
  5096. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  5097. }
  5098. res.type = x.type;
  5099. return res;
  5100. }
  5101. return res;
  5102. }
  5103. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  5104. lbModule *m = p->module;
  5105. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  5106. lhs = lb_emit_conv(p, lhs, type);
  5107. rhs = lb_emit_conv(p, rhs, type);
  5108. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  5109. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  5110. GB_ASSERT(is_type_array(type));
  5111. Type *elem_type = base_array_type(type);
  5112. lbAddr res = lb_add_local_generated(p, type, false);
  5113. i64 count = base_type(type)->Array.count;
  5114. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5115. if (inline_array_arith) {
  5116. for (i64 i = 0; i < count; i++) {
  5117. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  5118. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  5119. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  5120. lbValue a = lb_emit_load(p, a_ptr);
  5121. lbValue b = lb_emit_load(p, b_ptr);
  5122. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5123. lb_emit_store(p, dst_ptr, c);
  5124. }
  5125. } else {
  5126. auto loop_data = lb_loop_start(p, count, t_i32);
  5127. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  5128. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  5129. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  5130. lbValue a = lb_emit_load(p, a_ptr);
  5131. lbValue b = lb_emit_load(p, b_ptr);
  5132. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5133. lb_emit_store(p, dst_ptr, c);
  5134. lb_loop_end(p, loop_data);
  5135. }
  5136. return lb_addr_load(p, res);
  5137. } else if (is_type_complex(type)) {
  5138. lhs = lb_emit_conv(p, lhs, type);
  5139. rhs = lb_emit_conv(p, rhs, type);
  5140. Type *ft = base_complex_elem_type(type);
  5141. if (op == Token_Quo) {
  5142. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5143. args[0] = lhs;
  5144. args[1] = rhs;
  5145. switch (type_size_of(ft)) {
  5146. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  5147. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  5148. default: GB_PANIC("Unknown float type"); break;
  5149. }
  5150. }
  5151. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5152. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  5153. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  5154. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  5155. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  5156. lbValue real = {};
  5157. lbValue imag = {};
  5158. switch (op) {
  5159. case Token_Add:
  5160. real = lb_emit_arith(p, Token_Add, a, c, ft);
  5161. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  5162. break;
  5163. case Token_Sub:
  5164. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  5165. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  5166. break;
  5167. case Token_Mul: {
  5168. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  5169. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  5170. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  5171. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  5172. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  5173. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  5174. break;
  5175. }
  5176. }
  5177. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  5178. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  5179. return lb_addr_load(p, res);
  5180. } else if (is_type_quaternion(type)) {
  5181. lhs = lb_emit_conv(p, lhs, type);
  5182. rhs = lb_emit_conv(p, rhs, type);
  5183. Type *ft = base_complex_elem_type(type);
  5184. if (op == Token_Add || op == Token_Sub) {
  5185. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5186. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  5187. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  5188. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  5189. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  5190. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  5191. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  5192. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  5193. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  5194. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  5195. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  5196. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  5197. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  5198. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  5199. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  5200. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  5201. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  5202. return lb_addr_load(p, res);
  5203. } else if (op == Token_Mul) {
  5204. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5205. args[0] = lhs;
  5206. args[1] = rhs;
  5207. switch (8*type_size_of(ft)) {
  5208. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  5209. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  5210. default: GB_PANIC("Unknown float type"); break;
  5211. }
  5212. } else if (op == Token_Quo) {
  5213. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5214. args[0] = lhs;
  5215. args[1] = rhs;
  5216. switch (8*type_size_of(ft)) {
  5217. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  5218. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  5219. default: GB_PANIC("Unknown float type"); break;
  5220. }
  5221. }
  5222. }
  5223. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5224. switch (op) {
  5225. case Token_AndNot:
  5226. case Token_And:
  5227. case Token_Or:
  5228. case Token_Xor:
  5229. goto handle_op;
  5230. }
  5231. Type *platform_type = integer_endian_type_to_platform_type(type);
  5232. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5233. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5234. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5235. return lb_emit_byte_swap(p, res, type);
  5236. }
  5237. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5238. Type *platform_type = integer_endian_type_to_platform_type(type);
  5239. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5240. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5241. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5242. return lb_emit_byte_swap(p, res, type);
  5243. }
  5244. handle_op:
  5245. lhs = lb_emit_conv(p, lhs, type);
  5246. rhs = lb_emit_conv(p, rhs, type);
  5247. lbValue res = {};
  5248. res.type = type;
  5249. switch (op) {
  5250. case Token_Add:
  5251. if (is_type_float(type)) {
  5252. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  5253. return res;
  5254. }
  5255. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  5256. return res;
  5257. case Token_Sub:
  5258. if (is_type_float(type)) {
  5259. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  5260. return res;
  5261. }
  5262. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  5263. return res;
  5264. case Token_Mul:
  5265. if (is_type_float(type)) {
  5266. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  5267. return res;
  5268. }
  5269. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  5270. return res;
  5271. case Token_Quo:
  5272. if (is_type_float(type)) {
  5273. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  5274. return res;
  5275. } else if (is_type_unsigned(type)) {
  5276. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  5277. return res;
  5278. }
  5279. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  5280. return res;
  5281. case Token_Mod:
  5282. if (is_type_float(type)) {
  5283. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  5284. return res;
  5285. } else if (is_type_unsigned(type)) {
  5286. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5287. return res;
  5288. }
  5289. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5290. return res;
  5291. case Token_ModMod:
  5292. if (is_type_unsigned(type)) {
  5293. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5294. return res;
  5295. } else {
  5296. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5297. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5298. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5299. res.value = c;
  5300. return res;
  5301. }
  5302. case Token_And:
  5303. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5304. return res;
  5305. case Token_Or:
  5306. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5307. return res;
  5308. case Token_Xor:
  5309. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5310. return res;
  5311. case Token_Shl:
  5312. {
  5313. rhs = lb_emit_conv(p, rhs, lhs.type);
  5314. LLVMValueRef lhsval = lhs.value;
  5315. LLVMValueRef bits = rhs.value;
  5316. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5317. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULT, bits, max, "");
  5318. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5319. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5320. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  5321. return res;
  5322. }
  5323. case Token_Shr:
  5324. {
  5325. rhs = lb_emit_conv(p, rhs, lhs.type);
  5326. LLVMValueRef lhsval = lhs.value;
  5327. LLVMValueRef bits = rhs.value;
  5328. bool is_unsigned = is_type_unsigned(type);
  5329. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5330. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULT, bits, max, "");
  5331. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  5332. if (is_unsigned) {
  5333. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  5334. } else {
  5335. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5336. }
  5337. return res;
  5338. }
  5339. case Token_AndNot:
  5340. {
  5341. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5342. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5343. return res;
  5344. }
  5345. break;
  5346. }
  5347. GB_PANIC("unhandled operator of lb_emit_arith");
  5348. return {};
  5349. }
  5350. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5351. ast_node(be, BinaryExpr, expr);
  5352. TypeAndValue tv = type_and_value_of_expr(expr);
  5353. switch (be->op.kind) {
  5354. case Token_Add:
  5355. case Token_Sub:
  5356. case Token_Mul:
  5357. case Token_Quo:
  5358. case Token_Mod:
  5359. case Token_ModMod:
  5360. case Token_And:
  5361. case Token_Or:
  5362. case Token_Xor:
  5363. case Token_AndNot:
  5364. case Token_Shl:
  5365. case Token_Shr: {
  5366. Type *type = default_type(tv.type);
  5367. lbValue left = lb_build_expr(p, be->left);
  5368. lbValue right = lb_build_expr(p, be->right);
  5369. return lb_emit_arith(p, be->op.kind, left, right, type);
  5370. }
  5371. case Token_CmpEq:
  5372. case Token_NotEq:
  5373. case Token_Lt:
  5374. case Token_LtEq:
  5375. case Token_Gt:
  5376. case Token_GtEq:
  5377. {
  5378. lbValue left = {};
  5379. lbValue right = {};
  5380. if (be->left->tav.mode == Addressing_Type) {
  5381. left = lb_typeid(p->module, be->left->tav.type);
  5382. }
  5383. if (be->right->tav.mode == Addressing_Type) {
  5384. right = lb_typeid(p->module, be->right->tav.type);
  5385. }
  5386. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5387. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5388. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5389. Type *type = default_type(tv.type);
  5390. return lb_emit_conv(p, cmp, type);
  5391. }
  5392. case Token_CmpAnd:
  5393. case Token_CmpOr:
  5394. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5395. case Token_in:
  5396. case Token_not_in:
  5397. {
  5398. lbValue left = lb_build_expr(p, be->left);
  5399. Type *type = default_type(tv.type);
  5400. lbValue right = lb_build_expr(p, be->right);
  5401. Type *rt = base_type(right.type);
  5402. switch (rt->kind) {
  5403. case Type_Map:
  5404. {
  5405. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5406. lbValue h = lb_gen_map_header(p, addr, rt);
  5407. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  5408. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5409. args[0] = h;
  5410. args[1] = key;
  5411. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5412. if (be->op.kind == Token_in) {
  5413. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5414. } else {
  5415. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  5416. }
  5417. }
  5418. break;
  5419. case Type_BitSet:
  5420. {
  5421. Type *key_type = rt->BitSet.elem;
  5422. GB_ASSERT(are_types_identical(left.type, key_type));
  5423. Type *it = bit_set_to_int(rt);
  5424. left = lb_emit_conv(p, left, it);
  5425. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  5426. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  5427. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  5428. bit = lb_emit_conv(p, bit, it);
  5429. lbValue old_value = lb_emit_transmute(p, right, it);
  5430. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  5431. if (be->op.kind == Token_in) {
  5432. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5433. } else {
  5434. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5435. }
  5436. }
  5437. break;
  5438. default:
  5439. GB_PANIC("Invalid 'in' type");
  5440. }
  5441. break;
  5442. }
  5443. break;
  5444. default:
  5445. GB_PANIC("Invalid binary expression");
  5446. break;
  5447. }
  5448. return {};
  5449. }
  5450. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5451. Type *prev_src = src;
  5452. // Type *prev_dst = dst;
  5453. src = base_type(type_deref(src));
  5454. // dst = base_type(type_deref(dst));
  5455. bool src_is_ptr = src != prev_src;
  5456. // bool dst_is_ptr = dst != prev_dst;
  5457. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5458. for_array(i, src->Struct.fields) {
  5459. Entity *f = src->Struct.fields[i];
  5460. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5461. if (are_types_identical(dst, f->type)) {
  5462. return f->token.string;
  5463. }
  5464. if (src_is_ptr && is_type_pointer(dst)) {
  5465. if (are_types_identical(type_deref(dst), f->type)) {
  5466. return f->token.string;
  5467. }
  5468. }
  5469. if (is_type_struct(f->type)) {
  5470. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5471. if (name.len > 0) {
  5472. return name;
  5473. }
  5474. }
  5475. }
  5476. }
  5477. return str_lit("");
  5478. }
  5479. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5480. GB_ASSERT(is_type_pointer(value.type));
  5481. GB_ASSERT(is_type_pointer(t));
  5482. GB_ASSERT(lb_is_const(value));
  5483. lbValue res = {};
  5484. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5485. res.type = t;
  5486. return res;
  5487. }
  5488. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5489. lbModule *m = p->module;
  5490. t = reduce_tuple_to_single_type(t);
  5491. Type *src_type = value.type;
  5492. if (are_types_identical(t, src_type)) {
  5493. return value;
  5494. }
  5495. Type *src = core_type(src_type);
  5496. Type *dst = core_type(t);
  5497. GB_ASSERT(src != nullptr);
  5498. GB_ASSERT(dst != nullptr);
  5499. if (is_type_untyped_nil(src)) {
  5500. return lb_const_nil(m, t);
  5501. }
  5502. if (is_type_untyped_undef(src)) {
  5503. return lb_const_undef(m, t);
  5504. }
  5505. if (LLVMIsConstant(value.value)) {
  5506. if (is_type_any(dst)) {
  5507. Type *st = default_type(src_type);
  5508. lbAddr default_value = lb_add_local_generated(p, st, false);
  5509. lb_addr_store(p, default_value, value);
  5510. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5511. lbValue id = lb_typeid(m, st);
  5512. lbAddr res = lb_add_local_generated(p, t, false);
  5513. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5514. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5515. lb_emit_store(p, a0, data);
  5516. lb_emit_store(p, a1, id);
  5517. return lb_addr_load(p, res);
  5518. } else if (dst->kind == Type_Basic) {
  5519. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5520. String str = lb_get_const_string(m, value);
  5521. lbValue res = {};
  5522. res.type = t;
  5523. res.value = llvm_cstring(m, str);
  5524. return res;
  5525. }
  5526. // if (is_type_float(dst)) {
  5527. // return value;
  5528. // } else if (is_type_integer(dst)) {
  5529. // return value;
  5530. // }
  5531. // ExactValue ev = value->Constant.value;
  5532. // if (is_type_float(dst)) {
  5533. // ev = exact_value_to_float(ev);
  5534. // } else if (is_type_complex(dst)) {
  5535. // ev = exact_value_to_complex(ev);
  5536. // } else if (is_type_quaternion(dst)) {
  5537. // ev = exact_value_to_quaternion(ev);
  5538. // } else if (is_type_string(dst)) {
  5539. // // Handled elsewhere
  5540. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5541. // } else if (is_type_integer(dst)) {
  5542. // ev = exact_value_to_integer(ev);
  5543. // } else if (is_type_pointer(dst)) {
  5544. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5545. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5546. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5547. // }
  5548. // return lb_const_value(p->module, t, ev);
  5549. }
  5550. }
  5551. if (are_types_identical(src, dst)) {
  5552. if (!are_types_identical(src_type, t)) {
  5553. return lb_emit_transmute(p, value, t);
  5554. }
  5555. return value;
  5556. }
  5557. // bool <-> llvm bool
  5558. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5559. lbValue res = {};
  5560. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5561. res.type = dst;
  5562. return res;
  5563. }
  5564. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5565. lbValue res = {};
  5566. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5567. res.type = dst;
  5568. return res;
  5569. }
  5570. // integer -> integer
  5571. if (is_type_integer(src) && is_type_integer(dst)) {
  5572. GB_ASSERT(src->kind == Type_Basic &&
  5573. dst->kind == Type_Basic);
  5574. i64 sz = type_size_of(default_type(src));
  5575. i64 dz = type_size_of(default_type(dst));
  5576. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5577. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5578. value = lb_emit_byte_swap(p, value, platform_src_type);
  5579. }
  5580. LLVMOpcode op = LLVMTrunc;
  5581. if (dz < sz) {
  5582. op = LLVMTrunc;
  5583. } else if (dz == sz) {
  5584. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5585. // NOTE(bill): Copy the value just for type correctness
  5586. op = LLVMBitCast;
  5587. } else if (dz > sz) {
  5588. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5589. }
  5590. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5591. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5592. lbValue res = {};
  5593. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5594. res.type = t;
  5595. return lb_emit_byte_swap(p, res, t);
  5596. } else {
  5597. lbValue res = {};
  5598. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5599. res.type = t;
  5600. return res;
  5601. }
  5602. }
  5603. // boolean -> boolean/integer
  5604. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5605. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5606. lbValue res = {};
  5607. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5608. res.type = t;
  5609. return res;
  5610. }
  5611. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5612. return lb_emit_transmute(p, value, dst);
  5613. }
  5614. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5615. return lb_emit_transmute(p, value, dst);
  5616. }
  5617. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5618. return lb_emit_transmute(p, value, dst);
  5619. }
  5620. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5621. return lb_emit_transmute(p, value, dst);
  5622. }
  5623. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5624. lbValue c = lb_emit_conv(p, value, t_cstring);
  5625. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5626. args[0] = c;
  5627. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5628. return lb_emit_conv(p, s, dst);
  5629. }
  5630. // integer -> boolean
  5631. if (is_type_integer(src) && is_type_boolean(dst)) {
  5632. lbValue res = {};
  5633. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5634. res.type = t_llvm_bool;
  5635. return lb_emit_conv(p, res, t);
  5636. }
  5637. // float -> float
  5638. if (is_type_float(src) && is_type_float(dst)) {
  5639. i64 sz = type_size_of(src);
  5640. i64 dz = type_size_of(dst);
  5641. if (dz == sz) {
  5642. if (types_have_same_internal_endian(src, dst)) {
  5643. lbValue res = {};
  5644. res.type = t;
  5645. res.value = value.value;
  5646. return res;
  5647. } else {
  5648. return lb_emit_byte_swap(p, value, t);
  5649. }
  5650. }
  5651. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5652. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5653. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5654. lbValue res = {};
  5655. res = lb_emit_conv(p, value, platform_src_type);
  5656. res = lb_emit_conv(p, res, platform_dst_type);
  5657. if (is_type_different_to_arch_endianness(dst)) {
  5658. res = lb_emit_byte_swap(p, res, t);
  5659. }
  5660. return lb_emit_conv(p, res, t);
  5661. }
  5662. lbValue res = {};
  5663. res.type = t;
  5664. if (dz >= sz) {
  5665. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5666. } else {
  5667. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5668. }
  5669. return res;
  5670. }
  5671. if (is_type_complex(src) && is_type_complex(dst)) {
  5672. Type *ft = base_complex_elem_type(dst);
  5673. lbAddr gen = lb_add_local_generated(p, dst, false);
  5674. lbValue gp = lb_addr_get_ptr(p, gen);
  5675. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5676. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5677. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5678. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5679. return lb_addr_load(p, gen);
  5680. }
  5681. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5682. // @QuaternionLayout
  5683. Type *ft = base_complex_elem_type(dst);
  5684. lbAddr gen = lb_add_local_generated(p, dst, false);
  5685. lbValue gp = lb_addr_get_ptr(p, gen);
  5686. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5687. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5688. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5689. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5690. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5691. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5692. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5693. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5694. return lb_addr_load(p, gen);
  5695. }
  5696. if (is_type_float(src) && is_type_complex(dst)) {
  5697. Type *ft = base_complex_elem_type(dst);
  5698. lbAddr gen = lb_add_local_generated(p, dst, true);
  5699. lbValue gp = lb_addr_get_ptr(p, gen);
  5700. lbValue real = lb_emit_conv(p, value, ft);
  5701. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5702. return lb_addr_load(p, gen);
  5703. }
  5704. if (is_type_float(src) && is_type_quaternion(dst)) {
  5705. Type *ft = base_complex_elem_type(dst);
  5706. lbAddr gen = lb_add_local_generated(p, dst, true);
  5707. lbValue gp = lb_addr_get_ptr(p, gen);
  5708. lbValue real = lb_emit_conv(p, value, ft);
  5709. // @QuaternionLayout
  5710. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5711. return lb_addr_load(p, gen);
  5712. }
  5713. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5714. Type *ft = base_complex_elem_type(dst);
  5715. lbAddr gen = lb_add_local_generated(p, dst, true);
  5716. lbValue gp = lb_addr_get_ptr(p, gen);
  5717. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5718. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5719. // @QuaternionLayout
  5720. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5721. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5722. return lb_addr_load(p, gen);
  5723. }
  5724. // float <-> integer
  5725. if (is_type_float(src) && is_type_integer(dst)) {
  5726. lbValue res = {};
  5727. res.type = t;
  5728. if (is_type_unsigned(dst)) {
  5729. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5730. } else {
  5731. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5732. }
  5733. return res;
  5734. }
  5735. if (is_type_integer(src) && is_type_float(dst)) {
  5736. lbValue res = {};
  5737. res.type = t;
  5738. if (is_type_unsigned(src)) {
  5739. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5740. } else {
  5741. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5742. }
  5743. return res;
  5744. }
  5745. // Pointer <-> uintptr
  5746. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5747. lbValue res = {};
  5748. res.type = t;
  5749. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5750. return res;
  5751. }
  5752. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5753. lbValue res = {};
  5754. res.type = t;
  5755. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5756. return res;
  5757. }
  5758. #if 1
  5759. if (is_type_union(dst)) {
  5760. for_array(i, dst->Union.variants) {
  5761. Type *vt = dst->Union.variants[i];
  5762. if (are_types_identical(vt, src_type)) {
  5763. lbAddr parent = lb_add_local_generated(p, t, true);
  5764. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5765. return lb_addr_load(p, parent);
  5766. }
  5767. }
  5768. }
  5769. #endif
  5770. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5771. // subtype polymorphism casting
  5772. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5773. Type *st = type_deref(src_type);
  5774. Type *pst = st;
  5775. st = type_deref(st);
  5776. bool st_is_ptr = is_type_pointer(src_type);
  5777. st = base_type(st);
  5778. Type *dt = t;
  5779. bool dt_is_ptr = type_deref(dt) != dt;
  5780. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5781. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  5782. if (field_name.len > 0) {
  5783. // NOTE(bill): It can be casted
  5784. Selection sel = lookup_field(st, field_name, false, true);
  5785. if (sel.entity != nullptr) {
  5786. if (st_is_ptr) {
  5787. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  5788. Type *rt = res.type;
  5789. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5790. res = lb_emit_load(p, res);
  5791. }
  5792. return res;
  5793. } else {
  5794. if (is_type_pointer(value.type)) {
  5795. Type *rt = value.type;
  5796. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5797. value = lb_emit_load(p, value);
  5798. } else {
  5799. value = lb_emit_deep_field_gep(p, value, sel);
  5800. return lb_emit_load(p, value);
  5801. }
  5802. }
  5803. return lb_emit_deep_field_ev(p, value, sel);
  5804. }
  5805. } else {
  5806. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5807. }
  5808. }
  5809. }
  5810. // Pointer <-> Pointer
  5811. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5812. lbValue res = {};
  5813. res.type = t;
  5814. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5815. return res;
  5816. }
  5817. // proc <-> proc
  5818. if (is_type_proc(src) && is_type_proc(dst)) {
  5819. lbValue res = {};
  5820. res.type = t;
  5821. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5822. return res;
  5823. }
  5824. // pointer -> proc
  5825. if (is_type_pointer(src) && is_type_proc(dst)) {
  5826. lbValue res = {};
  5827. res.type = t;
  5828. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5829. return res;
  5830. }
  5831. // proc -> pointer
  5832. if (is_type_proc(src) && is_type_pointer(dst)) {
  5833. lbValue res = {};
  5834. res.type = t;
  5835. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5836. return res;
  5837. }
  5838. // []byte/[]u8 <-> string
  5839. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5840. return lb_emit_transmute(p, value, t);
  5841. }
  5842. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5843. return lb_emit_transmute(p, value, t);
  5844. }
  5845. if (is_type_array(dst)) {
  5846. Type *elem = dst->Array.elem;
  5847. lbValue e = lb_emit_conv(p, value, elem);
  5848. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5849. lbAddr v = lb_add_local_generated(p, t, false);
  5850. isize index_count = cast(isize)dst->Array.count;
  5851. for (isize i = 0; i < index_count; i++) {
  5852. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  5853. lb_emit_store(p, elem, e);
  5854. }
  5855. return lb_addr_load(p, v);
  5856. }
  5857. if (is_type_any(dst)) {
  5858. if (is_type_untyped_nil(src)) {
  5859. return lb_const_nil(p->module, t);
  5860. }
  5861. if (is_type_untyped_undef(src)) {
  5862. return lb_const_undef(p->module, t);
  5863. }
  5864. lbAddr result = lb_add_local_generated(p, t, true);
  5865. Type *st = default_type(src_type);
  5866. lbValue data = lb_address_from_load_or_generate_local(p, value);
  5867. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  5868. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5869. data = lb_emit_conv(p, data, t_rawptr);
  5870. lbValue id = lb_typeid(p->module, st);
  5871. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  5872. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  5873. lb_emit_store(p, any_data, data);
  5874. lb_emit_store(p, any_id, id);
  5875. return lb_addr_load(p, result);
  5876. }
  5877. i64 src_sz = type_size_of(src);
  5878. i64 dst_sz = type_size_of(dst);
  5879. if (src_sz == dst_sz) {
  5880. // bit_set <-> integer
  5881. if (is_type_integer(src) && is_type_bit_set(dst)) {
  5882. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  5883. res.type = dst;
  5884. return res;
  5885. }
  5886. if (is_type_bit_set(src) && is_type_integer(dst)) {
  5887. lbValue bs = value;
  5888. bs.type = bit_set_to_int(src);
  5889. return lb_emit_conv(p, bs, dst);
  5890. }
  5891. // typeid <-> integer
  5892. if (is_type_integer(src) && is_type_typeid(dst)) {
  5893. return lb_emit_transmute(p, value, dst);
  5894. }
  5895. if (is_type_typeid(src) && is_type_integer(dst)) {
  5896. return lb_emit_transmute(p, value, dst);
  5897. }
  5898. }
  5899. if (is_type_untyped(src)) {
  5900. if (is_type_string(src) && is_type_string(dst)) {
  5901. lbAddr result = lb_add_local_generated(p, t, false);
  5902. lb_addr_store(p, result, value);
  5903. return lb_addr_load(p, result);
  5904. }
  5905. }
  5906. gb_printf_err("%.*s\n", LIT(p->name));
  5907. gb_printf_err("lb_emit_conv: src -> dst\n");
  5908. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5909. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5910. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  5911. gb_printf_err("Not Identical %p != %p\n", src, dst);
  5912. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5913. type_to_string(src_type), type_to_string(t),
  5914. LIT(p->name));
  5915. return {};
  5916. }
  5917. bool lb_is_type_aggregate(Type *t) {
  5918. t = base_type(t);
  5919. switch (t->kind) {
  5920. case Type_Basic:
  5921. switch (t->Basic.kind) {
  5922. case Basic_string:
  5923. case Basic_any:
  5924. return true;
  5925. // case Basic_complex32:
  5926. case Basic_complex64:
  5927. case Basic_complex128:
  5928. case Basic_quaternion128:
  5929. case Basic_quaternion256:
  5930. return true;
  5931. }
  5932. break;
  5933. case Type_Pointer:
  5934. return false;
  5935. case Type_Array:
  5936. case Type_Slice:
  5937. case Type_Struct:
  5938. case Type_Union:
  5939. case Type_Tuple:
  5940. case Type_DynamicArray:
  5941. case Type_Map:
  5942. case Type_SimdVector:
  5943. return true;
  5944. case Type_Named:
  5945. return lb_is_type_aggregate(t->Named.base);
  5946. }
  5947. return false;
  5948. }
  5949. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  5950. Type *src_type = value.type;
  5951. if (are_types_identical(t, src_type)) {
  5952. return value;
  5953. }
  5954. lbValue res = {};
  5955. res.type = t;
  5956. Type *src = base_type(src_type);
  5957. Type *dst = base_type(t);
  5958. lbModule *m = p->module;
  5959. i64 sz = type_size_of(src);
  5960. i64 dz = type_size_of(dst);
  5961. if (sz != dz) {
  5962. LLVMTypeRef s = lb_type(m, src);
  5963. LLVMTypeRef d = lb_type(m, dst);
  5964. i64 llvm_sz = lb_sizeof(s);
  5965. i64 llvm_dz = lb_sizeof(d);
  5966. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  5967. }
  5968. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5969. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5970. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5971. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5972. return res;
  5973. }
  5974. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5975. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5976. return res;
  5977. }
  5978. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5979. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5980. return res;
  5981. }
  5982. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5983. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5984. return res;
  5985. }
  5986. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5987. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5988. return res;
  5989. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5990. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5991. return res;
  5992. }
  5993. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5994. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  5995. return res;
  5996. }
  5997. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  5998. lbValue s = lb_address_from_load_or_generate_local(p, value);
  5999. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  6000. return lb_emit_load(p, d);
  6001. }
  6002. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  6003. // GB_PANIC("lb_emit_transmute");
  6004. return res;
  6005. }
  6006. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  6007. GB_ASSERT(addr.kind == lbAddr_Context);
  6008. GB_ASSERT(addr.ctx.sel.index.count == 0);
  6009. lbModule *m = p->module;
  6010. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6011. args[0] = addr.addr;
  6012. lb_emit_runtime_call(p, "__init_context", args);
  6013. }
  6014. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  6015. Type *pt = base_type(p->type);
  6016. GB_ASSERT(pt->kind == Type_Proc);
  6017. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  6018. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  6019. e->flags |= EntityFlag_NoAlias;
  6020. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  6021. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  6022. lbValue param = {context_ptr, e->type};
  6023. lb_add_entity(p->module, e, param);
  6024. lbAddr ctx_addr = {};
  6025. ctx_addr.kind = lbAddr_Context;
  6026. ctx_addr.addr = param;
  6027. lbContextData *cd = array_add_and_get(&p->context_stack);
  6028. cd->ctx = ctx_addr;
  6029. cd->scope_index = -1;
  6030. return cd;
  6031. }
  6032. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  6033. ctx.kind = lbAddr_Context;
  6034. lbContextData *cd = array_add_and_get(&p->context_stack);
  6035. cd->ctx = ctx;
  6036. cd->scope_index = p->scope_index;
  6037. return cd;
  6038. }
  6039. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  6040. if (p->context_stack.count > 0) {
  6041. return p->context_stack[p->context_stack.count-1].ctx;
  6042. }
  6043. Type *pt = base_type(p->type);
  6044. GB_ASSERT(pt->kind == Type_Proc);
  6045. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  6046. lbAddr c = lb_add_local_generated(p, t_context, true);
  6047. c.kind = lbAddr_Context;
  6048. lb_emit_init_context(p, c);
  6049. lb_push_context_onto_stack(p, c);
  6050. lb_add_debug_context_variable(p, c);
  6051. return c;
  6052. }
  6053. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  6054. if (LLVMIsALoadInst(value.value)) {
  6055. lbValue res = {};
  6056. res.value = LLVMGetOperand(value.value, 0);
  6057. res.type = alloc_type_pointer(value.type);
  6058. return res;
  6059. }
  6060. GB_ASSERT(is_type_typed(value.type));
  6061. lbAddr res = lb_add_local_generated(p, value.type, false);
  6062. lb_addr_store(p, res, value);
  6063. return res.addr;
  6064. }
  6065. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  6066. if (LLVMIsALoadInst(value.value)) {
  6067. lbValue res = {};
  6068. res.value = LLVMGetOperand(value.value, 0);
  6069. res.type = alloc_type_pointer(value.type);
  6070. return res;
  6071. }
  6072. GB_PANIC("lb_address_from_load");
  6073. return {};
  6074. }
  6075. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  6076. i64 type_alignment = type_align_of(new_type);
  6077. if (alignment < type_alignment) {
  6078. alignment = type_alignment;
  6079. }
  6080. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  6081. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  6082. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  6083. lb_addr_store(p, ptr, val);
  6084. // ptr.kind = lbAddr_Context;
  6085. return ptr.addr;
  6086. }
  6087. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  6088. GB_ASSERT(is_type_pointer(s.type));
  6089. Type *t = base_type(type_deref(s.type));
  6090. Type *result_type = nullptr;
  6091. if (is_type_relative_pointer(t)) {
  6092. s = lb_addr_get_ptr(p, lb_addr(s));
  6093. }
  6094. if (is_type_struct(t)) {
  6095. result_type = get_struct_field_type(t, index);
  6096. } else if (is_type_union(t)) {
  6097. GB_ASSERT(index == -1);
  6098. return lb_emit_union_tag_ptr(p, s);
  6099. } else if (is_type_tuple(t)) {
  6100. GB_ASSERT(t->Tuple.variables.count > 0);
  6101. result_type = t->Tuple.variables[index]->type;
  6102. } else if (is_type_complex(t)) {
  6103. Type *ft = base_complex_elem_type(t);
  6104. switch (index) {
  6105. case 0: result_type = ft; break;
  6106. case 1: result_type = ft; break;
  6107. }
  6108. } else if (is_type_quaternion(t)) {
  6109. Type *ft = base_complex_elem_type(t);
  6110. switch (index) {
  6111. case 0: result_type = ft; break;
  6112. case 1: result_type = ft; break;
  6113. case 2: result_type = ft; break;
  6114. case 3: result_type = ft; break;
  6115. }
  6116. } else if (is_type_slice(t)) {
  6117. switch (index) {
  6118. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6119. case 1: result_type = t_int; break;
  6120. }
  6121. } else if (is_type_string(t)) {
  6122. switch (index) {
  6123. case 0: result_type = t_u8_ptr; break;
  6124. case 1: result_type = t_int; break;
  6125. }
  6126. } else if (is_type_any(t)) {
  6127. switch (index) {
  6128. case 0: result_type = t_rawptr; break;
  6129. case 1: result_type = t_typeid; break;
  6130. }
  6131. } else if (is_type_dynamic_array(t)) {
  6132. switch (index) {
  6133. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6134. case 1: result_type = t_int; break;
  6135. case 2: result_type = t_int; break;
  6136. case 3: result_type = t_allocator; break;
  6137. }
  6138. } else if (is_type_map(t)) {
  6139. init_map_internal_types(t);
  6140. Type *itp = alloc_type_pointer(t->Map.internal_type);
  6141. s = lb_emit_transmute(p, s, itp);
  6142. Type *gst = t->Map.internal_type;
  6143. GB_ASSERT(gst->kind == Type_Struct);
  6144. switch (index) {
  6145. case 0: result_type = get_struct_field_type(gst, 0); break;
  6146. case 1: result_type = get_struct_field_type(gst, 1); break;
  6147. }
  6148. } else if (is_type_array(t)) {
  6149. return lb_emit_array_epi(p, s, index);
  6150. } else if (is_type_relative_slice(t)) {
  6151. switch (index) {
  6152. case 0: result_type = t->RelativeSlice.base_integer; break;
  6153. case 1: result_type = t->RelativeSlice.base_integer; break;
  6154. }
  6155. } else {
  6156. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  6157. }
  6158. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  6159. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6160. index += 1;
  6161. }
  6162. if (lb_is_const(s)) {
  6163. lbModule *m = p->module;
  6164. lbValue res = {};
  6165. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  6166. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6167. res.type = alloc_type_pointer(result_type);
  6168. return res;
  6169. } else {
  6170. lbValue res = {};
  6171. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  6172. res.type = alloc_type_pointer(result_type);
  6173. return res;
  6174. }
  6175. }
  6176. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  6177. if (LLVMIsALoadInst(s.value)) {
  6178. lbValue res = {};
  6179. res.value = LLVMGetOperand(s.value, 0);
  6180. res.type = alloc_type_pointer(s.type);
  6181. lbValue ptr = lb_emit_struct_ep(p, res, index);
  6182. return lb_emit_load(p, ptr);
  6183. }
  6184. Type *t = base_type(s.type);
  6185. Type *result_type = nullptr;
  6186. switch (t->kind) {
  6187. case Type_Basic:
  6188. switch (t->Basic.kind) {
  6189. case Basic_string:
  6190. switch (index) {
  6191. case 0: result_type = t_u8_ptr; break;
  6192. case 1: result_type = t_int; break;
  6193. }
  6194. break;
  6195. case Basic_any:
  6196. switch (index) {
  6197. case 0: result_type = t_rawptr; break;
  6198. case 1: result_type = t_typeid; break;
  6199. }
  6200. break;
  6201. case Basic_complex64: case Basic_complex128:
  6202. {
  6203. Type *ft = base_complex_elem_type(t);
  6204. switch (index) {
  6205. case 0: result_type = ft; break;
  6206. case 1: result_type = ft; break;
  6207. }
  6208. break;
  6209. }
  6210. case Basic_quaternion128: case Basic_quaternion256:
  6211. {
  6212. Type *ft = base_complex_elem_type(t);
  6213. switch (index) {
  6214. case 0: result_type = ft; break;
  6215. case 1: result_type = ft; break;
  6216. case 2: result_type = ft; break;
  6217. case 3: result_type = ft; break;
  6218. }
  6219. break;
  6220. }
  6221. }
  6222. break;
  6223. case Type_Struct:
  6224. result_type = get_struct_field_type(t, index);
  6225. break;
  6226. case Type_Union:
  6227. GB_ASSERT(index == -1);
  6228. // return lb_emit_union_tag_value(p, s);
  6229. GB_PANIC("lb_emit_union_tag_value");
  6230. case Type_Tuple:
  6231. GB_ASSERT(t->Tuple.variables.count > 0);
  6232. result_type = t->Tuple.variables[index]->type;
  6233. if (t->Tuple.variables.count == 1) {
  6234. return s;
  6235. }
  6236. break;
  6237. case Type_Slice:
  6238. switch (index) {
  6239. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6240. case 1: result_type = t_int; break;
  6241. }
  6242. break;
  6243. case Type_DynamicArray:
  6244. switch (index) {
  6245. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6246. case 1: result_type = t_int; break;
  6247. case 2: result_type = t_int; break;
  6248. case 3: result_type = t_allocator; break;
  6249. }
  6250. break;
  6251. case Type_Map:
  6252. {
  6253. init_map_internal_types(t);
  6254. Type *gst = t->Map.generated_struct_type;
  6255. switch (index) {
  6256. case 0: result_type = get_struct_field_type(gst, 0); break;
  6257. case 1: result_type = get_struct_field_type(gst, 1); break;
  6258. }
  6259. }
  6260. break;
  6261. case Type_Array:
  6262. result_type = t->Array.elem;
  6263. break;
  6264. default:
  6265. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  6266. break;
  6267. }
  6268. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  6269. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6270. index += 1;
  6271. }
  6272. lbValue res = {};
  6273. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  6274. res.type = result_type;
  6275. return res;
  6276. }
  6277. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  6278. GB_ASSERT(sel.index.count > 0);
  6279. Type *type = type_deref(e.type);
  6280. for_array(i, sel.index) {
  6281. i32 index = cast(i32)sel.index[i];
  6282. if (is_type_pointer(type)) {
  6283. type = type_deref(type);
  6284. e = lb_emit_load(p, e);
  6285. }
  6286. type = core_type(type);
  6287. if (is_type_quaternion(type)) {
  6288. e = lb_emit_struct_ep(p, e, index);
  6289. } else if (is_type_raw_union(type)) {
  6290. type = get_struct_field_type(type, index);
  6291. GB_ASSERT(is_type_pointer(e.type));
  6292. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  6293. } else if (is_type_struct(type)) {
  6294. type = get_struct_field_type(type, index);
  6295. e = lb_emit_struct_ep(p, e, index);
  6296. } else if (type->kind == Type_Union) {
  6297. GB_ASSERT(index == -1);
  6298. type = t_type_info_ptr;
  6299. e = lb_emit_struct_ep(p, e, index);
  6300. } else if (type->kind == Type_Tuple) {
  6301. type = type->Tuple.variables[index]->type;
  6302. e = lb_emit_struct_ep(p, e, index);
  6303. } else if (type->kind == Type_Basic) {
  6304. switch (type->Basic.kind) {
  6305. case Basic_any: {
  6306. if (index == 0) {
  6307. type = t_rawptr;
  6308. } else if (index == 1) {
  6309. type = t_type_info_ptr;
  6310. }
  6311. e = lb_emit_struct_ep(p, e, index);
  6312. break;
  6313. }
  6314. case Basic_string:
  6315. e = lb_emit_struct_ep(p, e, index);
  6316. break;
  6317. default:
  6318. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6319. break;
  6320. }
  6321. } else if (type->kind == Type_Slice) {
  6322. e = lb_emit_struct_ep(p, e, index);
  6323. } else if (type->kind == Type_DynamicArray) {
  6324. e = lb_emit_struct_ep(p, e, index);
  6325. } else if (type->kind == Type_Array) {
  6326. e = lb_emit_array_epi(p, e, index);
  6327. } else if (type->kind == Type_Map) {
  6328. e = lb_emit_struct_ep(p, e, index);
  6329. } else if (type->kind == Type_RelativePointer) {
  6330. e = lb_emit_struct_ep(p, e, index);
  6331. } else {
  6332. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6333. }
  6334. }
  6335. return e;
  6336. }
  6337. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6338. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6339. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6340. return lb_emit_load(p, res);
  6341. }
  6342. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  6343. // NOTE(bill): The prev block may defer injection before it's terminator
  6344. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6345. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6346. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6347. return;
  6348. }
  6349. isize prev_context_stack_count = p->context_stack.count;
  6350. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  6351. defer (p->context_stack.count = prev_context_stack_count);
  6352. p->context_stack.count = d.context_stack_count;
  6353. lbBlock *b = lb_create_block(p, "defer");
  6354. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6355. lb_emit_jump(p, b);
  6356. }
  6357. lb_start_block(p, b);
  6358. if (d.kind == lbDefer_Node) {
  6359. lb_build_stmt(p, d.stmt);
  6360. } else if (d.kind == lbDefer_Instr) {
  6361. // NOTE(bill): Need to make a new copy
  6362. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6363. LLVMInsertIntoBuilder(p->builder, instr);
  6364. } else if (d.kind == lbDefer_Proc) {
  6365. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6366. }
  6367. }
  6368. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6369. isize count = p->defer_stmts.count;
  6370. isize i = count;
  6371. while (i --> 0) {
  6372. lbDefer const &d = p->defer_stmts[i];
  6373. if (kind == lbDeferExit_Default) {
  6374. if (p->scope_index == d.scope_index &&
  6375. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6376. lb_build_defer_stmt(p, d);
  6377. array_pop(&p->defer_stmts);
  6378. continue;
  6379. } else {
  6380. break;
  6381. }
  6382. } else if (kind == lbDeferExit_Return) {
  6383. lb_build_defer_stmt(p, d);
  6384. } else if (kind == lbDeferExit_Branch) {
  6385. GB_ASSERT(block != nullptr);
  6386. isize lower_limit = block->scope_index;
  6387. if (lower_limit < d.scope_index) {
  6388. lb_build_defer_stmt(p, d);
  6389. }
  6390. }
  6391. }
  6392. }
  6393. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  6394. Type *pt = base_type(p->type);
  6395. GB_ASSERT(pt->kind == Type_Proc);
  6396. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6397. GB_ASSERT(p->context_stack.count != 0);
  6398. }
  6399. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6400. d->kind = lbDefer_Node;
  6401. d->scope_index = scope_index;
  6402. d->context_stack_count = p->context_stack.count;
  6403. d->block = p->curr_block;
  6404. d->stmt = stmt;
  6405. }
  6406. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  6407. Type *pt = base_type(p->type);
  6408. GB_ASSERT(pt->kind == Type_Proc);
  6409. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6410. GB_ASSERT(p->context_stack.count != 0);
  6411. }
  6412. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6413. d->kind = lbDefer_Proc;
  6414. d->scope_index = p->scope_index;
  6415. d->block = p->curr_block;
  6416. d->context_stack_count = p->context_stack.count;
  6417. d->proc.deferred = deferred;
  6418. d->proc.result_as_args = result_as_args;
  6419. }
  6420. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  6421. Array<lbValue> array = {};
  6422. Type *t = base_type(value.type);
  6423. if (t == nullptr) {
  6424. // Do nothing
  6425. } else if (is_type_tuple(t)) {
  6426. GB_ASSERT(t->kind == Type_Tuple);
  6427. auto *rt = &t->Tuple;
  6428. if (rt->variables.count > 0) {
  6429. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  6430. for_array(i, rt->variables) {
  6431. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  6432. array[i] = elem;
  6433. }
  6434. }
  6435. } else {
  6436. array = array_make<lbValue>(permanent_allocator(), 1);
  6437. array[0] = value;
  6438. }
  6439. return array;
  6440. }
  6441. 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) {
  6442. unsigned arg_count = cast(unsigned)processed_args.count;
  6443. if (return_ptr.value != nullptr) {
  6444. arg_count += 1;
  6445. }
  6446. if (context_ptr.addr.value != nullptr) {
  6447. arg_count += 1;
  6448. }
  6449. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  6450. isize arg_index = 0;
  6451. if (return_ptr.value != nullptr) {
  6452. args[arg_index++] = return_ptr.value;
  6453. }
  6454. for_array(i, processed_args) {
  6455. lbValue arg = processed_args[i];
  6456. args[arg_index++] = arg.value;
  6457. }
  6458. if (context_ptr.addr.value != nullptr) {
  6459. LLVMValueRef cp = context_ptr.addr.value;
  6460. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  6461. args[arg_index++] = cp;
  6462. }
  6463. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  6464. GB_ASSERT(curr_block != p->decl_block->block);
  6465. {
  6466. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6467. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6468. LLVMValueRef fn = value.value;
  6469. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6470. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6471. }
  6472. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6473. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6474. LLVMValueRef ret = LLVMBuildCall2(p->builder, ft, fn, args, arg_count, "");;
  6475. lbValue res = {};
  6476. res.value = ret;
  6477. res.type = abi_rt;
  6478. return res;
  6479. }
  6480. }
  6481. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6482. // LLVMMetadataRef curr_loc = LLVMGetCurrentDebugLocation2(p->builder);
  6483. // LLVMSetCurrentDebugLocation2(p->builder, nullptr);
  6484. // defer (if (curr_loc) {
  6485. // LLVMSetCurrentDebugLocation2(p->builder, curr_loc);
  6486. // });
  6487. String name = make_string_c(c_name);
  6488. AstPackage *pkg = p->module->info->runtime_package;
  6489. Entity *e = scope_lookup_current(pkg->scope, name);
  6490. lbValue *found = nullptr;
  6491. if (p->module != e->code_gen_module) {
  6492. gb_mutex_lock(&p->module->mutex);
  6493. }
  6494. GB_ASSERT(e->code_gen_module != nullptr);
  6495. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6496. if (p->module != e->code_gen_module) {
  6497. gb_mutex_unlock(&p->module->mutex);
  6498. }
  6499. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6500. return lb_emit_call(p, *found, args);
  6501. }
  6502. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6503. lbModule *m = p->module;
  6504. Type *pt = base_type(value.type);
  6505. GB_ASSERT(pt->kind == Type_Proc);
  6506. Type *results = pt->Proc.results;
  6507. if (p->entity != nullptr) {
  6508. if (p->entity->flags & EntityFlag_Disabled) {
  6509. return {};
  6510. }
  6511. }
  6512. lbAddr context_ptr = {};
  6513. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6514. context_ptr = lb_find_or_generate_context_ptr(p);
  6515. }
  6516. defer (if (pt->Proc.diverging) {
  6517. LLVMBuildUnreachable(p->builder);
  6518. });
  6519. set_procedure_abi_types(pt);
  6520. bool is_c_vararg = pt->Proc.c_vararg;
  6521. isize param_count = pt->Proc.param_count;
  6522. if (is_c_vararg) {
  6523. GB_ASSERT(param_count-1 <= args.count);
  6524. param_count -= 1;
  6525. } else {
  6526. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6527. }
  6528. lbValue result = {};
  6529. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6530. {
  6531. lbFunctionType **ft_found = nullptr;
  6532. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6533. if (!ft_found) {
  6534. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6535. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6536. }
  6537. GB_ASSERT(ft_found != nullptr);
  6538. lbFunctionType *ft = *ft_found;
  6539. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6540. unsigned param_index = 0;
  6541. for (isize i = 0; i < param_count; i++) {
  6542. Entity *e = pt->Proc.params->Tuple.variables[i];
  6543. if (e->kind != Entity_Variable) {
  6544. continue;
  6545. }
  6546. GB_ASSERT(e->flags & EntityFlag_Param);
  6547. Type *original_type = e->type;
  6548. lbArgType *arg = &ft->args[param_index];
  6549. if (arg->kind == lbArg_Ignore) {
  6550. continue;
  6551. }
  6552. lbValue x = lb_emit_conv(p, args[i], original_type);
  6553. LLVMTypeRef xt = lb_type(p->module, x.type);
  6554. if (arg->kind == lbArg_Direct) {
  6555. LLVMTypeRef abi_type = arg->cast_type;
  6556. if (!abi_type) {
  6557. abi_type = arg->type;
  6558. }
  6559. if (xt == abi_type) {
  6560. array_add(&processed_args, x);
  6561. } else {
  6562. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6563. array_add(&processed_args, x);
  6564. }
  6565. } else if (arg->kind == lbArg_Indirect) {
  6566. lbValue ptr = {};
  6567. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6568. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6569. // i.e. `T const &` in C++
  6570. ptr = lb_address_from_load_or_generate_local(p, x);
  6571. } else {
  6572. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6573. }
  6574. array_add(&processed_args, ptr);
  6575. }
  6576. param_index += 1;
  6577. }
  6578. if (inlining == ProcInlining_none) {
  6579. inlining = p->inlining;
  6580. }
  6581. Type *rt = reduce_tuple_to_single_type(results);
  6582. if (return_by_pointer) {
  6583. lbValue return_ptr = {};
  6584. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6585. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6586. return_ptr = p->return_ptr_hint_value;
  6587. p->return_ptr_hint_used = true;
  6588. }
  6589. }
  6590. if (return_ptr.value == nullptr) {
  6591. lbAddr r = lb_add_local_generated(p, rt, true);
  6592. return_ptr = r.addr;
  6593. }
  6594. GB_ASSERT(is_type_pointer(return_ptr.type));
  6595. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6596. result = lb_emit_load(p, return_ptr);
  6597. } else if (rt != nullptr) {
  6598. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  6599. if (ft->ret.cast_type) {
  6600. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  6601. }
  6602. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  6603. result.type = rt;
  6604. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  6605. result.type = t_llvm_bool;
  6606. }
  6607. if (!is_type_tuple(rt)) {
  6608. result = lb_emit_conv(p, result, rt);
  6609. }
  6610. } else {
  6611. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  6612. }
  6613. }
  6614. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6615. if (found != nullptr) {
  6616. Entity *e = *found;
  6617. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6618. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6619. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6620. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6621. GB_ASSERT(deferred_found != nullptr);
  6622. lbValue deferred = *deferred_found;
  6623. auto in_args = args;
  6624. Array<lbValue> result_as_args = {};
  6625. switch (kind) {
  6626. case DeferredProcedure_none:
  6627. break;
  6628. case DeferredProcedure_in:
  6629. result_as_args = in_args;
  6630. break;
  6631. case DeferredProcedure_out:
  6632. result_as_args = lb_value_to_array(p, result);
  6633. break;
  6634. case DeferredProcedure_in_out:
  6635. {
  6636. auto out_args = lb_value_to_array(p, result);
  6637. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  6638. array_copy(&result_as_args, in_args, 0);
  6639. array_copy(&result_as_args, out_args, in_args.count);
  6640. }
  6641. break;
  6642. }
  6643. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6644. }
  6645. }
  6646. return result;
  6647. }
  6648. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6649. Type *t = s.type;
  6650. GB_ASSERT(is_type_pointer(t));
  6651. Type *st = base_type(type_deref(t));
  6652. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6653. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6654. LLVMValueRef indices[2] = {};
  6655. indices[0] = llvm_zero(p->module);
  6656. indices[1] = lb_emit_conv(p, index, t_int).value;
  6657. Type *ptr = base_array_type(st);
  6658. lbValue res = {};
  6659. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6660. res.type = alloc_type_pointer(ptr);
  6661. return res;
  6662. }
  6663. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6664. Type *t = s.type;
  6665. GB_ASSERT(is_type_pointer(t));
  6666. Type *st = base_type(type_deref(t));
  6667. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6668. GB_ASSERT(0 <= index);
  6669. Type *ptr = base_array_type(st);
  6670. LLVMValueRef indices[2] = {
  6671. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6672. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6673. };
  6674. lbValue res = {};
  6675. if (lb_is_const(s)) {
  6676. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6677. } else {
  6678. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6679. }
  6680. res.type = alloc_type_pointer(ptr);
  6681. return res;
  6682. }
  6683. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6684. LLVMValueRef indices[1] = {index.value};
  6685. lbValue res = {};
  6686. res.type = ptr.type;
  6687. if (lb_is_const(ptr) && lb_is_const(index)) {
  6688. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6689. } else {
  6690. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6691. }
  6692. return res;
  6693. }
  6694. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  6695. GB_ASSERT(is_type_pointer(data.type));
  6696. GB_ASSERT(are_types_identical(len.type, t_int));
  6697. LLVMValueRef vals[2] = {
  6698. data.value,
  6699. len.value,
  6700. };
  6701. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  6702. }
  6703. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6704. Type *t = lb_addr_type(slice);
  6705. GB_ASSERT(is_type_slice(t));
  6706. lbValue ptr = lb_addr_get_ptr(p, slice);
  6707. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6708. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6709. }
  6710. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6711. Type *t = lb_addr_type(string);
  6712. GB_ASSERT(is_type_string(t));
  6713. lbValue ptr = lb_addr_get_ptr(p, string);
  6714. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6715. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6716. }
  6717. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6718. Type *t = base_type(string.type);
  6719. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6720. return lb_emit_struct_ev(p, string, 0);
  6721. }
  6722. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6723. Type *t = base_type(string.type);
  6724. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6725. return lb_emit_struct_ev(p, string, 1);
  6726. }
  6727. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6728. GB_ASSERT(is_type_cstring(value.type));
  6729. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6730. args[0] = lb_emit_conv(p, value, t_cstring);
  6731. return lb_emit_runtime_call(p, "cstring_len", args);
  6732. }
  6733. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6734. Type *t = type_deref(array_ptr.type);
  6735. GB_ASSERT(is_type_array(t));
  6736. return lb_emit_struct_ep(p, array_ptr, 0);
  6737. }
  6738. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6739. GB_ASSERT(is_type_slice(slice.type));
  6740. return lb_emit_struct_ev(p, slice, 0);
  6741. }
  6742. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6743. GB_ASSERT(is_type_slice(slice.type));
  6744. return lb_emit_struct_ev(p, slice, 1);
  6745. }
  6746. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6747. GB_ASSERT(is_type_dynamic_array(da.type));
  6748. return lb_emit_struct_ev(p, da, 0);
  6749. }
  6750. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6751. GB_ASSERT(is_type_dynamic_array(da.type));
  6752. return lb_emit_struct_ev(p, da, 1);
  6753. }
  6754. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6755. GB_ASSERT(is_type_dynamic_array(da.type));
  6756. return lb_emit_struct_ev(p, da, 2);
  6757. }
  6758. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6759. GB_ASSERT(is_type_dynamic_array(da.type));
  6760. return lb_emit_struct_ev(p, da, 3);
  6761. }
  6762. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6763. Type *t = base_type(value.type);
  6764. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6765. init_map_internal_types(t);
  6766. Type *gst = t->Map.generated_struct_type;
  6767. i32 index = 1;
  6768. lbValue entries = lb_emit_struct_ev(p, value, index);
  6769. return entries;
  6770. }
  6771. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6772. Type *t = base_type(type_deref(value.type));
  6773. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6774. init_map_internal_types(t);
  6775. Type *gst = t->Map.generated_struct_type;
  6776. i32 index = 1;
  6777. lbValue entries = lb_emit_struct_ep(p, value, index);
  6778. return entries;
  6779. }
  6780. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  6781. lbValue entries = lb_map_entries(p, value);
  6782. return lb_dynamic_array_len(p, entries);
  6783. }
  6784. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  6785. lbValue entries = lb_map_entries(p, value);
  6786. return lb_dynamic_array_cap(p, entries);
  6787. }
  6788. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  6789. Type *t = base_type(value.type);
  6790. bool is_ptr = false;
  6791. if (is_type_pointer(t)) {
  6792. is_ptr = true;
  6793. t = base_type(type_deref(t));
  6794. }
  6795. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6796. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6797. }
  6798. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  6799. t->Struct.soa_kind == StructSoa_Dynamic);
  6800. isize n = 0;
  6801. Type *elem = base_type(t->Struct.soa_elem);
  6802. if (elem->kind == Type_Struct) {
  6803. n = elem->Struct.fields.count;
  6804. } else if (elem->kind == Type_Array) {
  6805. n = elem->Array.count;
  6806. } else {
  6807. GB_PANIC("Unreachable");
  6808. }
  6809. if (is_ptr) {
  6810. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6811. return lb_emit_load(p, v);
  6812. }
  6813. return lb_emit_struct_ev(p, value, cast(i32)n);
  6814. }
  6815. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  6816. Type *t = base_type(value.type);
  6817. bool is_ptr = false;
  6818. if (is_type_pointer(t)) {
  6819. is_ptr = true;
  6820. t = base_type(type_deref(t));
  6821. }
  6822. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6823. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6824. }
  6825. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  6826. isize n = 0;
  6827. Type *elem = base_type(t->Struct.soa_elem);
  6828. if (elem->kind == Type_Struct) {
  6829. n = elem->Struct.fields.count+1;
  6830. } else if (elem->kind == Type_Array) {
  6831. n = elem->Array.count+1;
  6832. } else {
  6833. GB_PANIC("Unreachable");
  6834. }
  6835. if (is_ptr) {
  6836. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6837. return lb_emit_load(p, v);
  6838. }
  6839. return lb_emit_struct_ev(p, value, cast(i32)n);
  6840. }
  6841. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  6842. ast_node(ce, CallExpr, expr);
  6843. switch (id) {
  6844. case BuiltinProc_DIRECTIVE: {
  6845. ast_node(bd, BasicDirective, ce->proc);
  6846. String name = bd->name;
  6847. GB_ASSERT(name == "location");
  6848. String procedure = p->entity->token.string;
  6849. TokenPos pos = ast_token(ce->proc).pos;
  6850. if (ce->args.count > 0) {
  6851. Ast *ident = unselector_expr(ce->args[0]);
  6852. GB_ASSERT(ident->kind == Ast_Ident);
  6853. Entity *e = entity_of_node(ident);
  6854. GB_ASSERT(e != nullptr);
  6855. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  6856. procedure = e->parent_proc_decl->entity->token.string;
  6857. } else {
  6858. procedure = str_lit("");
  6859. }
  6860. pos = e->token.pos;
  6861. }
  6862. return lb_emit_source_code_location(p, procedure, pos);
  6863. }
  6864. case BuiltinProc_type_info_of: {
  6865. Ast *arg = ce->args[0];
  6866. TypeAndValue tav = type_and_value_of_expr(arg);
  6867. if (tav.mode == Addressing_Type) {
  6868. Type *t = default_type(type_of_expr(arg));
  6869. return lb_type_info(p->module, t);
  6870. }
  6871. GB_ASSERT(is_type_typeid(tav.type));
  6872. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6873. args[0] = lb_build_expr(p, arg);
  6874. return lb_emit_runtime_call(p, "__type_info_of", args);
  6875. }
  6876. case BuiltinProc_typeid_of: {
  6877. Ast *arg = ce->args[0];
  6878. TypeAndValue tav = type_and_value_of_expr(arg);
  6879. GB_ASSERT(tav.mode == Addressing_Type);
  6880. Type *t = default_type(type_of_expr(arg));
  6881. return lb_typeid(p->module, t);
  6882. }
  6883. case BuiltinProc_len: {
  6884. lbValue v = lb_build_expr(p, ce->args[0]);
  6885. Type *t = base_type(v.type);
  6886. if (is_type_pointer(t)) {
  6887. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6888. v = lb_emit_load(p, v);
  6889. t = type_deref(t);
  6890. }
  6891. if (is_type_cstring(t)) {
  6892. return lb_cstring_len(p, v);
  6893. } else if (is_type_string(t)) {
  6894. return lb_string_len(p, v);
  6895. } else if (is_type_array(t)) {
  6896. GB_PANIC("Array lengths are constant");
  6897. } else if (is_type_slice(t)) {
  6898. return lb_slice_len(p, v);
  6899. } else if (is_type_dynamic_array(t)) {
  6900. return lb_dynamic_array_len(p, v);
  6901. } else if (is_type_map(t)) {
  6902. return lb_map_len(p, v);
  6903. } else if (is_type_soa_struct(t)) {
  6904. return lb_soa_struct_len(p, v);
  6905. }
  6906. GB_PANIC("Unreachable");
  6907. break;
  6908. }
  6909. case BuiltinProc_cap: {
  6910. lbValue v = lb_build_expr(p, ce->args[0]);
  6911. Type *t = base_type(v.type);
  6912. if (is_type_pointer(t)) {
  6913. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6914. v = lb_emit_load(p, v);
  6915. t = type_deref(t);
  6916. }
  6917. if (is_type_string(t)) {
  6918. GB_PANIC("Unreachable");
  6919. } else if (is_type_array(t)) {
  6920. GB_PANIC("Array lengths are constant");
  6921. } else if (is_type_slice(t)) {
  6922. return lb_slice_len(p, v);
  6923. } else if (is_type_dynamic_array(t)) {
  6924. return lb_dynamic_array_cap(p, v);
  6925. } else if (is_type_map(t)) {
  6926. return lb_map_cap(p, v);
  6927. } else if (is_type_soa_struct(t)) {
  6928. return lb_soa_struct_cap(p, v);
  6929. }
  6930. GB_PANIC("Unreachable");
  6931. break;
  6932. }
  6933. case BuiltinProc_swizzle: {
  6934. isize index_count = ce->args.count-1;
  6935. if (is_type_simd_vector(tv.type)) {
  6936. lbValue vec = lb_build_expr(p, ce->args[0]);
  6937. if (index_count == 0) {
  6938. return vec;
  6939. }
  6940. unsigned mask_len = cast(unsigned)index_count;
  6941. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  6942. for (isize i = 1; i < ce->args.count; i++) {
  6943. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6944. GB_ASSERT(is_type_integer(tv.type));
  6945. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6946. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  6947. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  6948. }
  6949. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  6950. LLVMValueRef v1 = vec.value;
  6951. LLVMValueRef v2 = vec.value;
  6952. lbValue res = {};
  6953. res.type = tv.type;
  6954. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  6955. return res;
  6956. }
  6957. lbAddr addr = lb_build_addr(p, ce->args[0]);
  6958. if (index_count == 0) {
  6959. return lb_addr_load(p, addr);
  6960. }
  6961. lbValue src = lb_addr_get_ptr(p, addr);
  6962. // TODO(bill): Should this be zeroed or not?
  6963. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  6964. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  6965. for (i32 i = 1; i < ce->args.count; i++) {
  6966. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6967. GB_ASSERT(is_type_integer(tv.type));
  6968. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6969. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  6970. i32 dst_index = i-1;
  6971. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  6972. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  6973. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  6974. }
  6975. return lb_addr_load(p, dst);
  6976. }
  6977. case BuiltinProc_complex: {
  6978. lbValue real = lb_build_expr(p, ce->args[0]);
  6979. lbValue imag = lb_build_expr(p, ce->args[1]);
  6980. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6981. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6982. Type *ft = base_complex_elem_type(tv.type);
  6983. real = lb_emit_conv(p, real, ft);
  6984. imag = lb_emit_conv(p, imag, ft);
  6985. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  6986. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  6987. return lb_emit_load(p, dst);
  6988. }
  6989. case BuiltinProc_quaternion: {
  6990. lbValue real = lb_build_expr(p, ce->args[0]);
  6991. lbValue imag = lb_build_expr(p, ce->args[1]);
  6992. lbValue jmag = lb_build_expr(p, ce->args[2]);
  6993. lbValue kmag = lb_build_expr(p, ce->args[3]);
  6994. // @QuaternionLayout
  6995. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6996. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6997. Type *ft = base_complex_elem_type(tv.type);
  6998. real = lb_emit_conv(p, real, ft);
  6999. imag = lb_emit_conv(p, imag, ft);
  7000. jmag = lb_emit_conv(p, jmag, ft);
  7001. kmag = lb_emit_conv(p, kmag, ft);
  7002. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  7003. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  7004. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  7005. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  7006. return lb_emit_load(p, dst);
  7007. }
  7008. case BuiltinProc_real: {
  7009. lbValue val = lb_build_expr(p, ce->args[0]);
  7010. if (is_type_complex(val.type)) {
  7011. lbValue real = lb_emit_struct_ev(p, val, 0);
  7012. return lb_emit_conv(p, real, tv.type);
  7013. } else if (is_type_quaternion(val.type)) {
  7014. // @QuaternionLayout
  7015. lbValue real = lb_emit_struct_ev(p, val, 3);
  7016. return lb_emit_conv(p, real, tv.type);
  7017. }
  7018. GB_PANIC("invalid type for real");
  7019. return {};
  7020. }
  7021. case BuiltinProc_imag: {
  7022. lbValue val = lb_build_expr(p, ce->args[0]);
  7023. if (is_type_complex(val.type)) {
  7024. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7025. return lb_emit_conv(p, imag, tv.type);
  7026. } else if (is_type_quaternion(val.type)) {
  7027. // @QuaternionLayout
  7028. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7029. return lb_emit_conv(p, imag, tv.type);
  7030. }
  7031. GB_PANIC("invalid type for imag");
  7032. return {};
  7033. }
  7034. case BuiltinProc_jmag: {
  7035. lbValue val = lb_build_expr(p, ce->args[0]);
  7036. if (is_type_quaternion(val.type)) {
  7037. // @QuaternionLayout
  7038. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7039. return lb_emit_conv(p, imag, tv.type);
  7040. }
  7041. GB_PANIC("invalid type for jmag");
  7042. return {};
  7043. }
  7044. case BuiltinProc_kmag: {
  7045. lbValue val = lb_build_expr(p, ce->args[0]);
  7046. if (is_type_quaternion(val.type)) {
  7047. // @QuaternionLayout
  7048. lbValue imag = lb_emit_struct_ev(p, val, 2);
  7049. return lb_emit_conv(p, imag, tv.type);
  7050. }
  7051. GB_PANIC("invalid type for kmag");
  7052. return {};
  7053. }
  7054. case BuiltinProc_conj: {
  7055. lbValue val = lb_build_expr(p, ce->args[0]);
  7056. lbValue res = {};
  7057. Type *t = val.type;
  7058. if (is_type_complex(t)) {
  7059. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7060. lbValue real = lb_emit_struct_ev(p, val, 0);
  7061. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7062. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7063. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  7064. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  7065. } else if (is_type_quaternion(t)) {
  7066. // @QuaternionLayout
  7067. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7068. lbValue real = lb_emit_struct_ev(p, val, 3);
  7069. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7070. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  7071. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  7072. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7073. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  7074. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  7075. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  7076. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  7077. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  7078. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  7079. }
  7080. return lb_emit_load(p, res);
  7081. }
  7082. case BuiltinProc_expand_to_tuple: {
  7083. lbValue val = lb_build_expr(p, ce->args[0]);
  7084. Type *t = base_type(val.type);
  7085. if (!is_type_tuple(tv.type)) {
  7086. if (t->kind == Type_Struct) {
  7087. GB_ASSERT(t->Struct.fields.count == 1);
  7088. return lb_emit_struct_ev(p, val, 0);
  7089. } else if (t->kind == Type_Array) {
  7090. GB_ASSERT(t->Array.count == 1);
  7091. return lb_emit_array_epi(p, val, 0);
  7092. } else {
  7093. GB_PANIC("Unknown type of expand_to_tuple");
  7094. }
  7095. }
  7096. GB_ASSERT(is_type_tuple(tv.type));
  7097. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7098. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7099. if (t->kind == Type_Struct) {
  7100. for_array(src_index, t->Struct.fields) {
  7101. Entity *field = t->Struct.fields[src_index];
  7102. i32 field_index = field->Variable.field_index;
  7103. lbValue f = lb_emit_struct_ev(p, val, field_index);
  7104. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  7105. lb_emit_store(p, ep, f);
  7106. }
  7107. } else if (t->kind == Type_Array) {
  7108. // TODO(bill): Clean-up this code
  7109. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  7110. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  7111. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  7112. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  7113. lb_emit_store(p, ep, f);
  7114. }
  7115. } else {
  7116. GB_PANIC("Unknown type of expand_to_tuple");
  7117. }
  7118. return lb_emit_load(p, tuple);
  7119. }
  7120. case BuiltinProc_min: {
  7121. Type *t = type_of_expr(expr);
  7122. if (ce->args.count == 2) {
  7123. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7124. } else {
  7125. lbValue x = lb_build_expr(p, ce->args[0]);
  7126. for (isize i = 1; i < ce->args.count; i++) {
  7127. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  7128. }
  7129. return x;
  7130. }
  7131. }
  7132. case BuiltinProc_max: {
  7133. Type *t = type_of_expr(expr);
  7134. if (ce->args.count == 2) {
  7135. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7136. } else {
  7137. lbValue x = lb_build_expr(p, ce->args[0]);
  7138. for (isize i = 1; i < ce->args.count; i++) {
  7139. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  7140. }
  7141. return x;
  7142. }
  7143. }
  7144. case BuiltinProc_abs: {
  7145. lbValue x = lb_build_expr(p, ce->args[0]);
  7146. Type *t = x.type;
  7147. if (is_type_unsigned(t)) {
  7148. return x;
  7149. }
  7150. if (is_type_quaternion(t)) {
  7151. i64 sz = 8*type_size_of(t);
  7152. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7153. args[0] = x;
  7154. switch (sz) {
  7155. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  7156. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  7157. }
  7158. GB_PANIC("Unknown complex type");
  7159. } else if (is_type_complex(t)) {
  7160. i64 sz = 8*type_size_of(t);
  7161. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7162. args[0] = x;
  7163. switch (sz) {
  7164. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  7165. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  7166. }
  7167. GB_PANIC("Unknown complex type");
  7168. } else if (is_type_float(t)) {
  7169. i64 sz = 8*type_size_of(t);
  7170. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7171. args[0] = x;
  7172. switch (sz) {
  7173. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  7174. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  7175. }
  7176. GB_PANIC("Unknown float type");
  7177. }
  7178. lbValue zero = lb_const_nil(p->module, t);
  7179. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  7180. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  7181. return lb_emit_select(p, cond, neg, x);
  7182. }
  7183. case BuiltinProc_clamp:
  7184. return lb_emit_clamp(p, type_of_expr(expr),
  7185. lb_build_expr(p, ce->args[0]),
  7186. lb_build_expr(p, ce->args[1]),
  7187. lb_build_expr(p, ce->args[2]));
  7188. // "Intrinsics"
  7189. case BuiltinProc_alloca:
  7190. {
  7191. lbValue sz = lb_build_expr(p, ce->args[0]);
  7192. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  7193. lbValue res = {};
  7194. res.type = t_u8_ptr;
  7195. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  7196. LLVMSetAlignment(res.value, cast(unsigned)al);
  7197. return res;
  7198. }
  7199. case BuiltinProc_cpu_relax:
  7200. if (build_context.metrics.arch == TargetArch_386 ||
  7201. build_context.metrics.arch == TargetArch_amd64) {
  7202. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7203. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7204. cast(char *)"pause", 5,
  7205. cast(char *)"", 0,
  7206. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7207. LLVMInlineAsmDialectATT
  7208. );
  7209. GB_ASSERT(the_asm != nullptr);
  7210. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7211. }
  7212. return {};
  7213. case BuiltinProc_atomic_fence:
  7214. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  7215. return {};
  7216. case BuiltinProc_atomic_fence_acq:
  7217. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  7218. return {};
  7219. case BuiltinProc_atomic_fence_rel:
  7220. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  7221. return {};
  7222. case BuiltinProc_atomic_fence_acqrel:
  7223. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  7224. return {};
  7225. case BuiltinProc_volatile_store:
  7226. case BuiltinProc_atomic_store:
  7227. case BuiltinProc_atomic_store_rel:
  7228. case BuiltinProc_atomic_store_relaxed:
  7229. case BuiltinProc_atomic_store_unordered: {
  7230. lbValue dst = lb_build_expr(p, ce->args[0]);
  7231. lbValue val = lb_build_expr(p, ce->args[1]);
  7232. val = lb_emit_conv(p, val, type_deref(dst.type));
  7233. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  7234. switch (id) {
  7235. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  7236. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7237. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  7238. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7239. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7240. }
  7241. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7242. return {};
  7243. }
  7244. case BuiltinProc_volatile_load:
  7245. case BuiltinProc_atomic_load:
  7246. case BuiltinProc_atomic_load_acq:
  7247. case BuiltinProc_atomic_load_relaxed:
  7248. case BuiltinProc_atomic_load_unordered: {
  7249. lbValue dst = lb_build_expr(p, ce->args[0]);
  7250. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  7251. switch (id) {
  7252. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  7253. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7254. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  7255. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7256. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7257. }
  7258. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7259. lbValue res = {};
  7260. res.value = instr;
  7261. res.type = type_deref(dst.type);
  7262. return res;
  7263. }
  7264. case BuiltinProc_atomic_add:
  7265. case BuiltinProc_atomic_add_acq:
  7266. case BuiltinProc_atomic_add_rel:
  7267. case BuiltinProc_atomic_add_acqrel:
  7268. case BuiltinProc_atomic_add_relaxed:
  7269. case BuiltinProc_atomic_sub:
  7270. case BuiltinProc_atomic_sub_acq:
  7271. case BuiltinProc_atomic_sub_rel:
  7272. case BuiltinProc_atomic_sub_acqrel:
  7273. case BuiltinProc_atomic_sub_relaxed:
  7274. case BuiltinProc_atomic_and:
  7275. case BuiltinProc_atomic_and_acq:
  7276. case BuiltinProc_atomic_and_rel:
  7277. case BuiltinProc_atomic_and_acqrel:
  7278. case BuiltinProc_atomic_and_relaxed:
  7279. case BuiltinProc_atomic_nand:
  7280. case BuiltinProc_atomic_nand_acq:
  7281. case BuiltinProc_atomic_nand_rel:
  7282. case BuiltinProc_atomic_nand_acqrel:
  7283. case BuiltinProc_atomic_nand_relaxed:
  7284. case BuiltinProc_atomic_or:
  7285. case BuiltinProc_atomic_or_acq:
  7286. case BuiltinProc_atomic_or_rel:
  7287. case BuiltinProc_atomic_or_acqrel:
  7288. case BuiltinProc_atomic_or_relaxed:
  7289. case BuiltinProc_atomic_xor:
  7290. case BuiltinProc_atomic_xor_acq:
  7291. case BuiltinProc_atomic_xor_rel:
  7292. case BuiltinProc_atomic_xor_acqrel:
  7293. case BuiltinProc_atomic_xor_relaxed:
  7294. case BuiltinProc_atomic_xchg:
  7295. case BuiltinProc_atomic_xchg_acq:
  7296. case BuiltinProc_atomic_xchg_rel:
  7297. case BuiltinProc_atomic_xchg_acqrel:
  7298. case BuiltinProc_atomic_xchg_relaxed: {
  7299. lbValue dst = lb_build_expr(p, ce->args[0]);
  7300. lbValue val = lb_build_expr(p, ce->args[1]);
  7301. val = lb_emit_conv(p, val, type_deref(dst.type));
  7302. LLVMAtomicRMWBinOp op = {};
  7303. LLVMAtomicOrdering ordering = {};
  7304. switch (id) {
  7305. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7306. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  7307. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  7308. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7309. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  7310. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7311. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  7312. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  7313. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7314. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  7315. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7316. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  7317. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  7318. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7319. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  7320. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7321. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  7322. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  7323. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7324. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  7325. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7326. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  7327. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  7328. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7329. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  7330. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7331. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  7332. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  7333. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7334. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  7335. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7336. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  7337. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  7338. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7339. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  7340. }
  7341. lbValue res = {};
  7342. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  7343. res.type = tv.type;
  7344. return res;
  7345. }
  7346. case BuiltinProc_atomic_cxchg:
  7347. case BuiltinProc_atomic_cxchg_acq:
  7348. case BuiltinProc_atomic_cxchg_rel:
  7349. case BuiltinProc_atomic_cxchg_acqrel:
  7350. case BuiltinProc_atomic_cxchg_relaxed:
  7351. case BuiltinProc_atomic_cxchg_failrelaxed:
  7352. case BuiltinProc_atomic_cxchg_failacq:
  7353. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  7354. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  7355. case BuiltinProc_atomic_cxchgweak:
  7356. case BuiltinProc_atomic_cxchgweak_acq:
  7357. case BuiltinProc_atomic_cxchgweak_rel:
  7358. case BuiltinProc_atomic_cxchgweak_acqrel:
  7359. case BuiltinProc_atomic_cxchgweak_relaxed:
  7360. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  7361. case BuiltinProc_atomic_cxchgweak_failacq:
  7362. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  7363. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  7364. Type *type = expr->tav.type;
  7365. lbValue address = lb_build_expr(p, ce->args[0]);
  7366. Type *elem = type_deref(address.type);
  7367. lbValue old_value = lb_build_expr(p, ce->args[1]);
  7368. lbValue new_value = lb_build_expr(p, ce->args[2]);
  7369. old_value = lb_emit_conv(p, old_value, elem);
  7370. new_value = lb_emit_conv(p, new_value, elem);
  7371. LLVMAtomicOrdering success_ordering = {};
  7372. LLVMAtomicOrdering failure_ordering = {};
  7373. LLVMBool weak = false;
  7374. switch (id) {
  7375. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7376. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7377. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7378. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7379. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7380. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7381. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  7382. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7383. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7384. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7385. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7386. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7387. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7388. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7389. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7390. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  7391. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7392. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7393. }
  7394. // TODO(bill): Figure out how to make it weak
  7395. LLVMBool single_threaded = weak;
  7396. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  7397. p->builder, address.value,
  7398. old_value.value, new_value.value,
  7399. success_ordering,
  7400. failure_ordering,
  7401. single_threaded
  7402. );
  7403. GB_ASSERT(tv.type->kind == Type_Tuple);
  7404. Type *fix_typed = alloc_type_tuple();
  7405. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  7406. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  7407. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7408. lbValue res = {};
  7409. res.value = value;
  7410. res.type = fix_typed;
  7411. return res;
  7412. }
  7413. case BuiltinProc_type_equal_proc:
  7414. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  7415. case BuiltinProc_type_hasher_proc:
  7416. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  7417. }
  7418. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  7419. return {};
  7420. }
  7421. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  7422. switch (param_value.kind) {
  7423. case ParameterValue_Constant:
  7424. if (is_type_constant_type(parameter_type)) {
  7425. return lb_const_value(p->module, parameter_type, param_value.value);
  7426. } else {
  7427. ExactValue ev = param_value.value;
  7428. lbValue arg = {};
  7429. Type *type = type_of_expr(param_value.original_ast_expr);
  7430. if (type != nullptr) {
  7431. arg = lb_const_value(p->module, type, ev);
  7432. } else {
  7433. arg = lb_const_value(p->module, parameter_type, param_value.value);
  7434. }
  7435. return lb_emit_conv(p, arg, parameter_type);
  7436. }
  7437. case ParameterValue_Nil:
  7438. return lb_const_nil(p->module, parameter_type);
  7439. case ParameterValue_Location:
  7440. {
  7441. String proc_name = {};
  7442. if (p->entity != nullptr) {
  7443. proc_name = p->entity->token.string;
  7444. }
  7445. return lb_emit_source_code_location(p, proc_name, pos);
  7446. }
  7447. case ParameterValue_Value:
  7448. return lb_build_expr(p, param_value.ast_value);
  7449. }
  7450. return lb_const_nil(p->module, parameter_type);
  7451. }
  7452. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  7453. lbModule *m = p->module;
  7454. TypeAndValue tv = type_and_value_of_expr(expr);
  7455. ast_node(ce, CallExpr, expr);
  7456. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  7457. AddressingMode proc_mode = proc_tv.mode;
  7458. if (proc_mode == Addressing_Type) {
  7459. GB_ASSERT(ce->args.count == 1);
  7460. lbValue x = lb_build_expr(p, ce->args[0]);
  7461. lbValue y = lb_emit_conv(p, x, tv.type);
  7462. return y;
  7463. }
  7464. Ast *pexpr = unparen_expr(ce->proc);
  7465. if (proc_mode == Addressing_Builtin) {
  7466. Entity *e = entity_of_node(pexpr);
  7467. BuiltinProcId id = BuiltinProc_Invalid;
  7468. if (e != nullptr) {
  7469. id = cast(BuiltinProcId)e->Builtin.id;
  7470. } else {
  7471. id = BuiltinProc_DIRECTIVE;
  7472. }
  7473. return lb_build_builtin_proc(p, expr, tv, id);
  7474. }
  7475. // NOTE(bill): Regular call
  7476. lbValue value = {};
  7477. Ast *proc_expr = unparen_expr(ce->proc);
  7478. if (proc_expr->tav.mode == Addressing_Constant) {
  7479. ExactValue v = proc_expr->tav.value;
  7480. switch (v.kind) {
  7481. case ExactValue_Integer:
  7482. {
  7483. u64 u = big_int_to_u64(&v.value_integer);
  7484. lbValue x = {};
  7485. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7486. x.type = t_uintptr;
  7487. x = lb_emit_conv(p, x, t_rawptr);
  7488. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7489. break;
  7490. }
  7491. case ExactValue_Pointer:
  7492. {
  7493. u64 u = cast(u64)v.value_pointer;
  7494. lbValue x = {};
  7495. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7496. x.type = t_uintptr;
  7497. x = lb_emit_conv(p, x, t_rawptr);
  7498. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7499. break;
  7500. }
  7501. }
  7502. }
  7503. if (value.value == nullptr) {
  7504. value = lb_build_expr(p, proc_expr);
  7505. }
  7506. GB_ASSERT(value.value != nullptr);
  7507. Type *proc_type_ = base_type(value.type);
  7508. GB_ASSERT(proc_type_->kind == Type_Proc);
  7509. TypeProc *pt = &proc_type_->Proc;
  7510. set_procedure_abi_types(proc_type_);
  7511. if (is_call_expr_field_value(ce)) {
  7512. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  7513. for_array(arg_index, ce->args) {
  7514. Ast *arg = ce->args[arg_index];
  7515. ast_node(fv, FieldValue, arg);
  7516. GB_ASSERT(fv->field->kind == Ast_Ident);
  7517. String name = fv->field->Ident.token.string;
  7518. isize index = lookup_procedure_parameter(pt, name);
  7519. GB_ASSERT(index >= 0);
  7520. TypeAndValue tav = type_and_value_of_expr(fv->value);
  7521. if (tav.mode == Addressing_Type) {
  7522. args[index] = lb_const_nil(m, tav.type);
  7523. } else {
  7524. args[index] = lb_build_expr(p, fv->value);
  7525. }
  7526. }
  7527. TypeTuple *params = &pt->params->Tuple;
  7528. for (isize i = 0; i < args.count; i++) {
  7529. Entity *e = params->variables[i];
  7530. if (e->kind == Entity_TypeName) {
  7531. args[i] = lb_const_nil(m, e->type);
  7532. } else if (e->kind == Entity_Constant) {
  7533. continue;
  7534. } else {
  7535. GB_ASSERT(e->kind == Entity_Variable);
  7536. if (args[i].value == nullptr) {
  7537. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7538. } else {
  7539. args[i] = lb_emit_conv(p, args[i], e->type);
  7540. }
  7541. }
  7542. }
  7543. for (isize i = 0; i < args.count; i++) {
  7544. Entity *e = params->variables[i];
  7545. if (args[i].type == nullptr) {
  7546. continue;
  7547. } else if (is_type_untyped_nil(args[i].type)) {
  7548. args[i] = lb_const_nil(m, e->type);
  7549. } else if (is_type_untyped_undef(args[i].type)) {
  7550. args[i] = lb_const_undef(m, e->type);
  7551. }
  7552. }
  7553. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  7554. }
  7555. isize arg_index = 0;
  7556. isize arg_count = 0;
  7557. for_array(i, ce->args) {
  7558. Ast *arg = ce->args[i];
  7559. TypeAndValue tav = type_and_value_of_expr(arg);
  7560. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  7561. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  7562. Type *at = tav.type;
  7563. if (at->kind == Type_Tuple) {
  7564. arg_count += at->Tuple.variables.count;
  7565. } else {
  7566. arg_count++;
  7567. }
  7568. }
  7569. isize param_count = 0;
  7570. if (pt->params) {
  7571. GB_ASSERT(pt->params->kind == Type_Tuple);
  7572. param_count = pt->params->Tuple.variables.count;
  7573. }
  7574. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  7575. isize variadic_index = pt->variadic_index;
  7576. bool variadic = pt->variadic && variadic_index >= 0;
  7577. bool vari_expand = ce->ellipsis.pos.line != 0;
  7578. bool is_c_vararg = pt->c_vararg;
  7579. String proc_name = {};
  7580. if (p->entity != nullptr) {
  7581. proc_name = p->entity->token.string;
  7582. }
  7583. TokenPos pos = ast_token(ce->proc).pos;
  7584. TypeTuple *param_tuple = nullptr;
  7585. if (pt->params) {
  7586. GB_ASSERT(pt->params->kind == Type_Tuple);
  7587. param_tuple = &pt->params->Tuple;
  7588. }
  7589. for_array(i, ce->args) {
  7590. Ast *arg = ce->args[i];
  7591. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  7592. if (arg_tv.mode == Addressing_Type) {
  7593. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  7594. } else {
  7595. lbValue a = lb_build_expr(p, arg);
  7596. Type *at = a.type;
  7597. if (at->kind == Type_Tuple) {
  7598. for_array(i, at->Tuple.variables) {
  7599. Entity *e = at->Tuple.variables[i];
  7600. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  7601. args[arg_index++] = v;
  7602. }
  7603. } else {
  7604. args[arg_index++] = a;
  7605. }
  7606. }
  7607. }
  7608. if (param_count > 0) {
  7609. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7610. GB_ASSERT(param_count < 1000000);
  7611. if (arg_count < param_count) {
  7612. isize end = cast(isize)param_count;
  7613. if (variadic) {
  7614. end = variadic_index;
  7615. }
  7616. while (arg_index < end) {
  7617. Entity *e = param_tuple->variables[arg_index];
  7618. GB_ASSERT(e->kind == Entity_Variable);
  7619. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7620. }
  7621. }
  7622. if (is_c_vararg) {
  7623. GB_ASSERT(variadic);
  7624. GB_ASSERT(!vari_expand);
  7625. isize i = 0;
  7626. for (; i < variadic_index; i++) {
  7627. Entity *e = param_tuple->variables[i];
  7628. if (e->kind == Entity_Variable) {
  7629. args[i] = lb_emit_conv(p, args[i], e->type);
  7630. }
  7631. }
  7632. Type *variadic_type = param_tuple->variables[i]->type;
  7633. GB_ASSERT(is_type_slice(variadic_type));
  7634. variadic_type = base_type(variadic_type)->Slice.elem;
  7635. if (!is_type_any(variadic_type)) {
  7636. for (; i < arg_count; i++) {
  7637. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7638. }
  7639. } else {
  7640. for (; i < arg_count; i++) {
  7641. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7642. }
  7643. }
  7644. } else if (variadic) {
  7645. isize i = 0;
  7646. for (; i < variadic_index; i++) {
  7647. Entity *e = param_tuple->variables[i];
  7648. if (e->kind == Entity_Variable) {
  7649. args[i] = lb_emit_conv(p, args[i], e->type);
  7650. }
  7651. }
  7652. if (!vari_expand) {
  7653. Type *variadic_type = param_tuple->variables[i]->type;
  7654. GB_ASSERT(is_type_slice(variadic_type));
  7655. variadic_type = base_type(variadic_type)->Slice.elem;
  7656. for (; i < arg_count; i++) {
  7657. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7658. }
  7659. }
  7660. } else {
  7661. for (isize i = 0; i < param_count; i++) {
  7662. Entity *e = param_tuple->variables[i];
  7663. if (e->kind == Entity_Variable) {
  7664. if (args[i].value == nullptr) {
  7665. continue;
  7666. }
  7667. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7668. args[i] = lb_emit_conv(p, args[i], e->type);
  7669. }
  7670. }
  7671. }
  7672. if (variadic && !vari_expand && !is_c_vararg) {
  7673. // variadic call argument generation
  7674. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7675. Type *elem_type = base_type(slice_type)->Slice.elem;
  7676. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7677. isize slice_len = arg_count+1 - (variadic_index+1);
  7678. if (slice_len > 0) {
  7679. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7680. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7681. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7682. lb_emit_store(p, addr, args[i]);
  7683. }
  7684. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7685. lbValue len = lb_const_int(m, t_int, slice_len);
  7686. lb_fill_slice(p, slice, base_elem, len);
  7687. }
  7688. arg_count = param_count;
  7689. args[variadic_index] = lb_addr_load(p, slice);
  7690. }
  7691. }
  7692. if (variadic && variadic_index+1 < param_count) {
  7693. for (isize i = variadic_index+1; i < param_count; i++) {
  7694. Entity *e = param_tuple->variables[i];
  7695. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7696. }
  7697. }
  7698. isize final_count = param_count;
  7699. if (is_c_vararg) {
  7700. final_count = arg_count;
  7701. }
  7702. if (param_tuple != nullptr) {
  7703. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7704. Entity *e = param_tuple->variables[i];
  7705. if (args[i].type == nullptr) {
  7706. continue;
  7707. } else if (is_type_untyped_nil(args[i].type)) {
  7708. args[i] = lb_const_nil(m, e->type);
  7709. } else if (is_type_untyped_undef(args[i].type)) {
  7710. args[i] = lb_const_undef(m, e->type);
  7711. }
  7712. }
  7713. }
  7714. auto call_args = array_slice(args, 0, final_count);
  7715. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  7716. }
  7717. bool lb_is_const(lbValue value) {
  7718. LLVMValueRef v = value.value;
  7719. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  7720. // TODO(bill): Is this correct behaviour?
  7721. return true;
  7722. }
  7723. if (LLVMIsConstant(v)) {
  7724. return true;
  7725. }
  7726. return false;
  7727. }
  7728. bool lb_is_const_or_global(lbValue value) {
  7729. if (lb_is_const(value)) {
  7730. return true;
  7731. }
  7732. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  7733. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  7734. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  7735. return false;
  7736. }
  7737. LLVMTypeRef elem = LLVMGetElementType(t);
  7738. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  7739. }
  7740. return false;
  7741. }
  7742. bool lb_is_const_nil(lbValue value) {
  7743. LLVMValueRef v = value.value;
  7744. if (LLVMIsConstant(v)) {
  7745. if (LLVMIsAConstantAggregateZero(v)) {
  7746. return true;
  7747. } else if (LLVMIsAConstantPointerNull(v)) {
  7748. return true;
  7749. }
  7750. }
  7751. return false;
  7752. }
  7753. String lb_get_const_string(lbModule *m, lbValue value) {
  7754. GB_ASSERT(lb_is_const(value));
  7755. Type *t = base_type(value.type);
  7756. GB_ASSERT(are_types_identical(t, t_string));
  7757. unsigned ptr_indices[1] = {0};
  7758. unsigned len_indices[1] = {1};
  7759. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  7760. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  7761. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  7762. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  7763. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  7764. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  7765. size_t length = 0;
  7766. char const *text = LLVMGetAsString(underlying_ptr, &length);
  7767. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  7768. return make_string(cast(u8 const *)text, real_length);
  7769. }
  7770. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  7771. GB_ASSERT(is_type_pointer(addr.type));
  7772. Type *type = type_deref(addr.type);
  7773. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  7774. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  7775. }
  7776. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7777. AstPackage *pkg = m->info->runtime_package;
  7778. Entity *e = scope_lookup_current(pkg->scope, name);
  7779. lbValue *found = nullptr;
  7780. if (m != e->code_gen_module) {
  7781. gb_mutex_lock(&m->mutex);
  7782. }
  7783. GB_ASSERT(e->code_gen_module != nullptr);
  7784. found = map_get(&e->code_gen_module->values, hash_entity(e));
  7785. if (m != e->code_gen_module) {
  7786. gb_mutex_unlock(&m->mutex);
  7787. }
  7788. GB_ASSERT(found != nullptr);
  7789. return found->value;
  7790. }
  7791. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  7792. Type *vt = core_type(value.type);
  7793. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  7794. // TODO(bill): lb_emit_byte_swap
  7795. lbValue res = {};
  7796. res.type = platform_type;
  7797. res.value = value.value;
  7798. int sz = cast(int)type_size_of(vt);
  7799. if (sz > 1) {
  7800. if (is_type_float(platform_type)) {
  7801. String name = {};
  7802. switch (sz) {
  7803. case 4: name = str_lit("bswap_f32"); break;
  7804. case 8: name = str_lit("bswap_f64"); break;
  7805. default: GB_PANIC("unhandled byteswap size"); break;
  7806. }
  7807. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7808. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7809. } else {
  7810. GB_ASSERT(is_type_integer(platform_type));
  7811. String name = {};
  7812. switch (sz) {
  7813. case 2: name = str_lit("bswap_16"); break;
  7814. case 4: name = str_lit("bswap_32"); break;
  7815. case 8: name = str_lit("bswap_64"); break;
  7816. case 16: name = str_lit("bswap_128"); break;
  7817. default: GB_PANIC("unhandled byteswap size"); break;
  7818. }
  7819. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7820. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7821. }
  7822. }
  7823. return res;
  7824. }
  7825. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  7826. lbLoopData data = {};
  7827. lbValue max = lb_const_int(p->module, t_int, count);
  7828. data.idx_addr = lb_add_local_generated(p, index_type, true);
  7829. data.body = lb_create_block(p, "loop.body");
  7830. data.done = lb_create_block(p, "loop.done");
  7831. data.loop = lb_create_block(p, "loop.loop");
  7832. lb_emit_jump(p, data.loop);
  7833. lb_start_block(p, data.loop);
  7834. data.idx = lb_addr_load(p, data.idx_addr);
  7835. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  7836. lb_emit_if(p, cond, data.body, data.done);
  7837. lb_start_block(p, data.body);
  7838. return data;
  7839. }
  7840. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  7841. if (data.idx_addr.addr.value != nullptr) {
  7842. lb_emit_increment(p, data.idx_addr.addr);
  7843. lb_emit_jump(p, data.loop);
  7844. lb_start_block(p, data.done);
  7845. }
  7846. }
  7847. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  7848. lbValue res = {};
  7849. res.type = t_llvm_bool;
  7850. Type *t = x.type;
  7851. if (is_type_pointer(t)) {
  7852. if (op_kind == Token_CmpEq) {
  7853. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7854. } else if (op_kind == Token_NotEq) {
  7855. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7856. }
  7857. return res;
  7858. } else if (is_type_cstring(t)) {
  7859. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  7860. if (op_kind == Token_CmpEq) {
  7861. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  7862. } else if (op_kind == Token_NotEq) {
  7863. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  7864. }
  7865. return res;
  7866. } else if (is_type_proc(t)) {
  7867. if (op_kind == Token_CmpEq) {
  7868. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7869. } else if (op_kind == Token_NotEq) {
  7870. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7871. }
  7872. return res;
  7873. } else if (is_type_any(t)) {
  7874. // TODO(bill): is this correct behaviour for nil comparison for any?
  7875. lbValue data = lb_emit_struct_ev(p, x, 0);
  7876. lbValue ti = lb_emit_struct_ev(p, x, 1);
  7877. if (op_kind == Token_CmpEq) {
  7878. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  7879. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  7880. res.value = LLVMBuildOr(p->builder, a, b, "");
  7881. return res;
  7882. } else if (op_kind == Token_NotEq) {
  7883. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  7884. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  7885. res.value = LLVMBuildAnd(p->builder, a, b, "");
  7886. return res;
  7887. }
  7888. } else if (is_type_slice(t)) {
  7889. lbValue len = lb_emit_struct_ev(p, x, 1);
  7890. if (op_kind == Token_CmpEq) {
  7891. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7892. return res;
  7893. } else if (op_kind == Token_NotEq) {
  7894. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7895. return res;
  7896. }
  7897. } else if (is_type_dynamic_array(t)) {
  7898. lbValue cap = lb_emit_struct_ev(p, x, 2);
  7899. if (op_kind == Token_CmpEq) {
  7900. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7901. return res;
  7902. } else if (op_kind == Token_NotEq) {
  7903. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7904. return res;
  7905. }
  7906. } else if (is_type_map(t)) {
  7907. lbValue cap = lb_map_cap(p, x);
  7908. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  7909. } else if (is_type_union(t)) {
  7910. if (type_size_of(t) == 0) {
  7911. if (op_kind == Token_CmpEq) {
  7912. return lb_const_bool(p->module, t_llvm_bool, true);
  7913. } else if (op_kind == Token_NotEq) {
  7914. return lb_const_bool(p->module, t_llvm_bool, false);
  7915. }
  7916. } else {
  7917. lbValue tag = lb_emit_union_tag_value(p, x);
  7918. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  7919. }
  7920. } else if (is_type_typeid(t)) {
  7921. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  7922. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  7923. } else if (is_type_soa_struct(t)) {
  7924. Type *bt = base_type(t);
  7925. if (bt->Struct.soa_kind == StructSoa_Slice) {
  7926. lbValue len = lb_soa_struct_len(p, x);
  7927. if (op_kind == Token_CmpEq) {
  7928. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7929. return res;
  7930. } else if (op_kind == Token_NotEq) {
  7931. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7932. return res;
  7933. }
  7934. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  7935. lbValue cap = lb_soa_struct_cap(p, x);
  7936. if (op_kind == Token_CmpEq) {
  7937. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7938. return res;
  7939. } else if (op_kind == Token_NotEq) {
  7940. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7941. return res;
  7942. }
  7943. }
  7944. } else if (is_type_struct(t) && type_has_nil(t)) {
  7945. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7946. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7947. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7948. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7949. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7950. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7951. return res;
  7952. }
  7953. return {};
  7954. }
  7955. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  7956. Type *original_type = type;
  7957. type = base_type(type);
  7958. GB_ASSERT(is_type_comparable(type));
  7959. Type *pt = alloc_type_pointer(type);
  7960. LLVMTypeRef ptr_type = lb_type(m, pt);
  7961. auto key = hash_type(type);
  7962. lbProcedure **found = map_get(&m->equal_procs, key);
  7963. lbProcedure *compare_proc = nullptr;
  7964. if (found) {
  7965. compare_proc = *found;
  7966. GB_ASSERT(compare_proc != nullptr);
  7967. return {compare_proc->value, compare_proc->type};
  7968. }
  7969. static u32 proc_index = 0;
  7970. char buf[16] = {};
  7971. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  7972. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  7973. String proc_name = make_string_c(str);
  7974. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  7975. map_set(&m->equal_procs, key, p);
  7976. lb_begin_procedure_body(p);
  7977. LLVMValueRef x = LLVMGetParam(p->value, 0);
  7978. LLVMValueRef y = LLVMGetParam(p->value, 1);
  7979. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  7980. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  7981. lbValue lhs = {x, pt};
  7982. lbValue rhs = {y, pt};
  7983. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  7984. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  7985. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  7986. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  7987. lb_start_block(p, block_same_ptr);
  7988. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  7989. lb_start_block(p, block_diff_ptr);
  7990. if (type->kind == Type_Struct) {
  7991. type_set_offsets(type);
  7992. lbBlock *block_false = lb_create_block(p, "bfalse");
  7993. lbValue res = lb_const_bool(m, t_bool, true);
  7994. for_array(i, type->Struct.fields) {
  7995. lbBlock *next_block = lb_create_block(p, "btrue");
  7996. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  7997. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  7998. lbValue left = lb_emit_load(p, pleft);
  7999. lbValue right = lb_emit_load(p, pright);
  8000. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8001. lb_emit_if(p, ok, next_block, block_false);
  8002. lb_emit_jump(p, next_block);
  8003. lb_start_block(p, next_block);
  8004. }
  8005. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8006. lb_start_block(p, block_false);
  8007. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  8008. } else {
  8009. lbValue left = lb_emit_load(p, lhs);
  8010. lbValue right = lb_emit_load(p, rhs);
  8011. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8012. ok = lb_emit_conv(p, ok, t_bool);
  8013. LLVMBuildRet(p->builder, ok.value);
  8014. }
  8015. lb_end_procedure_body(p);
  8016. compare_proc = p;
  8017. return {compare_proc->value, compare_proc->type};
  8018. }
  8019. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  8020. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  8021. i64 sz = type_size_of(type);
  8022. if (1 <= sz && sz <= 16) {
  8023. char name[20] = {};
  8024. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  8025. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8026. args[0] = data;
  8027. args[1] = seed;
  8028. return lb_emit_runtime_call(p, name, args);
  8029. }
  8030. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8031. args[0] = data;
  8032. args[1] = seed;
  8033. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  8034. return lb_emit_runtime_call(p, "default_hasher_n", args);
  8035. }
  8036. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  8037. Type *original_type = type;
  8038. type = core_type(type);
  8039. GB_ASSERT(is_type_valid_for_keys(type));
  8040. Type *pt = alloc_type_pointer(type);
  8041. LLVMTypeRef ptr_type = lb_type(m, pt);
  8042. auto key = hash_type(type);
  8043. lbProcedure **found = map_get(&m->hasher_procs, key);
  8044. if (found) {
  8045. GB_ASSERT(*found != nullptr);
  8046. return {(*found)->value, (*found)->type};
  8047. }
  8048. static u32 proc_index = 0;
  8049. char buf[16] = {};
  8050. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  8051. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8052. String proc_name = make_string_c(str);
  8053. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  8054. map_set(&m->hasher_procs, key, p);
  8055. lb_begin_procedure_body(p);
  8056. defer (lb_end_procedure_body(p));
  8057. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8058. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8059. lbValue data = {x, t_rawptr};
  8060. lbValue seed = {y, t_uintptr};
  8061. if (is_type_simple_compare(type)) {
  8062. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  8063. LLVMBuildRet(p->builder, res.value);
  8064. return {p->value, p->type};
  8065. }
  8066. if (type->kind == Type_Struct) {
  8067. type_set_offsets(type);
  8068. data = lb_emit_conv(p, data, t_u8_ptr);
  8069. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8070. for_array(i, type->Struct.fields) {
  8071. i64 offset = type->Struct.offsets[i];
  8072. Entity *field = type->Struct.fields[i];
  8073. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  8074. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  8075. args[0] = ptr;
  8076. args[1] = seed;
  8077. seed = lb_emit_call(p, field_hasher, args);
  8078. }
  8079. LLVMBuildRet(p->builder, seed.value);
  8080. } else if (type->kind == Type_Array) {
  8081. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  8082. lb_addr_store(p, pres, seed);
  8083. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8084. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  8085. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  8086. data = lb_emit_conv(p, data, pt);
  8087. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8088. args[0] = ptr;
  8089. args[1] = lb_addr_load(p, pres);
  8090. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8091. lb_addr_store(p, pres, new_seed);
  8092. lb_loop_end(p, loop_data);
  8093. lbValue res = lb_addr_load(p, pres);
  8094. LLVMBuildRet(p->builder, res.value);
  8095. } else if (type->kind == Type_EnumeratedArray) {
  8096. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  8097. lb_addr_store(p, res, seed);
  8098. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8099. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  8100. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  8101. data = lb_emit_conv(p, data, pt);
  8102. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8103. args[0] = ptr;
  8104. args[1] = lb_addr_load(p, res);
  8105. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8106. lb_addr_store(p, res, new_seed);
  8107. lb_loop_end(p, loop_data);
  8108. lbValue vres = lb_addr_load(p, res);
  8109. LLVMBuildRet(p->builder, vres.value);
  8110. } else if (is_type_cstring(type)) {
  8111. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8112. args[0] = data;
  8113. args[1] = seed;
  8114. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  8115. LLVMBuildRet(p->builder, res.value);
  8116. } else if (is_type_string(type)) {
  8117. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8118. args[0] = data;
  8119. args[1] = seed;
  8120. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  8121. LLVMBuildRet(p->builder, res.value);
  8122. } else {
  8123. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  8124. }
  8125. return {p->value, p->type};
  8126. }
  8127. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  8128. Type *a = core_type(left.type);
  8129. Type *b = core_type(right.type);
  8130. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  8131. lbValue nil_check = {};
  8132. if (is_type_untyped_nil(left.type)) {
  8133. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  8134. } else if (is_type_untyped_nil(right.type)) {
  8135. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  8136. }
  8137. if (nil_check.value != nullptr) {
  8138. return nil_check;
  8139. }
  8140. if (are_types_identical(a, b)) {
  8141. // NOTE(bill): No need for a conversion
  8142. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  8143. left = lb_emit_conv(p, left, right.type);
  8144. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  8145. right = lb_emit_conv(p, right, left.type);
  8146. } else {
  8147. Type *lt = left.type;
  8148. Type *rt = right.type;
  8149. // if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  8150. // Type *blt = base_type(lt);
  8151. // Type *brt = base_type(rt);
  8152. // i64 bits = gb_max(blt->BitSet.bits, brt->BitSet.bits);
  8153. // i64 bytes = bits / 8;
  8154. // switch (bytes) {
  8155. // case 1:
  8156. // left = lb_emit_conv(p, left, t_u8);
  8157. // right = lb_emit_conv(p, right, t_u8);
  8158. // break;
  8159. // case 2:
  8160. // left = lb_emit_conv(p, left, t_u16);
  8161. // right = lb_emit_conv(p, right, t_u16);
  8162. // break;
  8163. // case 4:
  8164. // left = lb_emit_conv(p, left, t_u32);
  8165. // right = lb_emit_conv(p, right, t_u32);
  8166. // break;
  8167. // case 8:
  8168. // left = lb_emit_conv(p, left, t_u64);
  8169. // right = lb_emit_conv(p, right, t_u64);
  8170. // break;
  8171. // default: GB_PANIC("Unknown integer size"); break;
  8172. // }
  8173. // }
  8174. lt = left.type;
  8175. rt = right.type;
  8176. i64 ls = type_size_of(lt);
  8177. i64 rs = type_size_of(rt);
  8178. if (ls < rs) {
  8179. left = lb_emit_conv(p, left, rt);
  8180. } else if (ls > rs) {
  8181. right = lb_emit_conv(p, right, lt);
  8182. } else {
  8183. right = lb_emit_conv(p, right, lt);
  8184. }
  8185. }
  8186. if (is_type_array(a)) {
  8187. Type *tl = base_type(a);
  8188. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  8189. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  8190. TokenKind cmp_op = Token_And;
  8191. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  8192. if (op_kind == Token_NotEq) {
  8193. res = lb_const_bool(p->module, t_llvm_bool, false);
  8194. cmp_op = Token_Or;
  8195. } else if (op_kind == Token_CmpEq) {
  8196. res = lb_const_bool(p->module, t_llvm_bool, true);
  8197. cmp_op = Token_And;
  8198. }
  8199. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  8200. i32 count = cast(i32)tl->Array.count;
  8201. if (inline_array_arith) {
  8202. // inline
  8203. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8204. lb_addr_store(p, val, res);
  8205. for (i32 i = 0; i < count; i++) {
  8206. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  8207. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  8208. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8209. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8210. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8211. }
  8212. return lb_addr_load(p, val);
  8213. } else {
  8214. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  8215. // TODO(bill): Test to see if this is actually faster!!!!
  8216. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8217. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8218. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  8219. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  8220. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  8221. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  8222. return lb_emit_conv(p, res, t_bool);
  8223. } else {
  8224. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8225. lb_addr_store(p, val, res);
  8226. auto loop_data = lb_loop_start(p, count, t_i32);
  8227. {
  8228. lbValue i = loop_data.idx;
  8229. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  8230. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  8231. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8232. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8233. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8234. }
  8235. lb_loop_end(p, loop_data);
  8236. return lb_addr_load(p, val);
  8237. }
  8238. }
  8239. }
  8240. if (is_type_struct(a) && is_type_comparable(a)) {
  8241. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  8242. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  8243. lbValue res = {};
  8244. if (is_type_simple_compare(a)) {
  8245. // TODO(bill): Test to see if this is actually faster!!!!
  8246. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8247. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8248. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8249. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  8250. res = lb_emit_runtime_call(p, "memory_equal", args);
  8251. } else {
  8252. lbValue value = lb_get_equal_proc_for_type(p->module, a);
  8253. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8254. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8255. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8256. res = lb_emit_call(p, value, args);
  8257. }
  8258. if (op_kind == Token_NotEq) {
  8259. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  8260. }
  8261. return res;
  8262. }
  8263. if (is_type_string(a)) {
  8264. if (is_type_cstring(a)) {
  8265. left = lb_emit_conv(p, left, t_string);
  8266. right = lb_emit_conv(p, right, t_string);
  8267. }
  8268. char const *runtime_procedure = nullptr;
  8269. switch (op_kind) {
  8270. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  8271. case Token_NotEq: runtime_procedure = "string_ne"; break;
  8272. case Token_Lt: runtime_procedure = "string_lt"; break;
  8273. case Token_Gt: runtime_procedure = "string_gt"; break;
  8274. case Token_LtEq: runtime_procedure = "string_le"; break;
  8275. case Token_GtEq: runtime_procedure = "string_gt"; break;
  8276. }
  8277. GB_ASSERT(runtime_procedure != nullptr);
  8278. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8279. args[0] = left;
  8280. args[1] = right;
  8281. return lb_emit_runtime_call(p, runtime_procedure, args);
  8282. }
  8283. if (is_type_complex(a)) {
  8284. char const *runtime_procedure = "";
  8285. i64 sz = 8*type_size_of(a);
  8286. switch (sz) {
  8287. case 64:
  8288. switch (op_kind) {
  8289. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  8290. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  8291. }
  8292. break;
  8293. case 128:
  8294. switch (op_kind) {
  8295. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  8296. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  8297. }
  8298. break;
  8299. }
  8300. GB_ASSERT(runtime_procedure != nullptr);
  8301. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8302. args[0] = left;
  8303. args[1] = right;
  8304. return lb_emit_runtime_call(p, runtime_procedure, args);
  8305. }
  8306. if (is_type_quaternion(a)) {
  8307. char const *runtime_procedure = "";
  8308. i64 sz = 8*type_size_of(a);
  8309. switch (sz) {
  8310. case 128:
  8311. switch (op_kind) {
  8312. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  8313. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  8314. }
  8315. break;
  8316. case 256:
  8317. switch (op_kind) {
  8318. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  8319. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  8320. }
  8321. break;
  8322. }
  8323. GB_ASSERT(runtime_procedure != nullptr);
  8324. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8325. args[0] = left;
  8326. args[1] = right;
  8327. return lb_emit_runtime_call(p, runtime_procedure, args);
  8328. }
  8329. if (is_type_bit_set(a)) {
  8330. switch (op_kind) {
  8331. case Token_Lt:
  8332. case Token_LtEq:
  8333. case Token_Gt:
  8334. case Token_GtEq:
  8335. {
  8336. Type *it = bit_set_to_int(a);
  8337. lbValue lhs = lb_emit_transmute(p, left, it);
  8338. lbValue rhs = lb_emit_transmute(p, right, it);
  8339. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  8340. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  8341. // (lhs & rhs) == lhs
  8342. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  8343. res.type = t_llvm_bool;
  8344. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  8345. // (lhs & rhs) == rhs
  8346. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  8347. res.type = t_llvm_bool;
  8348. }
  8349. // NOTE(bill): Strict subsets
  8350. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  8351. // res &~ (lhs == rhs)
  8352. lbValue eq = {};
  8353. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  8354. eq.type = t_llvm_bool;
  8355. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  8356. }
  8357. return res;
  8358. }
  8359. case Token_CmpEq:
  8360. case Token_NotEq:
  8361. {
  8362. LLVMIntPredicate pred = {};
  8363. switch (op_kind) {
  8364. case Token_CmpEq: pred = LLVMIntEQ; break;
  8365. case Token_NotEq: pred = LLVMIntNE; break;
  8366. }
  8367. lbValue res = {};
  8368. res.type = t_llvm_bool;
  8369. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8370. return res;
  8371. }
  8372. }
  8373. }
  8374. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  8375. Type *t = left.type;
  8376. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  8377. Type *platform_type = integer_endian_type_to_platform_type(t);
  8378. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  8379. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  8380. left = x;
  8381. right = y;
  8382. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  8383. Type *platform_type = integer_endian_type_to_platform_type(t);
  8384. lbValue x = lb_emit_conv(p, left, platform_type);
  8385. lbValue y = lb_emit_conv(p, right, platform_type);
  8386. left = x;
  8387. right = y;
  8388. }
  8389. }
  8390. a = core_type(left.type);
  8391. b = core_type(right.type);
  8392. lbValue res = {};
  8393. res.type = t_llvm_bool;
  8394. if (is_type_integer(a) ||
  8395. is_type_boolean(a) ||
  8396. is_type_pointer(a) ||
  8397. is_type_proc(a) ||
  8398. is_type_enum(a)) {
  8399. LLVMIntPredicate pred = {};
  8400. if (is_type_unsigned(left.type)) {
  8401. switch (op_kind) {
  8402. case Token_Gt: pred = LLVMIntUGT; break;
  8403. case Token_GtEq: pred = LLVMIntUGE; break;
  8404. case Token_Lt: pred = LLVMIntULT; break;
  8405. case Token_LtEq: pred = LLVMIntULE; break;
  8406. }
  8407. } else {
  8408. switch (op_kind) {
  8409. case Token_Gt: pred = LLVMIntSGT; break;
  8410. case Token_GtEq: pred = LLVMIntSGE; break;
  8411. case Token_Lt: pred = LLVMIntSLT; break;
  8412. case Token_LtEq: pred = LLVMIntSLE; break;
  8413. }
  8414. }
  8415. switch (op_kind) {
  8416. case Token_CmpEq: pred = LLVMIntEQ; break;
  8417. case Token_NotEq: pred = LLVMIntNE; break;
  8418. }
  8419. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8420. } else if (is_type_float(a)) {
  8421. LLVMRealPredicate pred = {};
  8422. switch (op_kind) {
  8423. case Token_CmpEq: pred = LLVMRealOEQ; break;
  8424. case Token_Gt: pred = LLVMRealOGT; break;
  8425. case Token_GtEq: pred = LLVMRealOGE; break;
  8426. case Token_Lt: pred = LLVMRealOLT; break;
  8427. case Token_LtEq: pred = LLVMRealOLE; break;
  8428. case Token_NotEq: pred = LLVMRealONE; break;
  8429. }
  8430. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  8431. } else if (is_type_typeid(a)) {
  8432. LLVMIntPredicate pred = {};
  8433. switch (op_kind) {
  8434. case Token_Gt: pred = LLVMIntUGT; break;
  8435. case Token_GtEq: pred = LLVMIntUGE; break;
  8436. case Token_Lt: pred = LLVMIntULT; break;
  8437. case Token_LtEq: pred = LLVMIntULE; break;
  8438. case Token_CmpEq: pred = LLVMIntEQ; break;
  8439. case Token_NotEq: pred = LLVMIntNE; break;
  8440. }
  8441. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8442. } else {
  8443. 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)));
  8444. }
  8445. return res;
  8446. }
  8447. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  8448. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  8449. if (found != nullptr) {
  8450. lbValue value = {};
  8451. value.value = (*found)->value;
  8452. value.type = (*found)->type;
  8453. return value;
  8454. }
  8455. ast_node(pl, ProcLit, expr);
  8456. // NOTE(bill): Generate a new name
  8457. // parent$count
  8458. isize name_len = prefix_name.len + 1 + 8 + 1;
  8459. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  8460. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  8461. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  8462. String name = make_string((u8 *)name_text, name_len-1);
  8463. Type *type = type_of_expr(expr);
  8464. set_procedure_abi_types(type);
  8465. Token token = {};
  8466. token.pos = ast_token(expr).pos;
  8467. token.kind = Token_Ident;
  8468. token.string = name;
  8469. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  8470. e->file = expr->file;
  8471. e->decl_info = pl->decl;
  8472. lbProcedure *p = lb_create_procedure(m, e);
  8473. lbValue value = {};
  8474. value.value = p->value;
  8475. value.type = p->type;
  8476. array_add(&m->procedures_to_generate, p);
  8477. if (parent != nullptr) {
  8478. array_add(&parent->children, p);
  8479. } else {
  8480. string_map_set(&m->members, name, value);
  8481. }
  8482. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  8483. return value;
  8484. }
  8485. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  8486. lbModule *m = p->module;
  8487. Type *src_type = value.type;
  8488. bool is_ptr = is_type_pointer(src_type);
  8489. bool is_tuple = true;
  8490. Type *tuple = type;
  8491. if (type->kind != Type_Tuple) {
  8492. is_tuple = false;
  8493. tuple = make_optional_ok_type(type);
  8494. }
  8495. lbAddr v = lb_add_local_generated(p, tuple, true);
  8496. if (is_ptr) {
  8497. value = lb_emit_load(p, value);
  8498. }
  8499. Type *src = base_type(type_deref(src_type));
  8500. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  8501. Type *dst = tuple->Tuple.variables[0]->type;
  8502. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  8503. lbValue tag = {};
  8504. lbValue dst_tag = {};
  8505. lbValue cond = {};
  8506. lbValue data = {};
  8507. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8508. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8509. if (is_type_union_maybe_pointer(src)) {
  8510. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8511. } else {
  8512. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  8513. dst_tag = lb_const_union_tag(m, src, dst);
  8514. }
  8515. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  8516. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  8517. if (data.value != nullptr) {
  8518. GB_ASSERT(is_type_union_maybe_pointer(src));
  8519. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  8520. } else {
  8521. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  8522. }
  8523. lb_emit_if(p, cond, ok_block, end_block);
  8524. lb_start_block(p, ok_block);
  8525. if (data.value == nullptr) {
  8526. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8527. }
  8528. lb_emit_store(p, gep0, data);
  8529. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8530. lb_emit_jump(p, end_block);
  8531. lb_start_block(p, end_block);
  8532. if (!is_tuple) {
  8533. if (do_conversion_check) {
  8534. // NOTE(bill): Panic on invalid conversion
  8535. Type *dst_type = tuple->Tuple.variables[0]->type;
  8536. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8537. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8538. args[0] = ok;
  8539. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  8540. args[2] = lb_const_int(m, t_i32, pos.line);
  8541. args[3] = lb_const_int(m, t_i32, pos.column);
  8542. args[4] = lb_typeid(m, src_type);
  8543. args[5] = lb_typeid(m, dst_type);
  8544. args[6] = lb_emit_conv(p, value_, t_rawptr);
  8545. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8546. }
  8547. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  8548. }
  8549. return lb_addr_load(p, v);
  8550. }
  8551. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8552. lbModule *m = p->module;
  8553. Type *src_type = value.type;
  8554. if (is_type_pointer(src_type)) {
  8555. value = lb_emit_load(p, value);
  8556. }
  8557. bool is_tuple = true;
  8558. Type *tuple = type;
  8559. if (type->kind != Type_Tuple) {
  8560. is_tuple = false;
  8561. tuple = make_optional_ok_type(type);
  8562. }
  8563. Type *dst_type = tuple->Tuple.variables[0]->type;
  8564. lbAddr v = lb_add_local_generated(p, tuple, true);
  8565. lbValue dst_typeid = lb_typeid(m, dst_type);
  8566. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  8567. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  8568. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  8569. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  8570. lb_emit_if(p, cond, ok_block, end_block);
  8571. lb_start_block(p, ok_block);
  8572. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8573. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8574. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  8575. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  8576. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  8577. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8578. lb_emit_jump(p, end_block);
  8579. lb_start_block(p, end_block);
  8580. if (!is_tuple) {
  8581. // NOTE(bill): Panic on invalid conversion
  8582. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8583. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8584. args[0] = ok;
  8585. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  8586. args[2] = lb_const_int(m, t_i32, pos.line);
  8587. args[3] = lb_const_int(m, t_i32, pos.column);
  8588. args[4] = any_typeid;
  8589. args[5] = dst_typeid;
  8590. args[6] = lb_emit_struct_ev(p, value, 0);;
  8591. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8592. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  8593. }
  8594. return v;
  8595. }
  8596. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8597. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  8598. }
  8599. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  8600. lbModule *m = p->module;
  8601. u64 prev_state_flags = p->module->state_flags;
  8602. defer (p->module->state_flags = prev_state_flags);
  8603. if (expr->state_flags != 0) {
  8604. u64 in = expr->state_flags;
  8605. u64 out = p->module->state_flags;
  8606. if (in & StateFlag_bounds_check) {
  8607. out |= StateFlag_bounds_check;
  8608. out &= ~StateFlag_no_bounds_check;
  8609. } else if (in & StateFlag_no_bounds_check) {
  8610. out |= StateFlag_no_bounds_check;
  8611. out &= ~StateFlag_bounds_check;
  8612. }
  8613. p->module->state_flags = out;
  8614. }
  8615. expr = unparen_expr(expr);
  8616. TokenPos expr_pos = ast_token(expr).pos;
  8617. TypeAndValue tv = type_and_value_of_expr(expr);
  8618. 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));
  8619. if (tv.value.kind != ExactValue_Invalid) {
  8620. // NOTE(bill): Short on constant values
  8621. return lb_const_value(p->module, tv.type, tv.value);
  8622. }
  8623. #if 0
  8624. LLVMMetadataRef prev_debug_location = nullptr;
  8625. if (p->debug_info != nullptr) {
  8626. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  8627. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  8628. }
  8629. defer (if (prev_debug_location != nullptr) {
  8630. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  8631. });
  8632. #endif
  8633. switch (expr->kind) {
  8634. case_ast_node(bl, BasicLit, expr);
  8635. TokenPos pos = bl->token.pos;
  8636. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  8637. case_end;
  8638. case_ast_node(bd, BasicDirective, expr);
  8639. TokenPos pos = bd->token.pos;
  8640. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name));
  8641. case_end;
  8642. case_ast_node(i, Implicit, expr);
  8643. return lb_addr_load(p, lb_build_addr(p, expr));
  8644. case_end;
  8645. case_ast_node(u, Undef, expr)
  8646. lbValue res = {};
  8647. if (is_type_untyped(tv.type)) {
  8648. res.value = nullptr;
  8649. res.type = t_untyped_undef;
  8650. } else {
  8651. res.value = LLVMGetUndef(lb_type(m, tv.type));
  8652. res.type = tv.type;
  8653. }
  8654. return res;
  8655. case_end;
  8656. case_ast_node(i, Ident, expr);
  8657. Entity *e = entity_from_expr(expr);
  8658. e = strip_entity_wrapping(e);
  8659. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  8660. if (e->kind == Entity_Builtin) {
  8661. Token token = ast_token(expr);
  8662. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  8663. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  8664. token_pos_to_string(token.pos));
  8665. return {};
  8666. } else if (e->kind == Entity_Nil) {
  8667. lbValue res = {};
  8668. res.value = nullptr;
  8669. res.type = e->type;
  8670. return res;
  8671. }
  8672. GB_ASSERT(e->kind != Entity_ProcGroup);
  8673. auto *found = map_get(&p->module->values, hash_entity(e));
  8674. if (found) {
  8675. auto v = *found;
  8676. // NOTE(bill): This is because pointers are already pointers in LLVM
  8677. if (is_type_proc(v.type)) {
  8678. return v;
  8679. }
  8680. return lb_emit_load(p, v);
  8681. } else if (e != nullptr && e->kind == Entity_Variable) {
  8682. return lb_addr_load(p, lb_build_addr(p, expr));
  8683. }
  8684. gb_printf_err("Error in: %s\n", token_pos_to_string(i->token.pos));
  8685. String pkg = {};
  8686. if (e->pkg) {
  8687. pkg = e->pkg->name;
  8688. }
  8689. 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);
  8690. return {};
  8691. case_end;
  8692. case_ast_node(de, DerefExpr, expr);
  8693. return lb_addr_load(p, lb_build_addr(p, expr));
  8694. case_end;
  8695. case_ast_node(se, SelectorExpr, expr);
  8696. TypeAndValue tav = type_and_value_of_expr(expr);
  8697. GB_ASSERT(tav.mode != Addressing_Invalid);
  8698. return lb_addr_load(p, lb_build_addr(p, expr));
  8699. case_end;
  8700. case_ast_node(ise, ImplicitSelectorExpr, expr);
  8701. TypeAndValue tav = type_and_value_of_expr(expr);
  8702. GB_ASSERT(tav.mode == Addressing_Constant);
  8703. return lb_const_value(p->module, tv.type, tv.value);
  8704. case_end;
  8705. case_ast_node(se, SelectorCallExpr, expr);
  8706. GB_ASSERT(se->modified_call);
  8707. TypeAndValue tav = type_and_value_of_expr(expr);
  8708. GB_ASSERT(tav.mode != Addressing_Invalid);
  8709. return lb_build_expr(p, se->call);
  8710. case_end;
  8711. case_ast_node(te, TernaryExpr, expr);
  8712. LLVMValueRef incoming_values[2] = {};
  8713. LLVMBasicBlockRef incoming_blocks[2] = {};
  8714. GB_ASSERT(te->y != nullptr);
  8715. lbBlock *then = lb_create_block(p, "if.then");
  8716. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8717. lbBlock *else_ = lb_create_block(p, "if.else");
  8718. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8719. lb_start_block(p, then);
  8720. Type *type = default_type(type_of_expr(expr));
  8721. lb_open_scope(p, nullptr);
  8722. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8723. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8724. lb_emit_jump(p, done);
  8725. lb_start_block(p, else_);
  8726. lb_open_scope(p, nullptr);
  8727. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8728. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8729. lb_emit_jump(p, done);
  8730. lb_start_block(p, done);
  8731. lbValue res = {};
  8732. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8733. res.type = type;
  8734. GB_ASSERT(p->curr_block->preds.count >= 2);
  8735. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8736. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8737. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8738. return res;
  8739. case_end;
  8740. case_ast_node(te, TernaryIfExpr, expr);
  8741. LLVMValueRef incoming_values[2] = {};
  8742. LLVMBasicBlockRef incoming_blocks[2] = {};
  8743. GB_ASSERT(te->y != nullptr);
  8744. lbBlock *then = lb_create_block(p, "if.then");
  8745. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8746. lbBlock *else_ = lb_create_block(p, "if.else");
  8747. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8748. lb_start_block(p, then);
  8749. Type *type = default_type(type_of_expr(expr));
  8750. lb_open_scope(p, nullptr);
  8751. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8752. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8753. lb_emit_jump(p, done);
  8754. lb_start_block(p, else_);
  8755. lb_open_scope(p, nullptr);
  8756. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8757. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8758. lb_emit_jump(p, done);
  8759. lb_start_block(p, done);
  8760. lbValue res = {};
  8761. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8762. res.type = type;
  8763. GB_ASSERT(p->curr_block->preds.count >= 2);
  8764. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8765. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8766. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8767. return res;
  8768. case_end;
  8769. case_ast_node(te, TernaryWhenExpr, expr);
  8770. TypeAndValue tav = type_and_value_of_expr(te->cond);
  8771. GB_ASSERT(tav.mode == Addressing_Constant);
  8772. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  8773. if (tav.value.value_bool) {
  8774. return lb_build_expr(p, te->x);
  8775. } else {
  8776. return lb_build_expr(p, te->y);
  8777. }
  8778. case_end;
  8779. case_ast_node(ta, TypeAssertion, expr);
  8780. TokenPos pos = ast_token(expr).pos;
  8781. Type *type = tv.type;
  8782. lbValue e = lb_build_expr(p, ta->expr);
  8783. Type *t = type_deref(e.type);
  8784. if (is_type_union(t)) {
  8785. return lb_emit_union_cast(p, e, type, pos);
  8786. } else if (is_type_any(t)) {
  8787. return lb_emit_any_cast(p, e, type, pos);
  8788. } else {
  8789. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8790. }
  8791. case_end;
  8792. case_ast_node(tc, TypeCast, expr);
  8793. lbValue e = lb_build_expr(p, tc->expr);
  8794. switch (tc->token.kind) {
  8795. case Token_cast:
  8796. return lb_emit_conv(p, e, tv.type);
  8797. case Token_transmute:
  8798. return lb_emit_transmute(p, e, tv.type);
  8799. }
  8800. GB_PANIC("Invalid AST TypeCast");
  8801. case_end;
  8802. case_ast_node(ac, AutoCast, expr);
  8803. return lb_build_expr(p, ac->expr);
  8804. case_end;
  8805. case_ast_node(ue, UnaryExpr, expr);
  8806. switch (ue->op.kind) {
  8807. case Token_And: {
  8808. Ast *ue_expr = unparen_expr(ue->expr);
  8809. if (ue_expr->kind == Ast_CompoundLit) {
  8810. lbValue v = lb_build_expr(p, ue->expr);
  8811. Type *type = v.type;
  8812. lbAddr addr = {};
  8813. if (p->is_startup) {
  8814. addr = lb_add_global_generated(p->module, type, v);
  8815. } else {
  8816. addr = lb_add_local_generated(p, type, false);
  8817. }
  8818. lb_addr_store(p, addr, v);
  8819. return addr.addr;
  8820. } else if (ue_expr->kind == Ast_TypeAssertion) {
  8821. GB_ASSERT(is_type_pointer(tv.type));
  8822. ast_node(ta, TypeAssertion, ue_expr);
  8823. TokenPos pos = ast_token(expr).pos;
  8824. Type *type = type_of_expr(ue_expr);
  8825. GB_ASSERT(!is_type_tuple(type));
  8826. lbValue e = lb_build_expr(p, ta->expr);
  8827. Type *t = type_deref(e.type);
  8828. if (is_type_union(t)) {
  8829. lbValue v = e;
  8830. if (!is_type_pointer(v.type)) {
  8831. v = lb_address_from_load_or_generate_local(p, v);
  8832. }
  8833. Type *src_type = type_deref(v.type);
  8834. Type *dst_type = type;
  8835. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  8836. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  8837. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  8838. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8839. args[0] = ok;
  8840. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  8841. args[2] = lb_const_int(p->module, t_i32, pos.line);
  8842. args[3] = lb_const_int(p->module, t_i32, pos.column);
  8843. args[4] = lb_typeid(p->module, src_type);
  8844. args[5] = lb_typeid(p->module, dst_type);
  8845. lb_emit_runtime_call(p, "type_assertion_check", args);
  8846. lbValue data_ptr = v;
  8847. return lb_emit_conv(p, data_ptr, tv.type);
  8848. } else if (is_type_any(t)) {
  8849. lbValue v = e;
  8850. if (is_type_pointer(v.type)) {
  8851. v = lb_emit_load(p, v);
  8852. }
  8853. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  8854. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  8855. lbValue id = lb_typeid(p->module, type);
  8856. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  8857. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8858. args[0] = ok;
  8859. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  8860. args[2] = lb_const_int(p->module, t_i32, pos.line);
  8861. args[3] = lb_const_int(p->module, t_i32, pos.column);
  8862. args[4] = any_id;
  8863. args[5] = id;
  8864. lb_emit_runtime_call(p, "type_assertion_check", args);
  8865. return lb_emit_conv(p, data_ptr, tv.type);
  8866. } else {
  8867. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  8868. }
  8869. }
  8870. return lb_build_addr_ptr(p, ue->expr);
  8871. }
  8872. default:
  8873. {
  8874. lbValue v = lb_build_expr(p, ue->expr);
  8875. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  8876. }
  8877. }
  8878. case_end;
  8879. case_ast_node(be, BinaryExpr, expr);
  8880. return lb_build_binary_expr(p, expr);
  8881. case_end;
  8882. case_ast_node(pl, ProcLit, expr);
  8883. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  8884. case_end;
  8885. case_ast_node(cl, CompoundLit, expr);
  8886. return lb_addr_load(p, lb_build_addr(p, expr));
  8887. case_end;
  8888. case_ast_node(ce, CallExpr, expr);
  8889. lbValue res = lb_build_call_expr(p, expr);
  8890. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  8891. GB_ASSERT(is_type_tuple(res.type));
  8892. GB_ASSERT(res.type->Tuple.variables.count == 2);
  8893. return lb_emit_struct_ev(p, res, 0);
  8894. }
  8895. return res;
  8896. case_end;
  8897. case_ast_node(se, SliceExpr, expr);
  8898. return lb_addr_load(p, lb_build_addr(p, expr));
  8899. case_end;
  8900. case_ast_node(ie, IndexExpr, expr);
  8901. return lb_addr_load(p, lb_build_addr(p, expr));
  8902. case_end;
  8903. case_ast_node(ia, InlineAsmExpr, expr);
  8904. Type *t = type_of_expr(expr);
  8905. GB_ASSERT(is_type_asm_proc(t));
  8906. String asm_string = {};
  8907. String constraints_string = {};
  8908. TypeAndValue tav;
  8909. tav = type_and_value_of_expr(ia->asm_string);
  8910. GB_ASSERT(is_type_string(tav.type));
  8911. GB_ASSERT(tav.value.kind == ExactValue_String);
  8912. asm_string = tav.value.value_string;
  8913. tav = type_and_value_of_expr(ia->constraints_string);
  8914. GB_ASSERT(is_type_string(tav.type));
  8915. GB_ASSERT(tav.value.kind == ExactValue_String);
  8916. constraints_string = tav.value.value_string;
  8917. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  8918. switch (ia->dialect) {
  8919. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  8920. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  8921. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  8922. default: GB_PANIC("Unhandled inline asm dialect"); break;
  8923. }
  8924. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  8925. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8926. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  8927. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  8928. ia->has_side_effects, ia->is_align_stack, dialect
  8929. );
  8930. GB_ASSERT(the_asm != nullptr);
  8931. return {the_asm, t};
  8932. case_end;
  8933. }
  8934. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  8935. return {};
  8936. }
  8937. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  8938. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  8939. String name = e->token.string;
  8940. Entity *parent = e->using_parent;
  8941. Selection sel = lookup_field(parent->type, name, false);
  8942. GB_ASSERT(sel.entity != nullptr);
  8943. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  8944. lbValue v = {};
  8945. if (pv != nullptr) {
  8946. v = *pv;
  8947. } else {
  8948. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  8949. v = lb_build_addr_ptr(p, e->using_expr);
  8950. }
  8951. GB_ASSERT(v.value != nullptr);
  8952. GB_ASSERT(parent->type == type_deref(v.type));
  8953. return lb_emit_deep_field_gep(p, v, sel);
  8954. }
  8955. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  8956. GB_ASSERT(e != nullptr);
  8957. if (e->kind == Entity_Constant) {
  8958. Type *t = default_type(type_of_expr(expr));
  8959. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  8960. lbAddr g = lb_add_global_generated(p->module, t, v);
  8961. return g;
  8962. }
  8963. lbValue v = {};
  8964. lbValue *found = map_get(&p->module->values, hash_entity(e));
  8965. if (found) {
  8966. v = *found;
  8967. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  8968. // NOTE(bill): Calculate the using variable every time
  8969. v = lb_get_using_variable(p, e);
  8970. }
  8971. if (v.value == nullptr) {
  8972. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  8973. LIT(p->name),
  8974. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  8975. GB_PANIC("Unknown value");
  8976. }
  8977. return lb_addr(v);
  8978. }
  8979. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  8980. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  8981. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  8982. map_type = base_type(map_type);
  8983. GB_ASSERT(map_type->kind == Type_Map);
  8984. Type *key_type = map_type->Map.key;
  8985. Type *val_type = map_type->Map.value;
  8986. // NOTE(bill): Removes unnecessary allocation if split gep
  8987. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  8988. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  8989. lb_emit_store(p, gep0, m);
  8990. i64 entry_size = type_size_of (map_type->Map.entry_type);
  8991. i64 entry_align = type_align_of (map_type->Map.entry_type);
  8992. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  8993. i64 key_size = type_size_of (map_type->Map.key);
  8994. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  8995. i64 value_size = type_size_of (map_type->Map.value);
  8996. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  8997. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  8998. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  8999. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  9000. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  9001. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  9002. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  9003. return lb_addr_load(p, h);
  9004. }
  9005. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  9006. if (true) {
  9007. return {};
  9008. }
  9009. lbValue hashed_key = {};
  9010. if (lb_is_const(key)) {
  9011. u64 hash = 0xcbf29ce484222325;
  9012. if (is_type_cstring(key_type)) {
  9013. size_t length = 0;
  9014. char const *text = LLVMGetAsString(key.value, &length);
  9015. hash = fnv64a(text, cast(isize)length);
  9016. } else if (is_type_string(key_type)) {
  9017. unsigned data_indices[] = {0};
  9018. unsigned len_indices[] = {1};
  9019. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  9020. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  9021. isize length = LLVMConstIntGetSExtValue(len);
  9022. char const *text = nullptr;
  9023. if (false && length != 0) {
  9024. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  9025. return {};
  9026. }
  9027. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  9028. size_t ulength = 0;
  9029. text = LLVMGetAsString(data, &ulength);
  9030. gb_printf_err("%td %td %s\n", length, ulength, text);
  9031. length = gb_min(length, cast(isize)ulength);
  9032. }
  9033. hash = fnv64a(text, cast(isize)length);
  9034. } else {
  9035. return {};
  9036. }
  9037. // TODO(bill): other const hash types
  9038. if (build_context.word_size == 4) {
  9039. hash &= 0xffffffffull;
  9040. }
  9041. hashed_key = lb_const_int(m, t_uintptr, hash);
  9042. }
  9043. return hashed_key;
  9044. }
  9045. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  9046. Type *hash_type = t_u64;
  9047. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  9048. lbValue vp = lb_addr_get_ptr(p, v);
  9049. Type *t = base_type(key.type);
  9050. key = lb_emit_conv(p, key, key_type);
  9051. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  9052. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  9053. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  9054. if (hashed_key.value == nullptr) {
  9055. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  9056. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9057. args[0] = key_ptr;
  9058. args[1] = lb_const_int(p->module, t_uintptr, 0);
  9059. hashed_key = lb_emit_call(p, hasher, args);
  9060. }
  9061. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  9062. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  9063. return lb_addr_load(p, v);
  9064. }
  9065. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  9066. lbValue map_key, lbValue map_value, Ast *node) {
  9067. map_type = base_type(map_type);
  9068. GB_ASSERT(map_type->kind == Type_Map);
  9069. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  9070. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  9071. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  9072. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  9073. lb_addr_store(p, value_addr, v);
  9074. auto args = array_make<lbValue>(permanent_allocator(), 4);
  9075. args[0] = h;
  9076. args[1] = key;
  9077. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  9078. args[3] = lb_emit_source_code_location(p, node);
  9079. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  9080. }
  9081. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  9082. expr = unparen_expr(expr);
  9083. switch (expr->kind) {
  9084. case_ast_node(i, Implicit, expr);
  9085. lbAddr v = {};
  9086. switch (i->kind) {
  9087. case Token_context:
  9088. v = lb_find_or_generate_context_ptr(p);
  9089. break;
  9090. }
  9091. GB_ASSERT(v.addr.value != nullptr);
  9092. return v;
  9093. case_end;
  9094. case_ast_node(i, Ident, expr);
  9095. if (is_blank_ident(expr)) {
  9096. lbAddr val = {};
  9097. return val;
  9098. }
  9099. String name = i->token.string;
  9100. Entity *e = entity_of_node(expr);
  9101. return lb_build_addr_from_entity(p, e, expr);
  9102. case_end;
  9103. case_ast_node(se, SelectorExpr, expr);
  9104. Ast *sel = unparen_expr(se->selector);
  9105. if (sel->kind == Ast_Ident) {
  9106. String selector = sel->Ident.token.string;
  9107. TypeAndValue tav = type_and_value_of_expr(se->expr);
  9108. if (tav.mode == Addressing_Invalid) {
  9109. // NOTE(bill): Imports
  9110. Entity *imp = entity_of_node(se->expr);
  9111. if (imp != nullptr) {
  9112. GB_ASSERT(imp->kind == Entity_ImportName);
  9113. }
  9114. return lb_build_addr(p, unparen_expr(se->selector));
  9115. }
  9116. Type *type = base_type(tav.type);
  9117. if (tav.mode == Addressing_Type) { // Addressing_Type
  9118. Selection sel = lookup_field(type, selector, true);
  9119. Entity *e = sel.entity;
  9120. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  9121. GB_ASSERT(e->flags & EntityFlag_TypeField);
  9122. String name = e->token.string;
  9123. /*if (name == "names") {
  9124. lbValue ti_ptr = lb_type_info(m, type);
  9125. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  9126. lbValue names_ptr = nullptr;
  9127. if (is_type_enum(type)) {
  9128. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  9129. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  9130. } else if (type->kind == Type_Struct) {
  9131. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  9132. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  9133. }
  9134. return ir_addr(names_ptr);
  9135. } else */{
  9136. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  9137. }
  9138. GB_PANIC("Unreachable");
  9139. }
  9140. Selection sel = lookup_field(type, selector, false);
  9141. GB_ASSERT(sel.entity != nullptr);
  9142. {
  9143. lbAddr addr = lb_build_addr(p, se->expr);
  9144. if (addr.kind == lbAddr_Map) {
  9145. lbValue v = lb_addr_load(p, addr);
  9146. lbValue a = lb_address_from_load_or_generate_local(p, v);
  9147. a = lb_emit_deep_field_gep(p, a, sel);
  9148. return lb_addr(a);
  9149. } else if (addr.kind == lbAddr_Context) {
  9150. GB_ASSERT(sel.index.count > 0);
  9151. if (addr.ctx.sel.index.count >= 0) {
  9152. sel = selection_combine(addr.ctx.sel, sel);
  9153. }
  9154. addr.ctx.sel = sel;
  9155. addr.kind = lbAddr_Context;
  9156. return addr;
  9157. } else if (addr.kind == lbAddr_SoaVariable) {
  9158. lbValue index = addr.soa.index;
  9159. i32 first_index = sel.index[0];
  9160. Selection sub_sel = sel;
  9161. sub_sel.index.data += 1;
  9162. sub_sel.index.count -= 1;
  9163. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  9164. Type *t = base_type(type_deref(addr.addr.type));
  9165. GB_ASSERT(is_type_soa_struct(t));
  9166. // TODO(bill): Bounds check
  9167. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  9168. lbValue len = lb_soa_struct_len(p, addr.addr);
  9169. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  9170. }
  9171. lbValue item = {};
  9172. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9173. item = lb_emit_array_ep(p, arr, index);
  9174. } else {
  9175. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  9176. }
  9177. if (sub_sel.index.count > 0) {
  9178. item = lb_emit_deep_field_gep(p, item, sub_sel);
  9179. }
  9180. return lb_addr(item);
  9181. }
  9182. lbValue a = lb_addr_get_ptr(p, addr);
  9183. a = lb_emit_deep_field_gep(p, a, sel);
  9184. return lb_addr(a);
  9185. }
  9186. } else {
  9187. GB_PANIC("Unsupported selector expression");
  9188. }
  9189. case_end;
  9190. case_ast_node(se, SelectorCallExpr, expr);
  9191. GB_ASSERT(se->modified_call);
  9192. TypeAndValue tav = type_and_value_of_expr(expr);
  9193. GB_ASSERT(tav.mode != Addressing_Invalid);
  9194. return lb_build_addr(p, se->call);
  9195. case_end;
  9196. case_ast_node(ta, TypeAssertion, expr);
  9197. TokenPos pos = ast_token(expr).pos;
  9198. lbValue e = lb_build_expr(p, ta->expr);
  9199. Type *t = type_deref(e.type);
  9200. if (is_type_union(t)) {
  9201. Type *type = type_of_expr(expr);
  9202. lbAddr v = lb_add_local_generated(p, type, false);
  9203. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  9204. return v;
  9205. } else if (is_type_any(t)) {
  9206. Type *type = type_of_expr(expr);
  9207. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  9208. } else {
  9209. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9210. }
  9211. case_end;
  9212. case_ast_node(ue, UnaryExpr, expr);
  9213. switch (ue->op.kind) {
  9214. case Token_And: {
  9215. return lb_build_addr(p, ue->expr);
  9216. }
  9217. default:
  9218. GB_PANIC("Invalid unary expression for lb_build_addr");
  9219. }
  9220. case_end;
  9221. case_ast_node(be, BinaryExpr, expr);
  9222. lbValue v = lb_build_expr(p, expr);
  9223. Type *t = v.type;
  9224. if (is_type_pointer(t)) {
  9225. return lb_addr(v);
  9226. }
  9227. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  9228. case_end;
  9229. case_ast_node(ie, IndexExpr, expr);
  9230. Type *t = base_type(type_of_expr(ie->expr));
  9231. bool deref = is_type_pointer(t);
  9232. t = base_type(type_deref(t));
  9233. if (is_type_soa_struct(t)) {
  9234. // SOA STRUCTURES!!!!
  9235. lbValue val = lb_build_addr_ptr(p, ie->expr);
  9236. if (deref) {
  9237. val = lb_emit_load(p, val);
  9238. }
  9239. lbValue index = lb_build_expr(p, ie->index);
  9240. return lb_addr_soa_variable(val, index, ie->index);
  9241. }
  9242. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  9243. // SOA Structures for slices/dynamic arrays
  9244. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  9245. lbValue field = lb_build_expr(p, ie->expr);
  9246. lbValue index = lb_build_expr(p, ie->index);
  9247. if (!build_context.no_bounds_check) {
  9248. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  9249. // GB_ASSERT(LLVMIsALoadInst(field.value));
  9250. // lbValue a = {};
  9251. // a.value = LLVMGetOperand(field.value, 0);
  9252. // a.type = alloc_type_pointer(field.type);
  9253. // irInstr *b = &a->Instr;
  9254. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  9255. // lbValue base_struct = b->StructElementPtr.address;
  9256. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  9257. // lbValue len = ir_soa_struct_len(p, base_struct);
  9258. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9259. }
  9260. lbValue val = lb_emit_ptr_offset(p, field, index);
  9261. return lb_addr(val);
  9262. }
  9263. if (!is_type_indexable(t)) {
  9264. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9265. if (found != nullptr) {
  9266. if (found->kind == TypeAtomOp_index_get) {
  9267. return lb_build_addr(p, found->node);
  9268. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  9269. return lb_addr(lb_build_expr(p, found->node));
  9270. } else if (found->kind == TypeAtomOp_index_set) {
  9271. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  9272. if (deref) {
  9273. ptr = lb_emit_load(p, ptr);
  9274. }
  9275. lbAddr addr = {lbAddr_AtomOp_index_set};
  9276. addr.addr = ptr;
  9277. addr.index_set.index = lb_build_expr(p, ie->index);
  9278. addr.index_set.node = found->node;
  9279. return addr;
  9280. }
  9281. }
  9282. }
  9283. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  9284. if (is_type_map(t)) {
  9285. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  9286. if (deref) {
  9287. map_val = lb_emit_load(p, map_val);
  9288. }
  9289. lbValue key = lb_build_expr(p, ie->index);
  9290. key = lb_emit_conv(p, key, t->Map.key);
  9291. Type *result_type = type_of_expr(expr);
  9292. return lb_addr_map(map_val, key, t, result_type);
  9293. }
  9294. switch (t->kind) {
  9295. case Type_Array: {
  9296. lbValue array = {};
  9297. array = lb_build_addr_ptr(p, ie->expr);
  9298. if (deref) {
  9299. array = lb_emit_load(p, array);
  9300. }
  9301. lbValue index = lb_build_expr(p, ie->index);
  9302. index = lb_emit_conv(p, index, t_int);
  9303. lbValue elem = lb_emit_array_ep(p, array, index);
  9304. auto index_tv = type_and_value_of_expr(ie->index);
  9305. if (index_tv.mode != Addressing_Constant) {
  9306. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  9307. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9308. }
  9309. return lb_addr(elem);
  9310. }
  9311. case Type_EnumeratedArray: {
  9312. lbValue array = {};
  9313. array = lb_build_addr_ptr(p, ie->expr);
  9314. if (deref) {
  9315. array = lb_emit_load(p, array);
  9316. }
  9317. Type *index_type = t->EnumeratedArray.index;
  9318. auto index_tv = type_and_value_of_expr(ie->index);
  9319. lbValue index = {};
  9320. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  9321. if (index_tv.mode == Addressing_Constant) {
  9322. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  9323. index = lb_const_value(p->module, index_type, idx);
  9324. } else {
  9325. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9326. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  9327. }
  9328. } else {
  9329. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9330. }
  9331. lbValue elem = lb_emit_array_ep(p, array, index);
  9332. if (index_tv.mode != Addressing_Constant) {
  9333. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  9334. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9335. }
  9336. return lb_addr(elem);
  9337. }
  9338. case Type_Slice: {
  9339. lbValue slice = {};
  9340. slice = lb_build_expr(p, ie->expr);
  9341. if (deref) {
  9342. slice = lb_emit_load(p, slice);
  9343. }
  9344. lbValue elem = lb_slice_elem(p, slice);
  9345. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9346. lbValue len = lb_slice_len(p, slice);
  9347. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9348. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9349. return lb_addr(v);
  9350. }
  9351. case Type_RelativeSlice: {
  9352. lbAddr slice_addr = {};
  9353. if (deref) {
  9354. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  9355. } else {
  9356. slice_addr = lb_build_addr(p, ie->expr);
  9357. }
  9358. lbValue slice = lb_addr_load(p, slice_addr);
  9359. lbValue elem = lb_slice_elem(p, slice);
  9360. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9361. lbValue len = lb_slice_len(p, slice);
  9362. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9363. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9364. return lb_addr(v);
  9365. }
  9366. case Type_DynamicArray: {
  9367. lbValue dynamic_array = {};
  9368. dynamic_array = lb_build_expr(p, ie->expr);
  9369. if (deref) {
  9370. dynamic_array = lb_emit_load(p, dynamic_array);
  9371. }
  9372. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  9373. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  9374. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9375. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9376. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9377. return lb_addr(v);
  9378. }
  9379. case Type_Basic: { // Basic_string
  9380. lbValue str;
  9381. lbValue elem;
  9382. lbValue len;
  9383. lbValue index;
  9384. str = lb_build_expr(p, ie->expr);
  9385. if (deref) {
  9386. str = lb_emit_load(p, str);
  9387. }
  9388. elem = lb_string_elem(p, str);
  9389. len = lb_string_len(p, str);
  9390. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9391. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9392. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  9393. }
  9394. }
  9395. case_end;
  9396. case_ast_node(se, SliceExpr, expr);
  9397. lbValue low = lb_const_int(p->module, t_int, 0);
  9398. lbValue high = {};
  9399. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  9400. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  9401. bool no_indices = se->low == nullptr && se->high == nullptr;
  9402. {
  9403. Type *type = base_type(type_of_expr(se->expr));
  9404. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  9405. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  9406. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  9407. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9408. if (found) {
  9409. lbValue base = lb_build_expr(p, found->node);
  9410. Type *slice_type = base.type;
  9411. lbValue len = lb_slice_len(p, base);
  9412. if (high.value == nullptr) high = len;
  9413. if (!no_indices) {
  9414. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9415. }
  9416. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9417. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9418. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9419. lb_fill_slice(p, slice, elem, new_len);
  9420. return slice;
  9421. }
  9422. }
  9423. }
  9424. }
  9425. lbAddr addr = lb_build_addr(p, se->expr);
  9426. lbValue base = lb_addr_load(p, addr);
  9427. Type *type = base_type(base.type);
  9428. if (is_type_pointer(type)) {
  9429. type = base_type(type_deref(type));
  9430. addr = lb_addr(base);
  9431. base = lb_addr_load(p, addr);
  9432. }
  9433. switch (type->kind) {
  9434. case Type_Slice: {
  9435. Type *slice_type = type;
  9436. lbValue len = lb_slice_len(p, base);
  9437. if (high.value == nullptr) high = len;
  9438. if (!no_indices) {
  9439. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9440. }
  9441. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9442. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9443. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9444. lb_fill_slice(p, slice, elem, new_len);
  9445. return slice;
  9446. }
  9447. case Type_RelativeSlice:
  9448. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  9449. break;
  9450. case Type_DynamicArray: {
  9451. Type *elem_type = type->DynamicArray.elem;
  9452. Type *slice_type = alloc_type_slice(elem_type);
  9453. lbValue len = lb_dynamic_array_len(p, base);
  9454. if (high.value == nullptr) high = len;
  9455. if (!no_indices) {
  9456. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9457. }
  9458. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  9459. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9460. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9461. lb_fill_slice(p, slice, elem, new_len);
  9462. return slice;
  9463. }
  9464. case Type_Array: {
  9465. Type *slice_type = alloc_type_slice(type->Array.elem);
  9466. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  9467. if (high.value == nullptr) high = len;
  9468. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  9469. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  9470. if (!low_const || !high_const) {
  9471. if (!no_indices) {
  9472. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9473. }
  9474. }
  9475. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  9476. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9477. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9478. lb_fill_slice(p, slice, elem, new_len);
  9479. return slice;
  9480. }
  9481. case Type_Basic: {
  9482. GB_ASSERT(type == t_string);
  9483. lbValue len = lb_string_len(p, base);
  9484. if (high.value == nullptr) high = len;
  9485. if (!no_indices) {
  9486. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9487. }
  9488. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  9489. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9490. lbAddr str = lb_add_local_generated(p, t_string, false);
  9491. lb_fill_string(p, str, elem, new_len);
  9492. return str;
  9493. }
  9494. case Type_Struct:
  9495. if (is_type_soa_struct(type)) {
  9496. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  9497. if (high.value == nullptr) high = len;
  9498. if (!no_indices) {
  9499. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9500. }
  9501. #if 1
  9502. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  9503. if (type->Struct.soa_kind == StructSoa_Fixed) {
  9504. i32 field_count = cast(i32)type->Struct.fields.count;
  9505. for (i32 i = 0; i < field_count; i++) {
  9506. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9507. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  9508. field_src = lb_emit_array_ep(p, field_src, low);
  9509. lb_emit_store(p, field_dst, field_src);
  9510. }
  9511. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9512. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9513. lb_emit_store(p, len_dst, new_len);
  9514. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  9515. if (no_indices) {
  9516. lb_addr_store(p, dst, base);
  9517. } else {
  9518. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  9519. for (i32 i = 0; i < field_count; i++) {
  9520. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9521. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9522. field_src = lb_emit_ptr_offset(p, field_src, low);
  9523. lb_emit_store(p, field_dst, field_src);
  9524. }
  9525. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9526. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9527. lb_emit_store(p, len_dst, new_len);
  9528. }
  9529. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  9530. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  9531. for (i32 i = 0; i < field_count; i++) {
  9532. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9533. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9534. field_src = lb_emit_ptr_offset(p, field_src, low);
  9535. lb_emit_store(p, field_dst, field_src);
  9536. }
  9537. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9538. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9539. lb_emit_store(p, len_dst, new_len);
  9540. }
  9541. return dst;
  9542. #endif
  9543. }
  9544. break;
  9545. }
  9546. GB_PANIC("Unknown slicable type");
  9547. case_end;
  9548. case_ast_node(de, DerefExpr, expr);
  9549. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  9550. lbAddr addr = lb_build_addr(p, de->expr);
  9551. addr.relative.deref = true;
  9552. return addr;
  9553. }
  9554. lbValue addr = lb_build_expr(p, de->expr);
  9555. return lb_addr(addr);
  9556. case_end;
  9557. case_ast_node(ce, CallExpr, expr);
  9558. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  9559. lbValue e = lb_build_expr(p, expr);
  9560. lbAddr v = lb_add_local_generated(p, e.type, false);
  9561. lb_addr_store(p, v, e);
  9562. return v;
  9563. case_end;
  9564. case_ast_node(cl, CompoundLit, expr);
  9565. Type *type = type_of_expr(expr);
  9566. Type *bt = base_type(type);
  9567. lbAddr v = lb_add_local_generated(p, type, true);
  9568. Type *et = nullptr;
  9569. switch (bt->kind) {
  9570. case Type_Array: et = bt->Array.elem; break;
  9571. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  9572. case Type_Slice: et = bt->Slice.elem; break;
  9573. case Type_BitSet: et = bt->BitSet.elem; break;
  9574. case Type_SimdVector: et = bt->SimdVector.elem; break;
  9575. }
  9576. String proc_name = {};
  9577. if (p->entity) {
  9578. proc_name = p->entity->token.string;
  9579. }
  9580. TokenPos pos = ast_token(expr).pos;
  9581. switch (bt->kind) {
  9582. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  9583. case Type_Struct: {
  9584. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  9585. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  9586. bool is_raw_union = is_type_raw_union(bt);
  9587. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  9588. TypeStruct *st = &bt->Struct;
  9589. if (cl->elems.count > 0) {
  9590. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9591. for_array(field_index, cl->elems) {
  9592. Ast *elem = cl->elems[field_index];
  9593. lbValue field_expr = {};
  9594. Entity *field = nullptr;
  9595. isize index = field_index;
  9596. if (elem->kind == Ast_FieldValue) {
  9597. ast_node(fv, FieldValue, elem);
  9598. String name = fv->field->Ident.token.string;
  9599. Selection sel = lookup_field(bt, name, false);
  9600. index = sel.index[0];
  9601. elem = fv->value;
  9602. TypeAndValue tav = type_and_value_of_expr(elem);
  9603. } else {
  9604. TypeAndValue tav = type_and_value_of_expr(elem);
  9605. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  9606. index = sel.index[0];
  9607. }
  9608. field = st->fields[index];
  9609. Type *ft = field->type;
  9610. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  9611. continue;
  9612. }
  9613. field_expr = lb_build_expr(p, elem);
  9614. Type *fet = field_expr.type;
  9615. GB_ASSERT(fet->kind != Type_Tuple);
  9616. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  9617. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  9618. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  9619. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9620. lb_emit_store_union_variant(p, gep, field_expr, fet);
  9621. } else {
  9622. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9623. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9624. lb_emit_store(p, gep, fv);
  9625. }
  9626. }
  9627. }
  9628. break;
  9629. }
  9630. case Type_Map: {
  9631. if (cl->elems.count == 0) {
  9632. break;
  9633. }
  9634. {
  9635. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9636. args[0] = lb_gen_map_header(p, v.addr, type);
  9637. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  9638. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  9639. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  9640. }
  9641. for_array(field_index, cl->elems) {
  9642. Ast *elem = cl->elems[field_index];
  9643. ast_node(fv, FieldValue, elem);
  9644. lbValue key = lb_build_expr(p, fv->field);
  9645. lbValue value = lb_build_expr(p, fv->value);
  9646. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  9647. }
  9648. break;
  9649. }
  9650. case Type_Array: {
  9651. if (cl->elems.count > 0) {
  9652. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9653. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9654. // NOTE(bill): Separate value, gep, store into their own chunks
  9655. for_array(i, cl->elems) {
  9656. Ast *elem = cl->elems[i];
  9657. if (elem->kind == Ast_FieldValue) {
  9658. ast_node(fv, FieldValue, elem);
  9659. if (lb_is_elem_const(fv->value, et)) {
  9660. continue;
  9661. }
  9662. if (is_ast_range(fv->field)) {
  9663. ast_node(ie, BinaryExpr, fv->field);
  9664. TypeAndValue lo_tav = ie->left->tav;
  9665. TypeAndValue hi_tav = ie->right->tav;
  9666. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9667. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9668. TokenKind op = ie->op.kind;
  9669. i64 lo = exact_value_to_i64(lo_tav.value);
  9670. i64 hi = exact_value_to_i64(hi_tav.value);
  9671. if (op == Token_Ellipsis) {
  9672. hi += 1;
  9673. }
  9674. lbValue value = lb_build_expr(p, fv->value);
  9675. for (i64 k = lo; k < hi; k++) {
  9676. lbCompoundLitElemTempData data = {};
  9677. data.value = value;
  9678. data.elem_index = cast(i32)k;
  9679. array_add(&temp_data, data);
  9680. }
  9681. } else {
  9682. auto tav = fv->field->tav;
  9683. GB_ASSERT(tav.mode == Addressing_Constant);
  9684. i64 index = exact_value_to_i64(tav.value);
  9685. lbValue value = lb_build_expr(p, fv->value);
  9686. lbCompoundLitElemTempData data = {};
  9687. data.value = lb_emit_conv(p, value, et);
  9688. data.expr = fv->value;
  9689. data.elem_index = cast(i32)index;
  9690. array_add(&temp_data, data);
  9691. }
  9692. } else {
  9693. if (lb_is_elem_const(elem, et)) {
  9694. continue;
  9695. }
  9696. lbCompoundLitElemTempData data = {};
  9697. data.expr = elem;
  9698. data.elem_index = cast(i32)i;
  9699. array_add(&temp_data, data);
  9700. }
  9701. }
  9702. for_array(i, temp_data) {
  9703. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  9704. }
  9705. for_array(i, temp_data) {
  9706. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9707. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9708. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9709. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9710. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9711. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9712. lbValue field_expr = temp_data[i].value;
  9713. Ast *expr = temp_data[i].expr;
  9714. p->return_ptr_hint_value = temp_data[i].gep;
  9715. p->return_ptr_hint_ast = unparen_expr(expr);
  9716. if (field_expr.value == nullptr) {
  9717. field_expr = lb_build_expr(p, expr);
  9718. }
  9719. Type *t = field_expr.type;
  9720. GB_ASSERT(t->kind != Type_Tuple);
  9721. lbValue ev = lb_emit_conv(p, field_expr, et);
  9722. if (!p->return_ptr_hint_used) {
  9723. temp_data[i].value = ev;
  9724. }
  9725. }
  9726. for_array(i, temp_data) {
  9727. if (temp_data[i].value.value != nullptr) {
  9728. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9729. }
  9730. }
  9731. }
  9732. break;
  9733. }
  9734. case Type_EnumeratedArray: {
  9735. if (cl->elems.count > 0) {
  9736. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9737. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9738. // NOTE(bill): Separate value, gep, store into their own chunks
  9739. for_array(i, cl->elems) {
  9740. Ast *elem = cl->elems[i];
  9741. if (elem->kind == Ast_FieldValue) {
  9742. ast_node(fv, FieldValue, elem);
  9743. if (lb_is_elem_const(fv->value, et)) {
  9744. continue;
  9745. }
  9746. if (is_ast_range(fv->field)) {
  9747. ast_node(ie, BinaryExpr, fv->field);
  9748. TypeAndValue lo_tav = ie->left->tav;
  9749. TypeAndValue hi_tav = ie->right->tav;
  9750. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9751. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9752. TokenKind op = ie->op.kind;
  9753. i64 lo = exact_value_to_i64(lo_tav.value);
  9754. i64 hi = exact_value_to_i64(hi_tav.value);
  9755. if (op == Token_Ellipsis) {
  9756. hi += 1;
  9757. }
  9758. lbValue value = lb_build_expr(p, fv->value);
  9759. for (i64 k = lo; k < hi; k++) {
  9760. lbCompoundLitElemTempData data = {};
  9761. data.value = value;
  9762. data.elem_index = cast(i32)k;
  9763. array_add(&temp_data, data);
  9764. }
  9765. } else {
  9766. auto tav = fv->field->tav;
  9767. GB_ASSERT(tav.mode == Addressing_Constant);
  9768. i64 index = exact_value_to_i64(tav.value);
  9769. lbValue value = lb_build_expr(p, fv->value);
  9770. lbCompoundLitElemTempData data = {};
  9771. data.value = lb_emit_conv(p, value, et);
  9772. data.expr = fv->value;
  9773. data.elem_index = cast(i32)index;
  9774. array_add(&temp_data, data);
  9775. }
  9776. } else {
  9777. if (lb_is_elem_const(elem, et)) {
  9778. continue;
  9779. }
  9780. lbCompoundLitElemTempData data = {};
  9781. data.expr = elem;
  9782. data.elem_index = cast(i32)i;
  9783. array_add(&temp_data, data);
  9784. }
  9785. }
  9786. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  9787. for_array(i, temp_data) {
  9788. i32 index = temp_data[i].elem_index - index_offset;
  9789. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  9790. }
  9791. for_array(i, temp_data) {
  9792. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9793. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9794. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9795. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9796. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9797. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9798. lbValue field_expr = temp_data[i].value;
  9799. Ast *expr = temp_data[i].expr;
  9800. p->return_ptr_hint_value = temp_data[i].gep;
  9801. p->return_ptr_hint_ast = unparen_expr(expr);
  9802. if (field_expr.value == nullptr) {
  9803. field_expr = lb_build_expr(p, expr);
  9804. }
  9805. Type *t = field_expr.type;
  9806. GB_ASSERT(t->kind != Type_Tuple);
  9807. lbValue ev = lb_emit_conv(p, field_expr, et);
  9808. if (!p->return_ptr_hint_used) {
  9809. temp_data[i].value = ev;
  9810. }
  9811. }
  9812. for_array(i, temp_data) {
  9813. if (temp_data[i].value.value != nullptr) {
  9814. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9815. }
  9816. }
  9817. }
  9818. break;
  9819. }
  9820. case Type_Slice: {
  9821. if (cl->elems.count > 0) {
  9822. Type *elem_type = bt->Slice.elem;
  9823. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  9824. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  9825. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  9826. lbValue data = lb_slice_elem(p, slice);
  9827. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9828. for_array(i, cl->elems) {
  9829. Ast *elem = cl->elems[i];
  9830. if (elem->kind == Ast_FieldValue) {
  9831. ast_node(fv, FieldValue, elem);
  9832. if (lb_is_elem_const(fv->value, et)) {
  9833. continue;
  9834. }
  9835. if (is_ast_range(fv->field)) {
  9836. ast_node(ie, BinaryExpr, fv->field);
  9837. TypeAndValue lo_tav = ie->left->tav;
  9838. TypeAndValue hi_tav = ie->right->tav;
  9839. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9840. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9841. TokenKind op = ie->op.kind;
  9842. i64 lo = exact_value_to_i64(lo_tav.value);
  9843. i64 hi = exact_value_to_i64(hi_tav.value);
  9844. if (op == Token_Ellipsis) {
  9845. hi += 1;
  9846. }
  9847. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9848. for (i64 k = lo; k < hi; k++) {
  9849. lbCompoundLitElemTempData data = {};
  9850. data.value = value;
  9851. data.elem_index = cast(i32)k;
  9852. array_add(&temp_data, data);
  9853. }
  9854. } else {
  9855. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9856. i64 index = exact_value_to_i64(fv->field->tav.value);
  9857. lbValue field_expr = lb_build_expr(p, fv->value);
  9858. GB_ASSERT(!is_type_tuple(field_expr.type));
  9859. lbValue ev = lb_emit_conv(p, field_expr, et);
  9860. lbCompoundLitElemTempData data = {};
  9861. data.value = ev;
  9862. data.elem_index = cast(i32)index;
  9863. array_add(&temp_data, data);
  9864. }
  9865. } else {
  9866. if (lb_is_elem_const(elem, et)) {
  9867. continue;
  9868. }
  9869. lbValue field_expr = lb_build_expr(p, elem);
  9870. GB_ASSERT(!is_type_tuple(field_expr.type));
  9871. lbValue ev = lb_emit_conv(p, field_expr, et);
  9872. lbCompoundLitElemTempData data = {};
  9873. data.value = ev;
  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_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  9880. }
  9881. for_array(i, temp_data) {
  9882. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9883. }
  9884. {
  9885. lbValue count = {};
  9886. count.type = t_int;
  9887. if (lb_is_const(slice)) {
  9888. unsigned indices[1] = {1};
  9889. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  9890. } else {
  9891. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  9892. }
  9893. lb_fill_slice(p, v, data, count);
  9894. }
  9895. }
  9896. break;
  9897. }
  9898. case Type_DynamicArray: {
  9899. if (cl->elems.count == 0) {
  9900. break;
  9901. }
  9902. Type *et = bt->DynamicArray.elem;
  9903. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  9904. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  9905. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  9906. {
  9907. auto args = array_make<lbValue>(permanent_allocator(), 5);
  9908. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  9909. args[1] = size;
  9910. args[2] = align;
  9911. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  9912. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  9913. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  9914. }
  9915. lbValue items = lb_generate_local_array(p, et, item_count);
  9916. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  9917. for_array(i, cl->elems) {
  9918. Ast *elem = cl->elems[i];
  9919. if (elem->kind == Ast_FieldValue) {
  9920. ast_node(fv, FieldValue, elem);
  9921. if (is_ast_range(fv->field)) {
  9922. ast_node(ie, BinaryExpr, fv->field);
  9923. TypeAndValue lo_tav = ie->left->tav;
  9924. TypeAndValue hi_tav = ie->right->tav;
  9925. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9926. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9927. TokenKind op = ie->op.kind;
  9928. i64 lo = exact_value_to_i64(lo_tav.value);
  9929. i64 hi = exact_value_to_i64(hi_tav.value);
  9930. if (op == Token_Ellipsis) {
  9931. hi += 1;
  9932. }
  9933. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9934. for (i64 k = lo; k < hi; k++) {
  9935. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  9936. lb_emit_store(p, ep, value);
  9937. }
  9938. } else {
  9939. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9940. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  9941. lbValue ev = lb_build_expr(p, fv->value);
  9942. lbValue value = lb_emit_conv(p, ev, et);
  9943. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  9944. lb_emit_store(p, ep, value);
  9945. }
  9946. } else {
  9947. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  9948. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  9949. lb_emit_store(p, ep, value);
  9950. }
  9951. }
  9952. {
  9953. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9954. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  9955. args[1] = size;
  9956. args[2] = align;
  9957. args[3] = lb_emit_conv(p, items, t_rawptr);
  9958. args[4] = lb_const_int(p->module, t_int, item_count);
  9959. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  9960. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  9961. }
  9962. break;
  9963. }
  9964. case Type_Basic: {
  9965. GB_ASSERT(is_type_any(bt));
  9966. if (cl->elems.count > 0) {
  9967. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9968. String field_names[2] = {
  9969. str_lit("data"),
  9970. str_lit("id"),
  9971. };
  9972. Type *field_types[2] = {
  9973. t_rawptr,
  9974. t_typeid,
  9975. };
  9976. for_array(field_index, cl->elems) {
  9977. Ast *elem = cl->elems[field_index];
  9978. lbValue field_expr = {};
  9979. isize index = field_index;
  9980. if (elem->kind == Ast_FieldValue) {
  9981. ast_node(fv, FieldValue, elem);
  9982. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  9983. index = sel.index[0];
  9984. elem = fv->value;
  9985. } else {
  9986. TypeAndValue tav = type_and_value_of_expr(elem);
  9987. Selection sel = lookup_field(bt, field_names[field_index], false);
  9988. index = sel.index[0];
  9989. }
  9990. field_expr = lb_build_expr(p, elem);
  9991. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  9992. Type *ft = field_types[index];
  9993. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9994. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9995. lb_emit_store(p, gep, fv);
  9996. }
  9997. }
  9998. break;
  9999. }
  10000. case Type_BitSet: {
  10001. i64 sz = type_size_of(type);
  10002. if (cl->elems.count > 0 && sz > 0) {
  10003. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10004. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  10005. for_array(i, cl->elems) {
  10006. Ast *elem = cl->elems[i];
  10007. GB_ASSERT(elem->kind != Ast_FieldValue);
  10008. if (lb_is_elem_const(elem, et)) {
  10009. continue;
  10010. }
  10011. lbValue expr = lb_build_expr(p, elem);
  10012. GB_ASSERT(expr.type->kind != Type_Tuple);
  10013. Type *it = bit_set_to_int(bt);
  10014. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  10015. lbValue e = lb_emit_conv(p, expr, it);
  10016. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  10017. e = lb_emit_arith(p, Token_Shl, one, e, it);
  10018. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  10019. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  10020. new_value = lb_emit_transmute(p, new_value, type);
  10021. lb_addr_store(p, v, new_value);
  10022. }
  10023. }
  10024. break;
  10025. }
  10026. }
  10027. return v;
  10028. case_end;
  10029. case_ast_node(tc, TypeCast, expr);
  10030. Type *type = type_of_expr(expr);
  10031. lbValue x = lb_build_expr(p, tc->expr);
  10032. lbValue e = {};
  10033. switch (tc->token.kind) {
  10034. case Token_cast:
  10035. e = lb_emit_conv(p, x, type);
  10036. break;
  10037. case Token_transmute:
  10038. e = lb_emit_transmute(p, x, type);
  10039. break;
  10040. default:
  10041. GB_PANIC("Invalid AST TypeCast");
  10042. }
  10043. lbAddr v = lb_add_local_generated(p, type, false);
  10044. lb_addr_store(p, v, e);
  10045. return v;
  10046. case_end;
  10047. case_ast_node(ac, AutoCast, expr);
  10048. return lb_build_addr(p, ac->expr);
  10049. case_end;
  10050. }
  10051. TokenPos token_pos = ast_token(expr).pos;
  10052. GB_PANIC("Unexpected address expression\n"
  10053. "\tAst: %.*s @ "
  10054. "%s\n",
  10055. LIT(ast_strings[expr->kind]),
  10056. token_pos_to_string(token_pos));
  10057. return {};
  10058. }
  10059. void lb_init_module(lbModule *m, Checker *c) {
  10060. m->info = &c->info;
  10061. m->ctx = LLVMGetGlobalContext();
  10062. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  10063. // m->debug_builder = nullptr;
  10064. if (build_context.ODIN_DEBUG) {
  10065. enum {DEBUG_METADATA_VERSION = 3};
  10066. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  10067. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  10068. if (build_context.metrics.os == TargetOs_windows) {
  10069. LLVMMetadataRef ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true));
  10070. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "CodeView", 8, ref);
  10071. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  10072. }
  10073. }
  10074. m->state_flags = 0;
  10075. m->state_flags |= StateFlag_bounds_check;
  10076. gb_mutex_init(&m->mutex);
  10077. gbAllocator a = heap_allocator();
  10078. map_init(&m->types, a);
  10079. map_init(&m->llvm_types, a);
  10080. map_init(&m->values, a);
  10081. string_map_init(&m->members, a);
  10082. map_init(&m->procedure_values, a);
  10083. string_map_init(&m->procedures, a);
  10084. string_map_init(&m->const_strings, a);
  10085. map_init(&m->anonymous_proc_lits, a);
  10086. map_init(&m->function_type_map, a);
  10087. map_init(&m->equal_procs, a);
  10088. map_init(&m->hasher_procs, a);
  10089. array_init(&m->procedures_to_generate, a, 0, 1024);
  10090. array_init(&m->foreign_library_paths, a, 0, 1024);
  10091. map_init(&m->debug_values, a);
  10092. array_init(&m->debug_incomplete_types, a, 0, 1024);
  10093. }
  10094. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  10095. if (global_error_collector.count != 0) {
  10096. return false;
  10097. }
  10098. isize tc = c->parser->total_token_count;
  10099. if (tc < 2) {
  10100. return false;
  10101. }
  10102. String init_fullpath = c->parser->init_fullpath;
  10103. if (build_context.out_filepath.len == 0) {
  10104. gen->output_name = remove_directory_from_path(init_fullpath);
  10105. gen->output_name = remove_extension_from_path(gen->output_name);
  10106. gen->output_name = string_trim_whitespace(gen->output_name);
  10107. if (gen->output_name.len == 0) {
  10108. gen->output_name = c->info.init_scope->pkg->name;
  10109. }
  10110. gen->output_base = gen->output_name;
  10111. } else {
  10112. gen->output_name = build_context.out_filepath;
  10113. gen->output_name = string_trim_whitespace(gen->output_name);
  10114. if (gen->output_name.len == 0) {
  10115. gen->output_name = c->info.init_scope->pkg->name;
  10116. }
  10117. isize pos = string_extension_position(gen->output_name);
  10118. if (pos < 0) {
  10119. gen->output_base = gen->output_name;
  10120. } else {
  10121. gen->output_base = substring(gen->output_name, 0, pos);
  10122. }
  10123. }
  10124. gbAllocator ha = heap_allocator();
  10125. array_init(&gen->output_object_paths, ha);
  10126. gen->output_base = path_to_full_path(ha, gen->output_base);
  10127. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  10128. output_file_path = gb_string_appendc(output_file_path, ".obj");
  10129. defer (gb_string_free(output_file_path));
  10130. gen->info = &c->info;
  10131. lb_init_module(&gen->module, c);
  10132. return true;
  10133. }
  10134. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  10135. GB_ASSERT(type != nullptr);
  10136. type = default_type(type);
  10137. isize max_len = 7+8+1;
  10138. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  10139. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  10140. m->global_generated_index++;
  10141. String name = make_string(str, len-1);
  10142. Scope *scope = nullptr;
  10143. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  10144. lbValue g = {};
  10145. g.type = alloc_type_pointer(type);
  10146. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  10147. if (value.value != nullptr) {
  10148. GB_ASSERT(LLVMIsConstant(value.value));
  10149. LLVMSetInitializer(g.value, value.value);
  10150. } else {
  10151. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  10152. }
  10153. lb_add_entity(m, e, g);
  10154. lb_add_member(m, name, g);
  10155. return lb_addr(g);
  10156. }
  10157. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  10158. AstPackage *p = m->info->runtime_package;
  10159. Entity *e = scope_lookup_current(p->scope, name);
  10160. lbValue *found = map_get(&m->values, hash_entity(e));
  10161. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  10162. lbValue value = *found;
  10163. return value;
  10164. }
  10165. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  10166. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  10167. lbValue *found = map_get(&m->values, hash_entity(e));
  10168. GB_ASSERT_MSG(found != nullptr, "Unable to find value '%.*s.%.*s'", LIT(pkg), LIT(name));
  10169. lbValue value = *found;
  10170. return value;
  10171. }
  10172. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  10173. i32 index = cast(i32)lb_type_info_index(m->info, type);
  10174. GB_ASSERT(index >= 0);
  10175. // gb_printf_err("%d %s\n", index, type_to_string(type));
  10176. LLVMValueRef indices[2] = {
  10177. LLVMConstInt(lb_type(m, t_int), 0, false),
  10178. LLVMConstInt(lb_type(m, t_int), index, false),
  10179. };
  10180. lbValue res = {};
  10181. res.type = t_type_info_ptr;
  10182. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  10183. return res;
  10184. }
  10185. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  10186. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  10187. lb_global_type_info_member_types_index += cast(i32)count;
  10188. return offset;
  10189. }
  10190. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  10191. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  10192. lb_global_type_info_member_names_index += cast(i32)count;
  10193. return offset;
  10194. }
  10195. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  10196. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  10197. lb_global_type_info_member_offsets_index += cast(i32)count;
  10198. return offset;
  10199. }
  10200. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  10201. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  10202. lb_global_type_info_member_usings_index += cast(i32)count;
  10203. return offset;
  10204. }
  10205. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  10206. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  10207. lb_global_type_info_member_tags_index += cast(i32)count;
  10208. return offset;
  10209. }
  10210. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  10211. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  10212. return lb_addr_get_ptr(p, addr);
  10213. }
  10214. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  10215. Token token = {Token_Ident};
  10216. isize name_len = prefix.len + 1 + 20;
  10217. auto suffix_id = cast(unsigned long long)id;
  10218. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  10219. gb_snprintf(text, name_len,
  10220. "%.*s-%llu", LIT(prefix), suffix_id);
  10221. text[name_len] = 0;
  10222. String s = make_string_c(text);
  10223. Type *t = alloc_type_array(elem_type, count);
  10224. lbValue g = {};
  10225. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  10226. g.type = alloc_type_pointer(t);
  10227. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  10228. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  10229. string_map_set(&m->members, s, g);
  10230. return g;
  10231. }
  10232. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  10233. lbModule *m = p->module;
  10234. LLVMContextRef ctx = m->ctx;
  10235. CheckerInfo *info = m->info;
  10236. {
  10237. // NOTE(bill): Set the type_table slice with the global backing array
  10238. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  10239. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  10240. GB_ASSERT(is_type_array(type));
  10241. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  10242. LLVMValueRef values[2] = {
  10243. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  10244. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  10245. };
  10246. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  10247. LLVMSetInitializer(global_type_table.value, slice);
  10248. }
  10249. // Useful types
  10250. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  10251. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  10252. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  10253. Type *t_type_info_flags = type_info_flags_entity->type;
  10254. i32 type_info_member_types_index = 0;
  10255. i32 type_info_member_names_index = 0;
  10256. i32 type_info_member_offsets_index = 0;
  10257. for_array(type_info_type_index, info->type_info_types) {
  10258. Type *t = info->type_info_types[type_info_type_index];
  10259. if (t == nullptr || t == t_invalid) {
  10260. continue;
  10261. }
  10262. isize entry_index = lb_type_info_index(info, t, false);
  10263. if (entry_index <= 0) {
  10264. continue;
  10265. }
  10266. lbValue tag = {};
  10267. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  10268. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  10269. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  10270. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  10271. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  10272. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  10273. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  10274. switch (t->kind) {
  10275. case Type_Named: {
  10276. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  10277. LLVMValueRef pkg_name = nullptr;
  10278. if (t->Named.type_name->pkg) {
  10279. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  10280. } else {
  10281. pkg_name = LLVMConstNull(lb_type(m, t_string));
  10282. }
  10283. String proc_name = {};
  10284. if (t->Named.type_name->parent_proc_decl) {
  10285. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  10286. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  10287. proc_name = decl->entity->token.string;
  10288. }
  10289. }
  10290. TokenPos pos = t->Named.type_name->token.pos;
  10291. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  10292. LLVMValueRef vals[4] = {
  10293. lb_const_string(p->module, t->Named.type_name->token.string).value,
  10294. lb_get_type_info_ptr(m, t->Named.base).value,
  10295. pkg_name,
  10296. loc.value
  10297. };
  10298. lbValue res = {};
  10299. res.type = type_deref(tag.type);
  10300. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10301. lb_emit_store(p, tag, res);
  10302. break;
  10303. }
  10304. case Type_Basic:
  10305. switch (t->Basic.kind) {
  10306. case Basic_bool:
  10307. case Basic_b8:
  10308. case Basic_b16:
  10309. case Basic_b32:
  10310. case Basic_b64:
  10311. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  10312. break;
  10313. case Basic_i8:
  10314. case Basic_u8:
  10315. case Basic_i16:
  10316. case Basic_u16:
  10317. case Basic_i32:
  10318. case Basic_u32:
  10319. case Basic_i64:
  10320. case Basic_u64:
  10321. case Basic_i128:
  10322. case Basic_u128:
  10323. case Basic_i16le:
  10324. case Basic_u16le:
  10325. case Basic_i32le:
  10326. case Basic_u32le:
  10327. case Basic_i64le:
  10328. case Basic_u64le:
  10329. case Basic_i128le:
  10330. case Basic_u128le:
  10331. case Basic_i16be:
  10332. case Basic_u16be:
  10333. case Basic_i32be:
  10334. case Basic_u32be:
  10335. case Basic_i64be:
  10336. case Basic_u64be:
  10337. case Basic_i128be:
  10338. case Basic_u128be:
  10339. case Basic_int:
  10340. case Basic_uint:
  10341. case Basic_uintptr: {
  10342. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  10343. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  10344. // NOTE(bill): This is matches the runtime layout
  10345. u8 endianness_value = 0;
  10346. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10347. endianness_value = 1;
  10348. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10349. endianness_value = 2;
  10350. }
  10351. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10352. LLVMValueRef vals[2] = {
  10353. is_signed.value,
  10354. endianness.value,
  10355. };
  10356. lbValue res = {};
  10357. res.type = type_deref(tag.type);
  10358. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10359. lb_emit_store(p, tag, res);
  10360. break;
  10361. }
  10362. case Basic_rune:
  10363. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  10364. break;
  10365. // case Basic_f16:
  10366. case Basic_f32:
  10367. case Basic_f64:
  10368. case Basic_f32le:
  10369. case Basic_f64le:
  10370. case Basic_f32be:
  10371. case Basic_f64be:
  10372. {
  10373. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  10374. // NOTE(bill): This is matches the runtime layout
  10375. u8 endianness_value = 0;
  10376. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10377. endianness_value = 1;
  10378. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10379. endianness_value = 2;
  10380. }
  10381. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10382. LLVMValueRef vals[1] = {
  10383. endianness.value,
  10384. };
  10385. lbValue res = {};
  10386. res.type = type_deref(tag.type);
  10387. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10388. lb_emit_store(p, tag, res);
  10389. }
  10390. break;
  10391. // case Basic_complex32:
  10392. case Basic_complex64:
  10393. case Basic_complex128:
  10394. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  10395. break;
  10396. case Basic_quaternion128:
  10397. case Basic_quaternion256:
  10398. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  10399. break;
  10400. case Basic_rawptr:
  10401. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10402. break;
  10403. case Basic_string:
  10404. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10405. break;
  10406. case Basic_cstring:
  10407. {
  10408. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10409. LLVMValueRef vals[1] = {
  10410. lb_const_bool(m, t_bool, true).value,
  10411. };
  10412. lbValue res = {};
  10413. res.type = type_deref(tag.type);
  10414. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10415. lb_emit_store(p, tag, res);
  10416. }
  10417. break;
  10418. case Basic_any:
  10419. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  10420. break;
  10421. case Basic_typeid:
  10422. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  10423. break;
  10424. }
  10425. break;
  10426. case Type_Pointer: {
  10427. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10428. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  10429. LLVMValueRef vals[1] = {
  10430. gep.value,
  10431. };
  10432. lbValue res = {};
  10433. res.type = type_deref(tag.type);
  10434. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10435. lb_emit_store(p, tag, res);
  10436. break;
  10437. }
  10438. case Type_Array: {
  10439. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  10440. i64 ez = type_size_of(t->Array.elem);
  10441. LLVMValueRef vals[3] = {
  10442. lb_get_type_info_ptr(m, t->Array.elem).value,
  10443. lb_const_int(m, t_int, ez).value,
  10444. lb_const_int(m, t_int, t->Array.count).value,
  10445. };
  10446. lbValue res = {};
  10447. res.type = type_deref(tag.type);
  10448. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10449. lb_emit_store(p, tag, res);
  10450. break;
  10451. }
  10452. case Type_EnumeratedArray: {
  10453. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  10454. LLVMValueRef vals[6] = {
  10455. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  10456. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  10457. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  10458. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  10459. // Unions
  10460. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10461. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10462. };
  10463. lbValue res = {};
  10464. res.type = type_deref(tag.type);
  10465. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10466. lb_emit_store(p, tag, res);
  10467. // NOTE(bill): Union assignment
  10468. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  10469. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  10470. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  10471. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  10472. lb_emit_store(p, min_value, min_v);
  10473. lb_emit_store(p, max_value, max_v);
  10474. break;
  10475. }
  10476. case Type_DynamicArray: {
  10477. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  10478. LLVMValueRef vals[2] = {
  10479. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  10480. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  10481. };
  10482. lbValue res = {};
  10483. res.type = type_deref(tag.type);
  10484. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10485. lb_emit_store(p, tag, res);
  10486. break;
  10487. }
  10488. case Type_Slice: {
  10489. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  10490. LLVMValueRef vals[2] = {
  10491. lb_get_type_info_ptr(m, t->Slice.elem).value,
  10492. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  10493. };
  10494. lbValue res = {};
  10495. res.type = type_deref(tag.type);
  10496. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10497. lb_emit_store(p, tag, res);
  10498. break;
  10499. }
  10500. case Type_Proc: {
  10501. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  10502. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10503. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10504. if (t->Proc.params != nullptr) {
  10505. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  10506. }
  10507. if (t->Proc.results != nullptr) {
  10508. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  10509. }
  10510. LLVMValueRef vals[4] = {
  10511. params,
  10512. results,
  10513. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  10514. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  10515. };
  10516. lbValue res = {};
  10517. res.type = type_deref(tag.type);
  10518. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10519. lb_emit_store(p, tag, res);
  10520. break;
  10521. }
  10522. case Type_Tuple: {
  10523. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  10524. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  10525. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  10526. for_array(i, t->Tuple.variables) {
  10527. // NOTE(bill): offset is not used for tuples
  10528. Entity *f = t->Tuple.variables[i];
  10529. lbValue index = lb_const_int(m, t_int, i);
  10530. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10531. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  10532. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10533. if (f->token.string.len > 0) {
  10534. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10535. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10536. }
  10537. }
  10538. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  10539. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  10540. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  10541. LLVMValueRef vals[2] = {
  10542. types_slice,
  10543. names_slice,
  10544. };
  10545. lbValue res = {};
  10546. res.type = type_deref(tag.type);
  10547. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10548. lb_emit_store(p, tag, res);
  10549. break;
  10550. }
  10551. case Type_Enum:
  10552. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  10553. {
  10554. GB_ASSERT(t->Enum.base_type != nullptr);
  10555. // 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));
  10556. LLVMValueRef vals[3] = {};
  10557. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  10558. if (t->Enum.fields.count > 0) {
  10559. auto fields = t->Enum.fields;
  10560. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  10561. str_lit("$enum_names"), cast(i64)entry_index);
  10562. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  10563. str_lit("$enum_values"), cast(i64)entry_index);
  10564. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10565. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10566. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10567. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  10568. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  10569. for_array(i, fields) {
  10570. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  10571. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  10572. }
  10573. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  10574. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  10575. LLVMSetInitializer(name_array.value, name_init);
  10576. LLVMSetInitializer(value_array.value, value_init);
  10577. lbValue v_count = lb_const_int(m, t_int, fields.count);
  10578. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  10579. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  10580. } else {
  10581. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  10582. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  10583. }
  10584. lbValue res = {};
  10585. res.type = type_deref(tag.type);
  10586. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10587. lb_emit_store(p, tag, res);
  10588. }
  10589. break;
  10590. case Type_Union: {
  10591. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  10592. {
  10593. LLVMValueRef vals[6] = {};
  10594. isize variant_count = gb_max(0, t->Union.variants.count);
  10595. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  10596. // NOTE(bill): Zeroth is nil so ignore it
  10597. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10598. Type *vt = t->Union.variants[variant_index];
  10599. lbValue tip = lb_get_type_info_ptr(m, vt);
  10600. lbValue index = lb_const_int(m, t_int, variant_index);
  10601. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10602. lb_emit_store(p, type_info, lb_type_info(m, vt));
  10603. }
  10604. lbValue count = lb_const_int(m, t_int, variant_count);
  10605. vals[0] = llvm_const_slice(m, memory_types, count);
  10606. i64 tag_size = union_tag_size(t);
  10607. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10608. if (tag_size > 0) {
  10609. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  10610. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  10611. } else {
  10612. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  10613. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10614. }
  10615. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  10616. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  10617. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  10618. lbValue res = {};
  10619. res.type = type_deref(tag.type);
  10620. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10621. lb_emit_store(p, tag, res);
  10622. }
  10623. break;
  10624. }
  10625. case Type_Struct: {
  10626. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  10627. LLVMValueRef vals[12] = {};
  10628. {
  10629. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  10630. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  10631. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  10632. vals[5] = is_packed.value;
  10633. vals[6] = is_raw_union.value;
  10634. vals[7] = is_custom_align.value;
  10635. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  10636. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  10637. }
  10638. if (t->Struct.soa_kind != StructSoa_None) {
  10639. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  10640. Type *kind_type = type_deref(kind.type);
  10641. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  10642. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  10643. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  10644. vals[9] = soa_kind.value;
  10645. vals[10] = soa_type.value;
  10646. vals[11] = soa_len.value;
  10647. }
  10648. }
  10649. isize count = t->Struct.fields.count;
  10650. if (count > 0) {
  10651. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  10652. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  10653. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  10654. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  10655. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  10656. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10657. for (isize source_index = 0; source_index < count; source_index++) {
  10658. // TODO(bill): Order fields in source order not layout order
  10659. Entity *f = t->Struct.fields[source_index];
  10660. lbValue tip = lb_get_type_info_ptr(m, f->type);
  10661. i64 foffset = 0;
  10662. if (!t->Struct.is_raw_union) {
  10663. foffset = t->Struct.offsets[f->Variable.field_index];
  10664. }
  10665. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10666. lbValue index = lb_const_int(m, t_int, source_index);
  10667. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10668. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  10669. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  10670. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10671. if (f->token.string.len > 0) {
  10672. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10673. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10674. }
  10675. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  10676. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  10677. if (t->Struct.tags.count > 0) {
  10678. String tag_string = t->Struct.tags[source_index];
  10679. if (tag_string.len > 0) {
  10680. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  10681. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  10682. }
  10683. }
  10684. }
  10685. lbValue cv = lb_const_int(m, t_int, count);
  10686. vals[0] = llvm_const_slice(m, memory_types, cv);
  10687. vals[1] = llvm_const_slice(m, memory_names, cv);
  10688. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  10689. vals[3] = llvm_const_slice(m, memory_usings, cv);
  10690. vals[4] = llvm_const_slice(m, memory_tags, cv);
  10691. }
  10692. for (isize i = 0; i < gb_count_of(vals); i++) {
  10693. if (vals[i] == nullptr) {
  10694. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  10695. }
  10696. }
  10697. lbValue res = {};
  10698. res.type = type_deref(tag.type);
  10699. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10700. lb_emit_store(p, tag, res);
  10701. break;
  10702. }
  10703. case Type_Map: {
  10704. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  10705. init_map_internal_types(t);
  10706. LLVMValueRef vals[5] = {
  10707. lb_get_type_info_ptr(m, t->Map.key).value,
  10708. lb_get_type_info_ptr(m, t->Map.value).value,
  10709. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  10710. lb_get_equal_proc_for_type(m, t->Map.key).value,
  10711. lb_get_hasher_proc_for_type(m, t->Map.key).value
  10712. };
  10713. lbValue res = {};
  10714. res.type = type_deref(tag.type);
  10715. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10716. lb_emit_store(p, tag, res);
  10717. break;
  10718. }
  10719. case Type_BitSet:
  10720. {
  10721. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  10722. GB_ASSERT(is_type_typed(t->BitSet.elem));
  10723. LLVMValueRef vals[4] = {
  10724. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  10725. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  10726. lb_const_int(m, t_i64, t->BitSet.lower).value,
  10727. lb_const_int(m, t_i64, t->BitSet.upper).value,
  10728. };
  10729. if (t->BitSet.underlying != nullptr) {
  10730. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  10731. }
  10732. lbValue res = {};
  10733. res.type = type_deref(tag.type);
  10734. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10735. lb_emit_store(p, tag, res);
  10736. }
  10737. break;
  10738. case Type_SimdVector:
  10739. {
  10740. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  10741. LLVMValueRef vals[4] = {};
  10742. if (t->SimdVector.is_x86_mmx) {
  10743. vals[3] = lb_const_bool(m, t_bool, true).value;
  10744. } else {
  10745. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  10746. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  10747. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  10748. }
  10749. lbValue res = {};
  10750. res.type = type_deref(tag.type);
  10751. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10752. lb_emit_store(p, tag, res);
  10753. }
  10754. break;
  10755. case Type_RelativePointer:
  10756. {
  10757. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  10758. LLVMValueRef vals[2] = {
  10759. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  10760. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  10761. };
  10762. lbValue res = {};
  10763. res.type = type_deref(tag.type);
  10764. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10765. lb_emit_store(p, tag, res);
  10766. }
  10767. break;
  10768. case Type_RelativeSlice:
  10769. {
  10770. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  10771. LLVMValueRef vals[2] = {
  10772. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  10773. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  10774. };
  10775. lbValue res = {};
  10776. res.type = type_deref(tag.type);
  10777. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10778. lb_emit_store(p, tag, res);
  10779. }
  10780. break;
  10781. }
  10782. if (tag.value != nullptr) {
  10783. Type *tag_type = type_deref(tag.type);
  10784. GB_ASSERT(is_type_named(tag_type));
  10785. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  10786. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  10787. } else {
  10788. if (t != t_llvm_bool) {
  10789. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  10790. }
  10791. }
  10792. }
  10793. }
  10794. void lb_generate_code(lbGenerator *gen) {
  10795. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  10796. TIME_SECTION("LLVM Initializtion");
  10797. lbModule *m = &gen->module;
  10798. LLVMModuleRef mod = gen->module.mod;
  10799. CheckerInfo *info = gen->info;
  10800. auto *min_dep_set = &info->minimum_dependency_set;
  10801. LLVMInitializeAllTargetInfos();
  10802. LLVMInitializeAllTargets();
  10803. LLVMInitializeAllTargetMCs();
  10804. LLVMInitializeAllAsmPrinters();
  10805. LLVMInitializeAllAsmParsers();
  10806. LLVMInitializeAllDisassemblers();
  10807. LLVMInitializeNativeTarget();
  10808. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  10809. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  10810. LLVMSetTarget(mod, target_triple);
  10811. LLVMTargetRef target = {};
  10812. char *llvm_error = nullptr;
  10813. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  10814. GB_ASSERT(target != nullptr);
  10815. TIME_SECTION("LLVM Create Target Machine");
  10816. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  10817. if (build_context.metrics.arch == TargetArch_wasm32) {
  10818. code_mode = LLVMCodeModelJITDefault;
  10819. }
  10820. char const *host_cpu_name = LLVMGetHostCPUName();
  10821. char const *llvm_cpu = "generic";
  10822. char const *llvm_features = "";
  10823. if (build_context.microarch.len != 0) {
  10824. if (build_context.microarch == "native") {
  10825. llvm_cpu = host_cpu_name;
  10826. } else {
  10827. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  10828. }
  10829. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  10830. llvm_features = LLVMGetHostCPUFeatures();
  10831. }
  10832. }
  10833. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  10834. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  10835. switch (build_context.optimization_level) {
  10836. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  10837. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  10838. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  10839. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  10840. }
  10841. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, llvm_cpu, llvm_features, code_gen_level, LLVMRelocDefault, code_mode);
  10842. defer (LLVMDisposeTargetMachine(target_machine));
  10843. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  10844. if (m->debug_builder) { // Debug Info
  10845. for_array(i, info->files.entries) {
  10846. AstFile *f = info->files.entries[i].value;
  10847. String fullpath = f->fullpath;
  10848. String filename = remove_directory_from_path(fullpath);
  10849. String directory = directory_from_path(fullpath);
  10850. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  10851. cast(char const *)filename.text, filename.len,
  10852. cast(char const *)directory.text, directory.len);
  10853. lb_set_llvm_metadata(m, f, res);
  10854. }
  10855. gbString producer = gb_string_make(heap_allocator(), "odin");
  10856. producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  10857. #ifdef NIGHTLY
  10858. producer = gb_string_appendc(producer, "-nightly");
  10859. #endif
  10860. #ifdef GIT_SHA
  10861. producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  10862. #endif
  10863. gbString split_name = gb_string_make(heap_allocator(), "");
  10864. LLVMBool is_optimized = build_context.optimization_level > 0;
  10865. AstFile *init_file = m->info->init_package->files[0];
  10866. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  10867. init_file = m->info->entry_point->identifier->file;
  10868. }
  10869. LLVMBool split_debug_inlining = false;
  10870. LLVMBool debug_info_for_profiling = false;
  10871. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  10872. lb_get_llvm_metadata(m, init_file),
  10873. producer, gb_string_length(producer),
  10874. is_optimized, "", 0,
  10875. 1, split_name, gb_string_length(split_name),
  10876. LLVMDWARFEmissionFull,
  10877. 0, split_debug_inlining,
  10878. debug_info_for_profiling,
  10879. "", 0, // sys_root
  10880. "", 0 // SDK
  10881. );
  10882. GB_ASSERT(m->debug_compile_unit != nullptr);
  10883. }
  10884. TIME_SECTION("LLVM Global Variables");
  10885. {
  10886. { // Add type info data
  10887. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  10888. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  10889. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  10890. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  10891. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10892. LLVMSetLinkage(g, LLVMInternalLinkage);
  10893. lbValue value = {};
  10894. value.value = g;
  10895. value.type = alloc_type_pointer(t);
  10896. lb_global_type_info_data = lb_addr(value);
  10897. }
  10898. { // Type info member buffer
  10899. // NOTE(bill): Removes need for heap allocation by making it global memory
  10900. isize count = 0;
  10901. for_array(entry_index, m->info->type_info_types) {
  10902. Type *t = m->info->type_info_types[entry_index];
  10903. isize index = lb_type_info_index(m->info, t, false);
  10904. if (index < 0) {
  10905. continue;
  10906. }
  10907. switch (t->kind) {
  10908. case Type_Union:
  10909. count += t->Union.variants.count;
  10910. break;
  10911. case Type_Struct:
  10912. count += t->Struct.fields.count;
  10913. break;
  10914. case Type_Tuple:
  10915. count += t->Tuple.variables.count;
  10916. break;
  10917. }
  10918. }
  10919. if (count > 0) {
  10920. {
  10921. char const *name = LB_TYPE_INFO_TYPES_NAME;
  10922. Type *t = alloc_type_array(t_type_info_ptr, count);
  10923. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10924. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10925. LLVMSetLinkage(g, LLVMInternalLinkage);
  10926. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  10927. }
  10928. {
  10929. char const *name = LB_TYPE_INFO_NAMES_NAME;
  10930. Type *t = alloc_type_array(t_string, count);
  10931. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10932. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10933. LLVMSetLinkage(g, LLVMInternalLinkage);
  10934. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  10935. }
  10936. {
  10937. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  10938. Type *t = alloc_type_array(t_uintptr, count);
  10939. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10940. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10941. LLVMSetLinkage(g, LLVMInternalLinkage);
  10942. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  10943. }
  10944. {
  10945. char const *name = LB_TYPE_INFO_USINGS_NAME;
  10946. Type *t = alloc_type_array(t_bool, count);
  10947. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10948. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10949. LLVMSetLinkage(g, LLVMInternalLinkage);
  10950. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  10951. }
  10952. {
  10953. char const *name = LB_TYPE_INFO_TAGS_NAME;
  10954. Type *t = alloc_type_array(t_string, count);
  10955. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10956. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10957. LLVMSetLinkage(g, LLVMInternalLinkage);
  10958. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  10959. }
  10960. }
  10961. }
  10962. }
  10963. isize global_variable_max_count = 0;
  10964. Entity *entry_point = info->entry_point;
  10965. bool has_dll_main = false;
  10966. bool has_win_main = false;
  10967. for_array(i, info->entities) {
  10968. Entity *e = info->entities[i];
  10969. String name = e->token.string;
  10970. bool is_global = e->pkg != nullptr;
  10971. if (e->kind == Entity_Variable) {
  10972. global_variable_max_count++;
  10973. } else if (e->kind == Entity_Procedure && !is_global) {
  10974. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  10975. GB_ASSERT(e == entry_point);
  10976. // entry_point = e;
  10977. }
  10978. if (e->Procedure.is_export ||
  10979. (e->Procedure.link_name.len > 0) ||
  10980. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  10981. if (!has_dll_main && name == "DllMain") {
  10982. has_dll_main = true;
  10983. } else if (!has_win_main && name == "WinMain") {
  10984. has_win_main = true;
  10985. }
  10986. }
  10987. }
  10988. }
  10989. struct GlobalVariable {
  10990. lbValue var;
  10991. lbValue init;
  10992. DeclInfo *decl;
  10993. bool is_initialized;
  10994. };
  10995. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  10996. for_array(i, info->variable_init_order) {
  10997. DeclInfo *d = info->variable_init_order[i];
  10998. Entity *e = d->entity;
  10999. if ((e->scope->flags & ScopeFlag_File) == 0) {
  11000. continue;
  11001. }
  11002. if (!ptr_set_exists(min_dep_set, e)) {
  11003. continue;
  11004. }
  11005. DeclInfo *decl = decl_info_of_entity(e);
  11006. if (decl == nullptr) {
  11007. continue;
  11008. }
  11009. GB_ASSERT(e->kind == Entity_Variable);
  11010. bool is_foreign = e->Variable.is_foreign;
  11011. bool is_export = e->Variable.is_export;
  11012. String name = lb_get_entity_name(m, e);
  11013. lbValue g = {};
  11014. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  11015. g.type = alloc_type_pointer(e->type);
  11016. if (e->Variable.thread_local_model != "") {
  11017. LLVMSetThreadLocal(g.value, true);
  11018. String m = e->Variable.thread_local_model;
  11019. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  11020. if (m == "default") {
  11021. mode = LLVMGeneralDynamicTLSModel;
  11022. } else if (m == "localdynamic") {
  11023. mode = LLVMLocalDynamicTLSModel;
  11024. } else if (m == "initialexec") {
  11025. mode = LLVMInitialExecTLSModel;
  11026. } else if (m == "localexec") {
  11027. mode = LLVMLocalExecTLSModel;
  11028. } else {
  11029. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  11030. }
  11031. LLVMSetThreadLocalMode(g.value, mode);
  11032. }
  11033. if (is_foreign) {
  11034. LLVMSetExternallyInitialized(g.value, true);
  11035. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  11036. } else {
  11037. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  11038. }
  11039. if (is_export) {
  11040. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  11041. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  11042. }
  11043. if (e->flags & EntityFlag_Static) {
  11044. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  11045. }
  11046. GlobalVariable var = {};
  11047. var.var = g;
  11048. var.decl = decl;
  11049. if (decl->init_expr != nullptr) {
  11050. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  11051. if (!is_type_any(e->type)) {
  11052. if (tav.mode != Addressing_Invalid) {
  11053. if (tav.value.kind != ExactValue_Invalid) {
  11054. ExactValue v = tav.value;
  11055. lbValue init = lb_const_value(m, tav.type, v);
  11056. LLVMSetInitializer(g.value, init.value);
  11057. var.is_initialized = true;
  11058. }
  11059. }
  11060. }
  11061. if (!var.is_initialized &&
  11062. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  11063. var.is_initialized = true;
  11064. }
  11065. }
  11066. array_add(&global_variables, var);
  11067. lb_add_entity(m, e, g);
  11068. lb_add_member(m, name, g);
  11069. if (m->debug_builder) {
  11070. String global_name = e->token.string;
  11071. if (global_name.len != 0 && global_name != "_") {
  11072. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  11073. LLVMMetadataRef llvm_scope = llvm_file;
  11074. LLVMBool local_to_unit = e->flags & EntityFlag_Static;
  11075. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  11076. LLVMMetadataRef llvm_decl = nullptr;
  11077. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  11078. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  11079. m->debug_builder, llvm_scope,
  11080. cast(char const *)global_name.text, global_name.len,
  11081. "", 0, // linkage
  11082. llvm_file, e->token.pos.line,
  11083. lb_debug_type(m, e->type),
  11084. local_to_unit,
  11085. llvm_expr,
  11086. llvm_decl,
  11087. align_in_bits
  11088. );
  11089. }
  11090. }
  11091. }
  11092. TIME_SECTION("LLVM Global Procedures and Types");
  11093. for_array(i, info->entities) {
  11094. Entity *e = info->entities[i];
  11095. String name = e->token.string;
  11096. DeclInfo *decl = e->decl_info;
  11097. Scope * scope = e->scope;
  11098. if ((scope->flags & ScopeFlag_File) == 0) {
  11099. continue;
  11100. }
  11101. Scope *package_scope = scope->parent;
  11102. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  11103. switch (e->kind) {
  11104. case Entity_Variable:
  11105. // NOTE(bill): Handled above as it requires a specific load order
  11106. continue;
  11107. case Entity_ProcGroup:
  11108. continue;
  11109. case Entity_TypeName:
  11110. case Entity_Procedure:
  11111. break;
  11112. }
  11113. bool polymorphic_struct = false;
  11114. if (e->type != nullptr && e->kind == Entity_TypeName) {
  11115. Type *bt = base_type(e->type);
  11116. if (bt->kind == Type_Struct) {
  11117. polymorphic_struct = is_type_polymorphic(bt);
  11118. }
  11119. }
  11120. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  11121. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  11122. continue;
  11123. }
  11124. String mangled_name = lb_get_entity_name(m, e);
  11125. switch (e->kind) {
  11126. case Entity_TypeName:
  11127. lb_type(m, e->type);
  11128. break;
  11129. case Entity_Procedure:
  11130. {
  11131. lbProcedure *p = lb_create_procedure(m, e);
  11132. array_add(&m->procedures_to_generate, p);
  11133. }
  11134. break;
  11135. }
  11136. }
  11137. TIME_SECTION("LLVM Registry Initializtion");
  11138. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  11139. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  11140. defer (LLVMDisposePassManager(default_function_pass_manager));
  11141. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  11142. lb_populate_function_pass_manager(default_function_pass_manager, false);
  11143. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11144. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  11145. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  11146. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11147. lb_populate_function_pass_manager(default_function_pass_manager_without_memcpy, true);
  11148. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11149. TIME_SECTION("LLVM Runtime Type Information Creation");
  11150. lbProcedure *startup_type_info = nullptr;
  11151. lbProcedure *startup_runtime = nullptr;
  11152. { // Startup Type Info
  11153. Type *params = alloc_type_tuple();
  11154. Type *results = alloc_type_tuple();
  11155. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11156. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  11157. p->is_startup = true;
  11158. startup_type_info = p;
  11159. lb_begin_procedure_body(p);
  11160. lb_setup_type_info_data(p);
  11161. lb_end_procedure_body(p);
  11162. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11163. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11164. LLVMDumpValue(p->value);
  11165. gb_printf_err("\n\n\n\n");
  11166. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11167. }
  11168. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11169. }
  11170. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  11171. { // Startup Runtime
  11172. Type *params = alloc_type_tuple();
  11173. Type *results = alloc_type_tuple();
  11174. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11175. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  11176. p->is_startup = true;
  11177. startup_runtime = p;
  11178. lb_begin_procedure_body(p);
  11179. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  11180. for_array(i, global_variables) {
  11181. auto *var = &global_variables[i];
  11182. if (var->is_initialized) {
  11183. continue;
  11184. }
  11185. Entity *e = var->decl->entity;
  11186. GB_ASSERT(e->kind == Entity_Variable);
  11187. if (var->decl->init_expr != nullptr) {
  11188. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  11189. lbValue init = lb_build_expr(p, var->decl->init_expr);
  11190. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  11191. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  11192. if (lb_is_const_or_global(init)) {
  11193. if (!var->is_initialized) {
  11194. LLVMSetInitializer(var->var.value, init.value);
  11195. var->is_initialized = true;
  11196. continue;
  11197. }
  11198. } else {
  11199. var->init = init;
  11200. }
  11201. }
  11202. if (var->init.value != nullptr) {
  11203. GB_ASSERT(!var->is_initialized);
  11204. Type *t = type_deref(var->var.type);
  11205. if (is_type_any(t)) {
  11206. // NOTE(bill): Edge case for 'any' type
  11207. Type *var_type = default_type(var->init.type);
  11208. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  11209. lb_addr_store(p, g, var->init);
  11210. lbValue gp = lb_addr_get_ptr(p, g);
  11211. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  11212. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  11213. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  11214. lb_emit_store(p, ti, lb_type_info(m, var_type));
  11215. } else {
  11216. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  11217. LLVMTypeRef vt = LLVMGetElementType(pvt);
  11218. lbValue src0 = lb_emit_conv(p, var->init, t);
  11219. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  11220. LLVMValueRef dst = var->var.value;
  11221. LLVMBuildStore(p->builder, src, dst);
  11222. }
  11223. var->is_initialized = true;
  11224. }
  11225. }
  11226. lb_end_procedure_body(p);
  11227. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11228. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11229. LLVMDumpValue(p->value);
  11230. gb_printf_err("\n\n\n\n");
  11231. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11232. }
  11233. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11234. /*{
  11235. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  11236. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  11237. instr != last_instr;
  11238. instr = LLVMGetNextInstruction(instr)) {
  11239. if (LLVMIsAAllocaInst(instr)) {
  11240. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  11241. LLVMValueRef sz_val = LLVMSizeOf(type);
  11242. GB_ASSERT(LLVMIsConstant(sz_val));
  11243. gb_printf_err(">> 0x%p\n", sz_val);
  11244. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  11245. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  11246. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  11247. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  11248. gb_printf_err(">> %ll\n", sz);
  11249. }
  11250. }
  11251. }*/
  11252. }
  11253. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  11254. TIME_SECTION("LLVM DLL main");
  11255. Type *params = alloc_type_tuple();
  11256. Type *results = alloc_type_tuple();
  11257. String name = str_lit("main");
  11258. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  11259. name = str_lit("mainCRTStartup");
  11260. } else {
  11261. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  11262. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  11263. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  11264. }
  11265. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  11266. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  11267. Type *proc_type = alloc_type_proc(nullptr,
  11268. params, params->Tuple.variables.count,
  11269. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  11270. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  11271. p->is_startup = true;
  11272. lb_begin_procedure_body(p);
  11273. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  11274. if (build_context.command_kind == Command_test) {
  11275. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  11276. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  11277. Type *slice_type = alloc_type_slice(t_Internal_Test);
  11278. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  11279. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  11280. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  11281. LLVMValueRef indices[2] = {};
  11282. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  11283. for_array(i, m->info->testing_procedures) {
  11284. Entity *testing_proc = m->info->testing_procedures[i];
  11285. String name = testing_proc->token.string;
  11286. lbValue *found = map_get(&m->values, hash_entity(testing_proc));
  11287. GB_ASSERT(found != nullptr);
  11288. String pkg_name = {};
  11289. if (testing_proc->pkg != nullptr) {
  11290. pkg_name = testing_proc->pkg->name;
  11291. }
  11292. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  11293. lbValue v_name = lb_find_or_add_entity_string(m, name);
  11294. lbValue v_proc = *found;
  11295. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  11296. LLVMValueRef vals[3] = {};
  11297. vals[0] = v_pkg.value;
  11298. vals[1] = v_name.value;
  11299. vals[2] = v_proc.value;
  11300. GB_ASSERT(LLVMIsConstant(vals[0]));
  11301. GB_ASSERT(LLVMIsConstant(vals[1]));
  11302. GB_ASSERT(LLVMIsConstant(vals[2]));
  11303. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  11304. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  11305. LLVMBuildStore(p->builder, src, dst);
  11306. }
  11307. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  11308. lb_fill_slice(p, all_tests_slice,
  11309. lb_array_elem(p, all_tests_array),
  11310. lb_const_int(m, t_int, m->info->testing_procedures.count));
  11311. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  11312. auto args = array_make<lbValue>(heap_allocator(), 1);
  11313. args[0] = lb_addr_load(p, all_tests_slice);
  11314. lb_emit_call(p, runner, args);
  11315. } else {
  11316. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  11317. GB_ASSERT(found != nullptr);
  11318. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  11319. }
  11320. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  11321. lb_end_procedure_body(p);
  11322. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11323. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11324. LLVMDumpValue(p->value);
  11325. gb_printf_err("\n\n\n\n");
  11326. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11327. }
  11328. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11329. }
  11330. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  11331. TIME_SECTION("LLVM Procedure Generation");
  11332. for_array(i, m->procedures_to_generate) {
  11333. lbProcedure *p = m->procedures_to_generate[i];
  11334. if (p->is_done) {
  11335. continue;
  11336. }
  11337. if (p->body != nullptr) { // Build Procedure
  11338. m->curr_procedure = p;
  11339. lb_begin_procedure_body(p);
  11340. lb_build_stmt(p, p->body);
  11341. lb_end_procedure_body(p);
  11342. p->is_done = true;
  11343. m->curr_procedure = nullptr;
  11344. }
  11345. lb_end_procedure(p);
  11346. // Add Flags
  11347. if (p->body != nullptr) {
  11348. if (p->name == "memcpy" || p->name == "memmove" ||
  11349. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  11350. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  11351. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  11352. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  11353. }
  11354. }
  11355. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11356. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  11357. LLVMDumpValue(p->value);
  11358. gb_printf_err("\n\n\n\n");
  11359. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11360. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11361. }
  11362. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  11363. gb_exit(1);
  11364. }
  11365. }
  11366. if (m->debug_builder != nullptr) {
  11367. TIME_SECTION("LLVM Debug Info Complete Types");
  11368. lb_debug_complete_types(m);
  11369. TIME_SECTION("LLVM Print Module to File");
  11370. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11371. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11372. gb_exit(1);
  11373. return;
  11374. }
  11375. TIME_SECTION("LLVM Debug Info Builder Finalize");
  11376. LLVMDIBuilderFinalize(m->debug_builder);
  11377. }
  11378. TIME_SECTION("LLVM Function Pass");
  11379. {
  11380. for_array(i, m->procedures_to_generate) {
  11381. lbProcedure *p = m->procedures_to_generate[i];
  11382. if (p->body != nullptr) { // Build Procedure
  11383. for (i32 i = 0; i <= build_context.optimization_level; i++) {
  11384. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  11385. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  11386. } else {
  11387. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11388. }
  11389. }
  11390. }
  11391. }
  11392. for_array(i, m->equal_procs.entries) {
  11393. lbProcedure *p = m->equal_procs.entries[i].value;
  11394. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11395. }
  11396. for_array(i, m->hasher_procs.entries) {
  11397. lbProcedure *p = m->hasher_procs.entries[i].value;
  11398. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11399. }
  11400. }
  11401. TIME_SECTION("LLVM Module Pass");
  11402. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  11403. defer (LLVMDisposePassManager(module_pass_manager));
  11404. lb_populate_module_pass_manager(target_machine, module_pass_manager);
  11405. LLVMRunPassManager(module_pass_manager, mod);
  11406. llvm_error = nullptr;
  11407. defer (LLVMDisposeMessage(llvm_error));
  11408. String filepath_obj = {};
  11409. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  11410. if (build_context.build_mode == BuildMode_Assembly) {
  11411. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  11412. code_gen_file_type = LLVMAssemblyFile;
  11413. } else {
  11414. switch (build_context.metrics.os) {
  11415. case TargetOs_windows:
  11416. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  11417. break;
  11418. case TargetOs_darwin:
  11419. case TargetOs_linux:
  11420. case TargetOs_essence:
  11421. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  11422. break;
  11423. case TargetOs_js:
  11424. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  11425. break;
  11426. }
  11427. }
  11428. if (LLVMVerifyModule(mod, LLVMReturnStatusAction, &llvm_error)) {
  11429. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  11430. if (build_context.keep_temp_files) {
  11431. TIME_SECTION("LLVM Print Module to File");
  11432. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11433. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11434. gb_exit(1);
  11435. return;
  11436. }
  11437. }
  11438. gb_exit(1);
  11439. return;
  11440. }
  11441. llvm_error = nullptr;
  11442. if (build_context.keep_temp_files) {
  11443. TIME_SECTION("LLVM Print Module to File");
  11444. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11445. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11446. gb_exit(1);
  11447. return;
  11448. }
  11449. }
  11450. TIME_SECTION("LLVM Object Generation");
  11451. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  11452. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11453. gb_exit(1);
  11454. return;
  11455. }
  11456. array_add(&gen->output_object_paths, filepath_obj);
  11457. for_array(i, m->info->required_foreign_imports_through_force) {
  11458. Entity *e = m->info->required_foreign_imports_through_force[i];
  11459. lb_add_foreign_library_path(m, e);
  11460. }
  11461. #undef TIME_SECTION
  11462. }