llvm_backend.cpp 405 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046
  1. #include "llvm_backend.hpp"
  2. #include "llvm_abi.cpp"
  3. #ifdef USE_NEW_LLVM_ABI_SYSTEM
  4. #define USE_LLVM_ABI 1
  5. #else
  6. #define USE_LLVM_ABI 0
  7. #endif
  8. gb_global lbAddr lb_global_type_info_data = {};
  9. gb_global lbAddr lb_global_type_info_member_types = {};
  10. gb_global lbAddr lb_global_type_info_member_names = {};
  11. gb_global lbAddr lb_global_type_info_member_offsets = {};
  12. gb_global lbAddr lb_global_type_info_member_usings = {};
  13. gb_global lbAddr lb_global_type_info_member_tags = {};
  14. gb_global isize lb_global_type_info_data_index = 0;
  15. gb_global isize lb_global_type_info_member_types_index = 0;
  16. gb_global isize lb_global_type_info_member_names_index = 0;
  17. gb_global isize lb_global_type_info_member_offsets_index = 0;
  18. gb_global isize lb_global_type_info_member_usings_index = 0;
  19. gb_global isize lb_global_type_info_member_tags_index = 0;
  20. struct lbLoopData {
  21. lbAddr idx_addr;
  22. lbValue idx;
  23. lbBlock *body;
  24. lbBlock *done;
  25. lbBlock *loop;
  26. };
  27. struct lbCompoundLitElemTempData {
  28. Ast * expr;
  29. lbValue value;
  30. i32 elem_index;
  31. lbValue gep;
  32. };
  33. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  34. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  35. LLVMValueRef llvm_zero(lbModule *m) {
  36. return LLVMConstInt(lb_type(m, t_int), 0, false);
  37. }
  38. LLVMValueRef llvm_one(lbModule *m) {
  39. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  40. }
  41. lbValue lb_zero(lbModule *m, Type *t) {
  42. lbValue v = {};
  43. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  44. v.type = t;
  45. return v;
  46. }
  47. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  48. lbValue v = lb_find_or_add_entity_string(m, str);
  49. unsigned indices[1] = {0};
  50. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  51. }
  52. bool lb_is_instr_terminating(LLVMValueRef instr) {
  53. if (instr != nullptr) {
  54. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  55. switch (op) {
  56. case LLVMRet:
  57. case LLVMBr:
  58. case LLVMSwitch:
  59. case LLVMIndirectBr:
  60. case LLVMInvoke:
  61. case LLVMUnreachable:
  62. case LLVMCallBr:
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. lbAddr lb_addr(lbValue addr) {
  69. lbAddr v = {lbAddr_Default, addr};
  70. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  71. GB_ASSERT(is_type_pointer(addr.type));
  72. v.kind = lbAddr_RelativePointer;
  73. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  74. GB_ASSERT(is_type_pointer(addr.type));
  75. v.kind = lbAddr_RelativeSlice;
  76. }
  77. return v;
  78. }
  79. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  80. lbAddr v = {lbAddr_Map, addr};
  81. v.map.key = map_key;
  82. v.map.type = map_type;
  83. v.map.result = map_result;
  84. return v;
  85. }
  86. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  87. lbAddr v = {lbAddr_SoaVariable, addr};
  88. v.soa.index = index;
  89. v.soa.index_expr = index_expr;
  90. return v;
  91. }
  92. lbAddr lb_addr_bit_field(lbValue value, i32 index) {
  93. lbAddr addr = {};
  94. addr.kind = lbAddr_BitField;
  95. addr.addr = value;
  96. addr.bit_field.value_index = index;
  97. return addr;
  98. }
  99. Type *lb_addr_type(lbAddr const &addr) {
  100. if (addr.addr.value == nullptr) {
  101. return nullptr;
  102. }
  103. if (addr.kind == lbAddr_Map) {
  104. Type *t = base_type(addr.map.type);
  105. GB_ASSERT(is_type_map(t));
  106. return t->Map.value;
  107. }
  108. return type_deref(addr.addr.type);
  109. }
  110. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  111. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  112. }
  113. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  114. if (addr.addr.value == nullptr) {
  115. GB_PANIC("Illegal addr -> nullptr");
  116. return {};
  117. }
  118. switch (addr.kind) {
  119. case lbAddr_Map: {
  120. Type *map_type = base_type(addr.map.type);
  121. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  122. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  123. auto args = array_make<lbValue>(permanent_allocator(), 2);
  124. args[0] = h;
  125. args[1] = key;
  126. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  127. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  128. }
  129. case lbAddr_RelativePointer: {
  130. Type *rel_ptr = base_type(lb_addr_type(addr));
  131. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  132. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  133. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  134. offset = lb_emit_load(p, offset);
  135. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  136. offset = lb_emit_conv(p, offset, t_i64);
  137. }
  138. offset = lb_emit_conv(p, offset, t_uintptr);
  139. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  140. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  141. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  142. // NOTE(bill): nil check
  143. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  144. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  145. return final_ptr;
  146. }
  147. case lbAddr_BitField: {
  148. lbValue v = lb_addr_load(p, addr);
  149. return lb_address_from_load_or_generate_local(p, v);
  150. }
  151. case lbAddr_Context:
  152. GB_PANIC("lbAddr_Context should be handled elsewhere");
  153. }
  154. return addr.addr;
  155. }
  156. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  157. lbAddr addr = lb_build_addr(p, expr);
  158. return lb_addr_get_ptr(p, addr);
  159. }
  160. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  161. if (build_context.no_bounds_check) {
  162. return;
  163. }
  164. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  165. return;
  166. }
  167. index = lb_emit_conv(p, index, t_int);
  168. len = lb_emit_conv(p, len, t_int);
  169. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  170. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  171. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  172. auto args = array_make<lbValue>(permanent_allocator(), 5);
  173. args[0] = file;
  174. args[1] = line;
  175. args[2] = column;
  176. args[3] = index;
  177. args[4] = len;
  178. lb_emit_runtime_call(p, "bounds_check_error", args);
  179. }
  180. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  181. if (build_context.no_bounds_check) {
  182. return;
  183. }
  184. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  185. return;
  186. }
  187. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  188. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  189. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  190. high = lb_emit_conv(p, high, t_int);
  191. if (!lower_value_used) {
  192. auto args = array_make<lbValue>(permanent_allocator(), 5);
  193. args[0] = file;
  194. args[1] = line;
  195. args[2] = column;
  196. args[3] = high;
  197. args[4] = len;
  198. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  199. } else {
  200. // No need to convert unless used
  201. low = lb_emit_conv(p, low, t_int);
  202. auto args = array_make<lbValue>(permanent_allocator(), 6);
  203. args[0] = file;
  204. args[1] = line;
  205. args[2] = column;
  206. args[3] = low;
  207. args[4] = high;
  208. args[5] = len;
  209. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  210. }
  211. }
  212. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  213. if (addr.addr.value == nullptr) {
  214. return;
  215. }
  216. GB_ASSERT(value.type != nullptr);
  217. if (is_type_untyped_undef(value.type)) {
  218. Type *t = lb_addr_type(addr);
  219. value.type = t;
  220. value.value = LLVMGetUndef(lb_type(p->module, t));
  221. } else if (is_type_untyped_nil(value.type)) {
  222. Type *t = lb_addr_type(addr);
  223. value.type = t;
  224. value.value = LLVMConstNull(lb_type(p->module, t));
  225. }
  226. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  227. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  228. }
  229. if (addr.kind == lbAddr_RelativePointer) {
  230. Type *rel_ptr = base_type(lb_addr_type(addr));
  231. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  232. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  233. GB_ASSERT(is_type_pointer(addr.addr.type));
  234. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  235. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  236. lbValue offset = {};
  237. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  238. offset.type = t_uintptr;
  239. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  240. offset = lb_emit_conv(p, offset, t_i64);
  241. }
  242. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  243. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  244. offset = lb_emit_select(p,
  245. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  246. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  247. offset
  248. );
  249. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  250. return;
  251. } else if (addr.kind == lbAddr_RelativeSlice) {
  252. Type *rel_ptr = base_type(lb_addr_type(addr));
  253. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  254. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  255. GB_ASSERT(is_type_pointer(addr.addr.type));
  256. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  257. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  258. lbValue offset = {};
  259. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  260. offset.type = t_uintptr;
  261. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  262. offset = lb_emit_conv(p, offset, t_i64);
  263. }
  264. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  265. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  266. offset = lb_emit_select(p,
  267. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  268. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  269. offset
  270. );
  271. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  272. lbValue len = lb_slice_len(p, value);
  273. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  274. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  275. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  276. return;
  277. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  278. lbValue ptr = addr.addr;
  279. lbValue index = addr.index_set.index;
  280. Ast *node = addr.index_set.node;
  281. ast_node(ce, CallExpr, node);
  282. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  283. proc_type = base_type(proc_type);
  284. GB_ASSERT(is_type_proc(proc_type));
  285. TypeProc *pt = &proc_type->Proc;
  286. isize arg_count = 3;
  287. isize param_count = 0;
  288. if (pt->params) {
  289. GB_ASSERT(pt->params->kind == Type_Tuple);
  290. param_count = pt->params->Tuple.variables.count;
  291. }
  292. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  293. args[0] = ptr;
  294. args[1] = index;
  295. args[2] = value;
  296. isize arg_index = arg_count;
  297. if (arg_count < param_count) {
  298. lbModule *m = p->module;
  299. String proc_name = {};
  300. if (p->entity != nullptr) {
  301. proc_name = p->entity->token.string;
  302. }
  303. TokenPos pos = ast_token(ce->proc).pos;
  304. TypeTuple *param_tuple = &pt->params->Tuple;
  305. isize end = cast(isize)param_count;
  306. while (arg_index < end) {
  307. Entity *e = param_tuple->variables[arg_index];
  308. GB_ASSERT(e->kind == Entity_Variable);
  309. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  310. }
  311. }
  312. Entity *e = entity_from_expr(ce->proc);
  313. GB_ASSERT(e != nullptr);
  314. GB_ASSERT(is_type_polymorphic(e->type));
  315. {
  316. lbValue *found = nullptr;
  317. if (p->module != e->code_gen_module) {
  318. gb_mutex_lock(&p->module->mutex);
  319. }
  320. found = map_get(&e->code_gen_module->values, hash_entity(e));
  321. if (p->module != e->code_gen_module) {
  322. gb_mutex_unlock(&p->module->mutex);
  323. }
  324. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  325. lb_emit_call(p, *found, args);
  326. }
  327. return;
  328. } else if (addr.kind == lbAddr_Map) {
  329. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  330. return;
  331. } else if (addr.kind == lbAddr_BitField) {
  332. Type *bft = base_type(type_deref(addr.addr.type));
  333. GB_ASSERT(is_type_bit_field(bft));
  334. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  335. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  336. if (size_in_bits == 0) {
  337. return;
  338. }
  339. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  340. LLVMTypeRef dst_type = LLVMIntTypeInContext(p->module->ctx, size_in_bits);
  341. LLVMValueRef src = LLVMBuildIntCast2(p->builder, value.value, dst_type, false, "");
  342. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  343. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  344. LLVMBuildStore(p->builder, src, field_ptr);
  345. return;
  346. } else if (addr.kind == lbAddr_Context) {
  347. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  348. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  349. lb_addr_store(p, next_addr, old);
  350. lb_push_context_onto_stack(p, next_addr);
  351. lbValue next = lb_addr_get_ptr(p, next_addr);
  352. if (addr.ctx.sel.index.count > 0) {
  353. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  354. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  355. lb_emit_store(p, lhs, rhs);
  356. } else {
  357. lbValue lhs = next;
  358. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  359. lb_emit_store(p, lhs, rhs);
  360. }
  361. return;
  362. } else if (addr.kind == lbAddr_SoaVariable) {
  363. Type *t = type_deref(addr.addr.type);
  364. t = base_type(t);
  365. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  366. value = lb_emit_conv(p, value, t->Struct.soa_elem);
  367. lbValue index = addr.soa.index;
  368. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  369. Type *t = base_type(type_deref(addr.addr.type));
  370. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  371. i64 count = t->Struct.soa_count;
  372. lbValue len = lb_const_int(p->module, t_int, count);
  373. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  374. }
  375. for_array(i, t->Struct.fields) {
  376. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  377. dst = lb_emit_array_ep(p, dst, index);
  378. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  379. lb_emit_store(p, dst, src);
  380. }
  381. return;
  382. }
  383. GB_ASSERT(value.value != nullptr);
  384. value = lb_emit_conv(p, value, lb_addr_type(addr));
  385. if (USE_LLVM_ABI) {
  386. lb_emit_store(p, addr.addr, value);
  387. } else {
  388. LLVMBuildStore(p->builder, value.value, addr.addr.value);
  389. }
  390. }
  391. void lb_const_store(lbValue ptr, lbValue value) {
  392. GB_ASSERT(lb_is_const(ptr));
  393. GB_ASSERT(lb_is_const(value));
  394. GB_ASSERT(is_type_pointer(ptr.type));
  395. LLVMSetInitializer(ptr.value, value.value);
  396. }
  397. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  398. GB_ASSERT(value.value != nullptr);
  399. Type *a = type_deref(ptr.type);
  400. if (is_type_boolean(a)) {
  401. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  402. value = lb_emit_conv(p, value, a);
  403. }
  404. Type *ca = core_type(a);
  405. if (ca->kind == Type_Basic) {
  406. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  407. }
  408. if (USE_LLVM_ABI && is_type_proc(a)) {
  409. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  410. // stored as regular pointer with no procedure information
  411. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  412. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  413. LLVMBuildStore(p->builder, v, ptr.value);
  414. } else {
  415. Type *ca = core_type(a);
  416. if (ca->kind == Type_Basic) {
  417. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  418. } else {
  419. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  420. }
  421. LLVMBuildStore(p->builder, value.value, ptr.value);
  422. }
  423. }
  424. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  425. lbModule *m = p->module;
  426. GB_ASSERT(value.value != nullptr);
  427. Type *t = type_deref(value.type);
  428. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  429. return lbValue{v, t};
  430. }
  431. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  432. GB_ASSERT(addr.addr.value != nullptr);
  433. if (addr.kind == lbAddr_RelativePointer) {
  434. Type *rel_ptr = base_type(lb_addr_type(addr));
  435. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  436. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  437. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  438. offset = lb_emit_load(p, offset);
  439. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  440. offset = lb_emit_conv(p, offset, t_i64);
  441. }
  442. offset = lb_emit_conv(p, offset, t_uintptr);
  443. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  444. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  445. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  446. // NOTE(bill): nil check
  447. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  448. lbValue final_ptr = {};
  449. final_ptr.type = absolute_ptr.type;
  450. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  451. return lb_emit_load(p, final_ptr);
  452. } else if (addr.kind == lbAddr_RelativeSlice) {
  453. Type *rel_ptr = base_type(lb_addr_type(addr));
  454. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  455. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  456. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  457. lbValue offset = lb_emit_load(p, offset_ptr);
  458. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  459. offset = lb_emit_conv(p, offset, t_i64);
  460. }
  461. offset = lb_emit_conv(p, offset, t_uintptr);
  462. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  463. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  464. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  465. Type *slice_elem = slice_type->Slice.elem;
  466. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  467. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  468. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  469. // NOTE(bill): nil check
  470. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  471. lbValue data = {};
  472. data.type = absolute_ptr.type;
  473. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  474. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  475. len = lb_emit_conv(p, len, t_int);
  476. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  477. lb_fill_slice(p, slice, data, len);
  478. return lb_addr_load(p, slice);
  479. } else if (addr.kind == lbAddr_Map) {
  480. Type *map_type = base_type(addr.map.type);
  481. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  482. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  483. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  484. auto args = array_make<lbValue>(permanent_allocator(), 2);
  485. args[0] = h;
  486. args[1] = key;
  487. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  488. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  489. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  490. lbBlock *then = lb_create_block(p, "map.get.then");
  491. lbBlock *done = lb_create_block(p, "map.get.done");
  492. lb_emit_if(p, ok, then, done);
  493. lb_start_block(p, then);
  494. {
  495. // TODO(bill): mem copy it instead?
  496. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  497. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  498. lb_emit_store(p, gep0, lb_emit_load(p, value));
  499. }
  500. lb_emit_jump(p, done);
  501. lb_start_block(p, done);
  502. if (is_type_tuple(addr.map.result)) {
  503. return lb_addr_load(p, v);
  504. } else {
  505. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  506. return lb_emit_load(p, single);
  507. }
  508. } else if (addr.kind == lbAddr_BitField) {
  509. Type *bft = base_type(type_deref(addr.addr.type));
  510. GB_ASSERT(is_type_bit_field(bft));
  511. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  512. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  513. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  514. if (size_in_bytes == 0) {
  515. GB_ASSERT(size_in_bits == 0);
  516. lbValue res = {};
  517. res.type = t_i32;
  518. res.value = LLVMConstInt(lb_type(p->module, res.type), 0, false);
  519. return res;
  520. }
  521. Type *int_type = nullptr;
  522. switch (size_in_bytes) {
  523. case 1: int_type = t_u8; break;
  524. case 2: int_type = t_u16; break;
  525. case 4: int_type = t_u32; break;
  526. case 8: int_type = t_u64; break;
  527. case 16: int_type = t_u128; break;
  528. }
  529. GB_ASSERT(int_type != nullptr);
  530. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  531. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  532. LLVMValueRef field = LLVMBuildLoad(p->builder, field_ptr, "");
  533. lbValue res = {};
  534. res.type = int_type;
  535. res.value = LLVMBuildZExtOrBitCast(p->builder, field, lb_type(p->module, int_type), "");
  536. return res;
  537. } else if (addr.kind == lbAddr_Context) {
  538. if (addr.ctx.sel.index.count > 0) {
  539. lbValue a = addr.addr;
  540. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  541. return lb_emit_load(p, b);
  542. } else {
  543. return lb_emit_load(p, addr.addr);
  544. }
  545. } else if (addr.kind == lbAddr_SoaVariable) {
  546. Type *t = type_deref(addr.addr.type);
  547. t = base_type(t);
  548. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  549. Type *elem = t->Struct.soa_elem;
  550. lbValue len = {};
  551. if (t->Struct.soa_kind == StructSoa_Fixed) {
  552. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  553. } else {
  554. lbValue v = lb_emit_load(p, addr.addr);
  555. len = lb_soa_struct_len(p, v);
  556. }
  557. lbAddr res = lb_add_local_generated(p, elem, true);
  558. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  559. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  560. }
  561. if (t->Struct.soa_kind == StructSoa_Fixed) {
  562. for_array(i, t->Struct.fields) {
  563. Entity *field = t->Struct.fields[i];
  564. Type *base_type = field->type;
  565. GB_ASSERT(base_type->kind == Type_Array);
  566. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  567. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  568. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  569. lbValue src = lb_emit_load(p, src_ptr);
  570. lb_emit_store(p, dst, src);
  571. }
  572. } else {
  573. isize field_count = t->Struct.fields.count;
  574. if (t->Struct.soa_kind == StructSoa_Slice) {
  575. field_count -= 1;
  576. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  577. field_count -= 3;
  578. }
  579. for (isize i = 0; i < field_count; i++) {
  580. Entity *field = t->Struct.fields[i];
  581. Type *base_type = field->type;
  582. GB_ASSERT(base_type->kind == Type_Pointer);
  583. Type *elem = base_type->Pointer.elem;
  584. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  585. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  586. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  587. lbValue src = lb_emit_load(p, src_ptr);
  588. src = lb_emit_load(p, src);
  589. lb_emit_store(p, dst, src);
  590. }
  591. }
  592. return lb_addr_load(p, res);
  593. }
  594. if (is_type_proc(addr.addr.type)) {
  595. return addr.addr;
  596. }
  597. return lb_emit_load(p, addr.addr);
  598. }
  599. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  600. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  601. }
  602. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  603. Type *t = u.type;
  604. GB_ASSERT_MSG(is_type_pointer(t) &&
  605. is_type_union(type_deref(t)), "%s", type_to_string(t));
  606. Type *ut = type_deref(t);
  607. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  608. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  609. GB_ASSERT(type_size_of(ut) > 0);
  610. Type *tag_type = union_tag_type(ut);
  611. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  612. unsigned element_count = LLVMCountStructElementTypes(uvt);
  613. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  614. lbValue tag_ptr = {};
  615. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  616. tag_ptr.type = alloc_type_pointer(tag_type);
  617. return tag_ptr;
  618. }
  619. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  620. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  621. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  622. return lb_emit_load(p, tag_ptr);
  623. }
  624. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  625. Type *t = type_deref(parent.type);
  626. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  627. // No tag needed!
  628. } else {
  629. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  630. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  631. }
  632. }
  633. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  634. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  635. lb_emit_store(p, underlying, variant);
  636. lb_emit_store_union_variant_tag(p, parent, variant_type);
  637. }
  638. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  639. unsigned field_count = LLVMCountStructElementTypes(src);
  640. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  641. LLVMGetStructElementTypes(src, fields);
  642. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  643. }
  644. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  645. switch (alignment) {
  646. case 1:
  647. return LLVMArrayType(lb_type(m, t_u8), 0);
  648. case 2:
  649. return LLVMArrayType(lb_type(m, t_u16), 0);
  650. case 4:
  651. return LLVMArrayType(lb_type(m, t_u32), 0);
  652. case 8:
  653. return LLVMArrayType(lb_type(m, t_u64), 0);
  654. case 16:
  655. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  656. default:
  657. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  658. break;
  659. }
  660. return nullptr;
  661. }
  662. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  663. if (!elem_type_can_be_constant(elem_type)) {
  664. return false;
  665. }
  666. if (elem->kind == Ast_FieldValue) {
  667. elem = elem->FieldValue.value;
  668. }
  669. TypeAndValue tav = type_and_value_of_expr(elem);
  670. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  671. return tav.value.kind != ExactValue_Invalid;
  672. }
  673. String lb_mangle_name(lbModule *m, Entity *e) {
  674. String name = e->token.string;
  675. AstPackage *pkg = e->pkg;
  676. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  677. String pkgn = pkg->name;
  678. GB_ASSERT(!rune_is_digit(pkgn[0]));
  679. if (pkgn == "llvm") {
  680. pkgn = str_lit("llvm$");
  681. }
  682. isize max_len = pkgn.len + 1 + name.len + 1;
  683. bool require_suffix_id = is_type_polymorphic(e->type, true);
  684. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  685. require_suffix_id = true;
  686. } else if (is_blank_ident(e->token)) {
  687. require_suffix_id = true;
  688. }if (e->flags & EntityFlag_NotExported) {
  689. require_suffix_id = true;
  690. }
  691. if (require_suffix_id) {
  692. max_len += 21;
  693. }
  694. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  695. isize new_name_len = gb_snprintf(
  696. new_name, max_len,
  697. "%.*s.%.*s", LIT(pkgn), LIT(name)
  698. );
  699. if (require_suffix_id) {
  700. char *str = new_name + new_name_len-1;
  701. isize len = max_len-new_name_len;
  702. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  703. new_name_len += extra-1;
  704. }
  705. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  706. return mangled_name;
  707. }
  708. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  709. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  710. // and as a result, the declaration does not have time to determine what it should be
  711. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  712. if (e->TypeName.ir_mangled_name.len != 0) {
  713. return e->TypeName.ir_mangled_name;
  714. }
  715. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  716. if (p == nullptr) {
  717. Entity *proc = nullptr;
  718. if (e->parent_proc_decl != nullptr) {
  719. proc = e->parent_proc_decl->entity;
  720. } else {
  721. Scope *scope = e->scope;
  722. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  723. scope = scope->parent;
  724. }
  725. GB_ASSERT(scope != nullptr);
  726. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  727. proc = scope->procedure_entity;
  728. }
  729. GB_ASSERT(proc->kind == Entity_Procedure);
  730. if (proc->code_gen_procedure != nullptr) {
  731. p = proc->code_gen_procedure;
  732. }
  733. }
  734. // NOTE(bill): Generate a new name
  735. // parent_proc.name-guid
  736. String ts_name = e->token.string;
  737. if (p != nullptr) {
  738. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  739. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  740. u32 guid = ++p->module->nested_type_name_guid;
  741. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  742. String name = make_string(cast(u8 *)name_text, name_len-1);
  743. e->TypeName.ir_mangled_name = name;
  744. return name;
  745. } else {
  746. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  747. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  748. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  749. static u32 guid = 0;
  750. guid += 1;
  751. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  752. String name = make_string(cast(u8 *)name_text, name_len-1);
  753. e->TypeName.ir_mangled_name = name;
  754. return name;
  755. }
  756. }
  757. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  758. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  759. return e->TypeName.ir_mangled_name;
  760. }
  761. GB_ASSERT(e != nullptr);
  762. if (e->pkg == nullptr) {
  763. return e->token.string;
  764. }
  765. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  766. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  767. }
  768. String name = {};
  769. bool no_name_mangle = false;
  770. if (e->kind == Entity_Variable) {
  771. bool is_foreign = e->Variable.is_foreign;
  772. bool is_export = e->Variable.is_export;
  773. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  774. if (e->Variable.link_name.len > 0) {
  775. return e->Variable.link_name;
  776. }
  777. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  778. return e->Procedure.link_name;
  779. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  780. no_name_mangle = true;
  781. }
  782. if (!no_name_mangle) {
  783. name = lb_mangle_name(m, e);
  784. }
  785. if (name.len == 0) {
  786. name = e->token.string;
  787. }
  788. if (e->kind == Entity_TypeName) {
  789. if ((e->scope->flags & ScopeFlag_File) == 0) {
  790. gb_printf_err("<<< %.*s %.*s %p\n", LIT(e->token.string), LIT(name), e);
  791. }
  792. e->TypeName.ir_mangled_name = name;
  793. } else if (e->kind == Entity_Procedure) {
  794. e->Procedure.link_name = name;
  795. }
  796. return name;
  797. }
  798. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  799. Type *original_type = type;
  800. LLVMContextRef ctx = m->ctx;
  801. i64 size = type_size_of(type); // Check size
  802. GB_ASSERT(type != t_invalid);
  803. switch (type->kind) {
  804. case Type_Basic:
  805. switch (type->Basic.kind) {
  806. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  807. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  808. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  809. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  810. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  811. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  812. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  813. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  814. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  815. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  816. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  817. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  818. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  819. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  820. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  821. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  822. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  823. // Basic_f16,
  824. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  825. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  826. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  827. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  828. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  829. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  830. // Basic_complex32,
  831. case Basic_complex64:
  832. {
  833. char const *name = "..complex64";
  834. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  835. if (type != nullptr) {
  836. return type;
  837. }
  838. type = LLVMStructCreateNamed(ctx, name);
  839. LLVMTypeRef fields[2] = {
  840. lb_type(m, t_f32),
  841. lb_type(m, t_f32),
  842. };
  843. LLVMStructSetBody(type, fields, 2, false);
  844. return type;
  845. }
  846. case Basic_complex128:
  847. {
  848. char const *name = "..complex128";
  849. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  850. if (type != nullptr) {
  851. return type;
  852. }
  853. type = LLVMStructCreateNamed(ctx, name);
  854. LLVMTypeRef fields[2] = {
  855. lb_type(m, t_f64),
  856. lb_type(m, t_f64),
  857. };
  858. LLVMStructSetBody(type, fields, 2, false);
  859. return type;
  860. }
  861. case Basic_quaternion128:
  862. {
  863. char const *name = "..quaternion128";
  864. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  865. if (type != nullptr) {
  866. return type;
  867. }
  868. type = LLVMStructCreateNamed(ctx, name);
  869. LLVMTypeRef fields[4] = {
  870. lb_type(m, t_f32),
  871. lb_type(m, t_f32),
  872. lb_type(m, t_f32),
  873. lb_type(m, t_f32),
  874. };
  875. LLVMStructSetBody(type, fields, 4, false);
  876. return type;
  877. }
  878. case Basic_quaternion256:
  879. {
  880. char const *name = "..quaternion256";
  881. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  882. if (type != nullptr) {
  883. return type;
  884. }
  885. type = LLVMStructCreateNamed(ctx, name);
  886. LLVMTypeRef fields[4] = {
  887. lb_type(m, t_f64),
  888. lb_type(m, t_f64),
  889. lb_type(m, t_f64),
  890. lb_type(m, t_f64),
  891. };
  892. LLVMStructSetBody(type, fields, 4, false);
  893. return type;
  894. }
  895. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  896. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  897. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  898. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  899. case Basic_string:
  900. {
  901. char const *name = "..string";
  902. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  903. if (type != nullptr) {
  904. return type;
  905. }
  906. type = LLVMStructCreateNamed(ctx, name);
  907. LLVMTypeRef fields[2] = {
  908. LLVMPointerType(lb_type(m, t_u8), 0),
  909. lb_type(m, t_int),
  910. };
  911. LLVMStructSetBody(type, fields, 2, false);
  912. return type;
  913. }
  914. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  915. case Basic_any:
  916. {
  917. char const *name = "..any";
  918. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  919. if (type != nullptr) {
  920. return type;
  921. }
  922. type = LLVMStructCreateNamed(ctx, name);
  923. LLVMTypeRef fields[2] = {
  924. lb_type(m, t_rawptr),
  925. lb_type(m, t_typeid),
  926. };
  927. LLVMStructSetBody(type, fields, 2, false);
  928. return type;
  929. }
  930. case Basic_typeid: return LLVMIntType(8*cast(unsigned)build_context.word_size);
  931. // Endian Specific Types
  932. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  933. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  934. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  935. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  936. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  937. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  938. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  939. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  940. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  941. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  942. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  943. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  944. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  945. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  946. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  947. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  948. // Untyped types
  949. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  950. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  951. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  952. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  953. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  954. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  955. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  956. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  957. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  958. }
  959. break;
  960. case Type_Named:
  961. {
  962. Type *base = base_type(type->Named.base);
  963. switch (base->kind) {
  964. case Type_Basic:
  965. return lb_type_internal(m, base);
  966. case Type_Named:
  967. case Type_Generic:
  968. case Type_BitFieldValue:
  969. GB_PANIC("INVALID TYPE");
  970. break;
  971. case Type_Opaque:
  972. return lb_type_internal(m, base->Opaque.elem);
  973. case Type_Pointer:
  974. case Type_Array:
  975. case Type_EnumeratedArray:
  976. case Type_Slice:
  977. case Type_DynamicArray:
  978. case Type_Map:
  979. case Type_Enum:
  980. case Type_BitSet:
  981. case Type_SimdVector:
  982. return lb_type_internal(m, base);
  983. // TODO(bill): Deal with this correctly. Can this be named?
  984. case Type_Proc:
  985. return lb_type_internal(m, base);
  986. case Type_Tuple:
  987. return lb_type_internal(m, base);
  988. }
  989. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  990. if (found) {
  991. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  992. if (kind == LLVMStructTypeKind) {
  993. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  994. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  995. if (llvm_type != nullptr) {
  996. return llvm_type;
  997. }
  998. llvm_type = LLVMStructCreateNamed(ctx, name);
  999. map_set(&m->types, hash_type(type), llvm_type);
  1000. lb_clone_struct_type(llvm_type, *found);
  1001. return llvm_type;
  1002. }
  1003. }
  1004. switch (base->kind) {
  1005. case Type_Struct:
  1006. case Type_Union:
  1007. case Type_BitField:
  1008. {
  1009. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1010. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1011. if (llvm_type != nullptr) {
  1012. return llvm_type;
  1013. }
  1014. llvm_type = LLVMStructCreateNamed(ctx, name);
  1015. map_set(&m->types, hash_type(type), llvm_type);
  1016. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1017. return llvm_type;
  1018. }
  1019. }
  1020. return lb_type_internal(m, base);
  1021. }
  1022. case Type_Pointer:
  1023. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1024. case Type_Opaque:
  1025. return lb_type(m, base_type(type));
  1026. case Type_Array:
  1027. return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1028. case Type_EnumeratedArray:
  1029. return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1030. case Type_Slice:
  1031. {
  1032. LLVMTypeRef fields[2] = {
  1033. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1034. lb_type(m, t_int), // len
  1035. };
  1036. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1037. }
  1038. break;
  1039. case Type_DynamicArray:
  1040. {
  1041. LLVMTypeRef fields[4] = {
  1042. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1043. lb_type(m, t_int), // len
  1044. lb_type(m, t_int), // cap
  1045. lb_type(m, t_allocator), // allocator
  1046. };
  1047. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1048. }
  1049. break;
  1050. case Type_Map:
  1051. return lb_type(m, type->Map.internal_type);
  1052. case Type_Struct:
  1053. {
  1054. if (type->Struct.is_raw_union) {
  1055. unsigned field_count = 2;
  1056. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1057. i64 alignment = type_align_of(type);
  1058. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1059. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1060. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1061. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1062. }
  1063. isize offset = 0;
  1064. if (type->Struct.custom_align > 0) {
  1065. offset = 1;
  1066. }
  1067. m->internal_type_level += 1;
  1068. defer (m->internal_type_level -= 1);
  1069. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1070. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1071. for_array(i, type->Struct.fields) {
  1072. Entity *field = type->Struct.fields[i];
  1073. fields[i+offset] = lb_type(m, field->type);
  1074. }
  1075. if (type->Struct.custom_align > 0) {
  1076. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1077. }
  1078. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1079. }
  1080. break;
  1081. case Type_Union:
  1082. if (type->Union.variants.count == 0) {
  1083. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1084. } else {
  1085. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1086. // LLVM takes the first element's alignment as the entire alignment (like C)
  1087. i64 align = type_align_of(type);
  1088. i64 size = type_size_of(type);
  1089. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1090. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1091. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1092. }
  1093. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1094. LLVMTypeRef fields[3] = {};
  1095. unsigned field_count = 1;
  1096. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1097. if (is_type_union_maybe_pointer(type)) {
  1098. field_count += 1;
  1099. fields[1] = lb_type(m, type->Union.variants[0]);
  1100. } else {
  1101. field_count += 2;
  1102. if (block_size == align) {
  1103. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1104. } else {
  1105. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1106. }
  1107. fields[2] = lb_type(m, union_tag_type(type));
  1108. }
  1109. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1110. }
  1111. break;
  1112. case Type_Enum:
  1113. return lb_type(m, base_enum_type(type));
  1114. case Type_Tuple:
  1115. if (type->Tuple.variables.count == 1) {
  1116. return lb_type(m, type->Tuple.variables[0]->type);
  1117. } else {
  1118. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1119. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1120. for_array(i, type->Tuple.variables) {
  1121. Entity *field = type->Tuple.variables[i];
  1122. LLVMTypeRef param_type = nullptr;
  1123. param_type = lb_type(m, field->type);
  1124. fields[i] = param_type;
  1125. }
  1126. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1127. }
  1128. case Type_Proc:
  1129. if (USE_LLVM_ABI) {
  1130. if (m->internal_type_level > 1) {
  1131. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1132. } else {
  1133. unsigned param_count = 0;
  1134. if (type->Proc.calling_convention == ProcCC_Odin) {
  1135. param_count += 1;
  1136. }
  1137. if (type->Proc.param_count != 0) {
  1138. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1139. for_array(i, type->Proc.params->Tuple.variables) {
  1140. Entity *e = type->Proc.params->Tuple.variables[i];
  1141. if (e->kind != Entity_Variable) {
  1142. continue;
  1143. }
  1144. param_count += 1;
  1145. }
  1146. }
  1147. LLVMTypeRef ret = nullptr;
  1148. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1149. if (type->Proc.result_count != 0) {
  1150. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1151. ret = lb_type(m, single_ret);
  1152. if (ret != nullptr) {
  1153. if (is_calling_convention_none(type->Proc.calling_convention) &&
  1154. is_type_boolean(single_ret) &&
  1155. type_size_of(single_ret) <= 1) {
  1156. ret = LLVMInt1TypeInContext(m->ctx);
  1157. }
  1158. }
  1159. }
  1160. isize param_index = 0;
  1161. if (type->Proc.param_count != 0) {
  1162. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1163. for_array(i, type->Proc.params->Tuple.variables) {
  1164. Entity *e = type->Proc.params->Tuple.variables[i];
  1165. if (e->kind != Entity_Variable) {
  1166. continue;
  1167. }
  1168. Type *e_type = reduce_tuple_to_single_type(e->type);
  1169. LLVMTypeRef param_type = nullptr;
  1170. if (is_calling_convention_none(type->Proc.calling_convention) &&
  1171. is_type_boolean(e_type) &&
  1172. type_size_of(e_type) <= 1) {
  1173. param_type = LLVMInt1TypeInContext(m->ctx);
  1174. } else {
  1175. param_type = lb_type(m, e_type);
  1176. }
  1177. params[param_index++] = param_type;
  1178. }
  1179. }
  1180. if (param_index < param_count) {
  1181. params[param_index++] = lb_type(m, t_context_ptr);
  1182. }
  1183. GB_ASSERT(param_index == param_count);
  1184. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1185. map_set(&m->function_type_map, hash_type(type), ft);
  1186. return lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1187. }
  1188. } else {
  1189. set_procedure_abi_types(type);
  1190. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1191. if (type->Proc.return_by_pointer) {
  1192. // Void
  1193. } else if (type->Proc.abi_compat_result_type != nullptr) {
  1194. return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1195. }
  1196. isize extra_param_count = 0;
  1197. if (type->Proc.return_by_pointer) {
  1198. extra_param_count += 1;
  1199. }
  1200. if (type->Proc.calling_convention == ProcCC_Odin) {
  1201. extra_param_count += 1;
  1202. }
  1203. isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1204. auto param_types = array_make<LLVMTypeRef>(temporary_allocator(), 0, param_count);
  1205. if (type->Proc.return_by_pointer) {
  1206. array_add(&param_types, LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0));
  1207. }
  1208. for_array(i, type->Proc.abi_compat_params) {
  1209. Type *param = type->Proc.abi_compat_params[i];
  1210. if (param == nullptr) {
  1211. continue;
  1212. }
  1213. if (type->Proc.params->Tuple.variables[i]->flags & EntityFlag_CVarArg) {
  1214. GB_ASSERT(i+1 == type->Proc.abi_compat_params.count);
  1215. break;
  1216. }
  1217. if (is_type_tuple(param)) {
  1218. param = base_type(param);
  1219. for_array(j, param->Tuple.variables) {
  1220. Entity *v = param->Tuple.variables[j];
  1221. if (v->kind != Entity_Variable) {
  1222. // Sanity check
  1223. continue;
  1224. }
  1225. LLVMTypeRef t = lb_type(m, v->type);
  1226. array_add(&param_types, t);
  1227. }
  1228. } else {
  1229. array_add(&param_types, lb_type(m, param));
  1230. }
  1231. }
  1232. if (type->Proc.calling_convention == ProcCC_Odin) {
  1233. array_add(&param_types, lb_type(m, t_context_ptr));
  1234. }
  1235. LLVMTypeRef t = LLVMFunctionType(return_type, param_types.data, cast(unsigned)param_types.count, type->Proc.c_vararg);
  1236. return LLVMPointerType(t, 0);
  1237. }
  1238. break;
  1239. case Type_BitFieldValue:
  1240. return LLVMIntType(type->BitFieldValue.bits);
  1241. case Type_BitField:
  1242. {
  1243. LLVMTypeRef internal_type = nullptr;
  1244. {
  1245. GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1246. unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1247. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1248. for_array(i, type->BitField.sizes) {
  1249. u32 size = type->BitField.sizes[i];
  1250. fields[i] = LLVMIntType(size);
  1251. }
  1252. internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1253. }
  1254. unsigned field_count = 2;
  1255. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1256. i64 alignment = 1;
  1257. if (type->BitField.custom_align > 0) {
  1258. alignment = type->BitField.custom_align;
  1259. }
  1260. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1261. fields[1] = internal_type;
  1262. return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1263. }
  1264. break;
  1265. case Type_BitSet:
  1266. return LLVMIntType(8*cast(unsigned)type_size_of(type));
  1267. case Type_SimdVector:
  1268. if (type->SimdVector.is_x86_mmx) {
  1269. return LLVMX86MMXTypeInContext(ctx);
  1270. }
  1271. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1272. case Type_RelativePointer:
  1273. return lb_type_internal(m, type->RelativePointer.base_integer);
  1274. case Type_RelativeSlice:
  1275. {
  1276. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1277. unsigned field_count = 2;
  1278. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1279. fields[0] = base_integer;
  1280. fields[1] = base_integer;
  1281. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1282. }
  1283. }
  1284. GB_PANIC("Invalid type %s", type_to_string(type));
  1285. return LLVMInt32TypeInContext(ctx);
  1286. }
  1287. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1288. type = default_type(type);
  1289. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1290. if (found) {
  1291. return *found;
  1292. }
  1293. LLVMTypeRef llvm_type = nullptr;
  1294. m->internal_type_level += 1;
  1295. llvm_type = lb_type_internal(m, type);
  1296. m->internal_type_level -= 1;
  1297. if (USE_LLVM_ABI && m->internal_type_level == 0) {
  1298. map_set(&m->types, hash_type(type), llvm_type);
  1299. }
  1300. return llvm_type;
  1301. }
  1302. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1303. Type *original_type = type;
  1304. LLVMContextRef ctx = m->ctx;
  1305. i64 size = type_size_of(type); // Check size
  1306. GB_ASSERT(type != t_invalid);
  1307. switch (type->kind) {
  1308. case Type_Basic:
  1309. switch (type->Basic.kind) {
  1310. case Basic_llvm_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "llvm bool", 9, 1, 0, LLVMDIFlagZero);
  1311. case Basic_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "bool", 4, 8, 0, LLVMDIFlagZero);
  1312. case Basic_b8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b8", 2, 8, 0, LLVMDIFlagZero);
  1313. case Basic_b16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b16", 3, 16, 0, LLVMDIFlagZero);
  1314. case Basic_b32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b32", 3, 32, 0, LLVMDIFlagZero);
  1315. case Basic_b64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b64", 3, 64, 0, LLVMDIFlagZero);
  1316. case Basic_i8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i8", 2, 8, 0, LLVMDIFlagZero);
  1317. case Basic_u8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u8", 2, 8, 0, LLVMDIFlagZero);
  1318. case Basic_i16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16", 3, 16, 0, LLVMDIFlagZero);
  1319. case Basic_u16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16", 3, 16, 0, LLVMDIFlagZero);
  1320. case Basic_i32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32", 3, 32, 0, LLVMDIFlagZero);
  1321. case Basic_u32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32", 3, 32, 0, LLVMDIFlagZero);
  1322. case Basic_i64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64", 3, 64, 0, LLVMDIFlagZero);
  1323. case Basic_u64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64", 3, 64, 0, LLVMDIFlagZero);
  1324. case Basic_i128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128", 4, 128, 0, LLVMDIFlagZero);
  1325. case Basic_u128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128", 4, 128, 0, LLVMDIFlagZero);
  1326. case Basic_rune: return LLVMDIBuilderCreateBasicType(m->debug_builder, "rune", 4, 32, 0, LLVMDIFlagZero);
  1327. // Basic_f16,
  1328. case Basic_f32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32", 3, 32, 0, LLVMDIFlagZero);
  1329. case Basic_f64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64", 3, 64, 0, LLVMDIFlagZero);
  1330. // Basic_complex32,
  1331. case Basic_complex64:
  1332. {
  1333. return nullptr;
  1334. // char const *name = "..complex64";
  1335. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1336. // if (type != nullptr) {
  1337. // return type;
  1338. // }
  1339. // type = LLVMStructCreateNamed(ctx, name);
  1340. // LLVMTypeRef fields[2] = {
  1341. // lb_type(m, t_f32),
  1342. // lb_type(m, t_f32),
  1343. // };
  1344. // LLVMStructSetBody(type, fields, 2, false);
  1345. // return type;
  1346. }
  1347. case Basic_complex128:
  1348. {
  1349. return nullptr;
  1350. // char const *name = "..complex128";
  1351. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1352. // if (type != nullptr) {
  1353. // return type;
  1354. // }
  1355. // type = LLVMStructCreateNamed(ctx, name);
  1356. // LLVMTypeRef fields[2] = {
  1357. // lb_type(m, t_f64),
  1358. // lb_type(m, t_f64),
  1359. // };
  1360. // LLVMStructSetBody(type, fields, 2, false);
  1361. // return type;
  1362. }
  1363. case Basic_quaternion128:
  1364. {
  1365. return nullptr;
  1366. // char const *name = "..quaternion128";
  1367. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1368. // if (type != nullptr) {
  1369. // return type;
  1370. // }
  1371. // type = LLVMStructCreateNamed(ctx, name);
  1372. // LLVMTypeRef fields[4] = {
  1373. // lb_type(m, t_f32),
  1374. // lb_type(m, t_f32),
  1375. // lb_type(m, t_f32),
  1376. // lb_type(m, t_f32),
  1377. // };
  1378. // LLVMStructSetBody(type, fields, 4, false);
  1379. // return type;
  1380. }
  1381. case Basic_quaternion256:
  1382. {
  1383. return nullptr;
  1384. // char const *name = "..quaternion256";
  1385. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1386. // if (type != nullptr) {
  1387. // return type;
  1388. // }
  1389. // type = LLVMStructCreateNamed(ctx, name);
  1390. // LLVMTypeRef fields[4] = {
  1391. // lb_type(m, t_f64),
  1392. // lb_type(m, t_f64),
  1393. // lb_type(m, t_f64),
  1394. // lb_type(m, t_f64),
  1395. // };
  1396. // LLVMStructSetBody(type, fields, 4, false);
  1397. // return type;
  1398. }
  1399. case Basic_int: return LLVMDIBuilderCreateBasicType(m->debug_builder, "int", 3, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1400. case Basic_uint: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uint", 4, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1401. case Basic_uintptr: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uintptr", 7, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1402. case Basic_rawptr:
  1403. return nullptr;
  1404. // return LLVMPointerType(LLVMInt8Type(), 0);
  1405. case Basic_string:
  1406. {
  1407. return nullptr;
  1408. // char const *name = "..string";
  1409. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1410. // if (type != nullptr) {
  1411. // return type;
  1412. // }
  1413. // type = LLVMStructCreateNamed(ctx, name);
  1414. // LLVMTypeRef fields[2] = {
  1415. // LLVMPointerType(lb_type(m, t_u8), 0),
  1416. // lb_type(m, t_int),
  1417. // };
  1418. // LLVMStructSetBody(type, fields, 2, false);
  1419. // return type;
  1420. }
  1421. case Basic_cstring:
  1422. return nullptr;
  1423. // return LLVMPointerType(LLVMInt8Type(), 0);
  1424. case Basic_any:
  1425. {
  1426. return nullptr;
  1427. // char const *name = "..any";
  1428. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1429. // if (type != nullptr) {
  1430. // return type;
  1431. // }
  1432. // type = LLVMStructCreateNamed(ctx, name);
  1433. // LLVMTypeRef fields[2] = {
  1434. // lb_type(m, t_rawptr),
  1435. // lb_type(m, t_typeid),
  1436. // };
  1437. // LLVMStructSetBody(type, fields, 2, false);
  1438. // return type;
  1439. }
  1440. case Basic_typeid: return LLVMDIBuilderCreateBasicType(m->debug_builder, "typeid", 6, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1441. // Endian Specific Types
  1442. case Basic_i16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1443. case Basic_u16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1444. case Basic_i32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1445. case Basic_u32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1446. case Basic_i64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1447. case Basic_u64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1448. case Basic_i128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1449. case Basic_u128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1450. case Basic_i16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1451. case Basic_u16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1452. case Basic_i32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1453. case Basic_u32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1454. case Basic_i64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1455. case Basic_u64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1456. case Basic_i128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1457. case Basic_u128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1458. // Untyped types
  1459. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1460. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1461. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1462. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1463. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1464. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1465. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1466. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1467. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1468. }
  1469. break;
  1470. case Type_Named:
  1471. {
  1472. return nullptr;
  1473. // Type *base = base_type(type->Named.base);
  1474. // switch (base->kind) {
  1475. // case Type_Basic:
  1476. // return lb_type(m, base);
  1477. // case Type_Named:
  1478. // case Type_Generic:
  1479. // case Type_BitFieldValue:
  1480. // GB_PANIC("INVALID TYPE");
  1481. // break;
  1482. // case Type_Opaque:
  1483. // return lb_type(m, base->Opaque.elem);
  1484. // case Type_Pointer:
  1485. // case Type_Array:
  1486. // case Type_EnumeratedArray:
  1487. // case Type_Slice:
  1488. // case Type_DynamicArray:
  1489. // case Type_Map:
  1490. // case Type_Enum:
  1491. // case Type_BitSet:
  1492. // case Type_SimdVector:
  1493. // return lb_type(m, base);
  1494. // // TODO(bill): Deal with this correctly. Can this be named?
  1495. // case Type_Proc:
  1496. // return lb_type(m, base);
  1497. // case Type_Tuple:
  1498. // return lb_type(m, base);
  1499. // }
  1500. // LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1501. // if (found) {
  1502. // LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1503. // if (kind == LLVMStructTypeKind) {
  1504. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1505. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1506. // if (llvm_type != nullptr) {
  1507. // return llvm_type;
  1508. // }
  1509. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1510. // map_set(&m->types, hash_type(type), llvm_type);
  1511. // lb_clone_struct_type(llvm_type, *found);
  1512. // return llvm_type;
  1513. // }
  1514. // }
  1515. // switch (base->kind) {
  1516. // case Type_Struct:
  1517. // case Type_Union:
  1518. // case Type_BitField:
  1519. // {
  1520. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1521. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1522. // if (llvm_type != nullptr) {
  1523. // return llvm_type;
  1524. // }
  1525. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1526. // map_set(&m->types, hash_type(type), llvm_type);
  1527. // lb_clone_struct_type(llvm_type, lb_type(m, base));
  1528. // return llvm_type;
  1529. // }
  1530. // }
  1531. // return lb_type(m, base);
  1532. }
  1533. case Type_Pointer:
  1534. return nullptr;
  1535. // return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1536. case Type_Opaque:
  1537. return nullptr;
  1538. // return lb_type(m, base_type(type));
  1539. case Type_Array:
  1540. return nullptr;
  1541. // return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1542. case Type_EnumeratedArray:
  1543. return nullptr;
  1544. // return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1545. case Type_Slice:
  1546. {
  1547. return nullptr;
  1548. // LLVMTypeRef fields[2] = {
  1549. // LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1550. // lb_type(m, t_int), // len
  1551. // };
  1552. // return LLVMStructTypeInContext(ctx, fields, 2, false);
  1553. }
  1554. break;
  1555. case Type_DynamicArray:
  1556. {
  1557. return nullptr;
  1558. // LLVMTypeRef fields[4] = {
  1559. // LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1560. // lb_type(m, t_int), // len
  1561. // lb_type(m, t_int), // cap
  1562. // lb_type(m, t_allocator), // allocator
  1563. // };
  1564. // return LLVMStructTypeInContext(ctx, fields, 4, false);
  1565. }
  1566. break;
  1567. case Type_Map:
  1568. return nullptr;
  1569. // return lb_type(m, type->Map.internal_type);
  1570. case Type_Struct:
  1571. {
  1572. return nullptr;
  1573. // if (type->Struct.is_raw_union) {
  1574. // unsigned field_count = 2;
  1575. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1576. // i64 alignment = type_align_of(type);
  1577. // unsigned size_of_union = cast(unsigned)type_size_of(type);
  1578. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1579. // fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1580. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1581. // }
  1582. // isize offset = 0;
  1583. // if (type->Struct.custom_align > 0) {
  1584. // offset = 1;
  1585. // }
  1586. // unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1587. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1588. // GB_ASSERT(fields != nullptr);
  1589. // defer (gb_free(heap_allocator(), fields));
  1590. // for_array(i, type->Struct.fields) {
  1591. // Entity *field = type->Struct.fields[i];
  1592. // fields[i+offset] = lb_type(m, field->type);
  1593. // }
  1594. // if (type->Struct.custom_align > 0) {
  1595. // fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1596. // }
  1597. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1598. }
  1599. break;
  1600. case Type_Union:
  1601. return nullptr;
  1602. // if (type->Union.variants.count == 0) {
  1603. // return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1604. // } else {
  1605. // // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1606. // // LLVM takes the first element's alignment as the entire alignment (like C)
  1607. // i64 align = type_align_of(type);
  1608. // i64 size = type_size_of(type);
  1609. // if (is_type_union_maybe_pointer_original_alignment(type)) {
  1610. // LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1611. // return LLVMStructTypeInContext(ctx, fields, 1, false);
  1612. // }
  1613. // unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1614. // LLVMTypeRef fields[3] = {};
  1615. // unsigned field_count = 1;
  1616. // fields[0] = lb_alignment_prefix_type_hack(m, align);
  1617. // if (is_type_union_maybe_pointer(type)) {
  1618. // field_count += 1;
  1619. // fields[1] = lb_type(m, type->Union.variants[0]);
  1620. // } else {
  1621. // field_count += 2;
  1622. // if (block_size == align) {
  1623. // fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1624. // } else {
  1625. // fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1626. // }
  1627. // fields[2] = lb_type(m, union_tag_type(type));
  1628. // }
  1629. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1630. // }
  1631. // break;
  1632. case Type_Enum:
  1633. return nullptr;
  1634. // return lb_type(m, base_enum_type(type));
  1635. case Type_Tuple:
  1636. return nullptr;
  1637. // if (type->Tuple.variables.count == 1) {
  1638. // return lb_type(m, type->Tuple.variables[0]->type);
  1639. // } else {
  1640. // unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1641. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1642. // defer (gb_free(heap_allocator(), fields));
  1643. // for_array(i, type->Tuple.variables) {
  1644. // Entity *field = type->Tuple.variables[i];
  1645. // fields[i] = lb_type(m, field->type);
  1646. // }
  1647. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1648. // }
  1649. case Type_Proc:
  1650. {
  1651. return nullptr;
  1652. // set_procedure_abi_types(type);
  1653. // LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1654. // isize offset = 0;
  1655. // if (type->Proc.return_by_pointer) {
  1656. // offset = 1;
  1657. // } else if (type->Proc.abi_compat_result_type != nullptr) {
  1658. // return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1659. // }
  1660. // isize extra_param_count = offset;
  1661. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1662. // extra_param_count += 1;
  1663. // }
  1664. // isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1665. // LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1666. // defer (gb_free(heap_allocator(), param_types));
  1667. // isize param_index = offset;
  1668. // for_array(i, type->Proc.abi_compat_params) {
  1669. // Type *param = type->Proc.abi_compat_params[i];
  1670. // if (param == nullptr) {
  1671. // continue;
  1672. // }
  1673. // param_types[param_index++] = lb_type(m, param);
  1674. // }
  1675. // if (type->Proc.return_by_pointer) {
  1676. // param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  1677. // }
  1678. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1679. // param_types[param_index++] = lb_type(m, t_context_ptr);
  1680. // }
  1681. // LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  1682. // return LLVMPointerType(t, 0);
  1683. }
  1684. break;
  1685. case Type_BitFieldValue:
  1686. return nullptr;
  1687. // return LLVMIntType(type->BitFieldValue.bits);
  1688. case Type_BitField:
  1689. {
  1690. return nullptr;
  1691. // LLVMTypeRef internal_type = nullptr;
  1692. // {
  1693. // GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1694. // unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1695. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1696. // defer (gb_free(heap_allocator(), fields));
  1697. // for_array(i, type->BitField.sizes) {
  1698. // u32 size = type->BitField.sizes[i];
  1699. // fields[i] = LLVMIntType(size);
  1700. // }
  1701. // internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1702. // }
  1703. // unsigned field_count = 2;
  1704. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1705. // i64 alignment = 1;
  1706. // if (type->BitField.custom_align > 0) {
  1707. // alignment = type->BitField.custom_align;
  1708. // }
  1709. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1710. // fields[1] = internal_type;
  1711. // return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1712. }
  1713. break;
  1714. case Type_BitSet:
  1715. return nullptr;
  1716. // return LLVMIntType(8*cast(unsigned)type_size_of(type));
  1717. case Type_SimdVector:
  1718. return nullptr;
  1719. // if (type->SimdVector.is_x86_mmx) {
  1720. // return LLVMX86MMXTypeInContext(ctx);
  1721. // }
  1722. // return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1723. }
  1724. GB_PANIC("Invalid type %s", type_to_string(type));
  1725. return nullptr;
  1726. }
  1727. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1728. LLVMTypeRef t = lb_type(m, type);
  1729. LLVMMetadataRef *found = map_get(&m->debug_values, hash_pointer(t));
  1730. if (found != nullptr) {
  1731. return *found;
  1732. }
  1733. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1734. map_set(&m->debug_values, hash_pointer(t), dt);
  1735. return dt;
  1736. }
  1737. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1738. if (e != nullptr) {
  1739. map_set(&m->values, hash_entity(e), val);
  1740. }
  1741. }
  1742. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1743. if (name.len > 0) {
  1744. string_map_set(&m->members, name, val);
  1745. }
  1746. }
  1747. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1748. string_map_set(&m->members, key, val);
  1749. }
  1750. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1751. if (p->entity != nullptr) {
  1752. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1753. }
  1754. string_map_set(&m->procedures, p->name, p);
  1755. }
  1756. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  1757. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  1758. LLVMValueRef values[2] = {
  1759. str_elem.value,
  1760. str_len.value,
  1761. };
  1762. lbValue res = {};
  1763. res.type = t_string;
  1764. res.value = LLVMConstNamedStruct(lb_type(p->module, t_string), values, gb_count_of(values));
  1765. return res;
  1766. } else {
  1767. lbAddr res = lb_add_local_generated(p, t_string, false);
  1768. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  1769. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  1770. return lb_addr_load(p, res);
  1771. }
  1772. }
  1773. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1774. unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name));
  1775. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1776. return LLVMCreateEnumAttribute(ctx, kind, value);
  1777. }
  1778. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1779. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1780. GB_ASSERT(attr != nullptr);
  1781. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1782. }
  1783. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1784. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  1785. }
  1786. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  1787. GB_ASSERT(entity != nullptr);
  1788. String link_name = lb_get_entity_name(m, entity);
  1789. {
  1790. StringHashKey key = string_hash_string(link_name);
  1791. lbValue *found = string_map_get(&m->members, key);
  1792. if (found) {
  1793. lb_add_entity(m, entity, *found);
  1794. lbProcedure **p_found = string_map_get(&m->procedures, key);
  1795. GB_ASSERT(p_found != nullptr);
  1796. return *p_found;
  1797. }
  1798. }
  1799. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1800. p->module = m;
  1801. entity->code_gen_module = m;
  1802. entity->code_gen_procedure = p;
  1803. p->entity = entity;
  1804. p->name = link_name;
  1805. DeclInfo *decl = entity->decl_info;
  1806. ast_node(pl, ProcLit, decl->proc_lit);
  1807. Type *pt = base_type(entity->type);
  1808. GB_ASSERT(pt->kind == Type_Proc);
  1809. set_procedure_abi_types(entity->type);
  1810. p->type = entity->type;
  1811. p->type_expr = decl->type_expr;
  1812. p->body = pl->body;
  1813. p->tags = pt->Proc.tags;
  1814. p->inlining = ProcInlining_none;
  1815. p->is_foreign = entity->Procedure.is_foreign;
  1816. p->is_export = entity->Procedure.is_export;
  1817. p->is_entry_point = false;
  1818. gbAllocator a = heap_allocator();
  1819. p->children.allocator = a;
  1820. p->params.allocator = a;
  1821. p->defer_stmts.allocator = a;
  1822. p->blocks.allocator = a;
  1823. p->branch_blocks.allocator = a;
  1824. p->context_stack.allocator = a;
  1825. if (p->is_foreign) {
  1826. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  1827. }
  1828. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  1829. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1830. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1831. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1832. lbFunctionType **ft_found = map_get(&m->function_type_map, hash_type(p->type));
  1833. if (USE_LLVM_ABI && ft_found) {
  1834. lbFunctionType *abi_ft = *ft_found;
  1835. p->abi_function_type = abi_ft;
  1836. lb_add_function_type_attributes(p->value, abi_ft, abi_ft->calling_convention);
  1837. } else {
  1838. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1839. // TODO(bill): Clean up this logic
  1840. if (build_context.metrics.os != TargetOs_js) {
  1841. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1842. }
  1843. LLVMSetFunctionCallConv(p->value, cc_kind);
  1844. }
  1845. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1846. // // TODO(bill): Clean up this logic
  1847. // if (build_context.metrics.os != TargetOs_js) {
  1848. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1849. // }
  1850. // LLVMSetFunctionCallConv(p->value, cc_kind);
  1851. lbValue proc_value = {p->value, p->type};
  1852. lb_add_entity(m, entity, proc_value);
  1853. lb_add_member(m, p->name, proc_value);
  1854. lb_add_procedure_value(m, p);
  1855. if (p->is_export) {
  1856. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  1857. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  1858. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  1859. if (build_context.metrics.os == TargetOs_js) {
  1860. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  1861. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  1862. }
  1863. }
  1864. if (p->is_foreign) {
  1865. if (build_context.metrics.os == TargetOs_js) {
  1866. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  1867. char const *module_name = "env";
  1868. if (entity->Procedure.foreign_library != nullptr) {
  1869. Entity *foreign_library = entity->Procedure.foreign_library;
  1870. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1871. if (foreign_library->LibraryName.paths.count > 0) {
  1872. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  1873. }
  1874. }
  1875. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  1876. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  1877. }
  1878. }
  1879. // NOTE(bill): offset==0 is the return value
  1880. isize offset = 1;
  1881. if (pt->Proc.return_by_pointer) {
  1882. if (!USE_LLVM_ABI) {
  1883. lb_add_proc_attribute_at_index(p, 1, "sret");
  1884. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1885. }
  1886. offset = 2;
  1887. }
  1888. isize parameter_index = 0;
  1889. if (pt->Proc.param_count) {
  1890. TypeTuple *params = &pt->Proc.params->Tuple;
  1891. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1892. Entity *e = params->variables[i];
  1893. Type *original_type = e->type;
  1894. Type *abi_type = pt->Proc.abi_compat_params[i];
  1895. if (e->kind != Entity_Variable) continue;
  1896. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1897. continue;
  1898. }
  1899. if (is_type_tuple(abi_type)) {
  1900. for_array(j, abi_type->Tuple.variables) {
  1901. Type *tft = abi_type->Tuple.variables[j]->type;
  1902. if (e->flags&EntityFlag_NoAlias) {
  1903. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1904. }
  1905. }
  1906. parameter_index += abi_type->Tuple.variables.count;
  1907. } else {
  1908. if (e->flags&EntityFlag_NoAlias) {
  1909. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1910. }
  1911. parameter_index += 1;
  1912. }
  1913. }
  1914. }
  1915. if (!USE_LLVM_ABI && pt->Proc.calling_convention == ProcCC_Odin) {
  1916. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1917. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1918. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1919. }
  1920. { // Debug Information
  1921. unsigned line = cast(unsigned)entity->token.pos.line;
  1922. LLVMMetadataRef file = nullptr;
  1923. if (entity->file != nullptr) {
  1924. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1925. }
  1926. LLVMMetadataRef scope = nullptr;
  1927. LLVMMetadataRef type = nullptr;
  1928. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1929. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1930. cast(char const *)entity->token.string.text, entity->token.string.len,
  1931. cast(char const *)p->name.text, p->name.len,
  1932. file, line, type,
  1933. true, p->body == nullptr,
  1934. line, LLVMDIFlagZero, false
  1935. );
  1936. GB_ASSERT(res != nullptr);
  1937. map_set(&m->debug_values, hash_pointer(p), res);
  1938. }
  1939. return p;
  1940. }
  1941. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1942. {
  1943. lbValue *found = string_map_get(&m->members, link_name);
  1944. GB_ASSERT(found == nullptr);
  1945. }
  1946. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1947. p->module = m;
  1948. p->name = link_name;
  1949. p->type = type;
  1950. p->type_expr = nullptr;
  1951. p->body = nullptr;
  1952. p->tags = 0;
  1953. p->inlining = ProcInlining_none;
  1954. p->is_foreign = false;
  1955. p->is_export = false;
  1956. p->is_entry_point = false;
  1957. gbAllocator a = permanent_allocator();
  1958. p->children.allocator = a;
  1959. p->params.allocator = a;
  1960. p->defer_stmts.allocator = a;
  1961. p->blocks.allocator = a;
  1962. p->branch_blocks.allocator = a;
  1963. p->context_stack.allocator = a;
  1964. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  1965. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1966. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1967. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1968. Type *pt = p->type;
  1969. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1970. // TODO(bill): Clean up this logic
  1971. if (build_context.metrics.os != TargetOs_js) {
  1972. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1973. }
  1974. LLVMSetFunctionCallConv(p->value, cc_kind);
  1975. lbValue proc_value = {p->value, p->type};
  1976. lb_add_member(m, p->name, proc_value);
  1977. lb_add_procedure_value(m, p);
  1978. // NOTE(bill): offset==0 is the return value
  1979. isize offset = 1;
  1980. if (pt->Proc.return_by_pointer) {
  1981. lb_add_proc_attribute_at_index(p, 1, "sret");
  1982. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1983. offset = 2;
  1984. }
  1985. isize parameter_index = 0;
  1986. if (!USE_LLVM_ABI && pt->Proc.param_count) {
  1987. TypeTuple *params = &pt->Proc.params->Tuple;
  1988. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1989. Entity *e = params->variables[i];
  1990. Type *original_type = e->type;
  1991. Type *abi_type = pt->Proc.abi_compat_params[i];
  1992. if (e->kind != Entity_Variable) continue;
  1993. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1994. continue;
  1995. }
  1996. if (is_type_tuple(abi_type)) {
  1997. for_array(j, abi_type->Tuple.variables) {
  1998. Type *tft = abi_type->Tuple.variables[j]->type;
  1999. if (e->flags&EntityFlag_NoAlias) {
  2000. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  2001. }
  2002. }
  2003. parameter_index += abi_type->Tuple.variables.count;
  2004. } else {
  2005. if (e->flags&EntityFlag_NoAlias) {
  2006. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2007. }
  2008. parameter_index += 1;
  2009. }
  2010. }
  2011. }
  2012. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2013. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2014. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2015. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2016. }
  2017. return p;
  2018. }
  2019. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2020. lbParamPasskind kind = lbParamPass_Value;
  2021. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2022. if (is_type_pointer(abi_type)) {
  2023. GB_ASSERT(e->kind == Entity_Variable);
  2024. Type *av = core_type(type_deref(abi_type));
  2025. if (are_types_identical(av, core_type(e->type))) {
  2026. kind = lbParamPass_Pointer;
  2027. if (e->flags&EntityFlag_Value) {
  2028. kind = lbParamPass_ConstRef;
  2029. }
  2030. } else {
  2031. kind = lbParamPass_BitCast;
  2032. }
  2033. } else if (is_type_integer(abi_type)) {
  2034. kind = lbParamPass_Integer;
  2035. } else if (abi_type == t_llvm_bool) {
  2036. kind = lbParamPass_Value;
  2037. } else if (is_type_boolean(abi_type)) {
  2038. kind = lbParamPass_Integer;
  2039. } else if (is_type_simd_vector(abi_type)) {
  2040. kind = lbParamPass_BitCast;
  2041. } else if (is_type_float(abi_type)) {
  2042. kind = lbParamPass_BitCast;
  2043. } else if (is_type_tuple(abi_type)) {
  2044. kind = lbParamPass_Tuple;
  2045. } else if (is_type_proc(abi_type)) {
  2046. kind = lbParamPass_Value;
  2047. } else {
  2048. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2049. }
  2050. }
  2051. if (kind_) *kind_ = kind;
  2052. lbValue res = {};
  2053. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2054. res.type = abi_type;
  2055. return res;
  2056. }
  2057. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  2058. lbParamPasskind kind = lbParamPass_Value;
  2059. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  2060. array_add(&p->params, v);
  2061. lbValue res = {};
  2062. switch (kind) {
  2063. case lbParamPass_Value: {
  2064. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2065. lbValue x = v;
  2066. if (abi_type == t_llvm_bool) {
  2067. x = lb_emit_conv(p, x, t_bool);
  2068. }
  2069. lb_addr_store(p, l, x);
  2070. return x;
  2071. }
  2072. case lbParamPass_Pointer:
  2073. lb_add_entity(p->module, e, v);
  2074. return lb_emit_load(p, v);
  2075. case lbParamPass_Integer: {
  2076. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2077. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  2078. lb_emit_store(p, iptr, v);
  2079. return lb_addr_load(p, l);
  2080. }
  2081. case lbParamPass_ConstRef:
  2082. lb_add_entity(p->module, e, v);
  2083. return lb_emit_load(p, v);
  2084. case lbParamPass_BitCast: {
  2085. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2086. lbValue x = lb_emit_transmute(p, v, e->type);
  2087. lb_addr_store(p, l, x);
  2088. return x;
  2089. }
  2090. case lbParamPass_Tuple: {
  2091. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2092. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2093. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2094. if (abi_type->Tuple.variables.count > 0) {
  2095. array_pop(&p->params);
  2096. }
  2097. for_array(i, abi_type->Tuple.variables) {
  2098. Type *t = abi_type->Tuple.variables[i]->type;
  2099. GB_ASSERT(!is_type_tuple(t));
  2100. lbParamPasskind elem_kind = lbParamPass_Value;
  2101. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2102. array_add(&p->params, elem);
  2103. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2104. lb_emit_store(p, dst, elem);
  2105. }
  2106. return lb_addr_load(p, l);
  2107. }
  2108. }
  2109. GB_PANIC("Unreachable");
  2110. return {};
  2111. }
  2112. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2113. GB_ASSERT(b != nullptr);
  2114. if (!b->appended) {
  2115. b->appended = true;
  2116. LLVMAppendExistingBasicBlock(p->value, b->block);
  2117. }
  2118. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2119. p->curr_block = b;
  2120. }
  2121. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2122. LLVMTypeRef src_type = LLVMTypeOf(val);
  2123. i64 src_size = lb_sizeof(src_type);
  2124. i64 dst_size = lb_sizeof(dst_type);
  2125. if (src_size != dst_size && (lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2126. // Okay
  2127. } else {
  2128. GB_ASSERT_MSG(src_size == dst_size, "%s == %s", LLVMPrintTypeToString(src_type), LLVMPrintTypeToString(dst_type));
  2129. }
  2130. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2131. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2132. if (src_kind == dst_kind) {
  2133. if (src_kind == LLVMPointerTypeKind) {
  2134. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2135. } else if (src_kind != LLVMStructTypeKind) {
  2136. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2137. }
  2138. } else {
  2139. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2140. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2141. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2142. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2143. }
  2144. }
  2145. if (LLVMIsALoadInst(val)) {
  2146. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2147. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2148. return LLVMBuildLoad(p->builder, val_ptr, "");
  2149. } else {
  2150. GB_ASSERT(p->decl_block != p->curr_block);
  2151. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2152. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2153. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2154. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2155. max_align = gb_max(max_align, 4);
  2156. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2157. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2158. LLVMBuildStore(p->builder, val, nptr);
  2159. return LLVMBuildLoad(p->builder, ptr, "");
  2160. }
  2161. }
  2162. void lb_begin_procedure_body(lbProcedure *p) {
  2163. DeclInfo *decl = decl_info_of_entity(p->entity);
  2164. if (decl != nullptr) {
  2165. for_array(i, decl->labels) {
  2166. BlockLabel bl = decl->labels[i];
  2167. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2168. array_add(&p->branch_blocks, bb);
  2169. }
  2170. }
  2171. if (p->tags != 0) {
  2172. u64 in = p->tags;
  2173. u64 out = p->module->state_flags;
  2174. if (in & ProcTag_bounds_check) {
  2175. out |= StateFlag_bounds_check;
  2176. out &= ~StateFlag_no_bounds_check;
  2177. } else if (in & ProcTag_no_bounds_check) {
  2178. out |= StateFlag_no_bounds_check;
  2179. out &= ~StateFlag_bounds_check;
  2180. }
  2181. p->module->state_flags = out;
  2182. }
  2183. p->builder = LLVMCreateBuilder();
  2184. p->decl_block = lb_create_block(p, "decls", true);
  2185. p->entry_block = lb_create_block(p, "entry", true);
  2186. lb_start_block(p, p->entry_block);
  2187. GB_ASSERT(p->type != nullptr);
  2188. if (p->abi_function_type) {
  2189. lbFunctionType *ft = p->abi_function_type;
  2190. unsigned param_offset = 0;
  2191. lbValue return_ptr_value = {};
  2192. if (ft->ret.kind == lbArg_Indirect) {
  2193. // NOTE(bill): this must be parameter 0
  2194. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2195. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2196. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2197. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2198. return_ptr_value.type = ptr_type;
  2199. p->return_ptr = lb_addr(return_ptr_value);
  2200. lb_add_entity(p->module, e, return_ptr_value);
  2201. param_offset += 1;
  2202. }
  2203. if (p->type->Proc.params != nullptr) {
  2204. TypeTuple *params = &p->type->Proc.params->Tuple;
  2205. unsigned param_index = 0;
  2206. for_array(i, params->variables) {
  2207. Entity *e = params->variables[i];
  2208. if (e->kind != Entity_Variable) {
  2209. continue;
  2210. }
  2211. lbArgType *arg_type = &ft->args[param_index];
  2212. if (arg_type->kind == lbArg_Ignore) {
  2213. continue;
  2214. } else if (arg_type->kind == lbArg_Direct) {
  2215. lbParamPasskind kind = lbParamPass_Value;
  2216. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2217. if (param_type != arg_type->type) {
  2218. kind = lbParamPass_BitCast;
  2219. }
  2220. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2221. if (USE_LLVM_ABI && LLVMTypeOf(value) == LLVMInt1TypeInContext(p->module->ctx)) {
  2222. value = LLVMBuildZExtOrBitCast(p->builder, value, param_type, "");
  2223. } else {
  2224. value = OdinLLVMBuildTransmute(p, value, param_type);
  2225. }
  2226. lbValue param = {};
  2227. param.value = value;
  2228. param.type = e->type;
  2229. array_add(&p->params, param);
  2230. if (e->token.string.len != 0) {
  2231. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2232. lb_addr_store(p, l, param);
  2233. }
  2234. param_index += 1;
  2235. } else if (arg_type->kind == lbArg_Indirect) {
  2236. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2237. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2238. lbValue param = {};
  2239. param.value = value;
  2240. param.type = e->type;
  2241. array_add(&p->params, param);
  2242. lbValue ptr = {};
  2243. ptr.value = value_ptr;
  2244. ptr.type = alloc_type_pointer(e->type);
  2245. lb_add_entity(p->module, e, ptr);
  2246. param_index += 1;
  2247. }
  2248. }
  2249. }
  2250. if (p->type->Proc.has_named_results) {
  2251. GB_ASSERT(p->type->Proc.result_count > 0);
  2252. TypeTuple *results = &p->type->Proc.results->Tuple;
  2253. for_array(i, results->variables) {
  2254. Entity *e = results->variables[i];
  2255. GB_ASSERT(e->kind == Entity_Variable);
  2256. if (e->token.string != "") {
  2257. GB_ASSERT(!is_blank_ident(e->token));
  2258. lbAddr res = {};
  2259. if (return_ptr_value.value) {
  2260. lbValue ptr = return_ptr_value;
  2261. if (results->variables.count != 1) {
  2262. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2263. }
  2264. res = lb_addr(ptr);
  2265. lb_add_entity(p->module, e, ptr);
  2266. } else {
  2267. res = lb_add_local(p, e->type, e);
  2268. }
  2269. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2270. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2271. lb_addr_store(p, res, c);
  2272. }
  2273. }
  2274. }
  2275. }
  2276. } else {
  2277. i32 parameter_index = 0;
  2278. lbValue return_ptr_value = {};
  2279. if (p->type->Proc.return_by_pointer) {
  2280. // NOTE(bill): this must be parameter 0
  2281. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2282. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2283. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2284. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2285. return_ptr_value.type = ptr_type;
  2286. p->return_ptr = lb_addr(return_ptr_value);
  2287. lb_add_entity(p->module, e, return_ptr_value);
  2288. parameter_index += 1;
  2289. }
  2290. if (p->type->Proc.params != nullptr) {
  2291. TypeTuple *params = &p->type->Proc.params->Tuple;
  2292. auto abi_types = p->type->Proc.abi_compat_params;
  2293. for_array(i, params->variables) {
  2294. Entity *e = params->variables[i];
  2295. if (e->kind != Entity_Variable) {
  2296. continue;
  2297. }
  2298. Type *abi_type = e->type;
  2299. if (abi_types.count > 0) {
  2300. abi_type = abi_types[i];
  2301. }
  2302. if (e->token.string != "") {
  2303. lb_add_param(p, e, nullptr, abi_type, parameter_index);
  2304. }
  2305. if (is_type_tuple(abi_type)) {
  2306. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  2307. } else {
  2308. parameter_index += 1;
  2309. }
  2310. }
  2311. }
  2312. if (p->type->Proc.has_named_results) {
  2313. GB_ASSERT(p->type->Proc.result_count > 0);
  2314. TypeTuple *results = &p->type->Proc.results->Tuple;
  2315. for_array(i, results->variables) {
  2316. Entity *e = results->variables[i];
  2317. GB_ASSERT(e->kind == Entity_Variable);
  2318. if (e->token.string != "") {
  2319. GB_ASSERT(!is_blank_ident(e->token));
  2320. lbAddr res = {};
  2321. if (p->type->Proc.return_by_pointer) {
  2322. lbValue ptr = return_ptr_value;
  2323. if (results->variables.count != 1) {
  2324. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2325. }
  2326. res = lb_addr(ptr);
  2327. lb_add_entity(p->module, e, ptr);
  2328. } else {
  2329. res = lb_add_local(p, e->type, e);
  2330. }
  2331. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2332. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2333. lb_addr_store(p, res, c);
  2334. }
  2335. }
  2336. }
  2337. }
  2338. }
  2339. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2340. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  2341. e->flags |= EntityFlag_NoAlias;
  2342. lbValue param = {};
  2343. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  2344. param.type = e->type;
  2345. lb_add_entity(p->module, e, param);
  2346. lbAddr ctx_addr = {};
  2347. ctx_addr.kind = lbAddr_Context;
  2348. ctx_addr.addr = param;
  2349. lbContextData ctx = {ctx_addr, p->scope_index};
  2350. array_add(&p->context_stack, ctx);
  2351. }
  2352. lb_start_block(p, p->entry_block);
  2353. }
  2354. void lb_end_procedure_body(lbProcedure *p) {
  2355. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2356. LLVMBuildBr(p->builder, p->entry_block->block);
  2357. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2358. if (p->type->Proc.result_count == 0) {
  2359. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2360. if (!lb_is_instr_terminating(instr)) {
  2361. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2362. LLVMBuildRetVoid(p->builder);
  2363. }
  2364. } else {
  2365. if (p->curr_block->preds.count == 0) {
  2366. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2367. if (instr == nullptr) {
  2368. // NOTE(bill): Remove dead trailing block
  2369. LLVMDeleteBasicBlock(p->curr_block->block);
  2370. }
  2371. }
  2372. }
  2373. p->curr_block = nullptr;
  2374. p->module->state_flags = 0;
  2375. }
  2376. void lb_end_procedure(lbProcedure *p) {
  2377. LLVMDisposeBuilder(p->builder);
  2378. }
  2379. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2380. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2381. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2382. array_add(&from->succs, to);
  2383. array_add(&to->preds, from);
  2384. }
  2385. }
  2386. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2387. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2388. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2389. b->appended = false;
  2390. if (append) {
  2391. b->appended = true;
  2392. LLVMAppendExistingBasicBlock(p->value, b->block);
  2393. }
  2394. b->scope = p->curr_scope;
  2395. b->scope_index = p->scope_index;
  2396. b->preds.allocator = heap_allocator();
  2397. b->succs.allocator = heap_allocator();
  2398. array_add(&p->blocks, b);
  2399. return b;
  2400. }
  2401. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2402. if (p->curr_block == nullptr) {
  2403. return;
  2404. }
  2405. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2406. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2407. return;
  2408. }
  2409. lb_add_edge(p->curr_block, target_block);
  2410. LLVMBuildBr(p->builder, target_block->block);
  2411. p->curr_block = nullptr;
  2412. }
  2413. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2414. lbBlock *b = p->curr_block;
  2415. if (b == nullptr) {
  2416. return;
  2417. }
  2418. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2419. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2420. return;
  2421. }
  2422. lb_add_edge(b, true_block);
  2423. lb_add_edge(b, false_block);
  2424. LLVMValueRef cv = cond.value;
  2425. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2426. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2427. }
  2428. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2429. GB_ASSERT(cond != nullptr);
  2430. GB_ASSERT(true_block != nullptr);
  2431. GB_ASSERT(false_block != nullptr);
  2432. switch (cond->kind) {
  2433. case_ast_node(pe, ParenExpr, cond);
  2434. return lb_build_cond(p, pe->expr, true_block, false_block);
  2435. case_end;
  2436. case_ast_node(ue, UnaryExpr, cond);
  2437. if (ue->op.kind == Token_Not) {
  2438. return lb_build_cond(p, ue->expr, false_block, true_block);
  2439. }
  2440. case_end;
  2441. case_ast_node(be, BinaryExpr, cond);
  2442. if (be->op.kind == Token_CmpAnd) {
  2443. lbBlock *block = lb_create_block(p, "cmp.and");
  2444. lb_build_cond(p, be->left, block, false_block);
  2445. lb_start_block(p, block);
  2446. return lb_build_cond(p, be->right, true_block, false_block);
  2447. } else if (be->op.kind == Token_CmpOr) {
  2448. lbBlock *block = lb_create_block(p, "cmp.or");
  2449. lb_build_cond(p, be->left, true_block, block);
  2450. lb_start_block(p, block);
  2451. return lb_build_cond(p, be->right, true_block, false_block);
  2452. }
  2453. case_end;
  2454. }
  2455. lbValue v = lb_build_expr(p, cond);
  2456. // v = lb_emit_conv(p, v, t_bool);
  2457. v = lb_emit_conv(p, v, t_llvm_bool);
  2458. lb_emit_if(p, v, true_block, false_block);
  2459. return v;
  2460. }
  2461. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2462. GB_ASSERT(p->decl_block != p->curr_block);
  2463. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2464. char const *name = "";
  2465. if (e != nullptr) {
  2466. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2467. }
  2468. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2469. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2470. LLVMSetAlignment(ptr, 16); // TODO(bill): Make this configurable
  2471. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2472. if (zero_init) {
  2473. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2474. }
  2475. lbValue val = {};
  2476. val.value = ptr;
  2477. val.type = alloc_type_pointer(type);
  2478. if (e != nullptr) {
  2479. lb_add_entity(p->module, e, val);
  2480. }
  2481. return lb_addr(val);
  2482. }
  2483. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2484. return lb_add_local(p, type, nullptr, zero_init);
  2485. }
  2486. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2487. GB_ASSERT(pd->body != nullptr);
  2488. lbModule *m = p->module;
  2489. auto *min_dep_set = &m->info->minimum_dependency_set;
  2490. if (ptr_set_exists(min_dep_set, e) == false) {
  2491. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2492. return;
  2493. }
  2494. // NOTE(bill): Generate a new name
  2495. // parent.name-guid
  2496. String original_name = e->token.string;
  2497. String pd_name = original_name;
  2498. if (e->Procedure.link_name.len > 0) {
  2499. pd_name = e->Procedure.link_name;
  2500. }
  2501. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2502. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2503. i32 guid = cast(i32)p->children.count;
  2504. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2505. String name = make_string(cast(u8 *)name_text, name_len-1);
  2506. set_procedure_abi_types(e->type);
  2507. e->Procedure.link_name = name;
  2508. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2509. e->code_gen_procedure = nested_proc;
  2510. lbValue value = {};
  2511. value.value = nested_proc->value;
  2512. value.type = nested_proc->type;
  2513. lb_add_entity(m, e, value);
  2514. array_add(&p->children, nested_proc);
  2515. array_add(&m->procedures_to_generate, nested_proc);
  2516. }
  2517. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2518. if (e == nullptr) {
  2519. return;
  2520. }
  2521. GB_ASSERT(e->kind == Entity_LibraryName);
  2522. GB_ASSERT(e->flags & EntityFlag_Used);
  2523. for_array(i, e->LibraryName.paths) {
  2524. String library_path = e->LibraryName.paths[i];
  2525. if (library_path.len == 0) {
  2526. continue;
  2527. }
  2528. bool ok = true;
  2529. for_array(path_index, m->foreign_library_paths) {
  2530. String path = m->foreign_library_paths[path_index];
  2531. #if defined(GB_SYSTEM_WINDOWS)
  2532. if (str_eq_ignore_case(path, library_path)) {
  2533. #else
  2534. if (str_eq(path, library_path)) {
  2535. #endif
  2536. ok = false;
  2537. break;
  2538. }
  2539. }
  2540. if (ok) {
  2541. array_add(&m->foreign_library_paths, library_path);
  2542. }
  2543. }
  2544. }
  2545. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2546. if (vd == nullptr || vd->is_mutable) {
  2547. return;
  2548. }
  2549. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2550. static i32 global_guid = 0;
  2551. for_array(i, vd->names) {
  2552. Ast *ident = vd->names[i];
  2553. GB_ASSERT(ident->kind == Ast_Ident);
  2554. Entity *e = entity_of_node(ident);
  2555. GB_ASSERT(e != nullptr);
  2556. if (e->kind != Entity_TypeName) {
  2557. continue;
  2558. }
  2559. bool polymorphic_struct = false;
  2560. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2561. Type *bt = base_type(e->type);
  2562. if (bt->kind == Type_Struct) {
  2563. polymorphic_struct = bt->Struct.is_polymorphic;
  2564. }
  2565. }
  2566. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2567. continue;
  2568. }
  2569. if (e->TypeName.ir_mangled_name.len != 0) {
  2570. // NOTE(bill): Already set
  2571. continue;
  2572. }
  2573. lb_set_nested_type_name_ir_mangled_name(e, p);
  2574. }
  2575. for_array(i, vd->names) {
  2576. Ast *ident = vd->names[i];
  2577. GB_ASSERT(ident->kind == Ast_Ident);
  2578. Entity *e = entity_of_node(ident);
  2579. GB_ASSERT(e != nullptr);
  2580. if (e->kind != Entity_Procedure) {
  2581. continue;
  2582. }
  2583. CheckerInfo *info = p->module->info;
  2584. DeclInfo *decl = decl_info_of_entity(e);
  2585. ast_node(pl, ProcLit, decl->proc_lit);
  2586. if (pl->body != nullptr) {
  2587. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2588. if (found) {
  2589. auto procs = *found;
  2590. for_array(i, procs) {
  2591. Entity *e = procs[i];
  2592. if (!ptr_set_exists(min_dep_set, e)) {
  2593. continue;
  2594. }
  2595. DeclInfo *d = decl_info_of_entity(e);
  2596. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2597. }
  2598. } else {
  2599. lb_build_nested_proc(p, pl, e);
  2600. }
  2601. } else {
  2602. // FFI - Foreign function interace
  2603. String original_name = e->token.string;
  2604. String name = original_name;
  2605. if (e->Procedure.is_foreign) {
  2606. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2607. }
  2608. if (e->Procedure.link_name.len > 0) {
  2609. name = e->Procedure.link_name;
  2610. }
  2611. lbValue *prev_value = string_map_get(&p->module->members, name);
  2612. if (prev_value != nullptr) {
  2613. // NOTE(bill): Don't do mutliple declarations in the IR
  2614. return;
  2615. }
  2616. set_procedure_abi_types(e->type);
  2617. e->Procedure.link_name = name;
  2618. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2619. lbValue value = {};
  2620. value.value = nested_proc->value;
  2621. value.type = nested_proc->type;
  2622. array_add(&p->module->procedures_to_generate, nested_proc);
  2623. if (p != nullptr) {
  2624. array_add(&p->children, nested_proc);
  2625. } else {
  2626. string_map_set(&p->module->members, name, value);
  2627. }
  2628. }
  2629. }
  2630. }
  2631. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  2632. for_array(i, stmts) {
  2633. Ast *stmt = stmts[i];
  2634. switch (stmt->kind) {
  2635. case_ast_node(vd, ValueDecl, stmt);
  2636. lb_build_constant_value_decl(p, vd);
  2637. case_end;
  2638. case_ast_node(fb, ForeignBlockDecl, stmt);
  2639. ast_node(block, BlockStmt, fb->body);
  2640. lb_build_stmt_list(p, block->stmts);
  2641. case_end;
  2642. }
  2643. }
  2644. for_array(i, stmts) {
  2645. lb_build_stmt(p, stmts[i]);
  2646. }
  2647. }
  2648. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2649. GB_ASSERT(ident->kind == Ast_Ident);
  2650. Entity *e = entity_of_node(ident);
  2651. GB_ASSERT(e->kind == Entity_Label);
  2652. for_array(i, p->branch_blocks) {
  2653. lbBranchBlocks *b = &p->branch_blocks[i];
  2654. if (b->label == e->Label.node) {
  2655. return *b;
  2656. }
  2657. }
  2658. GB_PANIC("Unreachable");
  2659. lbBranchBlocks empty = {};
  2660. return empty;
  2661. }
  2662. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2663. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  2664. tl->prev = p->target_list;
  2665. tl->break_ = break_;
  2666. tl->continue_ = continue_;
  2667. tl->fallthrough_ = fallthrough_;
  2668. p->target_list = tl;
  2669. if (label != nullptr) { // Set label blocks
  2670. GB_ASSERT(label->kind == Ast_Label);
  2671. for_array(i, p->branch_blocks) {
  2672. lbBranchBlocks *b = &p->branch_blocks[i];
  2673. GB_ASSERT(b->label != nullptr && label != nullptr);
  2674. GB_ASSERT(b->label->kind == Ast_Label);
  2675. if (b->label == label) {
  2676. b->break_ = break_;
  2677. b->continue_ = continue_;
  2678. return tl;
  2679. }
  2680. }
  2681. GB_PANIC("Unreachable");
  2682. }
  2683. return tl;
  2684. }
  2685. void lb_pop_target_list(lbProcedure *p) {
  2686. p->target_list = p->target_list->prev;
  2687. }
  2688. void lb_open_scope(lbProcedure *p) {
  2689. p->scope_index += 1;
  2690. }
  2691. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  2692. lb_emit_defer_stmts(p, kind, block);
  2693. GB_ASSERT(p->scope_index > 0);
  2694. // NOTE(bill): Remove `context`s made in that scope
  2695. while (p->context_stack.count > 0) {
  2696. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  2697. if (ctx->scope_index >= p->scope_index) {
  2698. array_pop(&p->context_stack);
  2699. } else {
  2700. break;
  2701. }
  2702. }
  2703. p->scope_index -= 1;
  2704. }
  2705. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  2706. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  2707. GB_ASSERT(is_type_boolean(tv.type));
  2708. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  2709. if (tv.value.value_bool) {
  2710. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  2711. } else if (ws->else_stmt) {
  2712. switch (ws->else_stmt->kind) {
  2713. case Ast_BlockStmt:
  2714. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  2715. break;
  2716. case Ast_WhenStmt:
  2717. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  2718. break;
  2719. default:
  2720. GB_PANIC("Invalid 'else' statement in 'when' statement");
  2721. break;
  2722. }
  2723. }
  2724. }
  2725. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  2726. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2727. lbModule *m = p->module;
  2728. lbValue count = {};
  2729. Type *expr_type = base_type(type_deref(expr.type));
  2730. switch (expr_type->kind) {
  2731. case Type_Array:
  2732. count = lb_const_int(m, t_int, expr_type->Array.count);
  2733. break;
  2734. }
  2735. lbValue val = {};
  2736. lbValue idx = {};
  2737. lbBlock *loop = nullptr;
  2738. lbBlock *done = nullptr;
  2739. lbBlock *body = nullptr;
  2740. lbAddr index = lb_add_local_generated(p, t_int, false);
  2741. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  2742. loop = lb_create_block(p, "for.index.loop");
  2743. lb_emit_jump(p, loop);
  2744. lb_start_block(p, loop);
  2745. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  2746. lb_addr_store(p, index, incr);
  2747. body = lb_create_block(p, "for.index.body");
  2748. done = lb_create_block(p, "for.index.done");
  2749. if (count.value == nullptr) {
  2750. GB_ASSERT(count_ptr.value != nullptr);
  2751. count = lb_emit_load(p, count_ptr);
  2752. }
  2753. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  2754. lb_emit_if(p, cond, body, done);
  2755. lb_start_block(p, body);
  2756. idx = lb_addr_load(p, index);
  2757. switch (expr_type->kind) {
  2758. case Type_Array: {
  2759. if (val_type != nullptr) {
  2760. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2761. }
  2762. break;
  2763. }
  2764. case Type_EnumeratedArray: {
  2765. if (val_type != nullptr) {
  2766. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2767. // NOTE(bill): Override the idx value for the enumeration
  2768. Type *index_type = expr_type->EnumeratedArray.index;
  2769. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  2770. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  2771. }
  2772. }
  2773. break;
  2774. }
  2775. case Type_Slice: {
  2776. if (val_type != nullptr) {
  2777. lbValue elem = lb_slice_elem(p, expr);
  2778. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2779. }
  2780. break;
  2781. }
  2782. case Type_DynamicArray: {
  2783. if (val_type != nullptr) {
  2784. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  2785. elem = lb_emit_load(p, elem);
  2786. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2787. }
  2788. break;
  2789. }
  2790. case Type_Map: {
  2791. lbValue entries = lb_map_entries_ptr(p, expr);
  2792. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  2793. elem = lb_emit_load(p, elem);
  2794. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  2795. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  2796. lbValue key_raw = lb_emit_struct_ep(p, entry, 0);
  2797. key_raw = lb_emit_struct_ep(p, key_raw, 1);
  2798. lbValue key = lb_emit_conv(p, key_raw, alloc_type_pointer(expr_type->Map.key));
  2799. idx = lb_emit_load(p, key);
  2800. break;
  2801. }
  2802. default:
  2803. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  2804. break;
  2805. }
  2806. if (val_) *val_ = val;
  2807. if (idx_) *idx_ = idx;
  2808. if (loop_) *loop_ = loop;
  2809. if (done_) *done_ = done;
  2810. }
  2811. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  2812. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2813. lbModule *m = p->module;
  2814. lbValue count = lb_const_int(m, t_int, 0);
  2815. Type *expr_type = base_type(expr.type);
  2816. switch (expr_type->kind) {
  2817. case Type_Basic:
  2818. count = lb_string_len(p, expr);
  2819. break;
  2820. default:
  2821. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  2822. break;
  2823. }
  2824. lbValue val = {};
  2825. lbValue idx = {};
  2826. lbBlock *loop = nullptr;
  2827. lbBlock *done = nullptr;
  2828. lbBlock *body = nullptr;
  2829. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2830. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2831. loop = lb_create_block(p, "for.string.loop");
  2832. lb_emit_jump(p, loop);
  2833. lb_start_block(p, loop);
  2834. body = lb_create_block(p, "for.string.body");
  2835. done = lb_create_block(p, "for.string.done");
  2836. lbValue offset = lb_addr_load(p, offset_);
  2837. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  2838. lb_emit_if(p, cond, body, done);
  2839. lb_start_block(p, body);
  2840. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  2841. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  2842. auto args = array_make<lbValue>(permanent_allocator(), 1);
  2843. args[0] = lb_emit_string(p, str_elem, str_len);
  2844. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  2845. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  2846. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  2847. idx = offset;
  2848. if (val_type != nullptr) {
  2849. val = lb_emit_struct_ev(p, rune_and_len, 0);
  2850. }
  2851. if (val_) *val_ = val;
  2852. if (idx_) *idx_ = idx;
  2853. if (loop_) *loop_ = loop;
  2854. if (done_) *done_ = done;
  2855. }
  2856. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  2857. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2858. lbModule *m = p->module;
  2859. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  2860. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  2861. lbValue lower = lb_build_expr(p, node->left);
  2862. lbValue upper = {};
  2863. lbValue val = {};
  2864. lbValue idx = {};
  2865. lbBlock *loop = nullptr;
  2866. lbBlock *done = nullptr;
  2867. lbBlock *body = nullptr;
  2868. if (val_type == nullptr) {
  2869. val_type = lower.type;
  2870. }
  2871. lbAddr value = lb_add_local_generated(p, val_type, false);
  2872. lb_addr_store(p, value, lower);
  2873. lbAddr index = lb_add_local_generated(p, t_int, false);
  2874. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  2875. loop = lb_create_block(p, "for.interval.loop");
  2876. lb_emit_jump(p, loop);
  2877. lb_start_block(p, loop);
  2878. body = lb_create_block(p, "for.interval.body");
  2879. done = lb_create_block(p, "for.interval.done");
  2880. TokenKind op = Token_Lt;
  2881. switch (node->op.kind) {
  2882. case Token_Ellipsis: op = Token_LtEq; break;
  2883. case Token_RangeHalf: op = Token_Lt; break;
  2884. default: GB_PANIC("Invalid interval operator"); break;
  2885. }
  2886. upper = lb_build_expr(p, node->right);
  2887. lbValue curr_value = lb_addr_load(p, value);
  2888. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  2889. lb_emit_if(p, cond, body, done);
  2890. lb_start_block(p, body);
  2891. val = lb_addr_load(p, value);
  2892. idx = lb_addr_load(p, index);
  2893. lb_emit_increment(p, value.addr);
  2894. lb_emit_increment(p, index.addr);
  2895. if (val_) *val_ = val;
  2896. if (idx_) *idx_ = idx;
  2897. if (loop_) *loop_ = loop;
  2898. if (done_) *done_ = done;
  2899. }
  2900. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2901. lbModule *m = p->module;
  2902. Type *t = enum_type;
  2903. GB_ASSERT(is_type_enum(t));
  2904. Type *enum_ptr = alloc_type_pointer(t);
  2905. t = base_type(t);
  2906. Type *core_elem = core_type(t);
  2907. GB_ASSERT(t->kind == Type_Enum);
  2908. i64 enum_count = t->Enum.fields.count;
  2909. lbValue max_count = lb_const_int(m, t_int, enum_count);
  2910. lbValue ti = lb_type_info(m, t);
  2911. lbValue variant = lb_emit_struct_ep(p, ti, 3);
  2912. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  2913. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  2914. lbValue values_data = lb_slice_elem(p, values);
  2915. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2916. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2917. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  2918. lb_emit_jump(p, loop);
  2919. lb_start_block(p, loop);
  2920. lbBlock *body = lb_create_block(p, "for.enum.body");
  2921. lbBlock *done = lb_create_block(p, "for.enum.done");
  2922. lbValue offset = lb_addr_load(p, offset_);
  2923. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  2924. lb_emit_if(p, cond, body, done);
  2925. lb_start_block(p, body);
  2926. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  2927. lb_emit_increment(p, offset_.addr);
  2928. lbValue val = {};
  2929. if (val_type != nullptr) {
  2930. GB_ASSERT(are_types_identical(enum_type, val_type));
  2931. if (is_type_integer(core_elem)) {
  2932. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  2933. val = lb_emit_conv(p, i, t);
  2934. } else {
  2935. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  2936. }
  2937. }
  2938. if (val_) *val_ = val;
  2939. if (idx_) *idx_ = offset;
  2940. if (loop_) *loop_ = loop;
  2941. if (done_) *done_ = done;
  2942. }
  2943. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  2944. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  2945. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  2946. lb_emit_jump(p, loop);
  2947. lb_start_block(p, loop);
  2948. lbBlock *body = lb_create_block(p, "for.tuple.body");
  2949. lbBlock *done = lb_create_block(p, "for.tuple.done");
  2950. lbValue tuple_value = lb_build_expr(p, expr);
  2951. Type *tuple = tuple_value.type;
  2952. GB_ASSERT(tuple->kind == Type_Tuple);
  2953. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  2954. i32 cond_index = tuple_count-1;
  2955. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  2956. lb_emit_if(p, cond, body, done);
  2957. lb_start_block(p, body);
  2958. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  2959. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  2960. if (loop_) *loop_ = loop;
  2961. if (done_) *done_ = done;
  2962. }
  2963. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  2964. lb_open_scope(p);
  2965. Type *val0_type = nullptr;
  2966. Type *val1_type = nullptr;
  2967. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2968. val0_type = type_of_expr(rs->val0);
  2969. }
  2970. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2971. val1_type = type_of_expr(rs->val1);
  2972. }
  2973. if (val0_type != nullptr) {
  2974. Entity *e = entity_of_node(rs->val0);
  2975. lb_add_local(p, e->type, e, true);
  2976. }
  2977. if (val1_type != nullptr) {
  2978. Entity *e = entity_of_node(rs->val1);
  2979. lb_add_local(p, e->type, e, true);
  2980. }
  2981. lbValue val = {};
  2982. lbValue key = {};
  2983. lbBlock *loop = nullptr;
  2984. lbBlock *done = nullptr;
  2985. Ast *expr = unparen_expr(rs->expr);
  2986. bool is_map = false;
  2987. TypeAndValue tav = type_and_value_of_expr(expr);
  2988. if (is_ast_range(expr)) {
  2989. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  2990. } else if (tav.mode == Addressing_Type) {
  2991. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  2992. } else {
  2993. Type *expr_type = type_of_expr(expr);
  2994. Type *et = base_type(type_deref(expr_type));
  2995. switch (et->kind) {
  2996. case Type_Map: {
  2997. is_map = true;
  2998. lbValue map = lb_build_addr_ptr(p, expr);
  2999. if (is_type_pointer(type_deref(map.type))) {
  3000. map = lb_emit_load(p, map);
  3001. }
  3002. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3003. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3004. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3005. break;
  3006. }
  3007. case Type_Array: {
  3008. lbValue array = lb_build_addr_ptr(p, expr);
  3009. if (is_type_pointer(type_deref(array.type))) {
  3010. array = lb_emit_load(p, array);
  3011. }
  3012. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3013. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3014. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3015. break;
  3016. }
  3017. case Type_EnumeratedArray: {
  3018. lbValue array = lb_build_addr_ptr(p, expr);
  3019. if (is_type_pointer(type_deref(array.type))) {
  3020. array = lb_emit_load(p, array);
  3021. }
  3022. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3023. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3024. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3025. break;
  3026. }
  3027. case Type_DynamicArray: {
  3028. lbValue count_ptr = {};
  3029. lbValue array = lb_build_addr_ptr(p, expr);
  3030. if (is_type_pointer(type_deref(array.type))) {
  3031. array = lb_emit_load(p, array);
  3032. }
  3033. count_ptr = lb_emit_struct_ep(p, array, 1);
  3034. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3035. break;
  3036. }
  3037. case Type_Slice: {
  3038. lbValue count_ptr = {};
  3039. lbValue slice = lb_build_expr(p, expr);
  3040. if (is_type_pointer(slice.type)) {
  3041. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3042. slice = lb_emit_load(p, slice);
  3043. } else {
  3044. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3045. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3046. }
  3047. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3048. break;
  3049. }
  3050. case Type_Basic: {
  3051. lbValue string = lb_build_expr(p, expr);
  3052. if (is_type_pointer(string.type)) {
  3053. string = lb_emit_load(p, string);
  3054. }
  3055. if (is_type_untyped(expr_type)) {
  3056. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3057. lb_addr_store(p, s, string);
  3058. string = lb_addr_load(p, s);
  3059. }
  3060. Type *t = base_type(string.type);
  3061. GB_ASSERT(!is_type_cstring(t));
  3062. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3063. break;
  3064. }
  3065. case Type_Tuple:
  3066. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3067. break;
  3068. default:
  3069. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3070. break;
  3071. }
  3072. }
  3073. if (is_map) {
  3074. if (val0_type) lb_store_range_stmt_val(p, rs->val0, key);
  3075. if (val1_type) lb_store_range_stmt_val(p, rs->val1, val);
  3076. } else {
  3077. if (val0_type) lb_store_range_stmt_val(p, rs->val0, val);
  3078. if (val1_type) lb_store_range_stmt_val(p, rs->val1, key);
  3079. }
  3080. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3081. lb_build_stmt(p, rs->body);
  3082. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3083. lb_pop_target_list(p);
  3084. lb_emit_jump(p, loop);
  3085. lb_start_block(p, done);
  3086. }
  3087. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  3088. lbModule *m = p->module;
  3089. lb_open_scope(p); // Open scope here
  3090. Type *val0_type = nullptr;
  3091. Type *val1_type = nullptr;
  3092. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3093. val0_type = type_of_expr(rs->val0);
  3094. }
  3095. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3096. val1_type = type_of_expr(rs->val1);
  3097. }
  3098. if (val0_type != nullptr) {
  3099. Entity *e = entity_of_node(rs->val0);
  3100. lb_add_local(p, e->type, e, true);
  3101. }
  3102. if (val1_type != nullptr) {
  3103. Entity *e = entity_of_node(rs->val1);
  3104. lb_add_local(p, e->type, e, true);
  3105. }
  3106. lbValue val = {};
  3107. lbValue key = {};
  3108. lbBlock *loop = nullptr;
  3109. lbBlock *done = nullptr;
  3110. Ast *expr = unparen_expr(rs->expr);
  3111. TypeAndValue tav = type_and_value_of_expr(expr);
  3112. if (is_ast_range(expr)) {
  3113. lbAddr val0_addr = {};
  3114. lbAddr val1_addr = {};
  3115. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3116. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3117. TokenKind op = expr->BinaryExpr.op.kind;
  3118. Ast *start_expr = expr->BinaryExpr.left;
  3119. Ast *end_expr = expr->BinaryExpr.right;
  3120. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3121. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3122. ExactValue start = start_expr->tav.value;
  3123. ExactValue end = end_expr->tav.value;
  3124. if (op == Token_Ellipsis) { // .. [start, end]
  3125. ExactValue index = exact_value_i64(0);
  3126. for (ExactValue val = start;
  3127. compare_exact_values(Token_LtEq, val, end);
  3128. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3129. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3130. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3131. lb_build_stmt(p, rs->body);
  3132. }
  3133. } else if (op == Token_RangeHalf) { // ..< [start, end)
  3134. ExactValue index = exact_value_i64(0);
  3135. for (ExactValue val = start;
  3136. compare_exact_values(Token_Lt, val, end);
  3137. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3138. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3139. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3140. lb_build_stmt(p, rs->body);
  3141. }
  3142. }
  3143. } else if (tav.mode == Addressing_Type) {
  3144. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3145. Type *et = type_deref(tav.type);
  3146. Type *bet = base_type(et);
  3147. lbAddr val0_addr = {};
  3148. lbAddr val1_addr = {};
  3149. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3150. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3151. for_array(i, bet->Enum.fields) {
  3152. Entity *field = bet->Enum.fields[i];
  3153. GB_ASSERT(field->kind == Entity_Constant);
  3154. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3155. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3156. lb_build_stmt(p, rs->body);
  3157. }
  3158. } else {
  3159. lbAddr val0_addr = {};
  3160. lbAddr val1_addr = {};
  3161. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3162. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3163. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3164. Type *t = base_type(expr->tav.type);
  3165. switch (t->kind) {
  3166. case Type_Basic:
  3167. GB_ASSERT(is_type_string(t));
  3168. {
  3169. ExactValue value = expr->tav.value;
  3170. GB_ASSERT(value.kind == ExactValue_String);
  3171. String str = value.value_string;
  3172. Rune codepoint = 0;
  3173. isize offset = 0;
  3174. do {
  3175. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3176. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3177. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3178. lb_build_stmt(p, rs->body);
  3179. offset += width;
  3180. } while (offset < str.len);
  3181. }
  3182. break;
  3183. case Type_Array:
  3184. if (t->Array.count > 0) {
  3185. lbValue val = lb_build_expr(p, expr);
  3186. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3187. for (i64 i = 0; i < t->Array.count; i++) {
  3188. if (val0_type) {
  3189. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3190. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3191. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3192. }
  3193. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3194. lb_build_stmt(p, rs->body);
  3195. }
  3196. }
  3197. break;
  3198. case Type_EnumeratedArray:
  3199. if (t->EnumeratedArray.count > 0) {
  3200. lbValue val = lb_build_expr(p, expr);
  3201. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3202. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3203. if (val0_type) {
  3204. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3205. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3206. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3207. }
  3208. if (val1_type) {
  3209. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3210. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3211. }
  3212. lb_build_stmt(p, rs->body);
  3213. }
  3214. }
  3215. break;
  3216. default:
  3217. GB_PANIC("Invalid inline for type");
  3218. break;
  3219. }
  3220. }
  3221. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3222. }
  3223. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  3224. if (ss->init != nullptr) {
  3225. lb_build_stmt(p, ss->init);
  3226. }
  3227. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3228. if (ss->tag != nullptr) {
  3229. tag = lb_build_expr(p, ss->tag);
  3230. }
  3231. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3232. ast_node(body, BlockStmt, ss->body);
  3233. Slice<Ast *> default_stmts = {};
  3234. lbBlock *default_fall = nullptr;
  3235. lbBlock *default_block = nullptr;
  3236. lbBlock *fall = nullptr;
  3237. isize case_count = body->stmts.count;
  3238. for_array(i, body->stmts) {
  3239. Ast *clause = body->stmts[i];
  3240. ast_node(cc, CaseClause, clause);
  3241. lbBlock *body = fall;
  3242. if (body == nullptr) {
  3243. body = lb_create_block(p, "switch.case.body");
  3244. }
  3245. fall = done;
  3246. if (i+1 < case_count) {
  3247. fall = lb_create_block(p, "switch.fall.body");
  3248. }
  3249. if (cc->list.count == 0) {
  3250. // default case
  3251. default_stmts = cc->stmts;
  3252. default_fall = fall;
  3253. default_block = body;
  3254. continue;
  3255. }
  3256. lbBlock *next_cond = nullptr;
  3257. for_array(j, cc->list) {
  3258. Ast *expr = unparen_expr(cc->list[j]);
  3259. next_cond = lb_create_block(p, "switch.case.next");
  3260. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3261. if (is_ast_range(expr)) {
  3262. ast_node(ie, BinaryExpr, expr);
  3263. TokenKind op = Token_Invalid;
  3264. switch (ie->op.kind) {
  3265. case Token_Ellipsis: op = Token_LtEq; break;
  3266. case Token_RangeHalf: op = Token_Lt; break;
  3267. default: GB_PANIC("Invalid interval operator"); break;
  3268. }
  3269. lbValue lhs = lb_build_expr(p, ie->left);
  3270. lbValue rhs = lb_build_expr(p, ie->right);
  3271. // TODO(bill): do short circuit here
  3272. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3273. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3274. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3275. } else {
  3276. if (expr->tav.mode == Addressing_Type) {
  3277. GB_ASSERT(is_type_typeid(tag.type));
  3278. lbValue e = lb_typeid(p->module, expr->tav.type);
  3279. e = lb_emit_conv(p, e, tag.type);
  3280. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3281. } else {
  3282. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3283. }
  3284. }
  3285. lb_emit_if(p, cond, body, next_cond);
  3286. lb_start_block(p, next_cond);
  3287. }
  3288. lb_start_block(p, body);
  3289. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3290. lb_open_scope(p);
  3291. lb_build_stmt_list(p, cc->stmts);
  3292. lb_close_scope(p, lbDeferExit_Default, body);
  3293. lb_pop_target_list(p);
  3294. lb_emit_jump(p, done);
  3295. lb_start_block(p, next_cond);
  3296. }
  3297. if (default_block != nullptr) {
  3298. lb_emit_jump(p, default_block);
  3299. lb_start_block(p, default_block);
  3300. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3301. lb_open_scope(p);
  3302. lb_build_stmt_list(p, default_stmts);
  3303. lb_close_scope(p, lbDeferExit_Default, default_block);
  3304. lb_pop_target_list(p);
  3305. }
  3306. lb_emit_jump(p, done);
  3307. lb_start_block(p, done);
  3308. }
  3309. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3310. Entity *e = implicit_entity_of_node(clause);
  3311. GB_ASSERT(e != nullptr);
  3312. if (e->flags & EntityFlag_Value) {
  3313. // by value
  3314. GB_ASSERT(are_types_identical(e->type, value.type));
  3315. lbAddr x = lb_add_local(p, e->type, e, false);
  3316. lb_addr_store(p, x, value);
  3317. } else {
  3318. // by reference
  3319. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3320. lb_add_entity(p->module, e, value);
  3321. }
  3322. }
  3323. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3324. Entity *e = entity_of_node(stmt_val);
  3325. if (e == nullptr) {
  3326. return {};
  3327. }
  3328. if ((e->flags & EntityFlag_Value) == 0) {
  3329. if (LLVMIsALoadInst(value.value)) {
  3330. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3331. lb_add_entity(p->module, e, ptr);
  3332. return lb_addr(ptr);
  3333. }
  3334. }
  3335. // by value
  3336. lbAddr addr = lb_add_local(p, e->type, e, false);
  3337. lb_addr_store(p, addr, value);
  3338. return addr;
  3339. }
  3340. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3341. ast_node(cc, CaseClause, clause);
  3342. lb_push_target_list(p, label, done, nullptr, nullptr);
  3343. lb_open_scope(p);
  3344. lb_build_stmt_list(p, cc->stmts);
  3345. lb_close_scope(p, lbDeferExit_Default, body);
  3346. lb_pop_target_list(p);
  3347. lb_emit_jump(p, done);
  3348. }
  3349. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3350. lbModule *m = p->module;
  3351. ast_node(as, AssignStmt, ss->tag);
  3352. GB_ASSERT(as->lhs.count == 1);
  3353. GB_ASSERT(as->rhs.count == 1);
  3354. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3355. bool is_parent_ptr = is_type_pointer(parent.type);
  3356. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3357. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3358. lbValue parent_value = parent;
  3359. lbValue parent_ptr = parent;
  3360. if (!is_parent_ptr) {
  3361. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3362. }
  3363. lbValue tag_index = {};
  3364. lbValue union_data = {};
  3365. if (switch_kind == TypeSwitch_Union) {
  3366. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3367. tag_index = lb_emit_load(p, tag_ptr);
  3368. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3369. }
  3370. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3371. lb_emit_jump(p, start_block);
  3372. lb_start_block(p, start_block);
  3373. // NOTE(bill): Append this later
  3374. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3375. Ast *default_ = nullptr;
  3376. ast_node(body, BlockStmt, ss->body);
  3377. gb_local_persist i32 weird_count = 0;
  3378. for_array(i, body->stmts) {
  3379. Ast *clause = body->stmts[i];
  3380. ast_node(cc, CaseClause, clause);
  3381. if (cc->list.count == 0) {
  3382. default_ = clause;
  3383. continue;
  3384. }
  3385. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3386. lbBlock *next = nullptr;
  3387. Type *case_type = nullptr;
  3388. for_array(type_index, cc->list) {
  3389. next = lb_create_block(p, "typeswitch.next");
  3390. case_type = type_of_expr(cc->list[type_index]);
  3391. lbValue cond = {};
  3392. if (switch_kind == TypeSwitch_Union) {
  3393. Type *ut = base_type(type_deref(parent.type));
  3394. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3395. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3396. } else if (switch_kind == TypeSwitch_Any) {
  3397. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3398. lbValue case_typeid = lb_typeid(m, case_type);
  3399. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3400. }
  3401. GB_ASSERT(cond.value != nullptr);
  3402. lb_emit_if(p, cond, body, next);
  3403. lb_start_block(p, next);
  3404. }
  3405. Entity *case_entity = implicit_entity_of_node(clause);
  3406. lbValue value = parent_value;
  3407. lb_start_block(p, body);
  3408. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3409. if (cc->list.count == 1) {
  3410. lbValue data = {};
  3411. if (switch_kind == TypeSwitch_Union) {
  3412. data = union_data;
  3413. } else if (switch_kind == TypeSwitch_Any) {
  3414. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3415. data = any_data;
  3416. }
  3417. Type *ct = case_entity->type;
  3418. Type *ct_ptr = alloc_type_pointer(ct);
  3419. value = lb_emit_conv(p, data, ct_ptr);
  3420. if (!by_reference) {
  3421. value = lb_emit_load(p, value);
  3422. }
  3423. }
  3424. lb_store_type_case_implicit(p, clause, value);
  3425. lb_type_case_body(p, ss->label, clause, body, done);
  3426. lb_start_block(p, next);
  3427. }
  3428. if (default_ != nullptr) {
  3429. lb_store_type_case_implicit(p, default_, parent_value);
  3430. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3431. } else {
  3432. lb_emit_jump(p, done);
  3433. }
  3434. lb_start_block(p, done);
  3435. }
  3436. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3437. lbModule *m = p->module;
  3438. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3439. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3440. type = default_type(type);
  3441. lbValue short_circuit = {};
  3442. if (op == Token_CmpAnd) {
  3443. lb_build_cond(p, left, rhs, done);
  3444. short_circuit = lb_const_bool(m, type, false);
  3445. } else if (op == Token_CmpOr) {
  3446. lb_build_cond(p, left, done, rhs);
  3447. short_circuit = lb_const_bool(m, type, true);
  3448. }
  3449. if (rhs->preds.count == 0) {
  3450. lb_start_block(p, done);
  3451. return short_circuit;
  3452. }
  3453. if (done->preds.count == 0) {
  3454. lb_start_block(p, rhs);
  3455. return lb_build_expr(p, right);
  3456. }
  3457. Array<LLVMValueRef> incoming_values = {};
  3458. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3459. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3460. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3461. for_array(i, done->preds) {
  3462. incoming_values[i] = short_circuit.value;
  3463. incoming_blocks[i] = done->preds[i]->block;
  3464. }
  3465. lb_start_block(p, rhs);
  3466. lbValue edge = lb_build_expr(p, right);
  3467. incoming_values[done->preds.count] = edge.value;
  3468. incoming_blocks[done->preds.count] = p->curr_block->block;
  3469. lb_emit_jump(p, done);
  3470. lb_start_block(p, done);
  3471. lbValue res = {};
  3472. res.type = type;
  3473. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3474. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3475. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3476. return res;
  3477. }
  3478. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3479. Ast *prev_stmt = p->curr_stmt;
  3480. defer (p->curr_stmt = prev_stmt);
  3481. p->curr_stmt = node;
  3482. if (p->curr_block != nullptr) {
  3483. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3484. if (lb_is_instr_terminating(last_instr)) {
  3485. return;
  3486. }
  3487. }
  3488. u64 prev_state_flags = p->module->state_flags;
  3489. defer (p->module->state_flags = prev_state_flags);
  3490. if (node->state_flags != 0) {
  3491. u64 in = node->state_flags;
  3492. u64 out = p->module->state_flags;
  3493. if (in & StateFlag_bounds_check) {
  3494. out |= StateFlag_bounds_check;
  3495. out &= ~StateFlag_no_bounds_check;
  3496. } else if (in & StateFlag_no_bounds_check) {
  3497. out |= StateFlag_no_bounds_check;
  3498. out &= ~StateFlag_bounds_check;
  3499. }
  3500. p->module->state_flags = out;
  3501. }
  3502. switch (node->kind) {
  3503. case_ast_node(bs, EmptyStmt, node);
  3504. case_end;
  3505. case_ast_node(us, UsingStmt, node);
  3506. case_end;
  3507. case_ast_node(ws, WhenStmt, node);
  3508. lb_build_when_stmt(p, ws);
  3509. case_end;
  3510. case_ast_node(bs, BlockStmt, node);
  3511. if (bs->label != nullptr) {
  3512. lbBlock *done = lb_create_block(p, "block.done");
  3513. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3514. tl->is_block = true;
  3515. lb_open_scope(p);
  3516. lb_build_stmt_list(p, bs->stmts);
  3517. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3518. lb_emit_jump(p, done);
  3519. lb_start_block(p, done);
  3520. } else {
  3521. lb_open_scope(p);
  3522. lb_build_stmt_list(p, bs->stmts);
  3523. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3524. }
  3525. case_end;
  3526. case_ast_node(vd, ValueDecl, node);
  3527. if (!vd->is_mutable) {
  3528. return;
  3529. }
  3530. bool is_static = false;
  3531. if (vd->names.count > 0) {
  3532. Entity *e = entity_of_node(vd->names[0]);
  3533. if (e->flags & EntityFlag_Static) {
  3534. // NOTE(bill): If one of the entities is static, they all are
  3535. is_static = true;
  3536. }
  3537. }
  3538. if (is_static) {
  3539. for_array(i, vd->names) {
  3540. lbValue value = {};
  3541. if (vd->values.count > 0) {
  3542. GB_ASSERT(vd->names.count == vd->values.count);
  3543. Ast *ast_value = vd->values[i];
  3544. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3545. ast_value->tav.mode == Addressing_Invalid);
  3546. bool allow_local = false;
  3547. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3548. }
  3549. Ast *ident = vd->names[i];
  3550. GB_ASSERT(!is_blank_ident(ident));
  3551. Entity *e = entity_of_node(ident);
  3552. GB_ASSERT(e->flags & EntityFlag_Static);
  3553. String name = e->token.string;
  3554. String mangled_name = {};
  3555. {
  3556. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  3557. str = gb_string_appendc(str, "-");
  3558. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3559. mangled_name.text = cast(u8 *)str;
  3560. mangled_name.len = gb_string_length(str);
  3561. }
  3562. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  3563. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3564. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3565. if (value.value != nullptr) {
  3566. LLVMSetInitializer(global, value.value);
  3567. } else {
  3568. }
  3569. if (e->Variable.thread_local_model != "") {
  3570. LLVMSetThreadLocal(global, true);
  3571. String m = e->Variable.thread_local_model;
  3572. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3573. if (m == "default") {
  3574. mode = LLVMGeneralDynamicTLSModel;
  3575. } else if (m == "localdynamic") {
  3576. mode = LLVMLocalDynamicTLSModel;
  3577. } else if (m == "initialexec") {
  3578. mode = LLVMInitialExecTLSModel;
  3579. } else if (m == "localexec") {
  3580. mode = LLVMLocalExecTLSModel;
  3581. } else {
  3582. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3583. }
  3584. LLVMSetThreadLocalMode(global, mode);
  3585. } else {
  3586. LLVMSetLinkage(global, LLVMInternalLinkage);
  3587. }
  3588. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3589. lb_add_entity(p->module, e, global_val);
  3590. lb_add_member(p->module, mangled_name, global_val);
  3591. }
  3592. return;
  3593. }
  3594. if (vd->values.count == 0) { // declared and zero-initialized
  3595. for_array(i, vd->names) {
  3596. Ast *name = vd->names[i];
  3597. if (!is_blank_ident(name)) {
  3598. Entity *e = entity_of_node(name);
  3599. lb_add_local(p, e->type, e, true);
  3600. }
  3601. }
  3602. } else { // Tuple(s)
  3603. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  3604. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  3605. for_array(i, vd->names) {
  3606. Ast *name = vd->names[i];
  3607. lbAddr lval = {};
  3608. if (!is_blank_ident(name)) {
  3609. Entity *e = entity_of_node(name);
  3610. lval = lb_add_local(p, e->type, e, false);
  3611. }
  3612. array_add(&lvals, lval);
  3613. }
  3614. for_array(i, vd->values) {
  3615. lbValue init = lb_build_expr(p, vd->values[i]);
  3616. Type *t = init.type;
  3617. if (t->kind == Type_Tuple) {
  3618. for_array(i, t->Tuple.variables) {
  3619. Entity *e = t->Tuple.variables[i];
  3620. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3621. array_add(&inits, v);
  3622. }
  3623. } else {
  3624. array_add(&inits, init);
  3625. }
  3626. }
  3627. for_array(i, inits) {
  3628. lbAddr lval = lvals[i];
  3629. lbValue init = inits[i];
  3630. lb_addr_store(p, lval, init);
  3631. }
  3632. }
  3633. case_end;
  3634. case_ast_node(as, AssignStmt, node);
  3635. if (as->op.kind == Token_Eq) {
  3636. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  3637. for_array(i, as->lhs) {
  3638. Ast *lhs = as->lhs[i];
  3639. lbAddr lval = {};
  3640. if (!is_blank_ident(lhs)) {
  3641. lval = lb_build_addr(p, lhs);
  3642. }
  3643. array_add(&lvals, lval);
  3644. }
  3645. if (as->lhs.count == as->rhs.count) {
  3646. if (as->lhs.count == 1) {
  3647. lbAddr lval = lvals[0];
  3648. Ast *rhs = as->rhs[0];
  3649. lbValue init = lb_build_expr(p, rhs);
  3650. lb_addr_store(p, lvals[0], init);
  3651. } else {
  3652. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3653. for_array(i, as->rhs) {
  3654. lbValue init = lb_build_expr(p, as->rhs[i]);
  3655. array_add(&inits, init);
  3656. }
  3657. for_array(i, inits) {
  3658. lbAddr lval = lvals[i];
  3659. lbValue init = inits[i];
  3660. lb_addr_store(p, lval, init);
  3661. }
  3662. }
  3663. } else {
  3664. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3665. for_array(i, as->rhs) {
  3666. lbValue init = lb_build_expr(p, as->rhs[i]);
  3667. Type *t = init.type;
  3668. // TODO(bill): refactor for code reuse as this is repeated a bit
  3669. if (t->kind == Type_Tuple) {
  3670. for_array(i, t->Tuple.variables) {
  3671. Entity *e = t->Tuple.variables[i];
  3672. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3673. array_add(&inits, v);
  3674. }
  3675. } else {
  3676. array_add(&inits, init);
  3677. }
  3678. }
  3679. for_array(i, inits) {
  3680. lbAddr lval = lvals[i];
  3681. lbValue init = inits[i];
  3682. lb_addr_store(p, lval, init);
  3683. }
  3684. }
  3685. } else {
  3686. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  3687. // +=, -=, etc
  3688. i32 op = cast(i32)as->op.kind;
  3689. op += Token_Add - Token_AddEq; // Convert += to +
  3690. if (op == Token_CmpAnd || op == Token_CmpOr) {
  3691. Type *type = as->lhs[0]->tav.type;
  3692. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  3693. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3694. lb_addr_store(p, lhs, new_value);
  3695. } else {
  3696. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3697. lbValue value = lb_build_expr(p, as->rhs[0]);
  3698. lbValue old_value = lb_addr_load(p, lhs);
  3699. Type *type = old_value.type;
  3700. lbValue change = lb_emit_conv(p, value, type);
  3701. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  3702. lb_addr_store(p, lhs, new_value);
  3703. }
  3704. return;
  3705. }
  3706. case_end;
  3707. case_ast_node(es, ExprStmt, node);
  3708. lb_build_expr(p, es->expr);
  3709. case_end;
  3710. case_ast_node(ds, DeferStmt, node);
  3711. isize scope_index = p->scope_index;
  3712. lb_add_defer_node(p, scope_index, ds->stmt);
  3713. case_end;
  3714. case_ast_node(rs, ReturnStmt, node);
  3715. lbValue res = {};
  3716. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  3717. isize return_count = p->type->Proc.result_count;
  3718. isize res_count = rs->results.count;
  3719. if (return_count == 0) {
  3720. // No return values
  3721. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3722. LLVMBuildRetVoid(p->builder);
  3723. return;
  3724. } else if (return_count == 1) {
  3725. Entity *e = tuple->variables[0];
  3726. if (res_count == 0) {
  3727. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3728. GB_ASSERT(found);
  3729. res = lb_emit_load(p, *found);
  3730. } else {
  3731. res = lb_build_expr(p, rs->results[0]);
  3732. res = lb_emit_conv(p, res, e->type);
  3733. }
  3734. if (p->type->Proc.has_named_results) {
  3735. // NOTE(bill): store the named values before returning
  3736. if (e->token.string != "") {
  3737. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3738. GB_ASSERT(found != nullptr);
  3739. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  3740. }
  3741. }
  3742. } else {
  3743. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  3744. if (res_count != 0) {
  3745. for (isize res_index = 0; res_index < res_count; res_index++) {
  3746. lbValue res = lb_build_expr(p, rs->results[res_index]);
  3747. Type *t = res.type;
  3748. if (t->kind == Type_Tuple) {
  3749. for_array(i, t->Tuple.variables) {
  3750. Entity *e = t->Tuple.variables[i];
  3751. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  3752. array_add(&results, v);
  3753. }
  3754. } else {
  3755. array_add(&results, res);
  3756. }
  3757. }
  3758. } else {
  3759. for (isize res_index = 0; res_index < return_count; res_index++) {
  3760. Entity *e = tuple->variables[res_index];
  3761. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3762. GB_ASSERT(found);
  3763. lbValue res = lb_emit_load(p, *found);
  3764. array_add(&results, res);
  3765. }
  3766. }
  3767. GB_ASSERT(results.count == return_count);
  3768. if (p->type->Proc.has_named_results) {
  3769. // NOTE(bill): store the named values before returning
  3770. for_array(i, p->type->Proc.results->Tuple.variables) {
  3771. Entity *e = p->type->Proc.results->Tuple.variables[i];
  3772. if (e->kind != Entity_Variable) {
  3773. continue;
  3774. }
  3775. if (e->token.string == "") {
  3776. continue;
  3777. }
  3778. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3779. GB_ASSERT(found != nullptr);
  3780. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  3781. }
  3782. }
  3783. Type *ret_type = p->type->Proc.results;
  3784. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3785. res = lb_add_local_generated(p, ret_type, false).addr;
  3786. for_array(i, results) {
  3787. Entity *e = tuple->variables[i];
  3788. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  3789. lbValue val = lb_emit_conv(p, results[i], e->type);
  3790. lb_emit_store(p, field, val);
  3791. }
  3792. res = lb_emit_load(p, res);
  3793. }
  3794. if (p->abi_function_type) {
  3795. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  3796. if (res.value != nullptr) {
  3797. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  3798. } else {
  3799. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  3800. }
  3801. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3802. LLVMBuildRetVoid(p->builder);
  3803. } else {
  3804. LLVMValueRef ret_val = res.value;
  3805. if (p->abi_function_type->ret.cast_type != nullptr) {
  3806. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  3807. }
  3808. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3809. LLVMBuildRet(p->builder, ret_val);
  3810. }
  3811. } else {
  3812. GB_ASSERT(!USE_LLVM_ABI);
  3813. if (p->type->Proc.return_by_pointer) {
  3814. if (res.value != nullptr) {
  3815. lb_addr_store(p, p->return_ptr, res);
  3816. } else {
  3817. lb_addr_store(p, p->return_ptr, lb_const_nil(p->module, p->type->Proc.abi_compat_result_type));
  3818. }
  3819. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3820. LLVMBuildRetVoid(p->builder);
  3821. } else {
  3822. GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name));
  3823. Type *abi_rt = p->type->Proc.abi_compat_result_type;
  3824. if (!are_types_identical(res.type, abi_rt)) {
  3825. res = lb_emit_transmute(p, res, abi_rt);
  3826. }
  3827. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3828. LLVMBuildRet(p->builder, res.value);
  3829. }
  3830. }
  3831. case_end;
  3832. case_ast_node(is, IfStmt, node);
  3833. lb_open_scope(p); // Scope #1
  3834. if (is->init != nullptr) {
  3835. // TODO(bill): Should this have a separate block to begin with?
  3836. #if 1
  3837. lbBlock *init = lb_create_block(p, "if.init");
  3838. lb_emit_jump(p, init);
  3839. lb_start_block(p, init);
  3840. #endif
  3841. lb_build_stmt(p, is->init);
  3842. }
  3843. lbBlock *then = lb_create_block(p, "if.then");
  3844. lbBlock *done = lb_create_block(p, "if.done");
  3845. lbBlock *else_ = done;
  3846. if (is->else_stmt != nullptr) {
  3847. else_ = lb_create_block(p, "if.else");
  3848. }
  3849. lb_build_cond(p, is->cond, then, else_);
  3850. lb_start_block(p, then);
  3851. if (is->label != nullptr) {
  3852. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  3853. tl->is_block = true;
  3854. }
  3855. lb_build_stmt(p, is->body);
  3856. lb_emit_jump(p, done);
  3857. if (is->else_stmt != nullptr) {
  3858. lb_start_block(p, else_);
  3859. lb_open_scope(p);
  3860. lb_build_stmt(p, is->else_stmt);
  3861. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3862. lb_emit_jump(p, done);
  3863. }
  3864. lb_start_block(p, done);
  3865. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3866. case_end;
  3867. case_ast_node(fs, ForStmt, node);
  3868. lb_open_scope(p); // Open Scope here
  3869. if (fs->init != nullptr) {
  3870. #if 1
  3871. lbBlock *init = lb_create_block(p, "for.init");
  3872. lb_emit_jump(p, init);
  3873. lb_start_block(p, init);
  3874. #endif
  3875. lb_build_stmt(p, fs->init);
  3876. }
  3877. lbBlock *body = lb_create_block(p, "for.body");
  3878. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  3879. lbBlock *loop = body;
  3880. if (fs->cond != nullptr) {
  3881. loop = lb_create_block(p, "for.loop");
  3882. }
  3883. lbBlock *post = loop;
  3884. if (fs->post != nullptr) {
  3885. post = lb_create_block(p, "for.post");
  3886. }
  3887. lb_emit_jump(p, loop);
  3888. lb_start_block(p, loop);
  3889. if (loop != body) {
  3890. lb_build_cond(p, fs->cond, body, done);
  3891. lb_start_block(p, body);
  3892. }
  3893. lb_push_target_list(p, fs->label, done, post, nullptr);
  3894. lb_build_stmt(p, fs->body);
  3895. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3896. lb_pop_target_list(p);
  3897. lb_emit_jump(p, post);
  3898. if (fs->post != nullptr) {
  3899. lb_start_block(p, post);
  3900. lb_build_stmt(p, fs->post);
  3901. lb_emit_jump(p, loop);
  3902. }
  3903. lb_start_block(p, done);
  3904. case_end;
  3905. case_ast_node(rs, RangeStmt, node);
  3906. lb_build_range_stmt(p, rs);
  3907. case_end;
  3908. case_ast_node(rs, InlineRangeStmt, node);
  3909. lb_build_inline_range_stmt(p, rs);
  3910. case_end;
  3911. case_ast_node(ss, SwitchStmt, node);
  3912. lb_build_switch_stmt(p, ss);
  3913. case_end;
  3914. case_ast_node(ss, TypeSwitchStmt, node);
  3915. lb_build_type_switch_stmt(p, ss);
  3916. case_end;
  3917. case_ast_node(bs, BranchStmt, node);
  3918. lbBlock *block = nullptr;
  3919. if (bs->label != nullptr) {
  3920. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  3921. switch (bs->token.kind) {
  3922. case Token_break: block = bb.break_; break;
  3923. case Token_continue: block = bb.continue_; break;
  3924. case Token_fallthrough:
  3925. GB_PANIC("fallthrough cannot have a label");
  3926. break;
  3927. }
  3928. } else {
  3929. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  3930. if (t->is_block) {
  3931. continue;
  3932. }
  3933. switch (bs->token.kind) {
  3934. case Token_break: block = t->break_; break;
  3935. case Token_continue: block = t->continue_; break;
  3936. case Token_fallthrough: block = t->fallthrough_; break;
  3937. }
  3938. }
  3939. }
  3940. if (block != nullptr) {
  3941. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  3942. }
  3943. lb_emit_jump(p, block);
  3944. case_end;
  3945. }
  3946. }
  3947. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  3948. cond = lb_emit_conv(p, cond, t_llvm_bool);
  3949. lbValue res = {};
  3950. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  3951. res.type = x.type;
  3952. return res;
  3953. }
  3954. lbValue lb_const_nil(lbModule *m, Type *type) {
  3955. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  3956. return lbValue{v, type};
  3957. }
  3958. lbValue lb_const_undef(lbModule *m, Type *type) {
  3959. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  3960. return lbValue{v, type};
  3961. }
  3962. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  3963. lbValue res = {};
  3964. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  3965. res.type = type;
  3966. return res;
  3967. }
  3968. lbValue lb_const_string(lbModule *m, String const &value) {
  3969. return lb_const_value(m, t_string, exact_value_string(value));
  3970. }
  3971. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  3972. lbValue res = {};
  3973. res.value = LLVMConstInt(lb_type(m, type), value, false);
  3974. res.type = type;
  3975. return res;
  3976. }
  3977. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  3978. GB_ASSERT(type_size_of(type) == 4);
  3979. u32 u = bit_cast<u32>(f);
  3980. if (is_type_different_to_arch_endianness(type)) {
  3981. u = gb_endian_swap32(u);
  3982. }
  3983. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  3984. return LLVMConstBitCast(i, lb_type(m, type));
  3985. }
  3986. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3987. x = lb_emit_conv(p, x, t);
  3988. y = lb_emit_conv(p, y, t);
  3989. if (is_type_float(t)) {
  3990. i64 sz = 8*type_size_of(t);
  3991. auto args = array_make<lbValue>(permanent_allocator(), 2);
  3992. args[0] = x;
  3993. args[1] = y;
  3994. switch (sz) {
  3995. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  3996. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  3997. }
  3998. GB_PANIC("Unknown float type");
  3999. }
  4000. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4001. }
  4002. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4003. x = lb_emit_conv(p, x, t);
  4004. y = lb_emit_conv(p, y, t);
  4005. if (is_type_float(t)) {
  4006. i64 sz = 8*type_size_of(t);
  4007. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4008. args[0] = x;
  4009. args[1] = y;
  4010. switch (sz) {
  4011. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4012. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4013. }
  4014. GB_PANIC("Unknown float type");
  4015. }
  4016. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4017. }
  4018. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4019. lbValue z = {};
  4020. z = lb_emit_max(p, t, x, min);
  4021. z = lb_emit_min(p, t, z, max);
  4022. return z;
  4023. }
  4024. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4025. StringHashKey key = string_hash_string(str);
  4026. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4027. if (found != nullptr) {
  4028. return *found;
  4029. } else {
  4030. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4031. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4032. cast(char const *)str.text,
  4033. cast(unsigned)str.len,
  4034. false);
  4035. isize max_len = 7+8+1;
  4036. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4037. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4038. len -= 1;
  4039. m->global_array_index++;
  4040. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4041. LLVMSetInitializer(global_data, data);
  4042. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4043. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4044. string_map_set(&m->const_strings, key, ptr);
  4045. return ptr;
  4046. }
  4047. }
  4048. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4049. LLVMValueRef ptr = nullptr;
  4050. if (str.len != 0) {
  4051. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4052. } else {
  4053. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4054. }
  4055. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4056. LLVMValueRef values[2] = {ptr, str_len};
  4057. lbValue res = {};
  4058. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  4059. res.type = t_string;
  4060. return res;
  4061. }
  4062. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4063. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4064. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4065. cast(char const *)str.text,
  4066. cast(unsigned)str.len,
  4067. false);
  4068. char *name = nullptr;
  4069. {
  4070. isize max_len = 7+8+1;
  4071. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4072. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4073. len -= 1;
  4074. m->global_array_index++;
  4075. }
  4076. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4077. LLVMSetInitializer(global_data, data);
  4078. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4079. LLVMValueRef ptr = nullptr;
  4080. if (str.len != 0) {
  4081. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4082. } else {
  4083. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4084. }
  4085. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4086. LLVMValueRef values[2] = {ptr, len};
  4087. lbValue res = {};
  4088. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  4089. res.type = t_u8_slice;
  4090. return res;
  4091. }
  4092. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4093. isize index = type_info_index(info, type, false);
  4094. if (index >= 0) {
  4095. auto *set = &info->minimum_dependency_type_info_set;
  4096. for_array(i, set->entries) {
  4097. if (set->entries[i].ptr == index) {
  4098. return i+1;
  4099. }
  4100. }
  4101. }
  4102. if (err_on_not_found) {
  4103. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4104. }
  4105. return -1;
  4106. }
  4107. lbValue lb_typeid(lbModule *m, Type *type) {
  4108. type = default_type(type);
  4109. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4110. GB_ASSERT(id >= 0);
  4111. u64 kind = Typeid_Invalid;
  4112. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4113. u64 special = 0;
  4114. u64 reserved = 0;
  4115. Type *bt = base_type(type);
  4116. TypeKind tk = bt->kind;
  4117. switch (tk) {
  4118. case Type_Basic: {
  4119. u32 flags = bt->Basic.flags;
  4120. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4121. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4122. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4123. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4124. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4125. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4126. if (flags & BasicFlag_String) kind = Typeid_String;
  4127. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4128. } break;
  4129. case Type_Pointer: kind = Typeid_Pointer; break;
  4130. case Type_Array: kind = Typeid_Array; break;
  4131. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4132. case Type_Slice: kind = Typeid_Slice; break;
  4133. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4134. case Type_Map: kind = Typeid_Map; break;
  4135. case Type_Struct: kind = Typeid_Struct; break;
  4136. case Type_Enum: kind = Typeid_Enum; break;
  4137. case Type_Union: kind = Typeid_Union; break;
  4138. case Type_Tuple: kind = Typeid_Tuple; break;
  4139. case Type_Proc: kind = Typeid_Procedure; break;
  4140. case Type_BitField: kind = Typeid_Bit_Field; break;
  4141. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4142. case Type_Opaque: kind = Typeid_Opaque; break;
  4143. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4144. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4145. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4146. }
  4147. if (is_type_cstring(type)) {
  4148. special = 1;
  4149. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4150. special = 1;
  4151. }
  4152. u64 data = 0;
  4153. if (build_context.word_size == 4) {
  4154. GB_ASSERT(id <= (1u<<24u));
  4155. data |= (id &~ (1u<<24)) << 0u; // index
  4156. data |= (kind &~ (1u<<5)) << 24u; // kind
  4157. data |= (named &~ (1u<<1)) << 29u; // kind
  4158. data |= (special &~ (1u<<1)) << 30u; // kind
  4159. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4160. } else {
  4161. GB_ASSERT(build_context.word_size == 8);
  4162. GB_ASSERT(id <= (1ull<<56u));
  4163. data |= (id &~ (1ull<<56)) << 0ul; // index
  4164. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4165. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4166. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4167. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4168. }
  4169. lbValue res = {};
  4170. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4171. res.type = t_typeid;
  4172. return res;
  4173. }
  4174. lbValue lb_type_info(lbModule *m, Type *type) {
  4175. type = default_type(type);
  4176. isize index = lb_type_info_index(m->info, type);
  4177. GB_ASSERT(index >= 0);
  4178. LLVMTypeRef it = lb_type(m, t_int);
  4179. LLVMValueRef indices[2] = {
  4180. LLVMConstInt(it, 0, false),
  4181. LLVMConstInt(it, index, true),
  4182. };
  4183. lbValue value = {};
  4184. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  4185. value.type = t_type_info_ptr;
  4186. return value;
  4187. }
  4188. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4189. LLVMContextRef ctx = m->ctx;
  4190. type = default_type(type);
  4191. Type *original_type = type;
  4192. lbValue res = {};
  4193. res.type = original_type;
  4194. type = core_type(type);
  4195. value = convert_exact_value_for_type(value, type);
  4196. if (value.kind == ExactValue_Typeid) {
  4197. return lb_typeid(m, value.value_typeid);
  4198. }
  4199. if (value.kind == ExactValue_Invalid) {
  4200. return lb_const_nil(m, type);
  4201. }
  4202. if (value.kind == ExactValue_Procedure) {
  4203. Ast *expr = unparen_expr(value.value_procedure);
  4204. if (expr->kind == Ast_ProcLit) {
  4205. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4206. }
  4207. Entity *e = entity_from_expr(expr);
  4208. e = strip_entity_wrapping(e);
  4209. GB_ASSERT(e != nullptr);
  4210. auto *found = map_get(&m->values, hash_entity(e));
  4211. if (found) {
  4212. return *found;
  4213. }
  4214. GB_PANIC("Error in: %.*s(%td:%td), missing procedure %.*s\n", LIT(e->token.pos.file), e->token.pos.line, e->token.pos.column, LIT(e->token.string));
  4215. }
  4216. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4217. if (is_type_slice(type)) {
  4218. if (value.kind == ExactValue_String) {
  4219. GB_ASSERT(is_type_u8_slice(type));
  4220. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4221. return res;
  4222. } else {
  4223. ast_node(cl, CompoundLit, value.value_compound);
  4224. isize count = cl->elems.count;
  4225. if (count == 0) {
  4226. return lb_const_nil(m, type);
  4227. }
  4228. count = gb_max(cl->max_count, count);
  4229. Type *elem = base_type(type)->Slice.elem;
  4230. Type *t = alloc_type_array(elem, count);
  4231. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4232. LLVMValueRef array_data = nullptr;
  4233. if (allow_local && m->curr_procedure != nullptr) {
  4234. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4235. // its backing data on the stack
  4236. lbProcedure *p = m->curr_procedure;
  4237. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4238. LLVMTypeRef llvm_type = lb_type(m, t);
  4239. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4240. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4241. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4242. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4243. {
  4244. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4245. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4246. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4247. lbAddr slice = lb_add_local_generated(p, type, false);
  4248. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4249. return lb_addr_load(p, slice);
  4250. }
  4251. } else {
  4252. isize max_len = 7+8+1;
  4253. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4254. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4255. m->global_array_index++;
  4256. String name = make_string(cast(u8 *)str, len-1);
  4257. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4258. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4259. LLVMSetInitializer(array_data, backing_array.value);
  4260. lbValue g = {};
  4261. g.value = array_data;
  4262. g.type = t;
  4263. lb_add_entity(m, e, g);
  4264. lb_add_member(m, name, g);
  4265. {
  4266. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4267. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4268. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4269. LLVMValueRef values[2] = {ptr, len};
  4270. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4271. return res;
  4272. }
  4273. }
  4274. }
  4275. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4276. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4277. cast(char const *)value.value_string.text,
  4278. cast(unsigned)value.value_string.len,
  4279. false);
  4280. res.value = data;
  4281. return res;
  4282. } else if (is_type_array(type) &&
  4283. value.kind != ExactValue_Invalid &&
  4284. value.kind != ExactValue_String &&
  4285. value.kind != ExactValue_Compound) {
  4286. i64 count = type->Array.count;
  4287. Type *elem = type->Array.elem;
  4288. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4289. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4290. for (i64 i = 0; i < count; i++) {
  4291. elems[i] = single_elem.value;
  4292. }
  4293. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  4294. return res;
  4295. }
  4296. switch (value.kind) {
  4297. case ExactValue_Invalid:
  4298. res.value = LLVMConstNull(lb_type(m, original_type));
  4299. return res;
  4300. case ExactValue_Bool:
  4301. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4302. return res;
  4303. case ExactValue_String:
  4304. {
  4305. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4306. lbValue res = {};
  4307. res.type = default_type(original_type);
  4308. if (is_type_cstring(res.type)) {
  4309. res.value = ptr;
  4310. } else {
  4311. if (value.value_string.len == 0) {
  4312. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4313. }
  4314. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4315. LLVMValueRef values[2] = {ptr, str_len};
  4316. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4317. }
  4318. return res;
  4319. }
  4320. case ExactValue_Integer:
  4321. if (is_type_pointer(type)) {
  4322. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4323. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4324. } else {
  4325. unsigned len = cast(unsigned)value.value_integer.len;
  4326. if (len == 0) {
  4327. u64 word = 0;
  4328. res.value = LLVMConstNull(lb_type(m, original_type));
  4329. } else {
  4330. u64 *words = big_int_ptr(&value.value_integer);
  4331. if (is_type_different_to_arch_endianness(type)) {
  4332. // NOTE(bill): Swap byte order for different endianness
  4333. i64 sz = type_size_of(type);
  4334. isize byte_len = gb_size_of(u64)*len;
  4335. u8 *old_bytes = cast(u8 *)words;
  4336. // TODO(bill): Use a different allocator here for a temporary allocation
  4337. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4338. for (i64 i = 0; i < sz; i++) {
  4339. new_bytes[i] = old_bytes[sz-1-i];
  4340. }
  4341. words = cast(u64 *)new_bytes;
  4342. }
  4343. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4344. if (value.value_integer.neg) {
  4345. res.value = LLVMConstNeg(res.value);
  4346. }
  4347. }
  4348. }
  4349. return res;
  4350. case ExactValue_Float:
  4351. if (type_size_of(type) == 4) {
  4352. f32 f = cast(f32)value.value_float;
  4353. res.value = lb_const_f32(m, f, type);
  4354. return res;
  4355. }
  4356. if (is_type_different_to_arch_endianness(type)) {
  4357. u64 u = bit_cast<u64>(value.value_float);
  4358. u = gb_endian_swap64(u);
  4359. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4360. } else {
  4361. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4362. }
  4363. return res;
  4364. case ExactValue_Complex:
  4365. {
  4366. LLVMValueRef values[2] = {};
  4367. switch (8*type_size_of(type)) {
  4368. case 64:
  4369. values[0] = lb_const_f32(m, cast(f32)value.value_complex.real);
  4370. values[1] = lb_const_f32(m, cast(f32)value.value_complex.imag);
  4371. break;
  4372. case 128:
  4373. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real);
  4374. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.imag);
  4375. break;
  4376. }
  4377. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4378. return res;
  4379. }
  4380. break;
  4381. case ExactValue_Quaternion:
  4382. {
  4383. LLVMValueRef values[4] = {};
  4384. switch (8*type_size_of(type)) {
  4385. case 128:
  4386. // @QuaternionLayout
  4387. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion.real);
  4388. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion.imag);
  4389. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion.jmag);
  4390. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion.kmag);
  4391. break;
  4392. case 256:
  4393. // @QuaternionLayout
  4394. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.real);
  4395. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.imag);
  4396. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.jmag);
  4397. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.kmag);
  4398. break;
  4399. }
  4400. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  4401. return res;
  4402. }
  4403. break;
  4404. case ExactValue_Pointer:
  4405. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4406. return res;
  4407. case ExactValue_Compound:
  4408. if (is_type_slice(type)) {
  4409. return lb_const_value(m, type, value, allow_local);
  4410. } else if (is_type_array(type)) {
  4411. ast_node(cl, CompoundLit, value.value_compound);
  4412. Type *elem_type = type->Array.elem;
  4413. isize elem_count = cl->elems.count;
  4414. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4415. return lb_const_nil(m, original_type);
  4416. }
  4417. if (cl->elems[0]->kind == Ast_FieldValue) {
  4418. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4419. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4420. isize value_index = 0;
  4421. for (i64 i = 0; i < type->Array.count; i++) {
  4422. bool found = false;
  4423. for (isize j = 0; j < elem_count; j++) {
  4424. Ast *elem = cl->elems[j];
  4425. ast_node(fv, FieldValue, elem);
  4426. if (is_ast_range(fv->field)) {
  4427. ast_node(ie, BinaryExpr, fv->field);
  4428. TypeAndValue lo_tav = ie->left->tav;
  4429. TypeAndValue hi_tav = ie->right->tav;
  4430. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4431. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4432. TokenKind op = ie->op.kind;
  4433. i64 lo = exact_value_to_i64(lo_tav.value);
  4434. i64 hi = exact_value_to_i64(hi_tav.value);
  4435. if (op == Token_Ellipsis) {
  4436. hi += 1;
  4437. }
  4438. if (lo == i) {
  4439. TypeAndValue tav = fv->value->tav;
  4440. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4441. for (i64 k = lo; k < hi; k++) {
  4442. values[value_index++] = val;
  4443. }
  4444. found = true;
  4445. i += (hi-lo-1);
  4446. break;
  4447. }
  4448. } else {
  4449. TypeAndValue index_tav = fv->field->tav;
  4450. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4451. i64 index = exact_value_to_i64(index_tav.value);
  4452. if (index == i) {
  4453. TypeAndValue tav = fv->value->tav;
  4454. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4455. values[value_index++] = val;
  4456. found = true;
  4457. break;
  4458. }
  4459. }
  4460. }
  4461. if (!found) {
  4462. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4463. }
  4464. }
  4465. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  4466. return res;
  4467. } else {
  4468. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4469. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4470. for (isize i = 0; i < elem_count; i++) {
  4471. TypeAndValue tav = cl->elems[i]->tav;
  4472. GB_ASSERT(tav.mode != Addressing_Invalid);
  4473. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4474. }
  4475. for (isize i = elem_count; i < type->Array.count; i++) {
  4476. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4477. }
  4478. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  4479. return res;
  4480. }
  4481. } else if (is_type_enumerated_array(type)) {
  4482. ast_node(cl, CompoundLit, value.value_compound);
  4483. Type *elem_type = type->EnumeratedArray.elem;
  4484. isize elem_count = cl->elems.count;
  4485. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4486. return lb_const_nil(m, original_type);
  4487. }
  4488. if (cl->elems[0]->kind == Ast_FieldValue) {
  4489. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4490. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4491. isize value_index = 0;
  4492. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4493. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4494. for (i64 i = total_lo; i <= total_hi; i++) {
  4495. bool found = false;
  4496. for (isize j = 0; j < elem_count; j++) {
  4497. Ast *elem = cl->elems[j];
  4498. ast_node(fv, FieldValue, elem);
  4499. if (is_ast_range(fv->field)) {
  4500. ast_node(ie, BinaryExpr, fv->field);
  4501. TypeAndValue lo_tav = ie->left->tav;
  4502. TypeAndValue hi_tav = ie->right->tav;
  4503. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4504. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4505. TokenKind op = ie->op.kind;
  4506. i64 lo = exact_value_to_i64(lo_tav.value);
  4507. i64 hi = exact_value_to_i64(hi_tav.value);
  4508. if (op == Token_Ellipsis) {
  4509. hi += 1;
  4510. }
  4511. if (lo == i) {
  4512. TypeAndValue tav = fv->value->tav;
  4513. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4514. for (i64 k = lo; k < hi; k++) {
  4515. values[value_index++] = val;
  4516. }
  4517. found = true;
  4518. i += (hi-lo-1);
  4519. break;
  4520. }
  4521. } else {
  4522. TypeAndValue index_tav = fv->field->tav;
  4523. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4524. i64 index = exact_value_to_i64(index_tav.value);
  4525. if (index == i) {
  4526. TypeAndValue tav = fv->value->tav;
  4527. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4528. values[value_index++] = val;
  4529. found = true;
  4530. break;
  4531. }
  4532. }
  4533. }
  4534. if (!found) {
  4535. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4536. }
  4537. }
  4538. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  4539. return res;
  4540. } else {
  4541. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4542. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4543. for (isize i = 0; i < elem_count; i++) {
  4544. TypeAndValue tav = cl->elems[i]->tav;
  4545. GB_ASSERT(tav.mode != Addressing_Invalid);
  4546. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4547. }
  4548. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4549. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4550. }
  4551. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  4552. return res;
  4553. }
  4554. } else if (is_type_simd_vector(type)) {
  4555. ast_node(cl, CompoundLit, value.value_compound);
  4556. Type *elem_type = type->SimdVector.elem;
  4557. isize elem_count = cl->elems.count;
  4558. if (elem_count == 0) {
  4559. return lb_const_nil(m, original_type);
  4560. }
  4561. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4562. isize total_elem_count = type->SimdVector.count;
  4563. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  4564. for (isize i = 0; i < elem_count; i++) {
  4565. TypeAndValue tav = cl->elems[i]->tav;
  4566. GB_ASSERT(tav.mode != Addressing_Invalid);
  4567. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4568. }
  4569. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  4570. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4571. }
  4572. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  4573. return res;
  4574. } else if (is_type_struct(type)) {
  4575. ast_node(cl, CompoundLit, value.value_compound);
  4576. if (cl->elems.count == 0) {
  4577. return lb_const_nil(m, original_type);
  4578. }
  4579. isize offset = 0;
  4580. if (type->Struct.custom_align > 0) {
  4581. offset = 1;
  4582. }
  4583. isize value_count = type->Struct.fields.count + offset;
  4584. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  4585. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  4586. if (cl->elems.count > 0) {
  4587. if (cl->elems[0]->kind == Ast_FieldValue) {
  4588. isize elem_count = cl->elems.count;
  4589. for (isize i = 0; i < elem_count; i++) {
  4590. ast_node(fv, FieldValue, cl->elems[i]);
  4591. String name = fv->field->Ident.token.string;
  4592. TypeAndValue tav = fv->value->tav;
  4593. GB_ASSERT(tav.mode != Addressing_Invalid);
  4594. Selection sel = lookup_field(type, name, false);
  4595. Entity *f = type->Struct.fields[sel.index[0]];
  4596. if (elem_type_can_be_constant(f->type)) {
  4597. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  4598. visited[offset+f->Variable.field_index] = true;
  4599. }
  4600. }
  4601. } else {
  4602. for_array(i, cl->elems) {
  4603. Entity *f = type->Struct.fields[i];
  4604. TypeAndValue tav = cl->elems[i]->tav;
  4605. ExactValue val = {};
  4606. if (tav.mode != Addressing_Invalid) {
  4607. val = tav.value;
  4608. }
  4609. if (elem_type_can_be_constant(f->type)) {
  4610. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  4611. visited[offset+f->Variable.field_index] = true;
  4612. }
  4613. }
  4614. }
  4615. }
  4616. for (isize i = 0; i < type->Struct.fields.count; i++) {
  4617. if (!visited[offset+i]) {
  4618. GB_ASSERT(values[offset+i] == nullptr);
  4619. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  4620. }
  4621. }
  4622. if (type->Struct.custom_align > 0) {
  4623. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  4624. }
  4625. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  4626. return res;
  4627. } else if (is_type_bit_set(type)) {
  4628. ast_node(cl, CompoundLit, value.value_compound);
  4629. if (cl->elems.count == 0) {
  4630. return lb_const_nil(m, original_type);
  4631. }
  4632. i64 sz = type_size_of(type);
  4633. if (sz == 0) {
  4634. return lb_const_nil(m, original_type);
  4635. }
  4636. u64 bits = 0;
  4637. for_array(i, cl->elems) {
  4638. Ast *e = cl->elems[i];
  4639. GB_ASSERT(e->kind != Ast_FieldValue);
  4640. TypeAndValue tav = e->tav;
  4641. if (tav.mode != Addressing_Constant) {
  4642. continue;
  4643. }
  4644. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  4645. i64 v = big_int_to_i64(&tav.value.value_integer);
  4646. i64 lower = type->BitSet.lower;
  4647. bits |= 1ull<<cast(u64)(v-lower);
  4648. }
  4649. if (is_type_different_to_arch_endianness(type)) {
  4650. i64 size = type_size_of(type);
  4651. switch (size) {
  4652. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  4653. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  4654. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  4655. }
  4656. }
  4657. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  4658. return res;
  4659. } else {
  4660. return lb_const_nil(m, original_type);
  4661. }
  4662. break;
  4663. case ExactValue_Procedure:
  4664. {
  4665. Ast *expr = value.value_procedure;
  4666. GB_ASSERT(expr != nullptr);
  4667. if (expr->kind == Ast_ProcLit) {
  4668. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4669. }
  4670. }
  4671. break;
  4672. case ExactValue_Typeid:
  4673. return lb_typeid(m, value.value_typeid);
  4674. }
  4675. return lb_const_nil(m, original_type);
  4676. }
  4677. u64 lb_generate_source_code_location_hash(TokenPos const &pos) {
  4678. u64 h = 0xcbf29ce484222325;
  4679. for (isize i = 0; i < pos.file.len; i++) {
  4680. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  4681. }
  4682. h = h ^ (u64(pos.line) * 0x100000001b3);
  4683. h = h ^ (u64(pos.column) * 0x100000001b3);
  4684. return h;
  4685. }
  4686. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  4687. lbModule *m = p->module;
  4688. LLVMValueRef fields[5] = {};
  4689. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  4690. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  4691. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  4692. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  4693. fields[4]/*hash*/ = lb_const_int(m, t_u64, lb_generate_source_code_location_hash(pos)).value;
  4694. lbValue res = {};
  4695. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, 5);
  4696. res.type = t_source_code_location;
  4697. return res;
  4698. }
  4699. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  4700. String proc_name = {};
  4701. if (p->entity) {
  4702. proc_name = p->entity->token.string;
  4703. }
  4704. TokenPos pos = {};
  4705. if (node) {
  4706. pos = ast_token(node).pos;
  4707. }
  4708. return lb_emit_source_code_location(p, proc_name, pos);
  4709. }
  4710. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  4711. switch (op) {
  4712. case Token_Add:
  4713. return x;
  4714. case Token_Not: // Boolean not
  4715. case Token_Xor: // Bitwise not
  4716. case Token_Sub: // Number negation
  4717. break;
  4718. case Token_Pointer:
  4719. GB_PANIC("This should be handled elsewhere");
  4720. break;
  4721. }
  4722. if (is_type_array(x.type)) {
  4723. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  4724. Type *tl = base_type(x.type);
  4725. lbValue val = lb_address_from_load_or_generate_local(p, x);
  4726. GB_ASSERT(is_type_array(type));
  4727. Type *elem_type = base_array_type(type);
  4728. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4729. lbAddr res_addr = lb_add_local_generated(p, type, false);
  4730. lbValue res = lb_addr_get_ptr(p, res_addr);
  4731. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4732. i32 count = cast(i32)tl->Array.count;
  4733. if (inline_array_arith) {
  4734. // inline
  4735. for (i32 i = 0; i < count; i++) {
  4736. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  4737. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4738. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  4739. }
  4740. } else {
  4741. auto loop_data = lb_loop_start(p, count, t_i32);
  4742. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  4743. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4744. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  4745. lb_loop_end(p, loop_data);
  4746. }
  4747. return lb_emit_load(p, res);
  4748. }
  4749. if (op == Token_Xor) {
  4750. lbValue cmp = {};
  4751. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  4752. cmp.type = x.type;
  4753. return lb_emit_conv(p, cmp, type);
  4754. }
  4755. if (op == Token_Not) {
  4756. lbValue cmp = {};
  4757. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  4758. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  4759. cmp.type = t_llvm_bool;
  4760. return lb_emit_conv(p, cmp, type);
  4761. }
  4762. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4763. Type *platform_type = integer_endian_type_to_platform_type(type);
  4764. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4765. lbValue res = {};
  4766. res.value = LLVMBuildNeg(p->builder, v.value, "");
  4767. res.type = platform_type;
  4768. return lb_emit_byte_swap(p, res, type);
  4769. }
  4770. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4771. Type *platform_type = integer_endian_type_to_platform_type(type);
  4772. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4773. lbValue res = {};
  4774. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  4775. res.type = platform_type;
  4776. return lb_emit_byte_swap(p, res, type);
  4777. }
  4778. lbValue res = {};
  4779. switch (op) {
  4780. case Token_Not: // Boolean not
  4781. case Token_Xor: // Bitwise not
  4782. res.value = LLVMBuildNot(p->builder, x.value, "");
  4783. res.type = x.type;
  4784. return res;
  4785. case Token_Sub: // Number negation
  4786. if (is_type_integer(x.type)) {
  4787. res.value = LLVMBuildNeg(p->builder, x.value, "");
  4788. } else if (is_type_float(x.type)) {
  4789. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  4790. } else if (is_type_complex(x.type)) {
  4791. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4792. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4793. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4794. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4795. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4796. return lb_addr_load(p, addr);
  4797. } else if (is_type_quaternion(x.type)) {
  4798. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4799. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4800. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  4801. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  4802. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4803. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4804. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4805. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  4806. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  4807. return lb_addr_load(p, addr);
  4808. } else {
  4809. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  4810. }
  4811. res.type = x.type;
  4812. return res;
  4813. }
  4814. return res;
  4815. }
  4816. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  4817. lbModule *m = p->module;
  4818. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  4819. lhs = lb_emit_conv(p, lhs, type);
  4820. rhs = lb_emit_conv(p, rhs, type);
  4821. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  4822. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4823. GB_ASSERT(is_type_array(type));
  4824. Type *elem_type = base_array_type(type);
  4825. lbAddr res = lb_add_local_generated(p, type, false);
  4826. i64 count = base_type(type)->Array.count;
  4827. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4828. if (inline_array_arith) {
  4829. for (i64 i = 0; i < count; i++) {
  4830. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  4831. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  4832. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  4833. lbValue a = lb_emit_load(p, a_ptr);
  4834. lbValue b = lb_emit_load(p, b_ptr);
  4835. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4836. lb_emit_store(p, dst_ptr, c);
  4837. }
  4838. } else {
  4839. auto loop_data = lb_loop_start(p, count, t_i32);
  4840. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  4841. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  4842. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  4843. lbValue a = lb_emit_load(p, a_ptr);
  4844. lbValue b = lb_emit_load(p, b_ptr);
  4845. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4846. lb_emit_store(p, dst_ptr, c);
  4847. lb_loop_end(p, loop_data);
  4848. }
  4849. return lb_addr_load(p, res);
  4850. } else if (is_type_complex(type)) {
  4851. lhs = lb_emit_conv(p, lhs, type);
  4852. rhs = lb_emit_conv(p, rhs, type);
  4853. Type *ft = base_complex_elem_type(type);
  4854. if (op == Token_Quo) {
  4855. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4856. args[0] = lhs;
  4857. args[1] = rhs;
  4858. switch (type_size_of(ft)) {
  4859. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  4860. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  4861. default: GB_PANIC("Unknown float type"); break;
  4862. }
  4863. }
  4864. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4865. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  4866. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  4867. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  4868. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  4869. lbValue real = {};
  4870. lbValue imag = {};
  4871. switch (op) {
  4872. case Token_Add:
  4873. real = lb_emit_arith(p, Token_Add, a, c, ft);
  4874. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  4875. break;
  4876. case Token_Sub:
  4877. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  4878. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  4879. break;
  4880. case Token_Mul: {
  4881. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  4882. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  4883. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  4884. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  4885. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  4886. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  4887. break;
  4888. }
  4889. }
  4890. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  4891. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  4892. return lb_addr_load(p, res);
  4893. } else if (is_type_quaternion(type)) {
  4894. lhs = lb_emit_conv(p, lhs, type);
  4895. rhs = lb_emit_conv(p, rhs, type);
  4896. Type *ft = base_complex_elem_type(type);
  4897. if (op == Token_Add || op == Token_Sub) {
  4898. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4899. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  4900. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  4901. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  4902. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  4903. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  4904. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  4905. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  4906. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  4907. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  4908. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  4909. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  4910. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  4911. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  4912. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  4913. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  4914. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  4915. return lb_addr_load(p, res);
  4916. } else if (op == Token_Mul) {
  4917. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4918. args[0] = lhs;
  4919. args[1] = rhs;
  4920. switch (8*type_size_of(ft)) {
  4921. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  4922. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  4923. default: GB_PANIC("Unknown float type"); break;
  4924. }
  4925. } else if (op == Token_Quo) {
  4926. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4927. args[0] = lhs;
  4928. args[1] = rhs;
  4929. switch (8*type_size_of(ft)) {
  4930. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  4931. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  4932. default: GB_PANIC("Unknown float type"); break;
  4933. }
  4934. }
  4935. }
  4936. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4937. switch (op) {
  4938. case Token_AndNot:
  4939. case Token_And:
  4940. case Token_Or:
  4941. case Token_Xor:
  4942. goto handle_op;
  4943. }
  4944. Type *platform_type = integer_endian_type_to_platform_type(type);
  4945. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4946. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4947. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4948. return lb_emit_byte_swap(p, res, type);
  4949. }
  4950. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4951. Type *platform_type = integer_endian_type_to_platform_type(type);
  4952. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4953. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4954. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4955. return lb_emit_byte_swap(p, res, type);
  4956. }
  4957. handle_op:
  4958. lhs = lb_emit_conv(p, lhs, type);
  4959. rhs = lb_emit_conv(p, rhs, type);
  4960. lbValue res = {};
  4961. res.type = type;
  4962. switch (op) {
  4963. case Token_Add:
  4964. if (is_type_float(type)) {
  4965. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  4966. return res;
  4967. }
  4968. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  4969. return res;
  4970. case Token_Sub:
  4971. if (is_type_float(type)) {
  4972. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  4973. return res;
  4974. }
  4975. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  4976. return res;
  4977. case Token_Mul:
  4978. if (is_type_float(type)) {
  4979. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  4980. return res;
  4981. }
  4982. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  4983. return res;
  4984. case Token_Quo:
  4985. if (is_type_float(type)) {
  4986. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  4987. return res;
  4988. } else if (is_type_unsigned(type)) {
  4989. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  4990. return res;
  4991. }
  4992. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  4993. return res;
  4994. case Token_Mod:
  4995. if (is_type_float(type)) {
  4996. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  4997. return res;
  4998. } else if (is_type_unsigned(type)) {
  4999. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5000. return res;
  5001. }
  5002. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5003. return res;
  5004. case Token_ModMod:
  5005. if (is_type_unsigned(type)) {
  5006. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5007. return res;
  5008. } else {
  5009. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5010. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5011. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5012. res.value = c;
  5013. return res;
  5014. }
  5015. case Token_And:
  5016. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5017. return res;
  5018. case Token_Or:
  5019. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5020. return res;
  5021. case Token_Xor:
  5022. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5023. return res;
  5024. case Token_Shl:
  5025. {
  5026. rhs = lb_emit_conv(p, rhs, lhs.type);
  5027. LLVMValueRef lhsval = lhs.value;
  5028. LLVMValueRef bits = rhs.value;
  5029. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  5030. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  5031. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5032. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5033. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  5034. return res;
  5035. }
  5036. case Token_Shr:
  5037. {
  5038. rhs = lb_emit_conv(p, rhs, lhs.type);
  5039. LLVMValueRef lhsval = lhs.value;
  5040. LLVMValueRef bits = rhs.value;
  5041. bool is_unsigned = is_type_unsigned(type);
  5042. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  5043. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  5044. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  5045. if (is_unsigned) {
  5046. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  5047. } else {
  5048. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5049. }
  5050. return res;
  5051. }
  5052. case Token_AndNot:
  5053. {
  5054. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5055. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5056. return res;
  5057. }
  5058. break;
  5059. }
  5060. GB_PANIC("unhandled operator of lb_emit_arith");
  5061. return {};
  5062. }
  5063. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5064. ast_node(be, BinaryExpr, expr);
  5065. TypeAndValue tv = type_and_value_of_expr(expr);
  5066. switch (be->op.kind) {
  5067. case Token_Add:
  5068. case Token_Sub:
  5069. case Token_Mul:
  5070. case Token_Quo:
  5071. case Token_Mod:
  5072. case Token_ModMod:
  5073. case Token_And:
  5074. case Token_Or:
  5075. case Token_Xor:
  5076. case Token_AndNot:
  5077. case Token_Shl:
  5078. case Token_Shr: {
  5079. Type *type = default_type(tv.type);
  5080. lbValue left = lb_build_expr(p, be->left);
  5081. lbValue right = lb_build_expr(p, be->right);
  5082. return lb_emit_arith(p, be->op.kind, left, right, type);
  5083. }
  5084. case Token_CmpEq:
  5085. case Token_NotEq:
  5086. case Token_Lt:
  5087. case Token_LtEq:
  5088. case Token_Gt:
  5089. case Token_GtEq:
  5090. {
  5091. lbValue left = {};
  5092. lbValue right = {};
  5093. if (be->left->tav.mode == Addressing_Type) {
  5094. left = lb_typeid(p->module, be->left->tav.type);
  5095. }
  5096. if (be->right->tav.mode == Addressing_Type) {
  5097. right = lb_typeid(p->module, be->right->tav.type);
  5098. }
  5099. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5100. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5101. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5102. Type *type = default_type(tv.type);
  5103. return lb_emit_conv(p, cmp, type);
  5104. }
  5105. case Token_CmpAnd:
  5106. case Token_CmpOr:
  5107. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5108. case Token_in:
  5109. case Token_not_in:
  5110. {
  5111. lbValue left = lb_build_expr(p, be->left);
  5112. Type *type = default_type(tv.type);
  5113. lbValue right = lb_build_expr(p, be->right);
  5114. Type *rt = base_type(right.type);
  5115. switch (rt->kind) {
  5116. case Type_Map:
  5117. {
  5118. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5119. lbValue h = lb_gen_map_header(p, addr, rt);
  5120. lbValue key = lb_gen_map_key(p, left, rt->Map.key);
  5121. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5122. args[0] = h;
  5123. args[1] = key;
  5124. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5125. if (be->op.kind == Token_in) {
  5126. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5127. } else {
  5128. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  5129. }
  5130. }
  5131. break;
  5132. case Type_BitSet:
  5133. {
  5134. Type *key_type = rt->BitSet.elem;
  5135. GB_ASSERT(are_types_identical(left.type, key_type));
  5136. Type *it = bit_set_to_int(rt);
  5137. left = lb_emit_conv(p, left, it);
  5138. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  5139. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  5140. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  5141. bit = lb_emit_conv(p, bit, it);
  5142. lbValue old_value = lb_emit_transmute(p, right, it);
  5143. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  5144. if (be->op.kind == Token_in) {
  5145. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5146. } else {
  5147. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5148. }
  5149. }
  5150. break;
  5151. default:
  5152. GB_PANIC("Invalid 'in' type");
  5153. }
  5154. break;
  5155. }
  5156. break;
  5157. default:
  5158. GB_PANIC("Invalid binary expression");
  5159. break;
  5160. }
  5161. return {};
  5162. }
  5163. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5164. Type *prev_src = src;
  5165. // Type *prev_dst = dst;
  5166. src = base_type(type_deref(src));
  5167. // dst = base_type(type_deref(dst));
  5168. bool src_is_ptr = src != prev_src;
  5169. // bool dst_is_ptr = dst != prev_dst;
  5170. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5171. for_array(i, src->Struct.fields) {
  5172. Entity *f = src->Struct.fields[i];
  5173. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5174. if (are_types_identical(dst, f->type)) {
  5175. return f->token.string;
  5176. }
  5177. if (src_is_ptr && is_type_pointer(dst)) {
  5178. if (are_types_identical(type_deref(dst), f->type)) {
  5179. return f->token.string;
  5180. }
  5181. }
  5182. if (is_type_struct(f->type)) {
  5183. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5184. if (name.len > 0) {
  5185. return name;
  5186. }
  5187. }
  5188. }
  5189. }
  5190. return str_lit("");
  5191. }
  5192. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5193. GB_ASSERT(is_type_pointer(value.type));
  5194. GB_ASSERT(is_type_pointer(t));
  5195. GB_ASSERT(lb_is_const(value));
  5196. lbValue res = {};
  5197. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5198. res.type = t;
  5199. return res;
  5200. }
  5201. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5202. lbModule *m = p->module;
  5203. t = reduce_tuple_to_single_type(t);
  5204. Type *src_type = value.type;
  5205. if (are_types_identical(t, src_type)) {
  5206. return value;
  5207. }
  5208. Type *src = core_type(src_type);
  5209. Type *dst = core_type(t);
  5210. GB_ASSERT(src != nullptr);
  5211. GB_ASSERT(dst != nullptr);
  5212. if (is_type_untyped_nil(src)) {
  5213. return lb_const_nil(m, t);
  5214. }
  5215. if (is_type_untyped_undef(src)) {
  5216. return lb_const_undef(m, t);
  5217. }
  5218. if (LLVMIsConstant(value.value)) {
  5219. if (is_type_any(dst)) {
  5220. Type *st = default_type(src_type);
  5221. lbAddr default_value = lb_add_local_generated(p, st, false);
  5222. lb_addr_store(p, default_value, value);
  5223. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5224. lbValue id = lb_typeid(m, st);
  5225. lbAddr res = lb_add_local_generated(p, t, false);
  5226. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5227. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5228. lb_emit_store(p, a0, data);
  5229. lb_emit_store(p, a1, id);
  5230. return lb_addr_load(p, res);
  5231. } else if (dst->kind == Type_Basic) {
  5232. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5233. String str = lb_get_const_string(m, value);
  5234. lbValue res = {};
  5235. res.type = t;
  5236. res.value = llvm_cstring(m, str);
  5237. return res;
  5238. }
  5239. // if (is_type_float(dst)) {
  5240. // return value;
  5241. // } else if (is_type_integer(dst)) {
  5242. // return value;
  5243. // }
  5244. // ExactValue ev = value->Constant.value;
  5245. // if (is_type_float(dst)) {
  5246. // ev = exact_value_to_float(ev);
  5247. // } else if (is_type_complex(dst)) {
  5248. // ev = exact_value_to_complex(ev);
  5249. // } else if (is_type_quaternion(dst)) {
  5250. // ev = exact_value_to_quaternion(ev);
  5251. // } else if (is_type_string(dst)) {
  5252. // // Handled elsewhere
  5253. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5254. // } else if (is_type_integer(dst)) {
  5255. // ev = exact_value_to_integer(ev);
  5256. // } else if (is_type_pointer(dst)) {
  5257. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5258. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5259. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5260. // }
  5261. // return lb_const_value(p->module, t, ev);
  5262. }
  5263. }
  5264. if (are_types_identical(src, dst)) {
  5265. if (!are_types_identical(src_type, t)) {
  5266. return lb_emit_transmute(p, value, t);
  5267. }
  5268. return value;
  5269. }
  5270. // bool <-> llvm bool
  5271. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5272. lbValue res = {};
  5273. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5274. res.type = dst;
  5275. return res;
  5276. }
  5277. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5278. lbValue res = {};
  5279. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5280. res.type = dst;
  5281. return res;
  5282. }
  5283. // integer -> integer
  5284. if (is_type_integer(src) && is_type_integer(dst)) {
  5285. GB_ASSERT(src->kind == Type_Basic &&
  5286. dst->kind == Type_Basic);
  5287. i64 sz = type_size_of(default_type(src));
  5288. i64 dz = type_size_of(default_type(dst));
  5289. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5290. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5291. value = lb_emit_byte_swap(p, value, platform_src_type);
  5292. }
  5293. LLVMOpcode op = LLVMTrunc;
  5294. if (dz < sz) {
  5295. op = LLVMTrunc;
  5296. } else if (dz == sz) {
  5297. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5298. // NOTE(bill): Copy the value just for type correctness
  5299. op = LLVMBitCast;
  5300. } else if (dz > sz) {
  5301. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5302. }
  5303. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5304. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5305. lbValue res = {};
  5306. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5307. res.type = t;
  5308. return lb_emit_byte_swap(p, res, t);
  5309. } else {
  5310. lbValue res = {};
  5311. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5312. res.type = t;
  5313. return res;
  5314. }
  5315. }
  5316. // boolean -> boolean/integer
  5317. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5318. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5319. lbValue res = {};
  5320. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5321. res.type = t;
  5322. return res;
  5323. }
  5324. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5325. return lb_emit_transmute(p, value, dst);
  5326. }
  5327. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5328. return lb_emit_transmute(p, value, dst);
  5329. }
  5330. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5331. return lb_emit_transmute(p, value, dst);
  5332. }
  5333. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5334. return lb_emit_transmute(p, value, dst);
  5335. }
  5336. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5337. lbValue c = lb_emit_conv(p, value, t_cstring);
  5338. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5339. args[0] = c;
  5340. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5341. return lb_emit_conv(p, s, dst);
  5342. }
  5343. // integer -> boolean
  5344. if (is_type_integer(src) && is_type_boolean(dst)) {
  5345. lbValue res = {};
  5346. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5347. res.type = t_llvm_bool;
  5348. return lb_emit_conv(p, res, t);
  5349. }
  5350. // float -> float
  5351. if (is_type_float(src) && is_type_float(dst)) {
  5352. i64 sz = type_size_of(src);
  5353. i64 dz = type_size_of(dst);
  5354. if (dz == sz) {
  5355. if (types_have_same_internal_endian(src, dst)) {
  5356. lbValue res = {};
  5357. res.type = t;
  5358. res.value = value.value;
  5359. return res;
  5360. } else {
  5361. return lb_emit_byte_swap(p, value, t);
  5362. }
  5363. }
  5364. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5365. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5366. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5367. lbValue res = {};
  5368. res = lb_emit_conv(p, value, platform_src_type);
  5369. res = lb_emit_conv(p, res, platform_dst_type);
  5370. if (is_type_different_to_arch_endianness(dst)) {
  5371. res = lb_emit_byte_swap(p, res, t);
  5372. }
  5373. return lb_emit_conv(p, res, t);
  5374. }
  5375. lbValue res = {};
  5376. res.type = t;
  5377. if (dz >= sz) {
  5378. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5379. } else {
  5380. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5381. }
  5382. return res;
  5383. }
  5384. if (is_type_complex(src) && is_type_complex(dst)) {
  5385. Type *ft = base_complex_elem_type(dst);
  5386. lbAddr gen = lb_add_local_generated(p, dst, false);
  5387. lbValue gp = lb_addr_get_ptr(p, gen);
  5388. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5389. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5390. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5391. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5392. return lb_addr_load(p, gen);
  5393. }
  5394. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5395. // @QuaternionLayout
  5396. Type *ft = base_complex_elem_type(dst);
  5397. lbAddr gen = lb_add_local_generated(p, dst, false);
  5398. lbValue gp = lb_addr_get_ptr(p, gen);
  5399. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5400. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5401. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5402. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5403. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5404. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5405. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5406. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5407. return lb_addr_load(p, gen);
  5408. }
  5409. if (is_type_float(src) && is_type_complex(dst)) {
  5410. Type *ft = base_complex_elem_type(dst);
  5411. lbAddr gen = lb_add_local_generated(p, dst, true);
  5412. lbValue gp = lb_addr_get_ptr(p, gen);
  5413. lbValue real = lb_emit_conv(p, value, ft);
  5414. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5415. return lb_addr_load(p, gen);
  5416. }
  5417. if (is_type_float(src) && is_type_quaternion(dst)) {
  5418. Type *ft = base_complex_elem_type(dst);
  5419. lbAddr gen = lb_add_local_generated(p, dst, true);
  5420. lbValue gp = lb_addr_get_ptr(p, gen);
  5421. lbValue real = lb_emit_conv(p, value, ft);
  5422. // @QuaternionLayout
  5423. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5424. return lb_addr_load(p, gen);
  5425. }
  5426. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5427. Type *ft = base_complex_elem_type(dst);
  5428. lbAddr gen = lb_add_local_generated(p, dst, true);
  5429. lbValue gp = lb_addr_get_ptr(p, gen);
  5430. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5431. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5432. // @QuaternionLayout
  5433. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5434. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5435. return lb_addr_load(p, gen);
  5436. }
  5437. // float <-> integer
  5438. if (is_type_float(src) && is_type_integer(dst)) {
  5439. lbValue res = {};
  5440. res.type = t;
  5441. if (is_type_unsigned(dst)) {
  5442. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5443. } else {
  5444. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5445. }
  5446. return res;
  5447. }
  5448. if (is_type_integer(src) && is_type_float(dst)) {
  5449. lbValue res = {};
  5450. res.type = t;
  5451. if (is_type_unsigned(src)) {
  5452. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5453. } else {
  5454. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5455. }
  5456. return res;
  5457. }
  5458. // Pointer <-> uintptr
  5459. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5460. lbValue res = {};
  5461. res.type = t;
  5462. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5463. return res;
  5464. }
  5465. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5466. lbValue res = {};
  5467. res.type = t;
  5468. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5469. return res;
  5470. }
  5471. #if 1
  5472. if (is_type_union(dst)) {
  5473. for_array(i, dst->Union.variants) {
  5474. Type *vt = dst->Union.variants[i];
  5475. if (are_types_identical(vt, src_type)) {
  5476. lbAddr parent = lb_add_local_generated(p, t, true);
  5477. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5478. return lb_addr_load(p, parent);
  5479. }
  5480. }
  5481. }
  5482. #endif
  5483. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5484. // subtype polymorphism casting
  5485. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5486. Type *st = type_deref(src_type);
  5487. Type *pst = st;
  5488. st = type_deref(st);
  5489. bool st_is_ptr = is_type_pointer(src_type);
  5490. st = base_type(st);
  5491. Type *dt = t;
  5492. bool dt_is_ptr = type_deref(dt) != dt;
  5493. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5494. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  5495. if (field_name.len > 0) {
  5496. // NOTE(bill): It can be casted
  5497. Selection sel = lookup_field(st, field_name, false, true);
  5498. if (sel.entity != nullptr) {
  5499. if (st_is_ptr) {
  5500. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  5501. Type *rt = res.type;
  5502. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5503. res = lb_emit_load(p, res);
  5504. }
  5505. return res;
  5506. } else {
  5507. if (is_type_pointer(value.type)) {
  5508. Type *rt = value.type;
  5509. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5510. value = lb_emit_load(p, value);
  5511. } else {
  5512. value = lb_emit_deep_field_gep(p, value, sel);
  5513. return lb_emit_load(p, value);
  5514. }
  5515. }
  5516. return lb_emit_deep_field_ev(p, value, sel);
  5517. }
  5518. } else {
  5519. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5520. }
  5521. }
  5522. }
  5523. // Pointer <-> Pointer
  5524. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5525. lbValue res = {};
  5526. res.type = t;
  5527. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5528. return res;
  5529. }
  5530. // proc <-> proc
  5531. if (is_type_proc(src) && is_type_proc(dst)) {
  5532. lbValue res = {};
  5533. res.type = t;
  5534. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5535. return res;
  5536. }
  5537. // pointer -> proc
  5538. if (is_type_pointer(src) && is_type_proc(dst)) {
  5539. lbValue res = {};
  5540. res.type = t;
  5541. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5542. return res;
  5543. }
  5544. // proc -> pointer
  5545. if (is_type_proc(src) && is_type_pointer(dst)) {
  5546. lbValue res = {};
  5547. res.type = t;
  5548. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5549. return res;
  5550. }
  5551. // []byte/[]u8 <-> string
  5552. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5553. return lb_emit_transmute(p, value, t);
  5554. }
  5555. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5556. return lb_emit_transmute(p, value, t);
  5557. }
  5558. if (is_type_array(dst)) {
  5559. Type *elem = dst->Array.elem;
  5560. lbValue e = lb_emit_conv(p, value, elem);
  5561. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5562. lbAddr v = lb_add_local_generated(p, t, false);
  5563. isize index_count = cast(isize)dst->Array.count;
  5564. for (isize i = 0; i < index_count; i++) {
  5565. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  5566. lb_emit_store(p, elem, e);
  5567. }
  5568. return lb_addr_load(p, v);
  5569. }
  5570. if (is_type_any(dst)) {
  5571. if (is_type_untyped_nil(src)) {
  5572. return lb_const_nil(p->module, t);
  5573. }
  5574. if (is_type_untyped_undef(src)) {
  5575. return lb_const_undef(p->module, t);
  5576. }
  5577. lbAddr result = lb_add_local_generated(p, t, true);
  5578. Type *st = default_type(src_type);
  5579. lbValue data = lb_address_from_load_or_generate_local(p, value);
  5580. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  5581. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5582. data = lb_emit_conv(p, data, t_rawptr);
  5583. lbValue id = lb_typeid(p->module, st);
  5584. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  5585. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  5586. lb_emit_store(p, any_data, data);
  5587. lb_emit_store(p, any_id, id);
  5588. return lb_addr_load(p, result);
  5589. }
  5590. i64 src_sz = type_size_of(src);
  5591. i64 dst_sz = type_size_of(dst);
  5592. if (src_sz == dst_sz) {
  5593. // bit_set <-> integer
  5594. if (is_type_integer(src) && is_type_bit_set(dst)) {
  5595. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  5596. res.type = dst;
  5597. return res;
  5598. }
  5599. if (is_type_bit_set(src) && is_type_integer(dst)) {
  5600. lbValue bs = value;
  5601. bs.type = bit_set_to_int(src);
  5602. return lb_emit_conv(p, bs, dst);
  5603. }
  5604. // typeid <-> integer
  5605. if (is_type_integer(src) && is_type_typeid(dst)) {
  5606. return lb_emit_transmute(p, value, dst);
  5607. }
  5608. if (is_type_typeid(src) && is_type_integer(dst)) {
  5609. return lb_emit_transmute(p, value, dst);
  5610. }
  5611. }
  5612. if (is_type_untyped(src)) {
  5613. if (is_type_string(src) && is_type_string(dst)) {
  5614. lbAddr result = lb_add_local_generated(p, t, false);
  5615. lb_addr_store(p, result, value);
  5616. return lb_addr_load(p, result);
  5617. }
  5618. }
  5619. gb_printf_err("%.*s\n", LIT(p->name));
  5620. gb_printf_err("lb_emit_conv: src -> dst\n");
  5621. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5622. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5623. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  5624. gb_printf_err("Not Identical %p != %p\n", src, dst);
  5625. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5626. type_to_string(src_type), type_to_string(t),
  5627. LIT(p->name));
  5628. return {};
  5629. }
  5630. bool lb_is_type_aggregate(Type *t) {
  5631. t = base_type(t);
  5632. switch (t->kind) {
  5633. case Type_Basic:
  5634. switch (t->Basic.kind) {
  5635. case Basic_string:
  5636. case Basic_any:
  5637. return true;
  5638. // case Basic_complex32:
  5639. case Basic_complex64:
  5640. case Basic_complex128:
  5641. case Basic_quaternion128:
  5642. case Basic_quaternion256:
  5643. return true;
  5644. }
  5645. break;
  5646. case Type_Pointer:
  5647. return false;
  5648. case Type_Array:
  5649. case Type_Slice:
  5650. case Type_Struct:
  5651. case Type_Union:
  5652. case Type_Tuple:
  5653. case Type_DynamicArray:
  5654. case Type_Map:
  5655. case Type_BitField:
  5656. case Type_SimdVector:
  5657. return true;
  5658. case Type_Named:
  5659. return lb_is_type_aggregate(t->Named.base);
  5660. }
  5661. return false;
  5662. }
  5663. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  5664. Type *src_type = value.type;
  5665. if (are_types_identical(t, src_type)) {
  5666. return value;
  5667. }
  5668. lbValue res = {};
  5669. res.type = t;
  5670. Type *src = base_type(src_type);
  5671. Type *dst = base_type(t);
  5672. lbModule *m = p->module;
  5673. i64 sz = type_size_of(src);
  5674. i64 dz = type_size_of(dst);
  5675. if (sz != dz) {
  5676. LLVMTypeRef s = lb_type(m, src);
  5677. LLVMTypeRef d = lb_type(m, dst);
  5678. i64 llvm_sz = lb_sizeof(s);
  5679. i64 llvm_dz = lb_sizeof(d);
  5680. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  5681. }
  5682. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5683. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5684. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5685. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5686. return res;
  5687. }
  5688. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5689. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5690. return res;
  5691. }
  5692. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5693. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5694. return res;
  5695. }
  5696. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5697. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5698. return res;
  5699. }
  5700. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5701. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5702. return res;
  5703. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5704. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5705. return res;
  5706. }
  5707. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5708. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  5709. return res;
  5710. }
  5711. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  5712. lbValue s = lb_address_from_load_or_generate_local(p, value);
  5713. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  5714. return lb_emit_load(p, d);
  5715. }
  5716. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  5717. // GB_PANIC("lb_emit_transmute");
  5718. return res;
  5719. }
  5720. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  5721. GB_ASSERT(addr.kind == lbAddr_Context);
  5722. GB_ASSERT(addr.ctx.sel.index.count == 0);
  5723. lbModule *m = p->module;
  5724. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5725. args[0] = addr.addr;
  5726. lb_emit_runtime_call(p, "__init_context", args);
  5727. }
  5728. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  5729. ctx.kind = lbAddr_Context;
  5730. lbContextData cd = {ctx, p->scope_index};
  5731. array_add(&p->context_stack, cd);
  5732. }
  5733. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  5734. if (p->context_stack.count > 0) {
  5735. return p->context_stack[p->context_stack.count-1].ctx;
  5736. }
  5737. Type *pt = base_type(p->type);
  5738. GB_ASSERT(pt->kind == Type_Proc);
  5739. {
  5740. lbAddr c = lb_add_local_generated(p, t_context, false);
  5741. c.kind = lbAddr_Context;
  5742. lb_emit_init_context(p, c);
  5743. lb_push_context_onto_stack(p, c);
  5744. return c;
  5745. }
  5746. }
  5747. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  5748. if (LLVMIsALoadInst(value.value)) {
  5749. lbValue res = {};
  5750. res.value = LLVMGetOperand(value.value, 0);
  5751. res.type = alloc_type_pointer(value.type);
  5752. return res;
  5753. }
  5754. GB_ASSERT(is_type_typed(value.type));
  5755. lbAddr res = lb_add_local_generated(p, value.type, false);
  5756. lb_addr_store(p, res, value);
  5757. return res.addr;
  5758. }
  5759. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  5760. if (LLVMIsALoadInst(value.value)) {
  5761. lbValue res = {};
  5762. res.value = LLVMGetOperand(value.value, 0);
  5763. res.type = alloc_type_pointer(value.type);
  5764. return res;
  5765. }
  5766. GB_PANIC("lb_address_from_load");
  5767. return {};
  5768. }
  5769. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  5770. i64 type_alignment = type_align_of(new_type);
  5771. if (alignment < type_alignment) {
  5772. alignment = type_alignment;
  5773. }
  5774. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  5775. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  5776. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  5777. lb_addr_store(p, ptr, val);
  5778. ptr.kind = lbAddr_Context;
  5779. return ptr.addr;
  5780. }
  5781. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  5782. GB_ASSERT(is_type_pointer(s.type));
  5783. Type *t = base_type(type_deref(s.type));
  5784. Type *result_type = nullptr;
  5785. if (t->kind == Type_Opaque) {
  5786. t = t->Opaque.elem;
  5787. }
  5788. if (is_type_relative_pointer(t)) {
  5789. s = lb_addr_get_ptr(p, lb_addr(s));
  5790. }
  5791. if (is_type_struct(t)) {
  5792. result_type = get_struct_field_type(t, index);
  5793. } else if (is_type_union(t)) {
  5794. GB_ASSERT(index == -1);
  5795. return lb_emit_union_tag_ptr(p, s);
  5796. } else if (is_type_tuple(t)) {
  5797. GB_ASSERT(t->Tuple.variables.count > 0);
  5798. result_type = t->Tuple.variables[index]->type;
  5799. } else if (is_type_complex(t)) {
  5800. Type *ft = base_complex_elem_type(t);
  5801. switch (index) {
  5802. case 0: result_type = ft; break;
  5803. case 1: result_type = ft; break;
  5804. }
  5805. } else if (is_type_quaternion(t)) {
  5806. Type *ft = base_complex_elem_type(t);
  5807. switch (index) {
  5808. case 0: result_type = ft; break;
  5809. case 1: result_type = ft; break;
  5810. case 2: result_type = ft; break;
  5811. case 3: result_type = ft; break;
  5812. }
  5813. } else if (is_type_slice(t)) {
  5814. switch (index) {
  5815. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5816. case 1: result_type = t_int; break;
  5817. }
  5818. } else if (is_type_string(t)) {
  5819. switch (index) {
  5820. case 0: result_type = t_u8_ptr; break;
  5821. case 1: result_type = t_int; break;
  5822. }
  5823. } else if (is_type_any(t)) {
  5824. switch (index) {
  5825. case 0: result_type = t_rawptr; break;
  5826. case 1: result_type = t_typeid; break;
  5827. }
  5828. } else if (is_type_dynamic_array(t)) {
  5829. switch (index) {
  5830. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5831. case 1: result_type = t_int; break;
  5832. case 2: result_type = t_int; break;
  5833. case 3: result_type = t_allocator; break;
  5834. }
  5835. } else if (is_type_map(t)) {
  5836. init_map_internal_types(t);
  5837. Type *itp = alloc_type_pointer(t->Map.internal_type);
  5838. s = lb_emit_transmute(p, s, itp);
  5839. Type *gst = t->Map.internal_type;
  5840. GB_ASSERT(gst->kind == Type_Struct);
  5841. switch (index) {
  5842. case 0: result_type = get_struct_field_type(gst, 0); break;
  5843. case 1: result_type = get_struct_field_type(gst, 1); break;
  5844. }
  5845. } else if (is_type_array(t)) {
  5846. return lb_emit_array_epi(p, s, index);
  5847. } else if (is_type_relative_slice(t)) {
  5848. switch (index) {
  5849. case 0: result_type = t->RelativeSlice.base_integer; break;
  5850. case 1: result_type = t->RelativeSlice.base_integer; break;
  5851. }
  5852. } else {
  5853. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  5854. }
  5855. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  5856. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5857. index += 1;
  5858. }
  5859. if (lb_is_const(s)) {
  5860. lbModule *m = p->module;
  5861. lbValue res = {};
  5862. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  5863. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  5864. res.type = alloc_type_pointer(result_type);
  5865. return res;
  5866. } else {
  5867. lbValue res = {};
  5868. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  5869. res.type = alloc_type_pointer(result_type);
  5870. return res;
  5871. }
  5872. }
  5873. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  5874. if (LLVMIsALoadInst(s.value)) {
  5875. lbValue res = {};
  5876. res.value = LLVMGetOperand(s.value, 0);
  5877. res.type = alloc_type_pointer(s.type);
  5878. lbValue ptr = lb_emit_struct_ep(p, res, index);
  5879. return lb_emit_load(p, ptr);
  5880. }
  5881. Type *t = base_type(s.type);
  5882. Type *result_type = nullptr;
  5883. switch (t->kind) {
  5884. case Type_Basic:
  5885. switch (t->Basic.kind) {
  5886. case Basic_string:
  5887. switch (index) {
  5888. case 0: result_type = t_u8_ptr; break;
  5889. case 1: result_type = t_int; break;
  5890. }
  5891. break;
  5892. case Basic_any:
  5893. switch (index) {
  5894. case 0: result_type = t_rawptr; break;
  5895. case 1: result_type = t_typeid; break;
  5896. }
  5897. break;
  5898. case Basic_complex64: case Basic_complex128:
  5899. {
  5900. Type *ft = base_complex_elem_type(t);
  5901. switch (index) {
  5902. case 0: result_type = ft; break;
  5903. case 1: result_type = ft; break;
  5904. }
  5905. break;
  5906. }
  5907. case Basic_quaternion128: case Basic_quaternion256:
  5908. {
  5909. Type *ft = base_complex_elem_type(t);
  5910. switch (index) {
  5911. case 0: result_type = ft; break;
  5912. case 1: result_type = ft; break;
  5913. case 2: result_type = ft; break;
  5914. case 3: result_type = ft; break;
  5915. }
  5916. break;
  5917. }
  5918. }
  5919. break;
  5920. case Type_Struct:
  5921. result_type = get_struct_field_type(t, index);
  5922. break;
  5923. case Type_Union:
  5924. GB_ASSERT(index == -1);
  5925. // return lb_emit_union_tag_value(p, s);
  5926. GB_PANIC("lb_emit_union_tag_value");
  5927. case Type_Tuple:
  5928. GB_ASSERT(t->Tuple.variables.count > 0);
  5929. result_type = t->Tuple.variables[index]->type;
  5930. if (t->Tuple.variables.count == 1) {
  5931. return s;
  5932. }
  5933. break;
  5934. case Type_Slice:
  5935. switch (index) {
  5936. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5937. case 1: result_type = t_int; break;
  5938. }
  5939. break;
  5940. case Type_DynamicArray:
  5941. switch (index) {
  5942. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5943. case 1: result_type = t_int; break;
  5944. case 2: result_type = t_int; break;
  5945. case 3: result_type = t_allocator; break;
  5946. }
  5947. break;
  5948. case Type_Map:
  5949. {
  5950. init_map_internal_types(t);
  5951. Type *gst = t->Map.generated_struct_type;
  5952. switch (index) {
  5953. case 0: result_type = get_struct_field_type(gst, 0); break;
  5954. case 1: result_type = get_struct_field_type(gst, 1); break;
  5955. }
  5956. }
  5957. break;
  5958. case Type_Array:
  5959. result_type = t->Array.elem;
  5960. break;
  5961. default:
  5962. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  5963. break;
  5964. }
  5965. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  5966. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5967. index += 1;
  5968. }
  5969. lbValue res = {};
  5970. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  5971. res.type = result_type;
  5972. return res;
  5973. }
  5974. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  5975. GB_ASSERT(sel.index.count > 0);
  5976. Type *type = type_deref(e.type);
  5977. for_array(i, sel.index) {
  5978. i32 index = cast(i32)sel.index[i];
  5979. if (is_type_pointer(type)) {
  5980. type = type_deref(type);
  5981. e = lb_emit_load(p, e);
  5982. }
  5983. type = core_type(type);
  5984. if (type->kind == Type_Opaque) {
  5985. type = type->Opaque.elem;
  5986. }
  5987. if (is_type_quaternion(type)) {
  5988. e = lb_emit_struct_ep(p, e, index);
  5989. } else if (is_type_raw_union(type)) {
  5990. type = get_struct_field_type(type, index);
  5991. GB_ASSERT(is_type_pointer(e.type));
  5992. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  5993. } else if (is_type_struct(type)) {
  5994. type = get_struct_field_type(type, index);
  5995. e = lb_emit_struct_ep(p, e, index);
  5996. } else if (type->kind == Type_Union) {
  5997. GB_ASSERT(index == -1);
  5998. type = t_type_info_ptr;
  5999. e = lb_emit_struct_ep(p, e, index);
  6000. } else if (type->kind == Type_Tuple) {
  6001. type = type->Tuple.variables[index]->type;
  6002. e = lb_emit_struct_ep(p, e, index);
  6003. } else if (type->kind == Type_Basic) {
  6004. switch (type->Basic.kind) {
  6005. case Basic_any: {
  6006. if (index == 0) {
  6007. type = t_rawptr;
  6008. } else if (index == 1) {
  6009. type = t_type_info_ptr;
  6010. }
  6011. e = lb_emit_struct_ep(p, e, index);
  6012. break;
  6013. }
  6014. case Basic_string:
  6015. e = lb_emit_struct_ep(p, e, index);
  6016. break;
  6017. default:
  6018. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6019. break;
  6020. }
  6021. } else if (type->kind == Type_Slice) {
  6022. e = lb_emit_struct_ep(p, e, index);
  6023. } else if (type->kind == Type_DynamicArray) {
  6024. e = lb_emit_struct_ep(p, e, index);
  6025. } else if (type->kind == Type_Array) {
  6026. e = lb_emit_array_epi(p, e, index);
  6027. } else if (type->kind == Type_Map) {
  6028. e = lb_emit_struct_ep(p, e, index);
  6029. } else if (type->kind == Type_RelativePointer) {
  6030. e = lb_emit_struct_ep(p, e, index);
  6031. } else {
  6032. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6033. }
  6034. }
  6035. return e;
  6036. }
  6037. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6038. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6039. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6040. return lb_emit_load(p, res);
  6041. }
  6042. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  6043. // NOTE(bill): The prev block may defer injection before it's terminator
  6044. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6045. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6046. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6047. return;
  6048. }
  6049. isize prev_context_stack_count = p->context_stack.count;
  6050. defer (p->context_stack.count = prev_context_stack_count);
  6051. p->context_stack.count = d.context_stack_count;
  6052. lbBlock *b = lb_create_block(p, "defer");
  6053. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6054. lb_emit_jump(p, b);
  6055. }
  6056. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6057. lb_emit_jump(p, b);
  6058. }
  6059. lb_start_block(p, b);
  6060. if (d.kind == lbDefer_Node) {
  6061. lb_build_stmt(p, d.stmt);
  6062. } else if (d.kind == lbDefer_Instr) {
  6063. // NOTE(bill): Need to make a new copy
  6064. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6065. LLVMInsertIntoBuilder(p->builder, instr);
  6066. } else if (d.kind == lbDefer_Proc) {
  6067. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6068. }
  6069. }
  6070. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6071. isize count = p->defer_stmts.count;
  6072. isize i = count;
  6073. while (i --> 0) {
  6074. lbDefer d = p->defer_stmts[i];
  6075. isize prev_context_stack_count = p->context_stack.count;
  6076. defer (p->context_stack.count = prev_context_stack_count);
  6077. p->context_stack.count = d.context_stack_count;
  6078. if (kind == lbDeferExit_Default) {
  6079. if (p->scope_index == d.scope_index &&
  6080. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6081. lb_build_defer_stmt(p, d);
  6082. array_pop(&p->defer_stmts);
  6083. continue;
  6084. } else {
  6085. break;
  6086. }
  6087. } else if (kind == lbDeferExit_Return) {
  6088. lb_build_defer_stmt(p, d);
  6089. } else if (kind == lbDeferExit_Branch) {
  6090. GB_ASSERT(block != nullptr);
  6091. isize lower_limit = block->scope_index;
  6092. if (lower_limit < d.scope_index) {
  6093. lb_build_defer_stmt(p, d);
  6094. }
  6095. }
  6096. }
  6097. }
  6098. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  6099. lbDefer d = {lbDefer_Node};
  6100. d.scope_index = scope_index;
  6101. d.context_stack_count = p->context_stack.count;
  6102. d.block = p->curr_block;
  6103. d.stmt = stmt;
  6104. array_add(&p->defer_stmts, d);
  6105. return d;
  6106. }
  6107. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  6108. lbDefer d = {lbDefer_Proc};
  6109. d.scope_index = p->scope_index;
  6110. d.block = p->curr_block;
  6111. d.proc.deferred = deferred;
  6112. d.proc.result_as_args = result_as_args;
  6113. array_add(&p->defer_stmts, d);
  6114. return d;
  6115. }
  6116. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  6117. Array<lbValue> array = {};
  6118. Type *t = base_type(value.type);
  6119. if (t == nullptr) {
  6120. // Do nothing
  6121. } else if (is_type_tuple(t)) {
  6122. GB_ASSERT(t->kind == Type_Tuple);
  6123. auto *rt = &t->Tuple;
  6124. if (rt->variables.count > 0) {
  6125. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  6126. for_array(i, rt->variables) {
  6127. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  6128. array[i] = elem;
  6129. }
  6130. }
  6131. } else {
  6132. array = array_make<lbValue>(permanent_allocator(), 1);
  6133. array[0] = value;
  6134. }
  6135. return array;
  6136. }
  6137. 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) {
  6138. unsigned arg_count = cast(unsigned)processed_args.count;
  6139. if (return_ptr.value != nullptr) {
  6140. arg_count += 1;
  6141. }
  6142. if (context_ptr.addr.value != nullptr) {
  6143. arg_count += 1;
  6144. }
  6145. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  6146. isize arg_index = 0;
  6147. if (return_ptr.value != nullptr) {
  6148. args[arg_index++] = return_ptr.value;
  6149. }
  6150. for_array(i, processed_args) {
  6151. lbValue arg = processed_args[i];
  6152. args[arg_index++] = arg.value;
  6153. }
  6154. if (context_ptr.addr.value != nullptr) {
  6155. args[arg_index++] = context_ptr.addr.value;
  6156. }
  6157. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  6158. GB_ASSERT(curr_block != p->decl_block->block);
  6159. if (USE_LLVM_ABI) {
  6160. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6161. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6162. LLVMValueRef fn = value.value;
  6163. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6164. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6165. }
  6166. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6167. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6168. LLVMValueRef ret = LLVMBuildCall2(p->builder, ft, fn, args, arg_count, "");;
  6169. lbValue res = {};
  6170. res.value = ret;
  6171. res.type = abi_rt;
  6172. return res;
  6173. } else {
  6174. LLVMValueRef ret = LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(p->module, value.type)), value.value, args, arg_count, "");;
  6175. lbValue res = {};
  6176. res.value = ret;
  6177. res.type = abi_rt;
  6178. return res;
  6179. }
  6180. }
  6181. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6182. String name = make_string_c(c_name);
  6183. AstPackage *pkg = p->module->info->runtime_package;
  6184. Entity *e = scope_lookup_current(pkg->scope, name);
  6185. lbValue *found = nullptr;
  6186. if (p->module != e->code_gen_module) {
  6187. gb_mutex_lock(&p->module->mutex);
  6188. }
  6189. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6190. if (p->module != e->code_gen_module) {
  6191. gb_mutex_unlock(&p->module->mutex);
  6192. }
  6193. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6194. return lb_emit_call(p, *found, args);
  6195. }
  6196. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6197. lbModule *m = p->module;
  6198. Type *pt = base_type(value.type);
  6199. GB_ASSERT(pt->kind == Type_Proc);
  6200. Type *results = pt->Proc.results;
  6201. if (p->entity != nullptr) {
  6202. if (p->entity->flags & EntityFlag_Disabled) {
  6203. return {};
  6204. }
  6205. }
  6206. lbAddr context_ptr = {};
  6207. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6208. context_ptr = lb_find_or_generate_context_ptr(p);
  6209. }
  6210. defer (if (pt->Proc.diverging) {
  6211. LLVMBuildUnreachable(p->builder);
  6212. });
  6213. set_procedure_abi_types(pt);
  6214. bool is_c_vararg = pt->Proc.c_vararg;
  6215. isize param_count = pt->Proc.param_count;
  6216. if (is_c_vararg) {
  6217. GB_ASSERT(param_count-1 <= args.count);
  6218. param_count -= 1;
  6219. } else {
  6220. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6221. }
  6222. lbValue result = {};
  6223. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6224. if (USE_LLVM_ABI) {
  6225. lbFunctionType **ft_found = nullptr;
  6226. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6227. if (!ft_found) {
  6228. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6229. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6230. }
  6231. GB_ASSERT(ft_found != nullptr);
  6232. lbFunctionType *ft = *ft_found;
  6233. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6234. unsigned param_index = 0;
  6235. for (isize i = 0; i < param_count; i++) {
  6236. Entity *e = pt->Proc.params->Tuple.variables[i];
  6237. if (e->kind != Entity_Variable) {
  6238. continue;
  6239. }
  6240. GB_ASSERT(e->flags & EntityFlag_Param);
  6241. Type *original_type = e->type;
  6242. lbArgType *arg = &ft->args[param_index];
  6243. if (arg->kind == lbArg_Ignore) {
  6244. continue;
  6245. }
  6246. lbValue x = lb_emit_conv(p, args[i], original_type);
  6247. LLVMTypeRef xt = lb_type(p->module, x.type);
  6248. if (arg->kind == lbArg_Direct) {
  6249. LLVMTypeRef abi_type = arg->cast_type;
  6250. if (!abi_type) {
  6251. abi_type = arg->type;
  6252. }
  6253. if (xt == abi_type) {
  6254. array_add(&processed_args, x);
  6255. } else {
  6256. Type *at = lb_abi_to_odin_type(abi_type, false);
  6257. if (at == t_llvm_bool) {
  6258. x = lb_emit_conv(p, x, at);
  6259. } else if (is_type_simd_vector(at) && lb_sizeof(abi_type) > lb_sizeof(xt)) {
  6260. lbAddr v = lb_add_local_generated(p, at, false);
  6261. lbValue ptr = lb_addr_get_ptr(p, v);
  6262. ptr = lb_emit_conv(p, ptr, alloc_type_pointer(x.type));
  6263. lb_emit_store(p, ptr, x);
  6264. x = lb_addr_load(p, v);
  6265. } else {
  6266. x = lb_emit_transmute(p, x, at);
  6267. }
  6268. array_add(&processed_args, x);
  6269. }
  6270. } else if (arg->kind == lbArg_Indirect) {
  6271. lbValue ptr = {};
  6272. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6273. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6274. // i.e. `T const &` in C++
  6275. ptr = lb_address_from_load_or_generate_local(p, x);
  6276. } else {
  6277. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6278. }
  6279. array_add(&processed_args, ptr);
  6280. }
  6281. param_index += 1;
  6282. }
  6283. if (inlining == ProcInlining_none) {
  6284. inlining = p->inlining;
  6285. }
  6286. Type *rt = reduce_tuple_to_single_type(results);
  6287. if (return_by_pointer) {
  6288. lbValue return_ptr = {};
  6289. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6290. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6291. return_ptr = p->return_ptr_hint_value;
  6292. p->return_ptr_hint_used = true;
  6293. }
  6294. }
  6295. if (return_ptr.value == nullptr) {
  6296. lbAddr r = lb_add_local_generated(p, rt, true);
  6297. return_ptr = r.addr;
  6298. }
  6299. GB_ASSERT(is_type_pointer(return_ptr.type));
  6300. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6301. result = lb_emit_load(p, return_ptr);
  6302. } else if (rt != nullptr) {
  6303. LLVMTypeRef ret_type = ft->ret.cast_type;
  6304. if (!ret_type) {
  6305. ret_type = ft->ret.type;
  6306. }
  6307. Type *abi_rt = lb_abi_to_odin_type(ret_type, true);
  6308. result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining);
  6309. if (ret_type != lb_type(m, rt)) {
  6310. if (is_type_simd_vector(abi_rt) && lb_sizeof(ret_type) > type_size_of(rt)) {
  6311. lbValue ptr = lb_address_from_load_or_generate_local(p, result);
  6312. ptr = lb_emit_conv(p, ptr, alloc_type_pointer(rt));
  6313. result = lb_emit_load(p, ptr);
  6314. } else {
  6315. result = lb_emit_transmute(p, result, rt);
  6316. }
  6317. }
  6318. if (!is_type_tuple(rt)) {
  6319. result = lb_emit_conv(p, result, rt);
  6320. }
  6321. } else {
  6322. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  6323. }
  6324. } else {
  6325. for (isize i = 0; i < param_count; i++) {
  6326. Entity *e = pt->Proc.params->Tuple.variables[i];
  6327. if (e->kind != Entity_Variable) {
  6328. // array_add(&processed_args, args[i]);
  6329. continue;
  6330. }
  6331. GB_ASSERT(e->flags & EntityFlag_Param);
  6332. Type *original_type = e->type;
  6333. Type *new_type = pt->Proc.abi_compat_params[i];
  6334. Type *arg_type = args[i].type;
  6335. if (are_types_identical(arg_type, new_type)) {
  6336. // NOTE(bill): Done
  6337. array_add(&processed_args, args[i]);
  6338. } else if (!are_types_identical(original_type, new_type)) {
  6339. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  6340. Type *av = core_type(type_deref(new_type));
  6341. if (are_types_identical(av, core_type(original_type))) {
  6342. if (e->flags&EntityFlag_ImplicitReference) {
  6343. array_add(&processed_args, lb_address_from_load_or_generate_local(p, args[i]));
  6344. } else if (!is_type_pointer(arg_type)) {
  6345. array_add(&processed_args, lb_copy_value_to_ptr(p, args[i], original_type, 16));
  6346. }
  6347. } else {
  6348. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  6349. }
  6350. } else if (new_type == t_llvm_bool) {
  6351. array_add(&processed_args, lb_emit_conv(p, args[i], new_type));
  6352. } else if (is_type_integer(new_type) || is_type_float(new_type) || is_type_boolean(new_type)) {
  6353. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  6354. } else if (is_type_simd_vector(new_type)) {
  6355. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  6356. } else if (is_type_tuple(new_type)) {
  6357. Type *abi_type = pt->Proc.abi_compat_params[i];
  6358. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  6359. lbValue x = {};
  6360. i64 st_sz = type_size_of(st);
  6361. i64 arg_sz = type_size_of(args[i].type);
  6362. if (st_sz == arg_sz) {
  6363. x = lb_emit_transmute(p, args[i], st);
  6364. } else {
  6365. // NOTE(bill): struct{f32, f32, f32} != struct{#simd[2]f32, f32}
  6366. GB_ASSERT(st_sz > arg_sz);
  6367. lbAddr xx = lb_add_local_generated(p, st, false);
  6368. lbValue pp = lb_emit_conv(p, xx.addr, alloc_type_pointer(args[i].type));
  6369. lb_emit_store(p, pp, args[i]);
  6370. x = lb_addr_load(p, xx);
  6371. }
  6372. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  6373. lbValue xx = lb_emit_struct_ev(p, x, cast(i32)j);
  6374. array_add(&processed_args, xx);
  6375. }
  6376. }
  6377. } else {
  6378. lbValue x = lb_emit_conv(p, args[i], new_type);
  6379. array_add(&processed_args, x);
  6380. }
  6381. }
  6382. if (inlining == ProcInlining_none) {
  6383. inlining = p->inlining;
  6384. }
  6385. Type *abi_rt = reduce_tuple_to_single_type(pt->Proc.abi_compat_result_type);
  6386. Type *rt = reduce_tuple_to_single_type(results);
  6387. if (pt->Proc.return_by_pointer) {
  6388. lbValue return_ptr = {};
  6389. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6390. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6391. return_ptr = p->return_ptr_hint_value;
  6392. p->return_ptr_hint_used = true;
  6393. }
  6394. }
  6395. if (return_ptr.value == nullptr) {
  6396. lbAddr r = lb_add_local_generated(p, rt, true);
  6397. return_ptr = r.addr;
  6398. }
  6399. GB_ASSERT(is_type_pointer(return_ptr.type));
  6400. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6401. result = lb_emit_load(p, return_ptr);
  6402. } else {
  6403. result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining);
  6404. if (abi_rt != rt) {
  6405. result = lb_emit_transmute(p, result, rt);
  6406. }
  6407. }
  6408. }
  6409. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6410. if (found != nullptr) {
  6411. Entity *e = *found;
  6412. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6413. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6414. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6415. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6416. GB_ASSERT(deferred_found != nullptr);
  6417. lbValue deferred = *deferred_found;
  6418. auto in_args = args;
  6419. Array<lbValue> result_as_args = {};
  6420. switch (kind) {
  6421. case DeferredProcedure_none:
  6422. break;
  6423. case DeferredProcedure_in:
  6424. result_as_args = in_args;
  6425. break;
  6426. case DeferredProcedure_out:
  6427. result_as_args = lb_value_to_array(p, result);
  6428. break;
  6429. case DeferredProcedure_in_out:
  6430. {
  6431. auto out_args = lb_value_to_array(p, result);
  6432. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  6433. array_copy(&result_as_args, in_args, 0);
  6434. array_copy(&result_as_args, out_args, in_args.count);
  6435. }
  6436. break;
  6437. }
  6438. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6439. }
  6440. }
  6441. return result;
  6442. }
  6443. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6444. Type *t = s.type;
  6445. GB_ASSERT(is_type_pointer(t));
  6446. Type *st = base_type(type_deref(t));
  6447. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6448. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6449. LLVMValueRef indices[2] = {};
  6450. indices[0] = llvm_zero(p->module);
  6451. indices[1] = lb_emit_conv(p, index, t_int).value;
  6452. Type *ptr = base_array_type(st);
  6453. lbValue res = {};
  6454. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6455. res.type = alloc_type_pointer(ptr);
  6456. return res;
  6457. }
  6458. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6459. Type *t = s.type;
  6460. GB_ASSERT(is_type_pointer(t));
  6461. Type *st = base_type(type_deref(t));
  6462. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6463. GB_ASSERT(0 <= index);
  6464. Type *ptr = base_array_type(st);
  6465. LLVMValueRef indices[2] = {
  6466. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6467. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6468. };
  6469. lbValue res = {};
  6470. if (lb_is_const(s)) {
  6471. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6472. } else {
  6473. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6474. }
  6475. res.type = alloc_type_pointer(ptr);
  6476. return res;
  6477. }
  6478. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6479. LLVMValueRef indices[1] = {index.value};
  6480. lbValue res = {};
  6481. res.type = ptr.type;
  6482. if (lb_is_const(ptr) && lb_is_const(index)) {
  6483. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6484. } else {
  6485. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6486. }
  6487. return res;
  6488. }
  6489. LLVMValueRef llvm_const_slice(lbValue data, lbValue len) {
  6490. GB_ASSERT(is_type_pointer(data.type));
  6491. GB_ASSERT(are_types_identical(len.type, t_int));
  6492. LLVMValueRef vals[2] = {
  6493. data.value,
  6494. len.value,
  6495. };
  6496. return LLVMConstStruct(vals, gb_count_of(vals), false);
  6497. }
  6498. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6499. Type *t = lb_addr_type(slice);
  6500. GB_ASSERT(is_type_slice(t));
  6501. lbValue ptr = lb_addr_get_ptr(p, slice);
  6502. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6503. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6504. }
  6505. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6506. Type *t = lb_addr_type(string);
  6507. GB_ASSERT(is_type_string(t));
  6508. lbValue ptr = lb_addr_get_ptr(p, string);
  6509. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6510. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6511. }
  6512. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6513. Type *t = base_type(string.type);
  6514. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6515. return lb_emit_struct_ev(p, string, 0);
  6516. }
  6517. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6518. Type *t = base_type(string.type);
  6519. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6520. return lb_emit_struct_ev(p, string, 1);
  6521. }
  6522. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6523. GB_ASSERT(is_type_cstring(value.type));
  6524. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6525. args[0] = lb_emit_conv(p, value, t_cstring);
  6526. return lb_emit_runtime_call(p, "cstring_len", args);
  6527. }
  6528. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6529. Type *t = type_deref(array_ptr.type);
  6530. GB_ASSERT(is_type_array(t));
  6531. return lb_emit_struct_ep(p, array_ptr, 0);
  6532. }
  6533. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6534. GB_ASSERT(is_type_slice(slice.type));
  6535. return lb_emit_struct_ev(p, slice, 0);
  6536. }
  6537. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6538. GB_ASSERT(is_type_slice(slice.type));
  6539. return lb_emit_struct_ev(p, slice, 1);
  6540. }
  6541. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6542. GB_ASSERT(is_type_dynamic_array(da.type));
  6543. return lb_emit_struct_ev(p, da, 0);
  6544. }
  6545. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6546. GB_ASSERT(is_type_dynamic_array(da.type));
  6547. return lb_emit_struct_ev(p, da, 1);
  6548. }
  6549. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6550. GB_ASSERT(is_type_dynamic_array(da.type));
  6551. return lb_emit_struct_ev(p, da, 2);
  6552. }
  6553. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6554. GB_ASSERT(is_type_dynamic_array(da.type));
  6555. return lb_emit_struct_ev(p, da, 3);
  6556. }
  6557. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6558. Type *t = base_type(value.type);
  6559. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6560. init_map_internal_types(t);
  6561. Type *gst = t->Map.generated_struct_type;
  6562. i32 index = 1;
  6563. lbValue entries = lb_emit_struct_ev(p, value, index);
  6564. return entries;
  6565. }
  6566. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6567. Type *t = base_type(type_deref(value.type));
  6568. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6569. init_map_internal_types(t);
  6570. Type *gst = t->Map.generated_struct_type;
  6571. i32 index = 1;
  6572. lbValue entries = lb_emit_struct_ep(p, value, index);
  6573. return entries;
  6574. }
  6575. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  6576. lbValue entries = lb_map_entries(p, value);
  6577. return lb_dynamic_array_len(p, entries);
  6578. }
  6579. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  6580. lbValue entries = lb_map_entries(p, value);
  6581. return lb_dynamic_array_cap(p, entries);
  6582. }
  6583. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  6584. Type *t = base_type(value.type);
  6585. bool is_ptr = false;
  6586. if (is_type_pointer(t)) {
  6587. is_ptr = true;
  6588. t = base_type(type_deref(t));
  6589. }
  6590. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6591. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6592. }
  6593. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  6594. t->Struct.soa_kind == StructSoa_Dynamic);
  6595. isize n = 0;
  6596. Type *elem = base_type(t->Struct.soa_elem);
  6597. if (elem->kind == Type_Struct) {
  6598. n = elem->Struct.fields.count;
  6599. } else if (elem->kind == Type_Array) {
  6600. n = elem->Array.count;
  6601. } else {
  6602. GB_PANIC("Unreachable");
  6603. }
  6604. if (is_ptr) {
  6605. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6606. return lb_emit_load(p, v);
  6607. }
  6608. return lb_emit_struct_ev(p, value, cast(i32)n);
  6609. }
  6610. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  6611. Type *t = base_type(value.type);
  6612. bool is_ptr = false;
  6613. if (is_type_pointer(t)) {
  6614. is_ptr = true;
  6615. t = base_type(type_deref(t));
  6616. }
  6617. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6618. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6619. }
  6620. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  6621. isize n = 0;
  6622. Type *elem = base_type(t->Struct.soa_elem);
  6623. if (elem->kind == Type_Struct) {
  6624. n = elem->Struct.fields.count+1;
  6625. } else if (elem->kind == Type_Array) {
  6626. n = elem->Array.count+1;
  6627. } else {
  6628. GB_PANIC("Unreachable");
  6629. }
  6630. if (is_ptr) {
  6631. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6632. return lb_emit_load(p, v);
  6633. }
  6634. return lb_emit_struct_ev(p, value, cast(i32)n);
  6635. }
  6636. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  6637. ast_node(ce, CallExpr, expr);
  6638. switch (id) {
  6639. case BuiltinProc_DIRECTIVE: {
  6640. ast_node(bd, BasicDirective, ce->proc);
  6641. String name = bd->name;
  6642. GB_ASSERT(name == "location");
  6643. String procedure = p->entity->token.string;
  6644. TokenPos pos = ast_token(ce->proc).pos;
  6645. if (ce->args.count > 0) {
  6646. Ast *ident = unselector_expr(ce->args[0]);
  6647. GB_ASSERT(ident->kind == Ast_Ident);
  6648. Entity *e = entity_of_node(ident);
  6649. GB_ASSERT(e != nullptr);
  6650. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  6651. procedure = e->parent_proc_decl->entity->token.string;
  6652. } else {
  6653. procedure = str_lit("");
  6654. }
  6655. pos = e->token.pos;
  6656. }
  6657. return lb_emit_source_code_location(p, procedure, pos);
  6658. }
  6659. case BuiltinProc_type_info_of: {
  6660. Ast *arg = ce->args[0];
  6661. TypeAndValue tav = type_and_value_of_expr(arg);
  6662. if (tav.mode == Addressing_Type) {
  6663. Type *t = default_type(type_of_expr(arg));
  6664. return lb_type_info(p->module, t);
  6665. }
  6666. GB_ASSERT(is_type_typeid(tav.type));
  6667. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6668. args[0] = lb_build_expr(p, arg);
  6669. return lb_emit_runtime_call(p, "__type_info_of", args);
  6670. }
  6671. case BuiltinProc_typeid_of: {
  6672. Ast *arg = ce->args[0];
  6673. TypeAndValue tav = type_and_value_of_expr(arg);
  6674. GB_ASSERT(tav.mode == Addressing_Type);
  6675. Type *t = default_type(type_of_expr(arg));
  6676. return lb_typeid(p->module, t);
  6677. }
  6678. case BuiltinProc_len: {
  6679. lbValue v = lb_build_expr(p, ce->args[0]);
  6680. Type *t = base_type(v.type);
  6681. if (is_type_pointer(t)) {
  6682. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6683. v = lb_emit_load(p, v);
  6684. t = type_deref(t);
  6685. }
  6686. if (is_type_cstring(t)) {
  6687. return lb_cstring_len(p, v);
  6688. } else if (is_type_string(t)) {
  6689. return lb_string_len(p, v);
  6690. } else if (is_type_array(t)) {
  6691. GB_PANIC("Array lengths are constant");
  6692. } else if (is_type_slice(t)) {
  6693. return lb_slice_len(p, v);
  6694. } else if (is_type_dynamic_array(t)) {
  6695. return lb_dynamic_array_len(p, v);
  6696. } else if (is_type_map(t)) {
  6697. return lb_map_len(p, v);
  6698. } else if (is_type_soa_struct(t)) {
  6699. return lb_soa_struct_len(p, v);
  6700. }
  6701. GB_PANIC("Unreachable");
  6702. break;
  6703. }
  6704. case BuiltinProc_cap: {
  6705. lbValue v = lb_build_expr(p, ce->args[0]);
  6706. Type *t = base_type(v.type);
  6707. if (is_type_pointer(t)) {
  6708. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6709. v = lb_emit_load(p, v);
  6710. t = type_deref(t);
  6711. }
  6712. if (is_type_string(t)) {
  6713. GB_PANIC("Unreachable");
  6714. } else if (is_type_array(t)) {
  6715. GB_PANIC("Array lengths are constant");
  6716. } else if (is_type_slice(t)) {
  6717. return lb_slice_len(p, v);
  6718. } else if (is_type_dynamic_array(t)) {
  6719. return lb_dynamic_array_cap(p, v);
  6720. } else if (is_type_map(t)) {
  6721. return lb_map_cap(p, v);
  6722. } else if (is_type_soa_struct(t)) {
  6723. return lb_soa_struct_cap(p, v);
  6724. }
  6725. GB_PANIC("Unreachable");
  6726. break;
  6727. }
  6728. case BuiltinProc_swizzle: {
  6729. isize index_count = ce->args.count-1;
  6730. if (is_type_simd_vector(tv.type)) {
  6731. lbValue vec = lb_build_expr(p, ce->args[0]);
  6732. if (index_count == 0) {
  6733. return vec;
  6734. }
  6735. unsigned mask_len = cast(unsigned)index_count;
  6736. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  6737. for (isize i = 1; i < ce->args.count; i++) {
  6738. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6739. GB_ASSERT(is_type_integer(tv.type));
  6740. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6741. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  6742. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  6743. }
  6744. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  6745. LLVMValueRef v1 = vec.value;
  6746. LLVMValueRef v2 = vec.value;
  6747. lbValue res = {};
  6748. res.type = tv.type;
  6749. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  6750. return res;
  6751. }
  6752. lbAddr addr = lb_build_addr(p, ce->args[0]);
  6753. if (index_count == 0) {
  6754. return lb_addr_load(p, addr);
  6755. }
  6756. lbValue src = lb_addr_get_ptr(p, addr);
  6757. // TODO(bill): Should this be zeroed or not?
  6758. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  6759. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  6760. for (i32 i = 1; i < ce->args.count; i++) {
  6761. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6762. GB_ASSERT(is_type_integer(tv.type));
  6763. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6764. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  6765. i32 dst_index = i-1;
  6766. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  6767. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  6768. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  6769. }
  6770. return lb_addr_load(p, dst);
  6771. }
  6772. case BuiltinProc_complex: {
  6773. lbValue real = lb_build_expr(p, ce->args[0]);
  6774. lbValue imag = lb_build_expr(p, ce->args[1]);
  6775. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6776. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6777. Type *ft = base_complex_elem_type(tv.type);
  6778. real = lb_emit_conv(p, real, ft);
  6779. imag = lb_emit_conv(p, imag, ft);
  6780. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  6781. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  6782. return lb_emit_load(p, dst);
  6783. }
  6784. case BuiltinProc_quaternion: {
  6785. lbValue real = lb_build_expr(p, ce->args[0]);
  6786. lbValue imag = lb_build_expr(p, ce->args[1]);
  6787. lbValue jmag = lb_build_expr(p, ce->args[2]);
  6788. lbValue kmag = lb_build_expr(p, ce->args[3]);
  6789. // @QuaternionLayout
  6790. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6791. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6792. Type *ft = base_complex_elem_type(tv.type);
  6793. real = lb_emit_conv(p, real, ft);
  6794. imag = lb_emit_conv(p, imag, ft);
  6795. jmag = lb_emit_conv(p, jmag, ft);
  6796. kmag = lb_emit_conv(p, kmag, ft);
  6797. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  6798. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  6799. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  6800. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  6801. return lb_emit_load(p, dst);
  6802. }
  6803. case BuiltinProc_real: {
  6804. lbValue val = lb_build_expr(p, ce->args[0]);
  6805. if (is_type_complex(val.type)) {
  6806. lbValue real = lb_emit_struct_ev(p, val, 0);
  6807. return lb_emit_conv(p, real, tv.type);
  6808. } else if (is_type_quaternion(val.type)) {
  6809. // @QuaternionLayout
  6810. lbValue real = lb_emit_struct_ev(p, val, 3);
  6811. return lb_emit_conv(p, real, tv.type);
  6812. }
  6813. GB_PANIC("invalid type for real");
  6814. return {};
  6815. }
  6816. case BuiltinProc_imag: {
  6817. lbValue val = lb_build_expr(p, ce->args[0]);
  6818. if (is_type_complex(val.type)) {
  6819. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6820. return lb_emit_conv(p, imag, tv.type);
  6821. } else if (is_type_quaternion(val.type)) {
  6822. // @QuaternionLayout
  6823. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6824. return lb_emit_conv(p, imag, tv.type);
  6825. }
  6826. GB_PANIC("invalid type for imag");
  6827. return {};
  6828. }
  6829. case BuiltinProc_jmag: {
  6830. lbValue val = lb_build_expr(p, ce->args[0]);
  6831. if (is_type_quaternion(val.type)) {
  6832. // @QuaternionLayout
  6833. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6834. return lb_emit_conv(p, imag, tv.type);
  6835. }
  6836. GB_PANIC("invalid type for jmag");
  6837. return {};
  6838. }
  6839. case BuiltinProc_kmag: {
  6840. lbValue val = lb_build_expr(p, ce->args[0]);
  6841. if (is_type_quaternion(val.type)) {
  6842. // @QuaternionLayout
  6843. lbValue imag = lb_emit_struct_ev(p, val, 2);
  6844. return lb_emit_conv(p, imag, tv.type);
  6845. }
  6846. GB_PANIC("invalid type for kmag");
  6847. return {};
  6848. }
  6849. case BuiltinProc_conj: {
  6850. lbValue val = lb_build_expr(p, ce->args[0]);
  6851. lbValue res = {};
  6852. Type *t = val.type;
  6853. if (is_type_complex(t)) {
  6854. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6855. lbValue real = lb_emit_struct_ev(p, val, 0);
  6856. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6857. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6858. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  6859. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  6860. } else if (is_type_quaternion(t)) {
  6861. // @QuaternionLayout
  6862. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6863. lbValue real = lb_emit_struct_ev(p, val, 3);
  6864. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6865. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  6866. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  6867. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6868. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  6869. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  6870. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  6871. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  6872. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  6873. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  6874. }
  6875. return lb_emit_load(p, res);
  6876. }
  6877. case BuiltinProc_expand_to_tuple: {
  6878. lbValue val = lb_build_expr(p, ce->args[0]);
  6879. Type *t = base_type(val.type);
  6880. if (!is_type_tuple(tv.type)) {
  6881. if (t->kind == Type_Struct) {
  6882. GB_ASSERT(t->Struct.fields.count == 1);
  6883. return lb_emit_struct_ev(p, val, 0);
  6884. } else if (t->kind == Type_Array) {
  6885. GB_ASSERT(t->Array.count == 1);
  6886. return lb_emit_array_epi(p, val, 0);
  6887. } else {
  6888. GB_PANIC("Unknown type of expand_to_tuple");
  6889. }
  6890. }
  6891. GB_ASSERT(is_type_tuple(tv.type));
  6892. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6893. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6894. if (t->kind == Type_Struct) {
  6895. for_array(src_index, t->Struct.fields) {
  6896. Entity *field = t->Struct.fields[src_index];
  6897. i32 field_index = field->Variable.field_index;
  6898. lbValue f = lb_emit_struct_ev(p, val, field_index);
  6899. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  6900. lb_emit_store(p, ep, f);
  6901. }
  6902. } else if (t->kind == Type_Array) {
  6903. // TODO(bill): Clean-up this code
  6904. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  6905. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  6906. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  6907. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  6908. lb_emit_store(p, ep, f);
  6909. }
  6910. } else {
  6911. GB_PANIC("Unknown type of expand_to_tuple");
  6912. }
  6913. return lb_emit_load(p, tuple);
  6914. }
  6915. case BuiltinProc_min: {
  6916. Type *t = type_of_expr(expr);
  6917. if (ce->args.count == 2) {
  6918. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6919. } else {
  6920. lbValue x = lb_build_expr(p, ce->args[0]);
  6921. for (isize i = 1; i < ce->args.count; i++) {
  6922. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  6923. }
  6924. return x;
  6925. }
  6926. }
  6927. case BuiltinProc_max: {
  6928. Type *t = type_of_expr(expr);
  6929. if (ce->args.count == 2) {
  6930. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6931. } else {
  6932. lbValue x = lb_build_expr(p, ce->args[0]);
  6933. for (isize i = 1; i < ce->args.count; i++) {
  6934. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  6935. }
  6936. return x;
  6937. }
  6938. }
  6939. case BuiltinProc_abs: {
  6940. lbValue x = lb_build_expr(p, ce->args[0]);
  6941. Type *t = x.type;
  6942. if (is_type_unsigned(t)) {
  6943. return x;
  6944. }
  6945. if (is_type_quaternion(t)) {
  6946. i64 sz = 8*type_size_of(t);
  6947. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6948. args[0] = x;
  6949. switch (sz) {
  6950. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  6951. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  6952. }
  6953. GB_PANIC("Unknown complex type");
  6954. } else if (is_type_complex(t)) {
  6955. i64 sz = 8*type_size_of(t);
  6956. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6957. args[0] = x;
  6958. switch (sz) {
  6959. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  6960. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  6961. }
  6962. GB_PANIC("Unknown complex type");
  6963. } else if (is_type_float(t)) {
  6964. i64 sz = 8*type_size_of(t);
  6965. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6966. args[0] = x;
  6967. switch (sz) {
  6968. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  6969. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  6970. }
  6971. GB_PANIC("Unknown float type");
  6972. }
  6973. lbValue zero = lb_const_nil(p->module, t);
  6974. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  6975. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  6976. return lb_emit_select(p, cond, neg, x);
  6977. }
  6978. case BuiltinProc_clamp:
  6979. return lb_emit_clamp(p, type_of_expr(expr),
  6980. lb_build_expr(p, ce->args[0]),
  6981. lb_build_expr(p, ce->args[1]),
  6982. lb_build_expr(p, ce->args[2]));
  6983. // "Intrinsics"
  6984. case BuiltinProc_alloca:
  6985. {
  6986. lbValue sz = lb_build_expr(p, ce->args[0]);
  6987. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  6988. lbValue res = {};
  6989. res.type = t_u8_ptr;
  6990. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  6991. LLVMSetAlignment(res.value, cast(unsigned)al);
  6992. return res;
  6993. }
  6994. case BuiltinProc_cpu_relax:
  6995. {
  6996. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  6997. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  6998. "pause", 5,
  6999. "", 0,
  7000. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7001. LLVMInlineAsmDialectATT
  7002. );
  7003. GB_ASSERT(the_asm != nullptr);
  7004. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7005. }
  7006. return {};
  7007. case BuiltinProc_atomic_fence:
  7008. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  7009. return {};
  7010. case BuiltinProc_atomic_fence_acq:
  7011. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  7012. return {};
  7013. case BuiltinProc_atomic_fence_rel:
  7014. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  7015. return {};
  7016. case BuiltinProc_atomic_fence_acqrel:
  7017. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  7018. return {};
  7019. case BuiltinProc_atomic_store:
  7020. case BuiltinProc_atomic_store_rel:
  7021. case BuiltinProc_atomic_store_relaxed:
  7022. case BuiltinProc_atomic_store_unordered: {
  7023. lbValue dst = lb_build_expr(p, ce->args[0]);
  7024. lbValue val = lb_build_expr(p, ce->args[1]);
  7025. val = lb_emit_conv(p, val, type_deref(dst.type));
  7026. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  7027. switch (id) {
  7028. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7029. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  7030. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7031. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7032. }
  7033. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7034. return {};
  7035. }
  7036. case BuiltinProc_atomic_load:
  7037. case BuiltinProc_atomic_load_acq:
  7038. case BuiltinProc_atomic_load_relaxed:
  7039. case BuiltinProc_atomic_load_unordered: {
  7040. lbValue dst = lb_build_expr(p, ce->args[0]);
  7041. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  7042. switch (id) {
  7043. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7044. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  7045. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7046. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7047. }
  7048. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7049. lbValue res = {};
  7050. res.value = instr;
  7051. res.type = type_deref(dst.type);
  7052. return res;
  7053. }
  7054. case BuiltinProc_atomic_add:
  7055. case BuiltinProc_atomic_add_acq:
  7056. case BuiltinProc_atomic_add_rel:
  7057. case BuiltinProc_atomic_add_acqrel:
  7058. case BuiltinProc_atomic_add_relaxed:
  7059. case BuiltinProc_atomic_sub:
  7060. case BuiltinProc_atomic_sub_acq:
  7061. case BuiltinProc_atomic_sub_rel:
  7062. case BuiltinProc_atomic_sub_acqrel:
  7063. case BuiltinProc_atomic_sub_relaxed:
  7064. case BuiltinProc_atomic_and:
  7065. case BuiltinProc_atomic_and_acq:
  7066. case BuiltinProc_atomic_and_rel:
  7067. case BuiltinProc_atomic_and_acqrel:
  7068. case BuiltinProc_atomic_and_relaxed:
  7069. case BuiltinProc_atomic_nand:
  7070. case BuiltinProc_atomic_nand_acq:
  7071. case BuiltinProc_atomic_nand_rel:
  7072. case BuiltinProc_atomic_nand_acqrel:
  7073. case BuiltinProc_atomic_nand_relaxed:
  7074. case BuiltinProc_atomic_or:
  7075. case BuiltinProc_atomic_or_acq:
  7076. case BuiltinProc_atomic_or_rel:
  7077. case BuiltinProc_atomic_or_acqrel:
  7078. case BuiltinProc_atomic_or_relaxed:
  7079. case BuiltinProc_atomic_xor:
  7080. case BuiltinProc_atomic_xor_acq:
  7081. case BuiltinProc_atomic_xor_rel:
  7082. case BuiltinProc_atomic_xor_acqrel:
  7083. case BuiltinProc_atomic_xor_relaxed:
  7084. case BuiltinProc_atomic_xchg:
  7085. case BuiltinProc_atomic_xchg_acq:
  7086. case BuiltinProc_atomic_xchg_rel:
  7087. case BuiltinProc_atomic_xchg_acqrel:
  7088. case BuiltinProc_atomic_xchg_relaxed: {
  7089. lbValue dst = lb_build_expr(p, ce->args[0]);
  7090. lbValue val = lb_build_expr(p, ce->args[1]);
  7091. val = lb_emit_conv(p, val, type_deref(dst.type));
  7092. LLVMAtomicRMWBinOp op = {};
  7093. LLVMAtomicOrdering ordering = {};
  7094. switch (id) {
  7095. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7096. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  7097. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  7098. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7099. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  7100. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7101. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  7102. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  7103. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7104. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  7105. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7106. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  7107. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  7108. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7109. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  7110. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7111. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  7112. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  7113. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7114. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  7115. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7116. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  7117. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  7118. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7119. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  7120. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7121. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  7122. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  7123. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7124. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  7125. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7126. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  7127. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  7128. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7129. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  7130. }
  7131. lbValue res = {};
  7132. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  7133. res.type = tv.type;
  7134. return res;
  7135. }
  7136. case BuiltinProc_atomic_cxchg:
  7137. case BuiltinProc_atomic_cxchg_acq:
  7138. case BuiltinProc_atomic_cxchg_rel:
  7139. case BuiltinProc_atomic_cxchg_acqrel:
  7140. case BuiltinProc_atomic_cxchg_relaxed:
  7141. case BuiltinProc_atomic_cxchg_failrelaxed:
  7142. case BuiltinProc_atomic_cxchg_failacq:
  7143. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  7144. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  7145. case BuiltinProc_atomic_cxchgweak:
  7146. case BuiltinProc_atomic_cxchgweak_acq:
  7147. case BuiltinProc_atomic_cxchgweak_rel:
  7148. case BuiltinProc_atomic_cxchgweak_acqrel:
  7149. case BuiltinProc_atomic_cxchgweak_relaxed:
  7150. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  7151. case BuiltinProc_atomic_cxchgweak_failacq:
  7152. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  7153. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  7154. Type *type = expr->tav.type;
  7155. lbValue address = lb_build_expr(p, ce->args[0]);
  7156. Type *elem = type_deref(address.type);
  7157. lbValue old_value = lb_build_expr(p, ce->args[1]);
  7158. lbValue new_value = lb_build_expr(p, ce->args[2]);
  7159. old_value = lb_emit_conv(p, old_value, elem);
  7160. new_value = lb_emit_conv(p, new_value, elem);
  7161. LLVMAtomicOrdering success_ordering = {};
  7162. LLVMAtomicOrdering failure_ordering = {};
  7163. LLVMBool weak = false;
  7164. switch (id) {
  7165. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7166. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7167. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7168. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7169. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7170. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7171. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  7172. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7173. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7174. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7175. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7176. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7177. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7178. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7179. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7180. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  7181. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7182. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7183. }
  7184. // TODO(bill): Figure out how to make it weak
  7185. LLVMBool single_threaded = weak;
  7186. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  7187. p->builder, address.value,
  7188. old_value.value, new_value.value,
  7189. success_ordering,
  7190. failure_ordering,
  7191. single_threaded
  7192. );
  7193. GB_ASSERT(tv.type->kind == Type_Tuple);
  7194. Type *fix_typed = alloc_type_tuple();
  7195. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  7196. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  7197. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7198. lbValue res = {};
  7199. res.value = value;
  7200. res.type = fix_typed;
  7201. return res;
  7202. }
  7203. }
  7204. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  7205. return {};
  7206. }
  7207. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  7208. switch (param_value.kind) {
  7209. case ParameterValue_Constant:
  7210. if (is_type_constant_type(parameter_type)) {
  7211. return lb_const_value(p->module, parameter_type, param_value.value);
  7212. } else {
  7213. ExactValue ev = param_value.value;
  7214. lbValue arg = {};
  7215. Type *type = type_of_expr(param_value.original_ast_expr);
  7216. if (type != nullptr) {
  7217. arg = lb_const_value(p->module, type, ev);
  7218. } else {
  7219. arg = lb_const_value(p->module, parameter_type, param_value.value);
  7220. }
  7221. return lb_emit_conv(p, arg, parameter_type);
  7222. }
  7223. case ParameterValue_Nil:
  7224. return lb_const_nil(p->module, parameter_type);
  7225. case ParameterValue_Location:
  7226. {
  7227. String proc_name = {};
  7228. if (p->entity != nullptr) {
  7229. proc_name = p->entity->token.string;
  7230. }
  7231. return lb_emit_source_code_location(p, proc_name, pos);
  7232. }
  7233. case ParameterValue_Value:
  7234. return lb_build_expr(p, param_value.ast_value);
  7235. }
  7236. return lb_const_nil(p->module, parameter_type);
  7237. }
  7238. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  7239. lbModule *m = p->module;
  7240. TypeAndValue tv = type_and_value_of_expr(expr);
  7241. ast_node(ce, CallExpr, expr);
  7242. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  7243. AddressingMode proc_mode = proc_tv.mode;
  7244. if (proc_mode == Addressing_Type) {
  7245. GB_ASSERT(ce->args.count == 1);
  7246. lbValue x = lb_build_expr(p, ce->args[0]);
  7247. lbValue y = lb_emit_conv(p, x, tv.type);
  7248. return y;
  7249. }
  7250. Ast *pexpr = unparen_expr(ce->proc);
  7251. if (proc_mode == Addressing_Builtin) {
  7252. Entity *e = entity_of_node(pexpr);
  7253. BuiltinProcId id = BuiltinProc_Invalid;
  7254. if (e != nullptr) {
  7255. id = cast(BuiltinProcId)e->Builtin.id;
  7256. } else {
  7257. id = BuiltinProc_DIRECTIVE;
  7258. }
  7259. return lb_build_builtin_proc(p, expr, tv, id);
  7260. }
  7261. // NOTE(bill): Regular call
  7262. lbValue value = {};
  7263. Ast *proc_expr = unparen_expr(ce->proc);
  7264. if (proc_expr->tav.mode == Addressing_Constant) {
  7265. ExactValue v = proc_expr->tav.value;
  7266. switch (v.kind) {
  7267. case ExactValue_Integer:
  7268. {
  7269. u64 u = big_int_to_u64(&v.value_integer);
  7270. lbValue x = {};
  7271. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7272. x.type = t_uintptr;
  7273. x = lb_emit_conv(p, x, t_rawptr);
  7274. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7275. break;
  7276. }
  7277. case ExactValue_Pointer:
  7278. {
  7279. u64 u = cast(u64)v.value_pointer;
  7280. lbValue x = {};
  7281. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7282. x.type = t_uintptr;
  7283. x = lb_emit_conv(p, x, t_rawptr);
  7284. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7285. break;
  7286. }
  7287. }
  7288. }
  7289. if (value.value == nullptr) {
  7290. value = lb_build_expr(p, proc_expr);
  7291. }
  7292. GB_ASSERT(value.value != nullptr);
  7293. Type *proc_type_ = base_type(value.type);
  7294. GB_ASSERT(proc_type_->kind == Type_Proc);
  7295. TypeProc *pt = &proc_type_->Proc;
  7296. set_procedure_abi_types(proc_type_);
  7297. if (is_call_expr_field_value(ce)) {
  7298. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  7299. for_array(arg_index, ce->args) {
  7300. Ast *arg = ce->args[arg_index];
  7301. ast_node(fv, FieldValue, arg);
  7302. GB_ASSERT(fv->field->kind == Ast_Ident);
  7303. String name = fv->field->Ident.token.string;
  7304. isize index = lookup_procedure_parameter(pt, name);
  7305. GB_ASSERT(index >= 0);
  7306. TypeAndValue tav = type_and_value_of_expr(fv->value);
  7307. if (tav.mode == Addressing_Type) {
  7308. args[index] = lb_const_nil(m, tav.type);
  7309. } else {
  7310. args[index] = lb_build_expr(p, fv->value);
  7311. }
  7312. }
  7313. TypeTuple *params = &pt->params->Tuple;
  7314. for (isize i = 0; i < args.count; i++) {
  7315. Entity *e = params->variables[i];
  7316. if (e->kind == Entity_TypeName) {
  7317. args[i] = lb_const_nil(m, e->type);
  7318. } else if (e->kind == Entity_Constant) {
  7319. continue;
  7320. } else {
  7321. GB_ASSERT(e->kind == Entity_Variable);
  7322. if (args[i].value == nullptr) {
  7323. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7324. } else {
  7325. args[i] = lb_emit_conv(p, args[i], e->type);
  7326. }
  7327. }
  7328. }
  7329. for (isize i = 0; i < args.count; i++) {
  7330. Entity *e = params->variables[i];
  7331. if (args[i].type == nullptr) {
  7332. continue;
  7333. } else if (is_type_untyped_nil(args[i].type)) {
  7334. args[i] = lb_const_nil(m, e->type);
  7335. } else if (is_type_untyped_undef(args[i].type)) {
  7336. args[i] = lb_const_undef(m, e->type);
  7337. }
  7338. }
  7339. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  7340. }
  7341. isize arg_index = 0;
  7342. isize arg_count = 0;
  7343. for_array(i, ce->args) {
  7344. Ast *arg = ce->args[i];
  7345. TypeAndValue tav = type_and_value_of_expr(arg);
  7346. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  7347. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  7348. Type *at = tav.type;
  7349. if (at->kind == Type_Tuple) {
  7350. arg_count += at->Tuple.variables.count;
  7351. } else {
  7352. arg_count++;
  7353. }
  7354. }
  7355. isize param_count = 0;
  7356. if (pt->params) {
  7357. GB_ASSERT(pt->params->kind == Type_Tuple);
  7358. param_count = pt->params->Tuple.variables.count;
  7359. }
  7360. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  7361. isize variadic_index = pt->variadic_index;
  7362. bool variadic = pt->variadic && variadic_index >= 0;
  7363. bool vari_expand = ce->ellipsis.pos.line != 0;
  7364. bool is_c_vararg = pt->c_vararg;
  7365. String proc_name = {};
  7366. if (p->entity != nullptr) {
  7367. proc_name = p->entity->token.string;
  7368. }
  7369. TokenPos pos = ast_token(ce->proc).pos;
  7370. TypeTuple *param_tuple = nullptr;
  7371. if (pt->params) {
  7372. GB_ASSERT(pt->params->kind == Type_Tuple);
  7373. param_tuple = &pt->params->Tuple;
  7374. }
  7375. for_array(i, ce->args) {
  7376. Ast *arg = ce->args[i];
  7377. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  7378. if (arg_tv.mode == Addressing_Type) {
  7379. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  7380. } else {
  7381. lbValue a = lb_build_expr(p, arg);
  7382. Type *at = a.type;
  7383. if (at->kind == Type_Tuple) {
  7384. for_array(i, at->Tuple.variables) {
  7385. Entity *e = at->Tuple.variables[i];
  7386. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  7387. args[arg_index++] = v;
  7388. }
  7389. } else {
  7390. args[arg_index++] = a;
  7391. }
  7392. }
  7393. }
  7394. if (param_count > 0) {
  7395. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7396. GB_ASSERT(param_count < 1000000);
  7397. if (arg_count < param_count) {
  7398. isize end = cast(isize)param_count;
  7399. if (variadic) {
  7400. end = variadic_index;
  7401. }
  7402. while (arg_index < end) {
  7403. Entity *e = param_tuple->variables[arg_index];
  7404. GB_ASSERT(e->kind == Entity_Variable);
  7405. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7406. }
  7407. }
  7408. if (is_c_vararg) {
  7409. GB_ASSERT(variadic);
  7410. GB_ASSERT(!vari_expand);
  7411. isize i = 0;
  7412. for (; i < variadic_index; i++) {
  7413. Entity *e = param_tuple->variables[i];
  7414. if (e->kind == Entity_Variable) {
  7415. args[i] = lb_emit_conv(p, args[i], e->type);
  7416. }
  7417. }
  7418. Type *variadic_type = param_tuple->variables[i]->type;
  7419. GB_ASSERT(is_type_slice(variadic_type));
  7420. variadic_type = base_type(variadic_type)->Slice.elem;
  7421. if (!is_type_any(variadic_type)) {
  7422. for (; i < arg_count; i++) {
  7423. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7424. }
  7425. } else {
  7426. for (; i < arg_count; i++) {
  7427. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7428. }
  7429. }
  7430. } else if (variadic) {
  7431. isize i = 0;
  7432. for (; i < variadic_index; i++) {
  7433. Entity *e = param_tuple->variables[i];
  7434. if (e->kind == Entity_Variable) {
  7435. args[i] = lb_emit_conv(p, args[i], e->type);
  7436. }
  7437. }
  7438. if (!vari_expand) {
  7439. Type *variadic_type = param_tuple->variables[i]->type;
  7440. GB_ASSERT(is_type_slice(variadic_type));
  7441. variadic_type = base_type(variadic_type)->Slice.elem;
  7442. for (; i < arg_count; i++) {
  7443. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7444. }
  7445. }
  7446. } else {
  7447. for (isize i = 0; i < param_count; i++) {
  7448. Entity *e = param_tuple->variables[i];
  7449. if (e->kind == Entity_Variable) {
  7450. if (args[i].value == nullptr) {
  7451. continue;
  7452. }
  7453. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7454. args[i] = lb_emit_conv(p, args[i], e->type);
  7455. }
  7456. }
  7457. }
  7458. if (variadic && !vari_expand && !is_c_vararg) {
  7459. // variadic call argument generation
  7460. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7461. Type *elem_type = base_type(slice_type)->Slice.elem;
  7462. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7463. isize slice_len = arg_count+1 - (variadic_index+1);
  7464. if (slice_len > 0) {
  7465. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7466. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7467. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7468. lb_emit_store(p, addr, args[i]);
  7469. }
  7470. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7471. lbValue len = lb_const_int(m, t_int, slice_len);
  7472. lb_fill_slice(p, slice, base_elem, len);
  7473. }
  7474. arg_count = param_count;
  7475. args[variadic_index] = lb_addr_load(p, slice);
  7476. }
  7477. }
  7478. if (variadic && variadic_index+1 < param_count) {
  7479. for (isize i = variadic_index+1; i < param_count; i++) {
  7480. Entity *e = param_tuple->variables[i];
  7481. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7482. }
  7483. }
  7484. isize final_count = param_count;
  7485. if (is_c_vararg) {
  7486. final_count = arg_count;
  7487. }
  7488. if (param_tuple != nullptr) {
  7489. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7490. Entity *e = param_tuple->variables[i];
  7491. if (args[i].type == nullptr) {
  7492. continue;
  7493. } else if (is_type_untyped_nil(args[i].type)) {
  7494. args[i] = lb_const_nil(m, e->type);
  7495. } else if (is_type_untyped_undef(args[i].type)) {
  7496. args[i] = lb_const_undef(m, e->type);
  7497. }
  7498. }
  7499. }
  7500. auto call_args = array_slice(args, 0, final_count);
  7501. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  7502. }
  7503. bool lb_is_const(lbValue value) {
  7504. LLVMValueRef v = value.value;
  7505. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  7506. // TODO(bill): Is this correct behaviour?
  7507. return true;
  7508. }
  7509. if (LLVMIsConstant(v)) {
  7510. return true;
  7511. }
  7512. return false;
  7513. }
  7514. bool lb_is_const_nil(lbValue value) {
  7515. LLVMValueRef v = value.value;
  7516. if (LLVMIsConstant(v)) {
  7517. if (LLVMIsAConstantAggregateZero(v)) {
  7518. return true;
  7519. } else if (LLVMIsAConstantPointerNull(v)) {
  7520. return true;
  7521. }
  7522. }
  7523. return false;
  7524. }
  7525. String lb_get_const_string(lbModule *m, lbValue value) {
  7526. GB_ASSERT(lb_is_const(value));
  7527. Type *t = base_type(value.type);
  7528. GB_ASSERT(are_types_identical(t, t_string));
  7529. unsigned ptr_indices[1] = {0};
  7530. unsigned len_indices[1] = {1};
  7531. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  7532. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  7533. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  7534. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  7535. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  7536. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  7537. size_t length = 0;
  7538. char const *text = LLVMGetAsString(underlying_ptr, &length);
  7539. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  7540. return make_string(cast(u8 const *)text, real_length);
  7541. }
  7542. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  7543. GB_ASSERT(is_type_pointer(addr.type));
  7544. Type *type = type_deref(addr.type);
  7545. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  7546. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  7547. }
  7548. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7549. AstPackage *pkg = m->info->runtime_package;
  7550. Entity *e = scope_lookup_current(pkg->scope, name);
  7551. lbValue *found = nullptr;
  7552. if (m != e->code_gen_module) {
  7553. gb_mutex_lock(&m->mutex);
  7554. }
  7555. found = map_get(&e->code_gen_module->values, hash_entity(e));
  7556. if (m != e->code_gen_module) {
  7557. gb_mutex_unlock(&m->mutex);
  7558. }
  7559. GB_ASSERT(found != nullptr);
  7560. return found->value;
  7561. }
  7562. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  7563. Type *vt = core_type(value.type);
  7564. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  7565. // TODO(bill): lb_emit_byte_swap
  7566. lbValue res = {};
  7567. res.type = platform_type;
  7568. res.value = value.value;
  7569. int sz = cast(int)type_size_of(vt);
  7570. if (sz > 1) {
  7571. if (is_type_float(platform_type)) {
  7572. String name = {};
  7573. switch (sz) {
  7574. case 4: name = str_lit("bswap_f32"); break;
  7575. case 8: name = str_lit("bswap_f64"); break;
  7576. default: GB_PANIC("unhandled byteswap size"); break;
  7577. }
  7578. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7579. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7580. } else {
  7581. GB_ASSERT(is_type_integer(platform_type));
  7582. String name = {};
  7583. switch (sz) {
  7584. case 2: name = str_lit("bswap_16"); break;
  7585. case 4: name = str_lit("bswap_32"); break;
  7586. case 8: name = str_lit("bswap_64"); break;
  7587. case 16: name = str_lit("bswap_128"); break;
  7588. default: GB_PANIC("unhandled byteswap size"); break;
  7589. }
  7590. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7591. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7592. }
  7593. }
  7594. return res;
  7595. }
  7596. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  7597. lbLoopData data = {};
  7598. lbValue max = lb_const_int(p->module, t_int, count);
  7599. data.idx_addr = lb_add_local_generated(p, index_type, true);
  7600. data.body = lb_create_block(p, "loop.body");
  7601. data.done = lb_create_block(p, "loop.done");
  7602. data.loop = lb_create_block(p, "loop.loop");
  7603. lb_emit_jump(p, data.loop);
  7604. lb_start_block(p, data.loop);
  7605. data.idx = lb_addr_load(p, data.idx_addr);
  7606. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  7607. lb_emit_if(p, cond, data.body, data.done);
  7608. lb_start_block(p, data.body);
  7609. return data;
  7610. }
  7611. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  7612. if (data.idx_addr.addr.value != nullptr) {
  7613. lb_emit_increment(p, data.idx_addr.addr);
  7614. lb_emit_jump(p, data.loop);
  7615. lb_start_block(p, data.done);
  7616. }
  7617. }
  7618. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  7619. lbValue res = {};
  7620. res.type = t_llvm_bool;
  7621. Type *t = x.type;
  7622. if (is_type_pointer(t)) {
  7623. if (op_kind == Token_CmpEq) {
  7624. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7625. } else if (op_kind == Token_NotEq) {
  7626. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7627. }
  7628. return res;
  7629. } else if (is_type_cstring(t)) {
  7630. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  7631. if (op_kind == Token_CmpEq) {
  7632. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  7633. } else if (op_kind == Token_NotEq) {
  7634. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  7635. }
  7636. return res;
  7637. } else if (is_type_proc(t)) {
  7638. if (op_kind == Token_CmpEq) {
  7639. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7640. } else if (op_kind == Token_NotEq) {
  7641. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7642. }
  7643. return res;
  7644. } else if (is_type_any(t)) {
  7645. // TODO(bill): is this correct behaviour for nil comparison for any?
  7646. lbValue data = lb_emit_struct_ev(p, x, 0);
  7647. lbValue ti = lb_emit_struct_ev(p, x, 1);
  7648. if (op_kind == Token_CmpEq) {
  7649. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  7650. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  7651. res.value = LLVMBuildOr(p->builder, a, b, "");
  7652. return res;
  7653. } else if (op_kind == Token_NotEq) {
  7654. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  7655. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  7656. res.value = LLVMBuildAnd(p->builder, a, b, "");
  7657. return res;
  7658. }
  7659. } else if (is_type_slice(t)) {
  7660. lbValue len = lb_emit_struct_ev(p, x, 1);
  7661. if (op_kind == Token_CmpEq) {
  7662. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7663. return res;
  7664. } else if (op_kind == Token_NotEq) {
  7665. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7666. return res;
  7667. }
  7668. } else if (is_type_dynamic_array(t)) {
  7669. lbValue cap = lb_emit_struct_ev(p, x, 2);
  7670. if (op_kind == Token_CmpEq) {
  7671. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7672. return res;
  7673. } else if (op_kind == Token_NotEq) {
  7674. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7675. return res;
  7676. }
  7677. } else if (is_type_map(t)) {
  7678. lbValue cap = lb_map_cap(p, x);
  7679. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  7680. } else if (is_type_union(t)) {
  7681. if (type_size_of(t) == 0) {
  7682. if (op_kind == Token_CmpEq) {
  7683. return lb_const_bool(p->module, t_llvm_bool, true);
  7684. } else if (op_kind == Token_NotEq) {
  7685. return lb_const_bool(p->module, t_llvm_bool, false);
  7686. }
  7687. } else {
  7688. lbValue tag = lb_emit_union_tag_value(p, x);
  7689. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  7690. }
  7691. } else if (is_type_typeid(t)) {
  7692. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  7693. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  7694. } else if (is_type_bit_field(t)) {
  7695. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7696. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7697. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7698. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7699. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7700. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7701. return res;
  7702. } else if (is_type_soa_struct(t)) {
  7703. Type *bt = base_type(t);
  7704. if (bt->Struct.soa_kind == StructSoa_Slice) {
  7705. lbValue len = lb_soa_struct_len(p, x);
  7706. if (op_kind == Token_CmpEq) {
  7707. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7708. return res;
  7709. } else if (op_kind == Token_NotEq) {
  7710. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7711. return res;
  7712. }
  7713. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  7714. lbValue cap = lb_soa_struct_cap(p, x);
  7715. if (op_kind == Token_CmpEq) {
  7716. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7717. return res;
  7718. } else if (op_kind == Token_NotEq) {
  7719. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7720. return res;
  7721. }
  7722. }
  7723. } else if (is_type_struct(t) && type_has_nil(t)) {
  7724. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7725. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7726. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7727. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7728. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7729. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7730. return res;
  7731. }
  7732. return {};
  7733. }
  7734. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  7735. Type *a = core_type(left.type);
  7736. Type *b = core_type(right.type);
  7737. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  7738. lbValue nil_check = {};
  7739. if (is_type_untyped_nil(left.type)) {
  7740. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  7741. } else if (is_type_untyped_nil(right.type)) {
  7742. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  7743. }
  7744. if (nil_check.value != nullptr) {
  7745. return nil_check;
  7746. }
  7747. if (are_types_identical(a, b)) {
  7748. // NOTE(bill): No need for a conversion
  7749. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  7750. left = lb_emit_conv(p, left, right.type);
  7751. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  7752. right = lb_emit_conv(p, right, left.type);
  7753. } else {
  7754. Type *lt = left.type;
  7755. Type *rt = right.type;
  7756. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  7757. Type *blt = base_type(lt);
  7758. Type *brt = base_type(rt);
  7759. GB_ASSERT(is_type_bit_field_value(blt));
  7760. GB_ASSERT(is_type_bit_field_value(brt));
  7761. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  7762. i64 bytes = bits / 8;
  7763. switch (bytes) {
  7764. case 1:
  7765. left = lb_emit_conv(p, left, t_u8);
  7766. right = lb_emit_conv(p, right, t_u8);
  7767. break;
  7768. case 2:
  7769. left = lb_emit_conv(p, left, t_u16);
  7770. right = lb_emit_conv(p, right, t_u16);
  7771. break;
  7772. case 4:
  7773. left = lb_emit_conv(p, left, t_u32);
  7774. right = lb_emit_conv(p, right, t_u32);
  7775. break;
  7776. case 8:
  7777. left = lb_emit_conv(p, left, t_u64);
  7778. right = lb_emit_conv(p, right, t_u64);
  7779. break;
  7780. default: GB_PANIC("Unknown integer size"); break;
  7781. }
  7782. }
  7783. lt = left.type;
  7784. rt = right.type;
  7785. i64 ls = type_size_of(lt);
  7786. i64 rs = type_size_of(rt);
  7787. if (ls < rs) {
  7788. left = lb_emit_conv(p, left, rt);
  7789. } else if (ls > rs) {
  7790. right = lb_emit_conv(p, right, lt);
  7791. } else {
  7792. right = lb_emit_conv(p, right, lt);
  7793. }
  7794. }
  7795. if (is_type_array(a)) {
  7796. Type *tl = base_type(a);
  7797. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  7798. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  7799. TokenKind cmp_op = Token_And;
  7800. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  7801. if (op_kind == Token_NotEq) {
  7802. res = lb_const_bool(p->module, t_llvm_bool, false);
  7803. cmp_op = Token_Or;
  7804. } else if (op_kind == Token_CmpEq) {
  7805. res = lb_const_bool(p->module, t_llvm_bool, true);
  7806. cmp_op = Token_And;
  7807. }
  7808. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  7809. i32 count = cast(i32)tl->Array.count;
  7810. if (inline_array_arith) {
  7811. // inline
  7812. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7813. lb_addr_store(p, val, res);
  7814. for (i32 i = 0; i < count; i++) {
  7815. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  7816. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  7817. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7818. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7819. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7820. }
  7821. return lb_addr_load(p, val);
  7822. } else {
  7823. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  7824. // TODO(bill): Test to see if this is actually faster!!!!
  7825. auto args = array_make<lbValue>(permanent_allocator(), 3);
  7826. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7827. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  7828. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  7829. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  7830. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  7831. return lb_emit_conv(p, res, t_bool);
  7832. } else {
  7833. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7834. lb_addr_store(p, val, res);
  7835. auto loop_data = lb_loop_start(p, count, t_i32);
  7836. {
  7837. lbValue i = loop_data.idx;
  7838. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  7839. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  7840. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7841. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7842. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7843. }
  7844. lb_loop_end(p, loop_data);
  7845. return lb_addr_load(p, val);
  7846. }
  7847. }
  7848. }
  7849. if (is_type_string(a)) {
  7850. if (is_type_cstring(a)) {
  7851. left = lb_emit_conv(p, left, t_string);
  7852. right = lb_emit_conv(p, right, t_string);
  7853. }
  7854. char const *runtime_procedure = nullptr;
  7855. switch (op_kind) {
  7856. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  7857. case Token_NotEq: runtime_procedure = "string_ne"; break;
  7858. case Token_Lt: runtime_procedure = "string_lt"; break;
  7859. case Token_Gt: runtime_procedure = "string_gt"; break;
  7860. case Token_LtEq: runtime_procedure = "string_le"; break;
  7861. case Token_GtEq: runtime_procedure = "string_gt"; break;
  7862. }
  7863. GB_ASSERT(runtime_procedure != nullptr);
  7864. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7865. args[0] = left;
  7866. args[1] = right;
  7867. return lb_emit_runtime_call(p, runtime_procedure, args);
  7868. }
  7869. if (is_type_complex(a)) {
  7870. char const *runtime_procedure = "";
  7871. i64 sz = 8*type_size_of(a);
  7872. switch (sz) {
  7873. case 64:
  7874. switch (op_kind) {
  7875. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  7876. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  7877. }
  7878. break;
  7879. case 128:
  7880. switch (op_kind) {
  7881. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  7882. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  7883. }
  7884. break;
  7885. }
  7886. GB_ASSERT(runtime_procedure != nullptr);
  7887. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7888. args[0] = left;
  7889. args[1] = right;
  7890. return lb_emit_runtime_call(p, runtime_procedure, args);
  7891. }
  7892. if (is_type_quaternion(a)) {
  7893. char const *runtime_procedure = "";
  7894. i64 sz = 8*type_size_of(a);
  7895. switch (sz) {
  7896. case 128:
  7897. switch (op_kind) {
  7898. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  7899. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  7900. }
  7901. break;
  7902. case 256:
  7903. switch (op_kind) {
  7904. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  7905. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  7906. }
  7907. break;
  7908. }
  7909. GB_ASSERT(runtime_procedure != nullptr);
  7910. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7911. args[0] = left;
  7912. args[1] = right;
  7913. return lb_emit_runtime_call(p, runtime_procedure, args);
  7914. }
  7915. if (is_type_bit_set(a)) {
  7916. switch (op_kind) {
  7917. case Token_Lt:
  7918. case Token_LtEq:
  7919. case Token_Gt:
  7920. case Token_GtEq:
  7921. {
  7922. Type *it = bit_set_to_int(a);
  7923. lbValue lhs = lb_emit_transmute(p, left, it);
  7924. lbValue rhs = lb_emit_transmute(p, right, it);
  7925. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  7926. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  7927. // (lhs & rhs) == lhs
  7928. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  7929. res.type = t_llvm_bool;
  7930. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  7931. // (lhs & rhs) == rhs
  7932. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  7933. res.type = t_llvm_bool;
  7934. }
  7935. // NOTE(bill): Strict subsets
  7936. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  7937. // res &~ (lhs == rhs)
  7938. lbValue eq = {};
  7939. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  7940. eq.type = t_llvm_bool;
  7941. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  7942. }
  7943. return res;
  7944. }
  7945. case Token_CmpEq:
  7946. case Token_NotEq:
  7947. {
  7948. LLVMIntPredicate pred = {};
  7949. switch (op_kind) {
  7950. case Token_CmpEq: pred = LLVMIntEQ; break;
  7951. case Token_NotEq: pred = LLVMIntNE; break;
  7952. }
  7953. lbValue res = {};
  7954. res.type = t_llvm_bool;
  7955. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7956. return res;
  7957. }
  7958. }
  7959. }
  7960. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  7961. Type *t = left.type;
  7962. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  7963. Type *platform_type = integer_endian_type_to_platform_type(t);
  7964. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  7965. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  7966. left = x;
  7967. right = y;
  7968. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  7969. Type *platform_type = integer_endian_type_to_platform_type(t);
  7970. lbValue x = lb_emit_conv(p, left, platform_type);
  7971. lbValue y = lb_emit_conv(p, right, platform_type);
  7972. left = x;
  7973. right = y;
  7974. }
  7975. }
  7976. a = core_type(left.type);
  7977. b = core_type(right.type);
  7978. lbValue res = {};
  7979. res.type = t_llvm_bool;
  7980. if (is_type_integer(a) ||
  7981. is_type_boolean(a) ||
  7982. is_type_pointer(a) ||
  7983. is_type_proc(a) ||
  7984. is_type_enum(a)) {
  7985. LLVMIntPredicate pred = {};
  7986. if (is_type_unsigned(left.type)) {
  7987. switch (op_kind) {
  7988. case Token_Gt: pred = LLVMIntUGT; break;
  7989. case Token_GtEq: pred = LLVMIntUGE; break;
  7990. case Token_Lt: pred = LLVMIntULT; break;
  7991. case Token_LtEq: pred = LLVMIntULE; break;
  7992. }
  7993. } else {
  7994. switch (op_kind) {
  7995. case Token_Gt: pred = LLVMIntSGT; break;
  7996. case Token_GtEq: pred = LLVMIntSGE; break;
  7997. case Token_Lt: pred = LLVMIntSLT; break;
  7998. case Token_LtEq: pred = LLVMIntSLE; break;
  7999. }
  8000. }
  8001. switch (op_kind) {
  8002. case Token_CmpEq: pred = LLVMIntEQ; break;
  8003. case Token_NotEq: pred = LLVMIntNE; break;
  8004. }
  8005. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8006. } else if (is_type_float(a)) {
  8007. LLVMRealPredicate pred = {};
  8008. switch (op_kind) {
  8009. case Token_CmpEq: pred = LLVMRealOEQ; break;
  8010. case Token_Gt: pred = LLVMRealOGT; break;
  8011. case Token_GtEq: pred = LLVMRealOGE; break;
  8012. case Token_Lt: pred = LLVMRealOLT; break;
  8013. case Token_LtEq: pred = LLVMRealOLE; break;
  8014. case Token_NotEq: pred = LLVMRealONE; break;
  8015. }
  8016. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  8017. } else if (is_type_typeid(a)) {
  8018. LLVMIntPredicate pred = {};
  8019. switch (op_kind) {
  8020. case Token_Gt: pred = LLVMIntUGT; break;
  8021. case Token_GtEq: pred = LLVMIntUGE; break;
  8022. case Token_Lt: pred = LLVMIntULT; break;
  8023. case Token_LtEq: pred = LLVMIntULE; break;
  8024. case Token_CmpEq: pred = LLVMIntEQ; break;
  8025. case Token_NotEq: pred = LLVMIntNE; break;
  8026. }
  8027. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8028. } else {
  8029. 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)));
  8030. }
  8031. return res;
  8032. }
  8033. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  8034. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  8035. if (found != nullptr) {
  8036. lbValue value = {};
  8037. value.value = (*found)->value;
  8038. value.type = (*found)->type;
  8039. return value;
  8040. }
  8041. ast_node(pl, ProcLit, expr);
  8042. // NOTE(bill): Generate a new name
  8043. // parent$count
  8044. isize name_len = prefix_name.len + 1 + 8 + 1;
  8045. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  8046. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  8047. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  8048. String name = make_string((u8 *)name_text, name_len-1);
  8049. Type *type = type_of_expr(expr);
  8050. set_procedure_abi_types(type);
  8051. Token token = {};
  8052. token.pos = ast_token(expr).pos;
  8053. token.kind = Token_Ident;
  8054. token.string = name;
  8055. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  8056. e->decl_info = pl->decl;
  8057. lbProcedure *p = lb_create_procedure(m, e);
  8058. lbValue value = {};
  8059. value.value = p->value;
  8060. value.type = p->type;
  8061. array_add(&m->procedures_to_generate, p);
  8062. if (parent != nullptr) {
  8063. array_add(&parent->children, p);
  8064. } else {
  8065. string_map_set(&m->members, name, value);
  8066. }
  8067. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  8068. return value;
  8069. }
  8070. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  8071. lbModule *m = p->module;
  8072. Type *src_type = value.type;
  8073. bool is_ptr = is_type_pointer(src_type);
  8074. bool is_tuple = true;
  8075. Type *tuple = type;
  8076. if (type->kind != Type_Tuple) {
  8077. is_tuple = false;
  8078. tuple = make_optional_ok_type(type);
  8079. }
  8080. lbAddr v = lb_add_local_generated(p, tuple, true);
  8081. if (is_ptr) {
  8082. value = lb_emit_load(p, value);
  8083. }
  8084. Type *src = base_type(type_deref(src_type));
  8085. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  8086. Type *dst = tuple->Tuple.variables[0]->type;
  8087. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  8088. lbValue tag = {};
  8089. lbValue dst_tag = {};
  8090. lbValue cond = {};
  8091. lbValue data = {};
  8092. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8093. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8094. if (is_type_union_maybe_pointer(src)) {
  8095. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8096. } else {
  8097. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  8098. dst_tag = lb_const_union_tag(m, src, dst);
  8099. }
  8100. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  8101. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  8102. if (data.value != nullptr) {
  8103. GB_ASSERT(is_type_union_maybe_pointer(src));
  8104. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  8105. } else {
  8106. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  8107. }
  8108. lb_emit_if(p, cond, ok_block, end_block);
  8109. lb_start_block(p, ok_block);
  8110. if (data.value == nullptr) {
  8111. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8112. }
  8113. lb_emit_store(p, gep0, data);
  8114. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8115. lb_emit_jump(p, end_block);
  8116. lb_start_block(p, end_block);
  8117. if (!is_tuple) {
  8118. if (do_conversion_check) {
  8119. // NOTE(bill): Panic on invalid conversion
  8120. Type *dst_type = tuple->Tuple.variables[0]->type;
  8121. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8122. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8123. args[0] = ok;
  8124. args[1] = lb_const_string(m, pos.file);
  8125. args[2] = lb_const_int(m, t_int, pos.line);
  8126. args[3] = lb_const_int(m, t_int, pos.column);
  8127. args[4] = lb_typeid(m, src_type);
  8128. args[5] = lb_typeid(m, dst_type);
  8129. lb_emit_runtime_call(p, "type_assertion_check", args);
  8130. }
  8131. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  8132. }
  8133. return lb_addr_load(p, v);
  8134. }
  8135. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8136. lbModule *m = p->module;
  8137. Type *src_type = value.type;
  8138. if (is_type_pointer(src_type)) {
  8139. value = lb_emit_load(p, value);
  8140. }
  8141. bool is_tuple = true;
  8142. Type *tuple = type;
  8143. if (type->kind != Type_Tuple) {
  8144. is_tuple = false;
  8145. tuple = make_optional_ok_type(type);
  8146. }
  8147. Type *dst_type = tuple->Tuple.variables[0]->type;
  8148. lbAddr v = lb_add_local_generated(p, tuple, true);
  8149. lbValue dst_typeid = lb_typeid(m, dst_type);
  8150. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  8151. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  8152. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  8153. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  8154. lb_emit_if(p, cond, ok_block, end_block);
  8155. lb_start_block(p, ok_block);
  8156. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8157. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8158. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  8159. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  8160. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  8161. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8162. lb_emit_jump(p, end_block);
  8163. lb_start_block(p, end_block);
  8164. if (!is_tuple) {
  8165. // NOTE(bill): Panic on invalid conversion
  8166. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8167. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8168. args[0] = ok;
  8169. args[1] = lb_const_string(m, pos.file);
  8170. args[2] = lb_const_int(m, t_int, pos.line);
  8171. args[3] = lb_const_int(m, t_int, pos.column);
  8172. args[4] = any_typeid;
  8173. args[5] = dst_typeid;
  8174. lb_emit_runtime_call(p, "type_assertion_check", args);
  8175. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  8176. }
  8177. return v;
  8178. }
  8179. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8180. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  8181. }
  8182. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  8183. lbModule *m = p->module;
  8184. u64 prev_state_flags = p->module->state_flags;
  8185. defer (p->module->state_flags = prev_state_flags);
  8186. if (expr->state_flags != 0) {
  8187. u64 in = expr->state_flags;
  8188. u64 out = p->module->state_flags;
  8189. if (in & StateFlag_bounds_check) {
  8190. out |= StateFlag_bounds_check;
  8191. out &= ~StateFlag_no_bounds_check;
  8192. } else if (in & StateFlag_no_bounds_check) {
  8193. out |= StateFlag_no_bounds_check;
  8194. out &= ~StateFlag_bounds_check;
  8195. }
  8196. p->module->state_flags = out;
  8197. }
  8198. expr = unparen_expr(expr);
  8199. TypeAndValue tv = type_and_value_of_expr(expr);
  8200. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "%s", expr_to_string(expr));
  8201. GB_ASSERT(tv.mode != Addressing_Type);
  8202. if (tv.value.kind != ExactValue_Invalid) {
  8203. // NOTE(bill): Short on constant values
  8204. return lb_const_value(p->module, tv.type, tv.value);
  8205. }
  8206. switch (expr->kind) {
  8207. case_ast_node(bl, BasicLit, expr);
  8208. TokenPos pos = bl->token.pos;
  8209. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  8210. case_end;
  8211. case_ast_node(bd, BasicDirective, expr);
  8212. TokenPos pos = bd->token.pos;
  8213. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  8214. case_end;
  8215. case_ast_node(i, Implicit, expr);
  8216. return lb_addr_load(p, lb_build_addr(p, expr));
  8217. case_end;
  8218. case_ast_node(u, Undef, expr)
  8219. lbValue res = {};
  8220. if (is_type_untyped(tv.type)) {
  8221. res.value = nullptr;
  8222. res.type = t_untyped_undef;
  8223. } else {
  8224. res.value = LLVMGetUndef(lb_type(m, tv.type));
  8225. res.type = tv.type;
  8226. }
  8227. return res;
  8228. case_end;
  8229. case_ast_node(i, Ident, expr);
  8230. Entity *e = entity_from_expr(expr);
  8231. e = strip_entity_wrapping(e);
  8232. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  8233. if (e->kind == Entity_Builtin) {
  8234. Token token = ast_token(expr);
  8235. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  8236. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  8237. LIT(token.pos.file), token.pos.line, token.pos.column);
  8238. return {};
  8239. } else if (e->kind == Entity_Nil) {
  8240. lbValue res = {};
  8241. res.value = nullptr;
  8242. res.type = e->type;
  8243. return res;
  8244. }
  8245. GB_ASSERT(e->kind != Entity_ProcGroup);
  8246. auto *found = map_get(&p->module->values, hash_entity(e));
  8247. if (found) {
  8248. auto v = *found;
  8249. // NOTE(bill): This is because pointers are already pointers in LLVM
  8250. if (is_type_proc(v.type)) {
  8251. return v;
  8252. }
  8253. return lb_emit_load(p, v);
  8254. } else if (e != nullptr && e->kind == Entity_Variable) {
  8255. return lb_addr_load(p, lb_build_addr(p, expr));
  8256. }
  8257. gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  8258. String pkg = {};
  8259. if (e->pkg) {
  8260. pkg = e->pkg->name;
  8261. }
  8262. 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);
  8263. return {};
  8264. case_end;
  8265. case_ast_node(de, DerefExpr, expr);
  8266. return lb_addr_load(p, lb_build_addr(p, expr));
  8267. case_end;
  8268. case_ast_node(se, SelectorExpr, expr);
  8269. TypeAndValue tav = type_and_value_of_expr(expr);
  8270. GB_ASSERT(tav.mode != Addressing_Invalid);
  8271. return lb_addr_load(p, lb_build_addr(p, expr));
  8272. case_end;
  8273. case_ast_node(ise, ImplicitSelectorExpr, expr);
  8274. TypeAndValue tav = type_and_value_of_expr(expr);
  8275. GB_ASSERT(tav.mode == Addressing_Constant);
  8276. return lb_const_value(p->module, tv.type, tv.value);
  8277. case_end;
  8278. case_ast_node(se, SelectorCallExpr, expr);
  8279. GB_ASSERT(se->modified_call);
  8280. TypeAndValue tav = type_and_value_of_expr(expr);
  8281. GB_ASSERT(tav.mode != Addressing_Invalid);
  8282. return lb_build_expr(p, se->call);
  8283. case_end;
  8284. case_ast_node(te, TernaryExpr, expr);
  8285. LLVMValueRef incoming_values[2] = {};
  8286. LLVMBasicBlockRef incoming_blocks[2] = {};
  8287. GB_ASSERT(te->y != nullptr);
  8288. lbBlock *then = lb_create_block(p, "if.then");
  8289. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8290. lbBlock *else_ = lb_create_block(p, "if.else");
  8291. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8292. lb_start_block(p, then);
  8293. Type *type = default_type(type_of_expr(expr));
  8294. lb_open_scope(p);
  8295. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8296. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8297. lb_emit_jump(p, done);
  8298. lb_start_block(p, else_);
  8299. lb_open_scope(p);
  8300. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8301. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8302. lb_emit_jump(p, done);
  8303. lb_start_block(p, done);
  8304. lbValue res = {};
  8305. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8306. res.type = type;
  8307. GB_ASSERT(p->curr_block->preds.count >= 2);
  8308. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8309. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8310. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8311. return res;
  8312. case_end;
  8313. case_ast_node(te, TernaryIfExpr, expr);
  8314. LLVMValueRef incoming_values[2] = {};
  8315. LLVMBasicBlockRef incoming_blocks[2] = {};
  8316. GB_ASSERT(te->y != nullptr);
  8317. lbBlock *then = lb_create_block(p, "if.then");
  8318. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8319. lbBlock *else_ = lb_create_block(p, "if.else");
  8320. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8321. lb_start_block(p, then);
  8322. Type *type = default_type(type_of_expr(expr));
  8323. lb_open_scope(p);
  8324. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8325. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8326. lb_emit_jump(p, done);
  8327. lb_start_block(p, else_);
  8328. lb_open_scope(p);
  8329. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8330. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8331. lb_emit_jump(p, done);
  8332. lb_start_block(p, done);
  8333. lbValue res = {};
  8334. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8335. res.type = type;
  8336. GB_ASSERT(p->curr_block->preds.count >= 2);
  8337. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8338. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8339. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8340. return res;
  8341. case_end;
  8342. case_ast_node(te, TernaryWhenExpr, expr);
  8343. TypeAndValue tav = type_and_value_of_expr(te->cond);
  8344. GB_ASSERT(tav.mode == Addressing_Constant);
  8345. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  8346. if (tav.value.value_bool) {
  8347. return lb_build_expr(p, te->x);
  8348. } else {
  8349. return lb_build_expr(p, te->y);
  8350. }
  8351. case_end;
  8352. case_ast_node(ta, TypeAssertion, expr);
  8353. TokenPos pos = ast_token(expr).pos;
  8354. Type *type = tv.type;
  8355. lbValue e = lb_build_expr(p, ta->expr);
  8356. Type *t = type_deref(e.type);
  8357. if (is_type_union(t)) {
  8358. return lb_emit_union_cast(p, e, type, pos);
  8359. } else if (is_type_any(t)) {
  8360. return lb_emit_any_cast(p, e, type, pos);
  8361. } else {
  8362. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8363. }
  8364. case_end;
  8365. case_ast_node(tc, TypeCast, expr);
  8366. lbValue e = lb_build_expr(p, tc->expr);
  8367. switch (tc->token.kind) {
  8368. case Token_cast:
  8369. return lb_emit_conv(p, e, tv.type);
  8370. case Token_transmute:
  8371. return lb_emit_transmute(p, e, tv.type);
  8372. }
  8373. GB_PANIC("Invalid AST TypeCast");
  8374. case_end;
  8375. case_ast_node(ac, AutoCast, expr);
  8376. return lb_build_expr(p, ac->expr);
  8377. case_end;
  8378. case_ast_node(ue, UnaryExpr, expr);
  8379. switch (ue->op.kind) {
  8380. case Token_And: {
  8381. Ast *ue_expr = unparen_expr(ue->expr);
  8382. if (ue_expr->kind == Ast_CompoundLit) {
  8383. lbValue v = lb_build_expr(p, ue->expr);
  8384. Type *type = v.type;
  8385. lbAddr addr = {};
  8386. if (p->is_startup) {
  8387. addr = lb_add_global_generated(p->module, type, v);
  8388. } else {
  8389. addr = lb_add_local_generated(p, type, false);
  8390. }
  8391. lb_addr_store(p, addr, v);
  8392. return addr.addr;
  8393. } else if (ue_expr->kind == Ast_TypeAssertion) {
  8394. GB_ASSERT(is_type_pointer(tv.type));
  8395. ast_node(ta, TypeAssertion, ue_expr);
  8396. TokenPos pos = ast_token(expr).pos;
  8397. Type *type = type_of_expr(ue_expr);
  8398. GB_ASSERT(!is_type_tuple(type));
  8399. lbValue e = lb_build_expr(p, ta->expr);
  8400. Type *t = type_deref(e.type);
  8401. if (is_type_union(t)) {
  8402. lbValue v = e;
  8403. if (!is_type_pointer(v.type)) {
  8404. v = lb_address_from_load_or_generate_local(p, v);
  8405. }
  8406. Type *src_type = type_deref(v.type);
  8407. Type *dst_type = type;
  8408. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  8409. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  8410. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  8411. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8412. args[0] = ok;
  8413. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8414. args[2] = lb_const_int(p->module, t_int, pos.line);
  8415. args[3] = lb_const_int(p->module, t_int, pos.column);
  8416. args[4] = lb_typeid(p->module, src_type);
  8417. args[5] = lb_typeid(p->module, dst_type);
  8418. lb_emit_runtime_call(p, "type_assertion_check", args);
  8419. lbValue data_ptr = v;
  8420. return lb_emit_conv(p, data_ptr, tv.type);
  8421. } else if (is_type_any(t)) {
  8422. lbValue v = e;
  8423. if (is_type_pointer(v.type)) {
  8424. v = lb_emit_load(p, v);
  8425. }
  8426. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  8427. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  8428. lbValue id = lb_typeid(p->module, type);
  8429. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  8430. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8431. args[0] = ok;
  8432. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8433. args[2] = lb_const_int(p->module, t_int, pos.line);
  8434. args[3] = lb_const_int(p->module, t_int, pos.column);
  8435. args[4] = any_id;
  8436. args[5] = id;
  8437. lb_emit_runtime_call(p, "type_assertion_check", args);
  8438. return lb_emit_conv(p, data_ptr, tv.type);
  8439. } else {
  8440. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  8441. }
  8442. }
  8443. return lb_build_addr_ptr(p, ue->expr);
  8444. }
  8445. default:
  8446. {
  8447. lbValue v = lb_build_expr(p, ue->expr);
  8448. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  8449. }
  8450. }
  8451. case_end;
  8452. case_ast_node(be, BinaryExpr, expr);
  8453. return lb_build_binary_expr(p, expr);
  8454. case_end;
  8455. case_ast_node(pl, ProcLit, expr);
  8456. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  8457. case_end;
  8458. case_ast_node(cl, CompoundLit, expr);
  8459. return lb_addr_load(p, lb_build_addr(p, expr));
  8460. case_end;
  8461. case_ast_node(ce, CallExpr, expr);
  8462. lbValue res = lb_build_call_expr(p, expr);
  8463. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  8464. GB_ASSERT(is_type_tuple(res.type));
  8465. GB_ASSERT(res.type->Tuple.variables.count == 2);
  8466. return lb_emit_struct_ev(p, res, 0);
  8467. }
  8468. return res;
  8469. case_end;
  8470. case_ast_node(se, SliceExpr, expr);
  8471. return lb_addr_load(p, lb_build_addr(p, expr));
  8472. case_end;
  8473. case_ast_node(ie, IndexExpr, expr);
  8474. return lb_addr_load(p, lb_build_addr(p, expr));
  8475. case_end;
  8476. case_ast_node(ia, InlineAsmExpr, expr);
  8477. Type *t = type_of_expr(expr);
  8478. GB_ASSERT(is_type_asm_proc(t));
  8479. String asm_string = {};
  8480. String constraints_string = {};
  8481. TypeAndValue tav;
  8482. tav = type_and_value_of_expr(ia->asm_string);
  8483. GB_ASSERT(is_type_string(tav.type));
  8484. GB_ASSERT(tav.value.kind == ExactValue_String);
  8485. asm_string = tav.value.value_string;
  8486. tav = type_and_value_of_expr(ia->constraints_string);
  8487. GB_ASSERT(is_type_string(tav.type));
  8488. GB_ASSERT(tav.value.kind == ExactValue_String);
  8489. constraints_string = tav.value.value_string;
  8490. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  8491. switch (ia->dialect) {
  8492. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  8493. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  8494. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  8495. default: GB_PANIC("Unhandled inline asm dialect"); break;
  8496. }
  8497. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  8498. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8499. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  8500. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  8501. ia->has_side_effects, ia->is_align_stack, dialect
  8502. );
  8503. GB_ASSERT(the_asm != nullptr);
  8504. return {the_asm, t};
  8505. case_end;
  8506. }
  8507. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  8508. return {};
  8509. }
  8510. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  8511. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  8512. String name = e->token.string;
  8513. Entity *parent = e->using_parent;
  8514. Selection sel = lookup_field(parent->type, name, false);
  8515. GB_ASSERT(sel.entity != nullptr);
  8516. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  8517. lbValue v = {};
  8518. if (pv != nullptr) {
  8519. v = *pv;
  8520. } else {
  8521. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  8522. v = lb_build_addr_ptr(p, e->using_expr);
  8523. }
  8524. GB_ASSERT(v.value != nullptr);
  8525. GB_ASSERT(parent->type == type_deref(v.type));
  8526. return lb_emit_deep_field_gep(p, v, sel);
  8527. }
  8528. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  8529. GB_ASSERT(e != nullptr);
  8530. if (e->kind == Entity_Constant) {
  8531. Type *t = default_type(type_of_expr(expr));
  8532. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  8533. lbAddr g = lb_add_global_generated(p->module, t, v);
  8534. return g;
  8535. }
  8536. lbValue v = {};
  8537. lbValue *found = map_get(&p->module->values, hash_entity(e));
  8538. if (found) {
  8539. v = *found;
  8540. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  8541. // NOTE(bill): Calculate the using variable every time
  8542. v = lb_get_using_variable(p, e);
  8543. }
  8544. if (v.value == nullptr) {
  8545. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  8546. LIT(p->name),
  8547. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  8548. GB_PANIC("Unknown value");
  8549. }
  8550. return lb_addr(v);
  8551. }
  8552. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  8553. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  8554. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  8555. map_type = base_type(map_type);
  8556. GB_ASSERT(map_type->kind == Type_Map);
  8557. Type *key_type = map_type->Map.key;
  8558. Type *val_type = map_type->Map.value;
  8559. // NOTE(bill): Removes unnecessary allocation if split gep
  8560. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  8561. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  8562. lb_emit_store(p, gep0, m);
  8563. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_const_bool(p->module, t_bool, is_type_string(key_type)));
  8564. i64 entry_size = type_size_of (map_type->Map.entry_type);
  8565. i64 entry_align = type_align_of (map_type->Map.entry_type);
  8566. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  8567. i64 value_size = type_size_of (map_type->Map.value);
  8568. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  8569. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  8570. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, value_offset));
  8571. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, value_size));
  8572. return lb_addr_load(p, h);
  8573. }
  8574. lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) {
  8575. Type *hash_type = t_u64;
  8576. lbAddr v = lb_add_local_generated(p, t_map_key, true);
  8577. lbValue vp = lb_addr_get_ptr(p, v);
  8578. Type *t = base_type(key.type);
  8579. key = lb_emit_conv(p, key, key_type);
  8580. if (is_type_string(t)) {
  8581. lbValue str = lb_emit_conv(p, key, t_string);
  8582. lbValue hashed_str = {};
  8583. if (lb_is_const(str)) {
  8584. String v = lb_get_const_string(p->module, str);
  8585. u64 hs = fnv64a(v.text, v.len);
  8586. hashed_str = lb_const_int(p->module, t_u64, hs);
  8587. } else {
  8588. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8589. args[0] = str;
  8590. hashed_str = lb_emit_runtime_call(p, "default_hash_string", args);
  8591. }
  8592. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_str);
  8593. lbValue key_data = lb_emit_struct_ep(p, vp, 1);
  8594. key_data = lb_emit_conv(p, key_data, alloc_type_pointer(key_type));
  8595. lb_emit_store(p, key_data, str);
  8596. } else {
  8597. i64 sz = type_size_of(t);
  8598. GB_ASSERT(sz <= 8);
  8599. if (sz != 0) {
  8600. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8601. args[0] = lb_address_from_load_or_generate_local(p, key);
  8602. args[1] = lb_const_int(p->module, t_int, sz);
  8603. lbValue hash = lb_emit_runtime_call(p, "default_hash_ptr", args);
  8604. lbValue hash_ptr = lb_emit_struct_ep(p, vp, 0);
  8605. lbValue key_data = lb_emit_struct_ep(p, vp, 1);
  8606. key_data = lb_emit_conv(p, key_data, alloc_type_pointer(key_type));
  8607. lb_emit_store(p, hash_ptr, hash);
  8608. lb_emit_store(p, key_data, key);
  8609. }
  8610. }
  8611. return lb_addr_load(p, v);
  8612. }
  8613. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  8614. lbValue map_key, lbValue map_value, Ast *node) {
  8615. map_type = base_type(map_type);
  8616. GB_ASSERT(map_type->kind == Type_Map);
  8617. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  8618. lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key);
  8619. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  8620. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  8621. lb_addr_store(p, value_addr, v);
  8622. auto args = array_make<lbValue>(permanent_allocator(), 4);
  8623. args[0] = h;
  8624. args[1] = key;
  8625. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  8626. args[3] = lb_emit_source_code_location(p, node);
  8627. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  8628. }
  8629. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  8630. expr = unparen_expr(expr);
  8631. switch (expr->kind) {
  8632. case_ast_node(i, Implicit, expr);
  8633. lbAddr v = {};
  8634. switch (i->kind) {
  8635. case Token_context:
  8636. v = lb_find_or_generate_context_ptr(p);
  8637. break;
  8638. }
  8639. GB_ASSERT(v.addr.value != nullptr);
  8640. return v;
  8641. case_end;
  8642. case_ast_node(i, Ident, expr);
  8643. if (is_blank_ident(expr)) {
  8644. lbAddr val = {};
  8645. return val;
  8646. }
  8647. String name = i->token.string;
  8648. Entity *e = entity_of_node(expr);
  8649. return lb_build_addr_from_entity(p, e, expr);
  8650. case_end;
  8651. case_ast_node(se, SelectorExpr, expr);
  8652. Ast *sel = unparen_expr(se->selector);
  8653. if (sel->kind == Ast_Ident) {
  8654. String selector = sel->Ident.token.string;
  8655. TypeAndValue tav = type_and_value_of_expr(se->expr);
  8656. if (tav.mode == Addressing_Invalid) {
  8657. // NOTE(bill): Imports
  8658. Entity *imp = entity_of_node(se->expr);
  8659. if (imp != nullptr) {
  8660. GB_ASSERT(imp->kind == Entity_ImportName);
  8661. }
  8662. return lb_build_addr(p, unparen_expr(se->selector));
  8663. }
  8664. Type *type = base_type(tav.type);
  8665. if (tav.mode == Addressing_Type) { // Addressing_Type
  8666. Selection sel = lookup_field(type, selector, true);
  8667. Entity *e = sel.entity;
  8668. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  8669. GB_ASSERT(e->flags & EntityFlag_TypeField);
  8670. String name = e->token.string;
  8671. /*if (name == "names") {
  8672. lbValue ti_ptr = lb_type_info(m, type);
  8673. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  8674. lbValue names_ptr = nullptr;
  8675. if (is_type_enum(type)) {
  8676. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  8677. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  8678. } else if (type->kind == Type_Struct) {
  8679. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  8680. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  8681. }
  8682. return ir_addr(names_ptr);
  8683. } else */{
  8684. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  8685. }
  8686. GB_PANIC("Unreachable");
  8687. }
  8688. Selection sel = lookup_field(type, selector, false);
  8689. GB_ASSERT(sel.entity != nullptr);
  8690. if (sel.entity->type->kind == Type_BitFieldValue) {
  8691. lbAddr addr = lb_build_addr(p, se->expr);
  8692. Type *bft = type_deref(lb_addr_type(addr));
  8693. if (sel.index.count == 1) {
  8694. GB_ASSERT(is_type_bit_field(bft));
  8695. i32 index = sel.index[0];
  8696. return lb_addr_bit_field(lb_addr_get_ptr(p, addr), index);
  8697. } else {
  8698. Selection s = sel;
  8699. s.index.count--;
  8700. i32 index = s.index[s.index.count-1];
  8701. lbValue a = lb_addr_get_ptr(p, addr);
  8702. a = lb_emit_deep_field_gep(p, a, s);
  8703. return lb_addr_bit_field(a, index);
  8704. }
  8705. } else {
  8706. lbAddr addr = lb_build_addr(p, se->expr);
  8707. if (addr.kind == lbAddr_Map) {
  8708. lbValue v = lb_addr_load(p, addr);
  8709. lbValue a = lb_address_from_load_or_generate_local(p, v);
  8710. a = lb_emit_deep_field_gep(p, a, sel);
  8711. return lb_addr(a);
  8712. } else if (addr.kind == lbAddr_Context) {
  8713. GB_ASSERT(sel.index.count > 0);
  8714. if (addr.ctx.sel.index.count >= 0) {
  8715. sel = selection_combine(addr.ctx.sel, sel);
  8716. }
  8717. addr.ctx.sel = sel;
  8718. addr.kind = lbAddr_Context;
  8719. return addr;
  8720. } else if (addr.kind == lbAddr_SoaVariable) {
  8721. lbValue index = addr.soa.index;
  8722. i32 first_index = sel.index[0];
  8723. Selection sub_sel = sel;
  8724. sub_sel.index.data += 1;
  8725. sub_sel.index.count -= 1;
  8726. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  8727. Type *t = base_type(type_deref(addr.addr.type));
  8728. GB_ASSERT(is_type_soa_struct(t));
  8729. // TODO(bill): Bounds check
  8730. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  8731. lbValue len = lb_soa_struct_len(p, addr.addr);
  8732. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  8733. }
  8734. lbValue item = {};
  8735. if (t->Struct.soa_kind == StructSoa_Fixed) {
  8736. item = lb_emit_array_ep(p, arr, index);
  8737. } else {
  8738. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  8739. }
  8740. if (sub_sel.index.count > 0) {
  8741. item = lb_emit_deep_field_gep(p, item, sub_sel);
  8742. }
  8743. return lb_addr(item);
  8744. }
  8745. lbValue a = lb_addr_get_ptr(p, addr);
  8746. a = lb_emit_deep_field_gep(p, a, sel);
  8747. return lb_addr(a);
  8748. }
  8749. } else {
  8750. GB_PANIC("Unsupported selector expression");
  8751. }
  8752. case_end;
  8753. case_ast_node(se, SelectorCallExpr, expr);
  8754. GB_ASSERT(se->modified_call);
  8755. TypeAndValue tav = type_and_value_of_expr(expr);
  8756. GB_ASSERT(tav.mode != Addressing_Invalid);
  8757. return lb_build_addr(p, se->call);
  8758. case_end;
  8759. case_ast_node(ta, TypeAssertion, expr);
  8760. TokenPos pos = ast_token(expr).pos;
  8761. lbValue e = lb_build_expr(p, ta->expr);
  8762. Type *t = type_deref(e.type);
  8763. if (is_type_union(t)) {
  8764. Type *type = type_of_expr(expr);
  8765. lbAddr v = lb_add_local_generated(p, type, false);
  8766. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  8767. return v;
  8768. } else if (is_type_any(t)) {
  8769. Type *type = type_of_expr(expr);
  8770. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  8771. } else {
  8772. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8773. }
  8774. case_end;
  8775. case_ast_node(ue, UnaryExpr, expr);
  8776. switch (ue->op.kind) {
  8777. case Token_And: {
  8778. return lb_build_addr(p, ue->expr);
  8779. }
  8780. default:
  8781. GB_PANIC("Invalid unary expression for lb_build_addr");
  8782. }
  8783. case_end;
  8784. case_ast_node(be, BinaryExpr, expr);
  8785. lbValue v = lb_build_expr(p, expr);
  8786. Type *t = v.type;
  8787. if (is_type_pointer(t)) {
  8788. return lb_addr(v);
  8789. }
  8790. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  8791. case_end;
  8792. case_ast_node(ie, IndexExpr, expr);
  8793. Type *t = base_type(type_of_expr(ie->expr));
  8794. bool deref = is_type_pointer(t);
  8795. t = base_type(type_deref(t));
  8796. if (is_type_soa_struct(t)) {
  8797. // SOA STRUCTURES!!!!
  8798. lbValue val = lb_build_addr_ptr(p, ie->expr);
  8799. if (deref) {
  8800. val = lb_emit_load(p, val);
  8801. }
  8802. lbValue index = lb_build_expr(p, ie->index);
  8803. return lb_addr_soa_variable(val, index, ie->index);
  8804. }
  8805. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  8806. // SOA Structures for slices/dynamic arrays
  8807. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  8808. lbValue field = lb_build_expr(p, ie->expr);
  8809. lbValue index = lb_build_expr(p, ie->index);
  8810. if (!build_context.no_bounds_check) {
  8811. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  8812. // GB_ASSERT(LLVMIsALoadInst(field.value));
  8813. // lbValue a = {};
  8814. // a.value = LLVMGetOperand(field.value, 0);
  8815. // a.type = alloc_type_pointer(field.type);
  8816. // irInstr *b = &a->Instr;
  8817. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  8818. // lbValue base_struct = b->StructElementPtr.address;
  8819. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  8820. // lbValue len = ir_soa_struct_len(p, base_struct);
  8821. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8822. }
  8823. lbValue val = lb_emit_ptr_offset(p, field, index);
  8824. return lb_addr(val);
  8825. }
  8826. if (!is_type_indexable(t)) {
  8827. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8828. if (found != nullptr) {
  8829. if (found->kind == TypeAtomOp_index_get) {
  8830. return lb_build_addr(p, found->node);
  8831. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  8832. return lb_addr(lb_build_expr(p, found->node));
  8833. } else if (found->kind == TypeAtomOp_index_set) {
  8834. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  8835. if (deref) {
  8836. ptr = lb_emit_load(p, ptr);
  8837. }
  8838. lbAddr addr = {lbAddr_AtomOp_index_set};
  8839. addr.addr = ptr;
  8840. addr.index_set.index = lb_build_expr(p, ie->index);
  8841. addr.index_set.node = found->node;
  8842. return addr;
  8843. }
  8844. }
  8845. }
  8846. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  8847. if (is_type_map(t)) {
  8848. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  8849. if (deref) {
  8850. map_val = lb_emit_load(p, map_val);
  8851. }
  8852. lbValue key = lb_build_expr(p, ie->index);
  8853. key = lb_emit_conv(p, key, t->Map.key);
  8854. Type *result_type = type_of_expr(expr);
  8855. return lb_addr_map(map_val, key, t, result_type);
  8856. }
  8857. switch (t->kind) {
  8858. case Type_Array: {
  8859. lbValue array = {};
  8860. array = lb_build_addr_ptr(p, ie->expr);
  8861. if (deref) {
  8862. array = lb_emit_load(p, array);
  8863. }
  8864. lbValue index = lb_build_expr(p, ie->index);
  8865. index = lb_emit_conv(p, index, t_int);
  8866. lbValue elem = lb_emit_array_ep(p, array, index);
  8867. auto index_tv = type_and_value_of_expr(ie->index);
  8868. if (index_tv.mode != Addressing_Constant) {
  8869. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  8870. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8871. }
  8872. return lb_addr(elem);
  8873. }
  8874. case Type_EnumeratedArray: {
  8875. lbValue array = {};
  8876. array = lb_build_addr_ptr(p, ie->expr);
  8877. if (deref) {
  8878. array = lb_emit_load(p, array);
  8879. }
  8880. Type *index_type = t->EnumeratedArray.index;
  8881. auto index_tv = type_and_value_of_expr(ie->index);
  8882. lbValue index = {};
  8883. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  8884. if (index_tv.mode == Addressing_Constant) {
  8885. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  8886. index = lb_const_value(p->module, index_type, idx);
  8887. } else {
  8888. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8889. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  8890. }
  8891. } else {
  8892. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8893. }
  8894. lbValue elem = lb_emit_array_ep(p, array, index);
  8895. if (index_tv.mode != Addressing_Constant) {
  8896. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  8897. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8898. }
  8899. return lb_addr(elem);
  8900. }
  8901. case Type_Slice: {
  8902. lbValue slice = {};
  8903. slice = lb_build_expr(p, ie->expr);
  8904. if (deref) {
  8905. slice = lb_emit_load(p, slice);
  8906. }
  8907. lbValue elem = lb_slice_elem(p, slice);
  8908. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8909. lbValue len = lb_slice_len(p, slice);
  8910. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8911. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8912. return lb_addr(v);
  8913. }
  8914. case Type_RelativeSlice: {
  8915. lbAddr slice_addr = {};
  8916. if (deref) {
  8917. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  8918. } else {
  8919. slice_addr = lb_build_addr(p, ie->expr);
  8920. }
  8921. lbValue slice = lb_addr_load(p, slice_addr);
  8922. lbValue elem = lb_slice_elem(p, slice);
  8923. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8924. lbValue len = lb_slice_len(p, slice);
  8925. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8926. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8927. return lb_addr(v);
  8928. }
  8929. case Type_DynamicArray: {
  8930. lbValue dynamic_array = {};
  8931. dynamic_array = lb_build_expr(p, ie->expr);
  8932. if (deref) {
  8933. dynamic_array = lb_emit_load(p, dynamic_array);
  8934. }
  8935. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  8936. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  8937. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8938. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8939. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8940. return lb_addr(v);
  8941. }
  8942. case Type_Basic: { // Basic_string
  8943. lbValue str;
  8944. lbValue elem;
  8945. lbValue len;
  8946. lbValue index;
  8947. str = lb_build_expr(p, ie->expr);
  8948. if (deref) {
  8949. str = lb_emit_load(p, str);
  8950. }
  8951. elem = lb_string_elem(p, str);
  8952. len = lb_string_len(p, str);
  8953. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8954. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8955. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  8956. }
  8957. }
  8958. case_end;
  8959. case_ast_node(se, SliceExpr, expr);
  8960. lbValue low = lb_const_int(p->module, t_int, 0);
  8961. lbValue high = {};
  8962. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  8963. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  8964. bool no_indices = se->low == nullptr && se->high == nullptr;
  8965. {
  8966. Type *type = base_type(type_of_expr(se->expr));
  8967. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  8968. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  8969. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  8970. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8971. if (found) {
  8972. lbValue base = lb_build_expr(p, found->node);
  8973. Type *slice_type = base.type;
  8974. lbValue len = lb_slice_len(p, base);
  8975. if (high.value == nullptr) high = len;
  8976. if (!no_indices) {
  8977. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8978. }
  8979. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8980. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8981. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8982. lb_fill_slice(p, slice, elem, new_len);
  8983. return slice;
  8984. }
  8985. }
  8986. }
  8987. }
  8988. lbAddr addr = lb_build_addr(p, se->expr);
  8989. lbValue base = lb_addr_load(p, addr);
  8990. Type *type = base_type(base.type);
  8991. if (is_type_pointer(type)) {
  8992. type = base_type(type_deref(type));
  8993. addr = lb_addr(base);
  8994. base = lb_addr_load(p, addr);
  8995. }
  8996. switch (type->kind) {
  8997. case Type_Slice: {
  8998. Type *slice_type = type;
  8999. lbValue len = lb_slice_len(p, base);
  9000. if (high.value == nullptr) high = len;
  9001. if (!no_indices) {
  9002. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9003. }
  9004. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9005. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9006. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9007. lb_fill_slice(p, slice, elem, new_len);
  9008. return slice;
  9009. }
  9010. case Type_RelativeSlice:
  9011. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  9012. break;
  9013. case Type_DynamicArray: {
  9014. Type *elem_type = type->DynamicArray.elem;
  9015. Type *slice_type = alloc_type_slice(elem_type);
  9016. lbValue len = lb_dynamic_array_len(p, base);
  9017. if (high.value == nullptr) high = len;
  9018. if (!no_indices) {
  9019. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9020. }
  9021. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  9022. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9023. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9024. lb_fill_slice(p, slice, elem, new_len);
  9025. return slice;
  9026. }
  9027. case Type_Array: {
  9028. Type *slice_type = alloc_type_slice(type->Array.elem);
  9029. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  9030. if (high.value == nullptr) high = len;
  9031. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  9032. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  9033. if (!low_const || !high_const) {
  9034. if (!no_indices) {
  9035. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9036. }
  9037. }
  9038. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  9039. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9040. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9041. lb_fill_slice(p, slice, elem, new_len);
  9042. return slice;
  9043. }
  9044. case Type_Basic: {
  9045. GB_ASSERT(type == t_string);
  9046. lbValue len = lb_string_len(p, base);
  9047. if (high.value == nullptr) high = len;
  9048. if (!no_indices) {
  9049. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9050. }
  9051. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  9052. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9053. lbAddr str = lb_add_local_generated(p, t_string, false);
  9054. lb_fill_string(p, str, elem, new_len);
  9055. return str;
  9056. }
  9057. case Type_Struct:
  9058. if (is_type_soa_struct(type)) {
  9059. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  9060. if (high.value == nullptr) high = len;
  9061. if (!no_indices) {
  9062. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9063. }
  9064. #if 1
  9065. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  9066. if (type->Struct.soa_kind == StructSoa_Fixed) {
  9067. i32 field_count = cast(i32)type->Struct.fields.count;
  9068. for (i32 i = 0; i < field_count; i++) {
  9069. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9070. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  9071. field_src = lb_emit_array_ep(p, field_src, low);
  9072. lb_emit_store(p, field_dst, field_src);
  9073. }
  9074. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9075. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9076. lb_emit_store(p, len_dst, new_len);
  9077. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  9078. if (no_indices) {
  9079. lb_addr_store(p, dst, base);
  9080. } else {
  9081. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  9082. for (i32 i = 0; i < field_count; i++) {
  9083. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9084. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9085. field_src = lb_emit_ptr_offset(p, field_src, low);
  9086. lb_emit_store(p, field_dst, field_src);
  9087. }
  9088. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9089. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9090. lb_emit_store(p, len_dst, new_len);
  9091. }
  9092. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  9093. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  9094. for (i32 i = 0; i < field_count; i++) {
  9095. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9096. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9097. field_src = lb_emit_ptr_offset(p, field_src, low);
  9098. lb_emit_store(p, field_dst, field_src);
  9099. }
  9100. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9101. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9102. lb_emit_store(p, len_dst, new_len);
  9103. }
  9104. return dst;
  9105. #endif
  9106. }
  9107. break;
  9108. }
  9109. GB_PANIC("Unknown slicable type");
  9110. case_end;
  9111. case_ast_node(de, DerefExpr, expr);
  9112. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  9113. lbAddr addr = lb_build_addr(p, de->expr);
  9114. addr.relative.deref = true;
  9115. return addr;
  9116. }
  9117. lbValue addr = lb_build_expr(p, de->expr);
  9118. return lb_addr(addr);
  9119. case_end;
  9120. case_ast_node(ce, CallExpr, expr);
  9121. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  9122. lbValue e = lb_build_expr(p, expr);
  9123. lbAddr v = lb_add_local_generated(p, e.type, false);
  9124. lb_addr_store(p, v, e);
  9125. return v;
  9126. case_end;
  9127. case_ast_node(cl, CompoundLit, expr);
  9128. Type *type = type_of_expr(expr);
  9129. Type *bt = base_type(type);
  9130. lbAddr v = lb_add_local_generated(p, type, true);
  9131. Type *et = nullptr;
  9132. switch (bt->kind) {
  9133. case Type_Array: et = bt->Array.elem; break;
  9134. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  9135. case Type_Slice: et = bt->Slice.elem; break;
  9136. case Type_BitSet: et = bt->BitSet.elem; break;
  9137. case Type_SimdVector: et = bt->SimdVector.elem; break;
  9138. }
  9139. String proc_name = {};
  9140. if (p->entity) {
  9141. proc_name = p->entity->token.string;
  9142. }
  9143. TokenPos pos = ast_token(expr).pos;
  9144. switch (bt->kind) {
  9145. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  9146. case Type_Struct: {
  9147. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  9148. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  9149. bool is_raw_union = is_type_raw_union(bt);
  9150. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  9151. TypeStruct *st = &bt->Struct;
  9152. if (cl->elems.count > 0) {
  9153. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9154. for_array(field_index, cl->elems) {
  9155. Ast *elem = cl->elems[field_index];
  9156. lbValue field_expr = {};
  9157. Entity *field = nullptr;
  9158. isize index = field_index;
  9159. if (elem->kind == Ast_FieldValue) {
  9160. ast_node(fv, FieldValue, elem);
  9161. String name = fv->field->Ident.token.string;
  9162. Selection sel = lookup_field(bt, name, false);
  9163. index = sel.index[0];
  9164. elem = fv->value;
  9165. TypeAndValue tav = type_and_value_of_expr(elem);
  9166. } else {
  9167. TypeAndValue tav = type_and_value_of_expr(elem);
  9168. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  9169. index = sel.index[0];
  9170. }
  9171. field = st->fields[index];
  9172. Type *ft = field->type;
  9173. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  9174. continue;
  9175. }
  9176. field_expr = lb_build_expr(p, elem);
  9177. Type *fet = field_expr.type;
  9178. GB_ASSERT(fet->kind != Type_Tuple);
  9179. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  9180. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  9181. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  9182. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9183. lb_emit_store_union_variant(p, gep, field_expr, fet);
  9184. } else {
  9185. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9186. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9187. lb_emit_store(p, gep, fv);
  9188. }
  9189. }
  9190. }
  9191. break;
  9192. }
  9193. case Type_Map: {
  9194. if (cl->elems.count == 0) {
  9195. break;
  9196. }
  9197. {
  9198. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9199. args[0] = lb_gen_map_header(p, v.addr, type);
  9200. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  9201. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  9202. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  9203. }
  9204. for_array(field_index, cl->elems) {
  9205. Ast *elem = cl->elems[field_index];
  9206. ast_node(fv, FieldValue, elem);
  9207. lbValue key = lb_build_expr(p, fv->field);
  9208. lbValue value = lb_build_expr(p, fv->value);
  9209. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  9210. }
  9211. break;
  9212. }
  9213. case Type_Array: {
  9214. if (cl->elems.count > 0) {
  9215. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9216. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9217. // NOTE(bill): Separate value, gep, store into their own chunks
  9218. for_array(i, cl->elems) {
  9219. Ast *elem = cl->elems[i];
  9220. if (elem->kind == Ast_FieldValue) {
  9221. ast_node(fv, FieldValue, elem);
  9222. if (lb_is_elem_const(fv->value, et)) {
  9223. continue;
  9224. }
  9225. if (is_ast_range(fv->field)) {
  9226. ast_node(ie, BinaryExpr, fv->field);
  9227. TypeAndValue lo_tav = ie->left->tav;
  9228. TypeAndValue hi_tav = ie->right->tav;
  9229. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9230. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9231. TokenKind op = ie->op.kind;
  9232. i64 lo = exact_value_to_i64(lo_tav.value);
  9233. i64 hi = exact_value_to_i64(hi_tav.value);
  9234. if (op == Token_Ellipsis) {
  9235. hi += 1;
  9236. }
  9237. lbValue value = lb_build_expr(p, fv->value);
  9238. for (i64 k = lo; k < hi; k++) {
  9239. lbCompoundLitElemTempData data = {};
  9240. data.value = value;
  9241. data.elem_index = cast(i32)k;
  9242. array_add(&temp_data, data);
  9243. }
  9244. } else {
  9245. auto tav = fv->field->tav;
  9246. GB_ASSERT(tav.mode == Addressing_Constant);
  9247. i64 index = exact_value_to_i64(tav.value);
  9248. lbValue value = lb_build_expr(p, fv->value);
  9249. lbCompoundLitElemTempData data = {};
  9250. data.value = lb_emit_conv(p, value, et);
  9251. data.expr = fv->value;
  9252. data.elem_index = cast(i32)index;
  9253. array_add(&temp_data, data);
  9254. }
  9255. } else {
  9256. if (lb_is_elem_const(elem, et)) {
  9257. continue;
  9258. }
  9259. lbCompoundLitElemTempData data = {};
  9260. data.expr = elem;
  9261. data.elem_index = cast(i32)i;
  9262. array_add(&temp_data, data);
  9263. }
  9264. }
  9265. for_array(i, temp_data) {
  9266. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  9267. }
  9268. for_array(i, temp_data) {
  9269. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9270. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9271. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9272. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9273. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9274. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9275. lbValue field_expr = temp_data[i].value;
  9276. Ast *expr = temp_data[i].expr;
  9277. p->return_ptr_hint_value = temp_data[i].gep;
  9278. p->return_ptr_hint_ast = unparen_expr(expr);
  9279. if (field_expr.value == nullptr) {
  9280. field_expr = lb_build_expr(p, expr);
  9281. }
  9282. Type *t = field_expr.type;
  9283. GB_ASSERT(t->kind != Type_Tuple);
  9284. lbValue ev = lb_emit_conv(p, field_expr, et);
  9285. if (!p->return_ptr_hint_used) {
  9286. temp_data[i].value = ev;
  9287. }
  9288. }
  9289. for_array(i, temp_data) {
  9290. if (temp_data[i].value.value != nullptr) {
  9291. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9292. }
  9293. }
  9294. }
  9295. break;
  9296. }
  9297. case Type_EnumeratedArray: {
  9298. if (cl->elems.count > 0) {
  9299. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9300. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9301. // NOTE(bill): Separate value, gep, store into their own chunks
  9302. for_array(i, cl->elems) {
  9303. Ast *elem = cl->elems[i];
  9304. if (elem->kind == Ast_FieldValue) {
  9305. ast_node(fv, FieldValue, elem);
  9306. if (lb_is_elem_const(fv->value, et)) {
  9307. continue;
  9308. }
  9309. if (is_ast_range(fv->field)) {
  9310. ast_node(ie, BinaryExpr, fv->field);
  9311. TypeAndValue lo_tav = ie->left->tav;
  9312. TypeAndValue hi_tav = ie->right->tav;
  9313. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9314. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9315. TokenKind op = ie->op.kind;
  9316. i64 lo = exact_value_to_i64(lo_tav.value);
  9317. i64 hi = exact_value_to_i64(hi_tav.value);
  9318. if (op == Token_Ellipsis) {
  9319. hi += 1;
  9320. }
  9321. lbValue value = lb_build_expr(p, fv->value);
  9322. for (i64 k = lo; k < hi; k++) {
  9323. lbCompoundLitElemTempData data = {};
  9324. data.value = value;
  9325. data.elem_index = cast(i32)k;
  9326. array_add(&temp_data, data);
  9327. }
  9328. } else {
  9329. auto tav = fv->field->tav;
  9330. GB_ASSERT(tav.mode == Addressing_Constant);
  9331. i64 index = exact_value_to_i64(tav.value);
  9332. lbValue value = lb_build_expr(p, fv->value);
  9333. lbCompoundLitElemTempData data = {};
  9334. data.value = lb_emit_conv(p, value, et);
  9335. data.expr = fv->value;
  9336. data.elem_index = cast(i32)index;
  9337. array_add(&temp_data, data);
  9338. }
  9339. } else {
  9340. if (lb_is_elem_const(elem, et)) {
  9341. continue;
  9342. }
  9343. lbCompoundLitElemTempData data = {};
  9344. data.expr = elem;
  9345. data.elem_index = cast(i32)i;
  9346. array_add(&temp_data, data);
  9347. }
  9348. }
  9349. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  9350. for_array(i, temp_data) {
  9351. i32 index = temp_data[i].elem_index - index_offset;
  9352. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  9353. }
  9354. for_array(i, temp_data) {
  9355. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9356. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9357. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9358. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9359. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9360. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9361. lbValue field_expr = temp_data[i].value;
  9362. Ast *expr = temp_data[i].expr;
  9363. p->return_ptr_hint_value = temp_data[i].gep;
  9364. p->return_ptr_hint_ast = unparen_expr(expr);
  9365. if (field_expr.value == nullptr) {
  9366. field_expr = lb_build_expr(p, expr);
  9367. }
  9368. Type *t = field_expr.type;
  9369. GB_ASSERT(t->kind != Type_Tuple);
  9370. lbValue ev = lb_emit_conv(p, field_expr, et);
  9371. if (!p->return_ptr_hint_used) {
  9372. temp_data[i].value = ev;
  9373. }
  9374. }
  9375. for_array(i, temp_data) {
  9376. if (temp_data[i].value.value != nullptr) {
  9377. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9378. }
  9379. }
  9380. }
  9381. break;
  9382. }
  9383. case Type_Slice: {
  9384. if (cl->elems.count > 0) {
  9385. Type *elem_type = bt->Slice.elem;
  9386. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  9387. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  9388. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  9389. lbValue data = lb_slice_elem(p, slice);
  9390. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9391. for_array(i, cl->elems) {
  9392. Ast *elem = cl->elems[i];
  9393. if (elem->kind == Ast_FieldValue) {
  9394. ast_node(fv, FieldValue, elem);
  9395. if (lb_is_elem_const(fv->value, et)) {
  9396. continue;
  9397. }
  9398. if (is_ast_range(fv->field)) {
  9399. ast_node(ie, BinaryExpr, fv->field);
  9400. TypeAndValue lo_tav = ie->left->tav;
  9401. TypeAndValue hi_tav = ie->right->tav;
  9402. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9403. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9404. TokenKind op = ie->op.kind;
  9405. i64 lo = exact_value_to_i64(lo_tav.value);
  9406. i64 hi = exact_value_to_i64(hi_tav.value);
  9407. if (op == Token_Ellipsis) {
  9408. hi += 1;
  9409. }
  9410. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9411. for (i64 k = lo; k < hi; k++) {
  9412. lbCompoundLitElemTempData data = {};
  9413. data.value = value;
  9414. data.elem_index = cast(i32)k;
  9415. array_add(&temp_data, data);
  9416. }
  9417. } else {
  9418. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9419. i64 index = exact_value_to_i64(fv->field->tav.value);
  9420. lbValue field_expr = lb_build_expr(p, fv->value);
  9421. GB_ASSERT(!is_type_tuple(field_expr.type));
  9422. lbValue ev = lb_emit_conv(p, field_expr, et);
  9423. lbCompoundLitElemTempData data = {};
  9424. data.value = ev;
  9425. data.elem_index = cast(i32)index;
  9426. array_add(&temp_data, data);
  9427. }
  9428. } else {
  9429. if (lb_is_elem_const(elem, et)) {
  9430. continue;
  9431. }
  9432. lbValue field_expr = lb_build_expr(p, elem);
  9433. GB_ASSERT(!is_type_tuple(field_expr.type));
  9434. lbValue ev = lb_emit_conv(p, field_expr, et);
  9435. lbCompoundLitElemTempData data = {};
  9436. data.value = ev;
  9437. data.elem_index = cast(i32)i;
  9438. array_add(&temp_data, data);
  9439. }
  9440. }
  9441. for_array(i, temp_data) {
  9442. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  9443. }
  9444. for_array(i, temp_data) {
  9445. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9446. }
  9447. {
  9448. lbValue count = {};
  9449. count.type = t_int;
  9450. if (lb_is_const(slice)) {
  9451. unsigned indices[1] = {1};
  9452. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  9453. } else {
  9454. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  9455. }
  9456. lb_fill_slice(p, v, data, count);
  9457. }
  9458. }
  9459. break;
  9460. }
  9461. case Type_DynamicArray: {
  9462. if (cl->elems.count == 0) {
  9463. break;
  9464. }
  9465. Type *et = bt->DynamicArray.elem;
  9466. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  9467. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  9468. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  9469. {
  9470. auto args = array_make<lbValue>(permanent_allocator(), 5);
  9471. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  9472. args[1] = size;
  9473. args[2] = align;
  9474. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  9475. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  9476. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  9477. }
  9478. lbValue items = lb_generate_local_array(p, et, item_count);
  9479. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  9480. for_array(i, cl->elems) {
  9481. Ast *elem = cl->elems[i];
  9482. if (elem->kind == Ast_FieldValue) {
  9483. ast_node(fv, FieldValue, elem);
  9484. if (is_ast_range(fv->field)) {
  9485. ast_node(ie, BinaryExpr, fv->field);
  9486. TypeAndValue lo_tav = ie->left->tav;
  9487. TypeAndValue hi_tav = ie->right->tav;
  9488. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9489. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9490. TokenKind op = ie->op.kind;
  9491. i64 lo = exact_value_to_i64(lo_tav.value);
  9492. i64 hi = exact_value_to_i64(hi_tav.value);
  9493. if (op == Token_Ellipsis) {
  9494. hi += 1;
  9495. }
  9496. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9497. for (i64 k = lo; k < hi; k++) {
  9498. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  9499. lb_emit_store(p, ep, value);
  9500. }
  9501. } else {
  9502. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9503. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  9504. lbValue ev = lb_build_expr(p, fv->value);
  9505. lbValue value = lb_emit_conv(p, ev, et);
  9506. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  9507. lb_emit_store(p, ep, value);
  9508. }
  9509. } else {
  9510. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  9511. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  9512. lb_emit_store(p, ep, value);
  9513. }
  9514. }
  9515. {
  9516. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9517. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  9518. args[1] = size;
  9519. args[2] = align;
  9520. args[3] = lb_emit_conv(p, items, t_rawptr);
  9521. args[4] = lb_const_int(p->module, t_int, item_count);
  9522. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  9523. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  9524. }
  9525. break;
  9526. }
  9527. case Type_Basic: {
  9528. GB_ASSERT(is_type_any(bt));
  9529. if (cl->elems.count > 0) {
  9530. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9531. String field_names[2] = {
  9532. str_lit("data"),
  9533. str_lit("id"),
  9534. };
  9535. Type *field_types[2] = {
  9536. t_rawptr,
  9537. t_typeid,
  9538. };
  9539. for_array(field_index, cl->elems) {
  9540. Ast *elem = cl->elems[field_index];
  9541. lbValue field_expr = {};
  9542. isize index = field_index;
  9543. if (elem->kind == Ast_FieldValue) {
  9544. ast_node(fv, FieldValue, elem);
  9545. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  9546. index = sel.index[0];
  9547. elem = fv->value;
  9548. } else {
  9549. TypeAndValue tav = type_and_value_of_expr(elem);
  9550. Selection sel = lookup_field(bt, field_names[field_index], false);
  9551. index = sel.index[0];
  9552. }
  9553. field_expr = lb_build_expr(p, elem);
  9554. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  9555. Type *ft = field_types[index];
  9556. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9557. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9558. lb_emit_store(p, gep, fv);
  9559. }
  9560. }
  9561. break;
  9562. }
  9563. case Type_BitSet: {
  9564. i64 sz = type_size_of(type);
  9565. if (cl->elems.count > 0 && sz > 0) {
  9566. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9567. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  9568. for_array(i, cl->elems) {
  9569. Ast *elem = cl->elems[i];
  9570. GB_ASSERT(elem->kind != Ast_FieldValue);
  9571. if (lb_is_elem_const(elem, et)) {
  9572. continue;
  9573. }
  9574. lbValue expr = lb_build_expr(p, elem);
  9575. GB_ASSERT(expr.type->kind != Type_Tuple);
  9576. Type *it = bit_set_to_int(bt);
  9577. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  9578. lbValue e = lb_emit_conv(p, expr, it);
  9579. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  9580. e = lb_emit_arith(p, Token_Shl, one, e, it);
  9581. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  9582. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  9583. new_value = lb_emit_transmute(p, new_value, type);
  9584. lb_addr_store(p, v, new_value);
  9585. }
  9586. }
  9587. break;
  9588. }
  9589. }
  9590. return v;
  9591. case_end;
  9592. case_ast_node(tc, TypeCast, expr);
  9593. Type *type = type_of_expr(expr);
  9594. lbValue x = lb_build_expr(p, tc->expr);
  9595. lbValue e = {};
  9596. switch (tc->token.kind) {
  9597. case Token_cast:
  9598. e = lb_emit_conv(p, x, type);
  9599. break;
  9600. case Token_transmute:
  9601. e = lb_emit_transmute(p, x, type);
  9602. break;
  9603. default:
  9604. GB_PANIC("Invalid AST TypeCast");
  9605. }
  9606. lbAddr v = lb_add_local_generated(p, type, false);
  9607. lb_addr_store(p, v, e);
  9608. return v;
  9609. case_end;
  9610. case_ast_node(ac, AutoCast, expr);
  9611. return lb_build_addr(p, ac->expr);
  9612. case_end;
  9613. }
  9614. TokenPos token_pos = ast_token(expr).pos;
  9615. GB_PANIC("Unexpected address expression\n"
  9616. "\tAst: %.*s @ "
  9617. "%.*s(%td:%td)\n",
  9618. LIT(ast_strings[expr->kind]),
  9619. LIT(token_pos.file), token_pos.line, token_pos.column);
  9620. return {};
  9621. }
  9622. void lb_init_module(lbModule *m, Checker *c) {
  9623. m->info = &c->info;
  9624. m->ctx = LLVMGetGlobalContext();
  9625. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  9626. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  9627. m->state_flags = 0;
  9628. m->state_flags |= StateFlag_bounds_check;
  9629. gb_mutex_init(&m->mutex);
  9630. gbAllocator a = heap_allocator();
  9631. map_init(&m->types, a);
  9632. map_init(&m->values, a);
  9633. string_map_init(&m->members, a);
  9634. map_init(&m->procedure_values, a);
  9635. string_map_init(&m->procedures, a);
  9636. string_map_init(&m->const_strings, a);
  9637. map_init(&m->anonymous_proc_lits, a);
  9638. map_init(&m->function_type_map, a);
  9639. array_init(&m->procedures_to_generate, a);
  9640. array_init(&m->foreign_library_paths, a);
  9641. map_init(&m->debug_values, a);
  9642. }
  9643. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  9644. if (global_error_collector.count != 0) {
  9645. return false;
  9646. }
  9647. isize tc = c->parser->total_token_count;
  9648. if (tc < 2) {
  9649. return false;
  9650. }
  9651. String init_fullpath = c->parser->init_fullpath;
  9652. if (build_context.out_filepath.len == 0) {
  9653. gen->output_name = remove_directory_from_path(init_fullpath);
  9654. gen->output_name = remove_extension_from_path(gen->output_name);
  9655. gen->output_name = string_trim_whitespace(gen->output_name);
  9656. if (gen->output_name.len == 0) {
  9657. gen->output_name = c->info.init_scope->pkg->name;
  9658. }
  9659. gen->output_base = gen->output_name;
  9660. } else {
  9661. gen->output_name = build_context.out_filepath;
  9662. gen->output_name = string_trim_whitespace(gen->output_name);
  9663. if (gen->output_name.len == 0) {
  9664. gen->output_name = c->info.init_scope->pkg->name;
  9665. }
  9666. isize pos = string_extension_position(gen->output_name);
  9667. if (pos < 0) {
  9668. gen->output_base = gen->output_name;
  9669. } else {
  9670. gen->output_base = substring(gen->output_name, 0, pos);
  9671. }
  9672. }
  9673. gbAllocator ha = heap_allocator();
  9674. array_init(&gen->output_object_paths, ha);
  9675. gen->output_base = path_to_full_path(ha, gen->output_base);
  9676. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  9677. output_file_path = gb_string_appendc(output_file_path, ".obj");
  9678. defer (gb_string_free(output_file_path));
  9679. gen->info = &c->info;
  9680. lb_init_module(&gen->module, c);
  9681. return true;
  9682. }
  9683. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  9684. GB_ASSERT(type != nullptr);
  9685. type = default_type(type);
  9686. isize max_len = 7+8+1;
  9687. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  9688. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  9689. m->global_generated_index++;
  9690. String name = make_string(str, len-1);
  9691. Scope *scope = nullptr;
  9692. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  9693. lbValue g = {};
  9694. g.type = alloc_type_pointer(type);
  9695. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  9696. if (value.value != nullptr) {
  9697. GB_ASSERT(LLVMIsConstant(value.value));
  9698. LLVMSetInitializer(g.value, value.value);
  9699. } else {
  9700. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  9701. }
  9702. lb_add_entity(m, e, g);
  9703. lb_add_member(m, name, g);
  9704. return lb_addr(g);
  9705. }
  9706. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  9707. AstPackage *p = m->info->runtime_package;
  9708. Entity *e = scope_lookup_current(p->scope, name);
  9709. lbValue *found = map_get(&m->values, hash_entity(e));
  9710. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  9711. lbValue value = *found;
  9712. return value;
  9713. }
  9714. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  9715. i32 index = cast(i32)lb_type_info_index(m->info, type);
  9716. GB_ASSERT(index >= 0);
  9717. // gb_printf_err("%d %s\n", index, type_to_string(type));
  9718. LLVMValueRef indices[2] = {
  9719. LLVMConstInt(lb_type(m, t_int), 0, false),
  9720. LLVMConstInt(lb_type(m, t_int), index, false),
  9721. };
  9722. lbValue res = {};
  9723. res.type = t_type_info_ptr;
  9724. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  9725. return res;
  9726. }
  9727. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  9728. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  9729. lb_global_type_info_member_types_index += cast(i32)count;
  9730. return offset;
  9731. }
  9732. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  9733. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  9734. lb_global_type_info_member_names_index += cast(i32)count;
  9735. return offset;
  9736. }
  9737. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  9738. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  9739. lb_global_type_info_member_offsets_index += cast(i32)count;
  9740. return offset;
  9741. }
  9742. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  9743. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  9744. lb_global_type_info_member_usings_index += cast(i32)count;
  9745. return offset;
  9746. }
  9747. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  9748. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  9749. lb_global_type_info_member_tags_index += cast(i32)count;
  9750. return offset;
  9751. }
  9752. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  9753. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  9754. return lb_addr_get_ptr(p, addr);
  9755. }
  9756. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  9757. Token token = {Token_Ident};
  9758. isize name_len = prefix.len + 1 + 20;
  9759. auto suffix_id = cast(unsigned long long)id;
  9760. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  9761. gb_snprintf(text, name_len,
  9762. "%.*s-%llu", LIT(prefix), suffix_id);
  9763. text[name_len] = 0;
  9764. String s = make_string_c(text);
  9765. Type *t = alloc_type_array(elem_type, count);
  9766. lbValue g = {};
  9767. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  9768. g.type = alloc_type_pointer(t);
  9769. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  9770. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  9771. string_map_set(&m->members, s, g);
  9772. return g;
  9773. }
  9774. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  9775. lbModule *m = p->module;
  9776. LLVMContextRef ctx = m->ctx;
  9777. CheckerInfo *info = m->info;
  9778. {
  9779. // NOTE(bill): Set the type_table slice with the global backing array
  9780. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  9781. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  9782. GB_ASSERT(is_type_array(type));
  9783. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  9784. LLVMValueRef values[2] = {
  9785. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  9786. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  9787. };
  9788. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  9789. LLVMSetInitializer(global_type_table.value, slice);
  9790. }
  9791. // Useful types
  9792. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  9793. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  9794. i32 type_info_member_types_index = 0;
  9795. i32 type_info_member_names_index = 0;
  9796. i32 type_info_member_offsets_index = 0;
  9797. for_array(type_info_type_index, info->type_info_types) {
  9798. Type *t = info->type_info_types[type_info_type_index];
  9799. t = default_type(t);
  9800. if (t == t_invalid) {
  9801. continue;
  9802. }
  9803. isize entry_index = lb_type_info_index(info, t, false);
  9804. if (entry_index <= 0) {
  9805. continue;
  9806. }
  9807. lbValue tag = {};
  9808. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  9809. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 3);
  9810. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  9811. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  9812. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), lb_typeid(m, t));
  9813. switch (t->kind) {
  9814. case Type_Named: {
  9815. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  9816. LLVMValueRef vals[2] = {
  9817. lb_const_string(p->module, t->Named.type_name->token.string).value,
  9818. lb_get_type_info_ptr(m, t->Named.base).value,
  9819. };
  9820. lbValue res = {};
  9821. res.type = type_deref(tag.type);
  9822. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9823. lb_emit_store(p, tag, res);
  9824. break;
  9825. }
  9826. case Type_Basic:
  9827. switch (t->Basic.kind) {
  9828. case Basic_bool:
  9829. case Basic_b8:
  9830. case Basic_b16:
  9831. case Basic_b32:
  9832. case Basic_b64:
  9833. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  9834. break;
  9835. case Basic_i8:
  9836. case Basic_u8:
  9837. case Basic_i16:
  9838. case Basic_u16:
  9839. case Basic_i32:
  9840. case Basic_u32:
  9841. case Basic_i64:
  9842. case Basic_u64:
  9843. case Basic_i128:
  9844. case Basic_u128:
  9845. case Basic_i16le:
  9846. case Basic_u16le:
  9847. case Basic_i32le:
  9848. case Basic_u32le:
  9849. case Basic_i64le:
  9850. case Basic_u64le:
  9851. case Basic_i128le:
  9852. case Basic_u128le:
  9853. case Basic_i16be:
  9854. case Basic_u16be:
  9855. case Basic_i32be:
  9856. case Basic_u32be:
  9857. case Basic_i64be:
  9858. case Basic_u64be:
  9859. case Basic_i128be:
  9860. case Basic_u128be:
  9861. case Basic_int:
  9862. case Basic_uint:
  9863. case Basic_uintptr: {
  9864. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  9865. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  9866. // NOTE(bill): This is matches the runtime layout
  9867. u8 endianness_value = 0;
  9868. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9869. endianness_value = 1;
  9870. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9871. endianness_value = 2;
  9872. }
  9873. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9874. LLVMValueRef vals[2] = {
  9875. is_signed.value,
  9876. endianness.value,
  9877. };
  9878. lbValue res = {};
  9879. res.type = type_deref(tag.type);
  9880. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9881. lb_emit_store(p, tag, res);
  9882. break;
  9883. }
  9884. case Basic_rune:
  9885. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  9886. break;
  9887. // case Basic_f16:
  9888. case Basic_f32:
  9889. case Basic_f64:
  9890. case Basic_f32le:
  9891. case Basic_f64le:
  9892. case Basic_f32be:
  9893. case Basic_f64be:
  9894. {
  9895. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  9896. // NOTE(bill): This is matches the runtime layout
  9897. u8 endianness_value = 0;
  9898. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9899. endianness_value = 1;
  9900. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9901. endianness_value = 2;
  9902. }
  9903. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9904. LLVMValueRef vals[1] = {
  9905. endianness.value,
  9906. };
  9907. lbValue res = {};
  9908. res.type = type_deref(tag.type);
  9909. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9910. lb_emit_store(p, tag, res);
  9911. }
  9912. break;
  9913. // case Basic_complex32:
  9914. case Basic_complex64:
  9915. case Basic_complex128:
  9916. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  9917. break;
  9918. case Basic_quaternion128:
  9919. case Basic_quaternion256:
  9920. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  9921. break;
  9922. case Basic_rawptr:
  9923. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9924. break;
  9925. case Basic_string:
  9926. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9927. break;
  9928. case Basic_cstring:
  9929. {
  9930. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9931. LLVMValueRef vals[1] = {
  9932. lb_const_bool(m, t_bool, true).value,
  9933. };
  9934. lbValue res = {};
  9935. res.type = type_deref(tag.type);
  9936. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9937. lb_emit_store(p, tag, res);
  9938. }
  9939. break;
  9940. case Basic_any:
  9941. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  9942. break;
  9943. case Basic_typeid:
  9944. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  9945. break;
  9946. }
  9947. break;
  9948. case Type_Pointer: {
  9949. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9950. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  9951. LLVMValueRef vals[1] = {
  9952. gep.value,
  9953. };
  9954. lbValue res = {};
  9955. res.type = type_deref(tag.type);
  9956. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9957. lb_emit_store(p, tag, res);
  9958. break;
  9959. }
  9960. case Type_Array: {
  9961. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  9962. i64 ez = type_size_of(t->Array.elem);
  9963. LLVMValueRef vals[3] = {
  9964. lb_get_type_info_ptr(m, t->Array.elem).value,
  9965. lb_const_int(m, t_int, ez).value,
  9966. lb_const_int(m, t_int, t->Array.count).value,
  9967. };
  9968. lbValue res = {};
  9969. res.type = type_deref(tag.type);
  9970. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9971. lb_emit_store(p, tag, res);
  9972. break;
  9973. }
  9974. case Type_EnumeratedArray: {
  9975. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  9976. LLVMValueRef vals[6] = {
  9977. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  9978. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  9979. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  9980. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  9981. // Unions
  9982. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9983. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9984. };
  9985. lbValue res = {};
  9986. res.type = type_deref(tag.type);
  9987. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9988. lb_emit_store(p, tag, res);
  9989. // NOTE(bill): Union assignment
  9990. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  9991. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  9992. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  9993. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  9994. lb_emit_store(p, min_value, min_v);
  9995. lb_emit_store(p, max_value, max_v);
  9996. break;
  9997. }
  9998. case Type_DynamicArray: {
  9999. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  10000. LLVMValueRef vals[2] = {
  10001. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  10002. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  10003. };
  10004. lbValue res = {};
  10005. res.type = type_deref(tag.type);
  10006. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10007. lb_emit_store(p, tag, res);
  10008. break;
  10009. }
  10010. case Type_Slice: {
  10011. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  10012. LLVMValueRef vals[2] = {
  10013. lb_get_type_info_ptr(m, t->Slice.elem).value,
  10014. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  10015. };
  10016. lbValue res = {};
  10017. res.type = type_deref(tag.type);
  10018. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10019. lb_emit_store(p, tag, res);
  10020. break;
  10021. }
  10022. case Type_Proc: {
  10023. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  10024. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10025. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10026. if (t->Proc.params != nullptr) {
  10027. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  10028. }
  10029. if (t->Proc.results != nullptr) {
  10030. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  10031. }
  10032. LLVMValueRef vals[4] = {
  10033. params,
  10034. results,
  10035. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  10036. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  10037. };
  10038. lbValue res = {};
  10039. res.type = type_deref(tag.type);
  10040. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10041. lb_emit_store(p, tag, res);
  10042. break;
  10043. }
  10044. case Type_Tuple: {
  10045. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  10046. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  10047. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  10048. for_array(i, t->Tuple.variables) {
  10049. // NOTE(bill): offset is not used for tuples
  10050. Entity *f = t->Tuple.variables[i];
  10051. lbValue index = lb_const_int(m, t_int, i);
  10052. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10053. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  10054. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10055. if (f->token.string.len > 0) {
  10056. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10057. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10058. }
  10059. }
  10060. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  10061. LLVMValueRef types_slice = llvm_const_slice(memory_types, count);
  10062. LLVMValueRef names_slice = llvm_const_slice(memory_names, count);
  10063. LLVMValueRef vals[2] = {
  10064. types_slice,
  10065. names_slice,
  10066. };
  10067. lbValue res = {};
  10068. res.type = type_deref(tag.type);
  10069. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10070. lb_emit_store(p, tag, res);
  10071. break;
  10072. }
  10073. case Type_Enum:
  10074. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  10075. {
  10076. GB_ASSERT(t->Enum.base_type != nullptr);
  10077. // 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));
  10078. LLVMValueRef vals[3] = {};
  10079. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  10080. if (t->Enum.fields.count > 0) {
  10081. auto fields = t->Enum.fields;
  10082. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  10083. str_lit("$enum_names"), cast(i64)entry_index);
  10084. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  10085. str_lit("$enum_values"), cast(i64)entry_index);
  10086. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10087. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10088. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10089. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  10090. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  10091. for_array(i, fields) {
  10092. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  10093. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  10094. }
  10095. LLVMValueRef name_init = LLVMConstArray(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  10096. LLVMValueRef value_init = LLVMConstArray(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  10097. LLVMSetInitializer(name_array.value, name_init);
  10098. LLVMSetInitializer(value_array.value, value_init);
  10099. lbValue v_count = lb_const_int(m, t_int, fields.count);
  10100. vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count);
  10101. vals[2] = llvm_const_slice(lb_array_elem(p, value_array), v_count);
  10102. } else {
  10103. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  10104. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  10105. }
  10106. lbValue res = {};
  10107. res.type = type_deref(tag.type);
  10108. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10109. lb_emit_store(p, tag, res);
  10110. }
  10111. break;
  10112. case Type_Union: {
  10113. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  10114. {
  10115. LLVMValueRef vals[6] = {};
  10116. isize variant_count = gb_max(0, t->Union.variants.count);
  10117. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  10118. // NOTE(bill): Zeroth is nil so ignore it
  10119. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10120. Type *vt = t->Union.variants[variant_index];
  10121. lbValue tip = lb_get_type_info_ptr(m, vt);
  10122. lbValue index = lb_const_int(m, t_int, variant_index);
  10123. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10124. lb_emit_store(p, type_info, lb_type_info(m, vt));
  10125. }
  10126. lbValue count = lb_const_int(m, t_int, variant_count);
  10127. vals[0] = llvm_const_slice(memory_types, count);
  10128. i64 tag_size = union_tag_size(t);
  10129. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10130. if (tag_size > 0) {
  10131. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  10132. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  10133. } else {
  10134. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  10135. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10136. }
  10137. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  10138. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  10139. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  10140. lbValue res = {};
  10141. res.type = type_deref(tag.type);
  10142. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10143. lb_emit_store(p, tag, res);
  10144. }
  10145. break;
  10146. }
  10147. case Type_Struct: {
  10148. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  10149. LLVMValueRef vals[11] = {};
  10150. {
  10151. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  10152. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  10153. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  10154. vals[5] = is_packed.value;
  10155. vals[6] = is_raw_union.value;
  10156. vals[7] = is_custom_align.value;
  10157. if (t->Struct.soa_kind != StructSoa_None) {
  10158. lbValue kind = lb_emit_struct_ep(p, tag, 8);
  10159. Type *kind_type = type_deref(kind.type);
  10160. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  10161. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  10162. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  10163. vals[8] = soa_kind.value;
  10164. vals[9] = soa_type.value;
  10165. vals[10] = soa_len.value;
  10166. }
  10167. }
  10168. isize count = t->Struct.fields.count;
  10169. if (count > 0) {
  10170. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  10171. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  10172. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  10173. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  10174. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  10175. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10176. for (isize source_index = 0; source_index < count; source_index++) {
  10177. // TODO(bill): Order fields in source order not layout order
  10178. Entity *f = t->Struct.fields[source_index];
  10179. lbValue tip = lb_get_type_info_ptr(m, f->type);
  10180. i64 foffset = 0;
  10181. if (!t->Struct.is_raw_union) {
  10182. foffset = t->Struct.offsets[f->Variable.field_index];
  10183. }
  10184. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10185. lbValue index = lb_const_int(m, t_int, source_index);
  10186. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10187. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  10188. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  10189. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10190. if (f->token.string.len > 0) {
  10191. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10192. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10193. }
  10194. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  10195. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  10196. if (t->Struct.tags.count > 0) {
  10197. String tag_string = t->Struct.tags[source_index];
  10198. if (tag_string.len > 0) {
  10199. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  10200. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  10201. }
  10202. }
  10203. }
  10204. lbValue cv = lb_const_int(m, t_int, count);
  10205. vals[0] = llvm_const_slice(memory_types, cv);
  10206. vals[1] = llvm_const_slice(memory_names, cv);
  10207. vals[2] = llvm_const_slice(memory_offsets, cv);
  10208. vals[3] = llvm_const_slice(memory_usings, cv);
  10209. vals[4] = llvm_const_slice(memory_tags, cv);
  10210. }
  10211. for (isize i = 0; i < gb_count_of(vals); i++) {
  10212. if (vals[i] == nullptr) {
  10213. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  10214. }
  10215. }
  10216. lbValue res = {};
  10217. res.type = type_deref(tag.type);
  10218. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10219. lb_emit_store(p, tag, res);
  10220. break;
  10221. }
  10222. case Type_Map: {
  10223. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  10224. init_map_internal_types(t);
  10225. LLVMValueRef vals[3] = {
  10226. lb_get_type_info_ptr(m, t->Map.key).value,
  10227. lb_get_type_info_ptr(m, t->Map.value).value,
  10228. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  10229. };
  10230. lbValue res = {};
  10231. res.type = type_deref(tag.type);
  10232. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10233. lb_emit_store(p, tag, res);
  10234. break;
  10235. }
  10236. case Type_BitField: {
  10237. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_field_ptr);
  10238. // names: []string;
  10239. // bits: []u32;
  10240. // offsets: []u32;
  10241. isize count = t->BitField.fields.count;
  10242. if (count > 0) {
  10243. auto fields = t->BitField.fields;
  10244. lbValue name_array = lb_generate_global_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  10245. lbValue bit_array = lb_generate_global_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  10246. lbValue offset_array = lb_generate_global_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  10247. for (isize i = 0; i < count; i++) {
  10248. Entity *f = fields[i];
  10249. GB_ASSERT(f->type != nullptr);
  10250. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  10251. lbValue name_ep = lb_emit_array_epi(p, name_array, cast(i32)i);
  10252. lbValue bit_ep = lb_emit_array_epi(p, bit_array, cast(i32)i);
  10253. lbValue offset_ep = lb_emit_array_epi(p, offset_array, cast(i32)i);
  10254. lb_emit_store(p, name_ep, lb_const_string(m, f->token.string));
  10255. lb_emit_store(p, bit_ep, lb_const_int(m, t_i32, f->type->BitFieldValue.bits));
  10256. lb_emit_store(p, offset_ep, lb_const_int(m, t_i32, t->BitField.offsets[i]));
  10257. }
  10258. lbValue v_count = lb_const_int(m, t_int, count);
  10259. lbValue name_array_elem = lb_array_elem(p, name_array);
  10260. lbValue bit_array_elem = lb_array_elem(p, bit_array);
  10261. lbValue offset_array_elem = lb_array_elem(p, offset_array);
  10262. LLVMValueRef vals[3] = {
  10263. llvm_const_slice(name_array_elem, v_count),
  10264. llvm_const_slice(bit_array_elem, v_count),
  10265. llvm_const_slice(offset_array_elem, v_count),
  10266. };
  10267. lbValue res = {};
  10268. res.type = type_deref(tag.type);
  10269. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10270. lb_emit_store(p, tag, res);
  10271. }
  10272. break;
  10273. }
  10274. case Type_BitSet:
  10275. {
  10276. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  10277. GB_ASSERT(is_type_typed(t->BitSet.elem));
  10278. LLVMValueRef vals[4] = {
  10279. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  10280. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  10281. lb_const_int(m, t_i64, t->BitSet.lower).value,
  10282. lb_const_int(m, t_i64, t->BitSet.upper).value,
  10283. };
  10284. if (t->BitSet.underlying != nullptr) {
  10285. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  10286. }
  10287. lbValue res = {};
  10288. res.type = type_deref(tag.type);
  10289. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10290. lb_emit_store(p, tag, res);
  10291. }
  10292. break;
  10293. case Type_Opaque:
  10294. {
  10295. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_opaque_ptr);
  10296. LLVMValueRef vals[1] = {
  10297. lb_get_type_info_ptr(m, t->Opaque.elem).value,
  10298. };
  10299. lbValue res = {};
  10300. res.type = type_deref(tag.type);
  10301. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10302. lb_emit_store(p, tag, res);
  10303. }
  10304. break;
  10305. case Type_SimdVector:
  10306. {
  10307. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  10308. LLVMValueRef vals[4] = {};
  10309. if (t->SimdVector.is_x86_mmx) {
  10310. vals[3] = lb_const_bool(m, t_bool, true).value;
  10311. } else {
  10312. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  10313. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  10314. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  10315. }
  10316. lbValue res = {};
  10317. res.type = type_deref(tag.type);
  10318. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10319. lb_emit_store(p, tag, res);
  10320. }
  10321. break;
  10322. case Type_RelativePointer:
  10323. {
  10324. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  10325. LLVMValueRef vals[2] = {
  10326. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  10327. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  10328. };
  10329. lbValue res = {};
  10330. res.type = type_deref(tag.type);
  10331. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10332. lb_emit_store(p, tag, res);
  10333. }
  10334. break;
  10335. case Type_RelativeSlice:
  10336. {
  10337. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  10338. LLVMValueRef vals[2] = {
  10339. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  10340. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  10341. };
  10342. lbValue res = {};
  10343. res.type = type_deref(tag.type);
  10344. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10345. lb_emit_store(p, tag, res);
  10346. }
  10347. break;
  10348. }
  10349. if (tag.value != nullptr) {
  10350. Type *tag_type = type_deref(tag.type);
  10351. GB_ASSERT(is_type_named(tag_type));
  10352. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  10353. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  10354. } else {
  10355. if (t != t_llvm_bool) {
  10356. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  10357. }
  10358. }
  10359. }
  10360. }
  10361. void lb_generate_code(lbGenerator *gen) {
  10362. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  10363. TIME_SECTION("LLVM Initializtion");
  10364. lbModule *m = &gen->module;
  10365. LLVMModuleRef mod = gen->module.mod;
  10366. CheckerInfo *info = gen->info;
  10367. auto *min_dep_set = &info->minimum_dependency_set;
  10368. LLVMInitializeAllTargetInfos();
  10369. LLVMInitializeAllTargets();
  10370. LLVMInitializeAllTargetMCs();
  10371. LLVMInitializeAllAsmPrinters();
  10372. LLVMInitializeAllAsmParsers();
  10373. LLVMInitializeAllDisassemblers();
  10374. LLVMInitializeNativeTarget();
  10375. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  10376. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  10377. LLVMSetTarget(mod, target_triple);
  10378. LLVMTargetRef target = {};
  10379. char *llvm_error = nullptr;
  10380. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  10381. GB_ASSERT(target != nullptr);
  10382. TIME_SECTION("LLVM Create Target Machine");
  10383. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  10384. if (build_context.metrics.arch == TargetArch_wasm32) {
  10385. code_mode = LLVMCodeModelJITDefault;
  10386. }
  10387. char const *host_cpu_name = LLVMGetHostCPUName();
  10388. char const *llvm_cpu = "generic";
  10389. char const *llvm_features = "";
  10390. if (build_context.microarch.len != 0) {
  10391. if (build_context.microarch == "native") {
  10392. llvm_cpu = host_cpu_name;
  10393. } else {
  10394. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  10395. }
  10396. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  10397. llvm_features = LLVMGetHostCPUFeatures();
  10398. }
  10399. }
  10400. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  10401. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  10402. switch (build_context.optimization_level) {
  10403. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  10404. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  10405. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  10406. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  10407. }
  10408. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, llvm_cpu, llvm_features, code_gen_level, LLVMRelocDefault, code_mode);
  10409. defer (LLVMDisposeTargetMachine(target_machine));
  10410. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  10411. { // Debug Info
  10412. for_array(i, info->files.entries) {
  10413. AstFile *f = info->files.entries[i].value;
  10414. String fullpath = f->fullpath;
  10415. String filename = filename_from_path(fullpath);
  10416. String directory = directory_from_path(fullpath);
  10417. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  10418. cast(char const *)filename.text, filename.len,
  10419. cast(char const *)directory.text, directory.len);
  10420. map_set(&m->debug_values, hash_pointer(f), res);
  10421. f->llvm_metadata = res;
  10422. }
  10423. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  10424. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  10425. "odin", 4,
  10426. false, "", 0,
  10427. 1, "", 0,
  10428. LLVMDWARFEmissionFull, 0, true,
  10429. true
  10430. );
  10431. }
  10432. TIME_SECTION("LLVM Global Variables");
  10433. {
  10434. { // Add type info data
  10435. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  10436. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  10437. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  10438. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  10439. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10440. LLVMSetLinkage(g, LLVMInternalLinkage);
  10441. lbValue value = {};
  10442. value.value = g;
  10443. value.type = alloc_type_pointer(t);
  10444. lb_global_type_info_data = lb_addr(value);
  10445. }
  10446. { // Type info member buffer
  10447. // NOTE(bill): Removes need for heap allocation by making it global memory
  10448. isize count = 0;
  10449. for_array(entry_index, m->info->type_info_types) {
  10450. Type *t = m->info->type_info_types[entry_index];
  10451. isize index = lb_type_info_index(m->info, t, false);
  10452. if (index < 0) {
  10453. continue;
  10454. }
  10455. switch (t->kind) {
  10456. case Type_Union:
  10457. count += t->Union.variants.count;
  10458. break;
  10459. case Type_Struct:
  10460. count += t->Struct.fields.count;
  10461. break;
  10462. case Type_Tuple:
  10463. count += t->Tuple.variables.count;
  10464. break;
  10465. }
  10466. }
  10467. if (count > 0) {
  10468. {
  10469. char const *name = LB_TYPE_INFO_TYPES_NAME;
  10470. Type *t = alloc_type_array(t_type_info_ptr, count);
  10471. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10472. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10473. LLVMSetLinkage(g, LLVMInternalLinkage);
  10474. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  10475. }
  10476. {
  10477. char const *name = LB_TYPE_INFO_NAMES_NAME;
  10478. Type *t = alloc_type_array(t_string, count);
  10479. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10480. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10481. LLVMSetLinkage(g, LLVMInternalLinkage);
  10482. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  10483. }
  10484. {
  10485. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  10486. Type *t = alloc_type_array(t_uintptr, count);
  10487. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10488. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10489. LLVMSetLinkage(g, LLVMInternalLinkage);
  10490. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  10491. }
  10492. {
  10493. char const *name = LB_TYPE_INFO_USINGS_NAME;
  10494. Type *t = alloc_type_array(t_bool, count);
  10495. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10496. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10497. LLVMSetLinkage(g, LLVMInternalLinkage);
  10498. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  10499. }
  10500. {
  10501. char const *name = LB_TYPE_INFO_TAGS_NAME;
  10502. Type *t = alloc_type_array(t_string, count);
  10503. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10504. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10505. LLVMSetLinkage(g, LLVMInternalLinkage);
  10506. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  10507. }
  10508. }
  10509. }
  10510. }
  10511. isize global_variable_max_count = 0;
  10512. Entity *entry_point = info->entry_point;
  10513. bool has_dll_main = false;
  10514. bool has_win_main = false;
  10515. for_array(i, info->entities) {
  10516. Entity *e = info->entities[i];
  10517. String name = e->token.string;
  10518. bool is_global = e->pkg != nullptr;
  10519. if (e->kind == Entity_Variable) {
  10520. global_variable_max_count++;
  10521. } else if (e->kind == Entity_Procedure && !is_global) {
  10522. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  10523. GB_ASSERT(e == entry_point);
  10524. // entry_point = e;
  10525. }
  10526. if (e->Procedure.is_export ||
  10527. (e->Procedure.link_name.len > 0) ||
  10528. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  10529. if (!has_dll_main && name == "DllMain") {
  10530. has_dll_main = true;
  10531. } else if (!has_win_main && name == "WinMain") {
  10532. has_win_main = true;
  10533. }
  10534. }
  10535. }
  10536. }
  10537. struct GlobalVariable {
  10538. lbValue var;
  10539. lbValue init;
  10540. DeclInfo *decl;
  10541. };
  10542. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  10543. for_array(i, info->variable_init_order) {
  10544. DeclInfo *d = info->variable_init_order[i];
  10545. Entity *e = d->entity;
  10546. if ((e->scope->flags & ScopeFlag_File) == 0) {
  10547. continue;
  10548. }
  10549. if (!ptr_set_exists(min_dep_set, e)) {
  10550. continue;
  10551. }
  10552. DeclInfo *decl = decl_info_of_entity(e);
  10553. if (decl == nullptr) {
  10554. continue;
  10555. }
  10556. GB_ASSERT(e->kind == Entity_Variable);
  10557. bool is_foreign = e->Variable.is_foreign;
  10558. bool is_export = e->Variable.is_export;
  10559. String name = lb_get_entity_name(m, e);
  10560. lbValue g = {};
  10561. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  10562. g.type = alloc_type_pointer(e->type);
  10563. if (e->Variable.thread_local_model != "") {
  10564. LLVMSetThreadLocal(g.value, true);
  10565. String m = e->Variable.thread_local_model;
  10566. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  10567. if (m == "default") {
  10568. mode = LLVMGeneralDynamicTLSModel;
  10569. } else if (m == "localdynamic") {
  10570. mode = LLVMLocalDynamicTLSModel;
  10571. } else if (m == "initialexec") {
  10572. mode = LLVMInitialExecTLSModel;
  10573. } else if (m == "localexec") {
  10574. mode = LLVMLocalExecTLSModel;
  10575. } else {
  10576. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  10577. }
  10578. LLVMSetThreadLocalMode(g.value, mode);
  10579. }
  10580. if (is_foreign) {
  10581. LLVMSetExternallyInitialized(g.value, true);
  10582. } else {
  10583. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  10584. }
  10585. if (is_export) {
  10586. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  10587. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  10588. }
  10589. GlobalVariable var = {};
  10590. var.var = g;
  10591. var.decl = decl;
  10592. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  10593. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  10594. if (tav.mode != Addressing_Invalid) {
  10595. if (tav.value.kind != ExactValue_Invalid) {
  10596. ExactValue v = tav.value;
  10597. lbValue init = lb_const_value(m, tav.type, v);
  10598. LLVMSetInitializer(g.value, init.value);
  10599. }
  10600. }
  10601. }
  10602. array_add(&global_variables, var);
  10603. lb_add_entity(m, e, g);
  10604. lb_add_member(m, name, g);
  10605. }
  10606. TIME_SECTION("LLVM Global Procedures and Types");
  10607. for_array(i, info->entities) {
  10608. Entity *e = info->entities[i];
  10609. String name = e->token.string;
  10610. DeclInfo *decl = e->decl_info;
  10611. Scope * scope = e->scope;
  10612. if ((scope->flags & ScopeFlag_File) == 0) {
  10613. continue;
  10614. }
  10615. Scope *package_scope = scope->parent;
  10616. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  10617. switch (e->kind) {
  10618. case Entity_Variable:
  10619. // NOTE(bill): Handled above as it requires a specific load order
  10620. continue;
  10621. case Entity_ProcGroup:
  10622. continue;
  10623. case Entity_TypeName:
  10624. case Entity_Procedure:
  10625. break;
  10626. }
  10627. bool polymorphic_struct = false;
  10628. if (e->type != nullptr && e->kind == Entity_TypeName) {
  10629. Type *bt = base_type(e->type);
  10630. if (bt->kind == Type_Struct) {
  10631. polymorphic_struct = is_type_polymorphic(bt);
  10632. }
  10633. }
  10634. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  10635. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  10636. continue;
  10637. }
  10638. String mangled_name = lb_get_entity_name(m, e);
  10639. switch (e->kind) {
  10640. case Entity_TypeName:
  10641. lb_type(m, e->type);
  10642. break;
  10643. case Entity_Procedure:
  10644. {
  10645. lbProcedure *p = lb_create_procedure(m, e);
  10646. array_add(&m->procedures_to_generate, p);
  10647. }
  10648. break;
  10649. }
  10650. }
  10651. TIME_SECTION("LLVM Registry Initializtion");
  10652. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  10653. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  10654. defer (LLVMDisposePassManager(default_function_pass_manager));
  10655. /*{
  10656. LLVMAddMemCpyOptPass(default_function_pass_manager);
  10657. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10658. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  10659. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  10660. LLVMAddConstantPropagationPass(default_function_pass_manager);
  10661. LLVMAddAggressiveDCEPass(default_function_pass_manager);
  10662. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  10663. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10664. LLVMAddCFGSimplificationPass(default_function_pass_manager);
  10665. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager);
  10666. if (build_context.optimization_level >= 2) {
  10667. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  10668. LLVMAddEarlyCSEPass(default_function_pass_manager);
  10669. LLVMAddEarlyCSEMemSSAPass(default_function_pass_manager);
  10670. LLVMAddLowerExpectIntrinsicPass(default_function_pass_manager);
  10671. LLVMAddAlignmentFromAssumptionsPass(default_function_pass_manager);
  10672. LLVMAddLoopRotatePass(default_function_pass_manager);
  10673. LLVMAddDeadStoreEliminationPass(default_function_pass_manager);
  10674. LLVMAddScalarizerPass(default_function_pass_manager);
  10675. LLVMAddReassociatePass(default_function_pass_manager);
  10676. LLVMAddAddDiscriminatorsPass(default_function_pass_manager);
  10677. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10678. LLVMAddCorrelatedValuePropagationPass(default_function_pass_manager);
  10679. LLVMAddSLPVectorizePass(default_function_pass_manager);
  10680. LLVMAddLoopVectorizePass(default_function_pass_manager);
  10681. }
  10682. }*/
  10683. if (build_context.optimization_level == 0 && false) {
  10684. auto dfpm = default_function_pass_manager;
  10685. LLVMAddMemCpyOptPass(dfpm);
  10686. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10687. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10688. LLVMAddAggressiveInstCombinerPass(dfpm);
  10689. LLVMAddConstantPropagationPass(dfpm);
  10690. LLVMAddAggressiveDCEPass(dfpm);
  10691. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10692. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10693. LLVMAddCFGSimplificationPass(dfpm);
  10694. LLVMAddScalarizerPass(dfpm);
  10695. } else {
  10696. auto dfpm = default_function_pass_manager;
  10697. LLVMAddMemCpyOptPass(dfpm);
  10698. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10699. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10700. LLVMAddAggressiveInstCombinerPass(dfpm);
  10701. LLVMAddConstantPropagationPass(dfpm);
  10702. LLVMAddAggressiveDCEPass(dfpm);
  10703. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10704. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10705. LLVMAddCFGSimplificationPass(dfpm);
  10706. // LLVMAddInstructionCombiningPass(dfpm);
  10707. LLVMAddSLPVectorizePass(dfpm);
  10708. LLVMAddLoopVectorizePass(dfpm);
  10709. LLVMAddEarlyCSEPass(dfpm);
  10710. LLVMAddEarlyCSEMemSSAPass(dfpm);
  10711. LLVMAddScalarizerPass(dfpm);
  10712. LLVMAddLoopIdiomPass(dfpm);
  10713. // LLVMAddAggressiveInstCombinerPass(dfpm);
  10714. // LLVMAddLowerExpectIntrinsicPass(dfpm);
  10715. // LLVMAddPartiallyInlineLibCallsPass(dfpm);
  10716. // LLVMAddAlignmentFromAssumptionsPass(dfpm);
  10717. // LLVMAddDeadStoreEliminationPass(dfpm);
  10718. // LLVMAddReassociatePass(dfpm);
  10719. // LLVMAddAddDiscriminatorsPass(dfpm);
  10720. // LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10721. // LLVMAddCorrelatedValuePropagationPass(dfpm);
  10722. // LLVMAddMemCpyOptPass(dfpm);
  10723. }
  10724. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  10725. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  10726. {
  10727. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  10728. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  10729. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager_without_memcpy);
  10730. LLVMAddConstantPropagationPass(default_function_pass_manager_without_memcpy);
  10731. LLVMAddAggressiveDCEPass(default_function_pass_manager_without_memcpy);
  10732. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  10733. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  10734. LLVMAddCFGSimplificationPass(default_function_pass_manager_without_memcpy);
  10735. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager_without_memcpy);
  10736. }
  10737. TIME_SECTION("LLVM Runtime Creation");
  10738. lbProcedure *startup_type_info = nullptr;
  10739. lbProcedure *startup_runtime = nullptr;
  10740. { // Startup Type Info
  10741. Type *params = alloc_type_tuple();
  10742. Type *results = alloc_type_tuple();
  10743. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10744. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  10745. p->is_startup = true;
  10746. startup_type_info = p;
  10747. lb_begin_procedure_body(p);
  10748. lb_setup_type_info_data(p);
  10749. lb_end_procedure_body(p);
  10750. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10751. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10752. LLVMDumpValue(p->value);
  10753. gb_printf_err("\n\n\n\n");
  10754. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10755. }
  10756. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10757. }
  10758. { // Startup Runtime
  10759. Type *params = alloc_type_tuple();
  10760. Type *results = alloc_type_tuple();
  10761. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10762. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  10763. p->is_startup = true;
  10764. startup_runtime = p;
  10765. lb_begin_procedure_body(p);
  10766. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  10767. for_array(i, global_variables) {
  10768. auto *var = &global_variables[i];
  10769. if (var->decl->init_expr != nullptr) {
  10770. lbValue init = lb_build_expr(p, var->decl->init_expr);
  10771. if (!lb_is_const(init)) {
  10772. var->init = init;
  10773. }
  10774. }
  10775. Entity *e = var->decl->entity;
  10776. GB_ASSERT(e->kind == Entity_Variable);
  10777. if (e->Variable.is_foreign) {
  10778. Entity *fl = e->Procedure.foreign_library;
  10779. lb_add_foreign_library_path(m, fl);
  10780. }
  10781. if (e->flags & EntityFlag_Static) {
  10782. LLVMSetLinkage(var->var.value, LLVMInternalLinkage);
  10783. }
  10784. if (var->init.value != nullptr) {
  10785. Type *t = type_deref(var->var.type);
  10786. if (is_type_any(t)) {
  10787. // NOTE(bill): Edge case for 'any' type
  10788. Type *var_type = default_type(var->init.type);
  10789. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  10790. lb_addr_store(p, g, var->init);
  10791. lbValue gp = lb_addr_get_ptr(p, g);
  10792. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  10793. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  10794. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  10795. lb_emit_store(p, ti, lb_type_info(m, var_type));
  10796. } else {
  10797. lb_emit_store(p, var->var, lb_emit_conv(p, var->init, t));
  10798. }
  10799. }
  10800. }
  10801. lb_end_procedure_body(p);
  10802. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10803. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10804. LLVMDumpValue(p->value);
  10805. gb_printf_err("\n\n\n\n");
  10806. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10807. }
  10808. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10809. /*{
  10810. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  10811. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  10812. instr != last_instr;
  10813. instr = LLVMGetNextInstruction(instr)) {
  10814. if (LLVMIsAAllocaInst(instr)) {
  10815. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  10816. LLVMValueRef sz_val = LLVMSizeOf(type);
  10817. GB_ASSERT(LLVMIsConstant(sz_val));
  10818. gb_printf_err(">> 0x%p\n", sz_val);
  10819. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  10820. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  10821. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  10822. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  10823. gb_printf_err(">> %ll\n", sz);
  10824. }
  10825. }
  10826. }*/
  10827. }
  10828. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  10829. Type *params = alloc_type_tuple();
  10830. Type *results = alloc_type_tuple();
  10831. String name = str_lit("main");
  10832. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  10833. name = str_lit("mainCRTStartup");
  10834. } else {
  10835. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  10836. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  10837. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  10838. }
  10839. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  10840. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  10841. Type *proc_type = alloc_type_proc(nullptr,
  10842. params, params->Tuple.variables.count,
  10843. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  10844. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  10845. p->is_startup = true;
  10846. lb_begin_procedure_body(p);
  10847. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  10848. if (build_context.command_kind == Command_test) {
  10849. for_array(i, m->info->testing_procedures) {
  10850. Entity *e = m->info->testing_procedures[i];
  10851. lbValue *found = map_get(&m->values, hash_entity(e));
  10852. GB_ASSERT(found != nullptr);
  10853. lb_emit_call(p, *found, {});
  10854. }
  10855. } else {
  10856. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  10857. GB_ASSERT(found != nullptr);
  10858. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  10859. }
  10860. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  10861. lb_end_procedure_body(p);
  10862. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10863. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10864. LLVMDumpValue(p->value);
  10865. gb_printf_err("\n\n\n\n");
  10866. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10867. }
  10868. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10869. }
  10870. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  10871. TIME_SECTION("LLVM Procedure Generation");
  10872. for_array(i, m->procedures_to_generate) {
  10873. lbProcedure *p = m->procedures_to_generate[i];
  10874. if (p->is_done) {
  10875. continue;
  10876. }
  10877. if (p->body != nullptr) { // Build Procedure
  10878. m->curr_procedure = p;
  10879. lb_begin_procedure_body(p);
  10880. lb_build_stmt(p, p->body);
  10881. lb_end_procedure_body(p);
  10882. p->is_done = true;
  10883. m->curr_procedure = nullptr;
  10884. }
  10885. lb_end_procedure(p);
  10886. // Add Flags
  10887. if (p->body != nullptr) {
  10888. if (p->name == "memcpy" || p->name == "memmove" ||
  10889. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  10890. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  10891. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  10892. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  10893. }
  10894. }
  10895. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10896. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  10897. LLVMDumpValue(p->value);
  10898. gb_printf_err("\n\n\n\n");
  10899. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  10900. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10901. }
  10902. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  10903. gb_exit(1);
  10904. }
  10905. }
  10906. TIME_SECTION("LLVM Function Pass");
  10907. for_array(i, m->procedures_to_generate) {
  10908. lbProcedure *p = m->procedures_to_generate[i];
  10909. if (p->body != nullptr) { // Build Procedure
  10910. for (i32 i = 0; i <= build_context.optimization_level; i++) {
  10911. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  10912. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  10913. } else {
  10914. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10915. }
  10916. }
  10917. }
  10918. }
  10919. TIME_SECTION("LLVM Module Pass");
  10920. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  10921. defer (LLVMDisposePassManager(module_pass_manager));
  10922. LLVMAddAlwaysInlinerPass(module_pass_manager);
  10923. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  10924. LLVMAddAnalysisPasses(target_machine, module_pass_manager);
  10925. // if (build_context.optimization_level >= 2) {
  10926. // LLVMAddArgumentPromotionPass(module_pass_manager);
  10927. // LLVMAddConstantMergePass(module_pass_manager);
  10928. // LLVMAddGlobalDCEPass(module_pass_manager);
  10929. // LLVMAddDeadArgEliminationPass(module_pass_manager);
  10930. // }
  10931. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  10932. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  10933. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level);
  10934. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level);
  10935. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  10936. LLVMRunPassManager(module_pass_manager, mod);
  10937. llvm_error = nullptr;
  10938. defer (LLVMDisposeMessage(llvm_error));
  10939. String filepath_obj = {};
  10940. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  10941. if (build_context.build_mode == BuildMode_Assembly) {
  10942. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  10943. code_gen_file_type = LLVMAssemblyFile;
  10944. } else {
  10945. switch (build_context.metrics.os) {
  10946. case TargetOs_windows:
  10947. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  10948. break;
  10949. case TargetOs_darwin:
  10950. case TargetOs_linux:
  10951. case TargetOs_essence:
  10952. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  10953. break;
  10954. case TargetOs_js:
  10955. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  10956. break;
  10957. }
  10958. }
  10959. LLVMDIBuilderFinalize(m->debug_builder);
  10960. if (LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error)) {
  10961. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10962. gb_exit(1);
  10963. return;
  10964. }
  10965. llvm_error = nullptr;
  10966. if (build_context.keep_temp_files) {
  10967. TIME_SECTION("LLVM Print Module to File");
  10968. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  10969. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10970. gb_exit(1);
  10971. return;
  10972. }
  10973. }
  10974. TIME_SECTION("LLVM Object Generation");
  10975. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  10976. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10977. gb_exit(1);
  10978. return;
  10979. }
  10980. array_add(&gen->output_object_paths, filepath_obj);
  10981. for_array(i, m->info->required_foreign_imports_through_force) {
  10982. Entity *e = m->info->required_foreign_imports_through_force[i];
  10983. lb_add_foreign_library_path(m, e);
  10984. }
  10985. #undef TIME_SECTION
  10986. }